AsyncTask kills a task when you click the back button

I am having small issues with AsyncTask.

I implemented it as follows

private class MakeConnection extends AsyncTask<String, Void, String> implements OnDismissListener{ Context context; ProgressDialog myDialog; public MakeConnection(Context conetext) { this.context = conetext; myDialog = new ProgressDialog(this.context); myDialog.setCancelable(true); myDialog.setOnDismissListener(this); } @Override protected String doInBackground(String... urls) { //do stuff } @Override protected void onPostExecute(String result) { try { myDialog.dismiss(); success(result); }catch(JSONException e) { data = e.toString(); } } @Override protected void onProgressUpdate(Void... values) { myDialog = ProgressDialog.show(context, "Please wait...", "Loading the data", true); } @Override public void onDismiss(DialogInterface dialog) { this.cancel(true); } } 

But when I press the back button, nothing happens, it just finishes the task, as if I did not press the back button

Any idea why?

+4
source share
3 answers

There are two parts to this problem:

1) doInBackground() your doInBackground() so that it checks to see if AsyncTask been canceled.

  @Override protected String doInBackground(String... urls) { for(int i = 0; i < 100 && !isCancelled(); i++) { //do some stuff } } 

2) You must call asynTask.cancel(true) in your onDestroy() activity.

+12
source

This fixes my problem

 @Override protected void onPreExecute(){ myDialog = ProgressDialog.show( context, "Please wait...", "Loading the data", true, true, new DialogInterface.OnCancelListener(){ @Override public void onCancel(DialogInterface dialog) { MakeConnection.this.cancel(true); } } ); } 
+4
source

You can also use the follwing method in activities

 @Override public void onBackPressed() { // TODO Auto-generated method stub super.onBackPressed(); imageLoadingAsyncTask.cancel(true); } 
+1
source

All Articles