Звук канала уведомлений Android не работает

Я знаю, что было много сообщений об этой проблеме. Я пробовал их все. Вот шаги, которые я сделал.

Сначала я узнал, что после того, как канал был создан, его нельзя изменить. Единственный выход - переустановить приложение. Так вот что я сделал, и это не сработало.

Во-вторых, некоторые говорят, что я могу удалить канал, поэтому я также сделал это, используя этот код.

val channelList = mNotificationManager.notificationChannels
        var i = 0
        while (channelList != null && i < channelList.size) {
            Log.d("channelList","channel ID is ${channelList[i].id}")
            //mNotificationManager.deleteNotificationChannel(channelList[i].id)
            i++
        }

а затем воссоздание канала после удаления.

В-третьих, я пытался использовать новый канал уведомлений, но каждый раз, когда я использую новый канал, я получаю сообщение об ошибке.

Вот код, который я использую со всеми теми решениями, которые я пробовал

 val audioAttributes = AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .setUsage(AudioAttributes.USAGE_ALARM)
                .build()


        val importance = NotificationManager.IMPORTANCE_DEFAULT

        val channelList = mNotificationManager.notificationChannels
        var i = 0
        while (channelList != null && i < channelList.size) {
            Log.d("channelList","channel ID is ${channelList[i].id}")
            mNotificationManager.deleteNotificationChannel(channelList[i].id)
            i++
        }

        Log.d("isnotification"," is it needed $isNotificationSoundNeeded importance is $importance")
        val mChannel = NotificationChannel(CHANNEL_ID, appName,  NotificationManager.IMPORTANCE_HIGH)
        mChannel.setShowBadge(false)
        mChannel.setSound(notifSound, audioAttributes)



        val mChannelnew = NotificationChannel(CHANNEL_ID2, appName,  NotificationManager.IMPORTANCE_DEFAULT)
        mChannelnew.setShowBadge(false)
        mChannelnew.setSound(notifSound, audioAttributes)




        mNotificationManager.createNotificationChannel(mChannel)

Что мне не хватает? Любые идеи? Спасибо

Обновление: вот код для notifsound

val notifSound = Uri.parse("android.resource://" + packageName + "/" + R.raw.unconvinced)

person thenewbie    schedule 30.05.2019    source источник
comment
Где ваш код для создания объекта notifSound? Обратите внимание, что удаление/переустановка приложения не приводит к сбросу ваших каналов — вам необходимо очистить данные в приложении.   -  person ianhanniballake    schedule 30.05.2019
comment
@ianhanniballake я обновил свой пост   -  person thenewbie    schedule 31.05.2019
comment
Какую ошибку вы получаете?   -  person Dmitriy Miyai    schedule 31.05.2019
comment
@DmitriyMiyai Если я использую новый канал, я получу ошибку неработающего канала. Если я использую оригинал, он работает, но вообще не регистрирует звук. Это так странно.   -  person thenewbie    schedule 31.05.2019
comment
пожалуйста, проверьте мой ответ!   -  person ismail alaoui    schedule 07.06.2019
comment
@thenewbie проверьте мой ответ Это даст вам все решение для настраиваемого уведомления   -  person BlackBlind    schedule 08.06.2019


Ответы (3)


Во-первых, я не знаю, на каких устройствах, таких как Oreo, Pie или ниже, чем N, ваше уведомление не работает.

For your question StackOver Flow have lots of answer.

Теперь, согласно вашему вопросу, у вас отсутствует только одна строка кода. Но здесь невозможно проверить весь код уведомления, потому что вы еще не вставлены.

Здесь я вставляю код уведомления, который просто выполняет все ваши требования к уведомлению. (Полное пользовательское уведомление)

Уведомление с изображением

public void createNotificationWithImage(String title,String message ,Bitmap image) {
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,
            0 /* Request code */, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

// Custom Sound Uri

Uri soundUri = Uri.parse("android.resource://" + mContext.getApplicationContext()
                .getPackageName() + "/" + R.raw.sniper_gun);

 mBuilder = new NotificationCompat.Builder(mContext);
 mBuilder.setSmallIcon(R.mipmap.notification_icon);

 // Pay attention on below line here (NOTE)
 mBuilder.setSound(soundUri);

if (image!=null) {
            mBuilder.setContentTitle(title)
                    .setContentText(message)
                    .setAutoCancel(false)
                    .setLargeIcon(image)
                    .setStyle(new NotificationCompat.BigPictureStyle()
                            .bigPicture(image).setSummaryText(message).bigLargeIcon(null))
                    .setColor(Color.GREEN)
                    .setContentIntent(resultPendingIntent);
        }
mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

Теперь я вставляю код уведомления, который будет работать выше или на устройствах OREO.

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});

        if(soundUri != null){
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_ALARM)
                    .build();
            notificationChannel.setSound(soundUri,audioAttributes);
        }

        assert mNotificationManager != null;
        mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
        mNotificationManager.createNotificationChannel(notificationChannel);
    }
    assert mNotificationManager != null;
    mNotificationManager.notify(0 /* Request Code */, mBuilder.build());


below middle braces use for close your method.
}

Уведомление без изображения

    public void createNotification(String title,String message){
    PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,
                0 /* Request code */, resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        Uri soundUri = Uri.parse("android.resource://" + mContext.getApplicationContext()
                .getPackageName() + "/" + R.raw.sniper_gun);



        mBuilder = new NotificationCompat.Builder(mContext);
        mBuilder.setSmallIcon(R.mipmap.notification_icon);
        mBuilder.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(),
                R.mipmap.icon));
        mBuilder.setSound(soundUri);
        mBuilder.setContentTitle(title)
                .setContentText(message)
                .setAutoCancel(false)
                .setColor(Color.GREEN)
                .setStyle(new NotificationCompat.BigTextStyle())
                .setContentIntent(resultPendingIntent);

        mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.enableVibration(true);
            notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
//            notificationChannel.s

            if(soundUri != null){
                AudioAttributes audioAttributes = new AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                        .setUsage(AudioAttributes.USAGE_ALARM)
                        .build();
                notificationChannel.setSound(soundUri,audioAttributes);
            }

            assert mNotificationManager != null;
            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            mNotificationManager.createNotificationChannel(notificationChannel);

        }

        assert mNotificationManager != null;
        mNotificationManager.notify(0 /* Request Code */, mBuilder.build());

    }

ПРИМЕЧАНИЕ. В моем коде я упомянул, что обратите внимание на одну конкретную строку, где я описал установку звука Uri с уведомлением. Можно так описать.

mBuilder.setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(false)
            .setSound(soundUri)
            .setColor(Color.GREEN)
            .setStyle(new NotificationCompat.BigTextStyle())
            .setContentIntent(resultPendingIntent);

но он не будет воспроизводить звук для вас, потому что после того, как устройство Oreo не устанавливает звук в качестве уровня приоритета.

Поэтому для звука всегда используйте код, как я описал.

person BlackBlind    schedule 07.06.2019
comment
Мне пришлось изменить свои аудиоатрибуты с типа уведомления на сигнал тревоги, как в этом посте. - person Robert Bentley; 24.12.2019

я предполагаю, что вы используете неправильный тип использования, пожалуйста, измените audioAttributes использование на USAGE_NOTIFICATION

            val audioAttributes = AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
            .build()

Из официального документа:

USAGE_NOTIFICATION : значение использования, используемое, когда использование является уведомлением.

person ismail alaoui    schedule 06.06.2019

Вам необходимо использовать атрибуты звука, а также определить URI мелодии звонка с разрешением.

Итак, сначала мы определяем URI рингтона:

Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
boolean vibrate = true;
long[] vibratePattern = new long[]{0L, 1000L};



public constructor(){
 notificationBuilder = new NotificationCompat.Builder(mContext, app.getAppContext().getString(R.string.default_notification_channel_id));
        mNotifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        mContext.grantUriPermission("com.android.systemui", ringtoneUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
 public void showNotificationNormal(String notificationTitle, String notificationBody, Intent intent) {
    String id = mContext.getString(R.string.default_notification_channel_id);
    PendingIntent lowIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext, id);
    NotificationManager mNotifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = mContext.getString(R.string.default_notification_channel_name);
        String description = mContext.getString(R.string.default_notification_channel_description); //user visible
        int importance = NotificationManager.IMPORTANCE_HIGH;

        AudioAttributes att = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build();

        NotificationChannel mChannel = new NotificationChannel(id, name, importance);
        mChannel.setDescription(description);
        mChannel.enableLights(true);
        mChannel.enableVibration(vibrate);
        mChannel.setVibrationPattern(vibratePattern);
        mChannel.setLightColor(Color.RED);
        mChannel.setSound(ringtoneUri, att);
        mChannel.setBypassDnd(true);
        mChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
        mChannel.setShowBadge(true);

        if (mNotifyManager != null) {
            mNotifyManager.createNotificationChannel(mChannel);
        }

        notificationBuilder
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                .setVibrate(vibratePattern)
                .setSound(ringtoneUri)
                .setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
                .setContentTitle(notificationTitle)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(notificationBody))
                .setAutoCancel(true)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setContentIntent(lowIntent);

    } else {
        notificationBuilder.setContentTitle(notificationTitle)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                .setVibrate(vibratePattern)
                .setSound(ringtoneUri)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(notificationBody))
                .setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
                .setAutoCancel(true)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setContentIntent(lowIntent);

    }

    notificationBuilder.setContentText(notificationBody);

    if (mNotifyManager != null) {
        mNotifyManager.notify(AppConstants.NOTIFY_ID, notificationBuilder.build());
    }
}
person Raja chakraborty    schedule 07.06.2019