从服务更新 UI(使用处理程序?) [英] Updating UI from a service (using a handler?)

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

问题描述

当我收到通知时,我正在尝试更新 FirstActivity 中的 UI,但被 runOnUiThreadRunnableHandler 弄糊涂了.这是我所拥有的:我正在运行 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

这里有一个例子:
示例:使用消息传递在活动和服务之间进行通信

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

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