在线程中执行任务时,有时需要没有执行完任务手动终止任务。
要中断线程执行时,可以通过在线程中设置标识(boolean型)来判断线程的运行和结束。在doInBackground(Params…)方法中标识为可运行的就运行,当为中断标识时就停止,且放在循环里可以循环检测中断标识。特别是在线程执行时,有加载框ProgressDialog阻塞,通过捕获back键中断,不能直接在 AsyncTask中处理捕获back键事件来处理,而是通过ProgressDialog的setOnCancelListener()响应事件来调用AsyncTask中中断线程的方法。
pdProgressDialogialog.setCancelable(true);
pdProgressDialogialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
httpexcuteExcuteHttp.setBreak();
}
});
///而 AsyncTask中通过标识判断来 实现
class ExcuteHttp extends AsyncTask<Void, Integer, String> {
........
@Override
protected String doInBackground(Void... params) {
.......
for (xxx; xxx&!stopflaghttp;xxx) {
}
}
//设置标识
public void setBreak() {
// TODO Auto-generated method stub
stopflaghttp=true;
}