【问题标题】:Setting sound for notification设置通知声音
【发布时间】:2025-12-31 17:35:02
【问题描述】:

如何为我的 android 应用程序设置通知声音。在我的应用程序中,通知将在 30 秒后显示。我想为此警报提供选项,例如静音模式、振动模式以及从设备的可用音调中进行选择的选项。我正在使用首选项屏幕来显示设置菜单。我想设置特定的通知铃声类型应用程序。有什么办法可以证明这一点..

【问题讨论】:

    标签: android audio sharedpreferences ringtone


    【解决方案1】:

    如何为 Android 通知设置自定义声音

    在您的 res/raw 目录中放置一个 .mp3 或 .wav 文件,例如“notification_sound.mp3”,如下例所示(文件名不得使用大写字母)。

    在创建通知时设置 Notification.sound,如下所示:

    final int iconResId = R.drawable.my_icon;
    final int soundResId = R.raw.notification_sound;
    final Notification notification =
        new Notification(iconResId, tickerText, System.currentTimeMillis());
    final String packageName = context.getPackageName();
    notification.sound =
        Uri.parse("android.resource://" + packageName + "/" + soundResId);
    

    (可选)为您的通知添加振动:

    notification.defaults = Notification.DEFAULT_VIBRATE;
    

    【讨论】:

      【解决方案2】:

      http://developer.android.com/reference/android/app/Notification.Builder.html#setSound(android.net.Uri)

      Notification.Builder.setSound();
      

      在偏好活动中使用铃声偏好来获取所选声音的 URI。

      【讨论】:

      • 谢谢马库斯。但是,当我尝试通过为铃声首选项设置 onclick 侦听器来获取铃声的 id 时,我收到以下错误:03-01 10:49:59.021: DEBUG/MediaPlayer(308): Couldn't open file on客户端,尝试服务器端 03-01 10:49:59.031:错误/MediaPlayerService(34):无法为内容打开 fd://settings/system/notification_sound 03-01 10:49:59.031:错误/MediaPlayer( 308): 无法创建媒体播放器 03-01 10:49:59.041: ERROR/RingtoneManager(308): 无法打开铃声内容://settings/system/notification_sound
      • notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, ringtoneId);
      • 您还可以引用与应用程序捆绑的声音资源:notification.sound = Uri.parse("android.resource://com.company.package/" + soundResourceId);