本文介绍了Android Oreo无法播放自定义声音以进行通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试向API> 26的通知添加自定义声音。以下是代码
I am trying to add a custom sound to notification for API > 26. Below is the code
NotificationChannel notificationChannel = new NotificationChannel("channel id","channel name",NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(notificationChannel);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
notificationChannel.setSound(Uri.parse("android.resource://" + BuildConfig.APPLICATION_ID + "/raw/beep"),audioAttributes);
这里的问题是它播放设备的默认钢琴声音,而不是播放资产的哔声。我不允许使用铃声管理器,但常识性统计表明通知声音应该是指定的声音而不是默认声音。
The problem here is that it, plays default piano sound of device rather than playing beep sound from assets. I am not allowed to use ringtone manager but common sense stats that notification sound should be that which is specified rather than default.
对于API< = 26来说很好用
It works fine for API <= 26
推荐答案
最后我设法自己找到了解决方案。下面是代码
Finally I managed to find a solution on my own. Below is the code
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
if(notificationSoundUri != null){
// Changing Default mode of notification
notificationCompatBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
// Creating an Audio Attribute
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
// Creating Channel
NotificationChannel notificationChannel = new NotificationChannel(context.getString(R.string.channel_id_prayers),context.getString(R.string.channel_name_prayers),NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setSound(notificationSoundUri,audioAttributes);
mNotificationManager.createNotificationChannel(notificationChannel);
}
}
mNotificationManager.notify(0, notificationCompatBuilder.build());
这篇关于Android Oreo无法播放自定义声音以进行通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!