我需要从runnable更新ui。我的逻辑如下。
我从片段生命周期的onCreate开始运行。而可运行实例负责请求网络。问题是可运行实例从网络获取数据后,我不知道如何更新片段。
代码在CustomFragment.java中的片段中开始运行。
public void onCreate(Bundle savedInstanceState) {
Log.d(DEBUG_TAG, "onCreate");
super.onCreate(savedInstanceState);
accountMgr.requestAccountInfo();
}
在AccountManager.java中启动可运行代码
/**
* request Account info from server
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void requestAccountInfo() {
Account act = getCurrentAccount();
Thread t = new Thread(new RequestAccountInfoTask(act));
t.start();
}
/**
* automatically update Account info, like space usage, total space size, from background.
*/
class RequestAccountInfoTask implements Runnable {
private Account account;
public RequestAccountInfoTask(Account account) {
this.account = account;
}
@Override
public void run() {
doRequestAccountInfo(account);
}
}
最佳答案
runOnUiThread()
需要Activity
参考。还有其他选择。您不需要Activity
引用您的Thread
。您始终可以通过主循环程序获取UI处理程序。传递其他参数(例如您的界面)以在任务完成时更新片段。
class RequestAccountInfoTask implements Runnable {
private Account account;
private Handler mHandler;
public RequestAccountInfoTask(Account account) {
this.account = account;
mHandler = new Handler(Looper.getMainLooper());
}
@Override
public void run() {
doRequestAccountInfo(account);
//use the handler
}
}
您在实例化的
Handler
上运行的所有内容都将位于UI线程上。当然,使用
runOnUiThread()
是完全合理的。