首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android Notification 聲音設置全攻略:系統音、本地文件、默認音三種方式

     編輯:程式設計綜合問答

給 Notification 設置提示音,核心是構建正確的 Uri。三種常見場景對應三種構建方式。

方式一:系統內置鈴聲

// 參數 "6" 對應系統鈴聲列表中的索引,實際開發建議用 RingtoneManager 讓用戶選擇
notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");

方式二:App 內置/下載的音頻文件

// 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)

最佳實踐

  1. 用戶自選:用 RingtoneManager.getRingtonePickerIntent() 彈出系統鈴聲選擇器,保存返回的 Uri 持久化。
  2. 版本適配:Android 8.0+ 必須設置 NotificationChannel,並在 Channel 中指定 setSound()。
  3. 靜默模式:尊重 AudioManager.getRingerMode(),勿勉強播放。

代碼片段:Channel 設置聲音 (API 26+)

NotificationChannel channel = new NotificationChannel(ID, NAME, IMPORTANCE_HIGH);
channel.setSound(soundUri, audioAttributes);
manager.createNotificationChannel(channel);

掌握 Uri 構建與 Channel 配置,通知聲音隨心控。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved