首先,大家在开发的时候,有时候做一些耗时任务时,难免会用到线程【Thread】,以免阻塞主线程。但是,有时候,我们只希望这个在线程里面执行的任务,不能太长,意思就是说,我需要在这个线程执行一段时间后,无论有没有完成我制定的任务,都要讲线程终止掉。这个时候又要用到【Timer】了。
变量声明:
private static final int TIME_LIMIT = 15000; // 登陆超时时间 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:
// 取消定时器
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();
// 设定定时器
timer.schedule(new TimerTask() {
@Override
public void run() {
sendTimeOutMsg();
}
}, TIME_LIMIT);
补充:
/**
* 错误对话框
*
* @param errorText
*/
private void errorDialog(String errorText) {
if (dialog != null) {
dialog.dismiss();
}
AlertDialog.Builder builder = new AlertDialog.Builder(this); // 先得到构造器
builder.setTitle("提示"); // 设置标题
builder.setMessage(errorText); // 设置内容
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { // 设置确定按钮
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); // 关闭dialog
}
});
// 参数都设置完成了,创建并显示出来
builder.create().show();
}
/**
* // 向handler发送超时信息
*/
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);
}