我怎样才能让我的机器人服务运行时的屏幕被关闭? [英] How can I keep my Android service running when the screen is turned off?

查看:187
本文介绍了我怎样才能让我的机器人服务运行时的屏幕被关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当屏幕关闭,我的应用程序服务已暂停。

When the screen turns off, my application service is paused.

我开始我的服务有以下code:

I start my service with the following code:

if (mSharedPrefs.getBoolean("prefAutoUpdatesMain", false)) {
     Intent svc = new Intent(this, MyService.class);
     startService(svc);
}

我怎样才能避免业务停顿?

How can I can avoid the service pause?

我有什么做的MyService是从网上下载一些数据。如果我有认识的过程中,我必须遵循的:

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:

  1. 获取wakeLock
  2. 下载数据
  3. 发布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.

事情需要提防:

如果您使用引用计数,确保通过您的应用程序的所有控制路径会妥善收购/释放... finally块在这里派上用场。

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.

这篇关于我怎样才能让我的机器人服务运行时的屏幕被关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆