Android: PLEASE DO NOT USE A WAKE LOCK

    技术2025-03-25  11

    PLEASE DO NOT USE A WAKE LOCK

    This requires that you give your app an additional permission, and it is very easy to introduce bugs where you accidentally remain holding the wake lock and thus leave the screen on.

    It is far, far better to use the window flag FLAG_KEEP_SCREEN_ON, which you can enable on your activity's window in your onCreate() like this:

    @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); }

    This will make sure that the screen stays on while your window is in the foreground, and only while it is in the foreground. It greatly simplifies this common use case, eliminating any juggling you need to do as your app transitions between states.

    link | edit | flag answered  Jan 25 '10 at 18:33 hackbod 6,490 1 4 12

    3  Does that prevent the device from sleeping? If so, the commonness of WAKE_LOCK strikes me as a shocking mistake! –  Michael Cramer  Jan 25 '10 at 18:52 3  Yes it keeps the screen on and prevents the device from sleeping. –  hackbod  Jan 26 '10 at 0:55   Thanks!! great info –  user244190  Feb 8 '10 at 16:28   I am currently using a Wake Lock to make sure the device does not turn off while tracking with the GPS. When the user stops tracking I release the wake lock. If I use your suggestion above, is it possible to remove the flag after you add it. Would I need to redraw the window? –  user244190  Feb 8 '10 at 20:04   Yes you can remove the flag, with the appropriate window API. You don't need to worry about causing anything to be drawn, the framework does that if needed. –  hackbod  Feb 9 '10 at 3:26

    最新回复(0)