2012年8月17日 星期五

[Android] Keep Service Alive after Screen is Off

Sometimes you just want your background services to keep alive, no matter what happens, even the screen is turned off.
PARTIAL_WAKE_LOCK is just the right thing to do this.


1. Add android.permission.WAKELOCK to your AndroidManifest.xml


2. PowerManager & WakeLock

    claim them as global variable
public class UndeadService extends Service {
  private PowerManager mgr;
  private WakeLock wakeLock;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
  super.onStartCommand(intent, flags, startId);
  mgr = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
  wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
  wakeLock.acquire();               // activate the wakelock
  return START_REDELIVER_INTENT;
}

@Override
public void onDestroy() {
  wakeLock.release();               // release the wakelock
  super.onDestroy();
}



沒有留言:

張貼留言