Thanks for your answers, here is a little more detail.
To be able to set ringer mode to silent, you must ask permission to access notification policy (like @ucsunil said).
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
Then, check if you have this permission. If you do not, open the settings for "Do Not Disturb access" for your app:
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !notificationManager.isNotificationPolicyAccessGranted()) {
Intent intent = new Intent(
android.provider.Settings
.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}
When you run startActivity(), Android opens the Do Not Disturb access settings for your app.
What confused me, was that the way to ask for this permission is completely different from other permissions.
Just for reference, here is the way to ask for permission READ_CONTACTS:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ActivityCompat.checkSelfPermission(activity,
Manifest.permission.READ_CONTACTS)
== PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(activity,
new String[]{ Manifest.permission.READ_CONTACTS },
REQUEST_CODE_READ_CONTACTS);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…