The main benefit of declaring a BroadcastReveiver
is that you can issue the action wherever you want and declare the receiver also whenever you want, so it makes it suitable for complex workflows.
You simply declare the receiver where you want to receive the information:
class ActivityBroadcast extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
if (intent.getAction().equals(CustomActions.RECEIVEMYDATA)) {
final String mydata = intent.getStringExtra("mydata");
if ((mydata != null) && (!mydata.isEmpty())) {
// Do your staff
...
}
}
}
}
As you may see, you'll be using Intent
s, so the data you want to send has to be serializable or parcelable.
Another thing is that you have to register your receiver for some actions
, it means that your receiver will only listen for this actions and this way you know that's the data you want to process. Despite Android already has some built-in actions, I strongly recommend defining your own. You may do that simply declaring a public class with public own actions. In my case you'll see I'm using CustomActions.RECEIVEMYDATA
, which is just a personalized and unique String
.
You now just have to declare your service, register it for your actions and register it. An unregistered receiver won't listen for anything.
final ActivityBroadcast broadcast_signal = new ActivityBroadcast();
final IntentFilter iFilter= new IntentFilter();
iFilter.addAction(CustomActions.RECEIVEMYDATA);
LocalBroadcastManager.getInstance(this).registerReceiver(broadcast_signal, iFilter);
You may see that this is registered as a local broadcast receiver. That means that you'll register actions just within your application. There's another kind of broadcast receiver and it might be used to communicate app-wide, in this case you'd use a global broadcast receiver.
There's just two things left:
The first is to send the signal to that receiver, so whenever and wherever you want, use something like this:
final Intent intentResult = new Intent(CustomActions.RECEIVEMYDATA); intentResult.putExtra("mydata", "data to send"); LocalBroadcastManager.getInstance(this).sendBroadcast(intentResult);
Don't forget to unregister your broadcast receiver when it's no longer needed. For both this and registering, you should have in mind the lifecycle of the
Activity
where you're handling it and unregister/register when needed.LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcast_signal);