android - 自定义通知声音在 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 中运行?
解决方案
要在 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());
}
}
推荐阅读
- javascript - 这些元素在这个 JS 函数中的作用是什么?
- python - 垃圾收集 - 标记+扫描是否必须是整体/原子的
- wordpress - 致命错误:不在对象上下文中使用 $this - Dokan Wordpress 插件
- java - POST 时出现内部服务器错误。弹簧靴
- haskell - Identity Monad - Haskell 中的行为差异?
- php - 我不能在类方法中使用属性
- laravel - 在 Laravel 中间件中设置全局变量/文本方向
- sql - 我需要加入 2 个数据库,每个数据库有 2 个表
- python - ImportError:没有名为“助手”的模块
- r - 如何清理此数据框以使用 ggplot 绘制箱线图?