在 Android 8.0 中,咱們已從新設計通知,以便爲管理通知行爲和設置提供更輕鬆和更統一的方式。這些變動包括:html
setTimeoutAfter()
建立通知時您能夠設置超時。您可使用此函數指定一個持續時間,超過該持續時間後,通知應取消。若是須要,您能夠在指定的超時持續時間以前取消通知。Notification.INTENT_CATEGORY_NOTIFICATION_PREFERENCES
Intent 從通知建立指向應用通知設置的連接時,您能夠調用 setSettingsText()
來設置要顯示的文本。此係統能夠提供如下 Extra 數據和 Intent,用於過濾應用必須向用戶顯示的設置:EXTRA_CHANNEL_ID
、NOTIFICATION_TAG
和 NOTIFICATION_ID
。NotificationListenerService
類的新 onNotificationRemoved()
函數。Notification.Builder.setColor()
設置所需的背景顏色。這樣作將容許您使用 Notification.Builder.setColorized()
啓用通知的背景顏色設置。MessagingStyle
類的通知可在其摺疊形式中顯示更多內容。對於與消息有關的通知,您應使用 MessagingStyle
類。您還可使用新的 addHistoricMessage()
函數,經過向與消息相關的通知添加歷史消息爲會話提供上下文。
您能夠在 NotificationCompat.Builder
對象中爲通知指定 UI 信息和操做。要建立通知,請調用 NotificationCompat.Builder.build()
,它將返回包含您的具體規範的 Notification
對象。要發出通知,請經過調用 NotificationManager.notify()
將 Notification
對象傳遞給系統。java
Notification
對象必須包含如下內容:android
setSmallIcon()
設置setContentTitle()
設置setContentText()
設置NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);複製代碼
// Creates an explicit intent for an Activity in your app
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(MainActivity.this);
taskStackBuilder.addParentStack(Main2Activity.class);
taskStackBuilder.addNextIntent(intent);
// 經過taskStackBuilder對象獲取PendingIntent
PendingIntent pi = taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
String custom_id = "marco_notification"; // 自定義通知渠道
idCharSequence name = getString(R.string.channel_name); // 自定義通知渠道
nameString description = getString(R.string.channel_description); // 自定義通知渠道描述
int importance = NotificationManager.IMPORTANCE_HIGH; // 自定義通知渠道級別
//建立自定義渠道
NotificationChannel marco_channel = new NotificationChannel(custom_id, name, importance);
// 添加一系列特性
marco_channel.setDescription(description);
marco_channel.enableLights(true);
marco_channel.setLightColor(Color.RED);
notificationManager.createNotificationChannel(marco_channel);複製代碼
NotificationCompat.Builder notification = new NotificationCompat.Builder(MainActivity.this, custom_id)
.setContentTitle("This is a Notification")
.setContentText("Notification contentText")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(pi);
notificationManager.notify(1,notification.build());複製代碼
如下爲代碼截圖和通知顯示效果:bash
圖1. 建立自定義渠道的Notification代碼邏輯app
圖2. Notification顯示截圖函數
NotificationCompat.Builder notification = new NotificationCompat.Builder(MainActivity.this, custom_id)
.setContentTitle("This is a Notification")
.setContentText("Notification contentText")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(pi)
// 設置超時時間,5000 = 5秒,Notification將會消失
.setTimeoutAfter(5000);複製代碼