英文:
AsyncTask check MainActivity for variable set before ending doInBackground
问题
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)
{
// 在后台运行时检查 MainActivity 的变量,当这个变量设置为 true 时退出或在 onPostExecute 中处理?
}
}
英文:
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?
}
}
答案1
得分: 2
假设Android与普通的Java线程和可运行对象在这方面是类似的,我会认为你可以在主线程(MainActivity.java)中创建一个原子变量,然后在你的AsyncTask中进行检查。
例如:
private final AtomicInteger myInt = new AtomicInteger(你需要的任何值);
public int getMyInt() {
return myInt.get();
}
然后只需获取该值并根据需求处理。你还可以编写方法来修改它或执行其他任何你想做的操作。
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html
否则,如果你需要传递对象,你将需要研究同步,你可以通过谷歌搜索找到一些很好的文章。
编辑:要实现这个,你可以将AtomicInteger和方法都设为静态的,然后只需调用该方法来获取整数的值。
例如:
private final static AtomicInteger myInt = new AtomicInteger(你需要的任何值);
public static int getMyInt() {
return myInt.get();
}
然后在你的AsyncTask中:
public void doInBackground() {
if(MainActivity.getMyInt() == 某个值) {
//对其进行某些操作
}
}
英文:
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
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论