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