notifications.jd revision ec80d7f311b1a0899bb4caf5b380b07027e902d1
1page.title=Creating Status Bar Notifications
2parent.title=Notifying the User
3parent.link=index.html
4@jd:body
5
6<div id="qv-wrapper">
7  <div id="qv">
8    <h2>Quickview</h2>
9    <ul>
10      <li>A status bar notification allows your application to notify the user of an event
11without interupting their current activity</li>
12      <li>You can attach an intent to your notification that the system will initiate when the
13user clicks it</li>
14    </ul>
15    
16    <h2>In this document</h2>
17    <ol>
18      <li><a href="#Basics">The Basics</a></li>
19      <li><a href="#ManageYourNotifications">Managing your Notifications</a></li>
20      <li><a href="#CreateANotification">Creating a Notification</a>
21        <ol>
22          <li><a href="#Updating">Updating the notification</a></li>
23          <li><a href="#Sound">Adding a sound</a></li>
24          <li><a href="#Vibration">Adding vibration</a></li>
25          <li><a href="#Lights">Adding flashing lights</a></li>
26          <li><a href="#More">More features</a></li>
27        </ol>
28      </li>
29      <li><a href="#CustomExpandedView">Creating a Custom Expanded View</a></li>
30    </ol>
31    <h2>Key classes</h2>
32    <ol>
33      <li>{@link android.app.Notification}</li>
34      <li>{@link android.app.NotificationManager}</li>
35    </ol>
36  </div>
37</div>
38
39<p>A status bar notification adds an icon to the system's status bar 
40(with an optional ticker-text message) and an expanded message in the "Notifications" window.
41When the user selects the expanded message, Android fires an 
42{@link android.content.Intent} that is defined by the notification (usually to launch an 
43{@link android.app.Activity}).
44You can also configure the notification to alert the user with a sound, a vibration, and flashing
45lights on the device.</p>
46
47<p>A status bar notification should be used for any case in
48which a background Service needs to alert the user about an event that requires a response. A background Service 
49<strong>should never</strong> launch an Activity on its own in order to receive user interaction.
50The Service should instead create a status bar notification that will launch the Activity
51when selected by the user.</p>
52
53<p>The screenshot below shows the status bar with a notification icon on the left side.</p>
54<img src="{@docRoot}images/status_bar.png" alt="" />
55
56<p>The next screenshot shows the notification's expanded message in the "Notifications" window.
57The user can reveal the Notifications window by pulling down the status bar
58(or selecting <em>Notifications</em> from the Home options menu).</p>
59<img src="{@docRoot}images/notifications_window.png" alt="" />
60
61
62<h2 id="Basics">The Basics</h2>
63
64<p>An {@link android.app.Activity} or {@link android.app.Service} can initiate a status bar 
65notification. Because an Activity can perform actions only while it is
66active and in focus, you should create your status bar notifications from a 
67Service. This way, the notification can be created from the background, 
68while the user is using another application or
69while the device is asleep. To create a notification, you must use two
70classes: {@link android.app.Notification} and {@link android.app.NotificationManager}.</p>
71
72<p>Use an instance of the {@link android.app.Notification} class to define the properties of your 
73status bar notification, such as the status bar icon, the expanded message, and extra settings such 
74as a sound to play. The {@link android.app.NotificationManager} is an Android system service that 
75executes and manages all Notifications. You do not instantiate the NotificationManager. In order
76to give it your Notification, you must retrieve a reference to the NotificationManager with
77{@link android.app.Activity#getSystemService(String) getSystemService()} and 
78then, when you want to notify the user, pass it your Notification object with 
79{@link android.app.NotificationManager#notify(int,Notification) notify()}. </p>
80
81<p>To create a status bar notification:</p>
82<ol>
83  <li>Get a reference to the NotificationManager:
84<pre>
85String ns = Context.NOTIFICATION_SERVICE;
86NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
87</pre>
88  </li>
89  <li>Instantiate the Notification:
90<pre>
91int icon = R.drawable.notification_icon;
92CharSequence tickerText = "Hello";
93long when = System.currentTimeMillis();
94
95Notification notification = new Notification(icon, tickerText, when);
96</pre>
97  </li>
98  <li>Define the Notification's expanded message and Intent:
99<pre>
100Context context = getApplicationContext();
101CharSequence contentTitle = "My notification";
102CharSequence contentText = "Hello World!";
103Intent notificationIntent = new Intent(this, MyClass.class);
104PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
105
106notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
107</pre>
108  </li>
109  <li>Pass the Notification to the NotificationManager:
110<pre>
111private static final int HELLO_ID = 1;
112
113mNotificationManager.notify(HELLO_ID, notification);
114</pre>
115  <p>That's it. Your user has now been notified.</p>
116  </li>
117</ol>
118
119
120<h2 id="ManageYourNotifications">Managing your Notifications</h2>
121
122<p>The {@link android.app.NotificationManager} is a system service that manages all
123notifications. You must retrieve a reference to it with the
124{@link android.app.Activity#getSystemService(String) getSystemService()} method. 
125For example:</p>
126<pre>
127String ns = Context.NOTIFICATION_SERVICE;
128NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
129</pre>
130
131<p>When you want to send your status bar notification, pass the Notification object
132to the NotificationManager with {@link android.app.NotificationManager#notify(int,Notification)}. 
133The first parameter is the unique ID for the Notification and the second is the Notification object.
134The ID uniquely identifies the Notification from within your
135application. This is necessary if you need to update the Notification or (if
136your application manages different kinds of Notifications) select the appropriate action
137when the user returns to your application via the Intent defined in the Notification.</p>
138
139<p>To clear the status bar notification when the user selects it from the Notifications
140window, add the "FLAG_AUTO_CANCEL" flag to your Notification object. You can also clear it
141manually with {@link android.app.NotificationManager#cancel(int)}, passing it the notification ID,
142or clear all your Notifications with {@link android.app.NotificationManager#cancelAll()}.</p>
143
144
145<h2 id="CreateANotification">Creating a Notification</h2>
146
147<p>A {@link android.app.Notification} object defines the details of the notification
148message that is displayed in the status bar and "Notifications" window, and any other
149alert settings, such as sounds and blinking lights.</p>
150
151<p>A status bar notification <em>requires</em> all of the following:</p>
152<ul>
153  <li>An icon for the status bar</li>
154  <li>A title and expanded message for the expanded view (unless you define a 
155    <a href="#CustomExpandedView">custom expanded view</a>)</li>
156  <li>A {@link android.app.PendingIntent}, to be fired when the notification is selected</li>
157</ul>
158<p>Optional settings for the status bar notification include:</p>
159<ul>
160  <li>A ticker-text message for the status bar</li>
161  <li>An alert sound</li>
162  <li>A vibrate setting</li>
163  <li>A flashing LED setting</li>
164</ul>
165
166<p>The starter-kit for a new Notification includes the 
167{@link android.app.Notification#Notification(int,CharSequence,long)} constructor and the 
168{@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent)} 
169method. These define all the required settings for a Notification. 
170The following snippet demonstrates a basic Notification setup:</p>
171<pre>
172int icon = R.drawable.notification_icon;        // icon from resources
173CharSequence tickerText = "Hello";              // ticker-text
174long when = System.currentTimeMillis();         // notification time
175Context context = getApplicationContext();      // application Context
176CharSequence contentTitle = "My notification";  // expanded message title
177CharSequence contentText = "Hello World!";      // expanded message text
178
179Intent notificationIntent = new Intent(this, MyClass.class);
180PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
181
182// the next two lines initialize the Notification, using the configurations above
183Notification notification = new Notification(icon, tickerText, when);
184notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
185</pre>
186
187
188<h3 id="Updating">Updating the notification</h3>
189
190<p>You can update the information in your status bar notification as events 
191continue to occur in your application. For example, when a new SMS text message arrives 
192before previous messages have been read, the Messaging application updates the existing 
193notification to display the total number of new messages received.
194This practice of updating an existing Notification is much better than adding new Notifications 
195to the NotificationManager because it avoids clutter in the Notifications window.</p>
196
197<p>Because each notification is uniquely identified
198by the NotificationManager with an integer ID, you can revise the notification by calling
199{@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent)
200setLatestEventInfo()} with new values, change some field values of the Notification, and then call
201{@link android.app.NotificationManager#notify(int,Notification) notify()} again.</p>
202
203<p>You can revise each property with the object member fields
204(except for the Context and the expanded message title and text). You should always 
205revise the text message when you update the notification by calling
206{@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent)
207setLatestEventInfo()} with new values for <var>contentTitle</var> and <var>contentText</var>. 
208Then call {@link android.app.NotificationManager#notify(int,Notification) notify()} to update the 
209notification. (Of course, if you've created a <a href="#CustomExpandedView">custom expanded 
210view</a>, then updating these title and text values has no effect.)</p>
211
212
213<h3 id="Sound">Adding a sound</h3>
214
215<p>You can alert the user with the default notification sound 
216(which is defined by the user) or with a sound specified by your application.</p>
217
218<p>To use the user's default sound, add "DEFAULT_SOUND" to the <var>defaults</var> field:</p>
219<pre>
220notification.defaults |= Notification.DEFAULT_SOUND;
221</pre>
222
223<p>To use a different sound with your notifications, pass a Uri reference to the
224<var>sound</var> field.
225The following example uses a known audio file saved to the device SD card:</p>
226<pre>
227notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");
228</pre>
229
230<p>In the next example, the audio file is chosen from the internal 
231{@link android.provider.MediaStore.Audio.Media MediaStore}'s {@link android.content.ContentProvider}:</p>
232<pre>
233notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");
234</pre>
235
236<p>In this case, the exact ID of the media file ("6") is known and appended to the content 
237{@link android.net.Uri}. If you don't know the exact ID, you must query all the
238media available in the MediaStore with a {@link android.content.ContentResolver}. 
239See the <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
240documentation for more information on using a ContentResolver.</p>
241
242<p>If you want the sound to continuously repeat until the user responds to the notification
243or the notification is cancelled, add "FLAG_INSISTENT" to the <var>flags</var> field.</p>
244
245<p class="note"><strong>Note:</strong> If the <var>defaults</var> field includes 
246"DEFAULT_SOUND", then the default sound overrides any sound defined by the <var>sound</var> field.</p>
247
248
249<h3 id="Vibration">Adding vibration</h3>
250
251<p>You can alert the user with the the default 
252vibration pattern or with a vibration pattern defined by your application.</p>
253
254<p>To use the default pattern, add "DEFAULT_VIBRATE" to the <var>defaults</var> field:</p>
255<pre>
256notification.defaults |= Notification.DEFAULT_VIBRATE;
257</pre>
258
259<p>To define your own vibration pattern, pass an array of <em>long</em> values to the
260<var>vibrate</var> field:</p>
261<pre>
262long[] vibrate = {0,100,200,300};
263notification.vibrate = vibrate;
264</pre>
265
266<p>The long array defines the alternating pattern for the length of vibration off and on
267(in milliseconds). The first value is how long to wait (off) before beginning, the second 
268value is the length of the first vibration, the third is the next length off, and so on. 
269The pattern can be as long as you like, but it can't be set to repeat.
270</p>
271
272<p class="note"><strong>Note:</strong> If the <var>defaults</var> field includes 
273"DEFAULT_VIBRATE", then the default vibration overrides any vibration defined by the 
274<var>vibrate</var> field.</p>
275
276
277<h3 id="Lights">Adding flashing lights</h3>
278
279<p>To alert the user by flashing LED lights, you can implement the default 
280light pattern (if available), or define your own color and pattern for the lights.</p>
281
282<p>To use the default light setting, add "DEFAULT_LIGHTS" to the <var>defaults</var> field:</p>
283<pre>
284notification.defaults |= Notification.DEFAULT_LIGHTS;
285</pre>
286
287<p>To define your own color and pattern, define a value for the <var>ledARGB</var> field
288(for the color), the <var>ledOffMS</var> field (length of time, in milliseconds, to 
289keep the light off), the <var>ledOnMS</var> (length of time, in milliseconds, to keep the light on), 
290and also add "FLAG_SHOW_LIGHTS" to the <var>flags</var> field:</p>
291<pre>
292notification.ledARGB = 0xff00ff00;
293notification.ledOnMS = 300;
294notification.ledOffMS = 1000;
295notification.flags |= Notification.FLAG_SHOW_LIGHTS;
296</pre>
297
298<p>In this example, the green light repeatedly flashes on for 300 milliseconds and 
299turns off for one second. Not every color in the spectrum is supported by the 
300device LEDs, and not every device supports the same colors, so the hardware 
301estimates to the best of its ability. Green is the most common notification color.</p>
302
303
304<h3 id="More">More features</h3>
305
306<p>You can add several more features to your notifications
307using Notification fields and flags. Some useful features include the following:</p>
308
309<dl>
310  <dt>"FLAG_AUTO_CANCEL" flag</dt>
311  <dd>Add this to the <var>flags</var> field to automatically cancel the notification
312  after it is selected from the Notifications window.</dd>
313  <dt>"FLAG_INSISTENT" flag</dt>
314  <dd>Add this to the <var>flags</var> field to repeat the audio until the
315  user responds.</dd>
316  <dt>"FLAG_ONGOING_EVENT" flag</dt>
317  <dd>Add this to the <var>flags</var> field to group the notification under the "Ongoing"
318  title in the Notifications window. This indicates that the application is on-going &mdash;
319  its processes is still running in the background, even when the application is not 
320  visible (such as with music or a phone call).</dd>
321  <dt>"FLAG_NO_CLEAR" flag</dt>
322  <dd>Add this to the <var>flags</var> field to indicate that the notification should 
323  <em>not</em> be cleared by the "Clear notifications" button. This is particularly useful if 
324  your notification is on-going.</dd>
325  <dt><var>number</var> field</dt>
326  <dd>This value indicates the current number of events represented by the notification.
327  The appropriate number is overlaid on top of the status bar icon.
328  If you intend to use this field, then you must start with "1" when the Notification is first
329  created. (If you change the value from zero to anything greater during an update, the number
330  is not shown.)</dd>
331  <dt><var>iconLevel</var> field</dt>
332  <dd>This value indicates the current level of a 
333  {@link android.graphics.drawable.LevelListDrawable} that is used for the notification icon.
334  You can animate the icon in the status bar by changing this value to correlate with the 
335  drawable's defined in a LevelListDrawable. See the {@link android.graphics.drawable.LevelListDrawable}
336  reference for more information.</dd>
337</dl>
338
339<p>See the {@link android.app.Notification} class reference for more information about additional 
340features that you can customize for your application.</p>
341
342
343<h2 id="CustomExpandedView">Creating a Custom Expanded View</h2>
344
345<img src="{@docRoot}images/custom_message.png" alt="" style="float:right;" />
346
347<p>By default, the expanded view used in the "Notifications" window includes a basic title and text 
348message. These are defined by the <var>contentTitle</var> and <var>contentText</var>
349parameters of the {@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent)
350setLatestEventInfo()} method. However, you can also define a custom layout for the expanded view using 
351{@link android.widget.RemoteViews}. The screenshot to the right shows an example of a
352custom expanded view that uses an ImageView and TextView in a LinearLayout.</p>
353
354<p>To define your own layout for the expanded message,
355instantiate a {@link android.widget.RemoteViews} object and
356pass it to the <var>contentView</var> field of your Notification. Pass the
357{@link android.app.PendingIntent} to the <var>contentIntent</var> field.</p>
358
359<p>Creating a custom expanded view is best understood with an example:</p>
360
361<ol>
362  <li>Create the XML layout for the expanded view.
363    For example, create a layout file called <code>custom_notification_layout.xml</code> and 
364    build it like so:
365<pre>
366&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
367              android:orientation="horizontal"
368              android:layout_width="fill_parent"
369              android:layout_height="fill_parent"
370              android:padding="3dp"
371              >
372    &lt;ImageView android:id="@+id/image"
373              android:layout_width="wrap_content"
374              android:layout_height="fill_parent"
375              android:layout_marginRight="10dp"
376              />
377    &lt;TextView android:id="@+id/text"
378              android:layout_width="wrap_content"
379              android:layout_height="fill_parent"
380              android:textColor="#000"
381              />
382&lt;/LinearLayout>
383</pre>
384
385    <p>This layout is used for the expanded view,
386    but the content of the ImageView and TextView still needs to be defined by the application.
387    RemoteViews offers some convenient methods that allow you to define this content...</p>
388  </li>
389
390  <li>In the application code, use the RemoveViews 
391    methods to define the image and text. Then pass the RemoteViews object to the <var>contentView</var>
392    field of the Notification, as shown in this example:
393<pre>
394RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
395contentView.setImageViewResource(R.id.image, R.drawable.notification_image);
396contentView.setTextViewText(R.id.text, "Hello, this message is in a custom expanded view");
397notification.contentView = contentView;
398</pre>
399
400    <p>As shown here, pass the application's package name and the layout 
401    resource ID to the RemoteViews constructor. Then, define the content for the ImageView and TextView,
402    using the {@link android.widget.RemoteViews#setImageViewResource(int, int) setImageViewResource()}
403    and {@link android.widget.RemoteViews#setTextViewText(int, CharSequence) setTextViewText()}.
404    In each case, pass the reference ID of the appropriate View object that you want to set, along with
405    the value for that View. Finally, the RemoteViews object is passed to the Notification in the 
406    <var>contentView</var> field.</p>
407  </li>
408
409  <li>Because you don't need the
410    {@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent)
411    setLatestEventInfo()} method when using a custom view, you must define the Intent for the Notification
412    with the <var>contentIntent</var> field, as in this example:
413<pre>
414Intent notificationIntent = new Intent(this, MyClass.class);
415PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
416notification.contentIntent = contentIntent;
417</pre>
418  </li>
419  
420  <li>The notification can now be sent as usual:
421    <pre>mNotificationManager.notify(CUSTOM_VIEW_ID, notification);</pre>
422  </li>
423</ol>
424
425
426<p>The RemoteViews class also includes methods that you can use to easily add a 
427{@link android.widget.Chronometer} or {@link android.widget.ProgressBar} 
428in your notification's expanded view. For more information about creating custom layouts with 
429RemoteViews, refer to the {@link android.widget.RemoteViews} class reference.</p>
430
431<p class="warning"><strong>Note:</strong>
432When creating a custom expanded view, you must take special care to ensure that your 
433custom layout functions properly in different device orientations and resolutions. While this 
434advice applies to all View layouts created on Android, it is especially important in this case
435because your layout real estate is very restricted. So don't make your custom layout too 
436complex and be sure to test it in various configurations.</p>
437
438
439
440
441