acquire Wake Lock - Android android.os

Android examples for android.os:PowerManager

Description

acquire Wake Lock

Demo Code

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;

public class Main {

  private static final String TAG = Main.class.getSimpleName();

  /**/*from   w w w.j  a v  a 2  s .  c om*/
   * Acquire a wake lock if not already acquired.
   * 
   * @param context
   *          the context
   * @param wakeLock
   *          wake lock or null
   */
  @SuppressLint("Wakelock")
  public static WakeLock acquireWakeLock(Context context, WakeLock wakeLock) {
    try {
      PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
      if (powerManager == null) {
        return wakeLock;
      }
      if (wakeLock == null) {
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        if (wakeLock == null) {
          return null;
        }
      }
      if (!wakeLock.isHeld()) {
        wakeLock.acquire();
        if (!wakeLock.isHeld()) {
          Log.e(TAG, "Cannot acquire wake lock.");
        }
      }
    } catch (RuntimeException e) {
      Log.e(TAG, e.getMessage(), e);
    }
    return wakeLock;
  }

}

Related Tutorials