首页 > 解决方案 > 如何在不同进程中使用 LocalBroadcastManager 在 Activity 和 Service 之间进行通信

问题描述

我有一个服务,它位于 Manifest 和MapboxMapActivity 中定义的不同进程中,我只是想知道如何使用LocalBroadcastManager.

我试图将服务上下文传递给LocalBroadcastManager.getInstance()然后LocalBroadcast在我的活动中注册一个。它注册成功,但无法从我的服务中获取信息!

这是我的代码,在我的服务中......

Intent locationIntent = new Intent("LocationIntent");
        locationIntent.setAction("updatedLocations");
        locationIntent.putExtra("list",updatedList);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(locationIntent);

...我在我的活动中注册它:

LocalBroadcastManager.getInstance(getApplicationContext()).registerReceive``r(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Timber.tag("localB").d("registered!");
                if (intent != null && intent.getAction() != null && 
intent.getAction().equals("updatedLocations")) {
                    sawLocationsList = (HashMap<Integer, 
MarkerItem>)intent.getSerializableExtra("list");
                    Timber.tag("sawL").d("updated");
                }
            }
        } , new IntentFilter("LocationIntent"));

当我运行应用程序时,我的 Service 发送了广播,但我的 Activity 没有收到广播消息!

我认为这个问题是因为我的服务是在我的清单中的另一个进程中定义的......

android:name=".services.ForegroundService"
            android:enabled="true"
            android:exported="false"
            android:process=":ForegroundService"

...但我想以这种方式交流,因为处于不同的流程有助于我实现电池效率目标。

标签: javaandroidandroid-activityandroid-broadcastlocalbroadcastmanager

解决方案


如何在不同进程中使用 LocalBroadcastManager 在 Activity 和 Service 之间进行通信

这是不可能的。中的“本地”LocalBroadcastManager表示“此过程的本地”。LocalBroadcastManager特别是在进程之间不起作用。

任何一个:

  • 让活动和服务在同一个进程中,或者

  • 使用某种形式的 IPC 在进程之间进行通信(系统广播Messenger等)


推荐阅读