Android 5.0 6.0 7.0和8.0都增加了什么

原味地址:https://blog.csdn.net/lixuce1234/article/details/79020418

随着安卓8.0的出现,越来越多的人开始要进行8.0系统的适配了,很多人都知道安卓最近几个版本的新特性这里大概说一下:

  1. 5.0的时候出现了Design风格
  2. 6.0出现的危险权限需要申请
  3. 7.0出现的目录访问被限制
  4. 今天要介绍的8.0通知栏的机制
在前一段时间用一个8.0的模拟器测试的时候,发送notifation(通知)的时候遇到了一个错误,如下图:

打印下来的错误信息:
No Channel found for pkg=com.lixuc.demo, channelId=null, id=1, tag=null, opPkg=com.lixuc.demo, callingUid=10081, userId=0, incomingUserId=0, notificationUid=10081, notification=Notification(channel=null pri=0 contentView=null vibrate=default sound=null defaults=0x2 flags=0x10 color=0xff98903b vis=PRIVATE)

跟进NotificationManager的notify方法,调用了NotificationManagerService的enqueueNotificationWithTag将通知入队,最后在NotificationManagerService的enqueueNotificationInternal方法中发现了error log的踪迹,截取代码片如下图:这里写图片描述

见图可知,是由于此条通知没有查找到应用中对应的NotificationChannel的原因,而无法弹出来。那NotificationChannel是个什么鬼,查阅官文得知,这是Android O新增的通知渠道,其允许您为要显示的每种通知类型创建用户可自定义的渠道。用户界面将通知渠道称之为通知类别。

先贴出我猜到坑的错误代码:



这里的NotificationCompat及NotificationManagerCompat来自官方提供的兼容库: 
com.android.support:appcompat-v7:26.1.0 
想着最新的Compat库兼容应该做得是最好的,然后错就错在这句代码: 
NotificationCompat.Builder(context, Integer.toString(notificationId)); 
一眼看到Builder构造函数的第二个参数,传的是id,就直接把notificationId传进去了,其实细看传的是channelId,我这里把channelId和notificationId概念搞混了。channelId传null,或者只有一个参数的Builder的构造方法,都不会出现错误,修正代码如下:

  1. NotificationCompat.Builder builder = new NotificationCompat.Builder( context, null);
  2. //或者
  3. NotificationCompat.Builder builder = new NotificationCompat.Builder( context);
  • 1
  • 2
  • 3
  • 4

原理就是:NotificationChannel是Android O新增的特性,为了兼容老代码,如果channelId为null的话,Android O会把通知归到“Other Channel”上。 
PS:将targetSdkVersion提到26以上的话,就必须设置channel了,不能为null。


下面来说一下我的解决方法

首先创建channel信息:

如果你需要发送属于某个自定义渠道的通知,你需要在发送通知前创建自定义通知渠道,示例如下:

  1. NotificationChannel channel = new NotificationChannel( "1",
  2. "Channel1", NotificationManager.IMPORTANCE_DEFAULT);
  3. channel.enableLights( true); //是否在桌面icon右上角展示小红点
  4. channel.setLightColor(Color.RED); //小红点颜色
  5. channel.setShowBadge( true); //是否在久按桌面图标时显示此渠道的通知
然后创建通知后,向自定义渠道发送通知

  1. int notificationId = 0x1234;
  2. Notification.Builder builder = new Notification.Builder(context, "1"); //与之前创建的channelId对应
  3. //icon title text必须包含,不然影响桌面图标小红点的展示
  4. builder.setSmallIcon(android.R.drawable.stat_notify_chat)
  5. .setContentTitle( "xxx")
  6. .setContentText( "xxx")
  7. .setNumber( 3); //久按桌面图标时允许的此条通知的数量
  8. notificationManager.notify(notificationId, builder.build());
删除掉某个渠道:
  1. NotificationChannel mChannel = mNotificationManager.getNotificationChannel(id);
  2. mNotificationManager.deleteNotificationChannel(mChannel);

如果你的应用里面有通知的话,恰巧你的targetSdkVersion是26以上的情况下,你就需要进行以上的操作了


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值