ninjasense
ninjasense

Reputation: 13856

How to play an android notification sound

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();

Upvotes: 191

Views: 269631

Answers (12)

Shubham Pandey
Shubham Pandey

Reputation: 209

To PLay the Phone ringtone while you get the notification use this

        val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)
        val r = RingtoneManager.getRingtone(applicationContext, notification)
        r.play())

You can use these methods in type

/**
* Type that refers to sounds that are used for the phone ringer.
*/
public static final int TYPE_RINGTONE = 1;

/**
 * Type that refers to sounds that are used for notifications.
 */
public static final int TYPE_NOTIFICATION = 2;

/**
 * Type that refers to sounds that are used for the alarm.
 */
public static final int TYPE_ALARM = 4;

/**
 * All types of sounds.
 */
public static final int TYPE_ALL = TYPE_RINGTONE | TYPE_NOTIFICATION | TYPE_ALARM;

Upvotes: 0

ΓDΛ
ΓDΛ

Reputation: 11060

I'm not sure if it will be useful or not, but I would like to share the Util class I use in my project.

class NotificationsUtil(private val context: Context,
                        private val channelName: String = "gi",
                        private val channelID: String,
                        private val channelDescription: String = "",
                        private val enableCustomSound: Boolean = false,
                        @IdRes rawNotificationSound: Int = -1) {


    private var notificationCompatBuilder: NotificationCompat.Builder? = null
    private var notificationManagerCompat: NotificationManagerCompat? = null
    private var soundUri: Uri? = null

    init {
        if (enableCustomSound) {
            soundUri = Uri.parse("android.resource://" + context.packageName + "/" + rawNotificationSound)
        }
    }


    fun createNotification(id: String, message: String, title: String, @IdRes notificationDrawable: Int): Notification? {
        notificationCompatBuilder = NotificationCompat.Builder(context, createNotificationChannel())
        notificationManagerCompat = NotificationManagerCompat.from(context)

        // val pendingIntent = PendingIntent.getActivity(context, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT)

        notificationCompatBuilder
                ?.setDefaults(Notification.DEFAULT_LIGHTS)
                ?.setSmallIcon(notificationDrawable)
                ?.setContentTitle(title)?.setContentText(message)
                ?.setPriority(NotificationCompat.PRIORITY_HIGH)
                ?.setAutoCancel(true)
                ?.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                ?.setColorized(true)
                ?.setOnlyAlertOnce(true)

        //   ?.setContentIntent(pendingIntent)
        if (enableCustomSound) {
            notificationCompatBuilder?.setSound(soundUri)
        }

        val notification = notificationCompatBuilder?.build()

        notification?.let { notificationManagerCompat?.notify(id.toInt(), it) }

        return notification


    }


    fun buildNotification(message: String, title: String, @IdRes notificationDrawable: Int): Notification? {
        notificationCompatBuilder = NotificationCompat.Builder(context, createNotificationChannel())
        notificationManagerCompat = NotificationManagerCompat.from(context)

        // val pendingIntent = PendingIntent.getActivity(context, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT)

        notificationCompatBuilder
                ?.setDefaults(Notification.DEFAULT_LIGHTS)
                ?.setSmallIcon(notificationDrawable)
                ?.setContentTitle(title)?.setContentText(message)
                ?.setPriority(NotificationCompat.PRIORITY_HIGH)
                ?.setAutoCancel(true)
                ?.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                ?.setColorized(true)
                ?.setOnlyAlertOnce(true)

        //   ?.setContentIntent(pendingIntent)
        if (enableCustomSound) {
            notificationCompatBuilder?.setSound(soundUri)
        }

        return notificationCompatBuilder?.build()
    }

    fun createNotificationWithPendingIntent(id: String, message: String, title: String, @IdRes notificationDrawable: Int, pendingIntent: PendingIntent): Notification? {
        notificationCompatBuilder = NotificationCompat.Builder(context, createNotificationChannel())
        notificationManagerCompat = NotificationManagerCompat.from(context)

        /* val pendingIntent = PendingIntent.getActivity(context, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT)*/

        notificationCompatBuilder
                ?.setDefaults(Notification.DEFAULT_LIGHTS)
                ?.setSmallIcon(notificationDrawable)
                ?.setContentTitle(title)?.setContentText(message)
                ?.setPriority(NotificationCompat.PRIORITY_HIGH)
                ?.setAutoCancel(true)
                ?.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                ?.setColorized(true)
                ?.setOnlyAlertOnce(true)
                ?.setContentIntent(pendingIntent)

        if (enableCustomSound) {
            notificationCompatBuilder?.setSound(soundUri)
        }

        val notification = notificationCompatBuilder?.build()

        notification?.let { notificationManagerCompat?.notify(id.toInt(), it) }

        return notification

    }

    fun createExpandableNotification(id: String, message: String, title: String, @IdRes notificationDrawable: Int): Notification? {
        notificationCompatBuilder = NotificationCompat.Builder(context, createNotificationChannel())
        notificationManagerCompat = NotificationManagerCompat.from(context)

        notificationCompatBuilder?.setSmallIcon(notificationDrawable)
                ?.setContentTitle(title)
                ?.setContentText(message)
                ?.setDefaults(Notification.DEFAULT_LIGHTS)
                ?.setPriority(NotificationCompat.PRIORITY_HIGH)
                ?.setAutoCancel(true)
                ?.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                ?.setColorized(true)
                ?.setStyle(NotificationCompat.BigTextStyle().bigText(message))
                ?.setOnlyAlertOnce(true)

        if (enableCustomSound) {
            notificationCompatBuilder?.setSound(soundUri)
        }

        val notification = notificationCompatBuilder?.build()

        notification?.let { notificationManagerCompat?.notify(id.toInt(), it) }

        return notification

    }

    fun createExpandableNotificationWithPendingIntent(id: String, message: String, title: String, @IdRes notificationDrawable: Int, pendingIntent: PendingIntent): Notification? {
        notificationCompatBuilder = NotificationCompat.Builder(context, createNotificationChannel())
        notificationManagerCompat = NotificationManagerCompat.from(context)

        notificationCompatBuilder?.setSmallIcon(notificationDrawable)
                ?.setContentTitle(title)
                ?.setContentText(message)
                ?.setDefaults(Notification.DEFAULT_LIGHTS)
                ?.setPriority(NotificationCompat.PRIORITY_HIGH)
                ?.setAutoCancel(true)
                ?.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                ?.setColorized(true)
                ?.setStyle(NotificationCompat.BigTextStyle().bigText(message))
                ?.setOnlyAlertOnce(true)
                ?.setContentIntent(pendingIntent)

        if (enableCustomSound) {
            notificationCompatBuilder?.setSound(soundUri)
        }

        val notification = notificationCompatBuilder?.build()

        notification?.let { notificationManagerCompat?.notify(id.toInt(), it) }

        return notification

    }

    private fun createNotificationChannel(): String {


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            val name = channelName
            val description = channelDescription
            val audioAttributes = AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .build()

            val notificationChannel = NotificationChannel(channelID, name, NotificationManager.IMPORTANCE_HIGH)
            if (enableCustomSound) {
                notificationChannel.setSound(soundUri, audioAttributes)
            }
            notificationChannel.description = description
            notificationChannel.enableLights(true)
            notificationChannel.lightColor = Color.MAGENTA
            val notificationManager = context.getSystemService(NotificationManager::class.java)
            notificationManager?.createNotificationChannel(notificationChannel)

        }

        return channelID

    }

}

Upvotes: 0

Garret Wilson
Garret Wilson

Reputation: 21356

I had pretty much the same question. After some research, I think that if you want to play the default system "notification sound", you pretty much have to display a notification and tell it to use the default sound. And there's something to be said for the argument in some of the other answers that if you're playing a notification sound, you should be presenting some notification message as well.

However, a little tweaking of the notification API and you can get close to what you want. You can display a blank notification and then remove it automatically after a few seconds. I think this will work for me; maybe it will work for you.

I've created a set of convenience methods in com.globalmentor.android.app.Notifications.java which allow you create a notification sound like this:

Notifications.notify(this);

The LED will also flash and, if you have vibrate permission, a vibration will occur. Yes, a notification icon will appear in the notification bar but will disappear after a few seconds.

At this point you may realize that, since the notification will go away anyway, you might as well have a scrolling ticker message in the notification bar; you can do that like this:

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

There are many other convenience methods in this class. You can download the whole library from its Subversion repository and build it with Maven. It depends on the globalmentor-core library, which can also be built and installed with Maven.

Upvotes: 2

Milind Chaudhary
Milind Chaudhary

Reputation: 1730

Set sound to notification channel

        Uri alarmUri = Uri.fromFile(new File(<path>));

        AudioAttributes attributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_ALARM)
                .build();

        channel.setSound(alarmUri, attributes);

Upvotes: 0

dsc clg
dsc clg

Reputation: 31

Intent intent = new Intent(this, MembersLocation.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("type",type);
    intent.putExtra("sender",sender);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    String channelId = getString(R.string.default_notification_channel_id);

    Uri Emergency_sound_uri=Uri.parse("android.resource://"+getPackageName()+"/raw/emergency_sound");
   // Uri Default_Sound_uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    if(type.equals("emergency"))
    {
        playSound=Emergency_sound_uri;
    }
    else
    {
        playSound= Settings.System.DEFAULT_NOTIFICATION_URI;
    }

    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.drawable.ic_notification)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setSound(playSound, AudioManager.STREAM_NOTIFICATION)
                    .setAutoCancel(true)
                    .setColor(getColor(R.color.dark_red))
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setContentIntent(pendingIntent);

   // notificationBuilder.setOngoing(true);//for Android notification swipe delete disabling...

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_HIGH);
        AudioAttributes att = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                .build();
        channel.setSound(Emergency_sound_uri, att);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }
    }

    if (notificationManager != null) {
        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}

Upvotes: 2

aga
aga

Reputation: 29416

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.

Upvotes: 50

Ragu
Ragu

Reputation: 233

Try this:

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

Upvotes: 20

Phidius
Phidius

Reputation: 5237

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.

Upvotes: 475

Rob Riddle
Rob Riddle

Reputation: 3584

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());

Upvotes: 208

copolii
copolii

Reputation: 14506

It's been a while since your question, but ... Have you tried setting the Audio stream type?

mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);

It must be done before prepare.

Upvotes: 9

cognitio
cognitio

Reputation: 691

I think the concept of "notification sound" is someway wrong for Android UI.

The Android expected behaviour is to use the standard Notification to alert the user. If you play a notification sound without the status bar icon, you get the user confused ("what was that sound? there is no icon here, maybe I have hearing problems?").

How to set sound on a notification is, for example, here: Setting sound for notification

Upvotes: 1

Valentin Rocher
Valentin Rocher

Reputation: 11669

You can use Notification and NotificationManager to display the notification you want. You can then customize the sound you want to play with your notification.

Upvotes: 0

Related Questions