我想在从其创建的AsyncTask在后台运行时在MainActivity中检查一个变量,然后在将该变量设置为某个值(例如,设为true时结束AsyncTask;
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?
}
}
e.x。
private 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否则,如果需要传递对象,则必须研究同步,您可以在Googling上找到一些不错的文章。