activity 如何从服务中提取值?

How can an activity pull a value from a service?

我有两个 classes:一个是 activity,另一个是从 NotificationListenerService 派生的 class。

我需要 activity 能够获取设备中断过滤器设置的初始值,然后在它发生变化时得到通知。

因此 activity 正在侦听 NLS 在中断过滤器的值发生变化时发出的广播。 但是,我需要获取中断过滤器的初始值 - 如果用户从不更改此值,那么我的 activity 将永远不会收到广播,因此它永远不会找出值是什么。

所以我的问题是 activity 如何从服务请求值?

请注意,NotificationListenerService 由 OS 启动,它不是我的 activity 创建或启动的。

您可以使用 SharedPreferences 存储一些值(在服务中),并且您的 activity 可以通过从 SharedPreferences 加载值来依赖它。
您也可以使用 EventBus 并使用它传递一些事件。方式应该是这样的:
- 你的 Activity 注册 EventBus 来捕捉一些特殊的事件而不是 NLS。 - 通知服务在需要时生成并发布事件。它还将您 activity 需要的任何数据打包到事件中 - 您的 Activity 从 NS 捕获一个新事件并从中获取数据:

public void onEvent(final FriendsRenameEvent event) {
    Log.i(this, "onEvent() FriendsRenameEvent event");
    if (event.isActionSucced)
        listAdapter.notifyDataSetChanged();
}

事件只是一个简单的class(扩展对象):

public class FriendsRenameEvent {

    public final boolean isActionSucced;

    public FriendsRenameEvent(final boolean isSucced/*, final Contact rejectedContact*/) {
        this.isActionSucced = isSucced;
    }
}

我像这样将它用于 GCM(GCMIntenService 的一部分):

private void handleMessage(final Bundle gcmBundle) {
    if (gcmBundle == null) {
        Log.e(this, "handleMessage(): Received null-gcmBundle in GCMIntentService.onReceive()!");
        return;
    }

    Log.i(this, "handleMessage(): gcmBundle: " + gcmBundle);

    EventBus.getDefault().post(new IncomingGCMEvent(gcmBundle));
}

在Activity中:

public void onEventMainThread(final IncomingGCMEvent event) {
   final String payloadMessage = event.gcmBundle.getString("collapse_key");
   ...
}

还有一种绑定机制可以将服务和活动绑定在一起。使用 Bind 接口,您可以 运行 来自 Activity 的服务的方法,就像它 Activity 自己的方法一样。