Search code examples
androidalarmmanagerandroid-audiomanager

How to completely set ringer mode to silent?


I'm trying to make an app that will set the ringer mode to silent automatically by using AlarmManager. It's running but not working as expected.

@Override
public void onReceive(Context context, Intent intent) {
    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}

Based on the Android documentation:

RINGER_MODE_SILENT - Ringer mode that will be silent and will not vibrate. (This overrides the vibrate setting.)

But I found that my phone still vibrating. It just set the Do Not Disturb on and change the ringer mode to vibrate. I have tried to set it to RINGER_MODE_NORMAL and RINGER_MODE_VIBRATE and it works but not with RINGER_MODE_SILENT. I already give my app access to Do Not Disturb and use these permissions:

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

Is there any wrong or missing steps?


Solution

  • Finally found a workaround for this problem. It seems that android still considers the phone in Silent Mode if the Do Not Disturb is on, even the ringer mode is set to Normal Mode manually. So, I need to set the ringer mode to Normal Mode first, wait it for 1 second, and then set to Silent Mode again.

    if(audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
            audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
    }
    
    // Wait for 1 second
    // Direct changing won't set the Do Not Disturb on
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    
    audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);