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.
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:
On the onCreate/onResume if an activity:
Then you can execute it in any method.
And in the onPause/onStop:
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:
Hope that helps, regards.
Alex