0

I wrote code to detect whether volume down is pressed or not:

public String OnKeyDown(int keycode,KeyEvent event){
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)){
a="Yes, It is pressed";
}else{a="No";}

return a;

For the android keycode for volume down is 25. When I'm giving value of 25, it's always returning yes even if I didn't pressed volume down.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 2
    Does this answer your question? [Android How to listen for Volume Button events?](https://stackoverflow.com/questions/9162705/android-how-to-listen-for-volume-button-events) – Morpheus Mar 04 '21 at 13:46

1 Answers1

0

You can simply do this.


class MainActivity : AppCompatActivity() { 
    override fun onCreate(savedInstanceState: Bundle?) { 
        super.onCreate(savedInstanceState) 
        setContentView(R.layout.activity_main) 
  
    } 
  
    // 1. onKeyDown is a boolean function, which returns the state of the KeyEvent. 
    // 2. This function is an internal function, that functions outside the actual application. 
    // 3. When the any Key is pressed, a Toast appears with the following message. 
    // 4. This code can be used to check if the device responds to any Key. 
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { 
  
        when (keyCode) { 
            KeyEvent.KEYCODE_VOLUME_DOWN -> Toast.makeText(applicationContext, "Volume Down Key Pressed", Toast.LENGTH_SHORT).show() 
            KeyEvent.KEYCODE_VOLUME_UP -> Toast.makeText(applicationContext, "Volume Up Key Pressed", Toast.LENGTH_SHORT).show() 
        return true
    } 
}


Let me know the result

Faramarz Afzali
  • 726
  • 1
  • 10
  • 24