0

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;
    }

    @NonNull
    @Override
    public Result doWork() {        
        setSetting("SLT");    
        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.setRingerMode(AudioManager.RINGER_MODE_SILENT);
                am.adjustVolume(AudioManager.ADJUST_MUTE, AudioManager.FLAG_SHOW_UI);
            case "VBR":
                am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
                am.adjustVolume(AudioManager.ADJUST_MUTE, AudioManager.FLAG_SHOW_UI);
                //TODO: perhaps let user decide the volume
            case "SND":
                am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                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?

  • 1
    Does this answer your question? [In Android 7 (API level 24) my app is not allowed to mute phone (set ringer mode to silent)](https://stackoverflow.com/questions/39151453/in-android-7-api-level-24-my-app-is-not-allowed-to-mute-phone-set-ringer-mode) – user3486184 Jul 07 '21 at 21:11

0 Answers0