欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android ApiDemos示例解析(26):App->Notification->IncomingMessage

程序员文章站 2022-03-16 21:03:43
...

应用程序可以使用Notifications来通知用户某个事件发生了(如收到短信)。类NotificationManager 用来处理Notification, NotificationManager可以:

  • 在Status Bar上显示一个新的图标。
  • 在Extended status bar 窗口上显示附加信息或是启动一个Activity。
  • 显示背光/LED。
  • 使设备震动。
  • 发出声音等。

对于一些没有UI的应用程序组件(如Broadcast Receiver, Services)或是非活动状态的Activity,Notification是推荐使用的可以提醒用户注意的方法。

Notification通常是在Status Bar上显示图标或是文字,此时用户如果想了解Notification的详细内容,可以按住Status Bar下拉显示Expanded Status bar 窗口,在Expanded Status bar窗口显示该Notification详情并可以启动对应的Activity。

IncomingMessage 示例介绍了Notification的一般用法:

1. 首先是取得NotificationManager 对象:

NotificationManager nm
= (NotificationManager)getSystemService(NOTIFICATION_SERVICE);


2. 然后创建Notification,创建Notification时指定显示在Status bar的图标,文字以及显示Notification的时间:

Notification notif = new Notification(R.drawable.stat_sample, tickerText,
System.currentTimeMillis());


3. 然后定义当用户打开Extented status windows窗口时的标题及详情。Notification常常代表了一个请求或者需要引起注意的事件,因此可以指定一个PendingIntent来响应用户点击这个Notification。

// The details of our fake message
CharSequence from = "Joe";
CharSequence message = "kthx. meet u for dinner. cul8r";
 
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, IncomingMessageView.class), 0);
// Set the info for the views that show in the notification panel.
notif.setLatestEventInfo(this, from, message, contentIntent);
// after a 100ms delay, vibrate for 250ms, pause for 100 ms and
// then vibrate for 500ms.
notif.vibrate = new long[] { 100, 250, 100, 500};


4. 最后是触发这个Notification

nm.notify(R.string.imcoming_message_ticker_text, notif);


一般来说对应同一个事件可以使用同一个Notification来通知用户,nm.notify的第一个参数为Notification 的ID,类型为整数。 可以使用同一个ID来表示同一个Notification,也可以使用这个ID来取消这个Notification,在IncomingMessage 中当用户点击显示了这个IncomingMessage详情后,会取消这个Notification(类IncomingMessageView中)。

nm.cancel(R.string.imcoming_message_ticker_text);


Android ApiDemos示例解析(26):App->Notification->IncomingMessage