从服务更新用户界面(使用处理器?) [英] Updating UI from a service (using a handler?)

查看:119
本文介绍了从服务更新用户界面(使用处理器?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更新我在 FirstActivity 的用户界面时,我收到通知,而是由 runOnUiThread 困惑,的Runnable 处理程序。下面是我:我正在运行FirstActivity和NotificationService。当NotificationService reeives一个通知,它会更新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
}

NotificationService

NotificationService

    //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   
}

我不断收到活套。prepare错误。我需要把额外的codeS在我的FirstActivity?

I keep getting looper.prepare error. Do I need to put extra codes in my FirstActivity?

推荐答案

我的第一直觉是,你应该改为有活动绑定到你的服务和处理在其一侧的UI更新,而不是服务直接修改活动。

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.

在这里看到更多信息:
<一href="http://developer.android.com/reference/android/app/Service.html#LocalServiceSample">http://developer.android.com/reference/android/app/Service.html#LocalServiceSample

See more info here:
http://developer.android.com/reference/android/app/Service.html#LocalServiceSample

和这里的一个例子:
<一href="http://stackoverflow.com/questions/4300291/example-communication-between-activity-and-service-using-messaging">Example:使用消息活动和服务之间的通信

And an example here:
Example: Communication between Activity and Service using Messaging

这篇关于从服务更新用户界面(使用处理器?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆