Search code examples
androidwakelock

Android PowerManager and Wakelock, help me understand


so I am looking into PowerManager to prevent phone from going to sleep.

Two questions:

1) My phone is currently set to turn the display off after X seconds, will the PowerManager.Wakelock functions override this?

2) My phone has a top button which can be used to turn off the display, or shut the phone off. Will PowerManager.WakeLock override this functionality as well?

insight appreciated


Solution

    1. I'm not sure but I think so. And it's hard to me to find this functionality in the sources.
    2. There is a function in PowerManager.java goToSleep(time). This function simply calls method of PowerManagerService goToSleepLocked:

      private void goToSleepLocked(long time, int reason) {
      
      if (mLastEventTime <= time) {
      mLastEventTime = time;
      // cancel all of the wake locks
      mWakeLockState = SCREEN_OFF;
      int N = mLocks.size();
      int numCleared = 0;
      boolean proxLock = false;
      
      for (int i=0; i<N; i++) {
          WakeLock wl = mLocks.get(i);
          if (isScreenLock(wl.flags)) {
              if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)
                   && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
              proxLock = true;
              } else {
                  mLocks.get(i).activated = false;
                  numCleared++;
              }
          }
      }
      if (!proxLock) {
          mProxIgnoredBecauseScreenTurnedOff = true;
          if (mDebugProximitySensor) {
              Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff");
          }
      }
      EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
      mStillNeedSleepNotification = true;
      mUserState = SCREEN_OFF;
      setPowerState(SCREEN_OFF, false, reason);
      cancelTimerLocked();
      }
      }
      

    So you can see that all wakelocks are shutdowned in this method.

    The method goToSleep can be called only by system components (protected with signature permission). And I think that it is called during the press of your power button. So it rewrites all the wakelocks.