当前位置:首页>开发>正文

android怎样实现异步任务停止

2023-05-22 17:35:59 互联网 未知 开发

 android怎样实现异步任务停止

android怎样实现异步任务停止

使用AsynTask异步任务处理耗时操作(work)时,通常会增加ProgressDialog进度条来显示等待操作(或加载进度)。

  此时按返回键,因为焦点在ProgressDialog上,ProgressDialog捕获返回键操作,而Activity是不响应返回键操作的。

  如果你想实现,当进行耗时操作时(ProgressDialog正在显示),按返回键,结束当前work操作。

  你需要注意ProgressDialog的设置:

  progress_dialog.setCancelable(true)//响应取消操作,这里如果设置false,按返回键ProgressDialog也不消失。
  progress_dialog.setOnCancelListener(new OnCancelListener() {
  @Override
  public void onCancel(DialogInterface dialog) {
  // TODO Auto-generated method stub

  AsynTask.this.cancle(true)//执行异步线程取消操作
  }
  })

  同时注意,AsynTask执行cancele()操作后,相应的方法是如何执行。

  You can stop a running task with cancel(true). A cancel will let the task finish its doInBackground but will never call onPostExecute. You could interrupt your background routine by checking isCanceled() and so return earlier since the task was killed

最新文章