4

How can I set sound for notification for my android application. In my application notification will be shown after 30 seconds. I want to give options for this alerts such as silent mode, vibration mode and an option to select from the available tones from the device. I am using the preference screen to show the settings menu. I want to to set the notification ring type application specific. Is there any way to establish this..

Dijo David
  • 6,175
  • 11
  • 35
  • 46

2 Answers2

11

How to Set a Custom Sound for an Android Notification

Place a .mp3 or .wav file in your res/raw directory such as "notification_sound.mp3" as in the example below (the filename must not use capital letters).

Set the Notification.sound when you create your Notification, like this:

final int iconResId = R.drawable.my_icon;
final int soundResId = R.raw.notification_sound;
final Notification notification =
    new Notification(iconResId, tickerText, System.currentTimeMillis());
final String packageName = context.getPackageName();
notification.sound =
    Uri.parse("android.resource://" + packageName + "/" + soundResId);

Optionally, add vibration to your Notification:

notification.defaults = Notification.DEFAULT_VIBRATE;
David Manpearl
  • 12,362
  • 8
  • 55
  • 72
2

http://developer.android.com/reference/android/app/Notification.Builder.html#setSound(android.net.Uri)

Notification.Builder.setSound();

Use a ringtone preference in the preference activity to get the URI of the selected sound.

AverageMarcus
  • 903
  • 1
  • 9
  • 26
  • Thank you Marcus. However when I try to get the id of the ringtone by setting an onclick listener for the ringtone preference, I m getting the following errors: 03-01 10:49:59.021: DEBUG/MediaPlayer(308): Couldn't open file on client side, trying server side 03-01 10:49:59.031: ERROR/MediaPlayerService(34): Couldn't open fd for content://settings/system/notification_sound 03-01 10:49:59.031: ERROR/MediaPlayer(308): Unable to to create media player 03-01 10:49:59.041: ERROR/RingtoneManager(308): Failed to open ringtone content://settings/system/notification_sound – Dijo David Mar 01 '11 at 05:29
  • 2
    notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, ringtoneId); – Dijo David Mar 14 '11 at 05:54
  • 2
    You can also reference sound resources you bundle with your application: notification.sound = Uri.parse("android.resource://com.company.package/" + soundResourceId); – Jerry Brady Apr 15 '11 at 14:22