Thursday, March 20, 2014

Android Tip - Displaying Notifications

In Android, a good way to notify the user outside of your application is through posting a notification in the notification area of the device. The notification will appear until the user opens the notification drawer and taps on it. Usually, tapping the notification will launch the application that displays the notification.

To create a notification, use the NotificationCompat.Builder class to create a Notification object, as shown in the following method:

    private void postNotification(String title, String msg) {
        //---which activity should be launched when the
        // notification is tapped---        
        Intent resultIntent = new Intent(this,
            MainActivity.class);
        PendingIntent pendingIntent =
                PendingIntent.getActivity(
                this,
                0,
                resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT
            );       
       
        //---create a notification---
        Notification notification = new
            NotificationCompat.Builder(this)   
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(title)
            .setContentText(msg)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .setNumber(1)
            .build();
       
        //---set the sound and lights---
        notification.defaults |= Notification.DEFAULT_SOUND;
        notification.defaults |= Notification.DEFAULT_LIGHTS;
       
        //---display the notification---
        notificationManager.notify(
            NOTIFICATION_ID,
            notification);       
    }

Each notification is identified using a notification id. Posting another notification using the same id replaces the previous notifications. You also need to use the NotificationManager class to post the notification:

public class MainActivity extends Activity { 
    private static final int NOTIFICATION_ID = 123;
    NotificationManager notificationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        notificationManager = (NotificationManager)
            getSystemService(
                Context.NOTIFICATION_SERVICE);
    }

You can now post a notification by calling the method that you have just defined:

        postNotification(
            "A sample notification",
            "Just testing the notification...");  


No comments: