Android通知仅播放声音

9
我在我的活动中有一个倒计时器,当它归零时,我会向状态栏发送通知,同时播放自定义wav文件以警示用户。我只希望在用户此时未使用应用程序时才出现状态栏通知,但我仍然希望无论计时器应用程序是否可见,wav文件都能播放。
是否可能使Android通知仅播放音频警报?我尝试使用MediaPlayer来播放wav文件,但这将使用自己的音量设置而不是常规通知音量,因此如果您的媒体音量较低,则通知声音也会以低音量播放,这不是我想要的。我希望声音以与其他通知相同的音量播放。
我正在使用这个: http://developer.android.com/guide/topics/ui/notifiers/notifications.html 并像这样提供声音:
notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notifysnd);

是的,只播放音频警报是可能的。 - coder_For_Life22
1
谢谢 @coder_For_Life22,请问你可以给我展示一下吗? - Daniel
4个回答

5
http://developer.android.com/guide/topics/ui/notifiers/notifications.html中的“添加声音”部分,有以下注释:

注意:如果defaults字段包括DEFAULT_SOUND,则默认声音将覆盖由声音字段定义的任何声音。

因此,如果您只想自定义声音,则可以使用 -

notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notifysnd);
notification.defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE;

4
根据我的实验,您确实可以发送通知,而不会出现在通知区域,但仍然播放声音。
您需要做的就是构建一个通知生成器并为其设置声音,但跳过待定意图、图标、内容标题和内容文本。
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSound(your_sound_uri);
notificationManager.notify(1234, builder.build());

1
这些答案非常有帮助,因为文档中关于此事的描述是错误的。http://developer.android.com/guide/topics/ui/notifiers/notifications.html#CreateNotification 上说,“通知对象必须包含以下内容:由setSmallIcon()设置的小图标;由setContentTitle()设置的标题;由setContentText()设置的详细文本”。 - Jerry101
2
需要图标。这会导致错误:java.lang.IllegalArgumentException: 无效通知(没有有效的小图标) - Tom Bevelander

0
NotificationCompat.Builder builder= new NotificationCompat.Builder(this);

三种设置声音的方法

builder.setDefaults(Notification.DEFAULT_SOUND);
builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);

0
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

Notification mNotification = new Notification.Builder(this)

            .setContentTitle("New Post!")
            .setContentText("Here's an awesome update for you!")
            .setSmallIcon(R.drawable.ic_lancher)
            .setContentIntent(pIntent)
            .setSound(soundUri)
            .build();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接