Android如何收听音量button事件?

我知道你们可能对这些post感到厌倦,但是当我按下音量时为什么没有发生什么事? 我只是想做一个简单的代码,但显然这是行不通的。

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."); } } 

Solutions Collecting From Web of "Android如何收听音量button事件?"

我不知道你是否可以获得硬件按键的长按事件。

我已经使用这个代码来听音量button。

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

如果这不起作用,让我们知道你正在testing什么设备。

另一种方法

 @Override public boolean dispatchKeyEvent(KeyEvent event) { int action = event.getAction(); int keyCode = event.getKeyCode(); switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: if (action == KeyEvent.ACTION_DOWN) { //TODO } return true; case KeyEvent.KEYCODE_VOLUME_DOWN: if (action == KeyEvent.ACTION_DOWN) { //TODO } return true; default: return super.dispatchKeyEvent(event); } } 
 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) { // ... your code return true; } else if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP)) { // ... your code return true; } else return super.onKeyDown(keyCode, event); } 

试试这些。 只是testing他们:

 @Override public boolean onKeyLongPress(int keyCode, KeyEvent event) { super.onKeyLongPress(keyCode, event); if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { Log.w("LightWriter", "I WORK BRO."); return true; } return false; } public boolean onKeyDown(int keyCode, KeyEvent event) { super.onKeyDown(keyCode, event); if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { Log.w("LightWriter", "I WORK BRO."); return true; } return true; } 

使用此代码来处理音量键事件

 @Override public boolean onKeyUp(int keyCode, KeyEvent event) { super.onKeyUp(keyCode, event); if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) { Toast.makeText(MainActivity.this,"Up working",Toast.LENGTH_SHORT).show(); return true; } return false; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { super.onKeyDown(keyCode, event); if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { Toast.makeText(MainActivity.this,"Down working",Toast.LENGTH_SHORT).show(); return true; } return false; }