Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local broadcast from Service not received by Activity

I have an Activity in which I am registering a BroadcastReceiver locally as follows:

public class SomeActivity extends Activity{

    public static final String PERFORM_SOME_ACTION = "PERFORM_SOME_ACTION";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.some_activity_layout);

        .....
        .....

        IntentFilter filter = new IntentFilter();
        filter.addAction(PERFORM_SOME_ACTION);

        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // perform some action ...
            }
        };

        registerReceiver(receiver, filter);
    }

    .....
    .....
}

And I have a Service from which I broadcast an Intent as follows:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {        

    Intent i = new Intent(SomeActivity.PERFORM_SOME_ACTION);
    sendBroadcast(i);   /* Send global broadcast. */

    return START_STICKY;
}

This works as intended. After having implemented this, I realized that a local broadcast would be more appropriate for this situation:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {        

    Intent i = new Intent(SomeActivity.PERFORM_SOME_ACTION);
    LocalBroadcastManager.getInstance(this).sendBroadcast(i);   /* Send local broadcast. */

    return START_STICKY;
}

Unfortunately, the above scheme doesn't work. A global broadcast is sent every time, while a local broadcast is apparently never sent/received.

What am I missing here? Can't local broadcasts be sent between two distinct app components, like two separate Activitys or from a Service to an Activity? What am I doing wrong??

Note:

As per the documentation, it is more efficient and more to the point to send a local broadcast (an intra-app broadcast whose scope is restricted to the app's own components) rather than a global broadcast (an inter-app broadcast which is transmitted to every single app on the phone) whenever we do not need the broadcast to propagate outside the application. This is the reason for making the aforementioned change.

like image 853
Y.S Avatar asked Aug 26 '16 05:08

Y.S


1 Answers

What am I missing here?

Use LocalBroadcastManager for registering LocalBroadcast, currently using registerReceiver method of Activity which is used for registering global Broadcast:

LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter);
like image 76
ρяσѕρєя K Avatar answered Oct 17 '22 21:10

ρяσѕρєя K