故障在Android静音模式播放声音静音、故障、声音、模式

2023-09-06 10:47:32 作者:你眼里有星星

我写一个Android应用程序简单地播放警报没有母校什么模式的手机即使是在静音模式。

I am writing an android application to simply play an alarm no mater what mode the phone even if it is in silent mode.

我发现这个question并使用code从应答覆盖当前的音量状态。我的code是这样的:

I found this question and used the code from the answer to override the current volume state. My code looks like this:

Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
    if (alert == null){
        // alert is null, using backup
        alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        if (alert == null){
            // alert backup is null, using 2nd backup
            alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
    }
}
ringtone = RingtoneManager.getRingtone(getApplicationContext(), alert);

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int volume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
if(volume == 0){
    volume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
}
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, volume,AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);

if(ringtone != null){
    ringtone.play();
}

通过调试看来我的问题,在这一行开始:

By debugging it seems that my problem start in this line:

int volume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);

因为我的手机好像又回到4时,它处于静音模式和7时,它在最大音量。我不知道这是,什么是应该返回。我只是认为,如果手机处于静音模式,将返回0。

since my phone seems to return 4 when it is in silent mode and 7 when it is at max volume. I do not know if this is, what it is supposed to return. I just supposed that if the phone is in silent mode it would return 0.

任何谁可以点我在正确的方向?

Anyone who can point me in the right direction?

推荐答案

回答了这个问题我自己,花更多的时间深入阅读文档。

Answered the question myself, spend more time reading the documentation in-depth.

Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
    if (alert == null){
        // alert is null, using backup
        alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        if (alert == null){
            // alert backup is null, using 2nd backup
            alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
    }
}
ringtone = RingtoneManager.getRingtone(getApplicationContext(), alert);

设置铃声之后,我不得不设置铃声流类型:

after setting the ringtone I had to set the stream type for the ringtone:

    ringtone.setStreamType(AudioManager.STREAM_ALARM);
 
精彩推荐
图片推荐