简体   繁体   English

启用“请勿打扰”时,Android无法播放声音效果

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

I'm using the MediaPlayer to play a sound effect. 我正在使用MediaPlayer播放声音效果。 However when DnD (Do not Disturb) is turned on it still plays the sound. 但是,当DnD(请勿打扰)打开时,它仍会播放声音。

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); mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);

How to initialize the media player so my sound does the following: 如何初始化媒体播放器,以便我的声音执行以下操作:

  • DnD off: play 关闭DnD:播放
  • DnD Total silence: don't play DnD完全沉默:不要玩
  • DnD Alarms only: don't play 仅DnD警报:不播放
  • DnD Priority only: don't play 仅限DnD优先级:不玩

Currently the sound is only silenced when DnD is in Total silence mode. 当前,只有当DnD处于完全静音模式时,声音才会静音。

The only thing I can think of now is to retrieve the DnD setting and only play the sound if it's off. 我现在唯一能想到的就是检索DnD设置,并且仅在声音关闭时播放声音。 But that seems more like a work-around to me. 但这对我来说似乎是一个变通方法。

You can get the status of the Do not disturb mode first like this 您可以像这样首先获得Do not disturb模式的状态

 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 该语句返回一个int值,您可以像这样使用

  • 0 - If DnD is off. 0-如果DnD关闭。
  • 1 - If DnD is on - Priority Only 1-如果DnD打开-仅优先
  • 2 - If DnD is on - Total Silence 2-如果启用DnD-完全静音
  • 3 - If DnD is on - Alarms Only 3-如果DnD打开-仅警报

Now all you have to do is a simple if statement and you play or stop you audio accordingly. 现在,您所要做的只是一个简单的if语句,并相应地播放或停止音频。

You can stop the MediaPlayer like this 您可以像这样停止MediaPlayer

mp.stop();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM