How to prevent the screen of an android device to turn off during the execution of an Activity?

后端 未结 6 712
我在风中等你
我在风中等你 2020-12-14 15:32

I have an Activity that usually needs some time to watch the screen without interacting with it.

The problem is that the screen turns off, just like wit

6条回答
  •  半阙折子戏
    2020-12-14 15:57

    Handling Fragments and Screen Rotation

    The Android documentation, Keep the device awake outlines each solution.

    Solution #1 - Flags

    Documentation - Alternatives to using wake locks

    For Fragments use the programmatic approach that is less battery intensive.

    Enable

    activity!!.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

    Disable

    activity!!.window.clearFlags(LayoutParams.FLAG_KEEP_SCREEN_ON)

    For my use case I called this in onStop() so the screen would default to the normal configuration when the Fragment showing the media content is exited.

    Avoid

    keepScreenOn=true does not work when there is a configuration change such as a screen rotation for Fragments.

    Note: Android's Keep the device awake documentation should be updated accordingly to handle this case.

    Solution #2 - Wake Lock

    Documentation - Keep the CPU on with Wake Locks

    A Wake Lock offers more control over keeping the specific elements of the device awake, but is more battery intensive, and important to release manually to save the battery since it is not handled automatically by the system.

提交回复
热议问题