Пользовательский звук уведомления не работает в 5.0 и выше

Я пытаюсь добавить собственный звук в уведомление. Ниже приведен мой код:

notificationSoundUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.error);

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    NotificationChannel channel = new NotificationChannel("default",
                            "YOUR_CHANNEL_NAME",
                            NotificationManager.IMPORTANCE_DEFAULT);
                    channel.setDescription("YOUR_NOTIFICATION_CHANNEL_DISCRIPTION");
                    mNotificationManager.createNotificationChannel(channel);
                }

                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "default")
                        .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
                        .setSmallIcon(R.mipmap.ic_launcher) // notification icon
                        .setContentTitle("BATTERY FULL") // title for notification
                        .setContentText("Battery is full. Please plug out the charger. Overcharging may decrease battery life span.")// message for notification
                        .setSound(notificationSoundUri) // set alarm sound for notification
                        .setAutoCancel(true); // clear notification after click

                mNotificationManager.notify(1, mBuilder.build());

Этот код работает на устройствах с леденцами, а не на Marshmallow. В Marshmallow используется звук уведомления телефона по умолчанию. Я предполагаю, что эта проблема для леденцов и более высоких устройств. Что мне здесь не хватает?




Ответы (3)


У этой проблемы было несколько попыток, похоже, что NotificationCompat пропускает метод звука между андроидами 21 и 25, чтобы уведомление работало, вам нужно установить звук как этот

val builder: Notification.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      Notification.Builder(this, channelId1)
} else {
      Notification.Builder(this)        
}
 ...
val audioAttr = AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_ALARM).build()
            builder.setSound(
                notification1Sound(), // custom uri
                audioAttr)

Я не поддерживаю версии до леденца на палочке, так что это работает для меня, для более старой версии вам может потребоваться добавить проверку второй версии

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
   builder.setSound(
       notification1Sound(),
       audioAttr
    )
} else {
   builder.setSound(notification1Sound(), AudioManager.STREAM_ALARM)
}
person Guilherme Titschkoski    schedule 16.08.2019

Вы должны использовать канал уведомлений с Android O (https://developer.android.com/training/notify-user/channels). Это работает только с API 26+, потому что класс NotificationChannel является новым и не входит в библиотеку поддержки.

person Eddi    schedule 09.07.2018

 builder.setStyle(new NotificationCompat.InboxStyle());

Полный код:

   NotificationCompat.Builder builder =  
        new NotificationCompat.Builder(this)  
        .setSmallIcon(R.drawable.ic_launcher)  
        .setContentTitle("Notifications Example")  
        .setContentText("This is a test notification");  


Intent notificationIntent = new Intent(this, MenuScreen.class);  

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,   
        PendingIntent.FLAG_UPDATE_CURRENT);  

builder.setContentIntent(contentIntent);  
builder.setAutoCancel(true);
builder.setLights(Color.BLUE, 500, 500);
long[] pattern = {500,500,500,500,500,500,500,500,500};
builder.setVibrate(pattern);
builder.setStyle(new NotificationCompat.InboxStyle());

Используйте эти строки кода для пользовательского звука

URI uri=Uri.parse("android.resource://"+context.getPackageName()+"/"+R.raw.FILE_NAME);//Here is FILE_NAME is the name of file that you want to play

builder.setSound(uri);

Не забудьте добавить канал уведомлений

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            @SuppressLint("WrongConstant")
            NotificationChannel channel = new NotificationChannel("XYZ", "ABC",NotificationManager.IMPORTANCE_MAX);
            mNotificationManager.createNotificationChannel(channel);
        }

        mNotificationManager.notify(0, mBuilder.build());
person Nidhi Mishra    schedule 09.07.2018
comment
Это не работает. Предполагалось ли, что .setStyle(new NotificationCompat.InboxStyle()) решит проблему? - person hasn; 09.07.2018