Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Filtering Foreground Notifications


Filtering Foreground Notifications


With that sharp corner filed down a bit, let’s turn to another imperfection in PhotoGallery. Your
notifications work great, but they are sent even when the user already has the application open.


You can fix this problem with broadcast intents, too. But they will work in a completely different way.


First, you will send (and receive) your own custom broadcast intent (and ultimately will lock it down
so it can be received only by components in your application). Second, you will register a receiver
for your broadcast dynamically in code, rather than in the manifest. Finally, you will send an ordered
broadcast to pass data along a chain of receivers, ensuring a certain receiver is run last. (You do not
know how to do all this yet, but you will by the time you are done.)


Sending broadcast intents


The first part is straightforward: You need to send your own broadcast intent. Specifically, you will
send a broadcast notifying interested components that a new search results notification is ready to post.
To send a broadcast intent, create an intent and pass it into sendBroadcast(Intent). In this case, you
will want it to broadcast an action you define, so define an action constant as well.


Add these items in PollService.


Listing 29.6  Sending a broadcast intent (PollService.java)


public class PollService extends IntentService {
private static final String TAG = "PollService";


private static final long POLL_INTERVAL_MS = TimeUnit.MINUTES.toMillis(15);


public static final String ACTION_SHOW_NOTIFICATION =
"com.bignerdranch.android.photogallery.SHOW_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 {
...
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(this);
notificationManager.notify(0, notification);


sendBroadcast(new Intent(ACTION_SHOW_NOTIFICATION));
}


QueryPreferences.setLastResultId(this, resultId);
}
...
}


Now your app will send out a broadcast every time new search results are available.

Free download pdf