Android: sending LocalBroadcastManager's intents from BroadcastReceiver events

android, android-context, android-intent

Solution

The `LocalBroadcastReceiver` documentation states that it is a

Helper to register for and send broadcasts of Intents to local objects within your process

This means if you are using a Service that is running in a separate process (eg `android:process=":remote"`), `LocalBroadcastManager` is quite likely to fail (albeit silently) because you are probably getting two separate instances of this class (one for each process).

Problem

I'm having a strange situation, where an intent receiver is registered with LocalBroadcastManager either from service or from MainActivity, and when intent is sent from PHONE_STATE receiver (defined in AndroidManifest.xml), it's never received. A "self-test" with sending same intent from activity|service - works. Is it worth trying to specify LocalBroadcastManager's intent to be received via AndroidManifest.xml? Service is defined as: ``` <service android:name=".AppService" android:process=":remote"> <intent-filter> <action android:name="me.cmp.app.AppService" /> </intent-filter> </service> ``` In service: ``` public class AppService extends Service { @Override public void onCreate() { super.onCreate(); LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("me.cmp.app.statechange")); // self-test uses same intent sending code: Intent intent2 = new Intent("me.cmp.app.statechange"); intent2.putExtra("message", "selfsend"); LocalBroadcastManager.getInstance(this).sendBroadcastSync(intent2); } ... ``` In manifest: ``` <receiver android:name="me.cmp.app.PhoneReceiver" > <intent-filter> <action android:name="android.intent.action.PHONE_STATE" > </action> </intent-filter> </receiver> ``` Listener: ``` public class PhoneReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle extras = intent.getExtras(); if (extras != null) { Log.e("test", extras.getString(TelephonyManager.EXTRA_STATE)); Intent intent2 = new Intent("me.cmp.app.statechange"); intent2.putExtra("message", state.toString()); LocalBroadcastManager.getInstance(context).sendBroadcastSync(intent2); Log.w("test", "Broadcast sent"); } } } ``` -- The main problem seems to be Should I use android: process =":remote" in my receiver? ; however I'm still not sure why MainActivity's receiver didn't worked earlier, maybe fully qualified names are a must.

Original source

Related problems