rafvasq
rafvasq

Reputation: 1522

Receiving data in activity from a service

I've look at many solutions to other questions with similar issues but I can't figure out what's wrong with my code. I understand that LocalBroadcast is a popular way to do this and I've spent time trying to implement it. At the moment, the receiver isn't declared in my manifest but from what I understand, that's what the register lines are for.

In my activity:

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("MyActivity", "onReceive");
        String action = intent.getAction();
        int current = intent.getIntExtra("test", 0);
        Toast.makeText(MyActivity.this, current.toString(), Toast.LENGTH_LONG).show();
    }
};

@Override
public void onResume() {
    super.onResume();
    Log.d("MyActivity", "onResume()");
    LocalBroadcastManager.getInstance(MyActivity.this).registerReceiver(
            mMessageReceiver, new IntentFilter("currentUpdate"));
}
@Override
protected void onPause() {
    Log.d("MyActivity", "onPause()");
    LocalBroadcastManager.getInstance(MyActivity.this).unregisterReceiver(mMessageReceiver);
    super.onPause();
}

In the service I have a method defined:

private void sendNewBroadcast(Intent intent, int current){
    intent.putExtra("test", current);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    Log.d("MyService", "new Broadcast sent from service");
}

and I use it like this elsewhere in the service:

Intent intent = new Intent("currentUpdate");
sendNewBroadcast(intent, 5);

I've debugged and everything seems to be working except for the 'receiving' part. Am I missing something? The service is started in a different activity and is ongoing.

Upvotes: 1

Views: 69

Answers (1)

Mike M.
Mike M.

Reputation: 39191

Firstly, the action String on the broadcast Intent needs to match the action set on the IntentFilter you're registering the Receiver with. Originally, they were different, but it was possibly just a typo.

Secondly, LocalBroadcastManager does not work across processes. The Activity and the Service must be running in the same process to be able to use LocalBroadcastManager. If the Service needs to be in a separate process, you'll have to use some other mechanism; e.g., Intents, broadcasts sent and received on a Context, some event bus implementation that supports IPC, etc.

Upvotes: 2

Related Questions