问题
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