Not allowed to change Do Not Disturb state, using AudioManager setRingerMode(int i) in Worker


I am using AudioManager and setRingerMode to adjust the ringer programmatically. This is done with a Worker.

public class SettingWorker extends Worker {

* Tag of the class
static final private String TAG = "SettingWorker";

Context mContext;

* Constructor of the worker
* @param context context of the application
* @param workerParams ..
public SettingWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
mContext = context;

public Result doWork() {
Logger.logD(TAG, "doWork(): finished");
return Result.success();

* method to set the sound setting as requested and found
* @param setting SND, SLT, VBR
private void setSetting(String setting) {

Logger.logD(TAG, "setSetting(): setting is " + setting);

AudioManager am = (AudioManager) mContext.getSystemService(mContext.AUDIO_SERVICE);
switch(setting) {
case "SLT":
am.adjustVolume(AudioManager.ADJUST_MUTE, AudioManager.FLAG_SHOW_UI);
case "VBR":
am.adjustVolume(AudioManager.ADJUST_MUTE, AudioManager.FLAG_SHOW_UI);
//TODO: perhaps let user decide the volume
case "SND":
am.adjustVolume(AudioManager.ADJUST_UNMUTE, AudioManager.FLAG_SHOW_UI);

I have added the needed permission to my manifest:

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

However, I still get the exception:

Caused by: java.lang.SecurityException: Not allowed to change Do Not Disturb state

I am not sure where the problem lies. Could somebody help me please?

I am making an app that needs to set the ringer mode to silent, when i run the AudioComponent.Ringer Mode Silent block an error occurs:
“Not allowed to change Do Not Disturb State”, both in companion and in apk.

I granted all the required permissions but still doesn’t work.
I’ve also tried to grant Access to Do not disturb state from the phone’s settings but i haven’t found my app in the list.

Tested with two phones: Samsung J7 pro and Samsung S8+, both with android 9
Aakil Working at The Next Hint