/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.service.dreams; import static android.content.pm.PackageManager.PERMISSION_GRANTED; import static android.service.dreams.Flags.dreamHandlesConfirmKeys; import static android.service.dreams.Flags.dreamHandlesBeingObscured; import android.annotation.FlaggedApi; import android.annotation.IdRes; import android.annotation.IntDef; import android.annotation.LayoutRes; import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.SdkConstant; import android.annotation.SdkConstant.SdkConstantType; import android.annotation.TestApi; import android.app.Activity; import android.app.AlarmManager; import android.app.KeyguardManager; import android.app.Service; import android.compat.annotation.UnsupportedAppUsage; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ServiceInfo; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Binder; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.os.IRemoteCallback; import android.os.Looper; import android.os.PowerManager; import android.os.RemoteException; import android.os.ServiceManager; import android.service.controls.flags.Flags; import android.service.dreams.utils.DreamAccessibility; import android.util.Log; import android.util.MathUtils; import android.util.Slog; import android.view.ActionMode; import android.view.Display; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.SearchEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowInsets; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.view.accessibility.AccessibilityEvent; import com.android.internal.R; import com.android.internal.annotations.VisibleForTesting; import com.android.internal.util.DumpUtils; import java.io.FileDescriptor; import java.io.PrintWriter; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.function.Consumer; /** * Extend this class to implement a custom dream (available to the user as a "Daydream"). * *
Dreams are interactive screensavers launched when a charging device is idle, or docked in a * desk dock. Dreams provide another modality for apps to express themselves, tailored for * an exhibition/lean-back experience.
* *The {@code DreamService} lifecycle is as follows:
*Use this for initial setup, such as calling {@link #setContentView setContentView()}.
Your dream has started, so you should begin animations or other behaviors here.
Use this to stop the things you started in {@link #onDreamingStarted}.
Use this to dismantle resources (for example, detach from handlers * and listeners).
In addition, onCreate and onDestroy (from the Service interface) will also be called, but * initialization and teardown should be done by overriding the hooks above.
* *To be available to the system, your {@code DreamService} should be declared in the * manifest as follows:
** <service * android:name=".MyDream" * android:exported="true" * android:icon="@drawable/my_icon" * android:label="@string/my_dream_label" > * * <intent-filter> * <action android:name="android.service.dreams.DreamService" /> * <category android:name="android.intent.category.DEFAULT" /> * </intent-filter> * * <!-- Point to additional information for this dream (optional) --> * <meta-data * android:name="android.service.dream" * android:resource="@xml/my_dream" /> * </service> ** *
If specified with the {@code
res/xml/my_dream.xml
** <dream xmlns:android="http://schemas.android.com/apk/res/android" * android:settingsActivity="com.example.app/.MyDreamSettingsActivity" /> **
This makes a Settings button available alongside your dream's listing in the * system settings, which when pressed opens the specified activity.
* * *To specify your dream layout, call {@link #setContentView}, typically during the * {@link #onAttachedToWindow} callback. For example:
** public class MyDream extends DreamService { * * @Override * public void onAttachedToWindow() { * super.onAttachedToWindow(); * * // Exit dream upon user touch * setInteractive(false); * // Hide system UI * setFullscreen(true); * // Set the dream layout * setContentView(R.layout.dream); * } * } ** *
When targeting api level 21 and above, you must declare the service in your manifest file * with the {@link android.Manifest.permission#BIND_DREAM_SERVICE} permission. For example:
** <service * android:name=".MyDream" * android:exported="true" * android:icon="@drawable/my_icon" * android:label="@string/my_dream_label" * android:permission="android.permission.BIND_DREAM_SERVICE"> * <intent-filter> * <action android:name=”android.service.dreams.DreamService” /> * <category android:name=”android.intent.category.DEFAULT” /> * </intent-filter> * </service> **/ public class DreamService extends Service implements Window.Callback { private static final String TAG = DreamService.class.getSimpleName(); private final String mTag = TAG + "[" + getClass().getSimpleName() + "]"; private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG); /** * The name of the dream manager service. * @hide */ public static final String DREAM_SERVICE = "dreams"; /** * The {@link Intent} that must be declared as handled by the service. */ @SdkConstant(SdkConstantType.SERVICE_ACTION) public static final String SERVICE_INTERFACE = "android.service.dreams.DreamService"; /** * Name under which a Dream publishes information about itself. * This meta-data must reference an XML resource containing * a
<{@link android.R.styleable#Dream dream}>
* tag.
*/
public static final String DREAM_META_DATA = "android.service.dream";
/**
* Name of the root tag under which a Dream defines its metadata in an XML file.
*/
private static final String DREAM_META_DATA_ROOT_TAG = "dream";
/**
* The default value for whether to show complications on the overlay.
*
* @hide
*/
public static final boolean DEFAULT_SHOW_COMPLICATIONS = false;
/**
* The default value for dream category
* @hide
*/
@VisibleForTesting
public static final int DREAM_CATEGORY_DEFAULT = 0;
/**
* Dream category for Low Light Dream
* @hide
*/
public static final int DREAM_CATEGORY_LOW_LIGHT = 1 << 0;
/**
* Dream category for Home Panel Dream
* @hide
*/
public static final int DREAM_CATEGORY_HOME_PANEL = 1 << 1;
/** @hide */
@IntDef(flag = true, prefix = {"DREAM_CATEGORY"}, value = {
DREAM_CATEGORY_DEFAULT,
DREAM_CATEGORY_LOW_LIGHT,
DREAM_CATEGORY_HOME_PANEL
})
@Retention(RetentionPolicy.SOURCE)
@interface DreamCategory {}
/**
* The name of the extra where the dream overlay component is stored.
*/
static final String EXTRA_DREAM_OVERLAY_COMPONENT =
"android.service.dream.DreamService.dream_overlay_component";
private final IDreamManager mDreamManager;
private final Handler mHandler;
private IBinder mDreamToken;
private Window mWindow;
private Activity mActivity;
private boolean mInteractive;
private boolean mFullscreen;
private boolean mScreenBright = true;
private boolean mStarted;
private boolean mWaking;
private boolean mFinished;
private boolean mCanDoze;
private boolean mDozing;
private boolean mWindowless;
private boolean mPreviewMode;
private int mDozeScreenState = Display.STATE_UNKNOWN;
private @Display.StateReason int mDozeScreenStateReason = Display.STATE_REASON_UNKNOWN;
private int mDozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
private boolean mDebug = false;
private ComponentName mDreamComponent;
private DreamAccessibility mDreamAccessibility;
private boolean mShouldShowComplications;
private DreamServiceWrapper mDreamServiceWrapper;
private Runnable mDispatchAfterOnAttachedToWindow;
private DreamOverlayConnectionHandler mOverlayConnection;
private IDreamOverlayCallback mOverlayCallback;
private Integer mTrackingConfirmKey = null;
private boolean mRedirectWake;
private final Injector mInjector;
/**
* A helper object to inject dependencies into {@link DreamService}.
* @hide
*/
@VisibleForTesting
public interface Injector {
/** Initializes the Injector */
void init(Context context);
/** Creates and returns the dream overlay connection */
DreamOverlayConnectionHandler createOverlayConnection(ComponentName overlayComponent);
/** Returns the {@link DreamActivity} component */
ComponentName getDreamActivityComponent();
/** Returns the dream component */
ComponentName getDreamComponent();
/** Returns the dream package name */
String getDreamPackageName();
/** Returns the {@link DreamManager} */
IDreamManager getDreamManager();
/** Returns the associated service info */
ServiceInfo getServiceInfo();
/** Returns the handler to be used for any posted operation */
Handler getHandler();
/** Returns the package manager */
PackageManager getPackageManager();
/** Returns the resources */
Resources getResources();
}
private static final class DefaultInjector implements Injector {
private Context mContext;
private Class> mClassName;
public void init(Context context) {
mContext = context;
mClassName = context.getClass();
}
@Override
public DreamOverlayConnectionHandler createOverlayConnection(
ComponentName overlayComponent) {
final Resources resources = mContext.getResources();
return new DreamOverlayConnectionHandler(
/* context= */ mContext,
Looper.getMainLooper(),
new Intent().setComponent(overlayComponent),
resources.getInteger(R.integer.config_minDreamOverlayDurationMs),
resources.getInteger(R.integer.config_dreamOverlayMaxReconnectAttempts),
resources.getInteger(R.integer.config_dreamOverlayReconnectTimeoutMs));
}
@Override
public ComponentName getDreamActivityComponent() {
return new ComponentName(mContext, DreamActivity.class);
}
@Override
public ComponentName getDreamComponent() {
return new ComponentName(mContext, mClassName);
}
@Override
public String getDreamPackageName() {
return mContext.getApplicationContext().getPackageName();
}
@Override
public IDreamManager getDreamManager() {
return IDreamManager.Stub.asInterface(ServiceManager.getService(DREAM_SERVICE));
}
@Override
public ServiceInfo getServiceInfo() {
return fetchServiceInfo(mContext, getDreamComponent());
}
@Override
public Handler getHandler() {
return new Handler(Looper.getMainLooper());
}
@Override
public PackageManager getPackageManager() {
return mContext.getPackageManager();
}
@Override
public Resources getResources() {
return mContext.getResources();
}
}
public DreamService() {
this(new DefaultInjector());
}
/**
* Constructor for test purposes.
*
* @param injector used for providing dependencies
* @hide
*/
@VisibleForTesting
public DreamService(Injector injector) {
mInjector = injector;
mInjector.init(this);
mDreamManager = mInjector.getDreamManager();
mHandler = mInjector.getHandler();
}
/**
* @hide
*/
public void setDebug(boolean dbg) {
mDebug = dbg;
}
// begin Window.Callback methods
/** {@inheritDoc} */
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (dreamHandlesConfirmKeys()) {
// In the case of an interactive dream that consumes the event, do not process further.
if (mInteractive && mWindow.superDispatchKeyEvent(event)) {
return true;
}
// If the key is a confirm key and on up, either unlock (no auth) or show bouncer.
if (KeyEvent.isConfirmKey(event.getKeyCode())) {
switch (event.getAction()) {
case KeyEvent.ACTION_DOWN -> {
if (mTrackingConfirmKey != null) {
return true;
}
mTrackingConfirmKey = event.getKeyCode();
}
case KeyEvent.ACTION_UP -> {
if (mTrackingConfirmKey != event.getKeyCode()) {
return true;
}
mTrackingConfirmKey = null;
final KeyguardManager keyguardManager =
getSystemService(KeyguardManager.class);
// Simply wake up in the case the device is not locked.
if (!keyguardManager.isKeyguardLocked()) {
wakeUp();
return true;
}
keyguardManager.requestDismissKeyguard(getActivity(),
new KeyguardManager.KeyguardDismissCallback() {
@Override
public void onDismissError() {
Log.e(TAG, "Could not dismiss keyguard on confirm key");
}
});
}
}
// All key events for matching key codes should be consumed to prevent other actions
// from triggering.
return true;
}
}
if (!mInteractive) {
if (mDebug) Slog.v(mTag, "Waking up on keyEvent");
wakeUp();
return true;
} else if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (mDebug) Slog.v(mTag, "Waking up on back key");
wakeUp();
return true;
}
return mWindow.superDispatchKeyEvent(event);
}
/** {@inheritDoc} */
@Override
public boolean dispatchKeyShortcutEvent(KeyEvent event) {
if (!mInteractive) {
if (mDebug) Slog.v(mTag, "Waking up on keyShortcutEvent");
wakeUp();
return true;
}
return mWindow.superDispatchKeyShortcutEvent(event);
}
/** {@inheritDoc} */
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
// TODO: create more flexible version of mInteractive that allows clicks
// but finish()es on any other kind of activity
if (!mInteractive && event.getActionMasked() == MotionEvent.ACTION_UP) {
if (mDebug) Slog.v(mTag, "Waking up on touchEvent");
wakeUp();
return true;
}
return mWindow.superDispatchTouchEvent(event);
}
/** {@inheritDoc} */
@Override
public boolean dispatchTrackballEvent(MotionEvent event) {
if (!mInteractive) {
if (mDebug) Slog.v(mTag, "Waking up on trackballEvent");
wakeUp();
return true;
}
return mWindow.superDispatchTrackballEvent(event);
}
/** {@inheritDoc} */
@Override
public boolean dispatchGenericMotionEvent(MotionEvent event) {
if (!mInteractive) {
if (mDebug) Slog.v(mTag, "Waking up on genericMotionEvent");
wakeUp();
return true;
}
return mWindow.superDispatchGenericMotionEvent(event);
}
/** {@inheritDoc} */
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
return false;
}
/** {@inheritDoc} */
@Override
public View onCreatePanelView(int featureId) {
return null;
}
/** {@inheritDoc} */
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
return false;
}
/** {@inheritDoc} */
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
return false;
}
/** {@inheritDoc} */
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
return false;
}
/** {@inheritDoc} */
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
return false;
}
/** {@inheritDoc} */
@Override
public void onWindowAttributesChanged(LayoutParams attrs) {
}
/** {@inheritDoc} */
@Override
public void onContentChanged() {
}
/** {@inheritDoc} */
@Override
public void onWindowFocusChanged(boolean hasFocus) {
}
/** {@inheritDoc} */
@Override
public void onAttachedToWindow() {
}
/** {@inheritDoc} */
@Override
public void onDetachedFromWindow() {
}
/** {@inheritDoc} */
@Override
public void onPanelClosed(int featureId, Menu menu) {
}
/** {@inheritDoc} */
@Override
public boolean onSearchRequested(SearchEvent event) {
return onSearchRequested();
}
/** {@inheritDoc} */
@Override
public boolean onSearchRequested() {
return false;
}
/** {@inheritDoc} */
@Override
public ActionMode onWindowStartingActionMode(android.view.ActionMode.Callback callback) {
return null;
}
/** {@inheritDoc} */
@Override
public ActionMode onWindowStartingActionMode(
android.view.ActionMode.Callback callback, int type) {
return null;
}
/** {@inheritDoc} */
@Override
public void onActionModeStarted(ActionMode mode) {
}
/** {@inheritDoc} */
@Override
public void onActionModeFinished(ActionMode mode) {
}
// end Window.Callback methods
// begin public api
/**
* Retrieves the current {@link android.view.WindowManager} for the dream.
* Behaves similarly to {@link android.app.Activity#getWindowManager()}.
*
* @return The current window manager, or null if the dream is not started.
*/
public WindowManager getWindowManager() {
return mWindow != null ? mWindow.getWindowManager() : null;
}
/**
* Retrieves the current {@link android.view.Window} for the dream.
* Behaves similarly to {@link android.app.Activity#getWindow()}.
*
* @return The current window, or null if the dream is not started.
*/
public Window getWindow() {
return mWindow;
}
/**
* Retrieves the current {@link android.app.Activity} associated with the dream.
* This method behaves similarly to calling {@link android.app.Activity#getActivity()}.
*
* @return The current activity, or null if the dream is not associated with an activity
* or not started.
*
* @hide
*/
public Activity getActivity() {
return mActivity;
}
/**
* Inflates a layout resource and set it to be the content view for this Dream.
* Behaves similarly to {@link android.app.Activity#setContentView(int)}.
*
* Note: Requires a window, do not call before {@link #onAttachedToWindow()}
* * @param layoutResID Resource ID to be inflated. * * @see #setContentView(android.view.View) * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams) */ public void setContentView(@LayoutRes int layoutResID) { getWindow().setContentView(layoutResID); } /** * Sets a view to be the content view for this Dream. * Behaves similarly to {@link android.app.Activity#setContentView(android.view.View)} in an activity, * including using {@link ViewGroup.LayoutParams#MATCH_PARENT} as the layout height and width of the view. * *Note: This requires a window, so you should usually call it during * {@link #onAttachedToWindow()} and never earlier (you cannot call it * during {@link #onCreate}).
* * @see #setContentView(int) * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams) */ public void setContentView(View view) { getWindow().setContentView(view); } /** * Sets a view to be the content view for this Dream. * Behaves similarly to * {@link android.app.Activity#setContentView(android.view.View, android.view.ViewGroup.LayoutParams)} * in an activity. * *Note: This requires a window, so you should usually call it during * {@link #onAttachedToWindow()} and never earlier (you cannot call it * during {@link #onCreate}).
* * @param view The desired content to display. * @param params Layout parameters for the view. * * @see #setContentView(android.view.View) * @see #setContentView(int) */ public void setContentView(View view, ViewGroup.LayoutParams params) { getWindow().setContentView(view, params); } /** * Adds a view to the Dream's window, leaving other content views in place. * *Note: Requires a window, do not call before {@link #onAttachedToWindow()}
* * @param view The desired content to display. * @param params Layout parameters for the view. */ public void addContentView(View view, ViewGroup.LayoutParams params) { getWindow().addContentView(view, params); } /** * Finds a view that was identified by the id attribute from the XML that * was processed in {@link #onCreate}. * *Note: Requires a window, do not call before {@link #onAttachedToWindow()}
*
* Note: In most cases -- depending on compiler support --
* the resulting view is automatically cast to the target class type. If
* the target class type is unconstrained, an explicit cast may be
* necessary.
*
* @param id the ID to search for
* @return The view if found or null otherwise.
* @see View#findViewById(int)
* @see DreamService#requireViewById(int)
*/
@Nullable
public Note: Requires a window, do not call before {@link #onAttachedToWindow()}
* Note: In most cases -- depending on compiler support --
* the resulting view is automatically cast to the target class type. If
* the target class type is unconstrained, an explicit cast may be
* necessary.
*
* @param id the ID to search for
* @return a view with given ID
* @see View#requireViewById(int)
* @see DreamService#findViewById(int)
*/
@NonNull
public final Non-interactive dreams (default) will dismiss on the first input event. Interactive dreams should call {@link #finish()} to dismiss themselves.
* The value returned by this method is only meaningful when the dream has started.
*
* Dozing enables the system to conserve power while the user is not actively interacting
* with the device. While dozing, the display will remain on in a low-power state
* and will continue to show its previous contents but the application processor and
* other system components will be allowed to suspend when possible.
*
* While the application processor is suspended, the dream may stop executing code
* for long periods of time. Prior to being suspended, the dream may schedule periodic
* wake-ups to render new content by scheduling an alarm with the {@link AlarmManager}.
* The dream may also keep the CPU awake by acquiring a
* {@link android.os.PowerManager#PARTIAL_WAKE_LOCK partial wake lock} when necessary.
* Note that since the purpose of doze mode is to conserve power (especially when
* running on battery), the dream should not wake the CPU very often or keep it
* awake for very long.
*
* It is a good idea to call this method some time after the dream's entry animation
* has completed and the dream is ready to doze. It is important to completely
* finish all of the work needed before dozing since the application processor may
* be suspended at any moment once this method is called unless other wake locks
* are being held.
*
* Call {@link #stopDozing} or {@link #finish} to stop dozing.
*
* This method reverses the effect of {@link #startDozing}. From this moment onward,
* the application processor will be kept awake as long as the dream is running
* or until the dream starts dozing again.
* Use {@link #setDozeScreenState(int, int)} whenever possible to allow properly accounting
* for the screen state reason.
*
* @hide
*/
@UnsupportedAppUsage
public void setDozeScreenState(int state) {
setDozeScreenState(state, Display.STATE_REASON_UNKNOWN);
}
/**
* Sets the screen state to use while dozing.
*
* The value of this property determines the power state of the primary display
* once {@link #startDozing} has been called. The default value is
* {@link Display#STATE_UNKNOWN} which lets the system decide.
* The dream may set a different state before starting to doze and may
* perform transitions between states while dozing to conserve power and
* achieve various effects.
*
* Some devices will have dedicated hardware ("Sidekick") to animate
* the display content while the CPU sleeps. If the dream and the hardware support
* this, {@link Display#STATE_ON_SUSPEND} or {@link Display#STATE_DOZE_SUSPEND}
* will switch control to the Sidekick.
*
* If not using Sidekick, it is recommended that the state be set to
* {@link Display#STATE_DOZE_SUSPEND} once the dream has completely
* finished drawing and before it releases its wakelock
* to allow the display hardware to be fully suspended. While suspended,
* the display will preserve its on-screen contents.
*
* If the doze suspend state is used, the dream must make sure to set the mode back
* to {@link Display#STATE_DOZE} or {@link Display#STATE_ON} before drawing again
* since the display updates may be ignored and not seen by the user otherwise.
*
* The set of available display power states and their behavior while dozing is
* hardware dependent and may vary across devices. The dream may therefore
* need to be modified or configured to correctly support the hardware.
*
* The value of this property determines the power state of the primary display
* once {@link #startDozing} has been called. The default value is
* {@link PowerManager#BRIGHTNESS_DEFAULT} which lets the system decide.
* The dream may set a different brightness before starting to doze and may adjust
* the brightness while dozing to conserve power and achieve various effects.
*
* Note that dream may specify any brightness in the full 0-255 range, including
* values that are less than the minimum value for manual screen brightness
* adjustments by the user. In particular, the value may be set to 0 which may
* turn off the backlight entirely while still leaving the screen on although
* this behavior is device dependent and not guaranteed.
*
* The available range of display brightness values and their behavior while dozing is
* hardware dependent and may vary across devices. The dream may therefore
* need to be modified or configured to correctly support the hardware.
*
* The default implementation simply calls {@link #finish} which ends the dream
* immediately. Subclasses may override this function to perform a smooth exit
* transition then call {@link #finish} afterwards.
*
* Note that the dream will only be given a short period of time (currently about
* five seconds) to wake up. If the dream does not finish itself in a timely manner
* then the system will forcibly finish it once the time allowance is up.
*
* When the dream ends, the system will be allowed to go to sleep fully unless there
* is a reason for it to be awake such as recent user activity or wake locks being held.
*
* Calls {@link #onWakeUp} to give the dream a chance to perform an exit transition.
* When the transition is over, the dream should call {@link #finish}.
*