Android8.0 Notification適配
1.新增的NotificationChannel
在Android8.0以后,發(fā)送通知都需要?jiǎng)?chuàng)建或者獲取一個(gè)已有的通知通道NotificationChannel
,這個(gè)通道可以定義通知的聲音震動(dòng)等類型借跪,然后每個(gè)使用這個(gè)通道的通知都會(huì)具有這個(gè)類型的通知屬性政己;
Demo
設(shè)置NotificationChannel
:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
boolean isVibrateEnabled = MyApplication.getGeneralAlarmSettings()[1] == 1
NotificationChannel notificationChannel = notificationManager.getNotificationChannel(NotificationUtils.NOTIFICATION_CHANNEL_ID);
if (notificationChannel == null) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
notificationChannel = new NotificationChannel(NotificationUtils.NOTIFICATION_CHANNEL_ID, NotificationUtils.NOTIFICATION_CHANNEL_DESC, importance);
notificationChannel.setLightColor(Color.GREEN);
notificationChannel.enableVibration(isVibrateEnabled);
notificationManager.createNotificationChannel(notificationChannel);
}
}
這里需要給通道設(shè)置一個(gè)唯一的ID,以及描述掏愁。
2.創(chuàng)建一個(gè)通知
final Notification.Builder notificationBuilder = new Notification.Builder(MyApplication.getInstance(),NOTIFICATION_CHANNEL_ID); notificationBuilder.setSmallIcon(R.drawable.ic_notification_logo); notificationBuilder.setTicker(ticker); notificationBuilder.setContentTitle(title); notificationBuilder.setContentText(content);
//設(shè)置Channel ID
notificationBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
//設(shè)置Channel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
boolean isVibrateEnabled = MyApplication.getGeneralAlarmSettings()[1] == 1
NotificationChannel notificationChannel = notificationManager.getNotificationChannel(NotificationUtils.NOTIFICATION_CHANNEL_ID);
if (notificationChannel == null) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
notificationChannel = new NotificationChannel(NotificationUtils.NOTIFICATION_CHANNEL_ID, NotificationUtils.NOTIFICATION_CHANNEL_DESC, importance);
notificationChannel.setLightColor(Color.GREEN);
notificationChannel.enableVibration(isVibrateEnabled);
notificationManager.createNotificationChannel(notificationChannel);
}
}
notificationBuilder.setAutoCancel(true);
Intent intent = new Intent(MyApplication.getInstance(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(MyApplication.getInstance(), 0 , intent, PendingIntent.FLAG_ONE_SHOT);
notificationBuilder.setContentIntent(pendingIntent);
notificationBuilder.setFullScreenIntent(pendingIntent, true);
notificationManager.notify(alarmType.getValue(), notificationBuilder.build());
3.成功通知
通知發(fā)送成功之后歇由,不同于之前版本的是發(fā)送通知的App右上角會(huì)有對(duì)應(yīng)通知數(shù)量的小紅點(diǎn)。