我尝试设置自定义通知声音,它在 Oreo(8.0) 设备下工作正常,但在 Oreo 设备中它不会触发自定义声音,始终只触发默认声音。谁能帮忙?
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
Notification.Builder notificationBuilder =
new Notification.Builder(getApplicationContext(), NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(content)
.setAutoCancel(true)
//.setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API
//.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build();
notificationChannel.setSound(defaultSoundUri, att);
notificationChannel.setDescription(content);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
} else {
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(content)
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
最佳答案
如果您使用的是 Oreo 下的 Android 版本,您只需将 MY_SOUND_NOTIFICATION.mp3 添加到名为 raw 的文件夹中的Resources,然后开始编写您的代码类,但由于您使用的是 Oreo 或更高版本,因此您需要检查您的 SDK_VERSION 以便使用 NotificationChannel
setSound
的方法
我不会发布任何代码,因为我没有发布代码来更正。如果您发布一些代码,我很乐意为您提供帮助
关于android - 如何在android 8.0中设置带有自定义声音的通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52757119/