Android: How to turn screen on and off programmatically?

后端 未结 16 2070
醉酒成梦
醉酒成梦 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:24

    If your app is a system app,you can use PowerManager.goToSleep() to turn screen off,you requires a special permission

    before you use goToSleep(), you need use reflection just like:

    public static void goToSleep(Context context) {
        PowerManager powerManager= (PowerManager)context.getSystemService(Context.POWER_SERVICE);
        try {
            powerManager.getClass().getMethod("goToSleep", new Class[]{long.class}).invoke(powerManager, SystemClock.uptimeMillis());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
    

    Now,you can use goToSleep() to turn screen off.

    This is what happens when the power key is pressed to turn off the screen.

提交回复
热议问题