Custom android notification

459

1. Common keywords:

Bundle: A mapping from String values to various Parcelable types.

2. Common problems:

Passing complicated data structure via Intent

3. Customize default behavior

Example 2:

Example 3:

Custom Notification Layouts


The notifications framework allows you to define a custom notification layout, which defines the notification’s appearance in a RemoteViews object. Custom layout notifications are similar to normal notifications, but they’re based on a RemoteViews defined in a XML layout file.

The height available for a custom notification layout depends on the notification view. Normal view layouts are limited to 64 dp, and expanded view layouts are limited to 256 dp.

To define a custom notification layout, start by instantiating a RemoteViews object that inflates an XML layout file. Then, instead of calling methods such as setContentTitle(), call setContent(). To set content details in the custom notification, use the methods in RemoteViews to set the values of the view’s children:

  1. Create an XML layout for the notification in a separate file. You can use any file name you wish, but you must use the extension .xml
  2. In your app, use RemoteViews methods to define your notification’s icons and text. Put this RemoteViewsobject into your NotificationCompat.Builder by calling setContent(). Avoid setting a backgroundDrawable on your RemoteViews object, because your text color may become unreadable.

The RemoteViews class also includes methods that you can use to easily add a Chronometer or ProgressBarto your notification’s layout. For more information about creating custom layouts for your notification, refer to the RemoteViews reference documentation.

Caution: When you use a custom notification layout, take special care to ensure that your custom layout works with different device orientations and resolutions. While this advice applies to all View layouts, it’s especially important for notifications because the space in the notification drawer is very restricted. Don’t make your custom layout too complex, and be sure to test it in various configurations.

Using style resources for custom notification text

Always use style resources for the text of a custom notification. The background color of the notification can vary across different devices and versions, and using style resources helps you account for this. Starting in Android 2.3, the system defined a style for the standard notification layout text. If you use the same style in applications that target Android 2.3 or higher, you’ll ensure that your text is visible against the display background.