上一次分享了Multi-Window的开发,今天继续介绍Android N Preview新特性-Notifications(通知)扩展功能,使用户快速响应通知而不需要进入你的App,可以设置通知组,相关通知折叠显示。
直接回复
背景
用户可以在通知界面里直接快速回复
开发
创建内联回复Notification
- 创建RemoteInput.Builder实例添加到notification action
private static final String KEY_TEXT_REPLY = "key_text_reply";
String replyLabel = getResources().getString(R.string.reply_label);
RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY)
.setLabel(replyLabel)
.build();
- 使用addRemoteInput()添加到RemoteInput
Notification.Action action =
new Notification.Action.Builder(R.drawable.ic_reply_icon,
getString(R.string.label), replyPendingIntent)
.addRemoteInput(remoteInput)
.build();
- 将该Action添加到Notification里,并且发出
Notification notification =
new Notification.Builder(mContext)
.setSmallIcon(R.drawable.ic_message)
.setContentTitle(getString(R.string.title))
.setContentText(getString(R.string.content))
.addAction(action))
.build();
NotificationManager notificationManager =
NotificationManager.from(mContext);
notificationManager.notify(notificationId, notification);
从内联回复中接受用户输入
- 调用getResultsFromIntent()从action intent获取用户输入参数
Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
if (remoteInput != null) {
return remoteInput.getCharSequence(KEY_TEXT_REPLY);
}
捆绑Notifications
背景
捆绑notifications和Android Wear里的Notification堆栈类似,如果你的app创建notifications来接受信息,当超过一个信息被接收到,捆绑这些notifications作为一个单独的组。
开发
- 为每一个你想捆绑在一起的notifications,调用setGroup()来设置指定的Group Key,然后调用notify()来发送到app。
final static String GROUP_KEY_EMAILS = "group_key_emails";
// Build the notification, setting the group appropriately
Notification notif = new NotificationCompat.Builder(mContext)
.setContentTitle("New mail from " + sender1)
.setContentText(subject1)
.setSmallIcon(R.drawable.new_mail)
.setGroup(GROUP_KEY_EMAILS)
.build();
// Issue the notification
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(this);
notificationManager.notify(notificationId1, notif);
- 当你创建另一个notification时,设置同一个Group Key。
Notification notif2 = new NotificationCompat.Builder(mContext)
.setContentTitle("New mail from " + sender2)
.setContentText(subject2)
.setSmallIcon(R.drawable.new_mail)
.setGroup(GROUP_KEY_EMAILS)
.build();
notificationManager.notify(notificationId2, notif2);
总结
Notifications新的特性开发还是很简单的,但确实可以很好地运用在之后的App中,Android N Preview开发就简单介绍到这里,期待Android之后新的特性。
参考
Notifications
Stacking Notifications
欢迎关注我的微博