Passing and receiving data with ordered broadcasts
Listing 29.13 Sending an ordered broadcast (PollService.java)
public static final String PERM_PRIVATE =
"com.bignerdranch.android.photogallery.PRIVATE";
public static final String REQUEST_CODE = "REQUEST_CODE";
public static final String NOTIFICATION = "NOTIFICATION";
...
@Override
protected void onHandleIntent(Intent intent) {
...
String resultId = items.get(0).getId();
if (resultId.equals(lastResultId)) {
Log.i(TAG, "Got an old result: " + resultId);
} else {
Log.i(TAG, "Got a new result: " + resultId);
...
Notification notification = ...;
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(this);
notificationManager.notify(0, notification);
sendBroadcast(new Intent(ACTION_SHOW_NOTIFICATION), PERM_PRIVATE);
showBackgroundNotification(0, notification);
}
QueryPreferences.setLastResultId(this, resultId);
}
private void showBackgroundNotification(int requestCode, Notification notification) {
Intent i = new Intent(ACTION_SHOW_NOTIFICATION);
i.putExtra(REQUEST_CODE, requestCode);
i.putExtra(NOTIFICATION, notification);
sendOrderedBroadcast(i, PERM_PRIVATE, null, null,
Activity.RESULT_OK, null, null);
}
Context.sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String,
Bundle) has five additional parameters beyond the ones you used in sendBroadcast(Intent,
String). They are, in order: a result receiver, a Handler to run the result receiver on, and initial values
for the result code, result data, and result extras for the ordered broadcast.
The result receiver is a special receiver that runs after all the other recipients of your ordered broadcast
intent. In other circumstances, you would be able to use the result receiver to receive the broadcast and
post the notification object. Here, though, that will not work. This broadcast intent will often be sent
right before PollService dies. That means that your broadcast receiver might be dead, too.
Thus, your final broadcast receiver will need to be a standalone receiver, and you will need to enforce
that it runs after the dynamically registered receiver by different means.