活动-> AsyncTask-> BroadcastReceiver->更新用户界面 [英] Activity -> AsyncTask -> BroadcastReceiver -> Update UI
问题描述
我正在从Activity
开始AsyncTask
.当AsyncTask
完成执行时,我需要发送广播,该广播需要调用Activity
方法来更新UI.
任何实现这一目标的好方法.
I am starting an AsyncTask
from an Activity
. When, the AsyncTask
completes its execution I need to send a broadcast which needs to call Activity
method to update the UI.
Any good approach to achieve this.
推荐答案
是.
如果AsyncTask
是Activity
的内部类,则它可以访问任何成员变量和Activity
方法.如果不是,那么您可以简单地将变量传递给其构造函数,甚至可以传递对Activity
的引用,以从onPostExecute()
调用Activity
方法.没有任何代码,很难说太多.
If the AsyncTask
is an inner class of your Activity
then it has access to any member variables and your Activity
methods. If it isn't then you can simply pass variables to its constructor or even a reference to the Activity
to call Activity
methods from onPostExecute()
. Without any code its hard to say much else.
要传递Activity
的实例并使用其方法(如果它是单独的类),则可以创建构造函数并执行类似的操作
To pass an instance of your Activity
and use its methods if its a separate class then you can create a constructor and do something like
public class MyTask extends AsyncTask<...> // add your params
{
private MyActivity activty;
public MyTask (MyActivity act)
{
this.activty = activty;
}
// ...
}
,然后在onPostExecute()
中添加类似内容
and in onPostExecute()
add something like
activity.myMethod();
并像这样调用任务
MyTask task = new MyTask(this); // pass a reference of the activity
task.execute(); // add params if needed
如果AsyncTask
是与Activity
不同的文件,则可以
If the AsyncTask
is a separate file from the Activity
then you can see this answer on how to use an interface for a callback
这篇关于活动-> AsyncTask-> BroadcastReceiver->更新用户界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!