Wednesday, 30 May 2012

Generate Notification using Notification.Builder for Android 3.0

Android 3.0 (API Level 11) introduce Notification.Builder, allows easier control over all the flags, as well as help constructing the typical notification layouts.

It's a example of using Notification.Builder, modified from the previous exercise "schedule a repeating alarm".

Generate Notification using Notification.Builder for Android 3.0


Change the code of AlarmReceiver.java in "schedule a repeating alarm", to generate Notificaton.

package com.exercise.AndroidTime;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent arg1) {
Toast.makeText(context, "Alarm received!", Toast.LENGTH_LONG).show();
buildNotification(context);

}

private void buildNotification(Context context){
NotificationManager notificationManager
= (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(context);

Intent intent = new Intent(context, AndroidTimeActivity.class);
PendingIntent pendingIntent
= PendingIntent.getActivity(context, 0, intent, 0);

builder
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("ContentTitle")
.setContentText("ContentText")
.setContentInfo("ContentInfo")
.setTicker("Ticker")
.setLights(0xFFFF0000, 500, 500) //setLights (int argb, int onMs, int offMs)
.setContentIntent(pendingIntent)
.setAutoCancel(true);

Notification notification = builder.getNotification();

notificationManager.notify(R.drawable.ic_launcher, notification);
}

}


Please notice that you have to change your project to target API Level 11, in order to use Notification.Builder.

Download the files.


No comments:

Post a Comment