How do I turn on/off 'do not disturb' (dnd) programmatically in Android? Is was hoping this would give me something but it doesn't:
Settings.System.putInt(getContentResolver(), Settings.System.DO_NOT_DISTURB, 1);
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.
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.
For those struggling with LG G4, there is a workaround.
LG didn't setup the settings option to grant
permission.ACCESS_NOTIFICATION_POLICY
Therefore it crashes when it receives
ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS
However, LG did setup the option to grant
permission.BIND_NOTIFICATION_LISTENER_SERVICE
And once this permission is granted, so is
permission.ACCESS_NOTIFICATION_POLICY
(at least on LG G4). This option is under Settings->General->Security->Notification access. For the user to be able to grant this permission, your app needs to request for it. This is done by declaring your service, assuming you have one for your app, as follows in the manifest:
<service android:name="myService"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>