从服务更新 UI(使用处理程序?)
问题说明
当我收到通知时,我正在尝试更新 FirstActivity
中的 UI,但被 runOnUiThread
、Runnable
和 Handler 弄糊涂了.这是我所拥有的:我正在运行 FirstActivity 和 NotificationService.当 NotificationService 收到通知时,它会更新 FirstActivity UI.
I am trying to update my UI in FirstActivity
when I receive a notification but is confused by runOnUiThread
, Runnable
and Handler
. Here is what I have: I am running FirstActivity and NotificationService. When NotificationService reeives a notification, it will update FirstActivity UI.
我还有另一个服务 AlarmService
正在运行.第一个活动
I also have another service AlarmService
running. First 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 中添加额外的代码吗?
I keep getting looper.prepare error. Do I need to put extra codes in my FirstActivity?
正确答案
我的第一直觉是,您应该将 Activity 绑定到您的服务并在其一侧处理 UI 更新,而不是直接修改 Activity 的服务.
My 1st instinct is that you should instead have the Activity bind to your service and handle the UI update on its side instead of the Service directly modifying the Activity.
在此处查看更多信息:
http://developer.android.com/reference/android/app/Service.html#LocalServiceSample
这里有一个例子:
示例:使用消息传递在活动和服务之间进行通信
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfijbj
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20