PowerManager.java revision 3b0218b0ae1fad67f539ff3c10d6d2f3abec1a11
1/* 2 * Copyright (C) 2007 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.os; 18 19import android.content.Context; 20import android.util.Log; 21 22/** 23 * This class gives you control of the power state of the device. 24 * 25 * <p> 26 * <b>Device battery life will be significantly affected by the use of this API.</b> 27 * Do not acquire {@link WakeLock}s unless you really need them, use the minimum levels 28 * possible, and be sure to release them as soon as possible. 29 * </p><p> 30 * You can obtain an instance of this class by calling 31 * {@link android.content.Context#getSystemService(java.lang.String) Context.getSystemService()}. 32 * </p><p> 33 * The primary API you'll use is {@link #newWakeLock(int, String) newWakeLock()}. 34 * This will create a {@link PowerManager.WakeLock} object. You can then use methods 35 * on the wake lock object to control the power state of the device. 36 * </p><p> 37 * In practice it's quite simple: 38 * {@samplecode 39 * PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); 40 * PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag"); 41 * wl.acquire(); 42 * ..screen will stay on during this section.. 43 * wl.release(); 44 * } 45 * </p><p> 46 * The following wake lock levels are defined, with varying effects on system power. 47 * <i>These levels are mutually exclusive - you may only specify one of them.</i> 48 * 49 * <table> 50 * <tr><th>Flag Value</th> 51 * <th>CPU</th> <th>Screen</th> <th>Keyboard</th></tr> 52 * 53 * <tr><td>{@link #PARTIAL_WAKE_LOCK}</td> 54 * <td>On*</td> <td>Off</td> <td>Off</td> 55 * </tr> 56 * 57 * <tr><td>{@link #SCREEN_DIM_WAKE_LOCK}</td> 58 * <td>On</td> <td>Dim</td> <td>Off</td> 59 * </tr> 60 * 61 * <tr><td>{@link #SCREEN_BRIGHT_WAKE_LOCK}</td> 62 * <td>On</td> <td>Bright</td> <td>Off</td> 63 * </tr> 64 * 65 * <tr><td>{@link #FULL_WAKE_LOCK}</td> 66 * <td>On</td> <td>Bright</td> <td>Bright</td> 67 * </tr> 68 * </table> 69 * </p><p> 70 * *<i>If you hold a partial wake lock, the CPU will continue to run, regardless of any 71 * display timeouts or the state of the screen and even after the user presses the power button. 72 * In all other wake locks, the CPU will run, but the user can still put the device to sleep 73 * using the power button.</i> 74 * </p><p> 75 * In addition, you can add two more flags, which affect behavior of the screen only. 76 * <i>These flags have no effect when combined with a {@link #PARTIAL_WAKE_LOCK}.</i></p> 77 * 78 * <table> 79 * <tr><th>Flag Value</th> <th>Description</th></tr> 80 * 81 * <tr><td>{@link #ACQUIRE_CAUSES_WAKEUP}</td> 82 * <td>Normal wake locks don't actually turn on the illumination. Instead, they cause 83 * the illumination to remain on once it turns on (e.g. from user activity). This flag 84 * will force the screen and/or keyboard to turn on immediately, when the WakeLock is 85 * acquired. A typical use would be for notifications which are important for the user to 86 * see immediately.</td> 87 * </tr> 88 * 89 * <tr><td>{@link #ON_AFTER_RELEASE}</td> 90 * <td>If this flag is set, the user activity timer will be reset when the WakeLock is 91 * released, causing the illumination to remain on a bit longer. This can be used to 92 * reduce flicker if you are cycling between wake lock conditions.</td> 93 * </tr> 94 * </table> 95 * <p> 96 * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK} 97 * permission in an {@code <uses-permission>} element of the application's manifest. 98 * </p> 99 */ 100public final class PowerManager { 101 private static final String TAG = "PowerManager"; 102 103 /* NOTE: Wake lock levels were previously defined as a bit field, except that only a few 104 * combinations were actually supported so the bit field was removed. This explains 105 * why the numbering scheme is so odd. If adding a new wake lock level, any unused 106 * value can be used. 107 */ 108 109 /** 110 * Wake lock level: Ensures that the CPU is running; the screen and keyboard 111 * backlight will be allowed to go off. 112 * <p> 113 * If the user presses the power button, then the screen will be turned off 114 * but the CPU will be kept on until all partial wake locks have been released. 115 * </p> 116 */ 117 public static final int PARTIAL_WAKE_LOCK = 0x00000001; 118 119 /** 120 * Wake lock level: Ensures that the screen is on (but may be dimmed); 121 * the keyboard backlight will be allowed to go off. 122 * <p> 123 * If the user presses the power button, then the {@link #SCREEN_DIM_WAKE_LOCK} will be 124 * implicitly released by the system, causing both the screen and the CPU to be turned off. 125 * Contrast with {@link #PARTIAL_WAKE_LOCK}. 126 * </p> 127 * 128 * @deprecated Most applications should use 129 * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead 130 * of this type of wake lock, as it will be correctly managed by the platform 131 * as the user moves between applications and doesn't require a special permission. 132 */ 133 @Deprecated 134 public static final int SCREEN_DIM_WAKE_LOCK = 0x00000006; 135 136 /** 137 * Wake lock level: Ensures that the screen is on at full brightness; 138 * the keyboard backlight will be allowed to go off. 139 * <p> 140 * If the user presses the power button, then the {@link #SCREEN_BRIGHT_WAKE_LOCK} will be 141 * implicitly released by the system, causing both the screen and the CPU to be turned off. 142 * Contrast with {@link #PARTIAL_WAKE_LOCK}. 143 * </p> 144 * 145 * @deprecated Most applications should use 146 * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead 147 * of this type of wake lock, as it will be correctly managed by the platform 148 * as the user moves between applications and doesn't require a special permission. 149 */ 150 @Deprecated 151 public static final int SCREEN_BRIGHT_WAKE_LOCK = 0x0000000a; 152 153 /** 154 * Wake lock level: Ensures that the screen and keyboard backlight are on at 155 * full brightness. 156 * <p> 157 * If the user presses the power button, then the {@link #FULL_WAKE_LOCK} will be 158 * implicitly released by the system, causing both the screen and the CPU to be turned off. 159 * Contrast with {@link #PARTIAL_WAKE_LOCK}. 160 * </p> 161 * 162 * @deprecated Most applications should use 163 * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead 164 * of this type of wake lock, as it will be correctly managed by the platform 165 * as the user moves between applications and doesn't require a special permission. 166 */ 167 @Deprecated 168 public static final int FULL_WAKE_LOCK = 0x0000001a; 169 170 /** 171 * Wake lock level: Turns the screen off when the proximity sensor activates. 172 * <p> 173 * If the proximity sensor detects that an object is nearby, the screen turns off 174 * immediately. Shortly after the object moves away, the screen turns on again. 175 * </p><p> 176 * A proximity wake lock does not prevent the device from falling asleep 177 * unlike {@link #FULL_WAKE_LOCK}, {@link #SCREEN_BRIGHT_WAKE_LOCK} and 178 * {@link #SCREEN_DIM_WAKE_LOCK}. If there is no user activity and no other 179 * wake locks are held, then the device will fall asleep (and lock) as usual. 180 * However, the device will not fall asleep while the screen has been turned off 181 * by the proximity sensor because it effectively counts as ongoing user activity. 182 * </p><p> 183 * Since not all devices have proximity sensors, use {@link #isWakeLockLevelSupported} 184 * to determine whether this wake lock level is supported. 185 * </p><p> 186 * Cannot be used with {@link #ACQUIRE_CAUSES_WAKEUP}. 187 * </p> 188 * 189 * {@hide} 190 */ 191 public static final int PROXIMITY_SCREEN_OFF_WAKE_LOCK = 0x00000020; 192 193 /** 194 * Mask for the wake lock level component of a combined wake lock level and flags integer. 195 * 196 * @hide 197 */ 198 public static final int WAKE_LOCK_LEVEL_MASK = 0x0000ffff; 199 200 /** 201 * Wake lock flag: Turn the screen on when the wake lock is acquired. 202 * <p> 203 * Normally wake locks don't actually wake the device, they just cause 204 * the screen to remain on once it's already on. Think of the video player 205 * application as the normal behavior. Notifications that pop up and want 206 * the device to be on are the exception; use this flag to be like them. 207 * </p><p> 208 * Cannot be used with {@link #PARTIAL_WAKE_LOCK}. 209 * </p> 210 */ 211 public static final int ACQUIRE_CAUSES_WAKEUP = 0x10000000; 212 213 /** 214 * Wake lock flag: When this wake lock is released, poke the user activity timer 215 * so the screen stays on for a little longer. 216 * <p> 217 * Will not turn the screen on if it is not already on. 218 * See {@link #ACQUIRE_CAUSES_WAKEUP} if you want that. 219 * </p><p> 220 * Cannot be used with {@link #PARTIAL_WAKE_LOCK}. 221 * </p> 222 */ 223 public static final int ON_AFTER_RELEASE = 0x20000000; 224 225 /** 226 * Flag for {@link WakeLock#release release(int)} to defer releasing a 227 * {@link #PROXIMITY_SCREEN_OFF_WAKE_LOCK} wake lock until the proximity sensor returns 228 * a negative value. 229 * 230 * {@hide} 231 */ 232 public static final int WAIT_FOR_PROXIMITY_NEGATIVE = 1; 233 234 /** 235 * Brightness value for fully on. 236 * @hide 237 */ 238 public static final int BRIGHTNESS_ON = 255; 239 240 /** 241 * Brightness value for fully off. 242 * @hide 243 */ 244 public static final int BRIGHTNESS_OFF = 0; 245 246 // Note: Be sure to update android.os.BatteryStats and PowerManager.h 247 // if adding or modifying user activity event constants. 248 249 /** 250 * User activity event type: Unspecified event type. 251 * @hide 252 */ 253 public static final int USER_ACTIVITY_EVENT_OTHER = 0; 254 255 /** 256 * User activity event type: Button or key pressed or released. 257 * @hide 258 */ 259 public static final int USER_ACTIVITY_EVENT_BUTTON = 1; 260 261 /** 262 * User activity event type: Touch down, move or up. 263 * @hide 264 */ 265 public static final int USER_ACTIVITY_EVENT_TOUCH = 2; 266 267 /** 268 * User activity flag: Do not restart the user activity timeout or brighten 269 * the display in response to user activity if it is already dimmed. 270 * @hide 271 */ 272 public static final int USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS = 1 << 0; 273 274 /** 275 * Go to sleep reason code: Going to sleep due by user request. 276 * @hide 277 */ 278 public static final int GO_TO_SLEEP_REASON_USER = 0; 279 280 /** 281 * Go to sleep reason code: Going to sleep due by request of the 282 * device administration policy. 283 * @hide 284 */ 285 public static final int GO_TO_SLEEP_REASON_DEVICE_ADMIN = 1; 286 287 /** 288 * Go to sleep reason code: Going to sleep due to a screen timeout. 289 * @hide 290 */ 291 public static final int GO_TO_SLEEP_REASON_TIMEOUT = 2; 292 293 /** 294 * The value to pass as the 'reason' argument to reboot() to 295 * reboot into recovery mode (for applying system updates, doing 296 * factory resets, etc.). 297 * <p> 298 * Requires the {@link android.Manifest.permission#RECOVERY} 299 * permission (in addition to 300 * {@link android.Manifest.permission#REBOOT}). 301 * </p> 302 */ 303 public static final String REBOOT_RECOVERY = "recovery"; 304 305 final Context mContext; 306 final IPowerManager mService; 307 final Handler mHandler; 308 309 /** 310 * {@hide} 311 */ 312 public PowerManager(Context context, IPowerManager service, Handler handler) { 313 mContext = context; 314 mService = service; 315 mHandler = handler; 316 } 317 318 /** 319 * Gets the minimum supported screen brightness setting. 320 * The screen may be allowed to become dimmer than this value but 321 * this is the minimum value that can be set by the user. 322 * @hide 323 */ 324 public int getMinimumScreenBrightnessSetting() { 325 return mContext.getResources().getInteger( 326 com.android.internal.R.integer.config_screenBrightnessSettingMinimum); 327 } 328 329 /** 330 * Gets the maximum supported screen brightness setting. 331 * The screen may be allowed to become dimmer than this value but 332 * this is the maximum value that can be set by the user. 333 * @hide 334 */ 335 public int getMaximumScreenBrightnessSetting() { 336 return mContext.getResources().getInteger( 337 com.android.internal.R.integer.config_screenBrightnessSettingMaximum); 338 } 339 340 /** 341 * Gets the default screen brightness setting. 342 * @hide 343 */ 344 public int getDefaultScreenBrightnessSetting() { 345 return mContext.getResources().getInteger( 346 com.android.internal.R.integer.config_screenBrightnessSettingDefault); 347 } 348 349 /** 350 * Returns true if the screen auto-brightness adjustment setting should 351 * be available in the UI. This setting is experimental and disabled by default. 352 * @hide 353 */ 354 public static boolean useScreenAutoBrightnessAdjustmentFeature() { 355 return SystemProperties.getBoolean("persist.power.useautobrightadj", false); 356 } 357 358 /** 359 * Returns true if the twilight service should be used to adjust screen brightness 360 * policy. This setting is experimental and disabled by default. 361 * @hide 362 */ 363 public static boolean useTwilightAdjustmentFeature() { 364 return SystemProperties.getBoolean("persist.power.usetwilightadj", false); 365 } 366 367 /** 368 * Creates a new wake lock with the specified level and flags. 369 * <p> 370 * The {@code levelAndFlags} parameter specifies a wake lock level and optional flags 371 * combined using the logical OR operator. 372 * </p><p> 373 * The wake lock levels are: {@link #PARTIAL_WAKE_LOCK}, 374 * {@link #FULL_WAKE_LOCK}, {@link #SCREEN_DIM_WAKE_LOCK} 375 * and {@link #SCREEN_BRIGHT_WAKE_LOCK}. Exactly one wake lock level must be 376 * specified as part of the {@code levelAndFlags} parameter. 377 * </p><p> 378 * The wake lock flags are: {@link #ACQUIRE_CAUSES_WAKEUP} 379 * and {@link #ON_AFTER_RELEASE}. Multiple flags can be combined as part of the 380 * {@code levelAndFlags} parameters. 381 * </p><p> 382 * Call {@link WakeLock#acquire() acquire()} on the object to acquire the 383 * wake lock, and {@link WakeLock#release release()} when you are done. 384 * </p><p> 385 * {@samplecode 386 * PowerManager pm = (PowerManager)mContext.getSystemService( 387 * Context.POWER_SERVICE); 388 * PowerManager.WakeLock wl = pm.newWakeLock( 389 * PowerManager.SCREEN_DIM_WAKE_LOCK 390 * | PowerManager.ON_AFTER_RELEASE, 391 * TAG); 392 * wl.acquire(); 393 * // ... do work... 394 * wl.release(); 395 * } 396 * </p><p> 397 * Although a wake lock can be created without special permissions, 398 * the {@link android.Manifest.permission#WAKE_LOCK} permission is 399 * required to actually acquire or release the wake lock that is returned. 400 * </p><p class="note"> 401 * If using this to keep the screen on, you should strongly consider using 402 * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead. 403 * This window flag will be correctly managed by the platform 404 * as the user moves between applications and doesn't require a special permission. 405 * </p> 406 * 407 * @param levelAndFlags Combination of wake lock level and flag values defining 408 * the requested behavior of the WakeLock. 409 * @param tag Your class name (or other tag) for debugging purposes. 410 * 411 * @see WakeLock#acquire() 412 * @see WakeLock#release() 413 * @see #PARTIAL_WAKE_LOCK 414 * @see #FULL_WAKE_LOCK 415 * @see #SCREEN_DIM_WAKE_LOCK 416 * @see #SCREEN_BRIGHT_WAKE_LOCK 417 * @see #ACQUIRE_CAUSES_WAKEUP 418 * @see #ON_AFTER_RELEASE 419 */ 420 public WakeLock newWakeLock(int levelAndFlags, String tag) { 421 validateWakeLockParameters(levelAndFlags, tag); 422 return new WakeLock(levelAndFlags, tag, mContext.getOpPackageName()); 423 } 424 425 /** @hide */ 426 public static void validateWakeLockParameters(int levelAndFlags, String tag) { 427 switch (levelAndFlags & WAKE_LOCK_LEVEL_MASK) { 428 case PARTIAL_WAKE_LOCK: 429 case SCREEN_DIM_WAKE_LOCK: 430 case SCREEN_BRIGHT_WAKE_LOCK: 431 case FULL_WAKE_LOCK: 432 case PROXIMITY_SCREEN_OFF_WAKE_LOCK: 433 break; 434 default: 435 throw new IllegalArgumentException("Must specify a valid wake lock level."); 436 } 437 if (tag == null) { 438 throw new IllegalArgumentException("The tag must not be null."); 439 } 440 } 441 442 /** 443 * Notifies the power manager that user activity happened. 444 * <p> 445 * Resets the auto-off timer and brightens the screen if the device 446 * is not asleep. This is what happens normally when a key or the touch 447 * screen is pressed or when some other user activity occurs. 448 * This method does not wake up the device if it has been put to sleep. 449 * </p><p> 450 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission. 451 * </p> 452 * 453 * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()} 454 * time base. This timestamp is used to correctly order the user activity request with 455 * other power management functions. It should be set 456 * to the timestamp of the input event that caused the user activity. 457 * @param noChangeLights If true, does not cause the keyboard backlight to turn on 458 * because of this event. This is set when the power key is pressed. 459 * We want the device to stay on while the button is down, but we're about 460 * to turn off the screen so we don't want the keyboard backlight to turn on again. 461 * Otherwise the lights flash on and then off and it looks weird. 462 * 463 * @see #wakeUp 464 * @see #goToSleep 465 */ 466 public void userActivity(long when, boolean noChangeLights) { 467 try { 468 mService.userActivity(when, USER_ACTIVITY_EVENT_OTHER, 469 noChangeLights ? USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS : 0); 470 } catch (RemoteException e) { 471 } 472 } 473 474 /** 475 * Forces the device to go to sleep. 476 * <p> 477 * Overrides all the wake locks that are held. 478 * This is what happens when the power key is pressed to turn off the screen. 479 * </p><p> 480 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission. 481 * </p> 482 * 483 * @param time The time when the request to go to sleep was issued, in the 484 * {@link SystemClock#uptimeMillis()} time base. This timestamp is used to correctly 485 * order the go to sleep request with other power management functions. It should be set 486 * to the timestamp of the input event that caused the request to go to sleep. 487 * 488 * @see #userActivity 489 * @see #wakeUp 490 */ 491 public void goToSleep(long time) { 492 try { 493 mService.goToSleep(time, GO_TO_SLEEP_REASON_USER); 494 } catch (RemoteException e) { 495 } 496 } 497 498 /** 499 * Forces the device to wake up from sleep. 500 * <p> 501 * If the device is currently asleep, wakes it up, otherwise does nothing. 502 * This is what happens when the power key is pressed to turn on the screen. 503 * </p><p> 504 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission. 505 * </p> 506 * 507 * @param time The time when the request to wake up was issued, in the 508 * {@link SystemClock#uptimeMillis()} time base. This timestamp is used to correctly 509 * order the wake up request with other power management functions. It should be set 510 * to the timestamp of the input event that caused the request to wake up. 511 * 512 * @see #userActivity 513 * @see #goToSleep 514 */ 515 public void wakeUp(long time) { 516 try { 517 mService.wakeUp(time); 518 } catch (RemoteException e) { 519 } 520 } 521 522 /** 523 * Forces the device to start napping. 524 * <p> 525 * If the device is currently awake, starts dreaming, otherwise does nothing. 526 * When the dream ends or if the dream cannot be started, the device will 527 * either wake up or go to sleep depending on whether there has been recent 528 * user activity. 529 * </p><p> 530 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission. 531 * </p> 532 * 533 * @param time The time when the request to nap was issued, in the 534 * {@link SystemClock#uptimeMillis()} time base. This timestamp is used to correctly 535 * order the nap request with other power management functions. It should be set 536 * to the timestamp of the input event that caused the request to nap. 537 * 538 * @see #wakeUp 539 * @see #goToSleep 540 * 541 * @hide 542 */ 543 public void nap(long time) { 544 try { 545 mService.nap(time); 546 } catch (RemoteException e) { 547 } 548 } 549 550 /** 551 * Sets the brightness of the backlights (screen, keyboard, button). 552 * <p> 553 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission. 554 * </p> 555 * 556 * @param brightness The brightness value from 0 to 255. 557 * 558 * {@hide} 559 */ 560 public void setBacklightBrightness(int brightness) { 561 try { 562 mService.setTemporaryScreenBrightnessSettingOverride(brightness); 563 } catch (RemoteException e) { 564 } 565 } 566 567 /** 568 * Returns true if the specified wake lock level is supported. 569 * 570 * @param level The wake lock level to check. 571 * @return True if the specified wake lock level is supported. 572 * 573 * {@hide} 574 */ 575 public boolean isWakeLockLevelSupported(int level) { 576 try { 577 return mService.isWakeLockLevelSupported(level); 578 } catch (RemoteException e) { 579 return false; 580 } 581 } 582 583 /** 584 * Returns whether the screen is currently on. 585 * <p> 586 * Only indicates whether the screen is on. The screen could be either bright or dim. 587 * </p><p> 588 * {@samplecode 589 * PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); 590 * boolean isScreenOn = pm.isScreenOn(); 591 * } 592 * </p> 593 * 594 * @return whether the screen is on (bright or dim). 595 */ 596 public boolean isScreenOn() { 597 try { 598 return mService.isScreenOn(); 599 } catch (RemoteException e) { 600 return false; 601 } 602 } 603 604 /** 605 * Reboot the device. Will not return if the reboot is successful. 606 * <p> 607 * Requires the {@link android.Manifest.permission#REBOOT} permission. 608 * </p> 609 * 610 * @param reason code to pass to the kernel (e.g., "recovery") to 611 * request special boot modes, or null. 612 */ 613 public void reboot(String reason) { 614 try { 615 mService.reboot(false, reason, true); 616 } catch (RemoteException e) { 617 } 618 } 619 620 /** 621 * A wake lock is a mechanism to indicate that your application needs 622 * to have the device stay on. 623 * <p> 624 * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK} 625 * permission in an {@code <uses-permission>} element of the application's manifest. 626 * Obtain a wake lock by calling {@link PowerManager#newWakeLock(int, String)}. 627 * </p><p> 628 * Call {@link #acquire()} to acquire the wake lock and force the device to stay 629 * on at the level that was requested when the wake lock was created. 630 * </p><p> 631 * Call {@link #release()} when you are done and don't need the lock anymore. 632 * It is very important to do this as soon as possible to avoid running down the 633 * device's battery excessively. 634 * </p> 635 */ 636 public final class WakeLock { 637 private final int mFlags; 638 private final String mTag; 639 private final String mPackageName; 640 private final IBinder mToken; 641 private int mCount; 642 private boolean mRefCounted = true; 643 private boolean mHeld; 644 private WorkSource mWorkSource; 645 646 private final Runnable mReleaser = new Runnable() { 647 public void run() { 648 release(); 649 } 650 }; 651 652 WakeLock(int flags, String tag, String packageName) { 653 mFlags = flags; 654 mTag = tag; 655 mPackageName = packageName; 656 mToken = new Binder(); 657 } 658 659 @Override 660 protected void finalize() throws Throwable { 661 synchronized (mToken) { 662 if (mHeld) { 663 Log.wtf(TAG, "WakeLock finalized while still held: " + mTag); 664 try { 665 mService.releaseWakeLock(mToken, 0); 666 } catch (RemoteException e) { 667 } 668 } 669 } 670 } 671 672 /** 673 * Sets whether this WakeLock is reference counted. 674 * <p> 675 * Wake locks are reference counted by default. If a wake lock is 676 * reference counted, then each call to {@link #acquire()} must be 677 * balanced by an equal number of calls to {@link #release()}. If a wake 678 * lock is not reference counted, then one call to {@link #release()} is 679 * sufficient to undo the effect of all previous calls to {@link #acquire()}. 680 * </p> 681 * 682 * @param value True to make the wake lock reference counted, false to 683 * make the wake lock non-reference counted. 684 */ 685 public void setReferenceCounted(boolean value) { 686 synchronized (mToken) { 687 mRefCounted = value; 688 } 689 } 690 691 /** 692 * Acquires the wake lock. 693 * <p> 694 * Ensures that the device is on at the level requested when 695 * the wake lock was created. 696 * </p> 697 */ 698 public void acquire() { 699 synchronized (mToken) { 700 acquireLocked(); 701 } 702 } 703 704 /** 705 * Acquires the wake lock with a timeout. 706 * <p> 707 * Ensures that the device is on at the level requested when 708 * the wake lock was created. The lock will be released after the given timeout 709 * expires. 710 * </p> 711 * 712 * @param timeout The timeout after which to release the wake lock, in milliseconds. 713 */ 714 public void acquire(long timeout) { 715 synchronized (mToken) { 716 acquireLocked(); 717 mHandler.postDelayed(mReleaser, timeout); 718 } 719 } 720 721 private void acquireLocked() { 722 if (!mRefCounted || mCount++ == 0) { 723 // Do this even if the wake lock is already thought to be held (mHeld == true) 724 // because non-reference counted wake locks are not always properly released. 725 // For example, the keyguard's wake lock might be forcibly released by the 726 // power manager without the keyguard knowing. A subsequent call to acquire 727 // should immediately acquire the wake lock once again despite never having 728 // been explicitly released by the keyguard. 729 mHandler.removeCallbacks(mReleaser); 730 try { 731 mService.acquireWakeLock(mToken, mFlags, mTag, mPackageName, mWorkSource); 732 } catch (RemoteException e) { 733 } 734 mHeld = true; 735 } 736 } 737 738 /** 739 * Releases the wake lock. 740 * <p> 741 * This method releases your claim to the CPU or screen being on. 742 * The screen may turn off shortly after you release the wake lock, or it may 743 * not if there are other wake locks still held. 744 * </p> 745 */ 746 public void release() { 747 release(0); 748 } 749 750 /** 751 * Releases the wake lock with flags to modify the release behavior. 752 * <p> 753 * This method releases your claim to the CPU or screen being on. 754 * The screen may turn off shortly after you release the wake lock, or it may 755 * not if there are other wake locks still held. 756 * </p> 757 * 758 * @param flags Combination of flag values to modify the release behavior. 759 * Currently only {@link #WAIT_FOR_PROXIMITY_NEGATIVE} is supported. 760 * 761 * {@hide} 762 */ 763 public void release(int flags) { 764 synchronized (mToken) { 765 if (!mRefCounted || --mCount == 0) { 766 mHandler.removeCallbacks(mReleaser); 767 if (mHeld) { 768 try { 769 mService.releaseWakeLock(mToken, flags); 770 } catch (RemoteException e) { 771 } 772 mHeld = false; 773 } 774 } 775 if (mCount < 0) { 776 throw new RuntimeException("WakeLock under-locked " + mTag); 777 } 778 } 779 } 780 781 /** 782 * Returns true if the wake lock has been acquired but not yet released. 783 * 784 * @return True if the wake lock is held. 785 */ 786 public boolean isHeld() { 787 synchronized (mToken) { 788 return mHeld; 789 } 790 } 791 792 /** 793 * Sets the work source associated with the wake lock. 794 * <p> 795 * The work source is used to determine on behalf of which application 796 * the wake lock is being held. This is useful in the case where a 797 * service is performing work on behalf of an application so that the 798 * cost of that work can be accounted to the application. 799 * </p> 800 * 801 * @param ws The work source, or null if none. 802 */ 803 public void setWorkSource(WorkSource ws) { 804 synchronized (mToken) { 805 if (ws != null && ws.size() == 0) { 806 ws = null; 807 } 808 809 final boolean changed; 810 if (ws == null) { 811 changed = mWorkSource != null; 812 mWorkSource = null; 813 } else if (mWorkSource == null) { 814 changed = true; 815 mWorkSource = new WorkSource(ws); 816 } else { 817 changed = mWorkSource.diff(ws); 818 if (changed) { 819 mWorkSource.set(ws); 820 } 821 } 822 823 if (changed && mHeld) { 824 try { 825 mService.updateWakeLockWorkSource(mToken, mWorkSource); 826 } catch (RemoteException e) { 827 } 828 } 829 } 830 } 831 832 @Override 833 public String toString() { 834 synchronized (mToken) { 835 return "WakeLock{" 836 + Integer.toHexString(System.identityHashCode(this)) 837 + " held=" + mHeld + ", refCount=" + mCount + "}"; 838 } 839 } 840 } 841} 842