DreamService.java revision 970d4132ea28e748c1010be39450a98bbf7466f3
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.SdkConstant; 22import android.annotation.SdkConstant.SdkConstantType; 23import android.app.AlarmManager; 24import android.app.Service; 25import android.content.Intent; 26import android.graphics.PixelFormat; 27import android.graphics.drawable.ColorDrawable; 28import android.os.Handler; 29import android.os.IBinder; 30import android.os.PowerManager; 31import android.os.RemoteException; 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.View; 42import android.view.ViewGroup; 43import android.view.Window; 44import android.view.WindowManager; 45import android.view.WindowManagerGlobal; 46import android.view.WindowManager.LayoutParams; 47import android.view.accessibility.AccessibilityEvent; 48import android.util.MathUtils; 49 50import com.android.internal.policy.PolicyManager; 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 DozeHardware mDozeHardware; 187 private int mDozeScreenState = Display.STATE_UNKNOWN; 188 private int mDozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT; 189 190 private boolean mDebug = false; 191 192 public DreamService() { 193 mSandman = IDreamManager.Stub.asInterface(ServiceManager.getService(DREAM_SERVICE)); 194 } 195 196 /** 197 * @hide 198 */ 199 public void setDebug(boolean dbg) { 200 mDebug = dbg; 201 } 202 203 // begin Window.Callback methods 204 /** {@inheritDoc} */ 205 @Override 206 public boolean dispatchKeyEvent(KeyEvent event) { 207 // TODO: create more flexible version of mInteractive that allows use of KEYCODE_BACK 208 if (!mInteractive) { 209 if (mDebug) Slog.v(TAG, "Waking up on keyEvent"); 210 wakeUp(); 211 return true; 212 } else if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { 213 if (mDebug) Slog.v(TAG, "Waking up on back key"); 214 wakeUp(); 215 return true; 216 } 217 return mWindow.superDispatchKeyEvent(event); 218 } 219 220 /** {@inheritDoc} */ 221 @Override 222 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 223 if (!mInteractive) { 224 if (mDebug) Slog.v(TAG, "Waking up on keyShortcutEvent"); 225 wakeUp(); 226 return true; 227 } 228 return mWindow.superDispatchKeyShortcutEvent(event); 229 } 230 231 /** {@inheritDoc} */ 232 @Override 233 public boolean dispatchTouchEvent(MotionEvent event) { 234 // TODO: create more flexible version of mInteractive that allows clicks 235 // but finish()es on any other kind of activity 236 if (!mInteractive) { 237 if (mDebug) Slog.v(TAG, "Waking up on touchEvent"); 238 wakeUp(); 239 return true; 240 } 241 return mWindow.superDispatchTouchEvent(event); 242 } 243 244 /** {@inheritDoc} */ 245 @Override 246 public boolean dispatchTrackballEvent(MotionEvent event) { 247 if (!mInteractive) { 248 if (mDebug) Slog.v(TAG, "Waking up on trackballEvent"); 249 wakeUp(); 250 return true; 251 } 252 return mWindow.superDispatchTrackballEvent(event); 253 } 254 255 /** {@inheritDoc} */ 256 @Override 257 public boolean dispatchGenericMotionEvent(MotionEvent event) { 258 if (!mInteractive) { 259 if (mDebug) Slog.v(TAG, "Waking up on genericMotionEvent"); 260 wakeUp(); 261 return true; 262 } 263 return mWindow.superDispatchGenericMotionEvent(event); 264 } 265 266 /** {@inheritDoc} */ 267 @Override 268 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 269 return false; 270 } 271 272 /** {@inheritDoc} */ 273 @Override 274 public View onCreatePanelView(int featureId) { 275 return null; 276 } 277 278 /** {@inheritDoc} */ 279 @Override 280 public boolean onCreatePanelMenu(int featureId, Menu menu) { 281 return false; 282 } 283 284 /** {@inheritDoc} */ 285 @Override 286 public boolean onPreparePanel(int featureId, View view, Menu menu) { 287 return false; 288 } 289 290 /** {@inheritDoc} */ 291 @Override 292 public boolean onMenuOpened(int featureId, Menu menu) { 293 return false; 294 } 295 296 /** {@inheritDoc} */ 297 @Override 298 public boolean onMenuItemSelected(int featureId, MenuItem item) { 299 return false; 300 } 301 302 /** {@inheritDoc} */ 303 @Override 304 public void onWindowAttributesChanged(LayoutParams attrs) { 305 } 306 307 /** {@inheritDoc} */ 308 @Override 309 public void onContentChanged() { 310 } 311 312 /** {@inheritDoc} */ 313 @Override 314 public void onWindowFocusChanged(boolean hasFocus) { 315 } 316 317 /** {@inheritDoc} */ 318 @Override 319 public void onAttachedToWindow() { 320 } 321 322 /** {@inheritDoc} */ 323 @Override 324 public void onDetachedFromWindow() { 325 } 326 327 /** {@inheritDoc} */ 328 @Override 329 public void onPanelClosed(int featureId, Menu menu) { 330 } 331 332 /** {@inheritDoc} */ 333 @Override 334 public boolean onSearchRequested() { 335 return false; 336 } 337 338 /** {@inheritDoc} */ 339 @Override 340 public ActionMode onWindowStartingActionMode(android.view.ActionMode.Callback callback) { 341 return null; 342 } 343 344 /** {@inheritDoc} */ 345 @Override 346 public void onActionModeStarted(ActionMode mode) { 347 } 348 349 /** {@inheritDoc} */ 350 @Override 351 public void onActionModeFinished(ActionMode mode) { 352 } 353 // end Window.Callback methods 354 355 // begin public api 356 /** 357 * Retrieves the current {@link android.view.WindowManager} for the dream. 358 * Behaves similarly to {@link android.app.Activity#getWindowManager()}. 359 * 360 * @return The current window manager, or null if the dream is not started. 361 */ 362 public WindowManager getWindowManager() { 363 return mWindow != null ? mWindow.getWindowManager() : null; 364 } 365 366 /** 367 * Retrieves the current {@link android.view.Window} for the dream. 368 * Behaves similarly to {@link android.app.Activity#getWindow()}. 369 * 370 * @return The current window, or null if the dream is not started. 371 */ 372 public Window getWindow() { 373 return mWindow; 374 } 375 376 /** 377 * Inflates a layout resource and set it to be the content view for this Dream. 378 * Behaves similarly to {@link android.app.Activity#setContentView(int)}. 379 * 380 * <p>Note: Requires a window, do not call before {@link #onAttachedToWindow()}</p> 381 * 382 * @param layoutResID Resource ID to be inflated. 383 * 384 * @see #setContentView(android.view.View) 385 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams) 386 */ 387 public void setContentView(int layoutResID) { 388 getWindow().setContentView(layoutResID); 389 } 390 391 /** 392 * Sets a view to be the content view for this Dream. 393 * Behaves similarly to {@link android.app.Activity#setContentView(android.view.View)} in an activity, 394 * including using {@link ViewGroup.LayoutParams#MATCH_PARENT} as the layout height and width of the view. 395 * 396 * <p>Note: This requires a window, so you should usually call it during 397 * {@link #onAttachedToWindow()} and never earlier (you <strong>cannot</strong> call it 398 * during {@link #onCreate}).</p> 399 * 400 * @see #setContentView(int) 401 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams) 402 */ 403 public void setContentView(View view) { 404 getWindow().setContentView(view); 405 } 406 407 /** 408 * Sets a view to be the content view for this Dream. 409 * Behaves similarly to 410 * {@link android.app.Activity#setContentView(android.view.View, android.view.ViewGroup.LayoutParams)} 411 * in an activity. 412 * 413 * <p>Note: This requires a window, so you should usually call it during 414 * {@link #onAttachedToWindow()} and never earlier (you <strong>cannot</strong> call it 415 * during {@link #onCreate}).</p> 416 * 417 * @param view The desired content to display. 418 * @param params Layout parameters for the view. 419 * 420 * @see #setContentView(android.view.View) 421 * @see #setContentView(int) 422 */ 423 public void setContentView(View view, ViewGroup.LayoutParams params) { 424 getWindow().setContentView(view, params); 425 } 426 427 /** 428 * Adds a view to the Dream's window, leaving other content views in place. 429 * 430 * <p>Note: Requires a window, do not call before {@link #onAttachedToWindow()}</p> 431 * 432 * @param view The desired content to display. 433 * @param params Layout parameters for the view. 434 */ 435 public void addContentView(View view, ViewGroup.LayoutParams params) { 436 getWindow().addContentView(view, params); 437 } 438 439 /** 440 * Finds a view that was identified by the id attribute from the XML that 441 * was processed in {@link #onCreate}. 442 * 443 * <p>Note: Requires a window, do not call before {@link #onAttachedToWindow()}</p> 444 * 445 * @return The view if found or null otherwise. 446 */ 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 an object that may be used to access low-level hardware features that a 662 * dream may use to provide a richer user experience while dozing. 663 * 664 * @return An instance of {@link DozeHardware} or null if this device does not offer 665 * hardware support for dozing. 666 * 667 * @hide For use by system UI components only. 668 */ 669 public DozeHardware getDozeHardware() { 670 if (mCanDoze && mDozeHardware == null && mWindowToken != null) { 671 try { 672 IDozeHardware hardware = mSandman.getDozeHardware(mWindowToken); 673 if (hardware != null) { 674 mDozeHardware = new DozeHardware(hardware); 675 } 676 } catch (RemoteException ex) { 677 // system server died 678 } 679 } 680 return mDozeHardware; 681 } 682 683 /** 684 * Gets the screen state to use while dozing. 685 * 686 * @return The screen state to use while dozing, such as {@link Display#STATE_ON}, 687 * {@link Display#STATE_DOZE}, {@link Display#STATE_DOZE_SUSPEND}, 688 * or {@link Display#STATE_OFF}, or {@link Display#STATE_UNKNOWN} for the default 689 * behavior. 690 * 691 * @see #setDozeScreenState 692 * @hide For use by system UI components only. 693 */ 694 public int getDozeScreenState() { 695 return mDozeScreenState; 696 } 697 698 /** 699 * Sets the screen state to use while dozing. 700 * <p> 701 * The value of this property determines the power state of the primary display 702 * once {@link #startDozing} has been called. The default value is 703 * {@link Display#STATE_UNKNOWN} which lets the system decide. 704 * The dream may set a different state before starting to doze and may 705 * perform transitions between states while dozing to conserve power and 706 * achieve various effects. 707 * </p><p> 708 * It is recommended that the state be set to {@link Display#STATE_DOZE_SUSPEND} 709 * once the dream has completely finished drawing and before it releases its wakelock 710 * to allow the display hardware to be fully suspended. While suspended, the 711 * display will preserve its on-screen contents or hand off control to dedicated 712 * doze hardware if the devices supports it. If the doze suspend state is 713 * used, the dream must make sure to set the mode back 714 * to {@link Display#STATE_DOZE} or {@link Display#STATE_ON} before drawing again 715 * since the display updates may be ignored and not seen by the user otherwise. 716 * </p><p> 717 * The set of available display power states and their behavior while dozing is 718 * hardware dependent and may vary across devices. The dream may therefore 719 * need to be modified or configured to correctly support the hardware. 720 * </p> 721 * 722 * @param state The screen state to use while dozing, such as {@link Display#STATE_ON}, 723 * {@link Display#STATE_DOZE}, {@link Display#STATE_DOZE_SUSPEND}, 724 * or {@link Display#STATE_OFF}, or {@link Display#STATE_UNKNOWN} for the default 725 * behavior. 726 * 727 * @hide For use by system UI components only. 728 */ 729 public void setDozeScreenState(int state) { 730 if (mDozeScreenState != state) { 731 mDozeScreenState = state; 732 updateDoze(); 733 } 734 } 735 736 /** 737 * Gets the screen brightness to use while dozing. 738 * 739 * @return The screen brightness while dozing as a value between 740 * {@link PowerManager#BRIGHTNESS_OFF} (0) and {@link PowerManager#BRIGHTNESS_ON} (255), 741 * or {@link PowerManager#BRIGHTNESS_DEFAULT} (-1) to ask the system to apply 742 * its default policy based on the screen state. 743 * 744 * @see #setDozeScreenBrightness 745 * @hide For use by system UI components only. 746 */ 747 public int getDozeScreenBrightness() { 748 return mDozeScreenBrightness; 749 } 750 751 /** 752 * Sets the screen brightness to use while dozing. 753 * <p> 754 * The value of this property determines the power state of the primary display 755 * once {@link #startDozing} has been called. The default value is 756 * {@link PowerManager#BRIGHTNESS_DEFAULT} which lets the system decide. 757 * The dream may set a different brightness before starting to doze and may adjust 758 * the brightness while dozing to conserve power and achieve various effects. 759 * </p><p> 760 * Note that dream may specify any brightness in the full 0-255 range, including 761 * values that are less than the minimum value for manual screen brightness 762 * adjustments by the user. In particular, the value may be set to 0 which may 763 * turn off the backlight entirely while still leaving the screen on although 764 * this behavior is device dependent and not guaranteed. 765 * </p><p> 766 * The available range of display brightness values and their behavior while dozing is 767 * hardware dependent and may vary across devices. The dream may therefore 768 * need to be modified or configured to correctly support the hardware. 769 * </p> 770 * 771 * @param brightness The screen brightness while dozing as a value between 772 * {@link PowerManager#BRIGHTNESS_OFF} (0) and {@link PowerManager#BRIGHTNESS_ON} (255), 773 * or {@link PowerManager#BRIGHTNESS_DEFAULT} (-1) to ask the system to apply 774 * its default policy based on the screen state. 775 * 776 * @hide For use by system UI components only. 777 */ 778 public void setDozeScreenBrightness(int brightness) { 779 if (brightness != PowerManager.BRIGHTNESS_DEFAULT) { 780 brightness = clampAbsoluteBrightness(brightness); 781 } 782 if (mDozeScreenBrightness != brightness) { 783 mDozeScreenBrightness = brightness; 784 updateDoze(); 785 } 786 } 787 788 /** 789 * Called when this Dream is constructed. 790 */ 791 @Override 792 public void onCreate() { 793 if (mDebug) Slog.v(TAG, "onCreate()"); 794 super.onCreate(); 795 } 796 797 /** 798 * Called when the dream's window has been created and is visible and animation may now begin. 799 */ 800 public void onDreamingStarted() { 801 if (mDebug) Slog.v(TAG, "onDreamingStarted()"); 802 // hook for subclasses 803 } 804 805 /** 806 * Called when this Dream is stopped, either by external request or by calling finish(), 807 * before the window has been removed. 808 */ 809 public void onDreamingStopped() { 810 if (mDebug) Slog.v(TAG, "onDreamingStopped()"); 811 // hook for subclasses 812 } 813 814 /** 815 * Called when the dream is being asked to stop itself and wake. 816 * <p> 817 * The default implementation simply calls {@link #finish} which ends the dream 818 * immediately. Subclasses may override this function to perform a smooth exit 819 * transition then call {@link #finish} afterwards. 820 * </p><p> 821 * Note that the dream will only be given a short period of time (currently about 822 * five seconds) to wake up. If the dream does not finish itself in a timely manner 823 * then the system will forcibly finish it once the time allowance is up. 824 * </p> 825 */ 826 public void onWakeUp() { 827 finish(); 828 } 829 830 /** {@inheritDoc} */ 831 @Override 832 public final IBinder onBind(Intent intent) { 833 if (mDebug) Slog.v(TAG, "onBind() intent = " + intent); 834 return new DreamServiceWrapper(); 835 } 836 837 /** 838 * Stops the dream and detaches from the window. 839 * <p> 840 * When the dream ends, the system will be allowed to go to sleep fully unless there 841 * is a reason for it to be awake such as recent user activity or wake locks being held. 842 * </p> 843 */ 844 public final void finish() { 845 if (mDebug) Slog.v(TAG, "finish(): mFinished=" + mFinished); 846 847 if (!mFinished) { 848 mFinished = true; 849 850 if (mWindowToken == null) { 851 Slog.w(TAG, "Finish was called before the dream was attached."); 852 } else { 853 try { 854 mSandman.finishSelf(mWindowToken, true /*immediate*/); 855 } catch (RemoteException ex) { 856 // system server died 857 } 858 } 859 860 stopSelf(); // if launched via any other means 861 } 862 } 863 864 /** 865 * Wakes the dream up gently. 866 * <p> 867 * Calls {@link #onWakeUp} to give the dream a chance to perform an exit transition. 868 * When the transition is over, the dream should call {@link #finish}. 869 * </p> 870 */ 871 public final void wakeUp() { 872 wakeUp(false); 873 } 874 875 private void wakeUp(boolean fromSystem) { 876 if (mDebug) Slog.v(TAG, "wakeUp(): fromSystem=" + fromSystem 877 + ", mWaking=" + mWaking + ", mFinished=" + mFinished); 878 879 if (!mWaking && !mFinished) { 880 mWaking = true; 881 882 // As a minor optimization, invoke the callback first in case it simply 883 // calls finish() immediately so there wouldn't be much point in telling 884 // the system that we are finishing the dream gently. 885 onWakeUp(); 886 887 // Now tell the system we are waking gently, unless we already told 888 // it we were finishing immediately. 889 if (!fromSystem && !mFinished) { 890 if (mWindowToken == null) { 891 Slog.w(TAG, "WakeUp was called before the dream was attached."); 892 } else { 893 try { 894 mSandman.finishSelf(mWindowToken, false /*immediate*/); 895 } catch (RemoteException ex) { 896 // system server died 897 } 898 } 899 } 900 } 901 } 902 903 /** {@inheritDoc} */ 904 @Override 905 public void onDestroy() { 906 if (mDebug) Slog.v(TAG, "onDestroy()"); 907 // hook for subclasses 908 909 // Just in case destroy came in before detach, let's take care of that now 910 detach(); 911 912 super.onDestroy(); 913 } 914 915 // end public api 916 917 /** 918 * Called by DreamController.stopDream() when the Dream is about to be unbound and destroyed. 919 * 920 * Must run on mHandler. 921 */ 922 private final void detach() { 923 if (mStarted) { 924 if (mDebug) Slog.v(TAG, "detach(): Calling onDreamingStopped()"); 925 mStarted = false; 926 onDreamingStopped(); 927 } 928 929 if (mWindow != null) { 930 // force our window to be removed synchronously 931 if (mDebug) Slog.v(TAG, "detach(): Removing window from window manager"); 932 mWindow.getWindowManager().removeViewImmediate(mWindow.getDecorView()); 933 mWindow = null; 934 } 935 936 if (mWindowToken != null) { 937 // the following will print a log message if it finds any other leaked windows 938 WindowManagerGlobal.getInstance().closeAll(mWindowToken, 939 this.getClass().getName(), "Dream"); 940 mWindowToken = null; 941 mCanDoze = false; 942 } 943 } 944 945 /** 946 * Called when the Dream is ready to be shown. 947 * 948 * Must run on mHandler. 949 * 950 * @param windowToken A window token that will allow a window to be created in the correct layer. 951 */ 952 private final void attach(IBinder windowToken, boolean canDoze) { 953 if (mWindowToken != null) { 954 Slog.e(TAG, "attach() called when already attached with token=" + mWindowToken); 955 return; 956 } 957 if (mFinished || mWaking) { 958 Slog.w(TAG, "attach() called after dream already finished"); 959 try { 960 mSandman.finishSelf(windowToken, true /*immediate*/); 961 } catch (RemoteException ex) { 962 // system server died 963 } 964 return; 965 } 966 967 mWindowToken = windowToken; 968 mCanDoze = canDoze; 969 if (mWindowless && !mCanDoze) { 970 throw new IllegalStateException("Only doze dreams can be windowless"); 971 } 972 if (!mWindowless) { 973 mWindow = PolicyManager.makeNewWindow(this); 974 mWindow.setCallback(this); 975 mWindow.requestFeature(Window.FEATURE_NO_TITLE); 976 mWindow.setBackgroundDrawable(new ColorDrawable(0xFF000000)); 977 mWindow.setFormat(PixelFormat.OPAQUE); 978 979 if (mDebug) Slog.v(TAG, String.format("Attaching window token: %s to window of type %s", 980 windowToken, WindowManager.LayoutParams.TYPE_DREAM)); 981 982 WindowManager.LayoutParams lp = mWindow.getAttributes(); 983 lp.type = WindowManager.LayoutParams.TYPE_DREAM; 984 lp.token = windowToken; 985 lp.windowAnimations = com.android.internal.R.style.Animation_Dream; 986 lp.flags |= ( WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN 987 | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR 988 | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED 989 | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD 990 | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON 991 | (mFullscreen ? WindowManager.LayoutParams.FLAG_FULLSCREEN : 0) 992 | (mScreenBright ? WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON : 0) 993 ); 994 mWindow.setAttributes(lp); 995 mWindow.setWindowManager(null, windowToken, "dream", true); 996 997 applySystemUiVisibilityFlags( 998 (mLowProfile ? View.SYSTEM_UI_FLAG_LOW_PROFILE : 0), 999 View.SYSTEM_UI_FLAG_LOW_PROFILE); 1000 1001 try { 1002 getWindowManager().addView(mWindow.getDecorView(), mWindow.getAttributes()); 1003 } catch (WindowManager.BadTokenException ex) { 1004 // This can happen because the dream manager service will remove the token 1005 // immediately without necessarily waiting for the dream to start. 1006 // We should receive a finish message soon. 1007 Slog.i(TAG, "attach() called after window token already removed, dream will " 1008 + "finish soon"); 1009 mWindow = null; 1010 return; 1011 } 1012 } 1013 // We need to defer calling onDreamingStarted until after onWindowAttached, 1014 // which is posted to the handler by addView, so we post onDreamingStarted 1015 // to the handler also. Need to watch out here in case detach occurs before 1016 // this callback is invoked. 1017 mHandler.post(new Runnable() { 1018 @Override 1019 public void run() { 1020 if (mWindow != null || mWindowless) { 1021 if (mDebug) Slog.v(TAG, "Calling onDreamingStarted()"); 1022 mStarted = true; 1023 onDreamingStarted(); 1024 } 1025 } 1026 }); 1027 } 1028 1029 private boolean getWindowFlagValue(int flag, boolean defaultValue) { 1030 return mWindow == null ? defaultValue : (mWindow.getAttributes().flags & flag) != 0; 1031 } 1032 1033 private void applyWindowFlags(int flags, int mask) { 1034 if (mWindow != null) { 1035 WindowManager.LayoutParams lp = mWindow.getAttributes(); 1036 lp.flags = applyFlags(lp.flags, flags, mask); 1037 mWindow.setAttributes(lp); 1038 mWindow.getWindowManager().updateViewLayout(mWindow.getDecorView(), lp); 1039 } 1040 } 1041 1042 private boolean getSystemUiVisibilityFlagValue(int flag, boolean defaultValue) { 1043 View v = mWindow == null ? null : mWindow.getDecorView(); 1044 return v == null ? defaultValue : (v.getSystemUiVisibility() & flag) != 0; 1045 } 1046 1047 private void applySystemUiVisibilityFlags(int flags, int mask) { 1048 View v = mWindow == null ? null : mWindow.getDecorView(); 1049 if (v != null) { 1050 v.setSystemUiVisibility(applyFlags(v.getSystemUiVisibility(), flags, mask)); 1051 } 1052 } 1053 1054 private int applyFlags(int oldFlags, int flags, int mask) { 1055 return (oldFlags&~mask) | (flags&mask); 1056 } 1057 1058 @Override 1059 protected void dump(final FileDescriptor fd, PrintWriter pw, final String[] args) { 1060 DumpUtils.dumpAsync(mHandler, new Dump() { 1061 @Override 1062 public void dump(PrintWriter pw) { 1063 dumpOnHandler(fd, pw, args); 1064 } 1065 }, pw, 1000); 1066 } 1067 1068 /** @hide */ 1069 protected void dumpOnHandler(FileDescriptor fd, PrintWriter pw, String[] args) { 1070 pw.print(TAG + ": "); 1071 if (mWindowToken == null) { 1072 pw.println("stopped"); 1073 } else { 1074 pw.println("running (token=" + mWindowToken + ")"); 1075 } 1076 pw.println(" window: " + mWindow); 1077 pw.print(" flags:"); 1078 if (isInteractive()) pw.print(" interactive"); 1079 if (isLowProfile()) pw.print(" lowprofile"); 1080 if (isFullscreen()) pw.print(" fullscreen"); 1081 if (isScreenBright()) pw.print(" bright"); 1082 if (isWindowless()) pw.print(" windowless"); 1083 if (isDozing()) pw.print(" dozing"); 1084 else if (canDoze()) pw.print(" candoze"); 1085 pw.println(); 1086 if (canDoze()) { 1087 pw.println(" doze hardware: " + mDozeHardware); 1088 pw.println(" doze screen state: " + Display.stateToString(mDozeScreenState)); 1089 pw.println(" doze screen brightness: " + mDozeScreenBrightness); 1090 } 1091 } 1092 1093 private static int clampAbsoluteBrightness(int value) { 1094 return MathUtils.constrain(value, PowerManager.BRIGHTNESS_OFF, PowerManager.BRIGHTNESS_ON); 1095 } 1096 1097 private final class DreamServiceWrapper extends IDreamService.Stub { 1098 @Override 1099 public void attach(final IBinder windowToken, final boolean canDoze) { 1100 mHandler.post(new Runnable() { 1101 @Override 1102 public void run() { 1103 DreamService.this.attach(windowToken, canDoze); 1104 } 1105 }); 1106 } 1107 1108 @Override 1109 public void detach() { 1110 mHandler.post(new Runnable() { 1111 @Override 1112 public void run() { 1113 DreamService.this.detach(); 1114 } 1115 }); 1116 } 1117 1118 @Override 1119 public void wakeUp() { 1120 mHandler.post(new Runnable() { 1121 @Override 1122 public void run() { 1123 DreamService.this.wakeUp(true /*fromSystem*/); 1124 } 1125 }); 1126 } 1127 } 1128} 1129