Android don't play sound effect when Do not Disturb is on

1k Views Asked by At

I'm using the MediaPlayer to play a sound effect. However when DnD (Do not Disturb) is turned on it still plays the sound.

This is my code:

public static void playSound(Context context, @RawRes int soundId)
{
    MediaPlayer mp = MediaPlayer.create(context, soundId);
    mp.start();
    mp.setOnCompletionListener(mediaPlayer -> {
        mp.release();
    });
}

I tried setting the audio stream type like this, but then my sound won't play at all:

mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);

How to initialize the media player so my sound does the following:

  • DnD off: play
  • DnD Total silence: don't play
  • DnD Alarms only: don't play
  • DnD Priority only: don't play

Currently the sound is only silenced when DnD is in Total silence mode.

The only thing I can think of now is to retrieve the DnD setting and only play the sound if it's off. But that seems more like a work-around to me.

1

There are 1 best solutions below

2
On

You can get the status of the Do not disturb mode first like this

 try {
        Settings.Global.getInt(getContentResolver(), "zen_mode"); // this return an int
    } catch (Settings.SettingNotFoundException e) {
        e.printStackTrace();
    }

That statement returns an int value that you can work with like this

  • 0 - If DnD is off.
  • 1 - If DnD is on - Priority Only
  • 2 - If DnD is on - Total Silence
  • 3 - If DnD is on - Alarms Only

Now all you have to do is a simple if statement and you play or stop you audio accordingly.

You can stop the MediaPlayer like this

mp.stop();