Troubles play sound in silent mode on Android

非 Y 不嫁゛ 提交于 2019-12-21 19:49:30

问题


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

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

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?


回答1:


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


来源:https://stackoverflow.com/questions/15578812/troubles-play-sound-in-silent-mode-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!