From 63fe6fa3e6ae40282980d2724d8d0f319e8d5d22 Mon Sep 17 00:00:00 2001
From: Scott Main A status bar notification adds an icon to the system's status bar
-(with an optional ticker-text message) and an expanded message in the "Notifications" window.
-When the user selects the expanded message, Android fires an
-{@link android.content.Intent} that is defined by the notification (usually to launch an
-{@link android.app.Activity}).
+ 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 android.app.Notification} (usually to
+launch an {@link android.app.Activity}).
You can also configure the notification to alert the user with a sound, a vibration, and flashing
lights on the device. 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
-should never 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
+which a background service needs to alert the user about an event that requires a response. A
+background service
+should never 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. The screenshot below shows the status bar with a notification icon on the left side. Figure 1 shows the status bar with a notification icon on the left side. Figure 1. Status bar with a notification. Figure 2 shows the notification's message in the notifications window. The next screenshot shows the notification's expanded message in the "Notifications" window.
-The user can reveal the Notifications window by pulling down the status bar
-(or selecting Notifications from the Home options menu). Figure 2. The notifications window. An {@link android.app.Activity} or {@link android.app.Service} can initiate a status bar
-notification. Because an Activity can perform actions only while it is
-active and in focus, you should create your status bar notifications from a
-Service. This way, the notification can be created from the background,
+ An {@link android.app.Activity} or {@link android.app.Service} 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 android.app.Notification} and {@link android.app.NotificationManager}. Use an instance of the {@link android.app.Notification} class to define the properties of your
-status bar notification, such as the status bar icon, the expanded message, and extra settings such
-as a sound to play. The {@link android.app.NotificationManager} is an Android system service that
-executes and manages all Notifications. You do not instantiate the NotificationManager. In order
-to give it your Notification, you must retrieve a reference to the NotificationManager with
-{@link android.app.Activity#getSystemService(String) getSystemService()} and
-then, when you want to notify the user, pass it your Notification object with
+ Use an instance of the {@link android.app.Notification} 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 android.app.NotificationManager} is an Android system service
+that executes and manages all status bar notifications. You do not instantiate the
+{@link android.app.NotificationManager} directly. In order
+to give it your {@link android.app.Notification}, you must retrieve a reference to the
+{@link android.app.NotificationManager} with
+{@link android.app.Activity#getSystemService(String) getSystemService()} and
+then, when you want to notify the user, pass it your {@link android.app.Notification} with
{@link android.app.NotificationManager#notify(int,Notification) notify()}. To create a status bar notification: The {@link android.app.NotificationManager} is a system service that manages all
notifications. You must retrieve a reference to it with the
-{@link android.app.Activity#getSystemService(String) getSystemService()} method.
+{@link android.app.Activity#getSystemService(String) getSystemService()} method.
For example: When you want to send your status bar notification, pass the Notification object
-to the NotificationManager with {@link android.app.NotificationManager#notify(int,Notification)}.
-The first parameter is the unique ID for the Notification and the second is the Notification object.
-The ID uniquely identifies the Notification from within your
-application. This 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. When you want to deliver your status bar notification, pass the {@link android.app.Notification}
+to the {@link android.app.NotificationManager} with {@link
+android.app.NotificationManager#notify(int,Notification)}.
+The first parameter is the unique ID for the notification and the second is the {@link
+android.app.Notification} 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. To clear the status bar notification when the user selects it from the Notifications
-window, add the "FLAG_AUTO_CANCEL" flag to your Notification object. You can also clear it
-manually with {@link android.app.NotificationManager#cancel(int)}, passing it the notification ID,
-or clear all your Notifications with {@link android.app.NotificationManager#cancelAll()}. To clear the status bar notification when the user selects it from the notifications
+window, add the "FLAG_AUTO_CANCEL" flag to your {@link android.app.Notification}. You can
+also clear it manually with {@link android.app.NotificationManager#cancel(int)}, passing it the
+notification ID, or clear all your notifications with {@link
+android.app.NotificationManager#cancelAll()}. A {@link android.app.Notification} object defines the details of the notification
-message that is displayed in the status bar and "Notifications" window, and any other
+message that is displayed in the status bar and notifications window, and any other
alert settings, such as sounds and blinking lights. A status bar notification requires all of the following: Optional settings for the status bar notification include:In this document
- Key classes
@@ -36,57 +36,63 @@ user clicks it
-
+
+The Basics
-
-
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.notification_icon;
CharSequence tickerText = "Hello";
@@ -95,7 +101,7 @@ long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
@@ -106,7 +112,7 @@ PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationInt
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
private static final int HELLO_ID = 1;
@@ -121,38 +127,41 @@ mNotificationManager.notify(HELLO_ID, notification);
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
-Creating a Notification
The starter-kit for a new Notification includes the -{@link android.app.Notification#Notification(int,CharSequence,long)} constructor and the -{@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent)} -method. These define all the required settings for a Notification. -The following snippet demonstrates a basic Notification setup:
+The starter-kit for a new notification includes the +{@link android.app.Notification#Notification(int,CharSequence,long)} constructor and the +{@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent)} +method. These define all the required settings for a notification. +The following snippet demonstrates a basic notification setup:
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"; // expanded message title -CharSequence contentText = "Hello World!"; // expanded message text +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); @@ -187,32 +196,33 @@ notification.setLatestEventInfo(context, contentTitle, contentText, contentInten-Updating the notification
-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 +
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 -to the NotificationManager because it avoids clutter in the Notifications window.
+This practice of updating an existing notification is much better than adding new +notifications, because it avoids clutter in the notifications window.Because each notification is uniquely identified -by the NotificationManager with an integer ID, you can revise the notification by calling -{@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent) -setLatestEventInfo()} with new values, change some field values of the Notification, and then call +by the {@link android.app.NotificationManager} with an integer ID, you can revise the notification +by calling {@link +android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent) +setLatestEventInfo()} with new values, change some field values of the notification, and then call {@link android.app.NotificationManager#notify(int,Notification) notify()} again.
You can revise each property with the object member fields -(except for the Context and the expanded message title and text). You should always -revise the text message when you update the notification by calling +(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 {@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent) -setLatestEventInfo()} with new values for contentTitle and contentText. -Then call {@link android.app.NotificationManager#notify(int,Notification) notify()} to update the -notification. (Of course, if you've created a custom expanded -view, then updating these title and text values has no effect.)
+setLatestEventInfo()} with new values for contentTitle and contentText. +Then call {@link android.app.NotificationManager#notify(int,Notification) notify()} to update the +notification. (Of course, if you've created a custom notification +layout, then updating these title and text values has no effect.)Adding a sound
-You can alert the user with the default notification sound +
You can alert the user with the default notification sound (which is defined by the user) or with a sound specified by your application.
To use the user's default sound, add "DEFAULT_SOUND" to the defaults field:
@@ -227,31 +237,35 @@ The following example uses a known audio file saved to the device SD card: notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");
In the next example, the audio file is chosen from the internal +
In the next example, the audio file is chosen from the internal {@link android.provider.MediaStore.Audio.Media MediaStore}'s {@link android.content.ContentProvider}:
notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");-
In this case, the exact ID of the media file ("6") is known and appended to the content +
In this case, the exact ID of the media file ("6") is known and appended to the content {@link android.net.Uri}. If you don't know the exact ID, you must query all the -media available in the MediaStore with a {@link android.content.ContentResolver}. +media available in the {@link android.provider.MediaStore} with a {@link +android.content.ContentResolver}. See the Content Providers documentation for more information on using a ContentResolver.
If you want the sound to continuously repeat until the user responds to the notification -or the notification is cancelled, add "FLAG_INSISTENT" to the flags field.
+or the notification is cancelled, add {@link android.app.Notification#FLAG_INSISTENT} to the +flags field. -Note: If the defaults field includes -"DEFAULT_SOUND", then the default sound overrides any sound defined by the sound field.
+Note: If the defaults field includes +{@link android.app.Notification#DEFAULT_SOUND}, then the default sound overrides any sound defined +by the sound field.
You can alert the user with the the default +
You can alert the user with the the default vibration pattern or with a vibration pattern defined by your application.
-To use the default pattern, add "DEFAULT_VIBRATE" to the defaults field:
+To use the default pattern, add {@link android.app.Notification#DEFAULT_VIBRATE} to the +defaults field:
notification.defaults |= Notification.DEFAULT_VIBRATE;@@ -264,30 +278,32 @@ notification.vibrate = vibrate;
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. +(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.
-Note: If the defaults field includes -"DEFAULT_VIBRATE", then the default vibration overrides any vibration defined by the +
Note: If the defaults field includes +{@link android.app.Notification#DEFAULT_VIBRATE}, then the default vibration overrides any vibration +defined by the vibrate field.
To alert the user by flashing LED lights, you can implement the default +
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.
-To use the default light setting, add "DEFAULT_LIGHTS" to the defaults field:
+To use the default light setting, add {@link android.app.Notification#DEFAULT_LIGHTS} to the +defaults field:
notification.defaults |= Notification.DEFAULT_LIGHTS;
To define your own color and pattern, define a value for the ledARGB field -(for the color), the ledOffMS field (length of time, in milliseconds, to -keep the light off), the ledOnMS (length of time, in milliseconds, to keep the light on), -and also add "FLAG_SHOW_LIGHTS" to the flags field:
+(for the color), the ledOffMS field (length of time, in milliseconds, to +keep the light off), the ledOnMS (length of time, in milliseconds, to keep the light on), +and also add {@link android.app.Notification#FLAG_SHOW_LIGHTS} to the flags field:notification.ledARGB = 0xff00ff00; notification.ledOnMS = 300; @@ -295,114 +311,161 @@ notification.ledOffMS = 1000; notification.flags |= Notification.FLAG_SHOW_LIGHTS;-
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 +
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.
You can add several more features to your notifications -using Notification fields and flags. Some useful features include the following:
+using {@link android.app.Notification} fields and flags. Some useful features include the +following:See the {@link android.app.Notification} class reference for more information about additional +
See the {@link android.app.Notification} class reference for more information about additional features that you can customize for your application.
-
+
+Figure 3. Notification with a custom layout.
+By default, the expanded view used in the "Notifications" window includes a basic title and text -message. These are defined by the contentTitle and contentText +
By default, the notification that appears in the notifications window includes a title +and the message text. +These are defined by the contentTitle and contentText parameters of the {@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent) -setLatestEventInfo()} method. However, you can also define a custom layout for the expanded view using -{@link android.widget.RemoteViews}. The screenshot to the right shows an example of a -custom expanded view that uses an ImageView and TextView in a LinearLayout.
+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. -To define your own layout for the expanded message, -instantiate a {@link android.widget.RemoteViews} object and -pass it to the contentView field of your Notification. Pass the -{@link android.app.PendingIntent} to the contentIntent field.
+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 contentView field of your +Notification.
-Creating a custom expanded view is best understood with an example:
+Creating a custom notification layout is best understood with an example:
custom_notification_layout.xml and
- build it like so:
+ custom_notification.xml:
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="horizontal"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:padding="3dp"
- >
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/layout"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent"
+ android:padding="10dp" >
<ImageView android:id="@+id/image"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_marginRight="10dp"
- />
+ android:layout_width="wrap_content"
+ android:layout_height="fill_parent"
+ android:layout_alignParentLeft="true"
+ android:layout_marginRight="10dp" />
+ <TextView android:id="@+id/title"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_toRightOf="@id/image"
+ style="@style/NotificationTitle" />
<TextView android:id="@+id/text"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:textColor="#000"
- />
-</LinearLayout>
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_toRightOf="@id/image"
+ android:layout_below="@id/title"
+ style="@style/NotificationText" />
+</RelativeLayout>
- This layout is used for the expanded view, - but the content of the ImageView and TextView still needs to be defined by the application. - RemoteViews offers some convenient methods that allow you to define this content...
+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.
+ +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}:
++<?xml version="1.0" encoding="utf-8"?> +<resources> + <style name="NotificationText"> + <item name="android:textColor">?android:attr/textColorPrimary</item> + </style> + <style name="NotificationTitle"> + <item name="android:textColor">?android:attr/textColorPrimary</item> + <item name="android:textStyle">bold</item> + </style> + <!-- If you want a slightly different color for some text, + consider using ?android:attr/textColorSecondary --> +</resources> ++
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}:
++<?xml version="1.0" encoding="utf-8"?> +<resources> + <style name="NotificationText" parent="android:TextAppearance.StatusBar.EventContent" /> + <style name="NotificationTitle" parent="android:TextAppearance.StatusBar.EventContent.Title" /> +</resources> ++
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.
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout); contentView.setImageViewResource(R.id.image, R.drawable.notification_image); -contentView.setTextViewText(R.id.text, "Hello, this message is in a custom expanded view"); +contentView.setTextViewText(R.id.title, "Custom notification"); +contentView.setTextViewText(R.id.text, "This is a custom layout"); notification.contentView = contentView;-
As shown here, pass the application's package name and the layout +
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 + the value for that View. Finally, the RemoteViews object is passed to the Notification in the contentView field.
mNotificationManager.notify(CUSTOM_VIEW_ID, notification);
The 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 expanded view. For more information about creating custom layouts with -RemoteViews, refer to the {@link android.widget.RemoteViews} class reference.
+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.
-Note: -When creating a custom expanded view, you must take special care to ensure that your -custom layout functions properly in different device orientations and resolutions. While this +
Caution: +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 +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.
-- cgit v1.1