首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将处理程序的值与Android中的活动/片段中的值进行比较

如何将处理程序的值与Android中的活动/片段中的值进行比较
EN

Stack Overflow用户
提问于 2018-01-10 23:52:23
回答 1查看 33关注 0票数 0

我的fragment中有3个fragment--所有这些都包含AsyncTask,而fragment包含一个int值,例如50。这里,我想要做的是将这3 int值(我在handler中的3 AsyncTask中获取)与在fragment中定义的int值进行比较。例如,如果AsyncTask in handler-1获得80,AsyncTaskhandler-2中获得10,AsyncTaskhandler-3中得到46,那么我想将这3 intsfragment int进行比较。

我忘记告诉您,比较之后,mFragmentValue需要使用来自onPostExecute()的新值进行更新。

我的代码在这里发布很大,下面是一个例子:

代码语言:javascript
复制
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;
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2018-01-11 16:24:40

如果您只需要mFragmentValueMyAsyncTask中的值,那么您可以直接传递它:

类MyFragment{

代码语言:javascript
复制
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中使用RunnableHandler的目的是方便线程之间的通信,但是AsyncTask已经为您处理了这个问题。此外,doInBackground()已经在自己的线程上运行,onPostExecute()运行在主线程上,因此不需要创建Runnable

如果您需要更改mFragmentValue的值,那么MyAsyncTask 必须有对Fragment的引用。您可以通过使MyAsyncTask非静态或添加一个构造函数来实现这一点,该构造函数接受Fragment作为参数(或者您的片段实现的一些接口)。无论是哪种方式,您都必须找到另一种解决内存泄漏警告的方法。这里有一个向MyAsyncTask添加方法的解决方案,您可以从onPause()onStop()onDestroy()调用该方法。调用此方法将告诉AsyncTask Fragment引用将不再有效。然后,AsyncTask就会采取相应的行动,可能会中止其在doInBackground()中的工作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48197924

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档