How to play ringtone/alarm sound in Android
Solution 1:
You can simply play a setted ringtone with this:
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
Solution 2:
If a user has never set an alarm on their phone, the TYPE_ALARM can return null. You can account for this with:
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if(alert == null){
// alert is null, using backup
alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// I can't see this ever being null (as always have a default notification)
// but just incase
if(alert == null) {
// alert backup is null, using 2nd backup
alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
Solution 3:
This is the way I've done:
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), notification);
mp.start();
It is similar to markov00's way, but uses MediaPlayer instead of Ringtone which prevents interrupting other sounds, like music, that might already be playing in the background.
Solution 4:
Your example is basically what I'm using. It never works on the emulator, however, because the emulator doesn't have any ringtones by default, and content://settings/system/ringtone
doesn't resolve to anything playable. It works fine on my actual phone.
Solution 5:
This works fine:
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
MediaPlayer thePlayer = MediaPlayer.create(getApplicationContext(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
try {
thePlayer.setVolume((float) (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) / 7.0)),
(float) (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) / 7.0)));
} catch (Exception e) {
e.printStackTrace();
}
thePlayer.start();