若要在Android 11上使用自定义声音,需要使用NotificationCompat API。以下是一个示例代码:
Uri soundUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.custom_sound);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setSound(soundUri)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, builder.build());
在上面的示例中,R.raw.custom_sound
是在res/raw文件夹下的自定义声音文件。使用setSound()
方法将自定义声音应用于通知。