Showing posts with label WakeLock. Show all posts
Showing posts with label WakeLock. Show all posts

Add WakeLock to an Android Project

How to add WakeLock to an Android Project, Step-By-Step

1. Add the WakeLock permission to the AndroidManifest.

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

2. Add import for PowerManager to MainActivity file

          import android.os.PowerManager.WakeLock;
          import android.os.PowerManager;
          import android.content.Context;

3. Decleare WakeLock as wl in the MainActivity file.

.....
public class MainActivity extends Activity {

     protected PowerManager.WakeLock mWakeLock;

    @Override

    public void onCreate(Bundle savedInstanceState) {
....

3.Add the below code to the onCreatae method.

    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); 
    this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
    this.mWakeLock.acquire();

4. Release the WakeLock in the onDestroy.

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mWakeLock.release();
    }

5. Compile and run!

Resources
http://developer.android.com/reference/android/os/PowerManager.html#newWakeLock(int, java.lang.String)