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