如何播放android通知声音

我想知道如何播放通知声音,而不通过媒体stream播放。 现在,我可以通过媒体播放器来做到这一点,但是我不希望它作为媒体文件播放,我希望它可以作为通知或提醒或铃声播放。 下面是我的代码现在的样子:

MediaPlayer mp = new MediaPlayer(); mp.reset(); mp.setDataSource(notificationsPath+ (String) apptSounds.getSelectedItem()); mp.prepare(); mp.start(); 

如果有人仍然在寻找解决scheme,我发现如何在Android中播放铃声/闹钟声音的答案

 try { Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification); r.play(); } catch (Exception e) { e.printStackTrace(); } 

您可以将TYPE_NOTIFICATION更改为TYPE_ALARM,但是您将需要跟踪铃声r以停止播放它…例如,当用户单击某个button时。

您现在可以通过在构build通知时包含声音而不是单独调用声音来实现此目的。

 //Define Notification Manager NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); //Define sound URI Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext()) .setSmallIcon(icon) .setContentTitle(title) .setContentText(message) .setSound(soundUri); //This sets the sound to play //Display notification notificationManager.notify(0, mBuilder.build()); 

如果您想要播放默认通知声音,则可以使用NotificationCompat.Builder类的setDefaults(int)方法:

 NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(getString(R.string.app_name)) .setContentText(someText) .setDefaults(Notification.DEFAULT_SOUND) .setAutoCancel(true); 

我相信这是完成你的任务的最简单的方法。

自从你的问题已经有一段时间了,但是…你有没有尝试设置audiostreamtypes?

 mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION); 

准备之前一定要做好。

尝试这个:

 public void ringtone(){ try { Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification); r.play(); } catch (Exception e) { e.printStackTrace(); } } 

您可以使用Notification和NotificationManager来显示您想要的通知。 然后,您可以自定义您想要播放通知的声音。

我有几乎相同的问题。 经过一番研究,我想如果你想播放默认的系统“通知声音”,你几乎不得不显示一个通知,并告诉它使用默认的声音。 在其他一些答案中有一些话要说,如果你在播放通知声音,你也应该提交一些通知消息。

不过,稍微调整一下通知API,你可以接近你想要的。 您可以显示空白通知,然后在几秒钟后自动将其删除。 我认为这会对我有用。 也许它会为你工作。

我已经在com.globalmentor.android.app.Notifications.java创build了一组便利方法,它们允许您创build如下的通知声音:

 Notifications.notify(this); 

LED也会闪烁,如果您有振动许可,则会发生振动。 是的,通知栏中会显示一个通知图标,但会在几秒钟后消失。

此时您可能会意识到,由于通知无论如何都会消失,因此您可能在通知栏中有滚动的滚动消息。 你可以这样做:

 Notifications.notify(this, 5000, "This text will go away after five seconds."); 

这个class有很多其他的方便方法。 你可以从它的Subversion版本库下载整个库,并用Maven构build它。 它取决于globalmentor-core库 ,也可以使用Maven构build和安装。

我认为“通知声音”的概念是Android UI的一些错误。

Android预期的行为是使用标准通知来提醒用户。 如果您播放没有状态栏图标的通知声音,则会让用户感到困惑(“这是什么声音?这里没有图标,也许我有听力问题?”)。

例如,如何在通知上设置声音:为通知设置声音