Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

How can I keep my Android service running when the screen is turned off?

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);
}

How can I can avoid the service pause?


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. Acquire wakeLock
  2. Download data
  3. Release wakeLock

In downloading data method there are no reference to wakeLock, it is the application to have the wakeLock, is it correct?

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A partial WakeLock is what you want. It will hold the CPU open, even if the screen is off.

To acquire:

PowerManager mgr = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
wakeLock.acquire();

To release:

wakeLock.release();

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.

Things to watch out for:

If you use reference counting, make sure all control paths through your application will properly acquire/release...finally blocks come in handy here.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...