Want to Access Power Button events in android

前端 未结 2 1043
猫巷女王i
猫巷女王i 2020-12-03 18:32
   i=0;
   public boolean onKeyDown(int keyCode, KeyEvent event) {
    System.out.println(\"In Key Down Method.\" + event.getKeyCode());
    if (event.getKeyCode() =         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 19:32

    You cannot override the power button press from your application. But when you press power button the screen turns on/off. So you can detect this using a broadcast receiver.

    
    
        
        
    
    
    

    MyBroadCastReciever.java

    public class MyBroadCastReciever extends BroadcastReceiver {
    
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            //Take count of the screen off position
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            //Take count of the screen on position
        }
    }
    }
    

    Hope this is helpful for you.

    Note:-For to keep my broadcast receiver always running in Background.I am written one Background Service which continuously start in background and give boost to my broadcast receiver.

提交回复
热议问题