Android: PLEASE DO NOT USE A WAKE LOCK

本文建议在应用程序中使用窗口标志FLAG_KEEP_SCREEN_ON替代WakeLock来保持屏幕常亮,以简化常见用例并消除潜在的bug。这种方法仅在应用程序处于前台时生效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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 infouser244190 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值