給 Notification 設置提示音,核心是構建正確的 Uri。三種常見場景對應三種構建方式。
// 參數 "6" 對應系統鈴聲列表中的索引,實際開發建議用 RingtoneManager 讓用戶選擇
notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");
// assets 目錄下文件
notification.sound = Uri.parse("file:///android_asset/notification.mp3");
// 外部存儲 (需 READ_EXTERNAL_STORAGE 權限)
notification.sound = Uri.parse("file:///sdcard/Download/ring.mp3");
// 更安全:用 FileProvider 生成 content:// Uri (Android 7.0+)
File file = new File(getFilesDir(), "notify.ogg");
notification.sound = FileProvider.getUriForFile(this, AUTHORITY, file);
notification.defaults = Notification.DEFAULT_SOUND;
// 等同於 notification.defaults |= Notification.DEFAULT_SOUND;
// 會同時觸發默認聲音、震動、燈光 (若同時設置了 DEFAULT_VIBRATE/DEFAULT_LIGHTS)
RingtoneManager.getRingtonePickerIntent() 彈出系統鈴聲選擇器,保存返回的 Uri 持久化。NotificationChannel,並在 Channel 中指定 setSound()。AudioManager.getRingerMode(),勿勉強播放。NotificationChannel channel = new NotificationChannel(ID, NAME, IMPORTANCE_HIGH);
channel.setSound(soundUri, audioAttributes);
manager.createNotificationChannel(channel);
掌握 Uri 構建與 Channel 配置,通知聲音隨心控。