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 Activity
s 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.
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