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

标签 android user-interface service handler runnable

当我收到通知时,我正尝试在 FirstActivity 中更新我的 UI,但对 runOnUiThreadRunnableHandler 感到困惑。这是我所拥有的:我正在运行 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/

相关文章:

user-interface - 如何放置 GUI 面板?

asp.net-mvc - 构建 ASP.net MVC 应用程序以使用存储库和服务

r - 基于窗口大小的 Shiny 动态内容(如 CSS 媒体查询)

c++ - 如何创建像 WinAmp 这样的自定义皮肤

android - setAction() 对 intent (Broadcast) 做了什么

linux - 防止在 Redhat 7 中停止 auditd 服务

java - 当用户退出微调器时调用哪个事件

android - kotlin 中的 Dagger2 编译问题

android - 数据更改时刷新 fragment 内容的方法(如调用 onCreateView)

android - 场景碰撞