Sunday, December 4, 2011

Android PowerManager and wake locks

Today I've tested the new version of my DroidRunner Android app that now relies on a background service to track gps location updates.
To my surprise when I finished my run, I've discovered that the GPS signal had been lost many times.
That was strange since with the previous versions the GPS tracking was much more precise.
After some googling I've found that I had forgot to add a wake lock that prevents the CPU from going asleep. In previous versions that was happening much less frequently maybe because I didin't had any background service and as there was always an activity running, probably would prevent the system from going in a sleep mode.

To add a wakelock just setup a new "use-permission" in AndroidManifest.xml:


<uses-permission android:name="android.permission.WAKE_LOCK"/>

Then, just decide which level of wake lock you want to have (for example, prevent CPU from going to sleep, with a PARTIAL_WAKE_LOCK).
Here is the list of possible options: PowerManager

This is the code snipped that can be used to request a wake lock:

PowerManager powerManager = (PowerManager)this.getApplicationContext().getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Service");

Finally, request the wakelock and release it as soon as you don't use it:

wakeLock.acquire();

...
wakeLock.release();




No comments:

Post a Comment