要在安卓上播放自定义通知声音,可以使用以下代码示例:
首先,确保将自定义通知声音文件放在 res/raw
目录下。
在创建通知时,使用 setSound()
方法将自定义声音文件与通知关联起来。
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My Notification")
.setContentText("This is a custom sound notification")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.custom_sound))
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, builder.build());
在上面的代码中,R.raw.custom_sound
是自定义声音文件的资源ID。通过将资源ID与 android.resource://
URI 结合使用,可以指定正确的声音文件路径。
请注意,如果您希望播放系统默认的通知声音,请将 setSound()
方法中的参数设置为 RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
。
此外,还需要确保在 AndroidManifest.xml 文件中声明 INTERNET
权限,以便应用可以访问本地文件。
这样就可以在安卓上播放自定义通知声音了。