Android 音量键的监听

实践后的结论: 

下面两种都可以获取到音量键的东西,  测试的时候,发现  

KeyEvent.KEYCODE_VOLUME_UP 一直按住的时候, 三星的一款平板计数到200,就不在触发该事件;

所以改为 KeyEvent.ACTION_DOWN 时启动一个方法用来计数, 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);
    }
 
}


你可能感兴趣的:(笔记)