Troubles play sound in silent mode on Android
Asked Answered
O

1

3

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?

Oeillade answered 22/3, 2013 at 19:54 Comment(4)
What you are misunderstanding is that silent mode means... silent. As in, no sound. You know those people in the movie theatre that we're finally teaching how to put their phones on vibrate?Ronald
@RobertHarvey I do know how the silent function work... I want to override the silent mode, when my alarm goes off. but it does not work with the code found in the answer to this question does not work on the phone I am using to run the application.Oeillade
I'm sorry. I didn't realize you were just writing this application for yourself.Ronald
Edited the question to be more specific.Oeillade
O
6

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);
Oeillade answered 27/3, 2013 at 17:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.