100

I'm trying to get a default vibrate and sound alert when my notification comes in, but so far no luck. I imagine it's something to do with the way I set the defaults, but I'm unsure of how to fix it. Any thoughts?

public void connectedNotify() {
    Integer mId = 0;
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_notify)
            .setContentTitle("Device Connected")
            .setContentText("Click to monitor");

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

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent =     
          PendingIntent.getActivity(getApplicationContext(), 
          0, 
          resultIntent,  
          PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    mBuilder.setOngoing(true);
    Notification note = mBuilder.build();
    note.defaults |= Notification.DEFAULT_VIBRATE;
    note.defaults |= Notification.DEFAULT_SOUND;
    NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(mId, note);

}
Dave Moore
  • 1,432
  • 4
  • 12
  • 17
  • 3
    All the answers only reiterate some variation of the code you already have, and none of them answers the question in my opinion. Your code looks fine, AFAICT. Most likely, you're just missing `android.permission.VIBRATE` in AndroidManifest.xml. – Olaf Dietsche Feb 26 '16 at 20:11
  • To whom that may apply solutions in this thread and still does not have any vibration on notifications, you may need to enable vibration of your notification channel first. Take a look at this: https://stackoverflow.com/a/47646166/8551764 – Mostafa Arian Nejad Mar 04 '20 at 06:37

9 Answers9

219

Some dummy code might help you.

   private static NotificationCompat.Builder buildNotificationCommon(Context _context, .....) {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(_context)
            .setWhen(System.currentTimeMillis()).......;
     //Vibration
        builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
 
     //LED
        builder.setLights(Color.RED, 3000, 3000);
 
     //Ton
        builder.setSound(Uri.parse("uri://sadfasdfasdf.mp3"));
 
    return builder;
   }

Add below permission for Vibration in AndroidManifest.xml file

<uses-permission android:name="android.permission.VIBRATE" />
starball
  • 20,030
  • 7
  • 43
  • 238
TeeTracker
  • 7,064
  • 8
  • 40
  • 46
  • 117
    +1 `vibrate` feature requires `` permission – ashakirov Mar 29 '14 at 14:11
  • 1
    In some cases you should use hex color argb format, like 0xffffffff, instead of Color.White, because there's is a small chance of user device use Color(RGB) for a ARGB param and you will get the wrong color. This Happened with me. – Beto Caldas Oct 24 '14 at 19:47
  • 60
    The vibration now has a delay of 1000 ms. If you set the first one to 0, it will go off instantly. It's a { delay, vibrate, sleep, vibrate, sleep } pattern. – Tom Apr 30 '15 at 11:22
  • 11
    I haven't needed to add `` to work. – Iqbal Feb 26 '16 at 08:22
  • 1
    Anyone knows how to use setSound on API 26? – Rodrigo Manguinho Sep 03 '17 at 01:31
61

An extension to TeeTracker's answer,

to get the default notification sound you can do as follows

NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_notify)
            .setContentTitle("Device Connected")
            .setContentText("Click to monitor");

Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(alarmSound);

This will give you the default notification sound.

nikoo28
  • 2,961
  • 1
  • 29
  • 39
37

Notification Vibrate

mBuilder.setVibrate(new long[] { 1000, 1000});

Sound

mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);

for more sound option

Community
  • 1
  • 1
Cristiana Chavez
  • 11,349
  • 5
  • 55
  • 54
14

Its work fine to me,You can try it.

 protected void displayNotification() {

        Log.i("Start", "notification");

      // Invoking the default notification service //
        NotificationCompat.Builder  mBuilder =
                new NotificationCompat.Builder(this);
        mBuilder.setAutoCancel(true);

        mBuilder.setContentTitle("New Message");
        mBuilder.setContentText("You have "+unMber_unRead_sms +" new message.");
        mBuilder.setTicker("New message from PayMe..");
        mBuilder.setSmallIcon(R.drawable.icon2);

      // Increase notification number every time a new notification arrives //
        mBuilder.setNumber(unMber_unRead_sms);

      // Creates an explicit intent for an Activity in your app //

        Intent resultIntent = new Intent(this, FreesmsLog.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(FreesmsLog.class);

      // Adds the Intent that starts the Activity to the top of the stack //
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);

      //  mBuilder.setOngoing(true);
        Notification note = mBuilder.build();
        note.defaults |= Notification.DEFAULT_VIBRATE;
        note.defaults |= Notification.DEFAULT_SOUND;

        mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
      // notificationID allows you to update the notification later on. //
        mNotificationManager.notify(notificationID, mBuilder.build());

    }
Selim Raza
  • 497
  • 7
  • 16
10

This is a simple way to call notification by using default vibrate and sound from system.

private void sendNotification(String message, String tick, String title, boolean sound, boolean vibrate, int iconID) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);
    Notification notification = new Notification();

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);

    if (sound) {
        notification.defaults |= Notification.DEFAULT_SOUND;
    }

    if (vibrate) {
        notification.defaults |= Notification.DEFAULT_VIBRATE;
    }

    notificationBuilder.setDefaults(notification.defaults);
    notificationBuilder.setSmallIcon(iconID)
            .setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(true)
            .setTicker(tick)
            .setContentIntent(pendingIntent);

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

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

Add vibrate permission if you are going to use it:

<uses-permission android:name="android.permission.VIBRATE"/>

Good luck,'.

Maher Abuthraa
  • 17,493
  • 11
  • 81
  • 103
  • Can someone tell me why vibration is not working when phone is in call ? OR can we make notification to force vibrate even in phone is in call –  Feb 08 '17 at 11:20
  • It helped me notificationBuilder.setDefaults(notification.defaults); – Saveen Mar 15 '17 at 12:12
  • @user526206, I dont know. I have never tested that. You can open new question since this has nothing with notification behavior. – Maher Abuthraa Mar 15 '17 at 15:01
7

I m using the followung code and its working fine for me .

private void sendNotification(String msg) {
    Log.d(TAG, "Preparing to send notification...: " + msg);
    mNotificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class), 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            this).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("GCM Notification")
            .setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setContentText(msg);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    Log.d(TAG, "Notification sent successfully.");
}
Suresh kumar
  • 789
  • 10
  • 13
5

To support SDK version >= 26, you also should build NotificationChanel and set a vibration pattern and sound there. There is a Kotlin code sample:

    val vibrationPattern = longArrayOf(500)
    val soundUri = "<your sound uri>"

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationManager =    
                 getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val attr = AudioAttributes.Builder()
                        .setUsage(AudioAttributes.USAGE_ALARM)
                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                        .build()
            val channelName: CharSequence = Constants.NOTIFICATION_CHANNEL_NAME
            val importance = NotificationManager.IMPORTANCE_HIGH
            val notificationChannel =
                NotificationChannel(Constants.NOTIFICATION_CHANNEL_ID, channelName, importance)
                notificationChannel.enableLights(true)
                notificationChannel.lightColor = Color.RED
                notificationChannel.enableVibration(true)
                notificationChannel.setSound(soundUri, attr)
                notificationChannel.vibrationPattern = vibrationPattern
                notificationManager.createNotificationChannel(notificationChannel)
    }

And this is the builder:

 with(NotificationCompat.Builder(applicationContext, Constants.NOTIFICATION_CHANNEL_ID)) {
        setContentTitle("Some title")
        setContentText("Some content")
        setSmallIcon(R.drawable.ic_logo)
        setAutoCancel(true)    
        setVibrate(vibrationPattern)
        setSound(soundUri)
        setDefaults(Notification.DEFAULT_VIBRATE)
        setContentIntent(
            // this is an extension function of context you should build
            // your own pending intent and place it here
            createNotificationPendingIntent(
                Intent(applicationContext, target).apply {
                    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                }
            )
        )

        return build()
    }

Be sure your AudioAttributes are chosen right to read more here.

MeLean
  • 3,092
  • 6
  • 29
  • 43
2

For Kotlin you can Try this.

var builder = NotificationCompat.Builder(this,CHANNEL_ID)
     .setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000))
     .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
Stypox
  • 963
  • 11
  • 18
2

// set notification audio

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