1. NotificationManager
是一个管理系统所有notification的服务.你必须通过getSystemService() 方法获取它的引用 . 比如:
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
当你要发送notification到你的工具栏时,传递Notification对象到NotificationManager 使用函数 notify(int, Notification)
. 第一个参数为标识Notification的唯一ID,第二个参数为 Notification 对象.
当用户从Notification窗口选择后清除状态栏Notification, 添加 "FLAG_AUTO_CANCEL" 标记到你的 Notification 对象. 你也可以使用函数cancel(int)手动清除,传递给它notification ID, 或者用cancelAll()清除全部Notifications .
2.创建Notification
A Notification
对象定义了notification显示在状态栏和"Notifications"窗口 消息的细节, 以及其他一些报警设置,如声音和闪烁的灯.
状态栏Notification必须包含以下几项:
- 状态栏icon
- 为扩展窗口的标题和扩展消息(除非你定义一个普通扩展view)
- 一个
PendingIntent
, 当被选中时启用
int icon = R.drawable.notification_icon; // icon from resources
CharSequence tickerText = "Hello"; // ticker-text
long when = System.currentTimeMillis(); // notification time
Context context = getApplicationContext(); // application Context
CharSequence contentTitle = "My notification"; // expanded message title
CharSequence contentText = "Hello World!"; // expanded message text
Intent notificationIntent = new Intent(this, MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
// the next two lines initialize the Notification, using the configurations above
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
3.传递 Notification 到 the NotificationManager:
private static final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);