Local broadcast from Service not received by Activity

做~自己de王妃 提交于 2019-12-12 09:36:22

问题


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.


回答1:


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);


来源:https://stackoverflow.com/questions/39158578/local-broadcast-from-service-not-received-by-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!