Android how to turn on do not disturb (dnd) programmatically

Just improving the answer from Jordan Parsons. To set the priority you need a permission that can only be obtained by asking the user opening an Activity. An activity will be prompted asking if you want to enable the permission for Do Not Disturb to you application.

This Activity can be opened this way:

 NotificationManager mNotificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);

 // Check if the notification policy access has been granted for the app.
 if (!mNotificationManager.isNotificationPolicyAccessGranted()) {
     Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
     startActivity(intent);
 }

After granting this permission, this setting can be changed.


I found this solution:

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE);

It requires:

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

Which as far as I can tell does not pop up a request dialog when doing requestPermissions(). It has to be granted through the settings menu Settings -> Sound & Notifcation -> Do Not Disturb Access.

This is on SDK 23 Marshmallow.

Tags:

Android