如何在按下后退按钮时停止异步任务执行

时间:2015-11-26 09:54:10

标签: android asynchronous

请我有一个包含异步任务方法的活动,即使用户已从该页面移动,此异步任务方法也会继续在后台执行。只要用户按下后退按钮或从该页面移动到另一页,就有办法停止异步任务执行。

以下是我的尝试,但它无法正常工作

private AsyncTask totalLikesAsync;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);
    context = this;

   totalLikesAsync = new TotalLikes().execute(msgID);
}






@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
    switch (menuItem.getItemId()) {
        case android.R.id.home:

            totalLikesAsync.cancel(true);
            this.finish();
            break;

        case R.id.share:
            new ShareImage().execute(msgImage);
        default:
            return super.onOptionsItemSelected(menuItem);
    }
    return true;
}





private class TotalLikes extends AsyncTask<String, String, JSONObject> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }



    @Override
    protected JSONObject doInBackground(String... msgIDs) {
        UserFunctions userFunction = new UserFunctions();

        String msgsID = msgIDs[0];
        JSONObject json=null;

        if(!isCancelled()){

            //This gets all the information unread from the server
            json = userFunction.TotalLikes(context, msgsID);
        }

        return json;
    }

    @Override
    protected void onPostExecute(JSONObject json) {
        /**
         * Checks for success message.
         **/
        if (json != null) {

            ...
        } else {

           ...
        }

}
}

更新

在测试下面的所有答案后,即使按下后退按钮,它们都允许在异步任务中执行doinbackground。我想要一种情况,只要按下后退按钮就会取消背景。

4 个答案:

答案 0 :(得分:3)

@Override
public void onBackPressed() {
    super.onBackPressed();
    if (totalLikesAsync != null && totalLikesAsync.getStatus().equals(AsyncTask.Status.RUNNING)) {
        totalLikesAsync.cancel(true);
    }
} 

答案 1 :(得分:1)

@Override
public void onBackPressed() {
    super.onBackPressed();
    totalLikesAsync.cancel(true);
}

答案 2 :(得分:0)

@Override
public void onBackPressed() {
TotalLikes.cancel(true);
// If you want to finish the activity you can use below code
// finish(); 
super.onBackPressed();
}

答案 3 :(得分:0)

自己处理onBackPressed()方法:

@Override  
public void onBackPressed() 
  {
   if (totalLikesAsync != null)
   totalLikesAsync.cancel(true);

   super.onBackPressed();
  }