Android8.0 Notification适配
1.新增的NotificationChannel
在Android8.0以后,发送通知都需要创建或者获取一个已有的通知通道NotificationChannel,这个通道可以定义通知的声音震动等类型,然后每个使用这个通道的通知都会具有这个类型的通知属性;
Demo
设置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);
}
}
这里需要给通道设置一个唯一的ID,以及描述。
2.创建一个通知
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);
//设置Channel ID
notificationBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
//设置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.成功通知
通知发送成功之后,不同于之前版本的是发送通知的App右上角会有对应通知数量的小红点。