According to Google documentation, if your Activity
and Service
are within the same app, using a LocalBroadcastManager is preferable over sendBroadcast (intent) because the information sent does not go through the system which eliminates the risk of interception.
It's quite easy to use.
In your activity, create a BroadcastReceiver
and dynamically add a listener in the onResume() method :
private BroadcastReceiver bReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
//put here whaterver you want your activity to do with the intent received
}
};
protected void onResume(){
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(bReceiver, new IntentFilter("message"));
}
protected void onPause (){
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(bReceiver);
}
And in your service, you get an instance of LocalBroadcastManager and use it to send an intent. I usually put it in its own method like this :
private void sendBroadcast (boolean success){
Intent intent = new Intent ("message"); //put the same message as in the filter you used in the activity when registering the receiver
intent.putExtra("success", success);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}