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

Android NotificationCompat.Builder 添加自定義聲音

     編輯:程式設計綜合問答

問題現象

使用 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);

關鍵細節

  1. Uri 格式:android.resource://[package_name]/[raw_resource_id],R.raw.xxx 為整數 ID。
  2. 聲音檔放置:res/raw/custom_sound.mp3(或 .ogg/.wav),檔名小寫、無特殊字元。
  3. Android 8.0+ 通知頻道:必須建立 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());
}

常見問題

  • 無聲音:檢查頻道重要性、裝置勿擾模式、媒體音量、Uri 拼寫。
  • 預設聲音:若不設定 sound,系統使用預設通知聲;若設定 notification.sound = null 可靜音。
  • 長聲音:通知聲音建議 < 30 秒,過長可能被系統截斷。

掌握 Notification.sound + NotificationChannel 組合,即可靈活控制通知聲音體驗。

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