Reputation: 1957
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
Upvotes: 1
Views: 8907
Reputation: 1
In Activity B's onDestroy()
method you should call asynTask.cancel(true)
.
Upvotes: 0
Reputation: 9272
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);
}
Upvotes: 1
Reputation: 3585
MyAsyncTask myTask=null;
myTask = new MyAsyncTask();
for executing task
myTask.execute();
for stop/cancel task
public void onBackPressed()
{
myTask.cancel(true);
}
Upvotes: 4
Reputation: 5599
AsyncTask has a cencel method: http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean)
Upvotes: 0