使用BroadcastReceiver处理Notification

来源:互联网 发布:网络贷款哪个最容易 编辑:程序博客网 时间:2024/06/10 21:43
Using Notifications from a Receiver 
Broadcast receivers often need to communicate to the user about something that 
happened or a status. This is usually done by alerting the user th rough a notifi cation icon 
in the systemwide notification bar. We will s how you, in this section, how to create a 
notification from a broadcast r eceiver, send it, and view  it through the notification manager.


Monitoring Notifications Through the Notification Manager 

Android shows icons of notifications as alerts in the not ification area.  The notification 
area is located at the top of device in a strip that looks like Figure 19–2. The look and 
placement of the notificati on area may change based on whether  the device is a tablet 
or a phone and may at times also change based on Android release. 
 
Figure 19–2.  Android notification icon status bar 
The notification area shown in  Figure 19–2 is called the status bar. This status bar is the 
staple of phone form factor. It contains  system indicators such as battery strength, 
signal strength, and so on. 
In 3.0, for tablet form fact ors, Android introduced a new system bar  that sits at the 
bottom of the tablet, taking t he place of the status bar for tablets. This system bar also 
includes navigation icons such as home, back, and search.  
When the phone and tablet APIs merged in 4.0, the navigation bar was introduced for 
phone form factors. A navi gation bar takes the place of  the system bar for phones. 
However, for phones, the status bar is still in play and continues to show notifications 
and system indicators. The navigation bar for phones prim arily shows the navigation 
icons: home, back, and search. 
Of course, we devote a full chapter to action bars  (Chapter 10), which  are solely owned 
by the activities in your application. 
When we deliver a notification, the notification will appear  as an icon in the area shown 
Figure 19–2. The notification icon is illustrated in Figure 19–3.  
 
Figure 19–3. Status bar showing a notification icon 
Figure 19–3 shows both the  notification area and an activity, in addition to the 
notification icon. For an  activity, we just happened to be  sitting in an application that is 
issuing the broadcast. It can be any activity or even the home page. 
The notification icon is an indicator to the user that so mething needs to be observed. To 
see the full notification, you have to hold a finger on the icon and drag the title strip 
shown in Figure 19–2 down like a curtain. This will expand the not ification area, as 
shown in Figure 19–4.  
CHAPTER 19:  Broadcast Receivers and Long-Running Services  510 
 
Figure 19–4.  Expanded notification view 
In the expanded view of t he notification in Figure 19–4,  you get to see the details 
supplied to the notification. You  can also click a notification deta il to fire off the intent to 
bring up the full application to which the notif ication belongs. 
As you can also see from Figure 19–4, you can use this view to clear notifications.  
You can also reach the notification detail view shown in Figure 19–4 from the menu on the 
home page. Figure 19–5 shows the available menu on the home page of the emulator. 
Depending on the device and the Android release, this homepage menu may differ. 
 
Figure 19–5. The Notifications menu item from home menu 
CHAPTER 19:  Broadcast Receivers and Long-Running Services  511 
Clicking the Notifications i con in Figure 19–5 will bring up the notification screen in 
Figure 19–4.  
Let’s see now how to generate a notification icon like the one shown in Figures 19–3 and 
19–4.  
Sending a Notification 
Let’s get started. The process  of sending a notification has the following three steps: 
1.   Create a suitable notification. 
2.   Get access to the notification manager. 
3.   Send the notification to the notification manager. 
When you create a notification, you’ll need to ensure that it had the following basic 
parts:  
 An icon to display 
 Ticker text like “hello world” 
 The time when it is delivered 
Once you have a notification object constructed with these details, you get the 
notification manager by aski ng the context to give you a system service named 
Context.NOTIFICATION_SERVICE. Once you have the notification manager reference, call 
the notify method on the not ification manager reference to  send the notification. 
Listing 19–8 presents the  source code for a broadcast receiver that sends the 
notification shown in Figures 19–3 and 19–4. 
Listing 19–8. A Receiver That Sends a Notification 

public class NotificationReceiver extends BroadcastReceiver  {     private static final String tag = "Notification Receiver";      @Override     public void onReceive(Context context, Intent intent)      {         Utils.logThreadSignature(tag);         Log.d(tag, "intent=" + intent);         String message = intent.getStringExtra("message");         Log.d(tag, message);         this.sendNotification(context, message);     }     private void sendNotification(Context ctx, String message)     {         //Get the notification manager         String ns = Context.NOTIFICATION_SERVICE;         NotificationManager nm =              (NotificationManager)ctx.getSystemService(ns);                  //Create Notification Object         int icon = R.drawable.robot; CHAPTER 19:  Broadcast Receivers and Long-Running Services  512         CharSequence tickerText = "Hello";         long when = System.currentTimeMillis();                  Notification notification =              new Notification(icon, tickerText, when);          //Set ContentView using setLatestEvenInfo         Intent intent = new Intent(Intent.ACTION_VIEW);         intent.setData(Uri.parse("http://www.google.com"));         PendingIntent pi = PendingIntent.getActivity(ctx, 0, intent, 0);         notification.setLatestEventInfo(ctx, "title", "text", pi);                        //Send notification         //The first argument is a unique id for this notification.         //This id allows you to cancel the notification later         //This id also allows you to update your notification         //by creating a new notification and resending it against that id         //This id is unique with in this application         nm.notify(1, notification);     } } 

In the source code in Listing 19–8, we have referenced an alert icon called 
R.drawable.robot. You can create your own alert  icon and drop it into the res/drawable 
subdirectory and name it  robot  with a proper image extensi on. Or you can refer to the 
downloadable ZIP file for this project (a URL is included in the “References” section).  
When you create a notification with the basic parameters (icon, text, and time) and send 
it to the notification manager, it looks like it is not sufficient  (the first part of creating the 
notification in Listing 19–8). You will also have to set up something called a  content view  
for that notification using this (inexplicably named) method: 
setLatestEventInfo(...)  
The content view of a notificat ion is displayed when the notif ication is expanded. This is 
what you see in Figure 19–4. Typically, the content view needs to be a  RemoteViews  
object. However, we don’t pass  a content view directly to the setLatestEventInfo 
method. This setLatestEventInfo() method is a shortcut for setting the standard 
predefined content view using a title and the text to display.  
This method setLatestEventInfo()  also takes a pending intent, called a  content intent, 
that gets fired when this expand ed view is clicked. Look b ack at Listing 19–8 to see 
what parameters we have used to pass to this method.  
You also have an option to create a remote view  yourself and set it as the content view, 
without using s etLatestEventInfo() . 
The steps for using remote views for a cont ent view of a notification follow:  
1.   Create a layout file.  
2.   Create a RemoteViews  object using the package name and the layout file 
ID. 
3.   Call set methods on the RemoteViews  to set text, icons, and so on. 
CHAPTER 19:  Broadcast Receivers and Long-Running Services  513 
4.   Call setContentView() on the notification object  before sending it to the 
notification manager. 
Keep in mind that only the following limited set of controls  may participate in a remote 
view as of Androi d release 2.2:  
 FrameLayout  
 LinearLayout  
 RelativeLayout  
 AnalogClock  
 Button  
 Chronometer  
 ImageButton  
 ImageView  
 ProgressBar  
 TextView  
Refer to Chapter 25 (Home Sc reen Widgets) to learn mo re about constructing these 
remote views as widget views on the homepage are essentially remote views. In that 
chapter on home screen widgets you will al so see an updated list of possible 
RemoteViews in releases 2.3 and 3.0. 
The code in Listing 19–8 creat es a notification and uses  setLatestEventInfo() to set the 
implicit content view (through title  and text) and the intent to fire (in our case, this intent 
is the browser intent).  
This method  setLatestEventInfo() is named as such because this method lets you 
create or adjust a new notifi cation based on the status. Once the notificati on is created 
with the new information, it can be resent through the notification manager and the 
unique ID of the notification. The ID of the notification, which is set  to 1 in Listing 19–8, 
is unique within this application context. This uniqueness allows us to continuously 
update what is happening to that not ification and also  cancel it if needed. 
You may also want to look at the various  flags available while creating a notif ication, 
such as  FLAG_NO_CLEAR  andFLAG_ONGOING_EVENT to control the persistence of these 
notifications. The URL to check these flags is 
http://developer.android.com/reference/android/app/Notification.html

原创粉丝点击