Android实现组合键监听功能

昨天接到一个任务,要做一下组合键长按监听事件。

由于Android设备是自家的,有点搓,系统代码根本没有区分长按和短按功能。

只能应用层通过diapatchKeyEvent函数实现。


话不多说,代码如下,


 @Override
    public boolean dispatchKeyEvent(KeyEvent event) {

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

        if (keyCode == KeyEvent.KEYCODE_BACK && action == KeyEvent.ACTION_DOWN) {
            mBackKeyAction = KeyEvent.ACTION_DOWN;  //记录按下状态
            if(mActionTime == 0 ) {
                mActionTime = System.currentTimeMillis();
            }
        }

        if (keyCode == KeyEvent.KEYCODE_BACK && action == KeyEvent.ACTION_UP) {
            mBackKeyAction = KeyEvent.ACTION_UP;  //记录松下状态
            mActionTime = 0;
        }

        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            mOkKeyAction = KeyEvent.ACTION_DOWN;   //记录按下状态
            if(mActionTime == 0 ) {
                mActionTime = System.currentTimeMillis();
            }
        }

        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER && event.getAction() == KeyEvent.ACTION_UP) {
            mOkKeyAction = KeyEvent.ACTION_UP;    //记录松下状态
            mActionTime = 0;
        }

        //长按,且Back键和OK键没松
        if (isLongPress() && mBackKeyAction == KeyEvent.ACTION_DOWN && mOkKeyAction == KeyEvent.ACTION_DOWN) {
            //do something
        }

        return super.dispatchKeyEvent(event);
    }
    
    private boolean isLongPress() {
        if (System.currentTimeMillis() - mActionTime > 3000) {
            return true;
        } else {
            return false;
        }
    }



 
  

你可能感兴趣的:(Android)