最近的版本中,Android系統的通知管理方面一直優化升級,Android O提供了更細粒度的Channel功能,通知欄推送時需要指定NotificationChannel,用戶可以對通知的Channel選擇,只允許感興趣的Channel推送的通知顯示。通過通道設置、免打擾優化等方式,極大增強了消息體驗。
Android P繼續改進和增強消息通知[v1] 。早在Android 7.0時,就提供了在通知中直接應答和輸入,Android P對這一功能做了更多的增強。
Android P的通知中支持圖像內容,可以通過setData()方法,給出消息的圖像內容,在通知上展示給用戶。
Android P同樣簡化了通知的配置形式。Android P中增加了Notification.Person類,用於區分同一個對話的參與者信息,如參與者的頭像、URI等。根據官方說明,Android P中,通知消息的其他一些API,也使用Person替代之前的CharSequence。
簡單的體驗下新的API的開發:
NotificationChannel channel = new NotificationChannel("WtTestChannel","WtTestChannel", NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true); // luncher icon right corner's point
channel.setLightColor(Color.RED); // read point
channel.setShowBadge(true); // whether show this channel notification on long press icon
Notification.Builder builder =
new Notification.Builder(MainActivity.this,
"WtTestChannel");
Notification.Person p = new Notification.Person();
p.setName("WeTest");
p.setUri("http://cdn.wetest.qq.com/" +
"ui/1.2.0/pc/static/image/newLogo-16042.png");
Notification.MessagingStyle messageStyle = new Notification.MessagingStyle(p);
Notification.MessagingStyle.Message message =
new Notification.MessagingStyle.Message("WeTestMessage", 2000, p);
//show image
Uri image = Uri.parse(
"http://cdn.wetest.qq.com/ui/1.2.0/pc/static/image/newLogo-16042.png");
message.setData("image/png", image);
messageStyle.addMessage(message);
builder.setStyle(messageStyle);
builder.setSmallIcon(R.mipmap.ic_launcher);
Notification notification = builder.build();
NotificationManager notifyManager =
(NotificationManager) getSystemService(
MainActivity.this.getApplicationContext().NOTIFICATION_SERVICE);
notifyManager.createNotificationChannel(channel);
notifyManager.notify("WeTest", 1, notification);
Android P中,重點做了內容豐富上的工作,同時也對Channel的設置方面做了一些簡化處理。
Android O版本里,首次推出了NotificationChannel,開發者需要配置相應的Channel,才能夠推送通知給用戶。用戶能夠更加細粒度[v1] 的針對App的Channel選擇,而不是禁止App的所有通知內容。
而在Android P中,對通知的管理做了進一步的優化,包括可以屏蔽通道組、提供新的廣播類型和新的免打擾優先級。
屏蔽通道組: 用戶可以在通知設置中屏蔽App的整個通道組。開發者可以通過isBlocked()來判斷某個通道組是否被屏蔽了,並根據結果,不向已經被屏蔽的通道組發送任何通知。另外,開發者可以在App中使用新接口getNotificationChannelGroup()來查詢當前的通道組設置。
新的廣播類型:新廣播類型是針對通道和通道組的功能增加的“通道(組)屏蔽狀態變化”廣播。開發者App中可以對所擁有的通道(組)接收廣播,並根據具體廣播內容作出動作。開發者可以通過NotificationManager,查看廣播相關的具體信息。針對廣播的動作可以通過Broadcasts查看具體的方法和信息。
免打擾優先級: NotificationManager.Policy增加了兩個新的優先級常量,PRIORITY_CATEGORY_ALARMS(警告優先),PRIORITY_CATEGORY_MEDIA_SYSTEM_OTHER (媒體、系統和遊戲聲音優先)。