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

Sina :

I have a Service which is in a different process defined in Manifest and a MapboxMap Activity, and I just wanted to know how I can communicate between my Service and Activity using LocalBroadcastManager.

I've tried to pass the Service Context to LocalBroadcastManager.getInstance() and then register a LocalBroadcast in my Activity. It registers successfully but it can't get the information from my Service!

Here's my code, in my Service...

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

...and I register it in my 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<Integer, 
MarkerItem>)intent.getSerializableExtra("list");
                    Timber.tag("sawL").d("updated");
                }
            }
        } , new IntentFilter("LocationIntent"));

When I run the app, my Service sends the broadcast, but my Activity doesn't get the broadcast message!

I think the issue is because of my Service which is defined in another process in my Manifest like this...

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

...but I would like to communicate this way, because being in a different process helps my battery efficiency goals.

CommonsWare :

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

This is not possible. The "local" in LocalBroadcastManager means "local to this process". LocalBroadcastManager specifically does not work between processes.

Either:

  • Have both the activity and the service be in the same process, or

  • Use some form of IPC to communicate between the processes (system broadcasts, Messenger, etc.)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=329783&siteId=1