KEYCODE_POWER only dispatched on long press

假如想象 提交于 2019-12-08 04:23:38

问题


Why does this key only get dispatched on a long press. Im trying to have it so that normal press of the power button mutes the currently playing audio in the Ringer stream. It only works on long press, normal press turns the screen off. I need it to work on normal press.

@Override
public boolean dispatchKeyEvent(KeyEvent event) {

        switch (event.getKeyCode()) {
        case KeyEvent.KEYCODE_POWER:
            if (ringer == null)
                return super.dispatchKeyEvent(event);

            if (!mute)
                if (ringer.isRinging())
                    ringer.stopRing();
                else if (!ringer.isRinging())
                    ringer.ring();

            mute = !mute;
            return true;
        }
return super.dispatchKeyEvent(event);

}


回答1:


It takes more than that to capture the POWER button being pressed.

This is done on purpose by Google so that malicious applications cannot take over your device by preventing any user input and blocking hardware buttons. Besides that overriding the POWER button should be done only if there is a very good reason for that.

If you want to know how to do it then visit THIS question and check the top rated answer.

PS. Search next time.




回答2:


As mentioned here https://stackoverflow.com/a/15828732/1065357

if you override this method in activity or in view that has focus then user cannot long press power button

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if(!hasFocus) {
        Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        sendBroadcast(closeDialog);
    }
}


来源:https://stackoverflow.com/questions/12353647/keycode-power-only-dispatched-on-long-press

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!