user18560558
user18560558

Reputation: 79

how to detect volume change in kotlin

I want to change the seekbar position according to the volume size. It was possible to change the seekbar position according to the volume level when the volume button is pressed, but I do not know how to change the seekbar position when the volume level changes regardless of the button press.

I tried the below but doesn't work.

MainActivity.kt

class MainActivity : AppCompatActivity() {

var volumeBroadcastReceiver = object: BroadcastReceiver(){
    override fun onReceive(p0: Context?, p1: Intent?) {
        var action = intent?.getAction()

        if (action != null) {
            if(action.equals("android.media.VOLUME_CHANGED_ACTION")){
                System.out.println("volume changed")
            }

        }
    }
}

    var filter = IntentFilter().apply{
        state("android.media.VOLUME_CHANGED_ACTION")
    }
  
    registerReceiver(volumeBroadcastReceiver,filter)
}

Upvotes: 0

Views: 221

Answers (1)

thanksalotquoraguy
thanksalotquoraguy

Reputation: 88

Inside onViewCreated

view.isFocusableInTouchMode = true
        view.requestFocus()

        view.setOnKeyListener { _, keyCode, event ->
            if (event.action == KeyEvent.ACTION_DOWN) {
                when (keyCode) {
                    KeyEvent.KEYCODE_VOLUME_DOWN -> {
                        // Handle volume down key press
                        // Replace the following line with your desired functionality
                        // For example, you can decrease a value, adjust the volume, etc.

                        true
                    }
                    KeyEvent.KEYCODE_VOLUME_UP -> {
                        // Handle volume up key press
                        // Replace the following line with your desired functionality
                        // For example, you can increase a value, adjust the volume, etc.

                        true
                    }
                    else -> false
                }
            } else {
                false
            }
        }

Upvotes: 1

Related Questions