简体   繁体   中英

AsyncTask kill task when back button pressed

I am having a little problems with AsyncTask.

I have it implemented 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 ever I press the back button nothing happens, it just completes the task as if I didn't press the back button

Any idea why?

There are two parts of this problem:

1) Implement your doInBackground() in such a way, so it checks whether AsyncTask is cancelled.

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

2) You should call asynTask.cancel(true) in your Activity's onDestroy() .

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);
                }
            }
    );
}

it is also possible to use follwing method in activity

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();
    imageLoadingAsyncTask.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