Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android How to listen for Volume Button events?

Tags:

java

android

I know you guys are probably tired of these kinds of posts, but why doesn't anything happen when I press volume down? I'm just trying to make a simple code, but apparently it's not working.

package com.cakemansapps.lightwriter; import android.app.Activity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.FrameLayout; import android.view.KeyEvent; import android.util.Log;  public class LightWriter extends Activity implements OnTouchListener { private static final String TAG = "Touch" ; @Override public void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setContentView(R.layout.main);   FrameLayout main = (FrameLayout) findViewById(R.id.main_view); }  @Override public boolean onKeyLongPress(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)  {     Log.w("LightWriter", "I WORK BRO.");     return true; } return super.onKeyLongPress(keyCode, event); }  public boolean onTouch(View view, MotionEvent me) {     throw new UnsupportedOperationException("Not supported yet."); }  } 
like image 845
t3hcakeman Avatar asked Feb 06 '12 15:02

t3hcakeman


People also ask

How do I check my volume buttons?

Open Settings on your Android phone by clicking the gear icon. Then, head over to the sound and vibrations option. You will see a few volume sliders adjusting the volume of media, ringtone, notifications, and alarms, now you just need to adjust the volume and that's it.

How do you skip songs with volume buttons?

With this option enabled, you can long press the volume up button to skip to the next track or long press the volume down button to return to the previous track.


1 Answers

I don't know if you can get long press events for the hardware keys.

I've used this code to listen for the volume button before.

@Override public boolean onKeyDown(int keyCode, KeyEvent event) {     if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){         // Do something     }     return true; } 

If that doesn't work for you let us know what device you are testing on.

Kotlin

override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {     if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {          // Do something     }     return true } 
like image 108
FoamyGuy Avatar answered Oct 17 '22 12:10

FoamyGuy