Search This Blog

23 April 2010

Notifications

Building on our Alert example, we are going to take a look at the Notification Service.  We are basing this example on the developer documentation.

First, open your MyActivity.java.  In the top of the file, add a static id for our notification:
    private static final int HELLO_ID = 1;
In the onClick method of our alert, replace the:
return;
with:
                String ns = Context.NOTIFICATION_SERVICE;
                NotificationManager mgr = (NotificationManager) getSystemService(ns);
               
                int icon = R.drawable.icon;
                CharSequence tickerText = "You closed the alert";
                long when = System.currentTimeMillis();
                Notification notification = new Notification(icon, tickerText, when);

                Context context = getApplicationContext();
                CharSequence contentTitle = "Hello Notification";
                CharSequence contentText = "This notification is to let you know you closed the popup alert.";
                Intent notificationIntent = new Intent(context, MyActivity.class);
                PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
                notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

                mgr.notify(HELLO_ID, notification);

Redeploy (mvn clean install) your app.  When you click OK to close the alert, a notification will appear in the notification bar.

No comments:

Post a Comment