Android: How to turn screen on and off programmatically?

后端 未结 16 2388
醉酒成梦
醉酒成梦 2020-11-22 13:05

Before marking this post as a \"duplicate\", I am writing this post because no other post holds the solution to the problem.

I am trying to turn off the device, then

16条回答
  •  礼貌的吻别
    2020-11-22 13:40

    The best way to do it ( using rooted devices) :

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        .
        .
        .
    
        int flags = WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
        getWindow().addFlags(flags); // this is how your app will wake up the screen
        //you will call this activity later
    
       .
       .
       .
    }
    

    Now we have this two functions:

    private void turnOffScreen(){
    
      try{
         Class c = Class.forName("android.os.PowerManager");
         PowerManager  mPowerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
         for(Method m : c.getDeclaredMethods()){
            if(m.getName().equals("goToSleep")){
              m.setAccessible(true);
              if(m.getParameterTypes().length == 1){
                m.invoke(mPowerManager,SystemClock.uptimeMillis()-2);
              }
            }
         } 
      } catch (Exception e){
      }
    }
    

    And this:

    public void turnOnScreen(){
      Intent i = new Intent(this,YOURACTIVITYWITHFLAGS.class);
      startActivity(i);
    }
    

    Sorry for my bad english.

提交回复
热议问题