Android: Notifications with Custom Layout

Posted by in Software

In the previous entries, I have managed to display a notification and make it sticky. Now, since the app I’m developing is supposed to be visible mainly through this notification, I wanted to see if I can customise the actual content. Yes, I know there are options by default, like:

  • Small and large notifications
  • Add some buttons to perform actions

However, I wanted to see if I can, for example, add some icons and buttons like Sonos notification does:

sonos-notification

It turns out that, with a bit of work and an OS Jelly Bean or better, anything is possible!

Preparation

Most for the NotificationBuilder code for custom notification is the same as the other ones:

Now, the builder is prepared to receive the custom layout. To make it compatible with devices pre-JellyBean, you need to do something like this:

The custom content is set (as seen above) with builder.setContent(RemoteViews views). Now all we have to do is to build the remote view.

For the purpose of this exercise, custom layout is designed to have an image, a larger and a smaller text underneath, just like the default notification:

custom-layout

The RemoteViews creation code is:

Once the view object is created, we can set the various components programmatically (e.g. content from an Intent):

Voila! the builder is now complete and we can show the notification as in the previous posts.

Code

Notification Layout

buildNotification Method

For the lazy:

getComplexNotificationView()

HTH,


A little experiment: If you find this post and ad below useful, please check the ad out :-)