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

AndroidService

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

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.

Solution 2 - Android

You need a partial wake lock.

Detailed example here in a previous question:

https://stackoverflow.com/questions/5286947/wake-locks-android-service-recurring

Solution 3 - Android

I'm just using a foregrgound service.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkristbyView Question on Stackoverflow
Solution 1 - AndroidjscharfView Answer on Stackoverflow
Solution 2 - AndroidCL22View Answer on Stackoverflow
Solution 3 - AndroidstefanView Answer on Stackoverflow