How to play an android notification sound

ninjasense picture ninjasense · Dec 14, 2010 · Viewed 224.9k times · Source

I was wondering how I could play a notification sound without playing it over the media stream. Right now I can do this via the media player, however I don't want it to play as a media file, I want it to play as a notification or alert or ringtone. heres an example of what my code looks like right now:

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

Answer

Phidius picture Phidius · Mar 8, 2012

If anyone's still looking for a solution to this, I found an answer at How to play ringtone/alarm sound in Android

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

You can change TYPE_NOTIFICATION to TYPE_ALARM, but you'll want to keep track of your Ringtone r in order to stop playing it... say, when the user clicks a button or something.