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