Play a ringtone when the phone is silent and keep

2020-07-11 09:59发布

I am building an alarm clock app, and when the phone is silent, i want it to play the alarm but keep the phone mode on silent. The alarm app I have right now (defualt samsung / android stock one) keeps the phone on silent mode but you still hear the alarm.

I tried setting it so I check if the audio is silent or vibrate, set the sound and then reset the audio.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    //get audiomanager and set the volume
    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    int oldVolume = 0;
    int maxVolume = 0;
    boolean silent = false;

    SoundMode soundMode = null;

    if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT
            || audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) {

        if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
            soundMode = soundMode.SILENT;
        } else if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) {
            soundMode = soundMode.VIBRATE;
        }

        oldVolume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
        maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
        maxVolume = maxVolume/2;

        audioManager.setStreamVolume(AudioManager.STREAM_ALARM, maxVolume, AudioManager.FLAG_ALLOW_RINGER_MODES);

        silent = true;

        Log.i(TAG, "silent if statement " + soundMode);
    }

   // audioManager.setStreamVolume(AudioManager.STREAM_ALARM, maxVolume / 2, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);

    Uri alarmTone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
    ringtoneAlarm = RingtoneManager.getRingtone(getApplicationContext(), alarmTone);

    ringtoneAlarm.play();

    if (silent) {

        if (soundMode == SoundMode.SILENT) {
            Log.i(TAG, "silent mode");
            audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
        } else if (soundMode == SoundMode.VIBRATE) {
            Log.i(TAG, "vibrate mote");
            audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
        }
    }

    return START_NOT_STICKY;
}

I've gotten to a point where the phone knows when it's silent or in vibrate mode, but it doesn't play the ringtone, it just either vibrates or doesn't make a noise. How do I make it so it plays the ringtone no matter what, but keeps the audio state the way it was?

标签: android
1条回答
太酷不给撩
2楼-- · 2020-07-11 10:29

So after looking for some other questions this question Troubles play sound in silent mode on Android

solved it for me.

I had to use

RingtoneManager.getRingtone().setStreamType(AudioManager.STREAM_ALARM) and that played the alarm in silent mode.

查看更多
登录 后发表回答