168

I've used the newer NotificationCompat builder and I can't get the notification to make a sound. It will vibrate and flash the light. The android documentation says to set a style which I've done with:

builder.setStyle(new NotificationCompat.InboxStyle());

But no sound?

The full code:

NotificationCompat.Builder builder =  
        new NotificationCompat.Builder(this)  
        .setSmallIcon(R.drawable.ic_launcher)  
        .setContentTitle("Notifications Example")  
        .setContentText("This is a test notification");  


Intent notificationIntent = new Intent(this, MenuScreen.class);  

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,   
        PendingIntent.FLAG_UPDATE_CURRENT);  

builder.setContentIntent(contentIntent);  
builder.setAutoCancel(true);
builder.setLights(Color.BLUE, 500, 500);
long[] pattern = {500,500,500,500,500,500,500,500,500};
builder.setVibrate(pattern);
builder.setStyle(new NotificationCompat.InboxStyle());
// Add as notification  
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
manager.notify(1, builder.build());  
pkamb
  • 33,281
  • 23
  • 160
  • 191
James MV
  • 8,569
  • 17
  • 65
  • 96

20 Answers20

271

What was missing from my previous code:

Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(alarmSound);
James MV
  • 8,569
  • 17
  • 65
  • 96
167

Just put your sound file in the Res\raw\siren.mp3 folder, then use this code:

For Custom Sound:

Notification notification = builder.build();
notification.sound = Uri.parse("android.resource://"
            + context.getPackageName() + "/" + R.raw.siren);

For Default Sound:

notification.defaults |= Notification.DEFAULT_SOUND;

For Custom Vibrate:

long[] vibrate = { 0, 100, 200, 300 };
notification.vibrate = vibrate;

For Default Vibrate:

notification.defaults |= Notification.DEFAULT_VIBRATE;
ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
Mitul Goti
  • 2,657
  • 1
  • 22
  • 19
55

Another way for the default sound

builder.setDefaults(Notification.DEFAULT_SOUND);
hayden
  • 2,643
  • 17
  • 21
14

On Oreo (Android 8) and above it should be done for custom sound in this way (notification channels):

Uri soundUri = Uri.parse(
                         "android.resource://" + 
                         getApplicationContext().getPackageName() +
                         "/" + 
                         R.raw.push_sound_file);

AudioAttributes audioAttributes = new AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .setUsage(AudioAttributes.USAGE_ALARM)
            .build();

// Creating Channel
NotificationChannel channel = new NotificationChannel("YOUR_CHANNEL_ID",
                                                      "YOUR_CHANNEL_NAME",
                                                      NotificationManager.IMPORTANCE_HIGH);
channel.setSound(soundUri, audioAttributes);

((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                                           .createNotificationChannel(notificationChannel);
oxied
  • 1,773
  • 19
  • 14
13

USE Can Codeding

 String en_alert, th_alert, en_title, th_title, id;
 int noti_all, noti_1, noti_2, noti_3, noti_4 = 0, Langage;

 class method
 Intent intent = new Intent(context, ReserveStatusActivity.class);
 PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

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


 intent = new Intent(String.valueOf(PushActivity.class));
 intent.putExtra("message", MESSAGE);
 TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
 stackBuilder.addParentStack(PushActivity.class);
 stackBuilder.addNextIntent(intent);
 // PendingIntent pendingIntent =
 stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

 //      android.support.v4.app.NotificationCompat.BigTextStyle bigStyle = new NotificationCompat.BigTextStyle();
 //        bigStyle.bigText((CharSequence) context);



 notification = new NotificationCompat.Builder(context)
    .setSmallIcon(R.mipmap.ic_launcher)
    .setContentTitle(th_title)
    .setContentText(th_alert)
    .setAutoCancel(true)

 // .setStyle(new Notification.BigTextStyle().bigText(th_alert)  ตัวเก่า
 //

 .setStyle(new NotificationCompat.BigTextStyle().bigText(th_title))

    .setStyle(new NotificationCompat.BigTextStyle().bigText(th_alert))

    .setContentIntent(pendingIntent)
    .setNumber(++numMessages)


    .build();

 notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

 notificationManager.notify(1000, notification);
Joaquin Iurchuk
  • 5,499
  • 2
  • 48
  • 64
Pong Petrung
  • 1,437
  • 17
  • 14
10

Just put the below simple code :

notification.sound = Uri.parse("android.resource://"
        + context.getPackageName() + "/" + R.raw.sound_file);

For Default Sound:

notification.defaults |= Notification.DEFAULT_SOUND;
Denny Sharma
  • 3,015
  • 1
  • 13
  • 14
9

You have to use RingtoneManager

private static final int MY_NOTIFICATION_ID = 1;
    private NotificationManager notificationManager;
    private Notification myNotification;

    private final String myBlog = "http://niravranpara.blogspot.com/";

Code for noficationmanager with alarm ringtone you can also set ring tone RingtoneManager.TYPE_RINGTONE

notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri
                        .parse(myBlog));
                  PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                    Notification note = new Notification(R.drawable.ic_launcher, "Alarm", System.currentTimeMillis());
                    note.setLatestEventInfo(getApplicationContext(), "Alarm", "sound" + " (alarm)", pi);
                    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
                    if(alarmSound == null){
                        alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
                        if(alarmSound == null){
                            alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                        }
                    }
                    note.sound = alarmSound;
                    note.defaults |= Notification.DEFAULT_VIBRATE;
                    note.flags |= Notification.FLAG_AUTO_CANCEL;
                    notificationManager.notify(MY_NOTIFICATION_ID, note);
Nirav Ranpara
  • 13,753
  • 3
  • 39
  • 54
  • Sorry this isn't how you do it for the newer NotificationCompat.Builder. – James MV Apr 06 '13 at 20:05
  • Notification can be created with NotificationCompat.Builder.build() function and it's OK to take the return value of build() and modify its values before passing to NotificationManager.notify. It doesn't make much sense, but it's perfectly OK. – holgac Jun 23 '13 at 15:08
8

You can make a function:

public void playNotificationSound() 
{
    try
    {

        Uri alarmSound = `Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + MyApplication.getInstance().getApplicationContext().getPackageName() + "/raw/notification");`
        Ringtone r = RingtoneManager.getRingtone(MyApplication.getInstance().getApplicationContext(), alarmSound);
        r.play();
    }
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

Call this function when you receive notification.

Here raw is the folder in res and the notification is the sound file in raw folder.

Saravanan Sachi
  • 2,572
  • 5
  • 33
  • 42
MageNative
  • 682
  • 5
  • 14
8

In Android OREO or later version enter image description here After Register the channel with the system; you can't change the importance or other notification behaviors after this of same Channel (Before Uninstalling App)

private void createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

channel.setSound(Settings.System.DEFAULT_NOTIFICATION_URI,audioAttributes);

Priority also matters Most Here Set Notification Priority to high by using

User-visible importance level Importance (Android 8.0 and higher)

1)Urgent Makes a sound and appears as a heads-up notification-->IMPORTANCE_HIGH
2)High Makes a sound -->IMPORTANCE_DEFAULT
3)Medium No sound -->IMPORTANCE_LOW
4)Low No sound and does not appear in the status bar->IMPORTANCE_MIN

same works in same order Priority (Android 7.1 and lower)

1)PRIORITY_HIGH or PRIORITY_MAX

2)PRIORITY_DEFAULT

3)PRIORITY_LOW

4)PRIORITY_MIN

Akash Anaghan
  • 431
  • 6
  • 8
  • 3
    "*you can't change the importance or other notification behaviors after this of same Channel*". Needed to uninstall app to make work, this action deleted channel's info from device as result. – Ely Dantas Jun 13 '19 at 01:11
6

You have to use builder.setSound

Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class);  

                PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0, notificationIntent,   
                        PendingIntent.FLAG_UPDATE_CURRENT);  

                builder.setContentIntent(contentIntent);  
                builder.setAutoCancel(true);
                builder.setLights(Color.BLUE, 500, 500);
                long[] pattern = {500,500,500,500,500,500,500,500,500};
                builder.setVibrate(pattern);
                builder.setStyle(new NotificationCompat.InboxStyle());
                 Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
                    if(alarmSound == null){
                        alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
                        if(alarmSound == null){
                            alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                        }
                    }

                // Add as notification  
                NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
             builder.setSound(alarmSound);
                manager.notify(1, builder.build());  
Nirav Ranpara
  • 13,753
  • 3
  • 39
  • 54
5

1st put "yourmp3file".mp3 file in the raw folder(ie inside Res folder)

2nd in your code put..

Notification noti = new Notification.Builder(this)
.setSound(Uri.parse("android.resource://" + v.getContext().getPackageName() + "/" + R.raw.yourmp3file))//*see note

This is what i put inside my onClick(View v) as only "context().getPackageName()" wont work from there as it wont get any context

user3833732
  • 886
  • 9
  • 14
4
private void showNotification() {

    // intent triggered, you can add other intent for other actions
    Intent i = new Intent(this, MainActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, i, 0);

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

    // this is it, we'll build the notification!
    // in the addAction method, if you don't want any icon, just set the first param to 0
    Notification mNotification = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {

        mNotification = new Notification.Builder(this)

           .setContentTitle("Wings-Traccar!")
           .setContentText("You are punched-in for more than 10hrs!")
           .setSmallIcon(R.drawable.wingslogo)
           .setContentIntent(pIntent)
           .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
           .addAction(R.drawable.favicon, "Goto App", pIntent)
           .build();

    }

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // If you want to hide the notification after it was selected, do the code below
    // myNotification.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(0, mNotification);
}

call this function wherever you want. this worked for me

Krishna Vyas
  • 1,009
  • 8
  • 25
1
notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
0

by Notification.builder class instance (builder) that is given below you can play default sound on notification:

builder.setDefaults(Notification.DEFAULT_SOUND);
mix3d
  • 4,122
  • 2
  • 25
  • 47
Vishal Sharma
  • 1,051
  • 2
  • 8
  • 15
0

// set notification audio (Tested upto android 10)

builder.setDefaults(Notification.DEFAULT_VIBRATE);
//OR 
builder.setDefaults(Notification.DEFAULT_SOUND);
Mayuri Khinvasara
  • 1,437
  • 1
  • 16
  • 12
0
Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user);

    btn= findViewById(R.id.btn); 

   btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            notification();
        }
    });
  }   



private void notification() {
    NotificationCompat.Builder builder= new 
    NotificationCompat.Builder(this);
    builder.setAutoCancel(true);
    builder.setContentTitle("Work Progress");
    builder.setContentText("Submit your today's work progress");
    builder.setSmallIcon(R.drawable.ic_email_black_24dp);
    Intent intent=new Intent(this, WorkStatus.class);
    PendingIntent pendingIntent= PendingIntent.getActivity(this, 1, intent, 
    PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);
    builder.setDefaults(Notification.DEFAULT_VIBRATE);
    builder.setDefaults(Notification.DEFAULT_SOUND);

    NotificationManager notificationManager= (NotificationManager) 
    getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(1, builder.build());
}

It is complete notification with sound and vibrates

Giuseppe Garassino
  • 2,272
  • 1
  • 27
  • 47
0

Don't depends on builder or notification. Use custom code for vibrate.

public static void vibrate(Context context, int millis){
    try {
        Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            v.vibrate(VibrationEffect.createOneShot(millis, VibrationEffect.DEFAULT_AMPLITUDE));
        } else {
            v.vibrate(millis);
        }
    }catch(Exception ex){
    }
}
0

Several answers discuss the use of NotificationChannel.setSound() for Oreo (Android 8, api 26) and above, and that once a channel is created, it cannot be changed.

What I hadn't realised it that when AndroidStudio runs your app and performs an "Install" step, it appears not to uninstall the previous version and its NotificationChannel first. Hence, changing something (e.g. the sound) and simply re-running will not work. You need to explicitly uninstall the app first, before running it again.

Dashman
  • 1
  • 1
0

This line for sound

notification.setDefaults(Notification.DEFAULT_SOUND)

Example

private fun createNotification()  {
    val downloadLogo = BitmapFactory.decodeResource(applicationContext.resources, R.drawable.download)
    val notificationManager = createNotificationChannel()
    val notification = NotificationCompat.Builder(applicationContext, "CHANNEL_ID")
        .setSmallIcon(R.drawable.download)
        .setContentTitle("Download")
        .setContentText("Download Successfully")
        .setLargeIcon(downloadLogo)

    notification.setDefaults(Notification.DEFAULT_SOUND)
    notificationManager.notify(0, notification.build())
}


private fun createNotificationChannel():NotificationManager {
    val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val name = applicationContext.getString(R.string.channel_name)
        val descriptionText = applicationContext.getString(R.string.channel_description)
        val importance = NotificationManager.IMPORTANCE_DEFAULT
        val channel = NotificationChannel("CHANNEL_ID", name, importance).apply {
            description = descriptionText
        }
        notificationManager.createNotificationChannel(channel)
    }
    return notificationManager
}
Hamdy Abd El Fattah
  • 1,405
  • 1
  • 16
  • 16
-1

You can do the following:

MediaPlayer mp;
mp =MediaPlayer.create(Activity_Order_Visor_Atender.this, R.raw.ok);         
mp.start();

You create a packages between your resources with the name of raw and there you keep your sounds then you just call it.

Sasikumar Murugesan
  • 4,412
  • 10
  • 51
  • 74