我有一个Service,它在Manifest和MapboxMap
Activity中定义了一个不同的进程,我只是想知道如何使用LocalBroadcastManager
在我的Service和Activity之间进行LocalBroadcastManager
。
我试图将服务上下文传递给LocalBroadcastManager.getInstance()
,然后在我的Activity中注册一个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"));
当我运行应用程序时,我的服务发送广播,但我的活动没有收到广播消息!
我认为这个问题是因为我的服务在我的Manifest中的另一个进程中定义了这样的...
android:name=".services.ForegroundService"
android:enabled="true"
android:exported="false"
android:process=":ForegroundService"
...但我希望以这种方式进行沟通,因为处于不同的过程有助于我的电池效率目标。
如何在不同的进程中使用LocalBroadcastManager在Activity和Service之间进行通信
这是不可能的。 LocalBroadcastManager
的“local”表示“此过程的本地”。 LocalBroadcastManager
特别不适用于进程之间。
或者:
让活动和服务都在同一个过程中,或者
使用某种形式的IPC在进程之间进行通信(系统广播, Messenger
等)