从不同的线程的Android更新视图 [英] Update view from different thread Android
问题描述
我做一个简单的Android应用程序接收到短信时将更新其视图。这是code为我的接收器类
I make a simple Android Apps that will update its view when an SMS is received. This is the code for my receiver class
public class SMSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
intent.setClass(context, SMSReceiverService.class);
intent.putExtra("result", getResultCode());
WakefulIntentService.sendWakefulWork(context.getApplicationContext(), intent);
}
}
这类将调用SMSReceiverService类来处理迎面而来的短信和执行方法notifyMessageReceived,这是如下图所示。
That class will call SMSReceiverService class to handle the oncoming SMS and execute method notifyMessageReceived, which is shown below.
private void notifyMessageRecevied(SMS message) {
if(!isInMyApps()) {
launchPopUp();
}
else {
//updating view should go here
}
}
问题是,我不知道如何更新我的活动视图(这是在单独的类,而不是SMSReceiverService类),当我试图在我的活动更新我的TextView,它抛出的CalledFromWrongThreadException。任何人都可以请帮我吗?
The problem is, I don't know how to update the view in my activity (which is in separate class, not the SMSReceiverService class), when I tried to update my TextView in my activity, it thrown an CalledFromWrongThreadException. Can anybody please help me ?
在此先感谢和抱歉我的英语不好...
Thanks in advance, and sorry about my bad English...
推荐答案
您可以创建一个活动变量来保存你想要的活动的实例。
You can create an activity variable to hold the instance of the activity you want.
在 SMSReceiver
(你要拨打的那个):
In SMSReceiver
(the one you want to call):
SMSReceiverService.setMainActivity(this);
在 SMSReceiverService
(您想从更新一):
public static SMSReceiver smsActivity;
public static void setMainActivity(SMSReceiver activity)
{
smsActivity = activity;
}
...
smsActivity.runOnUiThread(new Runnable() {
public void run() {
try{
smsActivity.textView.setText("");
}
catch{}
}
}
假设 SMSActivity
是包含您要更新视图中的文件。
Assuming SMSActivity
is the file that contains the view you want to update.
这篇关于从不同的线程的Android更新视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!