首先笑跛,大家在開發(fā)的時(shí)候,有時(shí)候做一些耗時(shí)任務(wù)時(shí)聊品,難免會(huì)用到線程【Thread】,以免阻塞主線程飞蹂。但是,有時(shí)候杨刨,我們只希望這個(gè)在線程里面執(zhí)行的任務(wù)晤柄,不能太長(zhǎng),意思就是說妖胀,我需要在這個(gè)線程執(zhí)行一段時(shí)間后芥颈,無論有沒有完成我制定的任務(wù),都要講線程終止掉赚抡。這個(gè)時(shí)候又要用到【Timer】了爬坑。
變量聲明:
private static final int TIME_LIMIT = 15000; // 登陸超時(shí)時(shí)間 15秒
Timer timer;
Thread thread;
final Handler myHandler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case TIME_OUT:
// 打斷線程
thread.interrupt();
if (dialog != null) {
dialog.dismiss();
}
// deal with what you should do after thread job is failed
break;
case SUCCESS:
// 取消定時(shí)器
if (timer != null) {
timer.cancel();
}
if (dialog != null) {
dialog.dismiss();
}
// do what you want after thread job is successed
break;
default:
break;
}
}
};
具體方法:
timer = new Timer();
thread = new Thread(new Runnable() {
@Override
public void run() {
if(doYourJob())
//after work is done...
Looper.prepare();
sendSuccessMsg();
Looper.loop();
} else {
//work is fail
errorDialog( "sorry work is not done !");
}
}
});
thread.start();
// 設(shè)定定時(shí)器
timer.schedule(new TimerTask() {
@Override
public void run() {
sendTimeOutMsg();
}
}, TIME_LIMIT);
補(bǔ)充:
/**
* 錯(cuò)誤對(duì)話框
*
* @param errorText
*/
private void errorDialog(String errorText) {
if (dialog != null) {
dialog.dismiss();
}
AlertDialog.Builder builder = new AlertDialog.Builder(this); // 先得到構(gòu)造器
builder.setTitle("提示"); // 設(shè)置標(biāo)題
builder.setMessage(errorText); // 設(shè)置內(nèi)容
builder.setPositiveButton("確定", new DialogInterface.OnClickListener() { // 設(shè)置確定按鈕
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); // 關(guān)閉dialog
}
});
// 參數(shù)都設(shè)置完成了,創(chuàng)建并顯示出來
builder.create().show();
}
/**
* // 向handler發(fā)送超時(shí)信息
*/
private void sendTimeOutMsg() {
Message timeOutMsg = new Message();
timeOutMsg.what = TIME_OUT;
myHandler.sendMessage(timeOutMsg);
}
/**
* // 向handler成功信息
*/
private void sendSuccessMsg() {
Message timeOutMsg = new Message();
timeOutMsg.what = SUCCESS;
myHandler.sendMessage(timeOutMsg);
}