Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 996
Armand Avatar asked Dec 03 '22 07:12

Armand


2 Answers

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().

like image 55
inazaruk Avatar answered Dec 05 '22 21:12

inazaruk


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);
                }
            }
    );
}
like image 31
Armand Avatar answered Dec 05 '22 19:12

Armand