首页 > 解决方案 > 自定义通知声音在 Android Oreo 中不起作用

问题描述

Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.notification_mp3);
            mBuilder.setSound(sound);

我已将 mp3 (notification_mp3.mp3) 文件复制到 res 文件夹中的 raw 文件夹中。当通知被触发时,它会在Android Nougat中产生给定的 mp3 声音,但在Android Oreo中产生默认声音。我推荐了很多网站,但在Android Oreo上没有任何效果。我在 Android Docs 中没有发现关于 Android O 及更高版本通知声音的任何变化。应该进行哪些更改才能使此代码也可以在 Android O 中运行?

标签: androidpush-notificationandroid-notifications

解决方案


要在 Oreo 中为通知设置声音,您必须设置声音,NotificationChannel而不是设置声音Notification Builder本身。您可以按以下方式执行此操作

Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.notification_mp3);

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

        NotificationChannel mChannel = new NotificationChannel("YOUR_CHANNEL_ID",
            "YOUR CHANNEL NAME",
            NotificationManager.IMPORTANCE_DEFAULT)

        AudioAttributes attributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .build();

        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, 
                context.getString(R.string.app_name),
                NotificationManager.IMPORTANCE_HIGH);

        // Configure the notification channel.
        mChannel.setDescription(msg);
        mChannel.enableLights(true);
        mChannel.enableVibration(true);
        mChannel.setSound(sound, attributes); // This is IMPORTANT


        if (mNotificationManager != null)
            mNotificationManager.createNotificationChannel(mChannel);
    }

这将为您的通知设置自定义声音。但是如果应用正在更新,并且之前使用过通知渠道,则不会更新。即您需要创建一个不同的频道并为其设置声音以使其正常工作。但这将在您应用的应用信息的通知部分显示多个频道。如果您将声音设置为一个全新的通道,这很好,但如果您希望之前使用该通道,则必须删除现有通道并重新创建该通道。为此,您可以在创建频道之前执行类似的操作

if (mNotificationManager != null) {
            List<NotificationChannel> channelList = mNotificationManager.getNotificationChannels();

            for (int i = 0; channelList != null && i < channelList.size(); i++) {
                mNotificationManager.deleteNotificationChannel(channelList.get(i).getId());
            }
        }

推荐阅读