Wake Locks Android Example

There are situation where you want your application not to sleep. It happens when you create a game like chess where the user spends more time in thinking than touching the mobile screen or when you are working with camera. So if you choose to do so you should acquire a WakeLock. Use it only if it is necessary because wakelock interferes with power management and it may drain your mobile battery so release the lock when you are done.

In this example we will create an android project and keep its activity awake indefinitely until it is destroyed

So lets Start :

1.In Eclipse, select “File -> New -> Project….”, “Android Project”, and input your application detail. Eclipse will create all the necessary Android project files and configuration.

2.Here I have mentioned my activity name as WakeLockActivity which is the startup activity and it will remain awake till the activity is destroyed

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;

public class WakeLockActivity extends Activity {
 /** Called when the activity is first created. */
 protected static WakeLock wakeLock = null;

 public void onCreate(Bundle savedInstanceState) {
  PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
  wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotSleep");

 protected void onDestroy() {
  // TODO Auto-generated method stub

3.Put any thing that interests you in the main.xml
4.Run the application by right clicking the project Run As → Android Application