How can I keep my Android service running when the screen is turned off?
Solution 1:
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:
You need a partial wake lock.
Detailed example here in a previous question:
Wake locks android service recurring