直接回復.png
上一次分享了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
歡迎關注我的微博