问题
I would like to know if its possible to override power button in android?
I read a lot of posts in Stack Overflow, some saying it's possible and some saying it's not (example).
What I am trying to achieve is that - when user is using my app he needs to press the lock/power button 5 times to lock the screen. I dont want to override the swtich off functionality only the lock one.
Is there anyway to fetch power button callback?
I tried WakeLock and disabled the keyguard but it does'nt serve my pupose.
I tried out below code from Shink link posted in comments section below:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
// do what you want with the power button
Toast.makeText(getApplicationContext(), "down", Toast.LENGTH_LONG).show();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
// do what you want with the power button
Toast.makeText(getApplicationContext(), "up", Toast.LENGTH_LONG).show();
return true;
}
return super.onKeyUp(keyCode, event);
}
The toast msg are only shown if I hold the power button for like 2 secs. why is that?
Is it possible override power button functionality which locks the screen? Or is there any other way to achieve what I am trying to do?
回答1:
You cannot disable POWER_BUTTON for security purpose. It runs with broadcast/subscriber patterns... :(
来源:https://stackoverflow.com/questions/21619950/overriding-lock-power-button-in-android-devices