Jack
Jack

Reputation: 135

How to send intent from Service to Activity using LocalBroadcastManager?

We have an app which uses an Android Service. Sending intents from the service to an activity doesn't work using LocalBroadcastManager. However, the intent is never received by the activity... (It works using context.sendBroadcast().)

Anyone an idea what's missing here?

The service:

public int onStartCommand(final Intent intent, int flags, int startId) {
        LocalBroadcastManager.getInstance(TestService.this).sendBroadcast(new Intent("bar"));

        return START_STICKY;
}

The activity:

public class MyActivity extends Activity
{
private static final String TAG = MyActivity.class.getName();

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "Recieved message by BroadcastReciever: " + intent.getAction());
    }
};

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    registerReceiver(mReceiver, new IntentFilter("bar"));

    Button loginButton = (Button) findViewById(R.id.button);
    loginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {                
            Intent serviceIntent = new Intent("foo", null, this, TestService.class);
            startService(serviceIntent);
        }
    });
}

The manifest:

<service android:name=".TestService"></service>

Upvotes: 1

Views: 3283

Answers (1)

Karakuri
Karakuri

Reputation: 38585

You need to use LocalBroadcastManager.getInstance(this).registerReceiver(...), as well as LocalBroadcastManager.getInstance(this).unregisterReceiver(...).

The normal registerReceiver(...) and unregisterReceiver(...) are for broadcasts sent by Context#sendBroadcast() and will not receive those sent by LocalBroadcastManager#sendBroadcast().

Upvotes: 4

Related Questions