Michael
Michael

Reputation: 111

Kotlin - How to turn back volume changing?

I'm trying to set set const volume with AudioManager by changing it every time.

Here is my code:

private val broadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if ("android.media.VOLUME_CHANGED_ACTION" == intent.action) {
                audioManager.setStreamVolume(AudioManager.STREAM_RING, constDeviceVolume, 0)
            }
        }
    }

The problem is in that it line audioManager.setStreamVolume(AudioManager.STREAM_RING, constDeviceVolume, 0) triggers onReceive() fun.

I need to change volume without triggering orReceive() fun or alternative method.

Upvotes: 0

Views: 266

Answers (1)

Rene Ferrari
Rene Ferrari

Reputation: 4216

Maybe you can handle it like this?

private val broadcastReceiver = object : BroadcastReceiver() {
var wasVolumeChangedByApp = false
override fun onReceive(context: Context, intent: Intent) {
    if ("android.media.VOLUME_CHANGED_ACTION" == intent.action && !wasVolumeChangedByApp) {
        audioManager.setStreamVolume(AudioManager.STREAM_RING, constDeviceVolume, 0)
        wasVolumeChangedByApp = true
        return
    }
    wasVolumeChangedByApp = false
}

When the boolean flag (indicating that your App modified the volume) is set the handling of onReceive() is simply ignored. This flag is then reset so the onReceive call afterwards will be handled as desired.

Upvotes: 1

Related Questions