2015-04-08 56 views
0

我使用異步任務如下:如何停止異步任務的回憶?

private first_async first; // global variable 

// In onCreate 
first = new first_async(); 
first.execute(1); 

// then on click of the button I want to stop this, but it works after some time like this: 
if (!first.isCancelled()) { 
    first.cancel(false); 
} 

private class first_async extends AsyncTask<Integer, Void, Void> { 

    int var; 
    @Override 
    protected void doInBackground(Integer... params) { 
     while (!isCancelled()) { 
      var = params[0]; 
      // do some task 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(void thumb) { 
     super.onPostExecute(thumb); 
     if (var >= 7) { 
     } else { 
      first_time_imageURL = new first_time_get_images_URL(); 
      first_time_imageURL.execute(var+1); 
     } 
    } 
} 

所以問題是,取消一段時間後異步任務的工作。如果我不正確,請糾正我或如果有其他替代方法,請提及它。

回答

0
if (!first.isCancelled()) { 
first.cancel(false); 
} 

假在這裏應該是真的,這將取消Asynctask。所以:

first.cancel(true);