问题
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