Android实现组合键监听功能

有关组合监听的思路:两个键的点击其实是有先后顺序的,要先做第一个键点击的记录,如有时间要求还得记录时间。

下面是两个例子的代码:

例子1:长按音量变大的键,再按回退键一次,处发要处理的事件。

boolean isKeyvolume=false;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int eventAction = event.getAction();
        int keyCode = event.getKeyCode();
        if (eventAction == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            isKeyvolume=true;
        }else if(eventAction == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_VOLUME_UP){
            isKeyvolume=false;
        }else if(eventAction == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK){
            if(isKeyvolume){
                Toast.makeText(MainActivity.this,"000",Toast.LENGTH_LONG).show();
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }


例子2:长按音量变大的键,再长按回退键,处发要处理的事件。(长按时这个事件会触发多次,如果没有做双击退出应用就会出现退出应用的效果)

int mBackKeyAction, mVolumnUpKeyAction;
    long mActionTime;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {

        int keyCode = event.getKeyCode();
        int action = event.getAction();

        if (keyCode == KeyEvent.KEYCODE_VOLUME_UP && event.getAction() == KeyEvent.ACTION_DOWN) {
            mVolumnUpKeyAction = KeyEvent.ACTION_DOWN;   //记录按下状态
            if (mActionTime == 0) {
                mActionTime = System.currentTimeMillis();
            }
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP && event.getAction() == KeyEvent.ACTION_UP) {
            mVolumnUpKeyAction = KeyEvent.ACTION_UP;    //记录松下状态
            mActionTime = 0;
        }else if (keyCode == KeyEvent.KEYCODE_BACK && action == KeyEvent.ACTION_DOWN) {
            mBackKeyAction = KeyEvent.ACTION_DOWN;  //记录按下状态
            if (mActionTime == 0) {
                mActionTime = System.currentTimeMillis();
            }
        } else if (keyCode == KeyEvent.KEYCODE_BACK && action == KeyEvent.ACTION_UP) {
            mBackKeyAction = KeyEvent.ACTION_UP;  //记录松下状态
            mActionTime = 0;
        }

        //长按,且Back键和音量变大键没松
        if (isLongPress() && mBackKeyAction == KeyEvent.ACTION_DOWN && mVolumnUpKeyAction == KeyEvent.ACTION_DOWN) {
            //do something
            Toast.makeText(MainActivity.this, "TestTest", Toast.LENGTH_SHORT).show();
            //事件不下发啦
            return true;
        }

        return super.dispatchKeyEvent(event);
    }

    private boolean isLongPress() {
        if (System.currentTimeMillis() - mActionTime > 2000) {
            return true;
        } else {
            return false;
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值