Android 按键屏蔽短按但不屏蔽长按的方法

记录一下屏蔽短按但不屏蔽长按的方法,代码如下

    private boolean shortPress = false;

    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
        Log.d(TAG,"onKeyDown");
        if (keyCode == 605) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                event.startTracking();
                //只有执行了这行代码才会调用onKeyLongPress的;
                if (event.getRepeatCount() == 0) {
                    shortPress = true;
                }
                return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) {
        Log.d(TAG,"onKeyUp");
        if (keyCode == 605) {
            if (shortPress) {
                //短按要执行的代码
                Log.d(TAG, "block jianguo key !!! ");
            }
            shortPress = false;
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        Log.d(TAG,"onKeyLongPress");
        if (keyCode == 605) {
            shortPress = false;
            //长按要执行的代码
            Log.e("onKeyLongPress", "onKeyLongPress");
            return false;
        }
        return false;
    }

你可能感兴趣的:(安卓基础篇)