我在通知中使用自定义 mp3 声音。它在 API 26 以下的所有设备上工作正常。我也尝试在通知通道上设置声音,但仍然没有工作。它播放默认声音。
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setAutoCancel(true)
.setSmallIcon(R.drawable.icon_push)
.setColor(ContextCompat.getColor(this, R.color.green))
.setContentTitle(title)
.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notification))
.setDefaults(Notification.DEFAULT_VIBRATE)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setContentText(message);
Notification notification = builder.build();
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.build();
channel.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notification), audioAttributes);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(1, notification);
原文由 Rodrigo Manguinho 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可能最初使用默认声音创建了频道。通道一经创建便无法更改。您需要重新安装应用程序或使用新频道 ID 创建频道。