2016-08-08 138 views
1

我正在运行一个AsyncTask,它需要一些时间来加载。在那段时间里,如果我按回按钮,那么它就不会回应。它只在几秒钟后响应。那么如何杀死或暂停或覆盖AsyncTask回去?或者有没有其他方法可以做类似的事情?当按下后退按钮时,如何停止android中的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(); 
} 
+0

发布您的代码? –

+0

我是这个平台的新手。你能告诉我,我如何发布代码?它在发布时显示错误。 –

+0

将您的代码复制并粘贴到编辑框中,在编辑框中选择所有代码,然后按Ctrl + K进行格式化。然后提交它。 –

回答

2

也没有办法,你可以停止asynch task instantly。每AsynchTask具有与之相关联的boolean flag property所以如果cancel_flag =True平均任务已被取消,并且有一个cancel()函数可以在01上调用这样

loginTask.cancel(true);

但是这一切都取消()函数,它会设定一个取消非同步任务的boolean(flag)财产True所以,你可以用isCancelled()功能检查该物业内doInBackGround,做一些事情,像

protected Object doInBackground(Object... x) { 
    while (/* condition */) { 
     // work... 
     if (isCancelled()) break; 
    } 
    return null; 
} 

,如果它是真实的,那么你可以使用break the loops(如果你正在做一个长期的任务)或return迅速走出去的doInBackground和呼叫cancel() on asynchtask将跳过执行onPostExecute()

另一种选择是,如果你想在后台停止多个运行异步任务,那么调用每个任务的取消操作可能会很繁琐,所以在这种情况下,你可以在container class(of asynchtask)有一个布尔标志并跳过asynchtask标志已设置为True,像

protected Object doInBackground(Object... x) { 
    while (/* condition */) { 
     // work... 
     if (container_asynch_running_flag) break; 
    } 
    return null; 
} 

但一定要也把支票onpostExecute在这种情况下,因为它不会停止onPOST等的执行。

0

您可以立即停止呼叫asyncTask.cancel(true)

但不建议这样做,因为它可能导致内存泄漏。最好拨打asyncTask.cancel(false)并退出doInBackground功能,手动检查isCancelled()值为@Pavneet建议。

相关问题