简体   繁体   English

Android电源管理器唤醒锁

[英]Android Power Manager Wake Lock

I've got application which is playing TV streams and needs to be ON all the time. 我有正在播放电视流的应用程序,需要一直打开。 I do acquire wake lock in OnCreate() 我确实在OnCreate()中获得了唤醒锁

pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, TAG);
wl.acquire();

and then release in onDestroy() 然后在onDestroy()中释放

if (wl != null) {
    wl.release();
    wl = null;
}

User usually minimize the app by pressing back, home or power button and then resumes from home screen tapping the app icon. 用户通常可以通过按下后退,主页或电源按钮来最小化该应用程序,然后通过点击应用程序图标从主屏幕恢复。 I do release wake lock in onPause() and acquire in onResume(). 我确实在onPause()中释放唤醒锁,并在onResume()中获取。

Time to time I see application crashes or disappears completely from screen and I see logs related to wake lock. 我有时会看到应用程序崩溃或完全从屏幕上消失,并且看到与唤醒锁定相关的日志。

Is this a best practice to control Android Power Manager Wake Lock? 这是控制Android Power Manager唤醒锁定的最佳实践吗?

Any opinions are welcome. 欢迎任何意见。

As you are saying that you do release wake lock in onPause() and acquire in onResume() . 正如您所说的,您确实在onPause()释放了唤醒锁,并在onResume()获取了。 That is a good practice however alongwith these I suggest you to release wakelock in onUserLeaveHint() as well. 不过,这是一个好习惯,我建议您也在onUserLeaveHint()释放唤醒onUserLeaveHint()

onUserLeaveHint() onUserLeaveHint()

@Override
protected void onUserLeaveHint() {

try {
     // your code.

     // release the wake lock
     wl.release();

    }catch(Exception ex){
     Log.e("Exception in onUserLeaveHint", ex.getMessage);
    }
    super.onUserLeaveHint();
}

Then use this in your oncreate after setContentView: 然后在setContentView之后的oncreate中使用它:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

Should help. 应该有帮助。

additional to silvia_aut's answer, try 除了silvia_aut的答案,请尝试

if (wakelock.isHeld())
       wakelock.release();

try this: 尝试这个:

wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");

and dont forget permissions: 并且不要忘记权限:

<uses-permission android:name="android.permission.WAKE_LOCK" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM