问题描述
当屏幕关闭时,我的应用程序服务暂停.
When the screen turns off, my application service is paused.
我使用以下代码启动我的服务:
I start my service with the following code:
if (mSharedPrefs.getBoolean("prefAutoUpdatesMain", false)) {
Intent svc = new Intent(this, MyService.class);
startService(svc);
}
如何避免服务暂停?
我在 MyService 中要做的是从 Internet 下载一些数据.如果我了解我必须遵循的流程是:
What I have to do in MyService is to download some data from Internet. If I have understand the process I have to follow is:
- 获取wakeLock
- 下载数据
- 释放唤醒锁
下载数据方法中没有引用wakeLock,是应用程序有wakeLock,对吗?
In downloading data method there are no reference to wakeLock, it is the application to have the wakeLock, is it correct?
唤醒锁默认是引用计数的.我认为最好是一个没有引用计数的wakeLock,一定要释放它,我错了吗?
Wake locks are reference counted by default. I think it is better a wakeLock without reference counting, to be sure to release it, am I wrong?
推荐答案
部分 WakeLock 正是您想要的.即使屏幕关闭,它也会使 CPU 保持打开状态.
A partial WakeLock is what you want. It will hold the CPU open, even if the screen is off.
获取:
PowerManager mgr = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
wakeLock.acquire();
发布:
wakeLock.release();
WakeLock 还支持引用计数,因此您的服务中可能有多个需要唤醒功能的东西,并且设备可以在它们都处于活动状态时休眠.
WakeLock also supports reference counting so you may have multiple things in your service that require wake functionality, and the device can sleep when none of them are active.
注意事项:
如果您使用引用计数,请确保通过您的应用程序的所有控制路径都能正确获取/释放......最后块在这里派上用场.
If you use reference counting, make sure all control paths through your application will properly acquire/release...finally blocks come in handy here.
还要确保不频繁地持有 WakeLocks,而且时间很短.它们在电池使用方面相加.获取您的锁,开展您的业务,并尽快发布.
Also be sure to hold WakeLocks infrequently and for short periods of time. They add up in terms of battery use. Acquire your lock, do your business, and release as soon as possible.
这篇关于如何在屏幕关闭时保持我的 Android 服务运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!