Android volume key monitoring and android Volume monitoring
Conclusion:
The following two methods can be used to obtain the volume key. During the test, we found that
When KeyEvent. KEYCODE_VOLUME_UP is held down all the time, Samsung's tablet counts to 200, and this event is not triggered;
Therefore, when KeyEvent. ACTION_DOWN is changed, a method is started to count the number of stop techniques of KeyEvent. ACTION_UP;
package com.akm.testvolume; import android.app.Activity;import android.os.Bundle;import android.view.KeyEvent;import android.widget.TextView; public class MainActivity extends Activity { private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); } int count = -1; @Override public boolean dispatchKeyEvent(KeyEvent event) { int action = event.getAction(); if (action ==KeyEvent.ACTION_DOWN) { tv.setText("+++++++++ACTION_DOWN++++++"+ count++); return true; } if (action== KeyEvent.ACTION_UP) { tv.setText("+++++ACTION_UP++++++++++"); return true; } return super.dispatchKeyEvent(event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_DOWN: tv.setText("-----------------"+count); count--; return true; case KeyEvent.KEYCODE_VOLUME_UP: tv.setText("++++++++++++++++"+ count); count++; return true; case KeyEvent.KEYCODE_VOLUME_MUTE: tv.setText("MUTE"); return true; } return super.onKeyDown(keyCode, event); } }