AsyncTask 在结束 doInBackground 之前检查 MainActivity 中的变量集

AsyncTask check MainActivity for variable set before ending doInBackground

我想检查 MainActivity 中的一个变量,而从它创建的 AsyncTask 在后台 运行,然后当此变量设置为某个值时结束 AsyncTask,假设为 true;

主要活动

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

我的任务


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

}

假设 Android 在这方面类似于普通的 Java 线程和可运行对象,我假设您可以在主线程 (MainActivity.java) 中创建一个原子变量,并且然后在你的 AsyncTask 中检查它。

e.x.

private final AtomicInteger myInt = new AtomicInteger(whatever value you need);

public int getMyInt() {
     return myInt.get();
}

然后只获取值并用它做你想做的事。您还可以编写方法来修改它或您想要做的任何其他事情。 https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html

否则如果你需要传递对象,你将不得不研究同步,你可以通过谷歌搜索找到一些好的文章。

编辑:要实现,您可以将 AtomicInteger 和方法设为静态,然后只需调用该方法即可获取整数的值。

e.x.

private final static AtomicInteger myInt = new AtomicInteger(whatever value you need);

public static int getMyInt() {
     return myInt.get();
}

然后在你的 AsyncTask 中:

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