简体   繁体   中英

How to stop asynctask in android when back button is pressed

I have an activity (say Avtivity A) which runs an asyncatsk and display some results which gets displayed in another activity (Activity B). All is working fine. When the user clicks on a button, the task is trigerred and the other activity (activity B) comes into display with the progress bar. If I press the back button in activity B (with the progress bar still visible) I go to Activity A. But after some time (when the task completes) Activity B becomes Visible.

I wish to stop the asynctask (which is associated with Activity A) when the user presses back button in Activity B.

Kindly help me and thanks for your help

MyAsyncTask myTask=null;
myTask = new MyAsyncTask();

for executing task

myTask.execute();

for stop/cancel task

public void onBackPressed()
{

    myTask.cancel(true);
}

If you display results and progressBar, and handle Canceling in activity B, then you probably should start your AsyncTask in Activity B. But I'd suggest you waiting until AsyncTask is finished and then starting Activity B with data in a bundle. In either case you handle all AsyncTask related things in one activity. Try to not overpmlicate everything. Just implement some OnAsyncTaskFinishedListener() like:

in AsyncTask class:

public interface OnMyAsyncTaskCompletedListener {
    void onMyAsyncTaskCompletedListener(MyResults results);
}

. . .

@Override
protected void onPostExecute(MyResults results) {
    onMyAsyncTaskCompletedListener(results);
}

@Override
protected void onCancelled() {
    onMyAsyncTaskCompletedListener(null);
}

Then in your Activity you implement OnMyAsyncTaskCompletedListener and

public void onServerRequestCompleted(MyResults results) {
    //Start activity passing results in Intent
}

Finally, to cancel running activity you do smth like:

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

Activity BonDestroy()方法中,你应该调用asynTask.cancel(true)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM