• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

从服务更新 UI(使用处理程序?)

用户头像
it1352
帮助1

问题说明

当我收到通知时,我正在尝试更新 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?

正确答案

#1

我的第一直觉是,您应该将 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
系列文章
更多 icon
同类精品
更多 icon
继续加载