Search code examples
javaandroidandroid-asynctask

AsyncTask check MainActivity for variable set before ending doInBackground


I would like to check for a variable in MainActivity while an AsyncTask created from it is running in the background, then end the AsyncTask when this variable is set to a certain value let's say to true;

MainActivity

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        new MyTask(this).execute();
    }

MyTask


public class MyTask extends AsyncTask<Void, Void, Void>
{
    @Override
    protected Void doInBackground(Void... ignore)
    {
      //check for MainActivity variable then exit or PostExecute when this variable is set to true?
    }

}

Solution

  • Assuming Android is similar to normal Java threads and runnables in this regard, I would assume that you could just create an atomic variable in your main thread (MainActivity.java) and then check it in your AsyncTask.

    e.x.

    private final AtomicInteger myInt = new AtomicInteger(whatever value you need);
    
    public int getMyInt() {
         return myInt.get();
    }
    

    Then just get the value and do what you want with it. You can also write methods to modify it or whatever else you want to do. https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html

    Otherwise if you need to pass objects, you'll have to look into synchronization, which you can find some good articles on by Googling.

    edit: To implement you could make the AtomicInteger static and the method as well, then just call the method to get the value of the integer.

    e.x.

    private final static AtomicInteger myInt = new AtomicInteger(whatever value you need);
    
    public static int getMyInt() {
         return myInt.get();
    }
    

    then in your AsyncTask:

    public void doInBackground() {
         if(MainActivity.getMyInt() == some value) {
              //do something with it
         }
    }