+-
麻烦在Android上以静音模式播放声音
我正在编写一个 Android应用程序来简单地播放一个警报,即使它处于静音模式,也不管电话是什么模式.

我发现这个question并使用答案中的代码覆盖当前的卷状态.我的代码看起来像这样:

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

通过调试,似乎我的问题从这一行开始:

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

因为我的手机在静音模式下似乎返回4,而在最大音量时则为7.我不知道这是不是,应该归还什么.我只是假设如果手机处于静音模式,它将返回0.

谁可以指出我正确的方向?

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

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

设置铃声后,我必须设置铃声的流类型:

    ringtone.setStreamType(AudioManager.STREAM_ALARM);
点击查看更多相关文章

转载注明原文:麻烦在Android上以静音模式播放声音 - 乐贴网