cuốn sách gpt4 ai đã làm

java - 如何在不同进程中使用 LocalBroadcastManager 在 Activity 和服务之间进行通信

In lại Tác giả: Walker 123 更新时间:2023-11-29 04:09:10 hai mươi bốn 4
mua khóa gpt4 Nike

我有一个服务,它在 list 中定义的不同进程和一个 MapboxMap Activity ,我只是想知道如何使用 LocalBroadcastManager 在我的服务和 Activity 之间进行通信.

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

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

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

...然后我将其注册到我的 Activity 中:

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
MarkerItem>)intent.getSerializableExtra("list");
Timber.tag("sawL").d("updated");
}
}
} , new IntentFilter("LocationIntent"));

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

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

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

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

câu trả lời hay nhất

How to Communicate between Activity and Service using LocalBroadcastManager in a different Process

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

hoặc:

  • 让 Activity 和服务都在同一个进程中,或者

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

关于java - 如何在不同进程中使用 LocalBroadcastManager 在 Activity 和服务之间进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56137212/

hai mươi bốn 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress