Overriding lock/power button in android devices

℡╲_俬逩灬. 提交于 2019-12-22 19:15:32

问题


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

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