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