I'm developing an app in which I need to do an action when the power button is pressed but unfortunately I cant handel the action of power button when it is pressed. I tried using the onKeyDown() and dispatchKeyEvent() methods but nothing seems to be working. Can anyone suggest me any other method or solution for this problem.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
// The action I want to perform when power button is pressed.
return true;
}
return super.onKeyDown(keyCode, event);
}
and
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
Intent i = new Intent(this, NewActivity.class);
startActivity(i);
return true;
}
return super.dispatchKeyEvent(event);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…