How can I keep my Android service running when the screen is 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 avoid a service pause?




What I need to do in MyService is to download some data from the Internet. If I realized that I had to perform the following process:

  • The acquisition of wakeLock
  • Data loading
  • Release wakelock

When loading the data method, there is no link to wakeLock, this application has wakeLock, is it correct?

Tuesday locks are considered the default. I think it's better to wakeLock without reference counting to free it, am I wrong?

+40
android service
May 22 '11 at 22:34
source share
3 answers

Partial WakeLock is what you want. It will keep the processor open, even if the screen is off.

To purchase:

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

Release:

 wakeLock.release(); 

WakeLock also supports link counting, so you may have several things in your service that require wake-up functions, and the device may sleep when none of them are active.

Beware:

If you use reference counting, make sure that all control paths through your application will correctly receive / release ... finally, blocks can be useful here.

Also remember to hold WakeLocks infrequently for short periods of time. They add up in terms of battery usage. Get your castle, do your business and release as soon as possible.

+62
May 22 '11 at 22:54
source share

You need a partial tracking lock.

A detailed example is here in the previous question:

Periodic blocking blocking attacks on Android

+3
May 22 '11 at 22:40
source share

I just use the foregrgound service.

+1
Nov 25 '15 at 21:20
source share



All Articles