1. 程式人生 > >關於Android 8.0後notification通知聲音無法關閉或開啟的問題

關於Android 8.0後notification通知聲音無法關閉或開啟的問題

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就可以了。