Android O更新已经有很长一段时间了,然而也带来了很多适配的问题,比如:app无法自动安装的问题,通知栏无法显示的问题等等。今天我们说说通知栏的声音无法关闭的问题,此篇博文针对关闭声音的,如果想开启声音则相反,道理一样的。
因为很多应用更新用的是notification创建一个前台通知,放在通知栏中给用户展示下载进度和提示内容,那么由于Android O引进了一个新的概念,那就是NotificationChannel,想知道相关属性和介绍可以去看看源码或api,这个新的概念的引进会导致很多新手很茫然,比如说:我!
首先我们检测手机sdk的当前版本如果是8。0或以上的话需要先适配notification
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationUtils.createNotificationChannel(
false,false,
channelId,//最好区别应用防止与其他应用冲突,可以加上包名之类,确定唯一性
channelName,
NotificationManager.IMPORTANCE_DEFAULT);
}
关于importance参数分为5个等级,大家自己去google一下或直接看源码。
然后创建NotificationChannel
@TargetApi(Build.VERSION_CODES.O)
public static void createNotificationChannel(boolean isVibrate,
boolean hasSound,
String channelId,
String channelName,
int importance) {
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
NotificationManager notificationManager = (NotificationManager) application.getSystemService(
NOTIFICATION_SERVICE);
channel.enableVibration(isVibrate);
channel.enableLights(true);
if (!hasSound)
channel.setSound(null, null);
if (notificationManager != null)
notificationManager.createNotificationChannel(channel);
}
很多人可能会碰到这个问题:明明代码一模一样都是复制的为什么还是有声音提醒呢?
那么这既是google的一个坑了;下面介绍几个解决办法:
一、更新channelId,设置为一个新的值,跟以往任何一个都不重复,然后再设置channel.setSound(null, null);就可以了。
二、卸载app,如果代码之前没问题,卸载重新安装就好了,
三、手动调用清空channelId的方法,(这个我没试过,但应该是可以的)
四、卸载app后把importance参数设置为NotificationManager.IMPORTANCE_LOW或者更低。再安装运行就好了。
五、mBuilder.setOnlyAlertOnce(true)设置为true,这样的话,每次只会提醒一次声音,不会重复提醒。
六、如果你不想卸载app的话,有个最好的办法就是同时更换channelId和NotificationManager.IMPORTANCE_LOW就可以了。