blob: 7bc1cde3ff367e53946a4dc355f50347149edd6a [file] [log] [blame]
page.title=Status Bar Notifications
<div id="qv-wrapper">
<div id="qv">
<li>A status bar notification allows your application to notify the user of an event
without interupting their current activity</li>
<li>You can attach an intent to your notification that the system will initiate when the
user clicks it</li>
<h2>In this document</h2>
<li><a href="#Basics">The Basics</a></li>
<li><a href="#ManageYourNotifications">Managing your Notifications</a></li>
<li><a href="#CreateANotification">Creating a Notification</a>
<li><a href="#Updating">Updating the notification</a></li>
<li><a href="#Sound">Adding a sound</a></li>
<li><a href="#Vibration">Adding vibration</a></li>
<li><a href="#Lights">Adding flashing lights</a></li>
<li><a href="#More">More features</a></li>
<li><a href="#CustomExpandedView">Creating a Custom Notification Layout</a></li>
<h2>Key classes</h2>
<p>A status bar notification adds an icon to the system's status bar
(with an optional ticker-text message) and a notification message in the notifications window.
When the user selects the notification, Android fires an
{@link android.content.Intent} that is defined by the {@link} (usually to
launch an {@link}).
You can also configure the notification to alert the user with a sound, a vibration, and flashing
lights on the device.</p>
<p>A status bar notification should be used for any case in
which a background service needs to alert the user about an event that requires a response. A
background service
<strong>should never</strong> launch an activity on its own in order to receive user interaction.
The service should instead create a status bar notification that will launch the activity
when selected by the user.</p>
<p>Figure 1 shows the status bar with a notification icon on the left side.</p>
<img src="{@docRoot}images/status_bar.png" alt="" />
<p class="img-caption"><strong>Figure 1.</strong> Status bar with a notification.</p>
<p>Figure 2 shows the notification's message in the notifications window.</p>
<img src="{@docRoot}images/notifications_window.png" alt="" />
<p class="img-caption"><strong>Figure 2.</strong> The notifications window.</p>
<h2 id="Basics">The Basics</h2>
<p>An {@link} or {@link} can initiate a status bar
notification. Because an activity can perform actions only while it is
running in the foreground and its window has focus, you will usually create status bar notifications
from a
service. This way, the notification can be created from the background,
while the user is using another application or
while the device is asleep. To create a notification, you must use two
classes: {@link} and {@link}.</p>
<p>Use an instance of the {@link} class to define the properties of your
status bar notification, such as the status bar icon, the notification message, and extra settings
such as a sound to play. The {@link} is an Android system service
that executes and manages all status bar notifications. You do not instantiate the
{@link} directly. In order
to give it your {@link}, you must retrieve a reference to the
{@link} with
{@link getSystemService()} and
then, when you want to notify the user, pass it your {@link} with
{@link,Notification) notify()}. </p>
<p>To create a status bar notification:</p>
<li>Get a reference to the {@link}:
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
<!-- use Notification.Builder in 3.0 -->
<li>Instantiate the {@link}:
int icon = R.drawable.notification_icon;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
<li>Define the notification's message and {@link}:
Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
CharSequence contentText = "Hello World!";
Intent notificationIntent = new Intent(this, MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
<li>Pass the {@link} to the {@link}:
private static final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);
<p>That's it. Your user has now been notified.</p>
<h2 id="ManageYourNotifications">Managing your Notifications</h2>
<p>The {@link} is a system service that manages all
notifications. You must retrieve a reference to it with the
{@link getSystemService()} method.
For example:</p>
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
<p>When you want to deliver your status bar notification, pass the {@link}
to the {@link} with {@link,Notification)}.
The first parameter is the unique ID for the notification and the second is the {@link} object.
The ID uniquely identifies the notification from within your
application. The ID is necessary if you need to update the notification or (if
your application manages different kinds of notifications) select the appropriate action
when the user returns to your application via the intent defined in the notification.</p>
<p>To clear the status bar notification when the user selects it from the notifications
window, add the "FLAG_AUTO_CANCEL" flag to your {@link}. You can
also clear it manually with {@link}, passing it the
notification ID, or clear all your notifications with {@link}.</p>
<h2 id="CreateANotification">Creating a Notification</h2>
<p>A {@link} object defines the details of the notification
message that is displayed in the status bar and notifications window, and any other
alert settings, such as sounds and blinking lights.</p>
<p>A status bar notification <em>requires</em> all of the following:</p>
<li>An icon for the status bar</li>
<li>A title and message, unless you define a
<a href="#CustomExpandedView">custom notification layout</a></li>
<li>A {@link}, to be fired when the notification is selected</li>
<p>Optional settings for the status bar notification include:</p>
<li>A ticker-text message for the status bar</li>
<li>An alert sound</li>
<li>A vibrate setting</li>
<li>A flashing LED setting</li>
<p>The starter-kit for a new notification includes the
{@link,CharSequence,long)} constructor and the
method. These define all the required settings for a notification.
The following snippet demonstrates a basic notification setup:</p>
int icon = R.drawable.notification_icon; // icon from resources
CharSequence tickerText = "Hello"; // ticker-text
long when = System.currentTimeMillis(); // notification time
Context context = getApplicationContext(); // application Context
CharSequence contentTitle = "My notification"; // message title
CharSequence contentText = "Hello World!"; // message text
Intent notificationIntent = new Intent(this, MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
// the next two lines initialize the Notification, using the configurations above
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
<h3 id="Updating">Updating the notification</h3>
<p>You can update the information in your status bar notification as events
continue to occur in your application. For example, when a new SMS text message arrives
before previous messages have been read, the Messaging application updates the existing
notification to display the total number of new messages received.
This practice of updating an existing notification is much better than adding new
notifications, because it avoids clutter in the notifications window.</p>
<p>Because each notification is uniquely identified
by the {@link} with an integer ID, you can revise the notification
by calling {@link,CharSequence,CharSequence,PendingIntent)
setLatestEventInfo()} with new values, change some field values of the notification, and then call
{@link,Notification) notify()} again.</p>
<p>You can revise each property with the object member fields
(except for the {@link android.content.Context} and the notification title and text). You
should always revise the text message when you update the notification by calling
setLatestEventInfo()} with new values for <var>contentTitle</var> and <var>contentText</var>.
Then call {@link,Notification) notify()} to update the
notification. (Of course, if you've created a <a href="#CustomExpandedView">custom notification
layout</a>, then updating these title and text values has no effect.)</p>
<h3 id="Sound">Adding a sound</h3>
<p>You can alert the user with the default notification sound
(which is defined by the user) or with a sound specified by your application.</p>
<p>To use the user's default sound, add "DEFAULT_SOUND" to the <var>defaults</var> field:</p>
notification.defaults |= Notification.DEFAULT_SOUND;
<p>To use a different sound with your notifications, pass a Uri reference to the
<var>sound</var> field.
The following example uses a known audio file saved to the device SD card:</p>
notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");
<p>In the next example, the audio file is chosen from the internal
{@link android.provider.MediaStore.Audio.Media MediaStore}'s {@link android.content.ContentProvider}:</p>
notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");
<p>In this case, the exact ID of the media file ("6") is known and appended to the content
{@link}. If you don't know the exact ID, you must query all the
media available in the {@link android.provider.MediaStore} with a {@link
See the <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
documentation for more information on using a ContentResolver.</p>
<p>If you want the sound to continuously repeat until the user responds to the notification
or the notification is cancelled, add {@link} to the
<var>flags</var> field.</p>
<p class="note"><strong>Note:</strong> If the <var>defaults</var> field includes
{@link}, then the default sound overrides any sound defined
by the <var>sound</var> field.</p>
<h3 id="Vibration">Adding vibration</h3>
<p>You can alert the user with the the default
vibration pattern or with a vibration pattern defined by your application.</p>
<p>To use the default pattern, add {@link} to the
<var>defaults</var> field:</p>
notification.defaults |= Notification.DEFAULT_VIBRATE;
<p>To define your own vibration pattern, pass an array of <em>long</em> values to the
<var>vibrate</var> field:</p>
long[] vibrate = {0,100,200,300};
notification.vibrate = vibrate;
<p>The long array defines the alternating pattern for the length of vibration off and on
(in milliseconds). The first value is how long to wait (off) before beginning, the second
value is the length of the first vibration, the third is the next length off, and so on.
The pattern can be as long as you like, but it can't be set to repeat.
<p class="note"><strong>Note:</strong> If the <var>defaults</var> field includes
{@link}, then the default vibration overrides any vibration
defined by the
<var>vibrate</var> field.</p>
<h3 id="Lights">Adding flashing lights</h3>
<p>To alert the user by flashing LED lights, you can implement the default
light pattern (if available), or define your own color and pattern for the lights.</p>
<p>To use the default light setting, add {@link} to the
<var>defaults</var> field:</p>
notification.defaults |= Notification.DEFAULT_LIGHTS;
<p>To define your own color and pattern, define a value for the <var>ledARGB</var> field
(for the color), the <var>ledOffMS</var> field (length of time, in milliseconds, to
keep the light off), the <var>ledOnMS</var> (length of time, in milliseconds, to keep the light on),
and also add {@link} to the <var>flags</var> field:</p>
notification.ledARGB = 0xff00ff00;
notification.ledOnMS = 300;
notification.ledOffMS = 1000;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
<p>In this example, the green light repeatedly flashes on for 300 milliseconds and
turns off for one second. Not every color in the spectrum is supported by the
device LEDs, and not every device supports the same colors, so the hardware
estimates to the best of its ability. Green is the most common notification color.</p>
<h3 id="More">More features</h3>
<p>You can add several more features to your notifications
using {@link} fields and flags. Some useful features include the
<dt>{@link} flag</dt>
<dd>Add this to the <var>flags</var> field to automatically cancel the notification
after it is selected from the notifications window.</dd>
<dt>{@link} flag</dt>
<dd>Add this to the <var>flags</var> field to repeat the audio until the
user responds.</dd>
<dt>{@link} flag</dt>
<dd>Add this to the <var>flags</var> field to group the notification under the "Ongoing"
title in the notifications window. This indicates that the application is on-going &mdash;
its processes are still running in the background, even when the application is not
visible (such as with music or a phone call).</dd>
<dt>{@link} flag</dt>
<dd>Add this to the <var>flags</var> field to indicate that the notification should
<em>not</em> be cleared by the "Clear notifications" button. This is particularly useful if
your notification is on-going.</dd>
<dt>{@link} field</dt>
<dd>This value indicates the current number of events represented by the notification.
The appropriate number is overlaid on top of the status bar icon.
If you intend to use this field, then you must start with "1" when the Notification is first
created. (If you change the value from zero to anything greater during an update, the number
is not shown.)</dd>
<dt>{@link} field</dt>
<dd>This value indicates the current level of a
{@link} that is used for the notification icon.
You can animate the icon in the status bar by changing this value to correlate with the
drawable's defined in a LevelListDrawable. See the {@link}
reference for more information.</dd>
<p>See the {@link} class reference for more information about additional
features that you can customize for your application.</p>
<h2 id="CustomExpandedView">Creating a Custom Notification Layout</h2>
<div class="figure" style="width:200px;margin-top:0">
<img src="{@docRoot}images/custom_message.png" alt="" />
<p class="img-caption"><strong>Figure 3.</strong> Notification with a custom layout.</p>
<p>By default, the notification that appears in the notifications window includes a title
and the message text.
These are defined by the <var>contentTitle</var> and <var>contentText</var>
parameters of the {@link,CharSequence,CharSequence,PendingIntent)
setLatestEventInfo()} method. However, you can also define a custom layout for the
notification using
{@link android.widget.RemoteViews}. Figure 3 shows an example of a
custom notification layout. It looks similar to the default notification, but is
actually created with a custom XML layout.</p>
<p>To define your own layout for the notification,
instantiate a {@link android.widget.RemoteViews} object that inflates a custom layout file, then
pass the {@link android.widget.RemoteViews} to the <var>contentView</var> field of your
<p>Creating a custom notification layout is best understood with an example:</p>
<li>Create the XML layout for the notification.
For example, the following layout is called <code>custom_notification.xml</code>:
&lt;RelativeLayout xmlns:android=""
android:padding="10dp" >
&lt;ImageView android:id="@+id/image"
android:layout_marginRight="10dp" />
&lt;TextView android:id="@+id/title"
style="@style/NotificationTitle" />
&lt;TextView android:id="@+id/text"
style="@style/NotificationText" />
<p>Notice that the two {@link android.widget.TextView} elements include the {@code style}
attribute. It's important that you use style resources for the text in your custom
notifications, because the background color of the notification can vary across different
devices and platform versions. Beginning with Android 2.3 (API level 9), the system defines a
style for the text it uses for the default notification layouts. Thus, you should apply
that style when running on Android 2.3 or higher to ensure that your text is visible against
the background.</p>
<p>For example, to use the standard text colors on versions of Android lower than 2.3, you
should use the following styles for {@code res/values/styles.xml}:</p>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;style name="NotificationText">
&lt;item name="android:textColor">?android:attr/textColorPrimary&lt;/item>
&lt;style name="NotificationTitle">
&lt;item name="android:textColor">?android:attr/textColorPrimary&lt;/item>
&lt;item name="android:textStyle">bold&lt;/item>
&lt;!-- If you want a slightly different color for some text,
consider using ?android:attr/textColorSecondary -->
<p>Then, to apply the system's default colors for notifications on Android
2.3 and higher, use the following styles for {@code res/values-v9/styles.xml}:</p>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;style name="NotificationText" parent="android:TextAppearance.StatusBar.EventContent" />
&lt;style name="NotificationTitle" parent="android:TextAppearance.StatusBar.EventContent.Title" />
<p>Now, when running on Android 2.3 (API level 9) or higher, the text in your custom view will
use the same colors that the system does for default notifications. This is important because later
versions of Android actually change the background color of the notifications to be dark. Inheriting
the system's styles ensures that your text will be light in such cases, but also if the background
is some other unexpected color, your text will also change as appropriate.</p>
<li>Now, in the application code, use the RemoveViews
methods to define the image and text. Then pass the RemoteViews object to the <var>contentView</var>
field of the Notification, as shown in this example:
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
contentView.setImageViewResource(, R.drawable.notification_image);
contentView.setTextViewText(, "Custom notification");
contentView.setTextViewText(, "This is a custom layout");
notification.contentView = contentView;
<p>As shown here, pass the application's package name and the layout
resource ID to the RemoteViews constructor. Then, define the content for the ImageView and TextView,
using the {@link android.widget.RemoteViews#setImageViewResource(int, int) setImageViewResource()}
and {@link android.widget.RemoteViews#setTextViewText(int, CharSequence) setTextViewText()}.
In each case, pass the reference ID of the appropriate View object that you want to set, along with
the value for that View. Finally, the RemoteViews object is passed to the Notification in the
<var>contentView</var> field.</p>
<li>Because you don't need the
setLatestEventInfo()} method when using a custom view, you must define the Intent for the Notification
with the <var>contentIntent</var> field, as in this example:
Intent notificationIntent = new Intent(this, MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.contentIntent = contentIntent;
<li>The notification can now be sent as usual:
<pre>mNotificationManager.notify(CUSTOM_VIEW_ID, notification);</pre>
<p>The {@link android.widget.RemoteViews} class also includes methods that you can use to easily add
a {@link android.widget.Chronometer} or {@link android.widget.ProgressBar}
in your notification's layout. For more information about creating custom layouts for your
notification, refer to the {@link android.widget.RemoteViews} class reference.</p>
<p class="caution"><strong>Caution:</strong>
When creating a custom notification layout, you must take special care to ensure that your
custom layout functions properly in different device orientations and resolutions. While this
advice applies to all View layouts created on Android, it is especially important in this case
because your layout real estate is very restricted. So don't make your custom layout too
complex and be sure to test it in various configurations.</p>