Android Studio 如何获取事件时,电源按钮android被按下

w1jd8yoj  于 2022-11-16  发布在  Android
关注(0)|答案(2)|浏览(215)

需要帮助,我正在使用React Native制作一个屏幕锁定应用程序,并希望在按下Android电源按钮时获得一个事件...
提前感谢。

z9zf31ra

z9zf31ra1#

您可以使用react native的react-native-keyevent包。

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();
}
ecfdbz9o

ecfdbz9o2#

@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);
}

只是只有键码电源不显示日志事件时,IAM按下,任何解决方案?

相关问题