Android Notifications like Google Play Music

    Notifications like that of Google Play Music offers more details and real estate to work with. However, it is available only from version Jellybean (API 16 and above). The documentation recommends using NotificationCompat.Builder API for fallback behavior on older API levels. The API levels can be handled at runtime and this blog is about posting a custom layout as an expanded view just like Google Play Music.



      First, lets create a custom layout for our own style needs,


    Now that we have a layout, we just have to inflate it and associate it with the Notification API. In case of NotificationManager, inflation of custom layouts is handled by RemoteViews.

         NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                                                   .setContentTitle("Notification")
                                                   .setContentText("Test Notification")
                                                   .setSmallIcon(R.drawable.ic_launcher);

         RemoteViews remoteView = new RemoteViews(this.getPackageName(), R.layout.notification);
         // Associate the drawable with the ImageView managed by RemoteViews
         remoteView.setImageViewResource(R.id.imageSample, R.drawable.topgun);


        Notification notification = builder.build();
        notification.contentView = remoteView;
        notification.bigContentView = remoteView;

        NotificationManager manager;
        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        final int NOTIFICATION_ID = 12;
        manager.notify(NOTIFICATION_ID, notification);

  And there you go, a custom layout in an expanded notification,


The field bigContentView isn't defined in android.app.Notification in pre-API16 and thats why this code fails in pre-16 system images. This limitation forces a runtime check of the API level and to notify accordingly.

No comments: