0

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?
    }

}
ruzip
  • 45
  • 5
  • 4
    Does this answer your question? [Ideal way to cancel an executing AsyncTask](https://stackoverflow.com/questions/2735102/ideal-way-to-cancel-an-executing-asynctask) – Ali Ahsan Apr 09 '20 at 14:01
  • Almost, but my running variable will be evaluated from my MainActivity. How do I? – ruzip Apr 09 '20 at 15:14

1 Answers1

2

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
     }
}
Nathan S
  • 58
  • 8
  • Thanks, but how do I call getMyInt() inside AsyncTask specifically in doinBackground? – ruzip Apr 09 '20 at 15:12
  • You could just as easily use a volatile variable for this. If you use an AtomicInteger, it's a good practice to make it final. – Ryan M Apr 09 '20 at 16:51
  • @Ryan M good point, I forgot that while writing this. And yeah, volatile would work, but if he was trying to make a counter or something, I thought the features of AtomicInteger would be better. – Nathan S Apr 09 '20 at 18:43
  • @Nathan Stark Thanks, it works with the static and the method as well. I haven't thoroughly tested it yet using the AtomicBoolean but will get back to this as soon as everything works. I will be voting this up for now. – ruzip Apr 10 '20 at 05:38