How to play an android notification sound
If you want a default notification sound to be played, then you can use setDefaults(int) method of NotificationCompat.Builder
class:
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);
I believe that's the easiest way to accomplish your task.
You can now do this by including the sound when building a notification rather than calling the sound separately.
//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());
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.