skip to Main Content

Need help, I’m making a screen locker app using React Native, and want to get an event when the android power button is pressed…

Thanks in advance..

2

Answers


  1. Chosen as BEST ANSWER
        @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
        || event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP
        || event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN
        || event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
            Log.i("Key", "keycode " + event.getKeyCode());
            return true;
        }
        
        return super.dispatchKeyEvent(event);
    }
    

    just only keycode power not show log the event when iam pressed, any solution for this?


  2. You can use the react-native-keyevent package for react native.

    componentDidMount() {
    KeyEvent.onKeyDownListener((keyEvent) => {
        if (keyEvent.keyCode === 'Keycode of the power button'){
            this.timeout = setTimeout(() => {
                //Your SOS Function here
            }, 1000)
        }
    });
    
    KeyEvent.onKeyUpListener((keyEvent) => {
        if (keyEvent.keyCode === 'Keycode of the power button'){
            clearTimeout(this.timeout)
        }
        })
    }
    
    componentWillUnmount() {
      KeyEvent.removeKeyDownListener();
      KeyEvent.removeKeyUpListener();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search