我正在运行一个 AsyncTask
,它需要一点时间来加载。在那段时间里,如果我按下后退按钮,它就没有反应。它仅在几秒钟后响应。那么我怎样才能终止或暂停或覆盖 AsyncTask
返回呢?或者有没有其他方法可以做类似的事情?
if (mainContent != null) {
mainContent.post(new Runnable() {
@Override
public void run() {
Bitmap bmp = Utilities.getBitmapFromView(mainContent);
BlurFilter blurFilter = new BlurFilter();
Bitmap blurredBitmap = blurFilter.fastblur(bmp,1,65);
asyncTask = new ConvertViews(blurredBitmap);
asyncTask.execute();
}
});
我的AsyncTask
:
class ConvertViews extends AsyncTask<Void,Void,Void> {
private Bitmap bmp;
public ConvertViews(Bitmap bmp){
this.bmp = bmp;
}
@Override
protected Void doInBackground(Void... params) {
try {
//Thread.sleep(200);
if(mainViewDrawable == null) {
mainViewDrawable = new BitmapDrawable(getResources(), bmp);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
我的onBackPressed()
:
public void onBackPressed() {
super.onBackPressed();
asyncTask.cancel(true);
finish();
}
最佳答案
您无法立即停止异步任务
。每个 AsynchTask 都有一个与其关联的 boolean 标志属性
,因此如果cancel_flag =True
表示任务已被取消,并且有一个 cancel()
函数可以像这样在 asynchtask 对象上调用
loginTask.cancel(true);
但是所有这个 cancel() 函数所做的是,它将异步任务的取消 boolean(flag)
属性设置为 True
所以,你可以检查这个属性isCancelled()
函数在 doInBackGround
中并做一些事情,比如
protected Object doInBackground(Object... x) {
while (/* condition */) {
// work...
if (isCancelled()) break;
}
return null;
}
如果它是 True 那么你可以使用 break the loops
(如果你正在做一个很长的任务)或者 return
来快速退出 doInBackground
并在 asynchtask 上调用 cancel()
将跳过 onPostExecute()
的执行。
另一个选项是,如果你想在后台停止多个正在运行的异步任务,那么对每个异步任务调用取消可能会很乏味,所以在这种情况下你可以在容器类(异步任务)
并跳过 asynchtask 中的工作,如果标志已设置为 True ,如
protected Object doInBackground(Object... x) {
while (/* condition */) {
// work...
if (container_asynch_running_flag) break;
}
return null;
}
但确保在这种情况下也检查 onpostExecute
,因为它不会停止 onpost 的执行。
关于java - 按下后退按钮时如何在android中停止asynctask?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38836610/