使用 NotificationCompat.Builder 建立通知,需播放 res/raw 目錄下的自定義聲音檔。
NotificationCompat.Builder 建構後需取得 Notification 物件,直接設定 sound 欄位為 Uri。
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("警告")
.setContentText("需要協助!")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true);
// 關鍵:build() 後設定 sound
Notification notification = builder.build();
notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.custom_sound);
// 發送
NotificationManagerCompat.from(this).notify(NOTIFY_ID, notification);
android.resource://[package_name]/[raw_resource_id],R.raw.xxx 為整數 ID。res/raw/custom_sound.mp3(或 .ogg/.wav),檔名小寫、無特殊字元。NotificationChannel,且頻道重要性 IMPORTANCE_DEFAULT 以上聲音才會播放。private static final String CHANNEL_ID = "alert_channel";
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID, "警告通知", NotificationManager.IMPORTANCE_HIGH);
channel.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.custom_sound), null);
NotificationManagerCompat.from(this).createNotificationChannel(channel);
}
}
public void sendNotification() {
createNotificationChannel();
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("警告")
.setContentText("需要協助!")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true);
NotificationManagerCompat.from(this).notify(100, builder.build());
}
sound,系統使用預設通知聲;若設定 notification.sound = null 可靜音。掌握 Notification.sound + NotificationChannel 組合,即可靈活控制通知聲音體驗。