Saturday, February 11, 2012

How to show Status-Bar Notifications (with sound from the SD card, vibration and flashing lights)?


Creates a new status-bar notification, optionally with sound, vibration and flashing lights.
  • Sound can either be default of an mp3 from the sd card
  • Vibration can either be default or a custom sequence
  • Flashing lights can either be default or a custom combination
// 1. Get a reference to the NotificationManager
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

// 2. Instantiate the Notification
int icon = R.drawable.notification_icon;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);

// 3. Define the Notification's expanded message and Intent
Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
CharSequence contentText = "Hello World!";
Intent notificationIntent = new Intent(this, MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

// 4. Pass the Notification to the NotificationManager
private static final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);


// ----------------------
//        Add Sound
// ----------------------
// a. Default sound
notification.defaults |= Notification.DEFAULT_SOUND;

// b. Custom sound from SD card
notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");


// ----------------------
//     Add Vibration
// ----------------------
// a. Default vibration
notification.defaults |= Notification.DEFAULT_VIBRATE;

// b. Custom vibration
long[] vibrate = {0,100,200,300};
notification.vibrate = vibrate;


// ------------------------
//   Add Flashing Lights
// ------------------------
// a. Default lights
notification.defaults |= Notification.DEFAULT_LIGHTS;

// b. Custom lights
notification.ledARGB = 0xff00ff00;
notification.ledOnMS = 300;
notification.ledOffMS = 1000;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;

No comments:

Post a Comment