【问题标题】:Have a service communicate with a widget [duplicate]让服务与小部件通信 [重复]
【发布时间】:2014-06-06 01:25:34
【问题描述】:

我提供了一项服务,用于获取某物的状态并将该状态显示为通知。我还想在小部件中显示此状态。我将如何在服务和小部件之间进行通信?

【问题讨论】:

  • 这似乎也是一个不错的资源:@​​987654321@

标签: android service android-widget


【解决方案1】:

最简单的方法是让服务在状态发生变化时发送广播,并让小部件实现广播接收器。

发送广播的文档在这里:

http://developer.android.com/reference/android/content/Context.html(在该页面搜索 sendBroadcast)

BroadcastReciver 的文档在这里:http://developer.android.com/reference/android/content/BroadcastReceiver.html

【讨论】:

    【解决方案2】:

    您可以使用AppWidgetManager 来更新您的小部件。

    例如:

    public class MyService extends IntentService {
        // ...
    
        private void updateWidgets() {
            AppWidgetManager widgetManager = AppWidgetManager.getInstance(this);
    
            // Get a list of widgets to update
            int[] widgetIds = widgetManager.getAppWidgetIds(new ComponentName(this, MyAppWidgetProvider.class);
    
            // Update the widgets
            RemoteViews updatedViews = // Create your new RemoteViews here
            widgetManager.updateAppWidget(widgetIds, updatedViews);
        }
    }
    

    【讨论】:

      【解决方案3】:

      我最喜欢的方法是使用事件总线。这是我完成这项任务时遇到的最干净的方式。查看 Roman Nurik 的 Muzei 项目,了解他如何使用 GreenRobot 的框架来完成这项工作。 https://github.com/romannurik/muzei/search?q=EventBus&ref=cmdform

      【讨论】:

        猜你喜欢
        • 2011-03-01
        • 2012-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多