簡體   English   中英

如何在不同的進程中使用LocalBroadcastManager在Activity和Service之間進行通信

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

我有一個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等)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM