我的fragment中有3个fragment--所有这些都包含AsyncTask,而fragment包含一个int值,例如50。这里,我想要做的是将这3 int值(我在handler中的3 AsyncTask中获取)与在fragment中定义的int值进行比较。例如,如果AsyncTask in handler-1获得80,AsyncTask在handler-2中获得10,AsyncTask在handler-3中得到46,那么我想将这3 ints与fragment int进行比较。
我忘记告诉您,比较之后,mFragmentValue需要使用来自onPostExecute()的新值进行更新。
我的代码在这里发布很大,下面是一个例子:
class MyFragment{
int mFragmentValue = 50;;
void onViewCreated(){
handler1.post(calling AsyncTask here using runnable); //Here I get 80 in onPostExecute in MyAsyncTask, now I need to compare this 80 with mFragmentValue. These AsyncTasks are sub class of my fragment.
handler2.post(calling AsyncTask here using runnable); //Here I get 10 in MyAsyncTask, now I need to compare this 10 with mFragmentValue;
handler3.post(calling AsyncTask here using runnable); //Here I get 46 in MyAsyncTask, now I need to compare this 46 with mFragmentValue;
}
static class MyAsyncTask extend AsyncTask{
void onPostExecute(){
// getting int here.
//need to compare fetched int with mFragmentValue;
}
}
}发布于 2018-01-11 16:24:40
如果您只需要mFragmentValue在MyAsyncTask中的值,那么您可以直接传递它:
类MyFragment{
int mFragmentValue = 50;;
void onViewCreated(){
AsyncTask task = new MyAsyncTask();
task.execute(mFragmentValue);
}
static class MyAsyncTask extend AsyncTask{
int mTaskValue;
void doInBackground(Integer...values) {
mTaskValue = values[0];
}
void onPostExecute(){
// Now use mTaskValue
}
}
}注意,不需要使用Handler,也不需要在AsyncTask中使用Runnable。Handler的目的是方便线程之间的通信,但是AsyncTask已经为您处理了这个问题。此外,doInBackground()已经在自己的线程上运行,onPostExecute()运行在主线程上,因此不需要创建Runnable。
如果您需要更改mFragmentValue的值,那么MyAsyncTask 必须有对Fragment的引用。您可以通过使MyAsyncTask非静态或添加一个构造函数来实现这一点,该构造函数接受Fragment作为参数(或者您的片段实现的一些接口)。无论是哪种方式,您都必须找到另一种解决内存泄漏警告的方法。这里有一个向MyAsyncTask添加方法的解决方案,您可以从onPause()、onStop()或onDestroy()调用该方法。调用此方法将告诉AsyncTask Fragment引用将不再有效。然后,AsyncTask就会采取相应的行动,可能会中止其在doInBackground()中的工作。
https://stackoverflow.com/questions/48197924
复制相似问题