DreamService.java revision 7b9c912f536925ac6ec43935d6e97506851b33d6
1/** 2 * Copyright (C) 2012 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 */ 16package android.service.dreams; 17 18import java.io.FileDescriptor; 19import java.io.PrintWriter; 20 21import android.annotation.IdRes; 22import android.annotation.LayoutRes; 23import android.annotation.Nullable; 24import android.annotation.SdkConstant; 25import android.annotation.SdkConstant.SdkConstantType; 26import android.app.AlarmManager; 27import android.app.Service; 28import android.content.Intent; 29import android.graphics.PixelFormat; 30import android.graphics.drawable.ColorDrawable; 31import android.os.Handler; 32import android.os.IBinder; 33import android.os.PowerManager; 34import android.os.RemoteException; 35import android.os.ServiceManager; 36import android.util.Slog; 37import android.view.ActionMode; 38import android.view.Display; 39import android.view.KeyEvent; 40import android.view.Menu; 41import android.view.MenuItem; 42import android.view.MotionEvent; 43import android.view.PhoneWindow; 44import android.view.View; 45import android.view.ViewGroup; 46import android.view.Window; 47import android.view.WindowManager; 48import android.view.WindowManagerGlobal; 49import android.view.WindowManager.LayoutParams; 50import android.view.accessibility.AccessibilityEvent; 51import android.util.MathUtils; 52 53import com.android.internal.util.DumpUtils; 54import com.android.internal.util.DumpUtils.Dump; 55 56/** 57 * Extend this class to implement a custom dream (available to the user as a "Daydream"). 58 * 59 * <p>Dreams are interactive screensavers launched when a charging device is idle, or docked in a 60 * desk dock. Dreams provide another modality for apps to express themselves, tailored for 61 * an exhibition/lean-back experience.</p> 62 * 63 * <p>The {@code DreamService} lifecycle is as follows:</p> 64 * <ol> 65 * <li>{@link #onAttachedToWindow} 66 * <p>Use this for initial setup, such as calling {@link #setContentView setContentView()}.</li> 67 * <li>{@link #onDreamingStarted} 68 * <p>Your dream has started, so you should begin animations or other behaviors here.</li> 69 * <li>{@link #onDreamingStopped} 70 * <p>Use this to stop the things you started in {@link #onDreamingStarted}.</li> 71 * <li>{@link #onDetachedFromWindow} 72 * <p>Use this to dismantle resources (for example, detach from handlers 73 * and listeners).</li> 74 * </ol> 75 * 76 * <p>In addition, onCreate and onDestroy (from the Service interface) will also be called, but 77 * initialization and teardown should be done by overriding the hooks above.</p> 78 * 79 * <p>To be available to the system, your {@code DreamService} should be declared in the 80 * manifest as follows:</p> 81 * <pre> 82 * <service 83 * android:name=".MyDream" 84 * android:exported="true" 85 * android:icon="@drawable/my_icon" 86 * android:label="@string/my_dream_label" > 87 * 88 * <intent-filter> 89 * <action android:name="android.service.dreams.DreamService" /> 90 * <category android:name="android.intent.category.DEFAULT" /> 91 * </intent-filter> 92 * 93 * <!-- Point to additional information for this dream (optional) --> 94 * <meta-data 95 * android:name="android.service.dream" 96 * android:resource="@xml/my_dream" /> 97 * </service> 98 * </pre> 99 * 100 * <p>If specified with the {@code <meta-data>} element, 101 * additional information for the dream is defined using the 102 * {@link android.R.styleable#Dream <dream>} element in a separate XML file. 103 * Currently, the only addtional 104 * information you can provide is for a settings activity that allows the user to configure 105 * the dream behavior. For example:</p> 106 * <p class="code-caption">res/xml/my_dream.xml</p> 107 * <pre> 108 * <dream xmlns:android="http://schemas.android.com/apk/res/android" 109 * android:settingsActivity="com.example.app/.MyDreamSettingsActivity" /> 110 * </pre> 111 * <p>This makes a Settings button available alongside your dream's listing in the 112 * system settings, which when pressed opens the specified activity.</p> 113 * 114 * 115 * <p>To specify your dream layout, call {@link #setContentView}, typically during the 116 * {@link #onAttachedToWindow} callback. For example:</p> 117 * <pre> 118 * public class MyDream extends DreamService { 119 * 120 * @Override 121 * public void onAttachedToWindow() { 122 * super.onAttachedToWindow(); 123 * 124 * // Exit dream upon user touch 125 * setInteractive(false); 126 * // Hide system UI 127 * setFullscreen(true); 128 * // Set the dream layout 129 * setContentView(R.layout.dream); 130 * } 131 * } 132 * </pre> 133 * 134 * <p>When targeting api level 21 and above, you must declare the service in your manifest file 135 * with the {@link android.Manifest.permission#BIND_DREAM_SERVICE} permission. For example:</p> 136 * <pre> 137 * <service 138 * android:name=".MyDream" 139 * android:exported="true" 140 * android:icon="@drawable/my_icon" 141 * android:label="@string/my_dream_label" 142 * android:permission="android.permission.BIND_DREAM_SERVICE"> 143 * <intent-filter> 144 * <action android:name=”android.service.dreams.DreamService” /> 145 * <category android:name=”android.intent.category.DEFAULT” /> 146 * </intent-filter> 147 * </service> 148 * </pre> 149 */ 150public class DreamService extends Service implements Window.Callback { 151 private final String TAG = DreamService.class.getSimpleName() + "[" + getClass().getSimpleName() + "]"; 152 153 /** 154 * The name of the dream manager service. 155 * @hide 156 */ 157 public static final String DREAM_SERVICE = "dreams"; 158 159 /** 160 * The {@link Intent} that must be declared as handled by the service. 161 */ 162 @SdkConstant(SdkConstantType.SERVICE_ACTION) 163 public static final String SERVICE_INTERFACE = 164 "android.service.dreams.DreamService"; 165 166 /** 167 * Name under which a Dream publishes information about itself. 168 * This meta-data must reference an XML resource containing 169 * a <code><{@link android.R.styleable#Dream dream}></code> 170 * tag. 171 */ 172 public static final String DREAM_META_DATA = "android.service.dream"; 173 174 private final IDreamManager mSandman; 175 private final Handler mHandler = new Handler(); 176 private IBinder mWindowToken; 177 private Window mWindow; 178 private boolean mInteractive; 179 private boolean mLowProfile = true; 180 private boolean mFullscreen; 181 private boolean mScreenBright = true; 182 private boolean mStarted; 183 private boolean mWaking; 184 private boolean mFinished; 185 private boolean mCanDoze; 186 private boolean mDozing; 187 private boolean mWindowless; 188 private int mDozeScreenState = Display.STATE_UNKNOWN; 189 private int mDozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT; 190 191 private boolean mDebug = false; 192 193 public DreamService() { 194 mSandman = IDreamManager.Stub.asInterface(ServiceManager.getService(DREAM_SERVICE)); 195 } 196 197 /** 198 * @hide 199 */ 200 public void setDebug(boolean dbg) { 201 mDebug = dbg; 202 } 203 204 // begin Window.Callback methods 205 /** {@inheritDoc} */ 206 @Override 207 public boolean dispatchKeyEvent(KeyEvent event) { 208 // TODO: create more flexible version of mInteractive that allows use of KEYCODE_BACK 209 if (!mInteractive) { 210 if (mDebug) Slog.v(TAG, "Waking up on keyEvent"); 211 wakeUp(); 212 return true; 213 } else if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { 214 if (mDebug) Slog.v(TAG, "Waking up on back key"); 215 wakeUp(); 216 return true; 217 } 218 return mWindow.superDispatchKeyEvent(event); 219 } 220 221 /** {@inheritDoc} */ 222 @Override 223 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 224 if (!mInteractive) { 225 if (mDebug) Slog.v(TAG, "Waking up on keyShortcutEvent"); 226 wakeUp(); 227 return true; 228 } 229 return mWindow.superDispatchKeyShortcutEvent(event); 230 } 231 232 /** {@inheritDoc} */ 233 @Override 234 public boolean dispatchTouchEvent(MotionEvent event) { 235 // TODO: create more flexible version of mInteractive that allows clicks 236 // but finish()es on any other kind of activity 237 if (!mInteractive) { 238 if (mDebug) Slog.v(TAG, "Waking up on touchEvent"); 239 wakeUp(); 240 return true; 241 } 242 return mWindow.superDispatchTouchEvent(event); 243 } 244 245 /** {@inheritDoc} */ 246 @Override 247 public boolean dispatchTrackballEvent(MotionEvent event) { 248 if (!mInteractive) { 249 if (mDebug) Slog.v(TAG, "Waking up on trackballEvent"); 250 wakeUp(); 251 return true; 252 } 253 return mWindow.superDispatchTrackballEvent(event); 254 } 255 256 /** {@inheritDoc} */ 257 @Override 258 public boolean dispatchGenericMotionEvent(MotionEvent event) { 259 if (!mInteractive) { 260 if (mDebug) Slog.v(TAG, "Waking up on genericMotionEvent"); 261 wakeUp(); 262 return true; 263 } 264 return mWindow.superDispatchGenericMotionEvent(event); 265 } 266 267 /** {@inheritDoc} */ 268 @Override 269 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 270 return false; 271 } 272 273 /** {@inheritDoc} */ 274 @Override 275 public View onCreatePanelView(int featureId) { 276 return null; 277 } 278 279 /** {@inheritDoc} */ 280 @Override 281 public boolean onCreatePanelMenu(int featureId, Menu menu) { 282 return false; 283 } 284 285 /** {@inheritDoc} */ 286 @Override 287 public boolean onPreparePanel(int featureId, View view, Menu menu) { 288 return false; 289 } 290 291 /** {@inheritDoc} */ 292 @Override 293 public boolean onMenuOpened(int featureId, Menu menu) { 294 return false; 295 } 296 297 /** {@inheritDoc} */ 298 @Override 299 public boolean onMenuItemSelected(int featureId, MenuItem item) { 300 return false; 301 } 302 303 /** {@inheritDoc} */ 304 @Override 305 public void onWindowAttributesChanged(LayoutParams attrs) { 306 } 307 308 /** {@inheritDoc} */ 309 @Override 310 public void onContentChanged() { 311 } 312 313 /** {@inheritDoc} */ 314 @Override 315 public void onWindowFocusChanged(boolean hasFocus) { 316 } 317 318 /** {@inheritDoc} */ 319 @Override 320 public void onAttachedToWindow() { 321 } 322 323 /** {@inheritDoc} */ 324 @Override 325 public void onDetachedFromWindow() { 326 } 327 328 /** {@inheritDoc} */ 329 @Override 330 public void onPanelClosed(int featureId, Menu menu) { 331 } 332 333 /** {@inheritDoc} */ 334 @Override 335 public boolean onSearchRequested() { 336 return false; 337 } 338 339 /** {@inheritDoc} */ 340 @Override 341 public ActionMode onWindowStartingActionMode(android.view.ActionMode.Callback callback) { 342 return null; 343 } 344 345 /** {@inheritDoc} */ 346 @Override 347 public void onActionModeStarted(ActionMode mode) { 348 } 349 350 /** {@inheritDoc} */ 351 @Override 352 public void onActionModeFinished(ActionMode mode) { 353 } 354 // end Window.Callback methods 355 356 // begin public api 357 /** 358 * Retrieves the current {@link android.view.WindowManager} for the dream. 359 * Behaves similarly to {@link android.app.Activity#getWindowManager()}. 360 * 361 * @return The current window manager, or null if the dream is not started. 362 */ 363 public WindowManager getWindowManager() { 364 return mWindow != null ? mWindow.getWindowManager() : null; 365 } 366 367 /** 368 * Retrieves the current {@link android.view.Window} for the dream. 369 * Behaves similarly to {@link android.app.Activity#getWindow()}. 370 * 371 * @return The current window, or null if the dream is not started. 372 */ 373 public Window getWindow() { 374 return mWindow; 375 } 376 377 /** 378 * Inflates a layout resource and set it to be the content view for this Dream. 379 * Behaves similarly to {@link android.app.Activity#setContentView(int)}. 380 * 381 * <p>Note: Requires a window, do not call before {@link #onAttachedToWindow()}</p> 382 * 383 * @param layoutResID Resource ID to be inflated. 384 * 385 * @see #setContentView(android.view.View) 386 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams) 387 */ 388 public void setContentView(@LayoutRes int layoutResID) { 389 getWindow().setContentView(layoutResID); 390 } 391 392 /** 393 * Sets a view to be the content view for this Dream. 394 * Behaves similarly to {@link android.app.Activity#setContentView(android.view.View)} in an activity, 395 * including using {@link ViewGroup.LayoutParams#MATCH_PARENT} as the layout height and width of the view. 396 * 397 * <p>Note: This requires a window, so you should usually call it during 398 * {@link #onAttachedToWindow()} and never earlier (you <strong>cannot</strong> call it 399 * during {@link #onCreate}).</p> 400 * 401 * @see #setContentView(int) 402 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams) 403 */ 404 public void setContentView(View view) { 405 getWindow().setContentView(view); 406 } 407 408 /** 409 * Sets a view to be the content view for this Dream. 410 * Behaves similarly to 411 * {@link android.app.Activity#setContentView(android.view.View, android.view.ViewGroup.LayoutParams)} 412 * in an activity. 413 * 414 * <p>Note: This requires a window, so you should usually call it during 415 * {@link #onAttachedToWindow()} and never earlier (you <strong>cannot</strong> call it 416 * during {@link #onCreate}).</p> 417 * 418 * @param view The desired content to display. 419 * @param params Layout parameters for the view. 420 * 421 * @see #setContentView(android.view.View) 422 * @see #setContentView(int) 423 */ 424 public void setContentView(View view, ViewGroup.LayoutParams params) { 425 getWindow().setContentView(view, params); 426 } 427 428 /** 429 * Adds a view to the Dream's window, leaving other content views in place. 430 * 431 * <p>Note: Requires a window, do not call before {@link #onAttachedToWindow()}</p> 432 * 433 * @param view The desired content to display. 434 * @param params Layout parameters for the view. 435 */ 436 public void addContentView(View view, ViewGroup.LayoutParams params) { 437 getWindow().addContentView(view, params); 438 } 439 440 /** 441 * Finds a view that was identified by the id attribute from the XML that 442 * was processed in {@link #onCreate}. 443 * 444 * <p>Note: Requires a window, do not call before {@link #onAttachedToWindow()}</p> 445 * 446 * @return The view if found or null otherwise. 447 */ 448 @Nullable 449 public View findViewById(@IdRes int id) { 450 return getWindow().findViewById(id); 451 } 452 453 /** 454 * Marks this dream as interactive to receive input events. 455 * 456 * <p>Non-interactive dreams (default) will dismiss on the first input event.</p> 457 * 458 * <p>Interactive dreams should call {@link #finish()} to dismiss themselves.</p> 459 * 460 * @param interactive True if this dream will handle input events. 461 */ 462 public void setInteractive(boolean interactive) { 463 mInteractive = interactive; 464 } 465 466 /** 467 * Returns whether or not this dream is interactive. Defaults to false. 468 * 469 * @see #setInteractive(boolean) 470 */ 471 public boolean isInteractive() { 472 return mInteractive; 473 } 474 475 /** 476 * Sets View.SYSTEM_UI_FLAG_LOW_PROFILE on the content view. 477 * 478 * @param lowProfile True to set View.SYSTEM_UI_FLAG_LOW_PROFILE 479 * @hide There is no reason to have this -- dreams can set this flag 480 * on their own content view, and from there can actually do the 481 * correct interactions with it (seeing when it is cleared etc). 482 */ 483 public void setLowProfile(boolean lowProfile) { 484 if (mLowProfile != lowProfile) { 485 mLowProfile = lowProfile; 486 int flag = View.SYSTEM_UI_FLAG_LOW_PROFILE; 487 applySystemUiVisibilityFlags(mLowProfile ? flag : 0, flag); 488 } 489 } 490 491 /** 492 * Returns whether or not this dream is in low profile mode. Defaults to true. 493 * 494 * @see #setLowProfile(boolean) 495 * @hide 496 */ 497 public boolean isLowProfile() { 498 return getSystemUiVisibilityFlagValue(View.SYSTEM_UI_FLAG_LOW_PROFILE, mLowProfile); 499 } 500 501 /** 502 * Controls {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN} 503 * on the dream's window. 504 * 505 * @param fullscreen If true, the fullscreen flag will be set; else it 506 * will be cleared. 507 */ 508 public void setFullscreen(boolean fullscreen) { 509 if (mFullscreen != fullscreen) { 510 mFullscreen = fullscreen; 511 int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN; 512 applyWindowFlags(mFullscreen ? flag : 0, flag); 513 } 514 } 515 516 /** 517 * Returns whether or not this dream is in fullscreen mode. Defaults to false. 518 * 519 * @see #setFullscreen(boolean) 520 */ 521 public boolean isFullscreen() { 522 return mFullscreen; 523 } 524 525 /** 526 * Marks this dream as keeping the screen bright while dreaming. 527 * 528 * @param screenBright True to keep the screen bright while dreaming. 529 */ 530 public void setScreenBright(boolean screenBright) { 531 if (mScreenBright != screenBright) { 532 mScreenBright = screenBright; 533 int flag = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; 534 applyWindowFlags(mScreenBright ? flag : 0, flag); 535 } 536 } 537 538 /** 539 * Returns whether or not this dream keeps the screen bright while dreaming. 540 * Defaults to false, allowing the screen to dim if necessary. 541 * 542 * @see #setScreenBright(boolean) 543 */ 544 public boolean isScreenBright() { 545 return getWindowFlagValue(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, mScreenBright); 546 } 547 548 /** 549 * Marks this dream as windowless. Only available to doze dreams. 550 * 551 * @hide 552 */ 553 public void setWindowless(boolean windowless) { 554 mWindowless = windowless; 555 } 556 557 /** 558 * Returns whether or not this dream is windowless. Only available to doze dreams. 559 * 560 * @hide 561 */ 562 public boolean isWindowless() { 563 return mWindowless; 564 } 565 566 /** 567 * Returns true if this dream is allowed to doze. 568 * <p> 569 * The value returned by this method is only meaningful when the dream has started. 570 * </p> 571 * 572 * @return True if this dream can doze. 573 * @see #startDozing 574 * @hide For use by system UI components only. 575 */ 576 public boolean canDoze() { 577 return mCanDoze; 578 } 579 580 /** 581 * Starts dozing, entering a deep dreamy sleep. 582 * <p> 583 * Dozing enables the system to conserve power while the user is not actively interacting 584 * with the device. While dozing, the display will remain on in a low-power state 585 * and will continue to show its previous contents but the application processor and 586 * other system components will be allowed to suspend when possible. 587 * </p><p> 588 * While the application processor is suspended, the dream may stop executing code 589 * for long periods of time. Prior to being suspended, the dream may schedule periodic 590 * wake-ups to render new content by scheduling an alarm with the {@link AlarmManager}. 591 * The dream may also keep the CPU awake by acquiring a 592 * {@link android.os.PowerManager#PARTIAL_WAKE_LOCK partial wake lock} when necessary. 593 * Note that since the purpose of doze mode is to conserve power (especially when 594 * running on battery), the dream should not wake the CPU very often or keep it 595 * awake for very long. 596 * </p><p> 597 * It is a good idea to call this method some time after the dream's entry animation 598 * has completed and the dream is ready to doze. It is important to completely 599 * finish all of the work needed before dozing since the application processor may 600 * be suspended at any moment once this method is called unless other wake locks 601 * are being held. 602 * </p><p> 603 * Call {@link #stopDozing} or {@link #finish} to stop dozing. 604 * </p> 605 * 606 * @see #stopDozing 607 * @hide For use by system UI components only. 608 */ 609 public void startDozing() { 610 if (mCanDoze && !mDozing) { 611 mDozing = true; 612 updateDoze(); 613 } 614 } 615 616 private void updateDoze() { 617 if (mDozing) { 618 try { 619 mSandman.startDozing(mWindowToken, mDozeScreenState, mDozeScreenBrightness); 620 } catch (RemoteException ex) { 621 // system server died 622 } 623 } 624 } 625 626 /** 627 * Stops dozing, returns to active dreaming. 628 * <p> 629 * This method reverses the effect of {@link #startDozing}. From this moment onward, 630 * the application processor will be kept awake as long as the dream is running 631 * or until the dream starts dozing again. 632 * </p> 633 * 634 * @see #startDozing 635 * @hide For use by system UI components only. 636 */ 637 public void stopDozing() { 638 if (mDozing) { 639 mDozing = false; 640 try { 641 mSandman.stopDozing(mWindowToken); 642 } catch (RemoteException ex) { 643 // system server died 644 } 645 } 646 } 647 648 /** 649 * Returns true if the dream will allow the system to enter a low-power state while 650 * it is running without actually turning off the screen. Defaults to false, 651 * keeping the application processor awake while the dream is running. 652 * 653 * @return True if the dream is dozing. 654 * 655 * @see #setDozing(boolean) 656 * @hide For use by system UI components only. 657 */ 658 public boolean isDozing() { 659 return mDozing; 660 } 661 662 /** 663 * Gets the screen state to use while dozing. 664 * 665 * @return The screen state to use while dozing, such as {@link Display#STATE_ON}, 666 * {@link Display#STATE_DOZE}, {@link Display#STATE_DOZE_SUSPEND}, 667 * or {@link Display#STATE_OFF}, or {@link Display#STATE_UNKNOWN} for the default 668 * behavior. 669 * 670 * @see #setDozeScreenState 671 * @hide For use by system UI components only. 672 */ 673 public int getDozeScreenState() { 674 return mDozeScreenState; 675 } 676 677 /** 678 * Sets the screen state to use while dozing. 679 * <p> 680 * The value of this property determines the power state of the primary display 681 * once {@link #startDozing} has been called. The default value is 682 * {@link Display#STATE_UNKNOWN} which lets the system decide. 683 * The dream may set a different state before starting to doze and may 684 * perform transitions between states while dozing to conserve power and 685 * achieve various effects. 686 * </p><p> 687 * It is recommended that the state be set to {@link Display#STATE_DOZE_SUSPEND} 688 * once the dream has completely finished drawing and before it releases its wakelock 689 * to allow the display hardware to be fully suspended. While suspended, the 690 * display will preserve its on-screen contents or hand off control to dedicated 691 * doze hardware if the devices supports it. If the doze suspend state is 692 * used, the dream must make sure to set the mode back 693 * to {@link Display#STATE_DOZE} or {@link Display#STATE_ON} before drawing again 694 * since the display updates may be ignored and not seen by the user otherwise. 695 * </p><p> 696 * The set of available display power states and their behavior while dozing is 697 * hardware dependent and may vary across devices. The dream may therefore 698 * need to be modified or configured to correctly support the hardware. 699 * </p> 700 * 701 * @param state The screen state to use while dozing, such as {@link Display#STATE_ON}, 702 * {@link Display#STATE_DOZE}, {@link Display#STATE_DOZE_SUSPEND}, 703 * or {@link Display#STATE_OFF}, or {@link Display#STATE_UNKNOWN} for the default 704 * behavior. 705 * 706 * @hide For use by system UI components only. 707 */ 708 public void setDozeScreenState(int state) { 709 if (mDozeScreenState != state) { 710 mDozeScreenState = state; 711 updateDoze(); 712 } 713 } 714 715 /** 716 * Gets the screen brightness to use while dozing. 717 * 718 * @return The screen brightness while dozing as a value between 719 * {@link PowerManager#BRIGHTNESS_OFF} (0) and {@link PowerManager#BRIGHTNESS_ON} (255), 720 * or {@link PowerManager#BRIGHTNESS_DEFAULT} (-1) to ask the system to apply 721 * its default policy based on the screen state. 722 * 723 * @see #setDozeScreenBrightness 724 * @hide For use by system UI components only. 725 */ 726 public int getDozeScreenBrightness() { 727 return mDozeScreenBrightness; 728 } 729 730 /** 731 * Sets the screen brightness to use while dozing. 732 * <p> 733 * The value of this property determines the power state of the primary display 734 * once {@link #startDozing} has been called. The default value is 735 * {@link PowerManager#BRIGHTNESS_DEFAULT} which lets the system decide. 736 * The dream may set a different brightness before starting to doze and may adjust 737 * the brightness while dozing to conserve power and achieve various effects. 738 * </p><p> 739 * Note that dream may specify any brightness in the full 0-255 range, including 740 * values that are less than the minimum value for manual screen brightness 741 * adjustments by the user. In particular, the value may be set to 0 which may 742 * turn off the backlight entirely while still leaving the screen on although 743 * this behavior is device dependent and not guaranteed. 744 * </p><p> 745 * The available range of display brightness values and their behavior while dozing is 746 * hardware dependent and may vary across devices. The dream may therefore 747 * need to be modified or configured to correctly support the hardware. 748 * </p> 749 * 750 * @param brightness The screen brightness while dozing as a value between 751 * {@link PowerManager#BRIGHTNESS_OFF} (0) and {@link PowerManager#BRIGHTNESS_ON} (255), 752 * or {@link PowerManager#BRIGHTNESS_DEFAULT} (-1) to ask the system to apply 753 * its default policy based on the screen state. 754 * 755 * @hide For use by system UI components only. 756 */ 757 public void setDozeScreenBrightness(int brightness) { 758 if (brightness != PowerManager.BRIGHTNESS_DEFAULT) { 759 brightness = clampAbsoluteBrightness(brightness); 760 } 761 if (mDozeScreenBrightness != brightness) { 762 mDozeScreenBrightness = brightness; 763 updateDoze(); 764 } 765 } 766 767 /** 768 * Called when this Dream is constructed. 769 */ 770 @Override 771 public void onCreate() { 772 if (mDebug) Slog.v(TAG, "onCreate()"); 773 super.onCreate(); 774 } 775 776 /** 777 * Called when the dream's window has been created and is visible and animation may now begin. 778 */ 779 public void onDreamingStarted() { 780 if (mDebug) Slog.v(TAG, "onDreamingStarted()"); 781 // hook for subclasses 782 } 783 784 /** 785 * Called when this Dream is stopped, either by external request or by calling finish(), 786 * before the window has been removed. 787 */ 788 public void onDreamingStopped() { 789 if (mDebug) Slog.v(TAG, "onDreamingStopped()"); 790 // hook for subclasses 791 } 792 793 /** 794 * Called when the dream is being asked to stop itself and wake. 795 * <p> 796 * The default implementation simply calls {@link #finish} which ends the dream 797 * immediately. Subclasses may override this function to perform a smooth exit 798 * transition then call {@link #finish} afterwards. 799 * </p><p> 800 * Note that the dream will only be given a short period of time (currently about 801 * five seconds) to wake up. If the dream does not finish itself in a timely manner 802 * then the system will forcibly finish it once the time allowance is up. 803 * </p> 804 */ 805 public void onWakeUp() { 806 finish(); 807 } 808 809 /** {@inheritDoc} */ 810 @Override 811 public final IBinder onBind(Intent intent) { 812 if (mDebug) Slog.v(TAG, "onBind() intent = " + intent); 813 return new DreamServiceWrapper(); 814 } 815 816 /** 817 * Stops the dream and detaches from the window. 818 * <p> 819 * When the dream ends, the system will be allowed to go to sleep fully unless there 820 * is a reason for it to be awake such as recent user activity or wake locks being held. 821 * </p> 822 */ 823 public final void finish() { 824 if (mDebug) Slog.v(TAG, "finish(): mFinished=" + mFinished); 825 826 if (!mFinished) { 827 mFinished = true; 828 829 if (mWindowToken == null) { 830 Slog.w(TAG, "Finish was called before the dream was attached."); 831 } else { 832 try { 833 mSandman.finishSelf(mWindowToken, true /*immediate*/); 834 } catch (RemoteException ex) { 835 // system server died 836 } 837 } 838 839 stopSelf(); // if launched via any other means 840 } 841 } 842 843 /** 844 * Wakes the dream up gently. 845 * <p> 846 * Calls {@link #onWakeUp} to give the dream a chance to perform an exit transition. 847 * When the transition is over, the dream should call {@link #finish}. 848 * </p> 849 */ 850 public final void wakeUp() { 851 wakeUp(false); 852 } 853 854 private void wakeUp(boolean fromSystem) { 855 if (mDebug) Slog.v(TAG, "wakeUp(): fromSystem=" + fromSystem 856 + ", mWaking=" + mWaking + ", mFinished=" + mFinished); 857 858 if (!mWaking && !mFinished) { 859 mWaking = true; 860 861 // As a minor optimization, invoke the callback first in case it simply 862 // calls finish() immediately so there wouldn't be much point in telling 863 // the system that we are finishing the dream gently. 864 onWakeUp(); 865 866 // Now tell the system we are waking gently, unless we already told 867 // it we were finishing immediately. 868 if (!fromSystem && !mFinished) { 869 if (mWindowToken == null) { 870 Slog.w(TAG, "WakeUp was called before the dream was attached."); 871 } else { 872 try { 873 mSandman.finishSelf(mWindowToken, false /*immediate*/); 874 } catch (RemoteException ex) { 875 // system server died 876 } 877 } 878 } 879 } 880 } 881 882 /** {@inheritDoc} */ 883 @Override 884 public void onDestroy() { 885 if (mDebug) Slog.v(TAG, "onDestroy()"); 886 // hook for subclasses 887 888 // Just in case destroy came in before detach, let's take care of that now 889 detach(); 890 891 super.onDestroy(); 892 } 893 894 // end public api 895 896 /** 897 * Called by DreamController.stopDream() when the Dream is about to be unbound and destroyed. 898 * 899 * Must run on mHandler. 900 */ 901 private final void detach() { 902 if (mStarted) { 903 if (mDebug) Slog.v(TAG, "detach(): Calling onDreamingStopped()"); 904 mStarted = false; 905 onDreamingStopped(); 906 } 907 908 if (mWindow != null) { 909 // force our window to be removed synchronously 910 if (mDebug) Slog.v(TAG, "detach(): Removing window from window manager"); 911 mWindow.getWindowManager().removeViewImmediate(mWindow.getDecorView()); 912 mWindow = null; 913 } 914 915 if (mWindowToken != null) { 916 // the following will print a log message if it finds any other leaked windows 917 WindowManagerGlobal.getInstance().closeAll(mWindowToken, 918 this.getClass().getName(), "Dream"); 919 mWindowToken = null; 920 mCanDoze = false; 921 } 922 } 923 924 /** 925 * Called when the Dream is ready to be shown. 926 * 927 * Must run on mHandler. 928 * 929 * @param windowToken A window token that will allow a window to be created in the correct layer. 930 */ 931 private final void attach(IBinder windowToken, boolean canDoze) { 932 if (mWindowToken != null) { 933 Slog.e(TAG, "attach() called when already attached with token=" + mWindowToken); 934 return; 935 } 936 if (mFinished || mWaking) { 937 Slog.w(TAG, "attach() called after dream already finished"); 938 try { 939 mSandman.finishSelf(windowToken, true /*immediate*/); 940 } catch (RemoteException ex) { 941 // system server died 942 } 943 return; 944 } 945 946 mWindowToken = windowToken; 947 mCanDoze = canDoze; 948 if (mWindowless && !mCanDoze) { 949 throw new IllegalStateException("Only doze dreams can be windowless"); 950 } 951 if (!mWindowless) { 952 mWindow = new PhoneWindow(this); 953 mWindow.setCallback(this); 954 mWindow.requestFeature(Window.FEATURE_NO_TITLE); 955 mWindow.setBackgroundDrawable(new ColorDrawable(0xFF000000)); 956 mWindow.setFormat(PixelFormat.OPAQUE); 957 958 if (mDebug) Slog.v(TAG, String.format("Attaching window token: %s to window of type %s", 959 windowToken, WindowManager.LayoutParams.TYPE_DREAM)); 960 961 WindowManager.LayoutParams lp = mWindow.getAttributes(); 962 lp.type = WindowManager.LayoutParams.TYPE_DREAM; 963 lp.token = windowToken; 964 lp.windowAnimations = com.android.internal.R.style.Animation_Dream; 965 lp.flags |= ( WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN 966 | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR 967 | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED 968 | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD 969 | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON 970 | (mFullscreen ? WindowManager.LayoutParams.FLAG_FULLSCREEN : 0) 971 | (mScreenBright ? WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON : 0) 972 ); 973 mWindow.setAttributes(lp); 974 // Workaround: Currently low-profile and in-window system bar backgrounds don't go 975 // along well. Dreams usually don't need such bars anyways, so disable them by default. 976 mWindow.clearFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); 977 mWindow.setWindowManager(null, windowToken, "dream", true); 978 979 applySystemUiVisibilityFlags( 980 (mLowProfile ? View.SYSTEM_UI_FLAG_LOW_PROFILE : 0), 981 View.SYSTEM_UI_FLAG_LOW_PROFILE); 982 983 try { 984 getWindowManager().addView(mWindow.getDecorView(), mWindow.getAttributes()); 985 } catch (WindowManager.BadTokenException ex) { 986 // This can happen because the dream manager service will remove the token 987 // immediately without necessarily waiting for the dream to start. 988 // We should receive a finish message soon. 989 Slog.i(TAG, "attach() called after window token already removed, dream will " 990 + "finish soon"); 991 mWindow = null; 992 return; 993 } 994 } 995 // We need to defer calling onDreamingStarted until after onWindowAttached, 996 // which is posted to the handler by addView, so we post onDreamingStarted 997 // to the handler also. Need to watch out here in case detach occurs before 998 // this callback is invoked. 999 mHandler.post(new Runnable() { 1000 @Override 1001 public void run() { 1002 if (mWindow != null || mWindowless) { 1003 if (mDebug) Slog.v(TAG, "Calling onDreamingStarted()"); 1004 mStarted = true; 1005 onDreamingStarted(); 1006 } 1007 } 1008 }); 1009 } 1010 1011 private boolean getWindowFlagValue(int flag, boolean defaultValue) { 1012 return mWindow == null ? defaultValue : (mWindow.getAttributes().flags & flag) != 0; 1013 } 1014 1015 private void applyWindowFlags(int flags, int mask) { 1016 if (mWindow != null) { 1017 WindowManager.LayoutParams lp = mWindow.getAttributes(); 1018 lp.flags = applyFlags(lp.flags, flags, mask); 1019 mWindow.setAttributes(lp); 1020 mWindow.getWindowManager().updateViewLayout(mWindow.getDecorView(), lp); 1021 } 1022 } 1023 1024 private boolean getSystemUiVisibilityFlagValue(int flag, boolean defaultValue) { 1025 View v = mWindow == null ? null : mWindow.getDecorView(); 1026 return v == null ? defaultValue : (v.getSystemUiVisibility() & flag) != 0; 1027 } 1028 1029 private void applySystemUiVisibilityFlags(int flags, int mask) { 1030 View v = mWindow == null ? null : mWindow.getDecorView(); 1031 if (v != null) { 1032 v.setSystemUiVisibility(applyFlags(v.getSystemUiVisibility(), flags, mask)); 1033 } 1034 } 1035 1036 private int applyFlags(int oldFlags, int flags, int mask) { 1037 return (oldFlags&~mask) | (flags&mask); 1038 } 1039 1040 @Override 1041 protected void dump(final FileDescriptor fd, PrintWriter pw, final String[] args) { 1042 DumpUtils.dumpAsync(mHandler, new Dump() { 1043 @Override 1044 public void dump(PrintWriter pw, String prefix) { 1045 dumpOnHandler(fd, pw, args); 1046 } 1047 }, pw, "", 1000); 1048 } 1049 1050 /** @hide */ 1051 protected void dumpOnHandler(FileDescriptor fd, PrintWriter pw, String[] args) { 1052 pw.print(TAG + ": "); 1053 if (mWindowToken == null) { 1054 pw.println("stopped"); 1055 } else { 1056 pw.println("running (token=" + mWindowToken + ")"); 1057 } 1058 pw.println(" window: " + mWindow); 1059 pw.print(" flags:"); 1060 if (isInteractive()) pw.print(" interactive"); 1061 if (isLowProfile()) pw.print(" lowprofile"); 1062 if (isFullscreen()) pw.print(" fullscreen"); 1063 if (isScreenBright()) pw.print(" bright"); 1064 if (isWindowless()) pw.print(" windowless"); 1065 if (isDozing()) pw.print(" dozing"); 1066 else if (canDoze()) pw.print(" candoze"); 1067 pw.println(); 1068 if (canDoze()) { 1069 pw.println(" doze screen state: " + Display.stateToString(mDozeScreenState)); 1070 pw.println(" doze screen brightness: " + mDozeScreenBrightness); 1071 } 1072 } 1073 1074 private static int clampAbsoluteBrightness(int value) { 1075 return MathUtils.constrain(value, PowerManager.BRIGHTNESS_OFF, PowerManager.BRIGHTNESS_ON); 1076 } 1077 1078 private final class DreamServiceWrapper extends IDreamService.Stub { 1079 @Override 1080 public void attach(final IBinder windowToken, final boolean canDoze) { 1081 mHandler.post(new Runnable() { 1082 @Override 1083 public void run() { 1084 DreamService.this.attach(windowToken, canDoze); 1085 } 1086 }); 1087 } 1088 1089 @Override 1090 public void detach() { 1091 mHandler.post(new Runnable() { 1092 @Override 1093 public void run() { 1094 DreamService.this.detach(); 1095 } 1096 }); 1097 } 1098 1099 @Override 1100 public void wakeUp() { 1101 mHandler.post(new Runnable() { 1102 @Override 1103 public void run() { 1104 DreamService.this.wakeUp(true /*fromSystem*/); 1105 } 1106 }); 1107 } 1108 } 1109} 1110