Search code examples
androidandroid-asynctask

Cancel asynctask without instance (Android)


I have multiple asynctask in one activity in android and I usually call them like this:

new call_SOAPCheck().execute();

or like this

new MainActivity.DownloadTask(getApplicationContext()).execute("http://.....");

I want to cancel any asynctask running when pressing the back button, but since I don't create an instance I cant call .cancell(true).

Is there a way to kill the asynctask running without the instance?

the reason I call them like that is that I need to execute them many times in the same activity, and if I declare them like "global" variables I get an error that I can only execute them once.

Also, there is no loop inside my asynctask so I can't check isCancelled() periodically


Solution

  • Why not keep a reference, and recreate them:

    Instead of doing this:

    new call_SOAPCheck().execute();
    

    Do this:

    //keep a global ref
    
    call_SOAPCheck task; 
    

    Then whenever you want call task again and again, just recreate over and over. By doing this:

    private void callTaskAgain(){
    
    task = new call_SOAPCheck();
    task.execute();
    
    }