Search code examples
androidnotificationsvibration

Android: Vibrate in accordance with selection checked in Sound Settings > General


How can I do that? My current code is shown below:

final NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.stat_sys_warning, System.currentTimeMillis());    
notification.defaults |= Notification.DEFAULT_SOUND;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent notificationIntent = new Intent(Intent.ACTION_MAIN, Uri.EMPTY, context, Activity....class).putExtra(...);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, text, contentIntent);
manager.notify(1, notification);

Solution

  • See the documentation for Notification#DEFAULT_ALL, as well as DEFAULT_VIBRATE below it. You are not currently indicating that you want the DEFAULT_VIBRATE configuration (your current code only selects DEFAULT_SOUND.

    notification.defaults |= Notification.DEFAULT_VIBRATE;
    

    If you want to use the device-default settings for both Sound and Vibrate, you can do that using bitwise OR:

    notification.defaults |= Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;
    

    Alternatively, you can specify that you want to use all the default notification settings:

    notification.defaults |= Notification.DEFAULT_ALL;
    

    In addition to that, you also need to make sure that you have the VIBRATE permission specified in your AndroidManifest.xml file:

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