Saturday, September 26, 2009

Stopping Android from sleeping

Yesterday I published the source for the extended Android TestIndex application. The primary difference from that my extension and the original is the introduction of wakelocks. The reason for that is that when tests started to use longer and longer time, I felt a need to be able to do the tests without having to hover over the phone and push "menu" to give it input, and thus stopping it from going into sleep mode. Another thing that was starting to happen was that if the test took really long time and I just left the phone running it would restart the application, and thus removing any results that it may or may not have produced. So I started to digg into a way  to keep the CPU from going into sleepmode while the tests was running. After a short while I found the PowerManager sections in the Android documentation, which talks about wakelocks. The wakelocks are aquired from the PowerManager, and controls the different sleep stages that the phone goes into. I choose to use the partial wakelock wich just keeps CPU from sleeping, but allows the screen and keyboard to go into various sleep stages. Below I've pasted the table from the Android documentation that tells what the different wakelocks do.
Flag ValueCPUScreen Keyboard
So to solve the problem you just:
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelock");
  // test code 

1 comment:

  1. Thanks, very helpful.

    Just remember to the other users that you have to add the proper permissions, in this case

    uses-permission android:name="android.permission.WAKE_LOCK"