0

When I log in into my app, an async task starts executing and while that task is being executed and I logout of app, that task is still running and give me the results after sometime(though I have logged out). I want to ask, is there any way to cancel that task so that it doesn't give me results?

  class AsyncClass extends AsyncTask<>{

    @Override
     protected String doInBackground(Void... params)
      {
             if(isCancelled())
               {
                Log.d("isCancelled", iscancelled());
               }
          //call the webservice

      }
    }

Now there is some other class from where I'm calling

if(asyncTaskObject!=null){
    asyncTaskObject.cancel(true);
        asyncTaskObject=null;
}

But Log statement inside iscancelled() is never called.

Rookie
  • 8,660
  • 17
  • 58
  • 91
  • check [this](http://stackoverflow.com/questions/2735102/ideal-way-to-cancel-an-executing-asynctask), [this](http://www.technotalkative.com/cancel-asynctask-in-android/). And i would go with Lalit's answer. – Paresh Mayani Jun 25 '12 at 10:44
  • What happens is, I am fetching the data from web service. Simultaneously 6 asyntasks are running. The problem is When fisrt async task starts executing and I log out, and when i login with different user, the first asyntask doesn't execute again. Does it make sense? – Rookie Jun 25 '12 at 12:07
  • http://vikaskanani.wordpress.com/2011/08/03/android-proper-way-to-cancel-asynctask/ – Rookie Jun 26 '12 at 10:05

4 Answers4

2

Yes you can cancel AsyncTask using cancel(boolean). You can create an instance of AsyncTask class and call,

if(task != null && task.equals(AsyncTask.Status.RUNNING))
task.cancel(true);
Lalit Poptani
  • 67,150
  • 23
  • 161
  • 242
1

Yes, it possible.

YourAsyncTask mTask;
 if(mTask!=null) mTask.cancel(); 

Thanks

Md Abdul Gafur
  • 6,213
  • 2
  • 27
  • 37
1

as per this link use Task.cancel(true);and isCancelled()

private class UpdateLibrary extends AsyncTask<Void, Integer, Boolean>{
    private ProgressDialog dialog = new ProgressDialog(Library.this);
    private int total = Library.instance.appState.getAvailableText().length;
    private int count = 0;

    //Used as handler to cancel task if back button is pressed
    private AsyncTask<Void, Integer, Boolean> updateTask = null;

    @Override
    protected void onPreExecute(){
        updateTask = this;
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setOnDismissListener(new OnDismissListener() {               
            @Override
            public void onDismiss(DialogInterface dialog) {
                updateTask.cancel(true);
            }
        });
        dialog.setMessage("Updating Library...");
        dialog.setMax(total);
        dialog.show();
    }

    @Override
    protected Boolean doInBackground(Void... arg0) {
            for (int i = 0; i < appState.getAvailableText().length;i++){
                if(isCancelled()){
                    break;
                }
                //Do your updating stuff here
            }
        }

    @Override
    protected void onProgressUpdate(Integer... progress){
        count += progress[0];
        dialog.setProgress(count);
    }

    @Override
    protected void onPostExecute(Boolean finished){
        dialog.dismiss();
        if (finished)
            DialogHelper.showMessage(Str.TEXT_UPDATELIBRARY, Str.TEXT_UPDATECOMPLETED, Library.instance);
        else {
                //Do nothing......
             }
    }
}
Community
  • 1
  • 1
Dheeresh Singh
  • 15,643
  • 3
  • 38
  • 36
1

I had the same problem just a day ago :)

A mixture of the 3 other answers that works for me.

First declare your asyncTask on a field:

private MyTaskClass miTask;

On the onCreate/onResume if an activity:

miTask = new MyTaskClass();

Then you can execute it in any method.

miTask.execute();

And in the onPause/onStop:

miTask.cancel(true);

This will only work if in your doInBackground you check isCancelled(), an example that i made for a cursor access that was already close if the fragment was dismissed:

@Override
    protected Void doInBackground(Void... params) {
        cached = true;
        int idIndex = currentCursor.getColumnIndex(Contacts._ID);
        int displayNameIndex = currentCursor
                .getColumnIndex(Contacts.DISPLAY_NAME);

        while (currentCursor.moveToNext()) {
            if (isCancelled()) {
                break;
            }

Hope that helps, regards. Alex

Goofyahead
  • 5,874
  • 6
  • 29
  • 33