Android AudioManager setStreamVolume Does Nothing

Viewed 357

I'm working on an APK with a requirement to reset the device volume to a default value after a certain amount of time, however the code I'm using doesn't seem to be doing anything. Currently I'm trying to do so by using the AudioManager.setStreamVolume method like so:

val audioStreamList = arrayOf(
    AudioManager.STREAM_MUSIC,
    AudioManager.STREAM_ALARM,
    AudioManager.STREAM_DTMF,
    AudioManager.STREAM_NOTIFICATION,
    AudioManager.STREAM_RING,
    AudioManager.STREAM_SYSTEM,
    AudioManager.STREAM_VOICE_CALL
)

fun setVolume() {
    for (stream in audioStreamList) {
        // Trying to set device volume to 50% by setting all stream volumes to 50%
        val volume = 0.5 * audioManager.getStreamMaxVolume(stream)

        audioManager.setStreamVolume(stream, volume, 0)
    }
}

I have added this to the AndroidManifest.xml:

<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

Some additional details:

  • Using Kotlin
  • This is an Alexa-enabled device
  • After the above code is executed, Alexa thinks the volume is 5 (that's what she says the volume is). However, the actual device volume is still at the last Alexa-set volume.

Any ideas?

1 Answers

I have these Java codes:

In this code, instead of setting all stream volumes to 50% it just sets the currently used stream volume:

audioManager.setStreamVolume((int)AudioManager.USE_DEFAULT_STREAM_TYPE, (int)Double.parseDouble(String.valueOf((long)(audioManager.getStreamMaxVolume((int)AudioManager.USE_DEFAULT_STREAM_TYPE) / 2))), 0);

But if you want to set all stream volumes then use this one:

 audioManager.setStreamVolume((int) stream, (int)Double.parseDouble(String.valueOf((long)(audioManager.getStreamMaxVolume((int) stream) / 2))), 0);

I also think that you should store the default volume in a variable ( before changing it ), and use this volume after finishing whatever what you want from changing it to reset the volume.

Related