Chapter 29 Broadcast Intents
First, create a new BroadcastReceiver subclass called NotificationReceiver. Implement it as
follows:
Listing 29.14 Implementing your result receiver
(NotificationReceiver.java)
public class NotificationReceiver extends BroadcastReceiver {
private static final String TAG = "NotificationReceiver";
@Override
public void onReceive(Context c, Intent i) {
Log.i(TAG, "received result: " + getResultCode());
if (getResultCode() != Activity.RESULT_OK) {
// A foreground activity cancelled the broadcast
return;
}
int requestCode = i.getIntExtra(PollService.REQUEST_CODE, 0);
Notification notification = (Notification)
i.getParcelableExtra(PollService.NOTIFICATION);
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(c);
notificationManager.notify(requestCode, notification);
}
}
Next, register your new receiver and assign it a priority. To ensure that NotificationReceiver
receives the broadcast after your dynamically registered receiver (so it can check to see whether
it should post the notification to NotificationManager), you need to set a low priority for
NotificationReceiver. Give it a priority of -999 so that it runs last. This is the lowest user-defined
priority possible (-1000 and below are reserved).
Also, since this receiver is only used by your application, you do not need it to be externally visible.
Set android:exported="false" to keep this receiver to yourself.
Listing 29.15 Registering the notification receiver (AndroidManifest.xml)
Run PhotoGallery and toggle background polling a couple of times. You should see that notifications
no longer appear when you have the app in the foreground. (If you have not already done so, change
PollService.POLL_INTERVAL_MS to 60 seconds so that you do not have to wait 15 minutes to verify
that notifications still work in the background.)