android 8.0适配Notification

拿一个以前的项目来重构,发现notification没有效果了,也没有报错,有的手机上能显示通知,但是没有action。奇怪,查了一下才知道是要适配了,我将新项目中的targetSdkVersion指定到了26以上,就强制要适配了。

从Android 8.0系统开始,Google引入了通知渠道这个概念。就是说每条通知都有一个渠道属性。App都可以自由选择拥有哪些通知渠道,但是通知渠道的控制权都是掌握在用户手上,用户可以自由地选择这些通知渠道的重要程度,是否响铃、是否振动、或者是否要关闭这个渠道的通知。

背景就交代到这里,here we go


android 8.0适配Notification_第1张图片

由上图可见NotificationCompat.Builder的构造方法Builder(Context context)已经被标注过时了,“当然,Google也并没有完全做绝,即使方法标为了废弃,但还是可以正常使用的。可是如果你将项目中的targetSdkVersion指定到了26或者更高,那么Android系统就会认为你的App已经做好了8.0系统的适配工作,当然包括了通知栏的适配。这个时候如果还不使用通知渠道的话,那么你的App的通知将完全无法弹出”

android 8.0适配Notification_第2张图片

新的构造方法多了一个参数channelId,也就是前面说的通知渠道,要提前创建渠道

@TargetApi(26)
private void createNotificationChannels() {
    List notificationChannels = new ArrayList<>();
    NotificationChannel recordingNotificationChannel = new NotificationChannel(
            NotificationUtil.channelId,
            NotificationUtil.channelName,
            NotificationManager.IMPORTANCE_DEFAULT
    );
    recordingNotificationChannel.enableLights(true);
    recordingNotificationChannel.setLightColor(Color.RED);
    recordingNotificationChannel.setShowBadge(true);
    recordingNotificationChannel.enableVibration(true);
    recordingNotificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
    notificationChannels.add(recordingNotificationChannel);
    getManager().createNotificationChannels(notificationChannels);
}

然后在new Builder的时候传入channel Id

NotificationCompat.Builder notification = new NotificationCompat.Builder(this, NotificationUtil.channelId)

创建通知的代码和传统创建通知的方法没什么两样,只是在NotificationCompat.Builder中需要多传入一个通知渠道ID。

详细参考郭神的文章:https://blog.csdn.net/guolin_blog/article/details/79854070

你可能感兴趣的:(问题解决)