Debian Codegraph @

core/java/android/service/dreams/DreamService.java

raw symbols SCIP
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 */
16
17 package android.service.dreams;
18
19 import android.annotation.IdRes;
20 import android.annotation.LayoutRes;
21 import android.annotation.NonNull;
22 import android.annotation.Nullable;
23 import android.annotation.SdkConstant;
24 import android.annotation.SdkConstant.SdkConstantType;
25 import android.annotation.TestApi;
26 import android.app.Activity;
27 import android.app.ActivityTaskManager;
28 import android.app.AlarmManager;
29 import android.app.Service;
30 import android.compat.annotation.UnsupportedAppUsage;
31 import android.content.ComponentName;
32 import android.content.Context;
33 import android.content.Intent;
34 import android.content.pm.PackageManager;
35 import android.content.pm.ServiceInfo;
36 import android.content.res.Resources;
37 import android.content.res.TypedArray;
38 import android.content.res.XmlResourceParser;
39 import android.graphics.drawable.Drawable;
40 import android.os.Binder;
41 import android.os.Build;
42 import android.os.Handler;
43 import android.os.IBinder;
44 import android.os.IRemoteCallback;
45 import android.os.Looper;
46 import android.os.PowerManager;
47 import android.os.RemoteException;
48 import android.os.ServiceManager;
49 import android.util.AttributeSet;
50 import android.util.Log;
51 import android.util.MathUtils;
52 import android.util.Slog;
53 import android.util.Xml;
54 import android.view.ActionMode;
55 import android.view.Display;
56 import android.view.KeyEvent;
57 import android.view.Menu;
58 import android.view.MenuItem;
59 import android.view.MotionEvent;
60 import android.view.SearchEvent;
61 import android.view.View;
62 import android.view.ViewGroup;
63 import android.view.Window;
64 import android.view.WindowInsets;
65 import android.view.WindowManager;
66 import android.view.WindowManager.LayoutParams;
67 import android.view.accessibility.AccessibilityEvent;
68
69 import com.android.internal.R;
70 import com.android.internal.util.DumpUtils;
71 import com.android.internal.util.ObservableServiceConnection;
72 import com.android.internal.util.PersistentServiceConnection;
73
74 import org.xmlpull.v1.XmlPullParser;
75 import org.xmlpull.v1.XmlPullParserException;
76
77 import java.io.FileDescriptor;
78 import java.io.IOException;
79 import java.io.PrintWriter;
80 import java.util.ArrayList;
81 import java.util.concurrent.Executor;
82 import java.util.function.Consumer;
83
84 /**
85 * Extend this class to implement a custom dream (available to the user as a "Daydream").
86 *
87 * <p>Dreams are interactive screensavers launched when a charging device is idle, or docked in a
88 * desk dock. Dreams provide another modality for apps to express themselves, tailored for
89 * an exhibition/lean-back experience.</p>
90 *
91 * <p>The {@code DreamService} lifecycle is as follows:</p>
92 * <ol>
93 * <li>{@link #onAttachedToWindow}
94 * <p>Use this for initial setup, such as calling {@link #setContentView setContentView()}.</li>
95 * <li>{@link #onDreamingStarted}
96 * <p>Your dream has started, so you should begin animations or other behaviors here.</li>
97 * <li>{@link #onDreamingStopped}
98 * <p>Use this to stop the things you started in {@link #onDreamingStarted}.</li>
99 * <li>{@link #onDetachedFromWindow}
100 * <p>Use this to dismantle resources (for example, detach from handlers
101 * and listeners).</li>
102 * </ol>
103 *
104 * <p>In addition, onCreate and onDestroy (from the Service interface) will also be called, but
105 * initialization and teardown should be done by overriding the hooks above.</p>
106 *
107 * <p>To be available to the system, your {@code DreamService} should be declared in the
108 * manifest as follows:</p>
109 * <pre>
110 * &lt;service
111 * android:name=".MyDream"
112 * android:exported="true"
113 * android:icon="@drawable/my_icon"
114 * android:label="@string/my_dream_label" >
115 *
116 * &lt;intent-filter>
117 * &lt;action android:name="android.service.dreams.DreamService" />
118 * &lt;category android:name="android.intent.category.DEFAULT" />
119 * &lt;/intent-filter>
120 *
121 * &lt;!-- Point to additional information for this dream (optional) -->
122 * &lt;meta-data
123 * android:name="android.service.dream"
124 * android:resource="@xml/my_dream" />
125 * &lt;/service>
126 * </pre>
127 *
128 * <p>If specified with the {@code <meta-data>} element,
129 * additional information for the dream is defined using the
130 * {@link android.R.styleable#Dream &lt;dream&gt;} element in a separate XML file.
131 * Currently, the only additional
132 * information you can provide is for a settings activity that allows the user to configure
133 * the dream behavior. For example:</p>
134 * <p class="code-caption">res/xml/my_dream.xml</p>
135 * <pre>
136 * &lt;dream xmlns:android="http://schemas.android.com/apk/res/android"
137 * android:settingsActivity="com.example.app/.MyDreamSettingsActivity" />
138 * </pre>
139 * <p>This makes a Settings button available alongside your dream's listing in the
140 * system settings, which when pressed opens the specified activity.</p>
141 *
142 *
143 * <p>To specify your dream layout, call {@link #setContentView}, typically during the
144 * {@link #onAttachedToWindow} callback. For example:</p>
145 * <pre>
146 * public class MyDream extends DreamService {
147 *
148 * &#64;Override
149 * public void onAttachedToWindow() {
150 * super.onAttachedToWindow();
151 *
152 * // Exit dream upon user touch
153 * setInteractive(false);
154 * // Hide system UI
155 * setFullscreen(true);
156 * // Set the dream layout
157 * setContentView(R.layout.dream);
158 * }
159 * }
160 * </pre>
161 *
162 * <p>When targeting api level 21 and above, you must declare the service in your manifest file
163 * with the {@link android.Manifest.permission#BIND_DREAM_SERVICE} permission. For example:</p>
164 * <pre>
165 * &lt;service
166 * android:name=".MyDream"
167 * android:exported="true"
168 * android:icon="@drawable/my_icon"
169 * android:label="@string/my_dream_label"
170 * android:permission="android.permission.BIND_DREAM_SERVICE">
171 * &lt;intent-filter>
172 * &lt;action android:name=”android.service.dreams.DreamService” />
173 * &lt;category android:name=”android.intent.category.DEFAULT” />
174 * &lt;/intent-filter>
175 * &lt;/service>
176 * </pre>
177 */
178 public class DreamService extends Service implements Window.Callback {
179 private static final String TAG = DreamService.class.getSimpleName();
180 private final String mTag = TAG + "[" + getClass().getSimpleName() + "]";
181 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
182
183 /**
184 * The name of the dream manager service.
185 * @hide
186 */
187 public static final String DREAM_SERVICE = "dreams";
188
189 /**
190 * The {@link Intent} that must be declared as handled by the service.
191 */
192 @SdkConstant(SdkConstantType.SERVICE_ACTION)
193 public static final String SERVICE_INTERFACE =
194 "android.service.dreams.DreamService";
195
196 /**
197 * The name of the extra where the dream overlay component is stored.
198 * @hide
199 */
200 public static final String EXTRA_DREAM_OVERLAY_COMPONENT =
201 "android.service.dream.DreamService.dream_overlay_component";
202
203 /**
204 * Name under which a Dream publishes information about itself.
205 * This meta-data must reference an XML resource containing
206 * a <code>&lt;{@link android.R.styleable#Dream dream}&gt;</code>
207 * tag.
208 */
209 public static final String DREAM_META_DATA = "android.service.dream";
210
211 /**
212 * Name of the root tag under which a Dream defines its metadata in an XML file.
213 */
214 private static final String DREAM_META_DATA_ROOT_TAG = "dream";
215
216 /**
217 * The default value for whether to show complications on the overlay.
218 *
219 * @hide
220 */
221 public static final boolean DEFAULT_SHOW_COMPLICATIONS = false;
222
223 private final IDreamManager mDreamManager;
224 private final Handler mHandler = new Handler(Looper.getMainLooper());
225 private IBinder mDreamToken;
226 private Window mWindow;
227 private Activity mActivity;
228 private boolean mInteractive;
229 private boolean mFullscreen;
230 private boolean mScreenBright = true;
231 private boolean mStarted;
232 private boolean mWaking;
233 private boolean mFinished;
234 private boolean mCanDoze;
235 private boolean mDozing;
236 private boolean mWindowless;
237 private int mDozeScreenState = Display.STATE_UNKNOWN;
238 private int mDozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
239
240 private boolean mDebug = false;
241
242 private ComponentName mDreamComponent;
243 private boolean mShouldShowComplications;
244
245 private DreamServiceWrapper mDreamServiceWrapper;
246 private Runnable mDispatchAfterOnAttachedToWindow;
247
248 private OverlayConnection mOverlayConnection;
249
250 private static class OverlayConnection extends PersistentServiceConnection<IDreamOverlay> {
251 // Overlay set during onBind.
252 private IDreamOverlay mOverlay;
253 // A list of pending requests to execute on the overlay.
254 private final ArrayList<Consumer<IDreamOverlay>> mConsumers = new ArrayList<>();
255
256 private final Callback<IDreamOverlay> mCallback = new Callback<IDreamOverlay>() {
257 @Override
258 public void onConnected(ObservableServiceConnection<IDreamOverlay> connection,
259 IDreamOverlay service) {
260 mOverlay = service;
261 for (Consumer<IDreamOverlay> consumer : mConsumers) {
262 consumer.accept(mOverlay);
263 }
264 }
265
266 @Override
267 public void onDisconnected(ObservableServiceConnection<IDreamOverlay> connection,
268 int reason) {
269 mOverlay = null;
270 }
271 };
272
273 OverlayConnection(Context context,
274 Executor executor,
275 Handler handler,
276 ServiceTransformer<IDreamOverlay> transformer,
277 Intent serviceIntent,
278 int flags,
279 int minConnectionDurationMs,
280 int maxReconnectAttempts,
281 int baseReconnectDelayMs) {
282 super(context, executor, handler, transformer, serviceIntent, flags,
283 minConnectionDurationMs,
284 maxReconnectAttempts, baseReconnectDelayMs);
285 }
286
287 @Override
288 public boolean bind() {
289 addCallback(mCallback);
290 return super.bind();
291 }
292
293 @Override
294 public void unbind() {
295 removeCallback(mCallback);
296 super.unbind();
297 }
298
299 public void addConsumer(Consumer<IDreamOverlay> consumer) {
300 mConsumers.add(consumer);
301 if (mOverlay != null) {
302 consumer.accept(mOverlay);
303 }
304 }
305
306 public void removeConsumer(Consumer<IDreamOverlay> consumer) {
307 mConsumers.remove(consumer);
308 }
309 }
310
311 private final IDreamOverlayCallback mOverlayCallback = new IDreamOverlayCallback.Stub() {
312 @Override
313 public void onExitRequested() {
314 // Simply finish dream when exit is requested.
315 mHandler.post(() -> finish());
316 }
317
318 @Override
319 public void onWakeUpComplete() {
320 // Finish the dream once overlay animations are complete. Execute on handler since
321 // this is coming in on the overlay binder.
322 mHandler.post(() -> finish());
323 }
324 };
325
326
327 public DreamService() {
328 mDreamManager = IDreamManager.Stub.asInterface(ServiceManager.getService(DREAM_SERVICE));
329 }
330
331 /**
332 * @hide
333 */
334 public void setDebug(boolean dbg) {
335 mDebug = dbg;
336 }
337
338 // begin Window.Callback methods
339 /** {@inheritDoc} */
340 @Override
341 public boolean dispatchKeyEvent(KeyEvent event) {
342 // TODO: create more flexible version of mInteractive that allows use of KEYCODE_BACK
343 if (!mInteractive) {
344 if (mDebug) Slog.v(mTag, "Waking up on keyEvent");
345 wakeUp();
346 return true;
347 } else if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
348 if (mDebug) Slog.v(mTag, "Waking up on back key");
349 wakeUp();
350 return true;
351 }
352 return mWindow.superDispatchKeyEvent(event);
353 }
354
355 /** {@inheritDoc} */
356 @Override
357 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
358 if (!mInteractive) {
359 if (mDebug) Slog.v(mTag, "Waking up on keyShortcutEvent");
360 wakeUp();
361 return true;
362 }
363 return mWindow.superDispatchKeyShortcutEvent(event);
364 }
365
366 /** {@inheritDoc} */
367 @Override
368 public boolean dispatchTouchEvent(MotionEvent event) {
369 // TODO: create more flexible version of mInteractive that allows clicks
370 // but finish()es on any other kind of activity
371 if (!mInteractive && event.getActionMasked() == MotionEvent.ACTION_UP) {
372 if (mDebug) Slog.v(mTag, "Waking up on touchEvent");
373 wakeUp();
374 return true;
375 }
376 return mWindow.superDispatchTouchEvent(event);
377 }
378
379 /** {@inheritDoc} */
380 @Override
381 public boolean dispatchTrackballEvent(MotionEvent event) {
382 if (!mInteractive) {
383 if (mDebug) Slog.v(mTag, "Waking up on trackballEvent");
384 wakeUp();
385 return true;
386 }
387 return mWindow.superDispatchTrackballEvent(event);
388 }
389
390 /** {@inheritDoc} */
391 @Override
392 public boolean dispatchGenericMotionEvent(MotionEvent event) {
393 if (!mInteractive) {
394 if (mDebug) Slog.v(mTag, "Waking up on genericMotionEvent");
395 wakeUp();
396 return true;
397 }
398 return mWindow.superDispatchGenericMotionEvent(event);
399 }
400
401 /** {@inheritDoc} */
402 @Override
403 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
404 return false;
405 }
406
407 /** {@inheritDoc} */
408 @Override
409 public View onCreatePanelView(int featureId) {
410 return null;
411 }
412
413 /** {@inheritDoc} */
414 @Override
415 public boolean onCreatePanelMenu(int featureId, Menu menu) {
416 return false;
417 }
418
419 /** {@inheritDoc} */
420 @Override
421 public boolean onPreparePanel(int featureId, View view, Menu menu) {
422 return false;
423 }
424
425 /** {@inheritDoc} */
426 @Override
427 public boolean onMenuOpened(int featureId, Menu menu) {
428 return false;
429 }
430
431 /** {@inheritDoc} */
432 @Override
433 public boolean onMenuItemSelected(int featureId, MenuItem item) {
434 return false;
435 }
436
437 /** {@inheritDoc} */
438 @Override
439 public void onWindowAttributesChanged(LayoutParams attrs) {
440 }
441
442 /** {@inheritDoc} */
443 @Override
444 public void onContentChanged() {
445 }
446
447 /** {@inheritDoc} */
448 @Override
449 public void onWindowFocusChanged(boolean hasFocus) {
450 }
451
452 /** {@inheritDoc} */
453 @Override
454 public void onAttachedToWindow() {
455 }
456
457 /** {@inheritDoc} */
458 @Override
459 public void onDetachedFromWindow() {
460 }
461
462 /** {@inheritDoc} */
463 @Override
464 public void onPanelClosed(int featureId, Menu menu) {
465 }
466
467 /** {@inheritDoc} */
468 @Override
469 public boolean onSearchRequested(SearchEvent event) {
470 return onSearchRequested();
471 }
472
473 /** {@inheritDoc} */
474 @Override
475 public boolean onSearchRequested() {
476 return false;
477 }
478
479 /** {@inheritDoc} */
480 @Override
481 public ActionMode onWindowStartingActionMode(android.view.ActionMode.Callback callback) {
482 return null;
483 }
484
485 /** {@inheritDoc} */
486 @Override
487 public ActionMode onWindowStartingActionMode(
488 android.view.ActionMode.Callback callback, int type) {
489 return null;
490 }
491
492 /** {@inheritDoc} */
493 @Override
494 public void onActionModeStarted(ActionMode mode) {
495 }
496
497 /** {@inheritDoc} */
498 @Override
499 public void onActionModeFinished(ActionMode mode) {
500 }
501 // end Window.Callback methods
502
503 // begin public api
504 /**
505 * Retrieves the current {@link android.view.WindowManager} for the dream.
506 * Behaves similarly to {@link android.app.Activity#getWindowManager()}.
507 *
508 * @return The current window manager, or null if the dream is not started.
509 */
510 public WindowManager getWindowManager() {
511 return mWindow != null ? mWindow.getWindowManager() : null;
512 }
513
514 /**
515 * Retrieves the current {@link android.view.Window} for the dream.
516 * Behaves similarly to {@link android.app.Activity#getWindow()}.
517 *
518 * @return The current window, or null if the dream is not started.
519 */
520 public Window getWindow() {
521 return mWindow;
522 }
523
524 /**
525 * Inflates a layout resource and set it to be the content view for this Dream.
526 * Behaves similarly to {@link android.app.Activity#setContentView(int)}.
527 *
528 * <p>Note: Requires a window, do not call before {@link #onAttachedToWindow()}</p>
529 *
530 * @param layoutResID Resource ID to be inflated.
531 *
532 * @see #setContentView(android.view.View)
533 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
534 */
535 public void setContentView(@LayoutRes int layoutResID) {
536 getWindow().setContentView(layoutResID);
537 }
538
539 /**
540 * Sets a view to be the content view for this Dream.
541 * Behaves similarly to {@link android.app.Activity#setContentView(android.view.View)} in an activity,
542 * including using {@link ViewGroup.LayoutParams#MATCH_PARENT} as the layout height and width of the view.
543 *
544 * <p>Note: This requires a window, so you should usually call it during
545 * {@link #onAttachedToWindow()} and never earlier (you <strong>cannot</strong> call it
546 * during {@link #onCreate}).</p>
547 *
548 * @see #setContentView(int)
549 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
550 */
551 public void setContentView(View view) {
552 getWindow().setContentView(view);
553 }
554
555 /**
556 * Sets a view to be the content view for this Dream.
557 * Behaves similarly to
558 * {@link android.app.Activity#setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
559 * in an activity.
560 *
561 * <p>Note: This requires a window, so you should usually call it during
562 * {@link #onAttachedToWindow()} and never earlier (you <strong>cannot</strong> call it
563 * during {@link #onCreate}).</p>
564 *
565 * @param view The desired content to display.
566 * @param params Layout parameters for the view.
567 *
568 * @see #setContentView(android.view.View)
569 * @see #setContentView(int)
570 */
571 public void setContentView(View view, ViewGroup.LayoutParams params) {
572 getWindow().setContentView(view, params);
573 }
574
575 /**
576 * Adds a view to the Dream's window, leaving other content views in place.
577 *
578 * <p>Note: Requires a window, do not call before {@link #onAttachedToWindow()}</p>
579 *
580 * @param view The desired content to display.
581 * @param params Layout parameters for the view.
582 */
583 public void addContentView(View view, ViewGroup.LayoutParams params) {
584 getWindow().addContentView(view, params);
585 }
586
587 /**
588 * Finds a view that was identified by the id attribute from the XML that
589 * was processed in {@link #onCreate}.
590 *
591 * <p>Note: Requires a window, do not call before {@link #onAttachedToWindow()}</p>
592 * <p>
593 * <strong>Note:</strong> In most cases -- depending on compiler support --
594 * the resulting view is automatically cast to the target class type. If
595 * the target class type is unconstrained, an explicit cast may be
596 * necessary.
597 *
598 * @param id the ID to search for
599 * @return The view if found or null otherwise.
600 * @see View#findViewById(int)
601 * @see DreamService#requireViewById(int)
602 */
603 @Nullable
604 public <T extends View> T findViewById(@IdRes int id) {
605 return getWindow().findViewById(id);
606 }
607
608 /**
609 * Finds a view that was identified by the id attribute from the XML that was processed in
610 * {@link #onCreate}, or throws an IllegalArgumentException if the ID is invalid or there is no
611 * matching view in the hierarchy.
612 *
613 * <p>Note: Requires a window, do not call before {@link #onAttachedToWindow()}</p>
614 * <p>
615 * <strong>Note:</strong> In most cases -- depending on compiler support --
616 * the resulting view is automatically cast to the target class type. If
617 * the target class type is unconstrained, an explicit cast may be
618 * necessary.
619 *
620 * @param id the ID to search for
621 * @return a view with given ID
622 * @see View#requireViewById(int)
623 * @see DreamService#findViewById(int)
624 */
625 @NonNull
626 public final <T extends View> T requireViewById(@IdRes int id) {
627 T view = findViewById(id);
628 if (view == null) {
629 throw new IllegalArgumentException(
630 "ID does not reference a View inside this DreamService");
631 }
632 return view;
633 }
634
635 /**
636 * Marks this dream as interactive to receive input events.
637 *
638 * <p>Non-interactive dreams (default) will dismiss on the first input event.</p>
639 *
640 * <p>Interactive dreams should call {@link #finish()} to dismiss themselves.</p>
641 *
642 * @param interactive True if this dream will handle input events.
643 */
644 public void setInteractive(boolean interactive) {
645 mInteractive = interactive;
646 }
647
648 /**
649 * Returns whether this dream is interactive. Defaults to false.
650 *
651 * @see #setInteractive(boolean)
652 */
653 public boolean isInteractive() {
654 return mInteractive;
655 }
656
657 /**
658 * Controls {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN}
659 * on the dream's window.
660 *
661 * @param fullscreen If true, the fullscreen flag will be set; else it
662 * will be cleared.
663 */
664 public void setFullscreen(boolean fullscreen) {
665 if (mFullscreen != fullscreen) {
666 mFullscreen = fullscreen;
667 int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
668 applyWindowFlags(mFullscreen ? flag : 0, flag);
669 }
670 }
671
672 /**
673 * Returns whether this dream is in fullscreen mode. Defaults to false.
674 *
675 * @see #setFullscreen(boolean)
676 */
677 public boolean isFullscreen() {
678 return mFullscreen;
679 }
680
681 /**
682 * Marks this dream as keeping the screen bright while dreaming.
683 *
684 * @param screenBright True to keep the screen bright while dreaming.
685 */
686 public void setScreenBright(boolean screenBright) {
687 if (mScreenBright != screenBright) {
688 mScreenBright = screenBright;
689 int flag = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
690 applyWindowFlags(mScreenBright ? flag : 0, flag);
691 }
692 }
693
694 /**
695 * Returns whether this dream keeps the screen bright while dreaming.
696 * Defaults to false, allowing the screen to dim if necessary.
697 *
698 * @see #setScreenBright(boolean)
699 */
700 public boolean isScreenBright() {
701 return getWindowFlagValue(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, mScreenBright);
702 }
703
704 /**
705 * Marks this dream as windowless. Only available to doze dreams.
706 *
707 * @hide
708 *
709 */
710 public void setWindowless(boolean windowless) {
711 mWindowless = windowless;
712 }
713
714 /**
715 * Returns whether this dream is windowless. Only available to doze dreams.
716 *
717 * @hide
718 */
719 public boolean isWindowless() {
720 return mWindowless;
721 }
722
723 /**
724 * Returns true if this dream is allowed to doze.
725 * <p>
726 * The value returned by this method is only meaningful when the dream has started.
727 * </p>
728 *
729 * @return True if this dream can doze.
730 * @see #startDozing
731 * @hide For use by system UI components only.
732 */
733 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
734 public boolean canDoze() {
735 return mCanDoze;
736 }
737
738 /**
739 * Starts dozing, entering a deep dreamy sleep.
740 * <p>
741 * Dozing enables the system to conserve power while the user is not actively interacting
742 * with the device. While dozing, the display will remain on in a low-power state
743 * and will continue to show its previous contents but the application processor and
744 * other system components will be allowed to suspend when possible.
745 * </p><p>
746 * While the application processor is suspended, the dream may stop executing code
747 * for long periods of time. Prior to being suspended, the dream may schedule periodic
748 * wake-ups to render new content by scheduling an alarm with the {@link AlarmManager}.
749 * The dream may also keep the CPU awake by acquiring a
750 * {@link android.os.PowerManager#PARTIAL_WAKE_LOCK partial wake lock} when necessary.
751 * Note that since the purpose of doze mode is to conserve power (especially when
752 * running on battery), the dream should not wake the CPU very often or keep it
753 * awake for very long.
754 * </p><p>
755 * It is a good idea to call this method some time after the dream's entry animation
756 * has completed and the dream is ready to doze. It is important to completely
757 * finish all of the work needed before dozing since the application processor may
758 * be suspended at any moment once this method is called unless other wake locks
759 * are being held.
760 * </p><p>
761 * Call {@link #stopDozing} or {@link #finish} to stop dozing.
762 * </p>
763 *
764 * @see #stopDozing
765 * @hide For use by system UI components only.
766 */
767 @UnsupportedAppUsage
768 public void startDozing() {
769 if (mCanDoze && !mDozing) {
770 mDozing = true;
771 updateDoze();
772 }
773 }
774
775 private void updateDoze() {
776 if (mDreamToken == null) {
777 Slog.w(mTag, "Updating doze without a dream token.");
778 return;
779 }
780
781 if (mDozing) {
782 try {
783 mDreamManager.startDozing(mDreamToken, mDozeScreenState, mDozeScreenBrightness);
784 } catch (RemoteException ex) {
785 // system server died
786 }
787 }
788 }
789
790 /**
791 * Stops dozing, returns to active dreaming.
792 * <p>
793 * This method reverses the effect of {@link #startDozing}. From this moment onward,
794 * the application processor will be kept awake as long as the dream is running
795 * or until the dream starts dozing again.
796 * </p>
797 *
798 * @see #startDozing
799 * @hide For use by system UI components only.
800 */
801 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
802 public void stopDozing() {
803 if (mDozing) {
804 mDozing = false;
805 try {
806 mDreamManager.stopDozing(mDreamToken);
807 } catch (RemoteException ex) {
808 // system server died
809 }
810 }
811 }
812
813 /**
814 * Returns true if the dream will allow the system to enter a low-power state while
815 * it is running without actually turning off the screen. Defaults to false,
816 * keeping the application processor awake while the dream is running.
817 *
818 * @return True if the dream is dozing.
819 *
820 * @hide For use by system UI components only.
821 */
822 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
823 public boolean isDozing() {
824 return mDozing;
825 }
826
827 /**
828 * Gets the screen state to use while dozing.
829 *
830 * @return The screen state to use while dozing, such as {@link Display#STATE_ON},
831 * {@link Display#STATE_DOZE}, {@link Display#STATE_DOZE_SUSPEND},
832 * {@link Display#STATE_ON_SUSPEND}, {@link Display#STATE_OFF}, or {@link Display#STATE_UNKNOWN}
833 * for the default behavior.
834 *
835 * @see #setDozeScreenState
836 * @hide For use by system UI components only.
837 */
838 public int getDozeScreenState() {
839 return mDozeScreenState;
840 }
841
842 /**
843 * Sets the screen state to use while dozing.
844 * <p>
845 * The value of this property determines the power state of the primary display
846 * once {@link #startDozing} has been called. The default value is
847 * {@link Display#STATE_UNKNOWN} which lets the system decide.
848 * The dream may set a different state before starting to doze and may
849 * perform transitions between states while dozing to conserve power and
850 * achieve various effects.
851 * </p><p>
852 * Some devices will have dedicated hardware ("Sidekick") to animate
853 * the display content while the CPU sleeps. If the dream and the hardware support
854 * this, {@link Display#STATE_ON_SUSPEND} or {@link Display#STATE_DOZE_SUSPEND}
855 * will switch control to the Sidekick.
856 * </p><p>
857 * If not using Sidekick, it is recommended that the state be set to
858 * {@link Display#STATE_DOZE_SUSPEND} once the dream has completely
859 * finished drawing and before it releases its wakelock
860 * to allow the display hardware to be fully suspended. While suspended,
861 * the display will preserve its on-screen contents.
862 * </p><p>
863 * If the doze suspend state is used, the dream must make sure to set the mode back
864 * to {@link Display#STATE_DOZE} or {@link Display#STATE_ON} before drawing again
865 * since the display updates may be ignored and not seen by the user otherwise.
866 * </p><p>
867 * The set of available display power states and their behavior while dozing is
868 * hardware dependent and may vary across devices. The dream may therefore
869 * need to be modified or configured to correctly support the hardware.
870 * </p>
871 *
872 * @param state The screen state to use while dozing, such as {@link Display#STATE_ON},
873 * {@link Display#STATE_DOZE}, {@link Display#STATE_DOZE_SUSPEND},
874 * {@link Display#STATE_ON_SUSPEND}, {@link Display#STATE_OFF}, or {@link Display#STATE_UNKNOWN}
875 * for the default behavior.
876 *
877 * @hide For use by system UI components only.
878 */
879 @UnsupportedAppUsage
880 public void setDozeScreenState(int state) {
881 if (mDozeScreenState != state) {
882 mDozeScreenState = state;
883 updateDoze();
884 }
885 }
886
887 /**
888 * Gets the screen brightness to use while dozing.
889 *
890 * @return The screen brightness while dozing as a value between
891 * {@link PowerManager#BRIGHTNESS_OFF} (0) and {@link PowerManager#BRIGHTNESS_ON} (255),
892 * or {@link PowerManager#BRIGHTNESS_DEFAULT} (-1) to ask the system to apply
893 * its default policy based on the screen state.
894 *
895 * @see #setDozeScreenBrightness
896 * @hide For use by system UI components only.
897 */
898 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
899 public int getDozeScreenBrightness() {
900 return mDozeScreenBrightness;
901 }
902
903 /**
904 * Sets the screen brightness to use while dozing.
905 * <p>
906 * The value of this property determines the power state of the primary display
907 * once {@link #startDozing} has been called. The default value is
908 * {@link PowerManager#BRIGHTNESS_DEFAULT} which lets the system decide.
909 * The dream may set a different brightness before starting to doze and may adjust
910 * the brightness while dozing to conserve power and achieve various effects.
911 * </p><p>
912 * Note that dream may specify any brightness in the full 0-255 range, including
913 * values that are less than the minimum value for manual screen brightness
914 * adjustments by the user. In particular, the value may be set to 0 which may
915 * turn off the backlight entirely while still leaving the screen on although
916 * this behavior is device dependent and not guaranteed.
917 * </p><p>
918 * The available range of display brightness values and their behavior while dozing is
919 * hardware dependent and may vary across devices. The dream may therefore
920 * need to be modified or configured to correctly support the hardware.
921 * </p>
922 *
923 * @param brightness The screen brightness while dozing as a value between
924 * {@link PowerManager#BRIGHTNESS_OFF} (0) and {@link PowerManager#BRIGHTNESS_ON} (255),
925 * or {@link PowerManager#BRIGHTNESS_DEFAULT} (-1) to ask the system to apply
926 * its default policy based on the screen state.
927 *
928 * @hide For use by system UI components only.
929 */
930 @UnsupportedAppUsage
931 public void setDozeScreenBrightness(int brightness) {
932 if (brightness != PowerManager.BRIGHTNESS_DEFAULT) {
933 brightness = clampAbsoluteBrightness(brightness);
934 }
935 if (mDozeScreenBrightness != brightness) {
936 mDozeScreenBrightness = brightness;
937 updateDoze();
938 }
939 }
940
941 /**
942 * Called when this Dream is constructed.
943 */
944 @Override
945 public void onCreate() {
946 if (mDebug) Slog.v(mTag, "onCreate()");
947
948 mDreamComponent = new ComponentName(this, getClass());
949 mShouldShowComplications = fetchShouldShowComplications(this /*context*/,
950 fetchServiceInfo(this /*context*/, mDreamComponent));
951
952 super.onCreate();
953 }
954
955 /**
956 * Called when the dream's window has been created and is visible and animation may now begin.
957 */
958 public void onDreamingStarted() {
959 if (mDebug) Slog.v(mTag, "onDreamingStarted()");
960 // hook for subclasses
961 }
962
963 /**
964 * Called when this Dream is stopped, either by external request or by calling finish(),
965 * before the window has been removed.
966 */
967 public void onDreamingStopped() {
968 if (mDebug) Slog.v(mTag, "onDreamingStopped()");
969 // hook for subclasses
970 }
971
972 /**
973 * Called when the dream is being asked to stop itself and wake.
974 * <p>
975 * The default implementation simply calls {@link #finish} which ends the dream
976 * immediately. Subclasses may override this function to perform a smooth exit
977 * transition then call {@link #finish} afterwards.
978 * </p><p>
979 * Note that the dream will only be given a short period of time (currently about
980 * five seconds) to wake up. If the dream does not finish itself in a timely manner
981 * then the system will forcibly finish it once the time allowance is up.
982 * </p>
983 */
984 public void onWakeUp() {
985 if (mOverlayConnection != null) {
986 mOverlayConnection.addConsumer(overlay -> {
987 try {
988 overlay.wakeUp();
989 } catch (RemoteException e) {
990 Slog.e(TAG, "Error waking the overlay service", e);
991 finish();
992 }
993 });
994 } else {
995 finish();
996 }
997 }
998
999 /** {@inheritDoc} */
1000 @Override
1001 public final IBinder onBind(Intent intent) {
1002 if (mDebug) Slog.v(mTag, "onBind() intent = " + intent);
1003 mDreamServiceWrapper = new DreamServiceWrapper();
1004 final ComponentName overlayComponent = intent.getParcelableExtra(
1005 EXTRA_DREAM_OVERLAY_COMPONENT, ComponentName.class);
1006
1007 // Connect to the overlay service if present.
1008 if (!mWindowless && overlayComponent != null) {
1009 final Resources resources = getResources();
1010 final Intent overlayIntent = new Intent().setComponent(overlayComponent);
1011
1012 mOverlayConnection = new OverlayConnection(
1013 /* context= */ this,
1014 getMainExecutor(),
1015 mHandler,
1016 IDreamOverlay.Stub::asInterface,
1017 overlayIntent,
1018 /* flags= */ Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
1019 resources.getInteger(R.integer.config_minDreamOverlayDurationMs),
1020 resources.getInteger(R.integer.config_dreamOverlayMaxReconnectAttempts),
1021 resources.getInteger(R.integer.config_dreamOverlayReconnectTimeoutMs));
1022
1023 mOverlayConnection.bind();
1024 }
1025
1026 return mDreamServiceWrapper;
1027 }
1028
1029 @Override
1030 public boolean onUnbind(Intent intent) {
1031 // We must unbind from any overlay connection if we are unbound before finishing.
1032 if (mOverlayConnection != null) {
1033 mOverlayConnection.unbind();
1034 }
1035
1036 return super.onUnbind(intent);
1037 }
1038
1039 /**
1040 * Stops the dream and detaches from the window.
1041 * <p>
1042 * When the dream ends, the system will be allowed to go to sleep fully unless there
1043 * is a reason for it to be awake such as recent user activity or wake locks being held.
1044 * </p>
1045 */
1046 public final void finish() {
1047 if (mDebug) Slog.v(mTag, "finish(): mFinished=" + mFinished);
1048
1049 Activity activity = mActivity;
1050 if (activity != null) {
1051 if (!activity.isFinishing()) {
1052 // In case the activity is not finished yet, do it now.
1053 activity.finishAndRemoveTask();
1054 }
1055 return;
1056 }
1057
1058 if (mFinished) {
1059 return;
1060 }
1061 mFinished = true;
1062
1063 if (mOverlayConnection != null) {
1064 mOverlayConnection.unbind();
1065 }
1066
1067 if (mDreamToken == null) {
1068 if (mDebug) Slog.v(mTag, "finish() called when not attached.");
1069 stopSelf();
1070 return;
1071 }
1072
1073 try {
1074 // finishSelf will unbind the dream controller from the dream service. This will
1075 // trigger DreamService.this.onDestroy and DreamService.this will die.
1076 mDreamManager.finishSelf(mDreamToken, true /*immediate*/);
1077 } catch (RemoteException ex) {
1078 // system server died
1079 }
1080 }
1081
1082 /**
1083 * Wakes the dream up gently.
1084 * <p>
1085 * Calls {@link #onWakeUp} to give the dream a chance to perform an exit transition.
1086 * When the transition is over, the dream should call {@link #finish}.
1087 * </p>
1088 */
1089 public final void wakeUp() {
1090 wakeUp(false);
1091 }
1092
1093 private void wakeUp(boolean fromSystem) {
1094 if (mDebug) {
1095 Slog.v(mTag, "wakeUp(): fromSystem=" + fromSystem + ", mWaking=" + mWaking
1096 + ", mFinished=" + mFinished);
1097 }
1098
1099 if (!mWaking && !mFinished) {
1100 mWaking = true;
1101
1102 if (mActivity != null) {
1103 // During wake up the activity should be translucent to allow the application
1104 // underneath to start drawing. Normally, the WM animation system takes care of
1105 // this, but here we give the dream application some time to perform a custom exit
1106 // animation. If it uses a view animation, the WM doesn't know about it and can't
1107 // make the activity translucent in the normal way. Therefore, here we ensure that
1108 // the activity is translucent during wake up regardless of what animation is used
1109 // in onWakeUp().
1110 mActivity.convertToTranslucent(null, null);
1111 }
1112
1113 // As a minor optimization, invoke the callback first in case it simply
1114 // calls finish() immediately so there wouldn't be much point in telling
1115 // the system that we are finishing the dream gently.
1116 onWakeUp();
1117
1118 // Now tell the system we are waking gently, unless we already told
1119 // it we were finishing immediately.
1120 if (!fromSystem && !mFinished) {
1121 if (mActivity == null) {
1122 Slog.w(mTag, "WakeUp was called before the dream was attached.");
1123 } else {
1124 try {
1125 mDreamManager.finishSelf(mDreamToken, false /*immediate*/);
1126 } catch (RemoteException ex) {
1127 // system server died
1128 }
1129 }
1130 }
1131 }
1132 }
1133
1134 /** {@inheritDoc} */
1135 @Override
1136 public void onDestroy() {
1137 if (mDebug) Slog.v(mTag, "onDestroy()");
1138 // hook for subclasses
1139
1140 // Just in case destroy came in before detach, let's take care of that now
1141 detach();
1142
1143 super.onDestroy();
1144 }
1145
1146 // end public api
1147
1148 /**
1149 * Parses and returns metadata of the dream service indicated by the service info. Returns null
1150 * if metadata cannot be found.
1151 *
1152 * Note that {@link ServiceInfo} must be fetched with {@link PackageManager#GET_META_DATA} flag.
1153 *
1154 * @hide
1155 */
1156 @Nullable
1157 @TestApi
1158 public static DreamMetadata getDreamMetadata(@NonNull Context context,
1159 @Nullable ServiceInfo serviceInfo) {
1160 if (serviceInfo == null) return null;
1161
1162 final PackageManager pm = context.getPackageManager();
1163
1164 try (TypedArray rawMetadata = readMetadata(pm, serviceInfo)) {
1165 if (rawMetadata == null) return null;
1166 return new DreamMetadata(
1167 convertToComponentName(rawMetadata.getString(
1168 com.android.internal.R.styleable.Dream_settingsActivity), serviceInfo),
1169 rawMetadata.getDrawable(
1170 com.android.internal.R.styleable.Dream_previewImage),
1171 rawMetadata.getBoolean(R.styleable.Dream_showClockAndComplications,
1172 DEFAULT_SHOW_COMPLICATIONS));
1173 }
1174 }
1175
1176 /**
1177 * Returns the raw XML metadata fetched from the {@link ServiceInfo}.
1178 *
1179 * Returns <code>null</code> if the {@link ServiceInfo} doesn't contain valid dream metadata.
1180 */
1181 @Nullable
1182 private static TypedArray readMetadata(PackageManager pm, ServiceInfo serviceInfo) {
1183 if (serviceInfo == null || serviceInfo.metaData == null) {
1184 return null;
1185 }
1186
1187 try (XmlResourceParser parser =
1188 serviceInfo.loadXmlMetaData(pm, DreamService.DREAM_META_DATA)) {
1189 if (parser == null) {
1190 if (DEBUG) Log.w(TAG, "No " + DreamService.DREAM_META_DATA + " metadata");
1191 return null;
1192 }
1193
1194 final AttributeSet attrs = Xml.asAttributeSet(parser);
1195 while (true) {
1196 final int type = parser.next();
1197 if (type == XmlPullParser.END_DOCUMENT || type == XmlPullParser.START_TAG) {
1198 break;
1199 }
1200 }
1201
1202 if (!parser.getName().equals(DREAM_META_DATA_ROOT_TAG)) {
1203 if (DEBUG) {
1204 Log.w(TAG, "Metadata does not start with " + DREAM_META_DATA_ROOT_TAG + " tag");
1205 }
1206 return null;
1207 }
1208
1209 return pm.getResourcesForApplication(serviceInfo.applicationInfo).obtainAttributes(
1210 attrs, com.android.internal.R.styleable.Dream);
1211 } catch (PackageManager.NameNotFoundException | IOException | XmlPullParserException e) {
1212 if (DEBUG) Log.e(TAG, "Error parsing: " + serviceInfo.packageName, e);
1213 return null;
1214 }
1215 }
1216
1217 @Nullable
1218 private static ComponentName convertToComponentName(@Nullable String flattenedString,
1219 ServiceInfo serviceInfo) {
1220 if (flattenedString == null) {
1221 return null;
1222 }
1223
1224 if (!flattenedString.contains("/")) {
1225 return new ComponentName(serviceInfo.packageName, flattenedString);
1226 }
1227
1228 // Ensure that the component is from the same package as the dream service. If not,
1229 // treat the component as invalid and return null instead.
1230 final ComponentName cn = ComponentName.unflattenFromString(flattenedString);
1231 if (cn == null) return null;
1232 if (!cn.getPackageName().equals(serviceInfo.packageName)) {
1233 Log.w(TAG,
1234 "Inconsistent package name in component: " + cn.getPackageName()
1235 + ", should be: " + serviceInfo.packageName);
1236 return null;
1237 }
1238 return cn;
1239 }
1240
1241 /**
1242 * Called by DreamController.stopDream() when the Dream is about to be unbound and destroyed.
1243 *
1244 * Must run on mHandler.
1245 */
1246 private void detach() {
1247 if (mStarted) {
1248 if (mDebug) Slog.v(mTag, "detach(): Calling onDreamingStopped()");
1249 mStarted = false;
1250 onDreamingStopped();
1251 }
1252
1253 if (mActivity != null && !mActivity.isFinishing()) {
1254 mActivity.finishAndRemoveTask();
1255 } else {
1256 finish();
1257 }
1258
1259 mDreamToken = null;
1260 mCanDoze = false;
1261 }
1262
1263 /**
1264 * Called when the Dream is ready to be shown.
1265 *
1266 * Must run on mHandler.
1267 *
1268 * @param dreamToken Token for this dream service.
1269 * @param started A callback that will be invoked once onDreamingStarted has completed.
1270 */
1271 private void attach(IBinder dreamToken, boolean canDoze, IRemoteCallback started) {
1272 if (mDreamToken != null) {
1273 Slog.e(mTag, "attach() called when dream with token=" + mDreamToken
1274 + " already attached");
1275 return;
1276 }
1277 if (mFinished || mWaking) {
1278 Slog.w(mTag, "attach() called after dream already finished");
1279 try {
1280 mDreamManager.finishSelf(dreamToken, true /*immediate*/);
1281 } catch (RemoteException ex) {
1282 // system server died
1283 }
1284 return;
1285 }
1286
1287 mDreamToken = dreamToken;
1288 mCanDoze = canDoze;
1289 if (mWindowless && !mCanDoze) {
1290 throw new IllegalStateException("Only doze dreams can be windowless");
1291 }
1292
1293 mDispatchAfterOnAttachedToWindow = () -> {
1294 if (mWindow != null || mWindowless) {
1295 mStarted = true;
1296 try {
1297 onDreamingStarted();
1298 } finally {
1299 try {
1300 started.sendResult(null);
1301 } catch (RemoteException e) {
1302 throw e.rethrowFromSystemServer();
1303 }
1304 }
1305 }
1306 };
1307
1308 // We need to defer calling onDreamingStarted until after the activity is created.
1309 // If the dream is windowless, we can call it immediately. Otherwise, we wait
1310 // for the DreamActivity to report onActivityCreated via
1311 // DreamServiceWrapper.onActivityCreated.
1312 if (!mWindowless) {
1313 Intent i = new Intent(this, DreamActivity.class);
1314 i.setPackage(getApplicationContext().getPackageName());
1315 i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
1316 i.putExtra(DreamActivity.EXTRA_CALLBACK, new DreamActivityCallbacks(mDreamToken));
1317 final ServiceInfo serviceInfo = fetchServiceInfo(this,
1318 new ComponentName(this, getClass()));
1319 i.putExtra(DreamActivity.EXTRA_DREAM_TITLE, fetchDreamLabel(this, serviceInfo));
1320
1321 try {
1322 if (!ActivityTaskManager.getService().startDreamActivity(i)) {
1323 detach();
1324 }
1325 } catch (RemoteException e) {
1326 Log.w(mTag, "Could not connect to activity task manager to start dream activity");
1327 e.rethrowFromSystemServer();
1328 }
1329 } else {
1330 mDispatchAfterOnAttachedToWindow.run();
1331 }
1332 }
1333
1334 private void onWindowCreated(Window w) {
1335 mWindow = w;
1336 mWindow.setCallback(this);
1337 mWindow.requestFeature(Window.FEATURE_NO_TITLE);
1338
1339 WindowManager.LayoutParams lp = mWindow.getAttributes();
1340 lp.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
1341 | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
1342 | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
1343 | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
1344 | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
1345 | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED
1346 | (mFullscreen ? WindowManager.LayoutParams.FLAG_FULLSCREEN : 0)
1347 | (mScreenBright ? WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON : 0)
1348 );
1349 lp.layoutInDisplayCutoutMode =
1350 WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
1351 mWindow.setAttributes(lp);
1352 // Workaround: Currently low-profile and in-window system bar backgrounds don't go
1353 // along well. Dreams usually don't need such bars anyways, so disable them by default.
1354 mWindow.clearFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
1355
1356 // Hide all insets when the dream is showing
1357 mWindow.getDecorView().getWindowInsetsController().hide(WindowInsets.Type.systemBars());
1358 mWindow.setDecorFitsSystemWindows(false);
1359
1360 mWindow.getDecorView().addOnAttachStateChangeListener(
1361 new View.OnAttachStateChangeListener() {
1362 private Consumer<IDreamOverlay> mDreamStartOverlayConsumer;
1363
1364 @Override
1365 public void onViewAttachedToWindow(View v) {
1366 mDispatchAfterOnAttachedToWindow.run();
1367
1368 if (mOverlayConnection != null) {
1369 // Request the DreamOverlay be told to dream with dream's window
1370 // parameters once the window has been attached.
1371 mDreamStartOverlayConsumer = overlay -> {
1372 try {
1373 overlay.startDream(mWindow.getAttributes(), mOverlayCallback,
1374 mDreamComponent.flattenToString(),
1375 mShouldShowComplications);
1376 } catch (RemoteException e) {
1377 Log.e(mTag, "could not send window attributes:" + e);
1378 }
1379 };
1380 mOverlayConnection.addConsumer(mDreamStartOverlayConsumer);
1381 }
1382 }
1383
1384 @Override
1385 public void onViewDetachedFromWindow(View v) {
1386 if (mActivity == null || !mActivity.isChangingConfigurations()) {
1387 // Only stop the dream if the view is not detached by relaunching
1388 // activity for configuration changes. It is important to also clear
1389 // the window reference in order to fully release the DreamActivity.
1390 mWindow = null;
1391 mActivity = null;
1392 finish();
1393 }
1394 if (mOverlayConnection != null && mDreamStartOverlayConsumer != null) {
1395 mOverlayConnection.removeConsumer(mDreamStartOverlayConsumer);
1396 }
1397 }
1398 });
1399 }
1400
1401 private boolean getWindowFlagValue(int flag, boolean defaultValue) {
1402 return mWindow == null ? defaultValue : (mWindow.getAttributes().flags & flag) != 0;
1403 }
1404
1405 private void applyWindowFlags(int flags, int mask) {
1406 if (mWindow != null) {
1407 WindowManager.LayoutParams lp = mWindow.getAttributes();
1408 lp.flags = applyFlags(lp.flags, flags, mask);
1409 mWindow.setAttributes(lp);
1410 mWindow.getWindowManager().updateViewLayout(mWindow.getDecorView(), lp);
1411 }
1412 }
1413
1414 private int applyFlags(int oldFlags, int flags, int mask) {
1415 return (oldFlags&~mask) | (flags&mask);
1416 }
1417
1418 /**
1419 * Fetches metadata of the dream indicated by the {@link ComponentName}, and returns whether
1420 * the dream should show complications on the overlay. If not defined, returns
1421 * {@link DreamService#DEFAULT_SHOW_COMPLICATIONS}.
1422 */
1423 private static boolean fetchShouldShowComplications(Context context,
1424 @Nullable ServiceInfo serviceInfo) {
1425 final DreamMetadata metadata = getDreamMetadata(context, serviceInfo);
1426 if (metadata != null) {
1427 return metadata.showComplications;
1428 }
1429 return DEFAULT_SHOW_COMPLICATIONS;
1430 }
1431
1432 @Nullable
1433 private static CharSequence fetchDreamLabel(Context context,
1434 @Nullable ServiceInfo serviceInfo) {
1435 if (serviceInfo == null) return null;
1436 final PackageManager pm = context.getPackageManager();
1437 return serviceInfo.loadLabel(pm);
1438 }
1439
1440 @Nullable
1441 private static ServiceInfo fetchServiceInfo(Context context, ComponentName componentName) {
1442 final PackageManager pm = context.getPackageManager();
1443
1444 try {
1445 return pm.getServiceInfo(componentName,
1446 PackageManager.ComponentInfoFlags.of(PackageManager.GET_META_DATA));
1447 } catch (PackageManager.NameNotFoundException e) {
1448 if (DEBUG) Log.w(TAG, "cannot find component " + componentName.flattenToShortString());
1449 }
1450 return null;
1451 }
1452
1453 @Override
1454 protected void dump(final FileDescriptor fd, PrintWriter pw, final String[] args) {
1455 DumpUtils.dumpAsync(mHandler, (pw1, prefix) -> dumpOnHandler(fd, pw1, args), pw, "", 1000);
1456 }
1457
1458 /** @hide */
1459 protected void dumpOnHandler(FileDescriptor fd, PrintWriter pw, String[] args) {
1460 pw.print(mTag + ": ");
1461 if (mFinished) {
1462 pw.println("stopped");
1463 } else {
1464 pw.println("running (dreamToken=" + mDreamToken + ")");
1465 }
1466 pw.println(" window: " + mWindow);
1467 pw.print(" flags:");
1468 if (isInteractive()) pw.print(" interactive");
1469 if (isFullscreen()) pw.print(" fullscreen");
1470 if (isScreenBright()) pw.print(" bright");
1471 if (isWindowless()) pw.print(" windowless");
1472 if (isDozing()) pw.print(" dozing");
1473 else if (canDoze()) pw.print(" candoze");
1474 pw.println();
1475 if (canDoze()) {
1476 pw.println(" doze screen state: " + Display.stateToString(mDozeScreenState));
1477 pw.println(" doze screen brightness: " + mDozeScreenBrightness);
1478 }
1479 }
1480
1481 private static int clampAbsoluteBrightness(int value) {
1482 return MathUtils.constrain(value, PowerManager.BRIGHTNESS_OFF, PowerManager.BRIGHTNESS_ON);
1483 }
1484
1485 /**
1486 * The DreamServiceWrapper is used as a gateway to the system_server, where DreamController
1487 * uses it to control the DreamService. It is also used to receive callbacks from the
1488 * DreamActivity.
1489 */
1490 final class DreamServiceWrapper extends IDreamService.Stub {
1491 @Override
1492 public void attach(final IBinder dreamToken, final boolean canDoze,
1493 IRemoteCallback started) {
1494 mHandler.post(() -> DreamService.this.attach(dreamToken, canDoze, started));
1495 }
1496
1497 @Override
1498 public void detach() {
1499 mHandler.post(DreamService.this::detach);
1500 }
1501
1502 @Override
1503 public void wakeUp() {
1504 mHandler.post(() -> DreamService.this.wakeUp(true /*fromSystem*/));
1505 }
1506 }
1507
1508 /** @hide */
1509 final class DreamActivityCallbacks extends Binder {
1510 private final IBinder mActivityDreamToken;
1511
1512 DreamActivityCallbacks(IBinder token) {
1513 mActivityDreamToken = token;
1514 }
1515
1516 void onActivityCreated(DreamActivity activity) {
1517 if (mActivityDreamToken != mDreamToken || mFinished) {
1518 Slog.d(TAG, "DreamActivity was created after the dream was finished or "
1519 + "a new dream started, finishing DreamActivity");
1520 if (!activity.isFinishing()) {
1521 activity.finishAndRemoveTask();
1522 }
1523 return;
1524 }
1525 if (mActivity != null) {
1526 Slog.w(TAG, "A DreamActivity has already been started, "
1527 + "finishing latest DreamActivity");
1528 if (!activity.isFinishing()) {
1529 activity.finishAndRemoveTask();
1530 }
1531 return;
1532 }
1533
1534 mActivity = activity;
1535 onWindowCreated(activity.getWindow());
1536 }
1537
1538 // If DreamActivity is destroyed, wake up from Dream.
1539 void onActivityDestroyed() {
1540 mActivity = null;
1541 onDestroy();
1542 }
1543 }
1544
1545 /**
1546 * Represents metadata defined in {@link android.R.styleable#Dream &lt;dream&gt;}.
1547 *
1548 * @hide
1549 */
1550 @TestApi
1551 public static final class DreamMetadata {
1552 @Nullable
1553 public final ComponentName settingsActivity;
1554
1555 @Nullable
1556 public final Drawable previewImage;
1557
1558 @NonNull
1559 public final boolean showComplications;
1560
1561 DreamMetadata(ComponentName settingsActivity, Drawable previewImage,
1562 boolean showComplications) {
1563 this.settingsActivity = settingsActivity;
1564 this.previewImage = previewImage;
1565 this.showComplications = showComplications;
1566 }
1567 }
1568 }