当我收到通知时,我正尝试在 FirstActivity
中更新我的 UI,但对 runOnUiThread
、Runnable
和 Handler 感到困惑
。这是我所拥有的:我正在运行 FirstActivity 和 NotificationService。当 NotificationService 收到通知时,它会更新 FirstActivity UI。
我还有另一个服务 AlarmService
正在运行。
第一个 Activity
@Override
public void onResume() {
super.onResume();
//some other code for alarm service
}
通知服务
//on receiving notification
private void showNotification(String text) {
//Get activity
Class<?> activityClass = null;
try {
activityClass = Class.forName("com.pakage.FirstActivity");
contextActivity = (Activity) activityClass.newInstance();
//Update UI on FirstActivity not working
contextActivity.runOnUiThread(new Runnable() {
public void run()
{
Looper.prepare();
TextView tv = (TextView ) contextActivity.findViewById(R.id.notifyTest);
Looper.loop();
}
});
} catch (Exception e) {
e.printStackTrace();
}
//Shows the notification
Notification n = new Notification();
//... etc
}
我不断收到 looper.prepare 错误。我需要在我的 FirstActivity 中添加额外的代码吗?
最佳答案
我的第一直觉是,您应该让 Activity 绑定(bind)到您的服务并在其端处理 UI 更新,而不是让服务直接修改 Activity。
在这里查看更多信息:
http://developer.android.com/reference/android/app/Service.html#LocalServiceSample
还有一个例子:
Example: Communication between Activity and Service using Messaging
关于android - 从服务更新 UI(使用处理程序?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7942083/