summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.clang-format13
-rw-r--r--Android.bp114
-rw-r--r--CleanSpec.mk3
-rw-r--r--PREUPLOAD.cfg10
-rw-r--r--apct-tests/perftests/core/src/android/wm/InternalWindowOperationPerfTest.java2
-rw-r--r--apct-tests/perftests/utils/src/android/perftests/utils/ManualBenchmarkState.java24
-rw-r--r--apct-tests/perftests/utils/src/android/perftests/utils/TraceMarkParser.java46
-rw-r--r--apex/Android.bp42
-rw-r--r--apex/appsearch/Android.bp6
-rw-r--r--apex/appsearch/framework/Android.bp57
-rw-r--r--apex/appsearch/framework/java/android/app/appsearch/AppSearchManagerFrameworkInitializer.java12
-rw-r--r--apex/jobscheduler/service/java/com/android/server/job/JobConcurrencyManager.java7
-rw-r--r--apex/sdkext/Android.bp40
-rw-r--r--apex/sdkext/TEST_MAPPING2
-rw-r--r--apex/sdkext/derive_sdk/derive_sdk.cpp2
-rw-r--r--apex/sdkext/framework/Android.bp41
-rw-r--r--apex/sdkext/framework/java/android/os/ext/SdkExtensions.java23
-rw-r--r--apex/sdkext/framework/tests/Android.bp11
-rw-r--r--apex/sdkext/gen_sdkinfo.py19
-rw-r--r--apex/sdkext/sdk.proto25
-rw-r--r--apex/statsd/Android.bp16
-rw-r--r--apex/statsd/aidl/Android.bp12
-rw-r--r--apex/statsd/aidl/android/os/IStatsManagerService.aidl65
-rw-r--r--apex/statsd/aidl/android/os/IStatsd.aidl (renamed from apex/statsd/aidl/android/os/IStatsManager.aidl)2
-rw-r--r--apex/statsd/framework/Android.bp67
-rw-r--r--apex/statsd/framework/java/android/util/StatsEvent.java (renamed from core/java/android/util/StatsEvent.java)66
-rw-r--r--apex/statsd/service/Android.bp6
-rw-r--r--apex/statsd/service/java/com/android/server/stats/StatsCompanion.java70
-rw-r--r--apex/statsd/service/java/com/android/server/stats/StatsCompanionService.java74
-rw-r--r--apex/statsd/service/java/com/android/server/stats/StatsManagerService.java108
-rw-r--r--apex/statsd/testing/Android.bp25
-rw-r--r--apex/statsd/testing/test_manifest.json4
-rw-r--r--api/current.txt233
-rw-r--r--api/removed.txt21
-rwxr-xr-x[-rw-r--r--]api/system-current.txt484
-rw-r--r--api/system-lint-baseline.txt1
-rw-r--r--api/test-current.txt87
-rw-r--r--api/test-lint-baseline.txt6
-rw-r--r--cmds/hid/jni/Android.bp1
-rw-r--r--cmds/hid/jni/com_android_commands_hid_Device.cpp129
-rw-r--r--cmds/hid/jni/com_android_commands_hid_Device.h12
-rw-r--r--cmds/hid/src/com/android/commands/hid/Device.java37
-rw-r--r--cmds/hid/src/com/android/commands/hid/Event.java75
-rw-r--r--cmds/hid/src/com/android/commands/hid/Hid.java9
-rw-r--r--cmds/incident/main.cpp4
-rw-r--r--cmds/incidentd/src/IncidentService.cpp4
-rw-r--r--cmds/incidentd/src/IncidentService.h4
-rw-r--r--cmds/incidentd/src/WorkDirectory.cpp2
-rw-r--r--cmds/media/Android.bp8
-rw-r--r--cmds/media/MODULE_LICENSE_APACHE20
-rw-r--r--cmds/media/NOTICE190
-rwxr-xr-xcmds/media/media3
-rw-r--r--cmds/statsd/Android.bp59
-rw-r--r--cmds/statsd/src/FieldValue.cpp2
-rw-r--r--cmds/statsd/src/StatsLogProcessor.cpp1
-rw-r--r--cmds/statsd/src/StatsService.cpp14
-rw-r--r--cmds/statsd/src/StatsService.h6
-rw-r--r--cmds/statsd/src/atoms.proto31
-rw-r--r--cmds/statsd/src/external/PowerStatsPuller.cpp1
-rw-r--r--cmds/statsd/src/external/StatsCallbackPuller.cpp21
-rw-r--r--cmds/statsd/src/external/StatsCallbackPuller.h8
-rw-r--r--cmds/statsd/src/external/StatsPullerManager.cpp13
-rw-r--r--cmds/statsd/src/external/puller_util.cpp2
-rw-r--r--cmds/statsd/src/guardrail/StatsdStats.h2
-rw-r--r--cmds/statsd/src/logd/LogEvent.cpp11
-rw-r--r--cmds/statsd/src/logd/LogEvent.h5
-rw-r--r--cmds/statsd/src/metrics/MetricsManager.cpp1
-rw-r--r--cmds/statsd/src/metrics/metrics_manager_util.cpp2
-rw-r--r--cmds/statsd/src/state/StateManager.cpp9
-rw-r--r--cmds/statsd/src/state/StateManager.h13
-rw-r--r--cmds/statsd/src/state/StateTracker.h2
-rw-r--r--cmds/statsd/src/stats_log_util.h2
-rw-r--r--cmds/statsd/tests/external/GpuStatsPuller_test.cpp1
-rw-r--r--cmds/statsd/tests/external/StatsCallbackPuller_test.cpp210
-rw-r--r--cmds/statsd/tests/external/StatsPuller_test.cpp5
-rw-r--r--cmds/statsd/tests/external/SurfaceflingerStatsPuller_test.cpp1
-rw-r--r--cmds/statsd/tests/external/puller_util_test.cpp1
-rw-r--r--cmds/uiautomator/library/Android.bp1
-rw-r--r--core/java/android/accessibilityservice/AccessibilityGestureEvent.java4
-rw-r--r--core/java/android/accessibilityservice/AccessibilityService.java14
-rw-r--r--core/java/android/accessibilityservice/AccessibilityServiceInfo.java2
-rw-r--r--core/java/android/accessibilityservice/AccessibilityShortcutInfo.java10
-rw-r--r--core/java/android/accounts/Account.java2
-rw-r--r--core/java/android/accounts/AccountAndUser.java2
-rw-r--r--core/java/android/accounts/AccountAuthenticatorResponse.java4
-rw-r--r--core/java/android/accounts/AccountManager.java31
-rw-r--r--core/java/android/accounts/AuthenticatorDescription.java4
-rw-r--r--core/java/android/accounts/IAccountManager.aidl3
-rw-r--r--core/java/android/animation/Animator.java2
-rw-r--r--core/java/android/animation/ArgbEvaluator.java2
-rw-r--r--core/java/android/animation/LayoutTransition.java2
-rw-r--r--core/java/android/animation/ValueAnimator.java2
-rw-r--r--core/java/android/annotation/Hide.java41
-rw-r--r--core/java/android/annotation/OWNERS1
-rw-r--r--core/java/android/annotation/SystemApi.java45
-rw-r--r--core/java/android/app/ActionBar.java2
-rw-r--r--core/java/android/app/Activity.java24
-rw-r--r--core/java/android/app/ActivityGroup.java2
-rw-r--r--core/java/android/app/ActivityManager.java142
-rw-r--r--core/java/android/app/ActivityManagerNative.java2
-rw-r--r--core/java/android/app/ActivityOptions.java2
-rw-r--r--core/java/android/app/ActivityTaskManager.java2
-rw-r--r--core/java/android/app/ActivityThread.java39
-rw-r--r--core/java/android/app/AlarmManager.java2
-rw-r--r--core/java/android/app/AlertDialog.java2
-rw-r--r--core/java/android/app/AppGlobals.java2
-rw-r--r--core/java/android/app/AppOpsManager.java4
-rw-r--r--core/java/android/app/Application.java2
-rw-r--r--core/java/android/app/ApplicationLoaders.java2
-rw-r--r--core/java/android/app/ApplicationPackageManager.java2
-rw-r--r--core/java/android/app/ContentProviderHolder.java2
-rw-r--r--core/java/android/app/ContextImpl.java23
-rw-r--r--core/java/android/app/DatePickerDialog.java2
-rw-r--r--core/java/android/app/Dialog.java2
-rw-r--r--core/java/android/app/DialogFragment.java2
-rw-r--r--core/java/android/app/DownloadManager.java6
-rw-r--r--core/java/android/app/Fragment.java2
-rw-r--r--core/java/android/app/FragmentController.java2
-rw-r--r--core/java/android/app/FragmentHostCallback.java2
-rw-r--r--core/java/android/app/FragmentManager.java2
-rw-r--r--core/java/android/app/IActivityManager.aidl1
-rw-r--r--core/java/android/app/IActivityTaskManager.aidl10
-rw-r--r--core/java/android/app/IBackupAgent.aidl13
-rw-r--r--core/java/android/app/IInstantAppResolver.aidl10
-rw-r--r--core/java/android/app/InstantAppResolverService.java131
-rw-r--r--core/java/android/app/Instrumentation.java19
-rw-r--r--core/java/android/app/IntentService.java4
-rw-r--r--core/java/android/app/KeyguardManager.java2
-rw-r--r--core/java/android/app/LoadedApk.java2
-rw-r--r--core/java/android/app/LocalActivityManager.java2
-rw-r--r--core/java/android/app/NativeActivity.java2
-rw-r--r--core/java/android/app/Notification.java2
-rw-r--r--core/java/android/app/NotificationChannel.java2
-rw-r--r--core/java/android/app/NotificationChannelGroup.java2
-rw-r--r--core/java/android/app/NotificationManager.java2
-rw-r--r--core/java/android/app/PackageDeleteObserver.java2
-rw-r--r--core/java/android/app/PackageInstallObserver.java2
-rw-r--r--core/java/android/app/PendingIntent.java2
-rw-r--r--core/java/android/app/Presentation.java12
-rw-r--r--core/java/android/app/ProgressDialog.java6
-rw-r--r--core/java/android/app/QueuedWork.java2
-rw-r--r--core/java/android/app/ResourcesManager.java2
-rw-r--r--core/java/android/app/ResultInfo.java2
-rw-r--r--core/java/android/app/SearchDialog.java2
-rw-r--r--core/java/android/app/SearchManager.java2
-rw-r--r--core/java/android/app/SearchableInfo.java10
-rw-r--r--core/java/android/app/Service.java2
-rw-r--r--core/java/android/app/SharedPreferencesImpl.java2
-rw-r--r--core/java/android/app/StatsManager.java40
-rw-r--r--core/java/android/app/StatusBarManager.java2
-rw-r--r--core/java/android/app/SystemServiceRegistry.java44
-rw-r--r--core/java/android/app/TaskEmbedder.java4
-rw-r--r--core/java/android/app/TaskInfo.java2
-rw-r--r--core/java/android/app/TaskStackListener.java2
-rw-r--r--core/java/android/app/TimePickerDialog.java2
-rw-r--r--core/java/android/app/UiAutomation.java2
-rw-r--r--core/java/android/app/UiAutomationConnection.java3
-rw-r--r--core/java/android/app/UiModeManager.java2
-rw-r--r--core/java/android/app/UserSwitchObserver.java2
-rw-r--r--core/java/android/app/VrManager.java2
-rw-r--r--core/java/android/app/WallpaperManager.java2
-rw-r--r--core/java/android/app/WindowConfiguration.java3
-rw-r--r--core/java/android/app/admin/DeviceAdminInfo.java2
-rw-r--r--core/java/android/app/admin/DevicePolicyManager.java133
-rw-r--r--core/java/android/app/admin/IDevicePolicyManager.aidl10
-rw-r--r--core/java/android/app/admin/SecurityLog.java2
-rw-r--r--core/java/android/app/assist/AssistContent.java2
-rw-r--r--core/java/android/app/backup/BackupAgent.java47
-rw-r--r--core/java/android/app/backup/BackupDataInput.java2
-rw-r--r--core/java/android/app/backup/BackupDataInputStream.java5
-rw-r--r--core/java/android/app/backup/BackupDataOutput.java2
-rw-r--r--core/java/android/app/backup/BackupHelperDispatcher.java2
-rw-r--r--core/java/android/app/backup/BackupManager.java2
-rw-r--r--core/java/android/app/backup/FileBackupHelperBase.java2
-rw-r--r--core/java/android/app/backup/FullBackup.java2
-rw-r--r--core/java/android/app/backup/FullBackupDataOutput.java2
-rw-r--r--core/java/android/app/backup/IBackupManager.aidl6
-rw-r--r--core/java/android/app/role/RoleControllerService.java15
-rw-r--r--core/java/android/app/role/RoleManager.java33
-rw-r--r--core/java/android/app/servertransaction/ActivityResultItem.java2
-rw-r--r--core/java/android/app/servertransaction/ClientTransaction.java2
-rw-r--r--core/java/android/app/servertransaction/LaunchActivityItem.java2
-rw-r--r--core/java/android/app/servertransaction/NewIntentItem.java2
-rw-r--r--core/java/android/app/slice/SliceProvider.java4
-rw-r--r--core/java/android/app/timedetector/ManualTimeSuggestion.java1
-rw-r--r--core/java/android/app/timedetector/PhoneTimeSuggestion.java7
-rw-r--r--core/java/android/app/trust/TrustManager.java2
-rw-r--r--core/java/android/app/usage/ConfigurationStats.java2
-rw-r--r--core/java/android/app/usage/IStorageStatsManager.aidl8
-rw-r--r--core/java/android/app/usage/NetworkStatsManager.java2
-rw-r--r--core/java/android/app/usage/StorageStatsManager.java101
-rw-r--r--core/java/android/app/usage/UsageEvents.java2
-rw-r--r--core/java/android/app/usage/UsageStats.java2
-rw-r--r--core/java/android/app/usage/UsageStatsManager.java5
-rw-r--r--core/java/android/appwidget/AppWidgetHost.java2
-rw-r--r--core/java/android/appwidget/AppWidgetHostView.java2
-rw-r--r--core/java/android/appwidget/AppWidgetManager.java2
-rw-r--r--core/java/android/appwidget/AppWidgetProviderInfo.java2
-rw-r--r--core/java/android/bluetooth/BluetoothA2dp.java2
-rwxr-xr-xcore/java/android/bluetooth/BluetoothA2dpSink.java105
-rw-r--r--core/java/android/bluetooth/BluetoothAdapter.java16
-rwxr-xr-xcore/java/android/bluetooth/BluetoothClass.java2
-rw-r--r--core/java/android/bluetooth/BluetoothCodecConfig.java2
-rw-r--r--core/java/android/bluetooth/BluetoothDevice.java129
-rw-r--r--core/java/android/bluetooth/BluetoothGatt.java2
-rw-r--r--core/java/android/bluetooth/BluetoothGattCharacteristic.java2
-rw-r--r--core/java/android/bluetooth/BluetoothGattDescriptor.java2
-rw-r--r--core/java/android/bluetooth/BluetoothGattService.java2
-rw-r--r--core/java/android/bluetooth/BluetoothHeadset.java2
-rw-r--r--core/java/android/bluetooth/BluetoothHeadsetClient.java2
-rw-r--r--core/java/android/bluetooth/BluetoothHeadsetClientCall.java2
-rw-r--r--core/java/android/bluetooth/BluetoothHearingAid.java9
-rw-r--r--core/java/android/bluetooth/BluetoothManager.java30
-rw-r--r--core/java/android/bluetooth/BluetoothMap.java2
-rw-r--r--core/java/android/bluetooth/BluetoothMapClient.java2
-rw-r--r--core/java/android/bluetooth/BluetoothPan.java2
-rw-r--r--core/java/android/bluetooth/BluetoothPbap.java97
-rw-r--r--core/java/android/bluetooth/BluetoothProfile.java2
-rw-r--r--core/java/android/bluetooth/BluetoothSap.java2
-rw-r--r--core/java/android/bluetooth/BluetoothServerSocket.java2
-rw-r--r--core/java/android/bluetooth/BluetoothSocket.java2
-rw-r--r--core/java/android/bluetooth/BluetoothUuid.java2
-rw-r--r--core/java/android/bluetooth/le/BluetoothLeScanner.java20
-rw-r--r--core/java/android/bluetooth/le/ScanRecord.java2
-rw-r--r--core/java/android/companion/AssociationRequest.java2
-rw-r--r--core/java/android/companion/BluetoothDeviceFilter.java2
-rw-r--r--core/java/android/companion/BluetoothDeviceFilterUtils.java2
-rw-r--r--core/java/android/companion/BluetoothLeDeviceFilter.java2
-rw-r--r--core/java/android/companion/DeviceFilter.java2
-rw-r--r--core/java/android/content/AsyncTaskLoader.java2
-rw-r--r--core/java/android/content/BroadcastReceiver.java2
-rw-r--r--core/java/android/content/ClipData.java2
-rw-r--r--core/java/android/content/ClipboardManager.java2
-rw-r--r--core/java/android/content/ComponentName.java2
-rw-r--r--core/java/android/content/ContentProvider.java2
-rw-r--r--core/java/android/content/ContentProviderClient.java2
-rw-r--r--core/java/android/content/ContentProviderNative.java2
-rw-r--r--core/java/android/content/ContentResolver.java2
-rw-r--r--core/java/android/content/ContentValues.java3
-rw-r--r--core/java/android/content/Context.java59
-rw-r--r--core/java/android/content/ContextWrapper.java12
-rw-r--r--core/java/android/content/CursorEntityIterator.java2
-rw-r--r--core/java/android/content/CursorLoader.java2
-rw-r--r--core/java/android/content/Entity.java2
-rw-r--r--core/java/android/content/IContentProvider.java2
-rw-r--r--core/java/android/content/Intent.java175
-rw-r--r--core/java/android/content/IntentFilter.java2
-rw-r--r--core/java/android/content/IntentSender.java4
-rw-r--r--core/java/android/content/RestrictionsManager.java2
-rw-r--r--core/java/android/content/SearchRecentSuggestionsProvider.java2
-rw-r--r--core/java/android/content/SyncAdapterType.java6
-rw-r--r--core/java/android/content/SyncAdaptersCache.java4
-rw-r--r--core/java/android/content/SyncContext.java4
-rw-r--r--core/java/android/content/SyncInfo.java2
-rw-r--r--core/java/android/content/SyncRequest.java2
-rw-r--r--core/java/android/content/SyncStatusInfo.java2
-rw-r--r--core/java/android/content/UndoManager.java2
-rw-r--r--core/java/android/content/UndoOperation.java2
-rw-r--r--core/java/android/content/UriMatcher.java2
-rw-r--r--core/java/android/content/integrity/AtomicFormula.java2
-rw-r--r--core/java/android/content/integrity/CompoundFormula.java1
-rw-r--r--core/java/android/content/integrity/Formula.java1
-rw-r--r--core/java/android/content/integrity/Rule.java1
-rw-r--r--core/java/android/content/om/OverlayInfo.java2
-rw-r--r--core/java/android/content/pm/ActivityInfo.java2
-rw-r--r--core/java/android/content/pm/ApplicationInfo.java2
-rw-r--r--core/java/android/content/pm/AuxiliaryResolveInfo.java9
-rw-r--r--core/java/android/content/pm/BaseParceledListSlice.java4
-rw-r--r--core/java/android/content/pm/ComponentInfo.java2
-rw-r--r--core/java/android/content/pm/DataLoaderParams.java (renamed from core/java/android/os/incremental/IncrementalDataLoaderParams.java)14
-rw-r--r--core/java/android/content/pm/DataLoaderParamsParcel.aidl (renamed from core/java/android/os/incremental/IncrementalDataLoaderParamsParcel.aidl)6
-rw-r--r--core/java/android/content/pm/FileSystemControlParcel.aidl31
-rw-r--r--core/java/android/content/pm/IDataLoader.aidl1
-rw-r--r--core/java/android/content/pm/IPackageInstallerSession.aidl4
-rw-r--r--core/java/android/content/pm/IPackageInstallerSessionFileSystemConnector.aidl24
-rw-r--r--core/java/android/content/pm/InstantAppRequest.java33
-rw-r--r--core/java/android/content/pm/InstantAppRequestInfo.aidl19
-rw-r--r--core/java/android/content/pm/InstantAppRequestInfo.java188
-rw-r--r--core/java/android/content/pm/LauncherActivityInfo.java2
-rw-r--r--core/java/android/content/pm/LauncherApps.java2
-rw-r--r--core/java/android/content/pm/NamedParcelFileDescriptor.aidl (renamed from core/java/android/os/incremental/NamedParcelFileDescriptor.aidl)2
-rw-r--r--core/java/android/content/pm/PackageInfo.java2
-rw-r--r--core/java/android/content/pm/PackageInfoLite.java2
-rw-r--r--core/java/android/content/pm/PackageInstaller.java115
-rw-r--r--core/java/android/content/pm/PackageManager.java22
-rw-r--r--core/java/android/content/pm/PackageParser.java2
-rw-r--r--core/java/android/content/pm/PackageStats.java2
-rw-r--r--core/java/android/content/pm/PackageUserState.java2
-rw-r--r--core/java/android/content/pm/ParceledListSlice.aidl2
-rw-r--r--core/java/android/content/pm/ParceledListSlice.java2
-rw-r--r--core/java/android/content/pm/PermissionInfo.java2
-rw-r--r--core/java/android/content/pm/RegisteredServicesCache.java6
-rw-r--r--core/java/android/content/pm/ResolveInfo.java2
-rw-r--r--core/java/android/content/pm/ShortcutInfo.java2
-rw-r--r--core/java/android/content/pm/ShortcutManager.java2
-rw-r--r--core/java/android/content/pm/Signature.java2
-rw-r--r--core/java/android/content/pm/UserInfo.java2
-rw-r--r--core/java/android/content/pm/VerifierInfo.java2
-rw-r--r--core/java/android/content/pm/XmlSerializerAndParser.java5
-rw-r--r--core/java/android/content/pm/parsing/ApkParseUtils.java2
-rw-r--r--core/java/android/content/pm/parsing/ComponentParseUtils.java8
-rw-r--r--core/java/android/content/pm/parsing/PackageInfoUtils.java3
-rw-r--r--core/java/android/content/res/ApkAssets.java2
-rw-r--r--core/java/android/content/res/AssetFileDescriptor.java2
-rw-r--r--core/java/android/content/res/AssetManager.java2
-rw-r--r--core/java/android/content/res/ColorStateList.java19
-rw-r--r--core/java/android/content/res/CompatibilityInfo.java2
-rw-r--r--core/java/android/content/res/Configuration.java8
-rw-r--r--core/java/android/content/res/ConfigurationBoundResourceCache.java2
-rw-r--r--core/java/android/content/res/DrawableCache.java2
-rw-r--r--core/java/android/content/res/ObbInfo.java2
-rw-r--r--core/java/android/content/res/Resources.java3
-rw-r--r--core/java/android/content/res/ResourcesImpl.java6
-rw-r--r--core/java/android/content/res/ResourcesKey.java2
-rw-r--r--core/java/android/content/res/StringBlock.java2
-rw-r--r--core/java/android/content/res/ThemedResourceCache.java2
-rw-r--r--core/java/android/content/res/TypedArray.java2
-rw-r--r--core/java/android/content/res/XmlBlock.java2
-rw-r--r--core/java/android/content/rollback/IRollbackManager.aidl3
-rw-r--r--core/java/android/database/sqlite/SQLiteQueryBuilder.java1
-rw-r--r--core/java/android/hardware/biometrics/BiometricConstants.java7
-rw-r--r--core/java/android/hardware/biometrics/BiometricManager.java127
-rw-r--r--core/java/android/hardware/biometrics/BiometricPrompt.java319
-rw-r--r--core/java/android/hardware/biometrics/IAuthService.aidl2
-rw-r--r--core/java/android/hardware/biometrics/IBiometricService.aidl5
-rw-r--r--core/java/android/hardware/camera2/CameraCharacteristics.java113
-rw-r--r--core/java/android/hardware/camera2/CameraMetadata.java49
-rw-r--r--core/java/android/hardware/camera2/CaptureRequest.java92
-rw-r--r--core/java/android/hardware/camera2/CaptureResult.java122
-rw-r--r--core/java/android/hardware/camera2/impl/CameraDeviceImpl.java33
-rw-r--r--core/java/android/hardware/camera2/impl/CameraMetadataNative.java66
-rw-r--r--core/java/android/hardware/camera2/impl/ICameraDeviceUserWrapper.java13
-rw-r--r--core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java7
-rw-r--r--core/java/android/hardware/camera2/marshal/impl/MarshalQueryableCapabilityAndMaxSize.java77
-rw-r--r--core/java/android/hardware/camera2/params/Capability.java (renamed from core/java/android/hardware/camera2/params/CapabilityAndMaxSize.java)61
-rw-r--r--core/java/android/hardware/camera2/params/MandatoryStreamCombination.java2
-rw-r--r--core/java/android/hardware/soundtrigger/ConversionUtil.java329
-rw-r--r--core/java/android/hardware/soundtrigger/ModelParams.aidl37
-rw-r--r--core/java/android/hardware/soundtrigger/SoundTrigger.aidl1
-rw-r--r--core/java/android/hardware/soundtrigger/SoundTrigger.java235
-rw-r--r--core/java/android/hardware/soundtrigger/SoundTriggerModule.java317
-rw-r--r--core/java/android/inputmethodservice/IInputMethodWrapper.java18
-rw-r--r--core/java/android/inputmethodservice/InputMethodService.java197
-rw-r--r--core/java/android/net/InterfaceConfiguration.java4
-rw-r--r--core/java/android/net/InvalidPacketException.java61
-rw-r--r--core/java/android/net/KeepalivePacketData.java48
-rw-r--r--core/java/android/net/LinkProperties.java70
-rw-r--r--core/java/android/net/NattKeepalivePacketData.java4
-rw-r--r--core/java/android/net/NetworkRequest.java9
-rw-r--r--core/java/android/net/SocketKeepalive.java11
-rw-r--r--core/java/android/net/nsd/NsdServiceInfo.java6
-rw-r--r--core/java/android/nfc/ErrorCodes.java2
-rw-r--r--core/java/android/nfc/NdefRecord.java2
-rw-r--r--core/java/android/nfc/NfcActivityManager.java3
-rw-r--r--core/java/android/nfc/NfcAdapter.java2
-rw-r--r--core/java/android/nfc/NfcManager.java2
-rw-r--r--core/java/android/nfc/Tag.java2
-rw-r--r--core/java/android/nfc/cardemulation/AidGroup.java14
-rw-r--r--core/java/android/nfc/cardemulation/ApduServiceInfo.java2
-rw-r--r--core/java/android/os/AsyncResult.java3
-rw-r--r--core/java/android/os/AsyncTask.java2
-rw-r--r--core/java/android/os/BaseBundle.java2
-rw-r--r--core/java/android/os/BatteryManager.java2
-rw-r--r--core/java/android/os/BatteryStats.java68
-rw-r--r--core/java/android/os/BatteryStatsManager.java118
-rw-r--r--core/java/android/os/Binder.java2
-rw-r--r--core/java/android/os/BinderProxy.java10
-rw-r--r--core/java/android/os/Broadcaster.java2
-rwxr-xr-xcore/java/android/os/Build.java2
-rw-r--r--core/java/android/os/Bundle.java2
-rw-r--r--core/java/android/os/CancellationSignal.java4
-rw-r--r--core/java/android/os/Debug.java33
-rw-r--r--core/java/android/os/DropBoxManager.java2
-rw-r--r--core/java/android/os/Environment.java20
-rw-r--r--core/java/android/os/FileObserver.java2
-rw-r--r--core/java/android/os/FileUtils.java2
-rw-r--r--core/java/android/os/Handler.java2
-rw-r--r--core/java/android/os/HwBinder.java2
-rw-r--r--core/java/android/os/HwParcel.java2
-rw-r--r--core/java/android/os/HwRemoteBinder.java3
-rw-r--r--core/java/android/os/IBinder.java10
-rw-r--r--core/java/android/os/IVibratorService.aidl1
-rw-r--r--core/java/android/os/LocaleList.java2
-rw-r--r--core/java/android/os/Looper.java2
-rw-r--r--core/java/android/os/MemoryFile.java2
-rw-r--r--core/java/android/os/Message.java2
-rw-r--r--core/java/android/os/MessageQueue.java3
-rw-r--r--core/java/android/os/Parcel.java25
-rw-r--r--core/java/android/os/ParcelFileDescriptor.java2
-rw-r--r--core/java/android/os/ParcelUuid.java2
-rw-r--r--core/java/android/os/ParcelableParcel.java2
-rw-r--r--core/java/android/os/PerformanceCollector.java3
-rw-r--r--core/java/android/os/PowerManager.java71
-rw-r--r--core/java/android/os/Process.java24
-rw-r--r--core/java/android/os/RecoverySystem.java2
-rw-r--r--core/java/android/os/Registrant.java4
-rw-r--r--core/java/android/os/RegistrantList.java2
-rw-r--r--core/java/android/os/RemoteCallback.java3
-rw-r--r--core/java/android/os/RemoteCallbackList.java2
-rw-r--r--core/java/android/os/SELinux.java2
-rw-r--r--core/java/android/os/ServiceManager.java4
-rw-r--r--core/java/android/os/ServiceManagerNative.java2
-rw-r--r--core/java/android/os/SharedMemory.java2
-rw-r--r--core/java/android/os/ShellCommand.java2
-rw-r--r--core/java/android/os/StatFs.java2
-rw-r--r--core/java/android/os/StrictMode.java2
-rw-r--r--core/java/android/os/SystemClock.java2
-rw-r--r--core/java/android/os/SystemProperties.java2
-rw-r--r--core/java/android/os/SystemService.java3
-rw-r--r--core/java/android/os/SystemVibrator.java16
-rw-r--r--core/java/android/os/TelephonyServiceManager.java138
-rw-r--r--core/java/android/os/Trace.java58
-rw-r--r--core/java/android/os/UEventObserver.java2
-rw-r--r--core/java/android/os/UpdateLock.java2
-rw-r--r--core/java/android/os/UserHandle.java2
-rw-r--r--core/java/android/os/UserManager.java27
-rw-r--r--core/java/android/os/VibrationEffect.java3
-rw-r--r--core/java/android/os/Vibrator.java21
-rw-r--r--core/java/android/os/WorkSource.java3
-rw-r--r--core/java/android/os/ZygoteProcess.java62
-rw-r--r--core/java/android/os/connectivity/WifiBatteryStats.java9
-rw-r--r--core/java/android/os/health/HealthStatsParceler.java3
-rw-r--r--core/java/android/os/health/SystemHealthManager.java3
-rw-r--r--core/java/android/os/incremental/IIncrementalManager.aidl101
-rw-r--r--core/java/android/os/incremental/IIncrementalManagerNative.aidl104
-rw-r--r--core/java/android/os/incremental/IIncrementalServiceProxy.aidl37
-rw-r--r--core/java/android/os/incremental/IncrementalFileStorages.java11
-rw-r--r--core/java/android/os/incremental/IncrementalManager.java85
-rw-r--r--core/java/android/os/incremental/IncrementalStorage.java17
-rw-r--r--core/java/android/os/storage/CrateInfo.aidl (renamed from core/java/android/util/StatsEvent.aidl)14
-rw-r--r--core/java/android/os/storage/CrateInfo.java282
-rw-r--r--core/java/android/os/storage/DiskInfo.java2
-rw-r--r--core/java/android/os/storage/StorageEventListener.java2
-rw-r--r--core/java/android/os/storage/StorageManager.java41
-rw-r--r--core/java/android/os/storage/StorageManagerInternal.java9
-rw-r--r--core/java/android/os/storage/StorageVolume.java48
-rw-r--r--core/java/android/os/storage/VolumeInfo.java2
-rw-r--r--core/java/android/os/storage/VolumeRecord.java27
-rw-r--r--core/java/android/permission/PermissionControllerService.java4
-rw-r--r--core/java/android/preference/DialogPreference.java2
-rw-r--r--core/java/android/preference/EditTextPreference.java2
-rw-r--r--core/java/android/preference/ListPreference.java2
-rw-r--r--core/java/android/preference/Preference.java2
-rw-r--r--core/java/android/preference/PreferenceActivity.java2
-rw-r--r--core/java/android/preference/PreferenceFragment.java2
-rw-r--r--core/java/android/preference/PreferenceGroupAdapter.java2
-rw-r--r--core/java/android/preference/PreferenceManager.java2
-rw-r--r--core/java/android/preference/PreferenceScreen.java2
-rw-r--r--core/java/android/preference/RingtonePreference.java2
-rw-r--r--core/java/android/preference/SeekBarDialogPreference.java2
-rw-r--r--core/java/android/preference/SeekBarPreference.java2
-rw-r--r--core/java/android/preference/SeekBarVolumizer.java2
-rw-r--r--core/java/android/preference/SwitchPreference.java2
-rw-r--r--core/java/android/preference/TwoStatePreference.java2
-rw-r--r--core/java/android/preference/VolumePreference.java2
-rw-r--r--core/java/android/print/PrintDocumentAdapter.java2
-rw-r--r--core/java/android/print/PrintJobInfo.java2
-rw-r--r--core/java/android/print/PrintManager.java2
-rw-r--r--core/java/android/print/PrinterId.java2
-rw-r--r--core/java/android/provider/BaseColumns.java4
-rw-r--r--core/java/android/provider/Browser.java6
-rw-r--r--core/java/android/provider/BrowserContract.java2
-rw-r--r--core/java/android/provider/CalendarContract.java2
-rw-r--r--core/java/android/provider/CallLog.java2
-rw-r--r--core/java/android/provider/ContactsContract.java65
-rw-r--r--core/java/android/provider/DeviceConfig.java130
-rw-r--r--core/java/android/provider/MediaStore.java905
-rw-r--r--core/java/android/provider/Settings.java107
-rw-r--r--core/java/android/provider/Telephony.java14
-rw-r--r--core/java/android/se/omapi/SEService.java26
-rw-r--r--core/java/android/security/keymaster/KeymasterDefs.java1
-rw-r--r--core/java/android/service/autofill/FillRequest.java107
-rw-r--r--core/java/android/service/autofill/FillResponse.java40
-rw-r--r--core/java/android/service/controls/BooleanAction.java19
-rw-r--r--core/java/android/service/controls/Control.java20
-rw-r--r--core/java/android/service/controls/ControlAction.java58
-rw-r--r--core/java/android/service/controls/ControlButton.java18
-rw-r--r--core/java/android/service/controls/ControlState.java219
-rw-r--r--core/java/android/service/controls/ControlTemplate.java28
-rw-r--r--core/java/android/service/controls/ControlsProviderService.java147
-rw-r--r--core/java/android/service/controls/DiscreteToggleTemplate.java23
-rw-r--r--core/java/android/service/controls/FloatAction.java18
-rw-r--r--core/java/android/service/controls/RangeTemplate.java41
-rw-r--r--core/java/android/service/controls/ThumbnailTemplate.java24
-rw-r--r--core/java/android/service/controls/ToggleTemplate.java19
-rw-r--r--core/java/android/service/dataloader/DataLoaderService.java307
-rw-r--r--core/java/android/service/dreams/Sandman.java11
-rw-r--r--core/java/android/service/notification/Adjustment.java7
-rw-r--r--core/java/android/service/notification/NotificationListenerService.java3
-rw-r--r--core/java/android/service/quicksettings/TileService.java5
-rw-r--r--core/java/android/service/sms/FinancialSmsService.java104
-rw-r--r--core/java/android/service/textclassifier/TextClassifierService.java25
-rw-r--r--core/java/android/service/voice/VoiceInteractionSession.java1
-rw-r--r--core/java/android/service/wallpaper/WallpaperService.java1
-rw-r--r--core/java/android/telephony/CellBroadcastIntents.java13
-rw-r--r--core/java/android/telephony/PhoneStateListener.java84
-rw-r--r--core/java/android/telephony/TelephonyRegistryManager.java64
-rw-r--r--core/java/android/text/AlteredCharSequence.java4
-rw-r--r--core/java/android/text/format/DateUtils.java6
-rw-r--r--core/java/android/util/CloseGuard.java145
-rw-r--r--core/java/android/util/FeatureFlagUtils.java1
-rw-r--r--core/java/android/util/LongArrayQueue.java20
-rw-r--r--core/java/android/util/SparseSetArray.java14
-rw-r--r--core/java/android/util/StatsLog.java21
-rw-r--r--core/java/android/util/apk/VerityBuilder.java53
-rw-r--r--core/java/android/view/Choreographer.java11
-rw-r--r--core/java/android/view/ContextThemeWrapper.java2
-rw-r--r--core/java/android/view/Display.java11
-rw-r--r--core/java/android/view/DisplayAdjustments.java2
-rw-r--r--core/java/android/view/DisplayCutout.java4
-rw-r--r--core/java/android/view/DisplayEventReceiver.java2
-rw-r--r--core/java/android/view/DisplayInfo.java2
-rw-r--r--core/java/android/view/DisplayListCanvas.java2
-rw-r--r--core/java/android/view/DragEvent.java2
-rw-r--r--core/java/android/view/FrameMetrics.java2
-rw-r--r--core/java/android/view/FrameMetricsObserver.java61
-rw-r--r--core/java/android/view/GestureDetector.java2
-rw-r--r--core/java/android/view/GhostView.java2
-rw-r--r--core/java/android/view/IWindowManager.aidl12
-rw-r--r--core/java/android/view/InputChannel.java2
-rw-r--r--core/java/android/view/InputDevice.java2
-rw-r--r--core/java/android/view/InputEvent.java2
-rw-r--r--core/java/android/view/InputEventConsistencyVerifier.java2
-rw-r--r--core/java/android/view/InputEventReceiver.java2
-rw-r--r--core/java/android/view/InputEventSender.java2
-rw-r--r--core/java/android/view/InputFilter.java2
-rw-r--r--core/java/android/view/InputQueue.java2
-rw-r--r--core/java/android/view/InsetsAnimationControlImpl.java83
-rw-r--r--core/java/android/view/InsetsController.java163
-rw-r--r--core/java/android/view/KeyCharacterMap.java2
-rw-r--r--core/java/android/view/KeyEvent.java2
-rw-r--r--core/java/android/view/LayoutInflater.java5
-rw-r--r--core/java/android/view/MotionEvent.java2
-rw-r--r--core/java/android/view/NotificationHeaderView.java2
-rw-r--r--core/java/android/view/PointerIcon.java2
-rw-r--r--core/java/android/view/RemoteAnimationAdapter.java2
-rw-r--r--core/java/android/view/RemoteAnimationDefinition.java2
-rw-r--r--core/java/android/view/RemoteAnimationTarget.java2
-rw-r--r--core/java/android/view/RenderNodeAnimator.java2
-rw-r--r--core/java/android/view/ScaleGestureDetector.java2
-rw-r--r--core/java/android/view/Surface.java2
-rw-r--r--core/java/android/view/SurfaceControl.java90
-rw-r--r--core/java/android/view/SurfaceSession.java2
-rw-r--r--core/java/android/view/SurfaceView.java2
-rw-r--r--core/java/android/view/TextureView.java2
-rw-r--r--core/java/android/view/TouchDelegate.java2
-rw-r--r--core/java/android/view/VelocityTracker.java2
-rw-r--r--core/java/android/view/View.java70
-rw-r--r--core/java/android/view/ViewConfiguration.java2
-rw-r--r--core/java/android/view/ViewDebug.java2
-rw-r--r--core/java/android/view/ViewGroup.java19
-rw-r--r--core/java/android/view/ViewHierarchyEncoder.java2
-rw-r--r--core/java/android/view/ViewOverlay.java2
-rw-r--r--core/java/android/view/ViewRootImpl.java116
-rw-r--r--core/java/android/view/ViewTreeObserver.java2
-rw-r--r--core/java/android/view/Window.java73
-rw-r--r--core/java/android/view/WindowAnimationFrameStats.java2
-rw-r--r--core/java/android/view/WindowContentFrameStats.java2
-rw-r--r--core/java/android/view/WindowInsets.java43
-rw-r--r--core/java/android/view/WindowInsetsAnimationCallback.java276
-rw-r--r--core/java/android/view/WindowInsetsAnimationControlListener.java8
-rw-r--r--core/java/android/view/WindowInsetsAnimationController.java96
-rw-r--r--core/java/android/view/WindowInsetsAnimationListener.java122
-rw-r--r--core/java/android/view/WindowInsetsController.java40
-rw-r--r--core/java/android/view/WindowManager.java289
-rw-r--r--core/java/android/view/WindowManagerGlobal.java2
-rw-r--r--core/java/android/view/WindowManagerImpl.java2
-rw-r--r--core/java/android/view/accessibility/AccessibilityCache.java58
-rw-r--r--core/java/android/view/accessibility/AccessibilityEvent.java2
-rw-r--r--core/java/android/view/accessibility/AccessibilityInteractionClient.java39
-rw-r--r--core/java/android/view/accessibility/AccessibilityManager.java53
-rw-r--r--core/java/android/view/accessibility/AccessibilityNodeInfo.java2
-rw-r--r--core/java/android/view/accessibility/AccessibilityRecord.java2
-rw-r--r--core/java/android/view/accessibility/AccessibilityWindowInfo.java29
-rw-r--r--core/java/android/view/accessibility/CaptioningManager.java2
-rw-r--r--core/java/android/view/accessibility/IAccessibilityManager.aidl2
-rw-r--r--core/java/android/view/animation/Animation.java2
-rw-r--r--core/java/android/view/animation/AnimationUtils.java2
-rw-r--r--core/java/android/view/animation/Transformation.java2
-rw-r--r--core/java/android/view/animation/TranslateAnimation.java2
-rw-r--r--core/java/android/view/animation/TranslateYAnimation.java2
-rw-r--r--core/java/android/view/inline/InlineContentView.java5
-rw-r--r--core/java/android/view/inputmethod/InlineSuggestion.java2
-rw-r--r--core/java/android/view/inputmethod/InputMethod.java19
-rw-r--r--core/java/android/view/inputmethod/InputMethodInfo.java2
-rw-r--r--core/java/android/view/inputmethod/InputMethodManager.java4
-rw-r--r--core/java/android/view/inputmethod/InputMethodSubtypeArray.java2
-rw-r--r--core/java/android/view/textclassifier/ConfigParser.java264
-rw-r--r--core/java/android/view/textclassifier/ConversationAction.java9
-rw-r--r--core/java/android/view/textclassifier/ConversationActions.java13
-rw-r--r--core/java/android/view/textclassifier/EntityConfidence.java7
-rw-r--r--core/java/android/view/textclassifier/GenerateLinksLogger.java7
-rw-r--r--core/java/android/view/textclassifier/ModelFileManager.java21
-rw-r--r--core/java/android/view/textclassifier/SelectionEvent.java14
-rw-r--r--core/java/android/view/textclassifier/SelectionSessionLogger.java13
-rw-r--r--core/java/android/view/textclassifier/SystemTextClassifier.java22
-rw-r--r--core/java/android/view/textclassifier/TextClassification.java4
-rw-r--r--core/java/android/view/textclassifier/TextClassificationConstants.java187
-rw-r--r--core/java/android/view/textclassifier/TextClassificationContext.java11
-rw-r--r--core/java/android/view/textclassifier/TextClassificationManager.java73
-rw-r--r--core/java/android/view/textclassifier/TextClassificationSession.java9
-rw-r--r--core/java/android/view/textclassifier/TextClassificationSessionId.java5
-rw-r--r--core/java/android/view/textclassifier/TextClassifier.java17
-rw-r--r--core/java/android/view/textclassifier/TextClassifierEvent.java8
-rw-r--r--core/java/android/view/textclassifier/TextClassifierEventTronLogger.java6
-rw-r--r--core/java/android/view/textclassifier/TextClassifierImpl.java16
-rw-r--r--core/java/android/view/textclassifier/TextLinks.java11
-rw-r--r--core/java/android/view/textclassifier/TextLinksParams.java7
-rw-r--r--core/java/android/view/textclassifier/TextSelection.java3
-rw-r--r--core/java/android/view/textclassifier/intent/LabeledIntent.java11
-rw-r--r--core/java/android/view/textclassifier/intent/TemplateClassificationIntentFactory.java5
-rw-r--r--core/java/android/view/textclassifier/logging/SmartSelectionEventTracker.java12
-rw-r--r--core/java/android/view/textservice/SpellCheckerSession.java2
-rw-r--r--core/java/android/view/textservice/TextServicesManager.java2
-rw-r--r--core/java/android/webkit/CacheManager.java2
-rw-r--r--core/java/android/webkit/ConsoleMessage.java2
-rw-r--r--core/java/android/webkit/JsResult.java2
-rw-r--r--core/java/android/webkit/PluginData.java3
-rw-r--r--core/java/android/webkit/URLUtil.java2
-rw-r--r--core/java/android/webkit/UrlInterceptHandler.java3
-rw-r--r--core/java/android/webkit/UrlInterceptRegistry.java4
-rw-r--r--core/java/android/webkit/WebResourceResponse.java2
-rw-r--r--core/java/android/webkit/WebSettings.java2
-rw-r--r--core/java/android/webkit/WebSyncManager.java2
-rw-r--r--core/java/android/webkit/WebView.java2
-rw-r--r--core/java/android/webkit/WebViewDelegate.java2
-rw-r--r--core/java/android/webkit/WebViewFactory.java2
-rw-r--r--core/java/android/webkit/WebViewProviderInfo.java2
-rw-r--r--core/java/android/webkit/WebViewProviderResponse.java2
-rw-r--r--core/java/android/webkit/WebViewUpdateService.java2
-rw-r--r--core/java/android/widget/AbsListView.java2
-rw-r--r--core/java/android/widget/AbsSeekBar.java2
-rw-r--r--core/java/android/widget/ActionMenuPresenter.java2
-rw-r--r--core/java/android/widget/ActionMenuView.java2
-rw-r--r--core/java/android/widget/ActivityChooserModel.java2
-rw-r--r--core/java/android/widget/ActivityChooserView.java2
-rw-r--r--core/java/android/widget/AdapterView.java2
-rw-r--r--core/java/android/widget/AnalogClock.java2
-rw-r--r--core/java/android/widget/ArrayAdapter.java2
-rw-r--r--core/java/android/widget/AutoCompleteTextView.java2
-rw-r--r--core/java/android/widget/BaseAdapter.java2
-rw-r--r--core/java/android/widget/CalendarView.java2
-rw-r--r--core/java/android/widget/CheckedTextView.java2
-rw-r--r--core/java/android/widget/RadioButton.java29
-rw-r--r--core/java/android/widget/RadioGroup.java51
-rw-r--r--core/java/android/widget/RemoteViews.java1
-rw-r--r--core/java/android/widget/Switch.java3
-rw-r--r--core/java/android/widget/Toast.java1
-rw-r--r--core/java/android/widget/ToggleButton.java3
-rw-r--r--core/java/com/android/ims/internal/uce/common/CapInfo.aidl (renamed from telephony/java/com/android/ims/internal/uce/common/CapInfo.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/common/CapInfo.java (renamed from telephony/java/com/android/ims/internal/uce/common/CapInfo.java)0
-rw-r--r--core/java/com/android/ims/internal/uce/common/StatusCode.aidl (renamed from telephony/java/com/android/ims/internal/uce/common/StatusCode.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/common/StatusCode.java (renamed from telephony/java/com/android/ims/internal/uce/common/StatusCode.java)0
-rw-r--r--core/java/com/android/ims/internal/uce/common/UceLong.aidl (renamed from telephony/java/com/android/ims/internal/uce/common/UceLong.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/common/UceLong.java (renamed from telephony/java/com/android/ims/internal/uce/common/UceLong.java)0
-rw-r--r--core/java/com/android/ims/internal/uce/options/IOptionsListener.aidl (renamed from telephony/java/com/android/ims/internal/uce/options/IOptionsListener.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/options/IOptionsService.aidl (renamed from telephony/java/com/android/ims/internal/uce/options/IOptionsService.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/options/OptionsCapInfo.aidl (renamed from telephony/java/com/android/ims/internal/uce/options/OptionsCapInfo.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/options/OptionsCapInfo.java (renamed from telephony/java/com/android/ims/internal/uce/options/OptionsCapInfo.java)0
-rw-r--r--core/java/com/android/ims/internal/uce/options/OptionsCmdId.aidl (renamed from telephony/java/com/android/ims/internal/uce/options/OptionsCmdId.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/options/OptionsCmdId.java (renamed from telephony/java/com/android/ims/internal/uce/options/OptionsCmdId.java)0
-rw-r--r--core/java/com/android/ims/internal/uce/options/OptionsCmdStatus.aidl (renamed from telephony/java/com/android/ims/internal/uce/options/OptionsCmdStatus.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/options/OptionsCmdStatus.java (renamed from telephony/java/com/android/ims/internal/uce/options/OptionsCmdStatus.java)0
-rw-r--r--core/java/com/android/ims/internal/uce/options/OptionsSipResponse.aidl (renamed from telephony/java/com/android/ims/internal/uce/options/OptionsSipResponse.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/options/OptionsSipResponse.java (renamed from telephony/java/com/android/ims/internal/uce/options/OptionsSipResponse.java)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/IPresenceListener.aidl (renamed from telephony/java/com/android/ims/internal/uce/presence/IPresenceListener.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/IPresenceService.aidl (renamed from telephony/java/com/android/ims/internal/uce/presence/IPresenceService.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresCapInfo.aidl (renamed from telephony/java/com/android/ims/internal/uce/presence/PresCapInfo.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresCapInfo.java (renamed from telephony/java/com/android/ims/internal/uce/presence/PresCapInfo.java)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresCmdId.aidl (renamed from telephony/java/com/android/ims/internal/uce/presence/PresCmdId.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresCmdId.java (renamed from telephony/java/com/android/ims/internal/uce/presence/PresCmdId.java)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresCmdStatus.aidl (renamed from telephony/java/com/android/ims/internal/uce/presence/PresCmdStatus.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresCmdStatus.java (renamed from telephony/java/com/android/ims/internal/uce/presence/PresCmdStatus.java)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresPublishTriggerType.aidl (renamed from telephony/java/com/android/ims/internal/uce/presence/PresPublishTriggerType.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresPublishTriggerType.java (renamed from telephony/java/com/android/ims/internal/uce/presence/PresPublishTriggerType.java)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresResInfo.aidl (renamed from telephony/java/com/android/ims/internal/uce/presence/PresResInfo.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresResInfo.java (renamed from telephony/java/com/android/ims/internal/uce/presence/PresResInfo.java)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresResInstanceInfo.aidl (renamed from telephony/java/com/android/ims/internal/uce/presence/PresResInstanceInfo.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresResInstanceInfo.java (renamed from telephony/java/com/android/ims/internal/uce/presence/PresResInstanceInfo.java)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresRlmiInfo.aidl (renamed from telephony/java/com/android/ims/internal/uce/presence/PresRlmiInfo.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresRlmiInfo.java (renamed from telephony/java/com/android/ims/internal/uce/presence/PresRlmiInfo.java)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresServiceInfo.aidl (renamed from telephony/java/com/android/ims/internal/uce/presence/PresServiceInfo.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresServiceInfo.java (renamed from telephony/java/com/android/ims/internal/uce/presence/PresServiceInfo.java)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresSipResponse.aidl (renamed from telephony/java/com/android/ims/internal/uce/presence/PresSipResponse.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresSipResponse.java (renamed from telephony/java/com/android/ims/internal/uce/presence/PresSipResponse.java)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresSubscriptionState.aidl (renamed from telephony/java/com/android/ims/internal/uce/presence/PresSubscriptionState.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresSubscriptionState.java (renamed from telephony/java/com/android/ims/internal/uce/presence/PresSubscriptionState.java)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresTupleInfo.aidl (renamed from telephony/java/com/android/ims/internal/uce/presence/PresTupleInfo.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/presence/PresTupleInfo.java (renamed from telephony/java/com/android/ims/internal/uce/presence/PresTupleInfo.java)0
-rw-r--r--core/java/com/android/ims/internal/uce/uceservice/IUceListener.aidl (renamed from telephony/java/com/android/ims/internal/uce/uceservice/IUceListener.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/uceservice/IUceService.aidl (renamed from telephony/java/com/android/ims/internal/uce/uceservice/IUceService.aidl)0
-rw-r--r--core/java/com/android/ims/internal/uce/uceservice/ImsUceManager.java (renamed from telephony/java/com/android/ims/internal/uce/uceservice/ImsUceManager.java)0
-rw-r--r--core/java/com/android/ims/internal/uce/uceservice/UceServiceBase.java (renamed from telephony/java/com/android/ims/internal/uce/uceservice/UceServiceBase.java)0
-rw-r--r--core/java/com/android/internal/accessibility/AccessibilityShortcutController.java133
-rw-r--r--core/java/com/android/internal/app/AbstractMultiProfilePagerAdapter.java163
-rw-r--r--core/java/com/android/internal/app/AbstractResolverComparator.java1
-rw-r--r--core/java/com/android/internal/app/ChooserActivity.java500
-rw-r--r--core/java/com/android/internal/app/ChooserListAdapter.java27
-rw-r--r--core/java/com/android/internal/app/ChooserMultiProfilePagerAdapter.java137
-rw-r--r--core/java/com/android/internal/app/ChooserStackedAppDialogFragment.java86
-rw-r--r--core/java/com/android/internal/app/ISoundTriggerService.aidl13
-rw-r--r--core/java/com/android/internal/app/ResolverActivity.java341
-rw-r--r--core/java/com/android/internal/app/ResolverListAdapter.java16
-rw-r--r--core/java/com/android/internal/app/ResolverListController.java16
-rw-r--r--core/java/com/android/internal/app/ResolverMultiProfilePagerAdapter.java122
-rw-r--r--core/java/com/android/internal/app/ResolverTargetActionsDialogFragment.java95
-rw-r--r--core/java/com/android/internal/app/WrapHeightViewPager.java71
-rw-r--r--core/java/com/android/internal/app/chooser/DisplayResolveInfo.java11
-rw-r--r--core/java/com/android/internal/app/chooser/MultiDisplayResolveInfo.java55
-rw-r--r--core/java/com/android/internal/content/FileSystemProvider.java6
-rw-r--r--core/java/com/android/internal/content/NativeLibraryHelper.java18
-rw-r--r--core/java/com/android/internal/content/PackageMonitor.java4
-rw-r--r--core/java/com/android/internal/infra/AndroidFuture.java11
-rw-r--r--core/java/com/android/internal/infra/ServiceConnector.java6
-rw-r--r--core/java/com/android/internal/infra/TEST_MAPPING16
-rw-r--r--core/java/com/android/internal/infra/WhitelistHelper.java9
-rw-r--r--core/java/com/android/internal/os/BatteryStatsImpl.java5
-rw-r--r--core/java/com/android/internal/os/FuseAppLoop.java11
-rw-r--r--core/java/com/android/internal/os/RuntimeInit.java5
-rw-r--r--core/java/com/android/internal/os/WrapperInit.java12
-rw-r--r--core/java/com/android/internal/os/Zygote.java27
-rw-r--r--core/java/com/android/internal/os/ZygoteArguments.java24
-rw-r--r--core/java/com/android/internal/os/ZygoteConnection.java3
-rw-r--r--core/java/com/android/internal/os/ZygoteInit.java14
-rw-r--r--core/java/com/android/internal/policy/DecorView.java58
-rw-r--r--core/java/com/android/internal/policy/PhoneWindow.java12
-rw-r--r--core/java/com/android/internal/telephony/IPhoneStateListener.aidl1
-rw-r--r--core/java/com/android/internal/telephony/ITelephonyRegistry.aidl14
-rw-r--r--core/java/com/android/internal/util/FileRotator.java7
-rw-r--r--core/java/com/android/internal/util/ObjectUtils.java3
-rw-r--r--core/java/com/android/internal/util/ScreenRecordHelper.java9
-rw-r--r--core/java/com/android/internal/util/ScreenshotHelper.java16
-rwxr-xr-xcore/java/com/android/internal/util/function/pooled/PooledLambdaImpl.java3
-rw-r--r--core/java/com/android/internal/view/FloatingActionMode.java12
-rw-r--r--core/java/com/android/internal/view/IInputMethod.aidl6
-rw-r--r--core/java/com/android/internal/view/menu/StandardMenuPopup.java4
-rw-r--r--core/java/com/android/internal/widget/FloatingToolbar.java26
-rw-r--r--core/java/com/android/internal/widget/LockscreenCredential.java3
-rw-r--r--core/java/com/android/server/SystemConfig.java30
-rw-r--r--core/jni/Android.bp9
-rw-r--r--core/jni/AndroidRuntime.cpp8
-rw-r--r--core/jni/android/graphics/AnimatedImageDrawable.cpp1
-rw-r--r--core/jni/android/graphics/BitmapFactory.cpp5
-rw-r--r--core/jni/android/graphics/ImageDecoder.cpp225
-rw-r--r--core/jni/android/graphics/ImageDecoder.h40
-rw-r--r--core/jni/android/graphics/apex/jni_runtime.cpp4
-rw-r--r--core/jni/android_graphics_HardwareRendererObserver.cpp130
-rw-r--r--core/jni/android_graphics_HardwareRendererObserver.h75
-rw-r--r--core/jni/android_hardware_SoundTrigger.cpp967
-rw-r--r--core/jni/android_media_AudioDeviceAddress.cpp53
-rw-r--r--core/jni/android_media_AudioDeviceAddress.h (renamed from libs/services/include/android/util/StatsEvent.h)32
-rw-r--r--core/jni/android_media_AudioRecord.cpp2
-rw-r--r--core/jni/android_media_AudioSystem.cpp63
-rw-r--r--core/jni/android_media_AudioTrack.cpp2
-rw-r--r--core/jni/android_os_Debug.cpp61
-rw-r--r--core/jni/android_os_Trace.cpp12
-rw-r--r--core/jni/android_service_DataLoaderService.cpp83
-rw-r--r--core/jni/android_view_FrameMetricsObserver.cpp149
-rw-r--r--core/jni/android_view_FrameMetricsObserver.h71
-rw-r--r--core/jni/android_view_ThreadedRenderer.cpp29
-rw-r--r--core/jni/com_android_internal_os_Zygote.cpp319
-rw-r--r--core/jni/fd_utils.cpp6
-rw-r--r--core/proto/android/app/settings_enums.proto47
-rw-r--r--core/proto/android/providers/settings/global.proto3
-rw-r--r--core/proto/android/providers/settings/secure.proto9
-rw-r--r--core/proto/android/server/windowmanagerservice.proto1
-rw-r--r--core/proto/android/stats/devicepolicy/device_policy_enums.proto1
-rw-r--r--core/proto/android/stats/docsui/docsui_enums.proto1
-rw-r--r--core/proto/android/util/quotatracker.proto219
-rw-r--r--core/proto/android/view/windowlayoutparams.proto10
-rw-r--r--core/res/AndroidManifest.xml46
-rw-r--r--core/res/res/layout/chooser_grid.xml20
-rw-r--r--core/res/res/layout/chooser_grid_preview_text.xml3
-rw-r--r--core/res/res/layout/chooser_list_per_profile.xml27
-rw-r--r--core/res/res/layout/resolver_list.xml16
-rw-r--r--core/res/res/layout/resolver_list_per_profile.xml31
-rw-r--r--core/res/res/layout/resolver_list_with_default.xml16
-rw-r--r--core/res/res/values-mcc510-mnc08/config.xml2
-rw-r--r--core/res/res/values-mcc510-mnc89/config.xml2
-rw-r--r--core/res/res/values-sw600dp/bools.xml1
-rw-r--r--core/res/res/values/bools.xml1
-rw-r--r--core/res/res/values/config.xml137
-rw-r--r--core/res/res/values/dimens.xml4
-rw-r--r--core/res/res/values/strings.xml76
-rw-r--r--core/res/res/values/symbols.xml33
-rw-r--r--core/res/res/xml/config_user_types.xml98
-rw-r--r--core/tests/bluetoothtests/src/android/bluetooth/BluetoothTestUtils.java2
-rw-r--r--core/tests/coretests/Android.bp1
-rw-r--r--core/tests/coretests/src/android/app/activity/ActivityManagerTest.java122
-rw-r--r--core/tests/coretests/src/android/provider/DeviceConfigTest.java60
-rw-r--r--core/tests/coretests/src/android/util/CloseGuardTest.java98
-rw-r--r--core/tests/coretests/src/android/util/StatsEventTest.java7
-rw-r--r--core/tests/coretests/src/android/view/InsetsAnimationControlImplTest.java38
-rw-r--r--core/tests/coretests/src/android/view/InsetsControllerTest.java9
-rw-r--r--core/tests/coretests/src/android/view/ViewRootImplTest.java92
-rw-r--r--core/tests/coretests/src/android/view/accessibility/AccessibilityCacheTest.java16
-rw-r--r--core/tests/coretests/src/android/view/textclassifier/ConfigParserTest.java138
-rw-r--r--core/tests/coretests/src/android/view/textclassifier/TextClassificationConstantsTest.java321
-rw-r--r--core/tests/coretests/src/android/view/textclassifier/TextClassificationManagerTest.java2
-rw-r--r--core/tests/coretests/src/android/view/textclassifier/TextClassifierTest.java2
-rw-r--r--core/tests/coretests/src/com/android/internal/accessibility/AccessibilityShortcutControllerTest.java89
-rw-r--r--core/tests/coretests/src/com/android/internal/app/ChooserActivityTest.java16
-rw-r--r--core/tests/coretests/src/com/android/internal/app/ChooserWrapperActivity.java5
-rw-r--r--core/tests/coretests/src/com/android/internal/app/ResolverActivityTest.java21
-rw-r--r--core/tests/coretests/src/com/android/internal/app/ResolverListControllerTest.java4
-rw-r--r--core/tests/coretests/src/com/android/internal/app/ResolverWrapperActivity.java13
-rw-r--r--core/tests/coretests/src/com/android/internal/infra/AndroidFutureTest.java152
-rw-r--r--core/tests/screenshothelpertests/src/com/android/internal/util/ScreenshotHelperTest.java15
-rw-r--r--data/etc/Android.bp6
-rw-r--r--data/etc/CleanSpec.mk4
-rw-r--r--data/etc/com.android.settings.xml1
-rw-r--r--data/etc/platform.xml1
-rw-r--r--data/etc/privapp-permissions-platform.xml11
-rw-r--r--data/etc/services.core.protolog.json84
-rw-r--r--framework-jarjar-rules.txt2
-rw-r--r--graphics/java/android/graphics/HardwareRenderer.java18
-rw-r--r--graphics/java/android/graphics/HardwareRendererObserver.java103
-rw-r--r--graphics/java/android/graphics/ImageDecoder.java5
-rw-r--r--graphics/java/android/graphics/drawable/ColorDrawable.java2
-rw-r--r--graphics/java/android/graphics/drawable/Drawable.java2
-rw-r--r--graphics/java/android/graphics/drawable/DrawableContainer.java2
-rw-r--r--graphics/java/android/graphics/drawable/DrawableInflater.java8
-rw-r--r--graphics/java/android/graphics/drawable/DrawableWrapper.java2
-rw-r--r--graphics/java/android/graphics/drawable/GradientDrawable.java6
-rw-r--r--graphics/java/android/graphics/drawable/Icon.java2
-rw-r--r--graphics/java/android/graphics/drawable/InsetDrawable.java2
-rw-r--r--graphics/java/android/graphics/drawable/LayerDrawable.java2
-rw-r--r--graphics/java/android/graphics/drawable/NinePatchDrawable.java2
-rw-r--r--graphics/java/android/graphics/drawable/RippleDrawable.java2
-rw-r--r--graphics/java/android/graphics/drawable/RotateDrawable.java20
-rw-r--r--graphics/java/android/graphics/drawable/ScaleDrawable.java12
-rw-r--r--graphics/java/android/graphics/drawable/StateListDrawable.java2
-rw-r--r--graphics/java/android/graphics/drawable/TransitionDrawable.java2
-rw-r--r--graphics/java/android/graphics/drawable/VectorDrawable.java2
-rw-r--r--graphics/java/android/graphics/fonts/FontVariationAxis.java2
-rw-r--r--graphics/java/android/graphics/pdf/PdfRenderer.java4
-rw-r--r--jarjar_rules_hidl.txt1
-rw-r--r--keystore/java/android/security/Credentials.java5
-rw-r--r--keystore/java/android/security/GateKeeper.java2
-rw-r--r--keystore/java/android/security/KeyStore.java3
-rw-r--r--keystore/java/android/security/keystore/AndroidKeyStoreProvider.java2
-rw-r--r--keystore/java/android/security/keystore/AttestationUtils.java5
-rw-r--r--keystore/java/android/security/keystore/KeyGenParameterSpec.java2
-rw-r--r--libs/androidfw/LocaleDataTables.cpp2717
-rw-r--r--libs/hwui/Android.bp1
-rw-r--r--libs/hwui/hwui/Bitmap.cpp6
-rw-r--r--libs/hwui/hwui/Bitmap.h4
-rw-r--r--libs/hwui/hwui/ImageDecoder.cpp213
-rw-r--r--libs/hwui/hwui/ImageDecoder.h71
-rw-r--r--libs/hwui/pipeline/skia/RenderNodeDrawable.cpp13
-rw-r--r--libs/hwui/pipeline/skia/RenderNodeDrawable.h4
-rw-r--r--libs/hwui/pipeline/skia/SkiaPipeline.cpp165
-rw-r--r--libs/hwui/pipeline/skia/SkiaPipeline.h4
-rw-r--r--libs/services/Android.bp5
-rw-r--r--libs/services/src/util/StatsEvent.cpp58
-rw-r--r--location/java/android/location/Country.java2
-rw-r--r--location/java/android/location/CountryDetector.java6
-rw-r--r--location/java/android/location/CountryListener.java2
-rw-r--r--location/java/android/location/GeocoderParams.java2
-rw-r--r--location/java/android/location/Geofence.java2
-rw-r--r--location/java/android/location/Location.java2
-rw-r--r--location/java/android/location/LocationManager.java10
-rw-r--r--location/java/android/location/LocationRequest.java2
-rw-r--r--location/java/com/android/internal/location/GpsNetInitiatedHandler.java5
-rw-r--r--location/java/com/android/internal/location/ProviderRequest.java2
-rw-r--r--media/Android.bp73
-rw-r--r--media/apex/java/android/media/MediaParser.java91
-rw-r--r--media/java/android/media/AmrInputStream.java10
-rw-r--r--media/java/android/media/AsyncPlayer.java3
-rw-r--r--media/java/android/media/AudioAttributes.java16
-rw-r--r--media/java/android/media/AudioDeviceAddress.java34
-rw-r--r--media/java/android/media/AudioDeviceInfo.java4
-rw-r--r--media/java/android/media/AudioDevicePort.java3
-rw-r--r--media/java/android/media/AudioDevicePortConfig.java2
-rw-r--r--media/java/android/media/AudioFormat.java2
-rw-r--r--media/java/android/media/AudioGain.java2
-rw-r--r--media/java/android/media/AudioGainConfig.java2
-rw-r--r--media/java/android/media/AudioHandle.java2
-rw-r--r--media/java/android/media/AudioManager.java83
-rw-r--r--media/java/android/media/AudioMixPort.java2
-rw-r--r--media/java/android/media/AudioMixPortConfig.java2
-rw-r--r--media/java/android/media/AudioPatch.java2
-rw-r--r--media/java/android/media/AudioPort.java2
-rw-r--r--media/java/android/media/AudioPortConfig.java2
-rw-r--r--media/java/android/media/AudioPortEventHandler.java2
-rw-r--r--media/java/android/media/AudioRecord.java2
-rw-r--r--media/java/android/media/AudioRecordingConfiguration.java2
-rw-r--r--media/java/android/media/AudioSystem.java60
-rw-r--r--media/java/android/media/AudioTrack.java2
-rw-r--r--media/java/android/media/CamcorderProfile.java2
-rw-r--r--media/java/android/media/DecoderCapabilities.java5
-rw-r--r--media/java/android/media/EncoderCapabilities.java5
-rw-r--r--media/java/android/media/ExifInterface.java2
-rw-r--r--media/java/android/media/IAudioService.aidl7
-rw-r--r--media/java/android/media/Image.java7
-rw-r--r--media/java/android/media/JetPlayer.java2
-rw-r--r--media/java/android/media/MediaCodec.java2
-rw-r--r--media/java/android/media/MediaCodecInfo.java2
-rw-r--r--media/java/android/media/MediaDrm.java6
-rw-r--r--media/java/android/media/MediaFile.java2
-rw-r--r--media/java/android/media/MediaFormat.java30
-rw-r--r--media/java/android/media/MediaHTTPConnection.java3
-rw-r--r--media/java/android/media/MediaHTTPService.java2
-rw-r--r--media/java/android/media/MediaInserter.java2
-rw-r--r--media/java/android/media/MediaMetadata.java2
-rw-r--r--media/java/android/media/MediaMetadataRetriever.java2
-rw-r--r--media/java/android/media/MediaMetrics.java634
-rw-r--r--media/java/android/media/MediaMuxer.java3
-rw-r--r--media/java/android/media/MediaPlayer.java2
-rw-r--r--media/java/android/media/MediaRecorder.java2
-rw-r--r--media/java/android/media/MediaRoute2ProviderInfo.java5
-rw-r--r--media/java/android/media/MediaRouter.java2
-rw-r--r--media/java/android/media/MediaRouter2.java210
-rw-r--r--media/java/android/media/MediaRouter2Manager.java86
-rw-r--r--media/java/android/media/MediaScanner.java2
-rw-r--r--media/java/android/media/MediaScannerConnection.java3
-rw-r--r--media/java/android/media/Metadata.java2
-rw-r--r--media/java/android/media/MicrophoneInfo.java2
-rw-r--r--media/java/android/media/PlaybackParams.java2
-rw-r--r--media/java/android/media/RemoteControlClient.java2
-rw-r--r--media/java/android/media/RemoteController.java2
-rw-r--r--media/java/android/media/RemoteDisplay.java6
-rw-r--r--media/java/android/media/RemoteDisplayState.java2
-rw-r--r--media/java/android/media/Ringtone.java2
-rw-r--r--media/java/android/media/RingtoneManager.java4
-rw-r--r--media/java/android/media/RouteSessionController.java208
-rw-r--r--media/java/android/media/RouteSessionInfo.aidl19
-rw-r--r--media/java/android/media/RouteSessionInfo.java300
-rw-r--r--media/java/android/media/SubtitleController.java8
-rw-r--r--media/java/android/media/SubtitleTrack.java2
-rw-r--r--media/java/android/media/ThumbnailUtils.java15
-rw-r--r--media/java/android/media/TimedText.java7
-rw-r--r--media/java/android/media/ToneGenerator.java2
-rw-r--r--media/java/android/media/TtmlRenderer.java10
-rw-r--r--media/java/android/media/VolumeShaper.java3
-rw-r--r--media/java/android/media/WebVttRenderer.java2
-rw-r--r--media/java/android/media/audio/common/AudioChannelMask.aidl217
-rw-r--r--media/java/android/media/audio/common/AudioConfig.aidl36
-rw-r--r--media/java/android/media/audio/common/AudioFormat.aidl170
-rw-r--r--media/java/android/media/audio/common/AudioOffloadInfo.aidl44
-rw-r--r--media/java/android/media/audio/common/AudioStreamType.aidl44
-rw-r--r--media/java/android/media/audio/common/AudioUsage.aidl40
-rw-r--r--media/java/android/media/audiofx/AudioEffect.java2
-rw-r--r--media/java/android/media/audiofx/Visualizer.java2
-rw-r--r--media/java/android/media/audiopolicy/AudioMix.java2
-rw-r--r--media/java/android/media/audiopolicy/AudioMixingRule.java2
-rw-r--r--media/java/android/media/audiopolicy/AudioProductStrategy.java14
-rw-r--r--media/java/android/media/session/IOnMediaKeyEventDispatchedListener.aidl (renamed from media/java/android/media/session/ICallback.aidl)15
-rw-r--r--media/java/android/media/session/IOnMediaKeyEventSessionChangedListener.aidl28
-rw-r--r--media/java/android/media/session/ISessionManager.aidl11
-rw-r--r--media/java/android/media/session/MediaController.java4
-rw-r--r--media/java/android/media/session/MediaSession.java2
-rw-r--r--media/java/android/media/session/MediaSessionLegacyHelper.java3
-rw-r--r--media/java/android/media/session/MediaSessionManager.java255
-rw-r--r--media/java/android/media/soundtrigger/SoundTriggerManager.java96
-rw-r--r--media/java/android/media/soundtrigger_middleware/ConfidenceLevel.aidl35
-rw-r--r--media/java/android/media/soundtrigger_middleware/ISoundTriggerCallback.aidl47
-rw-r--r--media/java/android/media/soundtrigger_middleware/ISoundTriggerMiddlewareService.aidl48
-rw-r--r--media/java/android/media/soundtrigger_middleware/ISoundTriggerModule.aidl148
-rw-r--r--media/java/android/media/soundtrigger_middleware/ModelParameter.aidl38
-rw-r--r--media/java/android/media/soundtrigger_middleware/ModelParameterRange.aidl28
-rw-r--r--media/java/android/media/soundtrigger_middleware/Phrase.aidl34
-rw-r--r--media/java/android/media/soundtrigger_middleware/PhraseRecognitionEvent.aidl31
-rw-r--r--media/java/android/media/soundtrigger_middleware/PhraseRecognitionExtra.aidl35
-rw-r--r--media/java/android/media/soundtrigger_middleware/PhraseSoundModel.aidl32
-rw-r--r--media/java/android/media/soundtrigger_middleware/RecognitionConfig.aidl33
-rw-r--r--media/java/android/media/soundtrigger_middleware/RecognitionEvent.aidl51
-rw-r--r--media/java/android/media/soundtrigger_middleware/RecognitionMode.aidl32
-rw-r--r--media/java/android/media/soundtrigger_middleware/RecognitionStatus.aidl35
-rw-r--r--media/java/android/media/soundtrigger_middleware/SoundModel.aidl36
-rw-r--r--media/java/android/media/soundtrigger_middleware/SoundModelType.aidl30
-rw-r--r--media/java/android/media/soundtrigger_middleware/SoundTriggerModuleDescriptor.aidl31
-rw-r--r--media/java/android/media/soundtrigger_middleware/SoundTriggerModuleProperties.aidl53
-rw-r--r--media/java/android/media/soundtrigger_middleware/Status.aidl29
-rwxr-xr-x[-rw-r--r--]media/java/android/media/tv/ITvInputService.aidl1
-rwxr-xr-x[-rw-r--r--]media/java/android/media/tv/TvInputService.java30
-rw-r--r--media/java/android/media/tv/tuner/DvrSettings.java124
-rw-r--r--media/java/android/media/tv/tuner/Tuner.java4
-rw-r--r--media/java/android/media/tv/tuner/TunerConstants.java7
-rwxr-xr-xmedia/java/android/mtp/MtpDatabase.java85
-rw-r--r--media/java/android/mtp/MtpStorage.java6
-rw-r--r--media/jni/android_media_MediaCodec.cpp8
-rw-r--r--media/jni/android_media_MediaCodec.h4
-rw-r--r--media/jni/android_media_MediaExtractor.cpp2
-rw-r--r--media/jni/android_media_MediaMetricsJNI.cpp67
-rw-r--r--media/jni/android_media_MediaMetricsJNI.h4
-rw-r--r--media/jni/android_media_MediaPlayer.cpp4
-rw-r--r--media/jni/android_media_MediaRecorder.cpp4
-rw-r--r--media/jni/android_media_tv_Tuner.cpp89
-rw-r--r--media/jni/android_media_tv_Tuner.h7
-rw-r--r--media/jni/audioeffect/Android.bp1
-rw-r--r--media/jni/soundpool/StreamManager.cpp3
-rw-r--r--media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouter2Test.java116
-rw-r--r--media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouterManagerTest.java150
-rw-r--r--media/tests/MediaRouter/src/com/android/mediaroutertest/RouteSessionTest.java62
-rw-r--r--packages/CarSystemUI/Android.bp5
-rw-r--r--packages/CarSystemUI/CleanSpec.mk50
-rw-r--r--packages/CarSystemUI/src/com/android/systemui/CarSystemUIModule.java9
-rw-r--r--packages/CarSystemUI/src/com/android/systemui/car/CarDeviceProvisionedController.java37
-rw-r--r--packages/CarSystemUI/src/com/android/systemui/car/CarDeviceProvisionedControllerImpl.java116
-rw-r--r--packages/CarSystemUI/src/com/android/systemui/car/CarDeviceProvisionedListener.java36
-rw-r--r--packages/CarSystemUI/src/com/android/systemui/navigationbar/car/CarNavigationBar.java44
-rw-r--r--packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarShadeControllerImpl.java85
-rw-r--r--packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java127
-rw-r--r--packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBarModule.java10
-rw-r--r--packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarTrustAgentUnlockDialogHelper.java4
-rw-r--r--packages/CarSystemUI/src/com/android/systemui/statusbar/car/FullscreenUserSwitcher.java21
-rw-r--r--packages/CarSystemUI/src/com/android/systemui/statusbar/car/UserGridRecyclerView.java126
-rw-r--r--packages/CarrierDefaultApp/src/com/android/carrierdefaultapp/CarrierActionUtils.java11
-rw-r--r--packages/Incremental/NativeAdbDataLoader/Android.bp22
-rw-r--r--packages/Incremental/NativeAdbDataLoader/AndroidManifest.xml39
-rw-r--r--packages/Incremental/NativeAdbDataLoader/jni/Android.bp37
-rw-r--r--packages/Incremental/NativeAdbDataLoader/jni/com_android_incremental_nativeadb_DataLoaderService.cpp519
-rw-r--r--packages/Incremental/NativeAdbDataLoader/res/values/strings.xml (renamed from apex/sdkext/framework/tests/AndroidManifest.xml)16
-rw-r--r--packages/Incremental/NativeAdbDataLoader/src/com/android/incremental/nativeadb/NativeAdbDataLoaderService.java32
-rw-r--r--packages/SettingsLib/res/values/arrays.xml6
-rw-r--r--packages/SettingsLib/res/values/strings.xml10
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/Utils.java27
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/A2dpProfile.java26
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/A2dpSinkProfile.java20
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothUtils.java2
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java8
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/HeadsetProfile.java16
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/HearingAidProfile.java26
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/HfpClientProfile.java16
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/HidProfile.java18
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/LocalBluetoothAdapter.java2
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/MapClientProfile.java16
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/MapProfile.java16
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/OWNERS9
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/OppProfile.java2
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/PbapClientProfile.java12
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/PbapServerProfile.java24
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/bluetooth/SapProfile.java16
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/core/instrumentation/MetricsFeatureProvider.java55
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/location/RecentLocationApps.java2
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/wifi/AccessPoint.java61
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/wifi/TestAccessPointBuilder.java16
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/wifi/WifiEntryPreference.java8
-rw-r--r--packages/SettingsLib/tests/integ/src/com/android/settingslib/wifi/AccessPointTest.java119
-rw-r--r--packages/SettingsLib/tests/robotests/src/com/android/settingslib/UtilsTest.java40
-rw-r--r--packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/instrumentation/MetricsFeatureProviderTest.java80
-rw-r--r--packages/SettingsProvider/res/values-af/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-am/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-ar/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-as/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-az/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-b+sr+Latn/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-be/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-bg/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-bn/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-bs/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-ca/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-cs/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-da/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-de/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-el/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-en-rAU/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-en-rCA/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-en-rGB/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-en-rIN/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-es-rUS/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-es/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-et/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-eu/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-fa/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-fi/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-fr-rCA/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-fr/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-gl/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-gu/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-hi/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-hr/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-hu/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-hy/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-in/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-is/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-it/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-iw/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-ja/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-ka/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-kk/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-km/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-kn/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-ko/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-ky/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-lo/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-lt/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-lv/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-mk/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-ml/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-mn/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-mr/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-ms/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-my/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-nb/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-ne/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-nl/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-or/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-pa/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-pl/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-pt-rBR/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-pt-rPT/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-pt/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-ro/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-ru/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-si/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-sk/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-sl/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-sq/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-sr/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-sv/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-sw/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-ta/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-te/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-th/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-tl/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-tr/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-uk/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-ur/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-uz/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-vi/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-zh-rCN/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-zh-rHK/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-zh-rTW/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values-zu/strings.xml9
-rw-r--r--packages/SettingsProvider/res/values/defaults.xml2
-rw-r--r--packages/SettingsProvider/src/android/provider/settings/backup/GlobalSettings.java1
-rw-r--r--packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java5
-rw-r--r--packages/SettingsProvider/src/android/provider/settings/validators/GlobalSettingsValidators.java1
-rw-r--r--packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java5
-rw-r--r--packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java9
-rw-r--r--packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java23
-rw-r--r--packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java11
-rw-r--r--packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java25
-rw-r--r--packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java47
-rw-r--r--packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java6
-rw-r--r--packages/Shell/AndroidManifest.xml6
-rw-r--r--packages/SoundPicker/src/com/android/soundpicker/RingtoneOverlayService.java2
-rw-r--r--packages/SystemUI/Android.bp6
-rw-r--r--packages/SystemUI/AndroidManifest.xml16
-rw-r--r--packages/SystemUI/CleanSpec.mk50
-rw-r--r--packages/SystemUI/plugin_core/Android.bp4
-rw-r--r--packages/SystemUI/res/drawable-xhdpi/tv_card_gradient_protection.pngbin139 -> 0 bytes
-rw-r--r--packages/SystemUI/res/drawable/ic_control_magnification_grey.xml22
-rw-r--r--packages/SystemUI/res/drawable/tv_circle_dark.xml (renamed from packages/SystemUI/res/drawable/tv_bg_item_app_info.xml)10
-rw-r--r--packages/SystemUI/res/drawable/tv_circle_white_translucent.xml (renamed from packages/SystemUI/res/drawable/circle_red.xml)7
-rw-r--r--packages/SystemUI/res/drawable/tv_ic_mic_white.xml46
-rw-r--r--packages/SystemUI/res/drawable/tv_rect_dark_left_rounded.xml26
-rw-r--r--packages/SystemUI/res/drawable/tv_rect_dark_right_rounded.xml26
-rw-r--r--packages/SystemUI/res/drawable/tv_ring_white.xml (renamed from packages/SystemUI/res/drawable/tv_gradient_protection.xml)13
-rw-r--r--packages/SystemUI/res/layout/bubble_overflow_activity.xml20
-rw-r--r--packages/SystemUI/res/layout/magnifier_controllers.xml65
-rw-r--r--packages/SystemUI/res/layout/tv_audio_recording_indicator.xml121
-rw-r--r--packages/SystemUI/res/layout/tv_item_app_info.xml41
-rw-r--r--packages/SystemUI/res/layout/tv_status_bar_audio_recording.xml63
-rw-r--r--packages/SystemUI/res/layout/window_magnifier_view.xml71
-rw-r--r--packages/SystemUI/res/values/attrs.xml7
-rw-r--r--packages/SystemUI/res/values/colors.xml1
-rw-r--r--packages/SystemUI/res/values/colors_tv.xml10
-rw-r--r--packages/SystemUI/res/values/config.xml1
-rw-r--r--packages/SystemUI/res/values/dimens.xml12
-rw-r--r--packages/SystemUI/res/values/integers.xml2
-rw-r--r--packages/SystemUI/res/values/strings.xml21
-rw-r--r--packages/SystemUI/res/values/strings_tv.xml4
-rw-r--r--packages/SystemUI/res/values/styles.xml1
-rw-r--r--packages/SystemUI/shared/src/com/android/systemui/shared/system/ActivityManagerWrapper.java18
-rw-r--r--packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskDescriptionCompat.java9
-rw-r--r--packages/SystemUI/shared/src/com/android/systemui/shared/system/WindowManagerWrapper.java20
-rw-r--r--packages/SystemUI/src/com/android/keyguard/CarrierTextController.java3
-rw-r--r--packages/SystemUI/src/com/android/keyguard/EmergencyButton.java36
-rw-r--r--packages/SystemUI/src/com/android/keyguard/KeyguardDisplayManager.java1
-rw-r--r--packages/SystemUI/src/com/android/keyguard/clock/ClockInfo.java10
-rw-r--r--packages/SystemUI/src/com/android/keyguard/clock/ClockManager.java11
-rw-r--r--packages/SystemUI/src/com/android/systemui/ActivityStarterDelegate.java86
-rw-r--r--packages/SystemUI/src/com/android/systemui/BatteryMeterView.java2
-rw-r--r--packages/SystemUI/src/com/android/systemui/CornerHandleView.java8
-rw-r--r--packages/SystemUI/src/com/android/systemui/Dependency.java5
-rw-r--r--packages/SystemUI/src/com/android/systemui/ExpandHelper.java3
-rw-r--r--packages/SystemUI/src/com/android/systemui/ScreenDecorations.java1
-rw-r--r--packages/SystemUI/src/com/android/systemui/SizeCompatModeActivityController.java1
-rw-r--r--packages/SystemUI/src/com/android/systemui/SwipeHelper.java5
-rw-r--r--packages/SystemUI/src/com/android/systemui/accessibility/WindowMagnification.java83
-rw-r--r--packages/SystemUI/src/com/android/systemui/accessibility/WindowMagnificationController.java424
-rw-r--r--packages/SystemUI/src/com/android/systemui/assist/AssistDisclosure.java1
-rw-r--r--packages/SystemUI/src/com/android/systemui/assist/ui/DefaultUiController.java1
-rw-r--r--packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java2
-rw-r--r--packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java8
-rw-r--r--packages/SystemUI/src/com/android/systemui/biometrics/OWNERS7
-rw-r--r--packages/SystemUI/src/com/android/systemui/biometrics/Utils.java8
-rw-r--r--packages/SystemUI/src/com/android/systemui/broadcast/BroadcastDispatcher.kt10
-rw-r--r--packages/SystemUI/src/com/android/systemui/bubbles/BadgedImageView.java105
-rw-r--r--packages/SystemUI/src/com/android/systemui/bubbles/Bubble.java168
-rw-r--r--packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java161
-rw-r--r--packages/SystemUI/src/com/android/systemui/bubbles/BubbleData.java42
-rw-r--r--packages/SystemUI/src/com/android/systemui/bubbles/BubbleDebugConfig.java20
-rw-r--r--packages/SystemUI/src/com/android/systemui/bubbles/BubbleExpandedView.java94
-rw-r--r--packages/SystemUI/src/com/android/systemui/bubbles/BubbleExperimentConfig.java40
-rw-r--r--packages/SystemUI/src/com/android/systemui/bubbles/BubbleIconFactory.java33
-rw-r--r--packages/SystemUI/src/com/android/systemui/bubbles/BubbleMenuView.java3
-rw-r--r--packages/SystemUI/src/com/android/systemui/bubbles/BubbleOverflowActivity.java69
-rw-r--r--packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java43
-rw-r--r--packages/SystemUI/src/com/android/systemui/bubbles/BubbleTouchHandler.java16
-rw-r--r--packages/SystemUI/src/com/android/systemui/bubbles/BubbleViewInfoTask.java182
-rw-r--r--packages/SystemUI/src/com/android/systemui/dagger/DefaultActivityBinder.java15
-rw-r--r--packages/SystemUI/src/com/android/systemui/dagger/DependencyProvider.java18
-rw-r--r--packages/SystemUI/src/com/android/systemui/dagger/SystemServicesModule.java7
-rw-r--r--packages/SystemUI/src/com/android/systemui/dagger/SystemUIBinder.java7
-rw-r--r--packages/SystemUI/src/com/android/systemui/dagger/SystemUIDefaultModule.java10
-rw-r--r--packages/SystemUI/src/com/android/systemui/doze/DozeEvent.java26
-rw-r--r--packages/SystemUI/src/com/android/systemui/doze/DozeLog.java66
-rw-r--r--packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java5
-rw-r--r--packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java3
-rw-r--r--packages/SystemUI/src/com/android/systemui/doze/DozeWallpaperState.java21
-rw-r--r--packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialog.java1
-rw-r--r--packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsImpl.java1
-rw-r--r--packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java5
-rw-r--r--packages/SystemUI/src/com/android/systemui/log/Event.java29
-rw-r--r--packages/SystemUI/src/com/android/systemui/log/RichEvent.java48
-rw-r--r--packages/SystemUI/src/com/android/systemui/log/SysuiLog.java58
-rw-r--r--packages/SystemUI/src/com/android/systemui/media/MediaProjectionPermissionActivity.java5
-rw-r--r--packages/SystemUI/src/com/android/systemui/pip/phone/PipDismissViewController.java1
-rw-r--r--packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java3
-rw-r--r--packages/SystemUI/src/com/android/systemui/qs/QuickQSMediaPlayer.java8
-rw-r--r--packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java53
-rw-r--r--packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java10
-rw-r--r--packages/SystemUI/src/com/android/systemui/qs/tileimpl/QSTileImpl.java1
-rw-r--r--packages/SystemUI/src/com/android/systemui/qs/tiles/UiModeNightTile.java11
-rw-r--r--packages/SystemUI/src/com/android/systemui/recents/ScreenPinningRequest.java1
-rw-r--r--packages/SystemUI/src/com/android/systemui/screenrecord/RecordingService.java3
-rw-r--r--packages/SystemUI/src/com/android/systemui/screenshot/GlobalScreenshot.java1
-rw-r--r--packages/SystemUI/src/com/android/systemui/screenshot/SaveImageInBackgroundTask.java38
-rw-r--r--packages/SystemUI/src/com/android/systemui/settings/CurrentUserTracker.java3
-rw-r--r--packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java15
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/FlingAnimationUtils.java61
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/KeyguardAffordanceView.java3
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java125
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/NotificationUpdateHandler.java60
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/NotificationViewHierarchyManager.java8
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationClicker.java9
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java54
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationFilter.java6
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/GroupEntry.java13
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ListEntry.java81
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifCollection.java2
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifListBuilderImpl.java263
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java63
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationRankingManager.kt46
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/DeviceProvisionedCoordinator.java17
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/ForegroundCoordinator.java21
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/KeyguardCoordinator.java22
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinator.java9
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/NotifListBuilder.java18
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/OnBeforeTransformGroupsListener.java4
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/PipelineState.java16
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/pluggable/NotifFilter.java10
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/provider/DerivedMember.java62
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/provider/IsHighPriorityProvider.java148
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotifEvent.java203
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotifLog.java92
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleHubModule.kt5
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleHubNotificationListener.kt2
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleHubViewController.kt97
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ChannelEditorDialogController.kt2
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java11
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationSectionsManager.java13
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java4
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/BiometricUnlockController.java13
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/EdgeBackGestureHandler.java1
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/FloatingRotationButton.java1
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardAffordanceHelper.java3
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/LockscreenGestureLogger.java6
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/LockscreenWallpaper.java44
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarFragment.java5
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java2
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java12
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java7
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java5
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/ShadeController.java18
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/ShadeControllerImpl.java236
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java226
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java7
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarModule.java2
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java7
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java6
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java14
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowController.java1
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowViewController.java11
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/SystemUIDialog.java14
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/policy/BluetoothController.java2
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/policy/BluetoothControllerImpl.java67
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceProvisionedControllerImpl.java6
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java3
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/tv/AudioRecordingDisclosureBar.java376
-rw-r--r--packages/SystemUI/src/com/android/systemui/usb/UsbDebuggingActivity.java55
-rw-r--r--packages/SystemUI/src/com/android/systemui/usb/UsbDebuggingSecondaryUserActivity.java56
-rw-r--r--packages/SystemUI/src/com/android/systemui/util/animation/PhysicsAnimator.kt717
-rw-r--r--packages/SystemUI/src/com/android/systemui/util/animation/PhysicsAnimatorTestUtils.kt457
-rw-r--r--packages/SystemUI/src/com/android/systemui/util/concurrency/ConcurrencyModule.java25
-rw-r--r--packages/SystemUI/src/com/android/systemui/volume/Events.java436
-rw-r--r--packages/SystemUI/src/com/android/systemui/wm/DisplayLayout.java474
-rw-r--r--packages/SystemUI/src/com/android/systemui/wm/DisplayWindowController.java56
-rw-r--r--packages/SystemUI/src/com/android/systemui/wm/SystemWindows.java330
-rw-r--r--packages/SystemUI/tests/Android.mk3
-rw-r--r--packages/SystemUI/tests/src/com/android/keyguard/clock/ClockInfoTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/keyguard/clock/ClockOptionsProviderTest.java4
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/ForegroundServiceControllerTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/ForegroundServiceNotificationListenerTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthBiometricViewTest.java7
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.java21
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java71
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/broadcast/BroadcastDispatcherTest.kt19
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java93
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleDataTest.java74
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleTest.java4
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/doze/DozeSensorsTest.java18
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/glwallpaper/ImageRevealHelperTest.java73
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardViewMediatorTest.java5
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/log/RichEventTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/log/SysuiLogTest.java59
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/qs/QSFragmentTest.java3
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/qs/customize/TileQueryHelperTest.java1
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/qs/tileimpl/QSTileImplTest.java12
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/AlertingNotificationManagerTest.java1
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationInterruptionStateProviderTest.java1
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationListenerTest.java41
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerTest.java7
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationRemoteInputManagerTest.java1
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationTestHelper.java1
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationViewHierarchyManagerTest.java5
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/RankingBuilder.java1
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/SmartReplyControllerTest.java1
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationFilterTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationListControllerTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/VisualStabilityManagerTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/GroupEntryTest.java148
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotifCollectionTest.java3
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotifListBuilderImplTest.java163
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationEntryBuilder.java (renamed from packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationEntryBuilder.java)38
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationEntryTest.java41
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationRankingManagerTest.kt128
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/DeviceProvisionedCoordinatorTest.java152
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/ForegroundCoordinatorTest.java188
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/KeyguardCoordinatorTest.java88
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinatorTest.java136
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/provider/IsHighPriorityProviderTest.java184
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/NotificationLoggerTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/people/PeopleHubViewControllerTest.kt46
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentInflaterTest.java3
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationGutsManagerTest.java14
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationInfoTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationMenuRowTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/BiometricsUnlockControllerTest.java30
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhoneTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarFragmentTest.java1
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationGroupTestHelper.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java11
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java14
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenterTest.java4
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallbackTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java10
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowViewTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/BluetoothControllerImplTest.java25
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/InflatedSmartRepliesTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyViewTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/util/DeviceConfigProxyFake.java13
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/util/animation/PhysicsAnimatorTest.kt436
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/util/concurrency/FakeExecutorTest.java6
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/util/time/FakeSystemClock.java25
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakeBluetoothController.java10
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/volume/EventsTest.java215
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/wm/DisplayLayoutTest.java141
-rw-r--r--packages/Tethering/Android.bp1
-rw-r--r--packages/Tethering/AndroidManifest.xml2
-rw-r--r--packages/Tethering/AndroidManifestBase.xml2
-rw-r--r--packages/Tethering/AndroidManifest_InProcess.xml2
-rw-r--r--packages/Tethering/apex/Android.bp14
-rw-r--r--packages/Tethering/apex/AndroidManifest.xml2
-rw-r--r--packages/Tethering/apex/com.android.tethering.apex.avbpubkeybin1032 -> 0 bytes
-rw-r--r--packages/Tethering/apex/com.android.tethering.apex.pem51
-rw-r--r--packages/Tethering/apex/com.android.tethering.apex.pk8bin2375 -> 0 bytes
-rw-r--r--packages/Tethering/apex/com.android.tethering.apex.x509.pem36
-rw-r--r--packages/Tethering/apex/com.android.tethering.avbpubkeybin0 -> 1032 bytes
-rw-r--r--packages/Tethering/apex/com.android.tethering.pem51
-rw-r--r--packages/Tethering/apex/com.android.tethering.pk8bin0 -> 2375 bytes
-rw-r--r--packages/Tethering/apex/com.android.tethering.x509.pem35
-rw-r--r--packages/Tethering/apex/manifest.json2
-rw-r--r--packages/Tethering/common/TetheringLib/src/android/net/TetheringManager.java25
-rw-r--r--packages/Tethering/src/com/android/server/connectivity/tethering/Tethering.java4
-rw-r--r--packages/Tethering/tests/unit/AndroidManifest.xml4
-rw-r--r--packages/Tethering/tests/unit/src/com/android/server/connectivity/tethering/TetheringTest.java16
-rw-r--r--services/Android.bp24
-rw-r--r--services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java430
-rw-r--r--services/accessibility/java/com/android/server/accessibility/AccessibilityServiceConnection.java1
-rw-r--r--services/accessibility/java/com/android/server/accessibility/AccessibilityUserState.java163
-rw-r--r--services/accessibility/java/com/android/server/accessibility/gestures/AccessibilityGestureDetector.java640
-rw-r--r--services/accessibility/java/com/android/server/accessibility/gestures/GestureManifold.java232
-rw-r--r--services/accessibility/java/com/android/server/accessibility/gestures/GestureMatcher.java371
-rw-r--r--services/accessibility/java/com/android/server/accessibility/gestures/MultiTap.java145
-rw-r--r--services/accessibility/java/com/android/server/accessibility/gestures/MultiTapAndHold.java51
-rw-r--r--services/accessibility/java/com/android/server/accessibility/gestures/Swipe.java430
-rw-r--r--services/accessibility/java/com/android/server/accessibility/gestures/TouchExplorer.java16
-rw-r--r--services/accessibility/java/com/android/server/accessibility/gestures/TouchState.java7
-rw-r--r--services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java6
-rw-r--r--services/autofill/java/com/android/server/autofill/Session.java248
-rw-r--r--services/autofill/java/com/android/server/autofill/ui/AutoFillUI.java79
-rw-r--r--services/backup/java/com/android/server/backup/BackupManagerService.java11
-rw-r--r--services/backup/java/com/android/server/backup/restore/PerformUnifiedRestoreTask.java6
-rw-r--r--services/core/Android.bp1
-rw-r--r--services/core/java/android/content/pm/PackageManagerInternal.java34
-rw-r--r--services/core/java/android/os/UserManagerInternal.java6
-rw-r--r--services/core/java/com/android/server/AlarmManagerService.java36
-rw-r--r--services/core/java/com/android/server/BluetoothManagerService.java28
-rw-r--r--services/core/java/com/android/server/ConnectivityService.java98
-rw-r--r--services/core/java/com/android/server/CountryDetectorService.java76
-rw-r--r--services/core/java/com/android/server/GnssManagerService.java1
-rw-r--r--services/core/java/com/android/server/LocationManagerService.java275
-rw-r--r--services/core/java/com/android/server/MmsServiceBroker.java22
-rw-r--r--services/core/java/com/android/server/NetworkManagementService.java6
-rw-r--r--services/core/java/com/android/server/NetworkTimeUpdateServiceImpl.java6
-rw-r--r--services/core/java/com/android/server/PackageWatchdog.java157
-rw-r--r--services/core/java/com/android/server/StorageManagerService.java148
-rw-r--r--services/core/java/com/android/server/SystemService.java23
-rw-r--r--services/core/java/com/android/server/TelephonyRegistry.java337
-rw-r--r--services/core/java/com/android/server/UiModeManagerService.java73
-rw-r--r--services/core/java/com/android/server/VibratorService.java70
-rw-r--r--services/core/java/com/android/server/accounts/AccountManagerService.java30
-rw-r--r--services/core/java/com/android/server/am/ActivityManagerService.java52
-rw-r--r--services/core/java/com/android/server/am/ActivityManagerShellCommand.java17
-rw-r--r--services/core/java/com/android/server/am/LmkdConnection.java27
-rw-r--r--services/core/java/com/android/server/am/ProcessList.java167
-rw-r--r--services/core/java/com/android/server/am/ProcessRecord.java2
-rw-r--r--services/core/java/com/android/server/appop/AppOpsService.java8
-rw-r--r--services/core/java/com/android/server/attention/AttentionManagerService.java41
-rw-r--r--services/core/java/com/android/server/audio/AudioDeviceBroker.java51
-rw-r--r--services/core/java/com/android/server/audio/AudioDeviceInventory.java230
-rw-r--r--services/core/java/com/android/server/audio/AudioService.java60
-rw-r--r--services/core/java/com/android/server/audio/BtHelper.java1
-rw-r--r--services/core/java/com/android/server/biometrics/AuthService.java95
-rw-r--r--services/core/java/com/android/server/biometrics/BiometricService.java304
-rw-r--r--services/core/java/com/android/server/biometrics/BiometricServiceBase.java13
-rw-r--r--services/core/java/com/android/server/biometrics/BiometricStrengthController.java119
-rw-r--r--services/core/java/com/android/server/biometrics/OWNERS7
-rw-r--r--services/core/java/com/android/server/biometrics/SensorConfig.java33
-rw-r--r--services/core/java/com/android/server/biometrics/Utils.java180
-rw-r--r--services/core/java/com/android/server/connectivity/DataConnectionStats.java38
-rw-r--r--services/core/java/com/android/server/connectivity/KeepaliveTracker.java7
-rw-r--r--services/core/java/com/android/server/connectivity/NetworkAgentInfo.java7
-rw-r--r--services/core/java/com/android/server/connectivity/TcpKeepaliveController.java2
-rw-r--r--services/core/java/com/android/server/display/AutomaticBrightnessController.java48
-rw-r--r--services/core/java/com/android/server/display/HysteresisLevels.java9
-rw-r--r--services/core/java/com/android/server/display/LocalDisplayAdapter.java7
-rw-r--r--services/core/java/com/android/server/emergency/EmergencyAffordanceService.java3
-rw-r--r--services/core/java/com/android/server/hdmi/HdmiCecKeycode.java4
-rw-r--r--services/core/java/com/android/server/incremental/IncrementalManagerService.java155
-rw-r--r--services/core/java/com/android/server/incremental/IncrementalManagerShellCommand.java295
-rw-r--r--services/core/java/com/android/server/infra/AbstractMasterSystemService.java1
-rw-r--r--services/core/java/com/android/server/input/ConfigurationProcessor.java16
-rw-r--r--services/core/java/com/android/server/input/InputManagerService.java51
-rw-r--r--services/core/java/com/android/server/inputmethod/InputMethodManagerInternal.java28
-rw-r--r--services/core/java/com/android/server/inputmethod/InputMethodManagerService.java42
-rw-r--r--services/core/java/com/android/server/inputmethod/MultiClientInputMethodManagerService.java15
-rw-r--r--services/core/java/com/android/server/integrity/AppIntegrityManagerService.java (renamed from apex/sdkext/framework/tests/src/android/os/ext/SdkExtensionsTest.java)35
-rw-r--r--services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java80
-rw-r--r--services/core/java/com/android/server/integrity/OWNERS1
-rw-r--r--services/core/java/com/android/server/integrity/serializer/RuleIndexingDetails.java67
-rw-r--r--services/core/java/com/android/server/integrity/serializer/RuleIndexingDetailsIdentifier.java169
-rw-r--r--services/core/java/com/android/server/location/LocationSettingsStore.java138
-rw-r--r--services/core/java/com/android/server/location/LocationUsageLogger.java (renamed from services/core/java/com/android/server/LocationUsageLogger.java)220
-rw-r--r--services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java8
-rw-r--r--services/core/java/com/android/server/media/MediaSessionService.java225
-rw-r--r--services/core/java/com/android/server/media/MediaShellCommand.java (renamed from cmds/media/src/com/android/commands/media/Media.java)196
-rw-r--r--[-rwxr-xr-x]services/core/java/com/android/server/media/VolumeCtrl.java (renamed from cmds/media/src/com/android/commands/media/VolumeCtrl.java)106
-rw-r--r--services/core/java/com/android/server/net/NetworkPolicyManagerService.java1
-rw-r--r--services/core/java/com/android/server/net/NetworkStatsService.java7
-rw-r--r--services/core/java/com/android/server/notification/NotificationComparator.java18
-rw-r--r--services/core/java/com/android/server/notification/NotificationRecord.java20
-rw-r--r--services/core/java/com/android/server/notification/NotificationUsageStats.java11
-rw-r--r--services/core/java/com/android/server/package-info.java (renamed from tests/utils/testutils/java/test/package-info.java)9
-rw-r--r--services/core/java/com/android/server/pm/ApexManager.java15
-rw-r--r--services/core/java/com/android/server/pm/ComponentResolver.java45
-rw-r--r--services/core/java/com/android/server/pm/Installer.java62
-rw-r--r--services/core/java/com/android/server/pm/InstantAppResolver.java61
-rw-r--r--services/core/java/com/android/server/pm/InstantAppResolverConnection.java27
-rw-r--r--services/core/java/com/android/server/pm/PackageInstallerService.java22
-rw-r--r--services/core/java/com/android/server/pm/PackageInstallerSession.java373
-rw-r--r--services/core/java/com/android/server/pm/PackageManagerService.java311
-rw-r--r--services/core/java/com/android/server/pm/PackageManagerShellCommand.java68
-rw-r--r--services/core/java/com/android/server/pm/StagingManager.java84
-rw-r--r--services/core/java/com/android/server/pm/TEST_MAPPING15
-rw-r--r--services/core/java/com/android/server/pm/UserManagerService.java126
-rw-r--r--services/core/java/com/android/server/pm/UserRestrictionsUtils.java14
-rw-r--r--services/core/java/com/android/server/pm/UserSystemPackageInstaller.java75
-rw-r--r--services/core/java/com/android/server/pm/UserTypeDetails.java69
-rw-r--r--services/core/java/com/android/server/pm/UserTypeFactory.java261
-rw-r--r--services/core/java/com/android/server/pm/permission/BasePermission.java28
-rw-r--r--services/core/java/com/android/server/pm/permission/PermissionManagerService.java8
-rw-r--r--services/core/java/com/android/server/policy/PermissionPolicyService.java15
-rw-r--r--services/core/java/com/android/server/policy/PhoneWindowManager.java4
-rw-r--r--services/core/java/com/android/server/policy/WindowManagerPolicy.java24
-rw-r--r--services/core/java/com/android/server/power/ShutdownThread.java29
-rw-r--r--services/core/java/com/android/server/power/batterysaver/BatterySaverStateMachine.java67
-rw-r--r--services/core/java/com/android/server/role/FinancialSmsManager.java218
-rw-r--r--services/core/java/com/android/server/role/RoleManagerService.java1
-rw-r--r--services/core/java/com/android/server/rollback/Rollback.java4
-rw-r--r--services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java32
-rw-r--r--services/core/java/com/android/server/rollback/RollbackPackageHealthObserver.java190
-rw-r--r--services/core/java/com/android/server/soundtrigger_middleware/AudioSessionProviderImpl.java29
-rw-r--r--services/core/java/com/android/server/soundtrigger_middleware/ConversionUtil.java390
-rw-r--r--services/core/java/com/android/server/soundtrigger_middleware/HalException.java49
-rw-r--r--services/core/java/com/android/server/soundtrigger_middleware/Hw2CompatUtil.java77
-rw-r--r--services/core/java/com/android/server/soundtrigger_middleware/ISoundTriggerHw2.java158
-rw-r--r--services/core/java/com/android/server/soundtrigger_middleware/InternalServerError.java40
-rw-r--r--services/core/java/com/android/server/soundtrigger_middleware/RecoverableException.java53
-rw-r--r--services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerHw2Compat.java470
-rw-r--r--services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerMiddlewareImpl.java140
-rw-r--r--services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerMiddlewareService.java709
-rw-r--r--services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerModule.java545
-rw-r--r--services/core/java/com/android/server/soundtrigger_middleware/TEST_MAPPING12
-rw-r--r--services/core/java/com/android/server/soundtrigger_middleware/UuidUtil.java44
-rw-r--r--services/core/java/com/android/server/soundtrigger_middleware/ValidationUtil.java117
-rw-r--r--services/core/java/com/android/server/storage/StorageSessionController.java64
-rw-r--r--services/core/java/com/android/server/storage/StorageUserConnection.java127
-rw-r--r--services/core/java/com/android/server/textclassifier/TextClassificationManagerService.java219
-rw-r--r--services/core/java/com/android/server/timedetector/SimpleTimeDetectorStrategy.java305
-rw-r--r--services/core/java/com/android/server/timedetector/TimeDetectorService.java11
-rw-r--r--services/core/java/com/android/server/timedetector/TimeDetectorStrategyImpl.java549
-rw-r--r--services/core/java/com/android/server/timezonedetector/TimeZoneDetectorCallbackImpl.java14
-rw-r--r--services/core/java/com/android/server/timezonedetector/TimeZoneDetectorStrategy.java22
-rwxr-xr-x[-rw-r--r--]services/core/java/com/android/server/tv/TvInputManagerService.java10
-rw-r--r--services/core/java/com/android/server/utils/TEST_MAPPING12
-rw-r--r--services/core/java/com/android/server/utils/quota/Categorizer.java (renamed from core/java/android/hardware/biometrics/Authenticator.java)26
-rw-r--r--services/core/java/com/android/server/utils/quota/Category.java71
-rw-r--r--services/core/java/com/android/server/utils/quota/QuotaChangeListener.java34
-rw-r--r--services/core/java/com/android/server/utils/quota/Uptc.java88
-rw-r--r--services/core/java/com/android/server/utils/quota/UptcMap.java163
-rw-r--r--services/core/java/com/android/server/wm/ActivityDisplay.java1396
-rw-r--r--services/core/java/com/android/server/wm/ActivityMetricsLogger.java70
-rw-r--r--services/core/java/com/android/server/wm/ActivityRecord.java392
-rw-r--r--services/core/java/com/android/server/wm/ActivityStack.java590
-rw-r--r--services/core/java/com/android/server/wm/ActivityStackSupervisor.java199
-rw-r--r--services/core/java/com/android/server/wm/ActivityStartController.java27
-rw-r--r--services/core/java/com/android/server/wm/ActivityStarter.java15
-rw-r--r--services/core/java/com/android/server/wm/ActivityTaskManagerService.java70
-rw-r--r--services/core/java/com/android/server/wm/AppTaskImpl.java2
-rw-r--r--services/core/java/com/android/server/wm/AppTransition.java21
-rw-r--r--services/core/java/com/android/server/wm/AppTransitionController.java112
-rw-r--r--services/core/java/com/android/server/wm/ConfigurationContainer.java12
-rw-r--r--services/core/java/com/android/server/wm/DisplayContent.java1951
-rw-r--r--services/core/java/com/android/server/wm/DisplayPolicy.java118
-rw-r--r--services/core/java/com/android/server/wm/DisplayRotation.java14
-rw-r--r--services/core/java/com/android/server/wm/DisplayWindowListenerController.java6
-rw-r--r--services/core/java/com/android/server/wm/DockedStackDividerController.java4
-rw-r--r--services/core/java/com/android/server/wm/EnsureActivitiesVisibleHelper.java2
-rw-r--r--services/core/java/com/android/server/wm/ImmersiveModeConfirmation.java2
-rw-r--r--services/core/java/com/android/server/wm/InsetsPolicy.java23
-rw-r--r--services/core/java/com/android/server/wm/InsetsSourceProvider.java23
-rw-r--r--services/core/java/com/android/server/wm/KeyguardController.java10
-rw-r--r--services/core/java/com/android/server/wm/LaunchParamsPersister.java6
-rw-r--r--services/core/java/com/android/server/wm/LockTaskController.java9
-rw-r--r--services/core/java/com/android/server/wm/RecentTasks.java24
-rw-r--r--services/core/java/com/android/server/wm/RecentsAnimation.java14
-rw-r--r--services/core/java/com/android/server/wm/ResetTargetTaskHelper.java2
-rw-r--r--services/core/java/com/android/server/wm/RootActivityContainer.java514
-rw-r--r--services/core/java/com/android/server/wm/RunningTasks.java84
-rw-r--r--services/core/java/com/android/server/wm/ScreenRotationAnimation.java2
-rw-r--r--services/core/java/com/android/server/wm/ShellRoot.java74
-rw-r--r--services/core/java/com/android/server/wm/Task.java39
-rw-r--r--services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java30
-rw-r--r--services/core/java/com/android/server/wm/TaskSnapshotCache.java2
-rw-r--r--services/core/java/com/android/server/wm/TaskSnapshotController.java211
-rw-r--r--services/core/java/com/android/server/wm/TaskSnapshotPersister.java11
-rw-r--r--services/core/java/com/android/server/wm/TaskSnapshotSurface.java40
-rw-r--r--services/core/java/com/android/server/wm/WindowContainer.java150
-rw-r--r--services/core/java/com/android/server/wm/WindowFrames.java1
-rw-r--r--services/core/java/com/android/server/wm/WindowManagerConstants.java6
-rw-r--r--services/core/java/com/android/server/wm/WindowManagerService.java80
-rw-r--r--services/core/java/com/android/server/wm/WindowProcessController.java20
-rw-r--r--services/core/java/com/android/server/wm/WindowState.java101
-rw-r--r--services/core/jni/Android.bp1
-rw-r--r--services/core/jni/com_android_server_VibratorService.cpp17
-rw-r--r--services/core/jni/com_android_server_input_InputManagerService.cpp6
-rw-r--r--services/core/jni/com_android_server_security_VerityUtils.cpp35
-rw-r--r--services/core/jni/com_android_server_soundtrigger_middleware_AudioSessionProviderImpl.cpp91
-rw-r--r--services/core/jni/onload.cpp4
-rw-r--r--services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java168
-rw-r--r--services/java/com/android/server/SystemServer.java48
-rw-r--r--services/net/java/android/net/NetworkMonitorManager.java2
-rw-r--r--services/net/java/android/net/TcpKeepalivePacketData.java1
-rw-r--r--services/net/java/android/net/ip/IpClientManager.java2
-rw-r--r--services/tests/mockingservicestests/src/com/android/server/am/MockingOomAdjusterTests.java2
-rw-r--r--services/tests/mockingservicestests/src/com/android/server/display/LocalDisplayAdapterTest.java52
-rw-r--r--services/tests/servicestests/Android.bp2
-rw-r--r--services/tests/servicestests/res/xml/usertypes_test_eraseArray.xml24
-rw-r--r--services/tests/servicestests/res/xml/usertypes_test_full.xml25
-rw-r--r--services/tests/servicestests/res/xml/usertypes_test_illegalOemName.xml19
-rw-r--r--services/tests/servicestests/res/xml/usertypes_test_illegalUserBaseType.xml18
-rw-r--r--services/tests/servicestests/res/xml/usertypes_test_profile.xml35
-rw-r--r--services/tests/servicestests/src/com/android/server/CountryDetectorServiceTest.java143
-rw-r--r--services/tests/servicestests/src/com/android/server/GnssManagerServiceTest.java1
-rw-r--r--services/tests/servicestests/src/com/android/server/accessibility/AccessibilityUserStateTest.java27
-rw-r--r--services/tests/servicestests/src/com/android/server/accessibility/AccessibilityWindowManagerTest.java20
-rw-r--r--services/tests/servicestests/src/com/android/server/accessibility/gestures/GestureManifoldTest.java (renamed from services/tests/servicestests/src/com/android/server/accessibility/gestures/AccessibilityGestureDetectorTest.java)52
-rw-r--r--services/tests/servicestests/src/com/android/server/accessibility/gestures/TouchExplorerTest.java4
-rw-r--r--services/tests/servicestests/src/com/android/server/am/ActivityManagerServiceTest.java13
-rw-r--r--services/tests/servicestests/src/com/android/server/attention/AttentionManagerServiceTest.java44
-rw-r--r--services/tests/servicestests/src/com/android/server/biometrics/AuthServiceTest.java25
-rw-r--r--services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java708
-rw-r--r--services/tests/servicestests/src/com/android/server/biometrics/OWNERS7
-rw-r--r--services/tests/servicestests/src/com/android/server/biometrics/UtilsTest.java226
-rw-r--r--services/tests/servicestests/src/com/android/server/compat/CompatConfigTest.java51
-rw-r--r--services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java178
-rw-r--r--services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java3
-rw-r--r--services/tests/servicestests/src/com/android/server/display/AutomaticBrightnessControllerTest.java192
-rw-r--r--services/tests/servicestests/src/com/android/server/display/DisplayManagerServiceTest.java2
-rw-r--r--services/tests/servicestests/src/com/android/server/display/TestUtils.java60
-rw-r--r--services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientLuxTest.java58
-rw-r--r--services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientSensorTest.java47
-rw-r--r--services/tests/servicestests/src/com/android/server/input/ConfigurationProcessorTest.java12
-rw-r--r--services/tests/servicestests/src/com/android/server/integrity/AppIntegrityManagerServiceImplTest.java72
-rw-r--r--services/tests/servicestests/src/com/android/server/integrity/serializer/RuleIndexingDetailsIdentifierTest.java323
-rw-r--r--services/tests/servicestests/src/com/android/server/om/MockitoUtils.kt (renamed from tests/utils/testutils/java/test/util/MockitoUtils.kt)4
-rw-r--r--services/tests/servicestests/src/com/android/server/om/OverlayReferenceMapperTests.kt2
-rw-r--r--services/tests/servicestests/src/com/android/server/pm/ApexManagerTest.java17
-rw-r--r--services/tests/servicestests/src/com/android/server/pm/PackageInstallerSessionTest.java1
-rw-r--r--services/tests/servicestests/src/com/android/server/pm/UserManagerServiceUserTypeTest.java198
-rw-r--r--services/tests/servicestests/src/com/android/server/pm/UserManagerTest.java406
-rw-r--r--services/tests/servicestests/src/com/android/server/pm/UserSystemPackageInstallerTest.java45
-rw-r--r--services/tests/servicestests/src/com/android/server/soundtrigger_middleware/ConversionUtilTest.java47
-rw-r--r--services/tests/servicestests/src/com/android/server/soundtrigger_middleware/SoundTriggerMiddlewareImplTest.java1306
-rw-r--r--services/tests/servicestests/src/com/android/server/timedetector/SimpleTimeDetectorStrategyTest.java661
-rw-r--r--services/tests/servicestests/src/com/android/server/timedetector/TimeDetectorServiceTest.java11
-rw-r--r--services/tests/servicestests/src/com/android/server/timedetector/TimeDetectorStrategyImplTest.java758
-rw-r--r--services/tests/servicestests/src/com/android/server/timezonedetector/TimeZoneDetectorStrategyTest.java68
-rw-r--r--services/tests/uiservicestests/src/com/android/server/notification/NotificationComparatorTest.java13
-rw-r--r--services/tests/uiservicestests/src/com/android/server/notification/NotificationRecordTest.java98
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/ActivityDisplayTests.java43
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java16
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/ActivityStackSupervisorTests.java2
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java40
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java21
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/ActivityTaskManagerServiceTests.java51
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java19
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/AnimatingActivityRegistryTest.java1
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java19
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java13
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/DisplayPolicyLayoutTests.java269
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/DisplayPolicyTestsBase.java2
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/LaunchParamsPersisterTests.java8
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java2
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java59
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java12
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java18
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/RootActivityContainerTests.java58
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java14
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java79
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/SurfaceAnimationRunnerTest.java1
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java7
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java136
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java20
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/TaskSnapshotControllerTest.java82
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/TaskSnapshotSurfaceTest.java2
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/TestDisplayContent.java (renamed from services/tests/wmtests/src/com/android/server/wm/TestActivityDisplay.java)12
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java38
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java52
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java4
-rw-r--r--services/usage/java/com/android/server/usage/StorageStatsService.java163
-rw-r--r--services/usage/java/com/android/server/usage/UsageStatsDatabase.java17
-rw-r--r--services/usb/java/com/android/server/usb/UsbHandlerManager.java16
-rw-r--r--services/usb/java/com/android/server/usb/UsbPortManager.java5
-rw-r--r--services/usb/java/com/android/server/usb/UsbSerialReader.java4
-rw-r--r--services/usb/java/com/android/server/usb/UsbUserPermissionManager.java5
-rw-r--r--services/voiceinteraction/java/com/android/server/soundtrigger/SoundTriggerHelper.java77
-rw-r--r--services/voiceinteraction/java/com/android/server/soundtrigger/SoundTriggerService.java99
-rw-r--r--services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java1
-rw-r--r--telecomm/java/android/telecom/Connection.java9
-rw-r--r--telecomm/java/android/telecom/TelecomManager.java97
-rw-r--r--telephony/common/com/android/internal/telephony/TelephonyPermissions.java154
-rw-r--r--telephony/java/android/telephony/Annotation.java5
-rwxr-xr-xtelephony/java/android/telephony/CarrierConfigManager.java136
-rw-r--r--telephony/java/android/telephony/CbGeoUtils.java83
-rw-r--r--telephony/java/android/telephony/DataFailCause.java9
-rw-r--r--telephony/java/android/telephony/ImsManager.java10
-rw-r--r--telephony/java/android/telephony/LocationAccessPolicy.java4
-rw-r--r--telephony/java/android/telephony/ModemActivityInfo.java4
-rw-r--r--telephony/java/android/telephony/NetworkScanRequest.java16
-rw-r--r--telephony/java/android/telephony/PhoneNumberRange.java16
-rw-r--r--telephony/java/android/telephony/PreciseDataConnectionState.java179
-rw-r--r--telephony/java/android/telephony/ServiceState.java5
-rw-r--r--telephony/java/android/telephony/SmsManager.java21
-rw-r--r--telephony/java/android/telephony/SubscriptionInfo.java57
-rw-r--r--telephony/java/android/telephony/SubscriptionManager.java8
-rw-r--r--telephony/java/android/telephony/TelephonyFrameworkInitializer.java26
-rw-r--r--telephony/java/android/telephony/TelephonyManager.java547
-rw-r--r--telephony/java/android/telephony/data/ApnSetting.java11
-rw-r--r--telephony/java/android/telephony/data/DataProfile.java4
-rw-r--r--telephony/java/android/telephony/ims/ImsCallSession.java14
-rw-r--r--telephony/java/android/telephony/ims/ImsRcsManager.java34
-rw-r--r--telephony/java/android/telephony/ims/aidl/IImsRcsController.aidl6
-rw-r--r--telephony/java/android/telephony/ims/feature/ImsFeature.java14
-rw-r--r--telephony/java/android/telephony/ims/feature/RcsFeature.java19
-rw-r--r--telephony/java/android/telephony/ims/stub/ImsConfigImplBase.java9
-rw-r--r--telephony/java/android/telephony/ims/stub/ImsRegistrationImplBase.java16
-rw-r--r--telephony/java/com/android/ims/ImsConfig.java3
-rw-r--r--telephony/java/com/android/internal/telephony/ISms.aidl8
-rw-r--r--telephony/java/com/android/internal/telephony/ISmsImplBase.java5
-rw-r--r--telephony/java/com/android/internal/telephony/ITelephony.aidl5
-rw-r--r--telephony/java/com/android/internal/telephony/IccCardConstants.java34
-rw-r--r--telephony/java/com/android/internal/telephony/PhoneConstantConversions.java8
-rw-r--r--telephony/java/com/android/internal/telephony/PhoneConstants.java31
-rw-r--r--telephony/java/com/android/internal/telephony/RILConstants.java3
-rw-r--r--telephony/java/com/android/internal/telephony/TelephonyIntents.java35
-rw-r--r--telephony/java/com/android/internal/telephony/gsm/GsmSmsCbMessage.java521
-rw-r--r--telephony/java/com/android/internal/telephony/util/HandlerExecutor.java47
-rw-r--r--telephony/java/com/android/internal/telephony/util/RemoteCallbackListExt.java46
-rw-r--r--test-mock/Android.bp3
-rw-r--r--test-mock/src/android/test/mock/MockContext.java10
-rw-r--r--tests/ActivityManagerPerfTests/stub-app/Android.bp68
-rw-r--r--tests/ActivityManagerPerfTests/stub-app/AndroidManifest.xml54
-rw-r--r--tests/ActivityManagerPerfTests/stub-app/app1/res/values/config.xml20
-rw-r--r--tests/ActivityManagerPerfTests/stub-app/app2/res/values/config.xml20
-rw-r--r--tests/ActivityManagerPerfTests/stub-app/app3/res/values/config.xml20
-rw-r--r--tests/ActivityManagerPerfTests/stub-app/res/layout/activity_content.xml20
-rw-r--r--tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/InitService.java301
-rw-r--r--tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/TestActivity.java86
-rw-r--r--tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/TestBroadcastReceiver.java32
-rw-r--r--tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/TestContentProvider.java62
-rw-r--r--tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/TestService.java71
-rw-r--r--tests/ActivityManagerPerfTests/tests/AndroidTest.xml5
-rw-r--r--tests/ActivityManagerPerfTests/tests/src/com/android/frameworks/perftests/am/tests/OomAdjPerfTest.java241
-rw-r--r--tests/ActivityManagerPerfTests/tests/src/com/android/frameworks/perftests/am/util/AtraceUtils.java108
-rw-r--r--tests/ActivityManagerPerfTests/tests/src/com/android/frameworks/perftests/am/util/TargetPackageUtils.java170
-rw-r--r--tests/ActivityManagerPerfTests/utils/Android.bp1
-rw-r--r--tests/ActivityManagerPerfTests/utils/src/com/android/frameworks/perftests/am/util/Constants.java29
-rw-r--r--tests/ActivityManagerPerfTests/utils/src/com/android/frameworks/perftests/am/util/ICommandReceiver.aidl (renamed from core/java/android/service/sms/IFinancialSmsService.aidl)18
-rw-r--r--tests/ApkVerityTest/Android.bp6
-rw-r--r--tests/ApkVerityTest/AndroidTest.xml2
-rw-r--r--tests/ManagedProfileLifecycleStressTest/app/DummyDPC/Android.bp1
-rw-r--r--tests/ManagedProfileLifecycleStressTest/src/com/android/test/stress/ManagedProfileLifecycleStressTest.java2
-rw-r--r--tests/PackageWatchdog/src/com/android/server/PackageWatchdogTest.java5
-rw-r--r--tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/RollbackTest.java24
-rw-r--r--tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/StagedRollbackTest.java64
-rw-r--r--tests/RollbackTest/StagedRollbackTest/src/com/android/tests/rollback/host/StagedRollbackTest.java10
-rw-r--r--tests/net/common/java/android/net/LinkPropertiesTest.java113
-rw-r--r--tests/net/java/android/net/TcpKeepalivePacketDataTest.java2
-rw-r--r--tests/utils/testutils/Android.bp7
-rw-r--r--tools/aapt2/ResourceUtils.cpp8
-rw-r--r--tools/aapt2/java/ProguardRules.cpp20
-rw-r--r--tools/aapt2/java/ProguardRules_test.cpp19
-rwxr-xr-xtools/localedata/extract_icu_data.py7
-rw-r--r--tools/stats_log_api_gen/Android.bp14
-rw-r--r--tools/stats_log_api_gen/Collation.cpp7
-rw-r--r--tools/stats_log_api_gen/Collation.h3
-rw-r--r--tools/stats_log_api_gen/atoms_info_writer.cpp227
-rw-r--r--tools/stats_log_api_gen/atoms_info_writer.h36
-rw-r--r--tools/stats_log_api_gen/java_writer.cpp1
-rw-r--r--tools/stats_log_api_gen/main.cpp324
-rw-r--r--tools/stats_log_api_gen/utils.cpp104
-rw-r--r--tools/stats_log_api_gen/utils.h11
-rw-r--r--wifi/Android.bp87
-rw-r--r--wifi/java/android/net/wifi/IWifiManager.aidl6
-rw-r--r--wifi/java/android/net/wifi/ScanResult.java23
-rw-r--r--wifi/java/android/net/wifi/SoftApConfiguration.java88
-rw-r--r--wifi/java/android/net/wifi/WifiAnnotations.java51
-rw-r--r--wifi/java/android/net/wifi/WifiCondManager.java983
-rw-r--r--wifi/java/android/net/wifi/WifiConfiguration.java124
-rw-r--r--wifi/java/android/net/wifi/WifiEnterpriseConfig.java96
-rw-r--r--wifi/java/android/net/wifi/WifiManager.java113
-rw-r--r--wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java3
-rw-r--r--wifi/java/android/net/wifi/WifiNetworkSuggestion.java59
-rw-r--r--wifi/java/android/net/wifi/WifiScanner.java20
-rw-r--r--wifi/java/android/net/wifi/aware/DiscoverySession.java7
-rw-r--r--wifi/java/android/net/wifi/aware/WifiAwareSession.java7
-rw-r--r--wifi/java/android/net/wifi/p2p/WifiP2pConfig.java35
-rw-r--r--wifi/java/android/net/wifi/p2p/WifiP2pGroup.java7
-rw-r--r--wifi/java/android/net/wifi/p2p/WifiP2pManager.java7
-rw-r--r--wifi/java/android/net/wifi/wificond/ChannelSettings.java95
-rw-r--r--wifi/java/android/net/wifi/wificond/HiddenNetwork.java87
-rw-r--r--wifi/java/android/net/wifi/wificond/NativeScanResult.java115
-rw-r--r--wifi/java/android/net/wifi/wificond/NativeWifiClient.java82
-rw-r--r--wifi/java/android/net/wifi/wificond/PnoNetwork.java95
-rw-r--r--wifi/java/android/net/wifi/wificond/PnoSettings.java105
-rw-r--r--wifi/java/android/net/wifi/wificond/RadioChainInfo.java100
-rw-r--r--wifi/java/android/net/wifi/wificond/SingleScanSettings.java119
-rw-r--r--wifi/java/com/android/server/wifi/BaseWifiService.java16
-rw-r--r--wifi/tests/Android.mk4
-rw-r--r--wifi/tests/AndroidTest.xml2
-rwxr-xr-xwifi/tests/runtests.sh1
-rw-r--r--wifi/tests/src/android/net/wifi/SoftApConfigurationTest.java4
-rw-r--r--wifi/tests/src/android/net/wifi/WifiCondManagerTest.java1281
-rw-r--r--wifi/tests/src/android/net/wifi/WifiConfigurationTest.java40
-rw-r--r--wifi/tests/src/android/net/wifi/WifiManagerTest.java36
-rw-r--r--wifi/tests/src/android/net/wifi/WifiNetworkSuggestionTest.java82
-rw-r--r--wifi/tests/src/android/net/wifi/wificond/NativeScanResultTest.java88
-rw-r--r--wifi/tests/src/android/net/wifi/wificond/PnoSettingsTest.java112
-rw-r--r--wifi/tests/src/android/net/wifi/wificond/SingleScanSettingsTest.java117
1798 files changed, 58822 insertions, 23139 deletions
diff --git a/.clang-format b/.clang-format
new file mode 100644
index 000000000000..03af56d64062
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1,13 @@
+BasedOnStyle: Google
+
+AccessModifierOffset: -4
+AlignOperands: false
+AllowShortFunctionsOnASingleLine: Inline
+AlwaysBreakBeforeMultilineStrings: false
+ColumnLimit: 100
+CommentPragmas: NOLINT:.*
+ConstructorInitializerIndentWidth: 6
+ContinuationIndentWidth: 8
+IndentWidth: 4
+PenaltyBreakBeforeFirstCallParameter: 100000
+SpacesBeforeTrailingComments: 1
diff --git a/Android.bp b/Android.bp
index 7b6d145e14e5..bf901ec2f50c 100644
--- a/Android.bp
+++ b/Android.bp
@@ -200,19 +200,9 @@ filegroup {
}
filegroup {
- name: "framework-wifi-sources",
- srcs: [
- "wifi/java/**/*.java",
- "wifi/java/**/*.aidl",
- ],
- path: "wifi/java",
-}
-
-filegroup {
name: "framework-non-updatable-sources",
srcs: [
// Java/AIDL sources under frameworks/base
- ":framework-appsearch-sources",
":framework-blobstore-sources",
":framework-core-sources",
":framework-drm-sources",
@@ -232,7 +222,8 @@ filegroup {
":framework-telecomm-sources",
":framework-telephony-common-sources",
":framework-telephony-sources",
- ":framework-wifi-sources",
+ ":framework-wifi-annotations",
+ ":framework-wifi-non-updatable-sources",
":PacProcessor-aidl-sources",
":ProxyHandler-aidl-sources",
@@ -254,7 +245,7 @@ filegroup {
":libcamera_client_framework_aidl",
":libupdate_engine_aidl",
// TODO: this needs to be removed when statsd-framework.jar is separated out
- ":statsd_aidl",
+ ":statsd_java_aidl",
":storaged_aidl",
":vold_aidl",
@@ -270,8 +261,11 @@ filegroup {
filegroup {
name: "framework-updatable-sources",
srcs: [
+ ":framework-appsearch-sources",
":framework-sdkext-sources",
+ ":framework-statsd-sources",
":updatable-media-srcs",
+ ":framework-wifi-updatable-sources",
]
}
@@ -357,6 +351,9 @@ java_library {
"com.android.sysprop.apex",
"PlatformProperties",
],
+ aidl: {
+ include_dirs: ["system/connectivity/wificond/aidl"],
+ },
sdk_version: "core_platform",
installable: false,
}
@@ -379,7 +376,9 @@ java_defaults {
sdk_version: "core_platform",
libs: [
+ "app-compat-annotations",
"ext",
+ "unsupportedappusage",
"updatable_media_stubs",
],
@@ -402,7 +401,7 @@ java_defaults {
filegroup {
name: "framework-jarjar-rules",
- srcs: ["jarjar_rules_hidl.txt"],
+ srcs: ["framework-jarjar-rules.txt"],
}
filegroup {
@@ -427,7 +426,12 @@ java_library {
name: "framework-minus-apex",
defaults: ["framework-defaults"],
srcs: [":framework-non-updatable-sources"],
- libs: ["app-compat-annotations"],
+ libs: [
+ "framework-appsearch-stubs",
+ // TODO(b/146167933): Use framework-statsd-stubs
+ "framework-statsd",
+ "framework-wifi-stubs",
+ ],
installable: true,
javac_shard_size: 150,
required: [
@@ -445,6 +449,7 @@ java_library {
],
// For backwards compatibility.
stem: "framework",
+ apex_available: ["//apex_available:platform"],
}
// This "framework" module is NOT installed to the device. It's
@@ -462,9 +467,17 @@ java_library {
installable: false, // this lib is a build-only library
static_libs: [
"framework-minus-apex",
- // TODO(jiyong): add stubs for APEXes here
+ "updatable_media_stubs",
+ "framework-appsearch", // TODO(b/146218515): should be framework-appsearch-stubs
+ "framework-sdkext-stubs-systemapi",
+ // TODO(b/146167933): Use framework-statsd-stubs instead.
+ "framework-statsd",
+ // TODO(b/140299412): should be framework-wifi-stubs
+ "framework-wifi",
+ // TODO(jiyong): add more stubs for APEXes here
],
sdk_version: "core_platform",
+ apex_available: ["//apex_available:platform"],
}
java_library {
@@ -472,15 +485,18 @@ java_library {
defaults: ["framework-defaults"],
srcs: [":framework-all-sources"],
installable: false,
- libs: ["app-compat-annotations"],
- static_libs: ["exoplayer2-core"]
+ static_libs: ["exoplayer2-core"],
+ apex_available: ["//apex_available:platform"],
}
java_library {
name: "framework-annotation-proc",
defaults: ["framework-aidl-export-defaults"],
srcs: [":framework-all-sources"],
- libs: ["app-compat-annotations"],
+ libs: [
+ "app-compat-annotations",
+ "unsupportedappusage",
+ ],
installable: false,
plugins: [
"unsupportedappusage-annotation-processor",
@@ -571,6 +587,7 @@ filegroup {
"core/java/android/annotation/Nullable.java",
"core/java/android/annotation/IntDef.java",
"core/java/android/annotation/IntRange.java",
+ "core/java/android/annotation/SystemApi.java",
"core/java/android/annotation/UnsupportedAppUsage.java",
"core/java/com/android/internal/annotations/GuardedBy.java",
"core/java/com/android/internal/annotations/VisibleForTesting.java",
@@ -783,11 +800,7 @@ cc_library {
filegroup {
name: "incremental_aidl",
srcs: [
- "core/java/android/os/incremental/IIncrementalManager.aidl",
- "core/java/android/os/incremental/IIncrementalServiceProxy.aidl",
- "core/java/android/os/incremental/IncrementalDataLoaderParamsParcel.aidl",
"core/java/android/os/incremental/IncrementalFileSystemControlParcel.aidl",
- "core/java/android/os/incremental/NamedParcelFileDescriptor.aidl",
],
path: "core/java",
}
@@ -795,7 +808,20 @@ filegroup {
filegroup {
name: "dataloader_aidl",
srcs: [
+ "core/java/android/content/pm/DataLoaderParamsParcel.aidl",
+ "core/java/android/content/pm/FileSystemControlParcel.aidl",
"core/java/android/content/pm/IDataLoaderStatusListener.aidl",
+ "core/java/android/content/pm/IPackageInstallerSessionFileSystemConnector.aidl",
+ "core/java/android/content/pm/NamedParcelFileDescriptor.aidl",
+ ],
+ path: "core/java",
+}
+
+filegroup {
+ name: "incremental_manager_aidl",
+ srcs: [
+ "core/java/android/os/incremental/IIncrementalManager.aidl",
+ "core/java/android/os/incremental/IIncrementalManagerNative.aidl",
],
path: "core/java",
}
@@ -805,9 +831,6 @@ aidl_interface {
srcs: [
":incremental_aidl",
],
- imports: [
- "libdataloader_aidl",
- ],
backend: {
java: {
sdk_version: "28",
@@ -826,6 +849,9 @@ aidl_interface {
srcs: [
":dataloader_aidl",
],
+ imports: [
+ "libincremental_aidl",
+ ],
backend: {
java: {
sdk_version: "28",
@@ -834,8 +860,30 @@ aidl_interface {
enabled: true,
},
ndk: {
+ enabled: false,
+ },
+ },
+}
+
+aidl_interface {
+ name: "libincremental_manager_aidl",
+ srcs: [
+ ":incremental_manager_aidl",
+ ],
+ imports: [
+ "libincremental_aidl",
+ "libdataloader_aidl",
+ ],
+ backend: {
+ java: {
+ sdk_version: "28",
+ },
+ cpp: {
enabled: true,
},
+ ndk: {
+ enabled: false,
+ },
},
}
@@ -919,6 +967,7 @@ java_library {
"core/java/android/os/RemoteException.java",
"core/java/android/util/AndroidException.java",
],
+ libs: [ "unsupportedappusage" ],
dxflags: ["--core-library"],
installable: false,
@@ -1151,7 +1200,7 @@ droidstubs {
arg_files: [
"core/res/AndroidManifest.xml",
],
- args: metalava_framework_docs_args + " --show-annotation android.annotation.SystemApi ",
+ args: metalava_framework_docs_args + " --show-annotation android.annotation.SystemApi\\(client=android.annotation.SystemApi.Client.PRIVILEGED_APPS,process=android.annotation.SystemApi.Process.ALL\\) ",
write_sdk_values: true,
}
@@ -1462,7 +1511,7 @@ droidstubs {
merge_annotations_dirs: [
"metalava-manual",
],
- args: " --show-annotation android.annotation.SystemApi",
+ args: " --show-annotation android.annotation.SystemApi\\(client=android.annotation.SystemApi.Client.PRIVILEGED_APPS,process=android.annotation.SystemApi.Process.ALL\\)",
}
java_library_static {
@@ -1484,7 +1533,7 @@ droidstubs {
removed_dex_api_filename: "removed-dex.txt",
args: metalava_framework_docs_args +
" --show-unannotated " +
- " --show-annotation android.annotation.SystemApi " +
+ " --show-annotation android.annotation.SystemApi\\(client=android.annotation.SystemApi.Client.PRIVILEGED_APPS,process=android.annotation.SystemApi.Process.ALL\\) " +
" --show-annotation android.annotation.TestApi ",
}
@@ -1503,7 +1552,7 @@ droidstubs {
" --hide ReferencesHidden " +
" --hide UnhiddenSystemApi " +
" --show-unannotated " +
- " --show-annotation android.annotation.SystemApi " +
+ " --show-annotation android.annotation.SystemApi\\(client=android.annotation.SystemApi.Client.PRIVILEGED_APPS,process=android.annotation.SystemApi.Process.ALL\\) " +
" --show-annotation android.annotation.TestApi ",
}
@@ -1547,7 +1596,7 @@ droidstubs {
arg_files: [
"core/res/AndroidManifest.xml",
],
- args: metalava_framework_docs_args + " --show-annotation android.annotation.SystemApi",
+ args: metalava_framework_docs_args + " --show-annotation android.annotation.SystemApi\\(client=android.annotation.SystemApi.Client.PRIVILEGED_APPS,process=android.annotation.SystemApi.Process.ALL\\)",
check_api: {
current: {
api_file: "api/system-current.txt",
@@ -1644,6 +1693,8 @@ filegroup {
"core/java/android/util/LocalLog.java",
"core/java/android/util/TimeUtils.java",
"core/java/com/android/internal/os/SomeArgs.java",
+ "core/java/com/android/internal/util/AsyncChannel.java",
+ "core/java/com/android/internal/util/BitwiseInputStream.java",
"core/java/com/android/internal/util/FastXmlSerializer.java",
"core/java/com/android/internal/util/HexDump.java",
"core/java/com/android/internal/util/IState.java",
@@ -1683,7 +1734,8 @@ filegroup {
name: "framework-wifi-service-shared-srcs",
srcs: [
":framework-annotations",
- "core/java/android/os/HandlerExecutor.java",
+ "core/java/android/net/InterfaceConfiguration.java",
+ "core/java/android/os/HandlerExecutor.java",
"core/java/android/util/BackupUtils.java",
"core/java/android/util/LocalLog.java",
"core/java/android/util/Rational.java",
diff --git a/CleanSpec.mk b/CleanSpec.mk
index 8fac394a97fa..b84e71526a14 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -256,6 +256,9 @@ $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/app/CaptivePortalLogin)
$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/framework/ext.jar)
$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/telephony/java/com/google/android/mms)
$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/framework/*-service.jar)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/framework/service-statsd.jar)
+$(call add-clean-step, rm -rf $(SOONG_OUT_DIR)/.intermediates/frameworks/base/libincremental_aidl-cpp-source/)
+$(call add-clean-step, rm -rf $(SOONG_OUT_DIR)/.intermediates/frameworks/base/libincremental_manager_aidl-cpp-source/)
# ******************************************************************
# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST ABOVE THIS BANNER
# ******************************************************************
diff --git a/PREUPLOAD.cfg b/PREUPLOAD.cfg
index 68311176a783..78e72bf39586 100644
--- a/PREUPLOAD.cfg
+++ b/PREUPLOAD.cfg
@@ -1,3 +1,13 @@
+[Builtin Hooks]
+clang_format = true
+
+[Builtin Hooks Options]
+# Only turn on clang-format check for the following subfolders.
+clang_format = --commit ${PREUPLOAD_COMMIT} --style file --extensions c,h,cc,cpp
+ cmds/hid/
+ cmds/input/
+ libs/input/
+
[Hook Scripts]
checkstyle_hook = ${REPO_ROOT}/prebuilts/checkstyle/checkstyle.py --sha ${PREUPLOAD_COMMIT}
diff --git a/apct-tests/perftests/core/src/android/wm/InternalWindowOperationPerfTest.java b/apct-tests/perftests/core/src/android/wm/InternalWindowOperationPerfTest.java
index c096cd22bdba..4ed3b4e09d11 100644
--- a/apct-tests/perftests/core/src/android/wm/InternalWindowOperationPerfTest.java
+++ b/apct-tests/perftests/core/src/android/wm/InternalWindowOperationPerfTest.java
@@ -95,7 +95,7 @@ public class InternalWindowOperationPerfTest extends WindowManagerPerfTestBase {
mTraceMarkParser.forAllSlices((key, slices) -> {
for (TraceMarkSlice slice : slices) {
- state.addExtraResult(key, (long) (slice.getDurarionInSeconds() * NANOS_PER_S));
+ state.addExtraResult(key, (long) (slice.getDurationInSeconds() * NANOS_PER_S));
}
});
diff --git a/apct-tests/perftests/utils/src/android/perftests/utils/ManualBenchmarkState.java b/apct-tests/perftests/utils/src/android/perftests/utils/ManualBenchmarkState.java
index b07523976bfe..fe2b1f6443b3 100644
--- a/apct-tests/perftests/utils/src/android/perftests/utils/ManualBenchmarkState.java
+++ b/apct-tests/perftests/utils/src/android/perftests/utils/ManualBenchmarkState.java
@@ -23,11 +23,15 @@ import android.os.Bundle;
import android.util.ArrayMap;
import android.util.Log;
+import com.android.internal.util.ArrayUtils;
+
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
import java.util.concurrent.TimeUnit;
/**
@@ -140,6 +144,8 @@ public final class ManualBenchmarkState {
/** @see #addExtraResult(String, long) */
private ArrayMap<String, ArrayList<Long>> mExtraResults;
+ private final List<Long> mTmpDurations = Arrays.asList(0L);
+
// Statistics. These values will be filled when the benchmark has finished.
// The computation needs double precision, but long int is fine for final reporting.
private Stats mStats;
@@ -188,14 +194,25 @@ public final class ManualBenchmarkState {
if (duration < 0) {
throw new RuntimeException("duration is negative: " + duration);
}
+ mTmpDurations.set(0, duration);
+ return keepRunning(mTmpDurations);
+ }
+
+ /**
+ * Similar to the {@link #keepRunning(long)} but accepts a list of durations
+ */
+ public boolean keepRunning(List<Long> durations) {
switch (mState) {
case NOT_STARTED:
mState = WARMUP;
mWarmupStartTime = System.nanoTime();
return true;
case WARMUP: {
+ if (ArrayUtils.isEmpty(durations)) {
+ return true;
+ }
final long timeSinceStartingWarmup = System.nanoTime() - mWarmupStartTime;
- ++mWarmupIterations;
+ mWarmupIterations += durations.size();
if (mWarmupIterations >= WARMUP_MIN_ITERATIONS
&& timeSinceStartingWarmup >= mWarmupDurationNs) {
beginBenchmark(timeSinceStartingWarmup, mWarmupIterations);
@@ -203,7 +220,10 @@ public final class ManualBenchmarkState {
return true;
}
case RUNNING: {
- mResults.add(duration);
+ if (ArrayUtils.isEmpty(durations)) {
+ return true;
+ }
+ mResults.addAll(durations);
final boolean keepRunning = mResults.size() < mMaxIterations;
if (!keepRunning) {
mStats = new Stats(mResults);
diff --git a/apct-tests/perftests/utils/src/android/perftests/utils/TraceMarkParser.java b/apct-tests/perftests/utils/src/android/perftests/utils/TraceMarkParser.java
index 1afed3a0be5b..b15b6f61ae5d 100644
--- a/apct-tests/perftests/utils/src/android/perftests/utils/TraceMarkParser.java
+++ b/apct-tests/perftests/utils/src/android/perftests/utils/TraceMarkParser.java
@@ -40,6 +40,8 @@ public class TraceMarkParser {
private final Predicate<TraceMarkLine> mTraceLineFilter;
+ private static final long MICROS_PER_SECOND = 1000L * 1000L;
+
public TraceMarkParser(Predicate<TraceMarkLine> traceLineFilter) {
mTraceLineFilter = traceLineFilter;
}
@@ -116,13 +118,19 @@ public class TraceMarkParser {
}
}
+ public void reset() {
+ mSlicesMap.clear();
+ mDepthMap.clear();
+ mPendingStarts.clear();
+ }
+
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
forAllSlices((key, slices) -> {
double totalMs = 0;
for (TraceMarkSlice s : slices) {
- totalMs += s.getDurarionInSeconds() * 1000;
+ totalMs += s.getDurationInSeconds() * 1000;
}
sb.append(key).append(" count=").append(slices.size()).append(" avg=")
.append(totalMs / slices.size()).append("ms\n");
@@ -134,6 +142,10 @@ public class TraceMarkParser {
return sb.toString();
}
+ static double microsecondToSeconds(long ms) {
+ return (ms * 1.0d) / MICROS_PER_SECOND;
+ }
+
public static class TraceMarkSlice {
public final TraceMarkLine begin;
public final TraceMarkLine end;
@@ -143,7 +155,11 @@ public class TraceMarkParser {
this.end = end;
}
- public double getDurarionInSeconds() {
+ public double getDurationInSeconds() {
+ return microsecondToSeconds(end.timestamp - begin.timestamp);
+ }
+
+ public long getDurationInMicroseconds() {
return end.timestamp - begin.timestamp;
}
}
@@ -164,7 +180,7 @@ public class TraceMarkParser {
static final char SYNC_END = 'E';
public final String taskPid;
- public final double timestamp;
+ public final long timestamp; // in microseconds
public final String name;
public final boolean isAsync;
public final boolean isBegin;
@@ -179,7 +195,7 @@ public class TraceMarkParser {
if (timeBegin < 0) {
throw new IllegalArgumentException("Timestamp start not found");
}
- timestamp = Double.parseDouble(rawLine.substring(timeBegin, timeEnd));
+ timestamp = parseMicroseconds(rawLine.substring(timeBegin, timeEnd));
isAsync = type == ASYNC_START || type == ASYNC_FINISH;
isBegin = type == ASYNC_START || type == SYNC_BEGIN;
@@ -223,9 +239,29 @@ public class TraceMarkParser {
return null;
}
+ /**
+ * Parse the timestamp from atrace output, the format will be like:
+ * 84962.920719 where the decimal part will be always exactly 6 digits.
+ * ^^^^^ ^^^^^^
+ * | |
+ * sec microsec
+ */
+ static long parseMicroseconds(String line) {
+ int end = line.length();
+ long t = 0;
+ for (int i = 0; i < end; i++) {
+ char c = line.charAt(i);
+ if (c >= '0' && c <= '9') {
+ t = t * 10 + (c - '0');
+ }
+ }
+ return t;
+ }
+
@Override
public String toString() {
- return "TraceMarkLine{pid=" + taskPid + " time=" + timestamp + " name=" + name
+ return "TraceMarkLine{pid=" + taskPid + " time="
+ + microsecondToSeconds(timestamp) + " name=" + name
+ " async=" + isAsync + " begin=" + isBegin + "}";
}
}
diff --git a/apex/Android.bp b/apex/Android.bp
new file mode 100644
index 000000000000..56f7db2c8dad
--- /dev/null
+++ b/apex/Android.bp
@@ -0,0 +1,42 @@
+// Copyright (C) 2019 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.
+
+mainline_stubs_args =
+ "--error UnhiddenSystemApi " +
+ "--hide BroadcastBehavior " +
+ "--hide DeprecationMismatch " +
+ "--hide HiddenSuperclass " +
+ "--hide HiddenTypedefConstant " +
+ "--hide HiddenTypeParameter " +
+ "--hide MissingPermission " +
+ "--hide RequiresPermission " +
+ "--hide SdkConstant " +
+ "--hide Todo " +
+ "--hide Typo " +
+ "--hide UnavailableSymbol "
+
+// TODO: remove this server classes are cleaned up.
+mainline_stubs_args += "--hide-package com.android.server "
+
+stubs_defaults {
+ name: "framework-module-stubs-defaults-publicapi",
+ args: mainline_stubs_args,
+ installable: false,
+}
+
+stubs_defaults {
+ name: "framework-module-stubs-defaults-systemapi",
+ args: mainline_stubs_args + " --show-annotation android.annotation.SystemApi\\(client=android.annotation.SystemApi.Client.PRIVILEGED_APPS,process=android.annotation.SystemApi.Process.ALL\\) ",
+ installable: false,
+}
diff --git a/apex/appsearch/Android.bp b/apex/appsearch/Android.bp
index bcdcc7da8070..b014fdcb3df3 100644
--- a/apex/appsearch/Android.bp
+++ b/apex/appsearch/Android.bp
@@ -14,9 +14,11 @@
apex {
name: "com.android.appsearch",
-
manifest: "apex_manifest.json",
-
+ java_libs: [
+ "framework-appsearch",
+ "service-appsearch",
+ ],
key: "com.android.appsearch.key",
certificate: ":com.android.appsearch.certificate",
}
diff --git a/apex/appsearch/framework/Android.bp b/apex/appsearch/framework/Android.bp
index 0a65f7320d8a..3dc5a2c10b6b 100644
--- a/apex/appsearch/framework/Android.bp
+++ b/apex/appsearch/framework/Android.bp
@@ -23,17 +23,52 @@ filegroup {
java_library {
name: "framework-appsearch",
- installable: false,
- sdk_version: "core_platform",
- srcs: [
- ":framework-appsearch-sources",
- ],
- aidl: {
- export_include_dirs: [
- "java",
- ],
- },
+ installable: true,
+ sdk_version: "core_platform", // TODO(b/146218515) should be core_current
+ srcs: [":framework-appsearch-sources"],
libs: [
- "framework-minus-apex",
+ "framework-minus-apex", // TODO(b/146218515) should be framework-system-stubs
],
}
+
+metalava_appsearch_docs_args =
+ "--hide-package com.android.server " +
+ "--error UnhiddenSystemApi " +
+ "--hide RequiresPermission " +
+ "--hide MissingPermission " +
+ "--hide BroadcastBehavior " +
+ "--hide HiddenSuperclass " +
+ "--hide DeprecationMismatch " +
+ "--hide UnavailableSymbol " +
+ "--hide SdkConstant " +
+ "--hide HiddenTypeParameter " +
+ "--hide Todo --hide Typo " +
+ "--hide HiddenTypedefConstant " +
+ "--show-annotation android.annotation.SystemApi "
+
+droidstubs {
+ name: "framework-appsearch-stubs-srcs",
+ srcs: [
+ ":framework-annotations",
+ ":framework-appsearch-sources",
+ ],
+ aidl: {
+ include_dirs: ["frameworks/base/core/java"],
+ },
+ args: metalava_appsearch_docs_args,
+ sdk_version: "core_current",
+ libs: ["android_system_stubs_current"],
+}
+
+java_library {
+ name: "framework-appsearch-stubs",
+ srcs: [":framework-appsearch-stubs-srcs"],
+ aidl: {
+ export_include_dirs: [
+ "java",
+ ],
+ },
+ sdk_version: "core_current",
+ libs: ["android_system_stubs_current"],
+ installable: false,
+}
diff --git a/apex/appsearch/framework/java/android/app/appsearch/AppSearchManagerFrameworkInitializer.java b/apex/appsearch/framework/java/android/app/appsearch/AppSearchManagerFrameworkInitializer.java
index fcebe3d9cf3c..02cc967e7daf 100644
--- a/apex/appsearch/framework/java/android/app/appsearch/AppSearchManagerFrameworkInitializer.java
+++ b/apex/appsearch/framework/java/android/app/appsearch/AppSearchManagerFrameworkInitializer.java
@@ -15,19 +15,25 @@
*/
package android.app.appsearch;
+import android.annotation.SystemApi;
import android.app.SystemServiceRegistry;
import android.content.Context;
/**
- * This is where the AppSearchManagerService wrapper is registered.
+ * Class holding initialization code for the AppSearch module.
*
- * TODO(b/142567528): add comments when implement this class
* @hide
*/
+@SystemApi
public class AppSearchManagerFrameworkInitializer {
+ private AppSearchManagerFrameworkInitializer() {}
/**
- * TODO(b/142567528): add comments when implement this class
+ * Called by {@link SystemServiceRegistry}'s static initializer and registers all AppSearch
+ * services to {@link Context}, so that {@link Context#getSystemService} can return them.
+ *
+ * @throws IllegalStateException if this is called from anywhere besides
+ * {@link SystemServiceRegistry}
*/
public static void initialize() {
SystemServiceRegistry.registerStaticService(
diff --git a/apex/jobscheduler/service/java/com/android/server/job/JobConcurrencyManager.java b/apex/jobscheduler/service/java/com/android/server/job/JobConcurrencyManager.java
index 525fbaedc140..435384dd2319 100644
--- a/apex/jobscheduler/service/java/com/android/server/job/JobConcurrencyManager.java
+++ b/apex/jobscheduler/service/java/com/android/server/job/JobConcurrencyManager.java
@@ -372,9 +372,10 @@ class JobConcurrencyManager {
continue;
}
- // TODO lastEvaluatedPriority should be evaluateJobPriorityLocked. (double check it)
- if (minPriorityForPreemption > nextPending.lastEvaluatedPriority) {
- minPriorityForPreemption = nextPending.lastEvaluatedPriority;
+ if (minPriorityForPreemption > jobPriority) {
+ // Step down the preemption threshold - wind up replacing
+ // the lowest-priority running job
+ minPriorityForPreemption = jobPriority;
selectedContextId = j;
// In this case, we're just going to preempt a low priority job, we're not
// actually starting a job, so don't set startingJob.
diff --git a/apex/sdkext/Android.bp b/apex/sdkext/Android.bp
index aaf25b1d40bb..5369a96d965c 100644
--- a/apex/sdkext/Android.bp
+++ b/apex/sdkext/Android.bp
@@ -12,6 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+package {
+ default_visibility: [":__subpackages__"],
+}
+
apex {
name: "com.android.sdkext",
manifest: "manifest.json",
@@ -19,12 +23,18 @@ apex {
java_libs: [ "framework-sdkext" ],
prebuilts: [
"com.android.sdkext.ldconfig",
+ "cur_sdkinfo",
"derive_sdk.rc",
],
key: "com.android.sdkext.key",
certificate: ":com.android.sdkext.certificate",
}
+sdk {
+ name: "sdkext-sdk",
+ java_libs: [ "framework-sdkext-stubs-systemapi" ],
+}
+
apex_key {
name: "com.android.sdkext.key",
public_key: "com.android.sdkext.avbpubkey",
@@ -42,3 +52,33 @@ prebuilt_etc {
filename: "ld.config.txt",
installable: false,
}
+
+python_binary_host {
+ name: "gen_sdkinfo",
+ srcs: [
+ "sdk.proto",
+ "gen_sdkinfo.py",
+ ],
+ proto: {
+ canonical_path_from_root: false,
+ },
+ version: {
+ py3: {
+ embedded_launcher: true,
+ },
+ },
+}
+
+gensrcs {
+ name: "cur_sdkinfo_src",
+ srcs: [""],
+ tools: [ "gen_sdkinfo" ],
+ cmd: "$(location) -v 0 -o $(out)",
+}
+
+prebuilt_etc {
+ name: "cur_sdkinfo",
+ src: ":cur_sdkinfo_src",
+ filename: "sdkinfo.binarypb",
+ installable: false,
+}
diff --git a/apex/sdkext/TEST_MAPPING b/apex/sdkext/TEST_MAPPING
index 8dc732d36c79..91947f39980a 100644
--- a/apex/sdkext/TEST_MAPPING
+++ b/apex/sdkext/TEST_MAPPING
@@ -1,7 +1,7 @@
{
"presubmit": [
{
- "name": "framework-sdkext-tests"
+ "name": "CtsSdkExtTestCases"
}
]
}
diff --git a/apex/sdkext/derive_sdk/derive_sdk.cpp b/apex/sdkext/derive_sdk/derive_sdk.cpp
index 0aacebefaaca..7536def60767 100644
--- a/apex/sdkext/derive_sdk/derive_sdk.cpp
+++ b/apex/sdkext/derive_sdk/derive_sdk.cpp
@@ -68,7 +68,7 @@ int main(int, char**) {
auto itr = std::min_element(versions.begin(), versions.end());
std::string prop_value = itr == versions.end() ? "0" : std::to_string(*itr);
- if (!android::base::SetProperty("persist.com.android.sdkext.sdk_info", prop_value)) {
+ if (!android::base::SetProperty("ro.build.version.extensions.r", prop_value)) {
LOG(ERROR) << "failed to set sdk_info prop";
return EXIT_FAILURE;
}
diff --git a/apex/sdkext/framework/Android.bp b/apex/sdkext/framework/Android.bp
index b17f0f84d6fa..a50dc3d4f349 100644
--- a/apex/sdkext/framework/Android.bp
+++ b/apex/sdkext/framework/Android.bp
@@ -12,12 +12,17 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+package {
+ default_visibility: [ ":__pkg__" ]
+}
+
filegroup {
name: "framework-sdkext-sources",
srcs: [
"java/**/*.java",
],
path: "java",
+ visibility: [ "//frameworks/base:__pkg__" ] // For the "global" stubs.
}
java_library {
@@ -27,4 +32,40 @@ java_library {
libs: [ "framework-annotations-lib" ],
permitted_packages: [ "android.os.ext" ],
installable: true,
+ visibility: [ "//frameworks/base/apex/sdkext:__pkg__" ],
+}
+
+droidstubs {
+ name: "framework-sdkext-droidstubs-publicapi",
+ defaults: [
+ "framework-sdkext-stubs-defaults",
+ "framework-module-stubs-defaults-publicapi",
+ ]
+}
+
+droidstubs {
+ name: "framework-sdkext-droidstubs-systemapi",
+ defaults: [
+ "framework-sdkext-stubs-defaults",
+ "framework-module-stubs-defaults-systemapi",
+ ]
+}
+
+stubs_defaults {
+ name: "framework-sdkext-stubs-defaults",
+ srcs: [
+ ":framework-sdkext-sources",
+ ":framework-annotations",
+ ],
+ sdk_version: "system_current",
+}
+
+java_library {
+ name: "framework-sdkext-stubs-systemapi",
+ srcs: [":framework-sdkext-droidstubs-systemapi"],
+ sdk_version: "system_current",
+ visibility: [
+ "//frameworks/base:__pkg__", // Framework
+ "//frameworks/base/apex/sdkext:__pkg__", // sdkext SDK
+ ]
}
diff --git a/apex/sdkext/framework/java/android/os/ext/SdkExtensions.java b/apex/sdkext/framework/java/android/os/ext/SdkExtensions.java
index c039a820fc04..a8a7effa9b6c 100644
--- a/apex/sdkext/framework/java/android/os/ext/SdkExtensions.java
+++ b/apex/sdkext/framework/java/android/os/ext/SdkExtensions.java
@@ -17,25 +17,40 @@
package android.os.ext;
import android.annotation.IntDef;
+import android.annotation.SystemApi;
import android.os.Build.VERSION_CODES;
import android.os.SystemProperties;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
-/** @hide */
+/**
+ * Methods for interacting with the extension SDK.
+ *
+ * This class provides information about the extension SDK version present
+ * on this device. Use the {@link #getExtensionVersion(int) getExtension} to
+ * query for the extension version for the given SDK version.
+
+ * @hide
+ */
+@SystemApi
public class SdkExtensions {
private static final int R_EXTENSION_INT;
static {
- R_EXTENSION_INT = SystemProperties.getInt("persist.com.android.sdkext.sdk_info", 0);
+ R_EXTENSION_INT = SystemProperties.getInt("ro.build.version.extensions.r", 0);
}
- /** Values suitable as parameters for {@link #getExtensionVersion(int)}. */
+ /**
+ * Values suitable as parameters for {@link #getExtensionVersion(int)}.
+ * @hide
+ */
@IntDef(value = { VERSION_CODES.R })
@Retention(RetentionPolicy.SOURCE)
public @interface SdkVersion {}
+ private SdkExtensions() { }
+
/**
* Return the version of the extension to the given SDK.
*
@@ -45,7 +60,7 @@ public class SdkExtensions {
*/
public static int getExtensionVersion(@SdkVersion int sdk) {
if (sdk < VERSION_CODES.R) {
- throw new IllegalArgumentException();
+ throw new IllegalArgumentException(String.valueOf(sdk) + " does not have extensions");
}
return R_EXTENSION_INT;
}
diff --git a/apex/sdkext/framework/tests/Android.bp b/apex/sdkext/framework/tests/Android.bp
deleted file mode 100644
index ab6327582efd..000000000000
--- a/apex/sdkext/framework/tests/Android.bp
+++ /dev/null
@@ -1,11 +0,0 @@
-android_test {
- name: "framework-sdkext-tests",
- srcs: ["src/**/*.java"],
- libs: [
- "android.test.base",
- "android.test.runner",
- ],
- static_libs: [ "framework-sdkext" ],
- test_suites: [ "general-tests" ],
- platform_apis: true,
-}
diff --git a/apex/sdkext/gen_sdkinfo.py b/apex/sdkext/gen_sdkinfo.py
new file mode 100644
index 000000000000..5af478ba7fe6
--- /dev/null
+++ b/apex/sdkext/gen_sdkinfo.py
@@ -0,0 +1,19 @@
+import sdk_pb2
+import sys
+
+if __name__ == '__main__':
+ argv = sys.argv[1:]
+ if not len(argv) == 4 or sorted([argv[0], argv[2]]) != ['-o', '-v']:
+ print('usage: gen_sdkinfo -v <version> -o <output-file>')
+ sys.exit(1)
+
+ for i in range(len(argv)):
+ if sys.argv[i] == '-o':
+ filename = sys.argv[i+1]
+ if sys.argv[i] == '-v':
+ version = int(sys.argv[i+1])
+
+ proto = sdk_pb2.SdkVersion()
+ proto.version = version
+ with open(filename, 'wb') as f:
+ f.write(proto.SerializeToString())
diff --git a/apex/sdkext/sdk.proto b/apex/sdkext/sdk.proto
new file mode 100644
index 000000000000..d15b93552ff4
--- /dev/null
+++ b/apex/sdkext/sdk.proto
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+syntax = "proto3";
+package com.android.sdkext.proto;
+
+option java_outer_classname = "SdkProto";
+option optimize_for = LITE_RUNTIME;
+
+message SdkVersion {
+ int32 version = 1;
+}
diff --git a/apex/statsd/Android.bp b/apex/statsd/Android.bp
index d76a40e9e26d..09ca1d257460 100644
--- a/apex/statsd/Android.bp
+++ b/apex/statsd/Android.bp
@@ -14,20 +14,20 @@
apex {
name: "com.android.os.statsd",
-
+ defaults: ["com.android.os.statsd-defaults"],
manifest: "apex_manifest.json",
+}
- // optional. if unspecified, a default one is auto-generated
- //androidManifest: "AndroidManifest.xml",
-
+apex_defaults {
// libc.so and libcutils.so are included in the apex
// native_shared_libs: ["libc", "libcutils"],
// binaries: ["vold"],
- // java_libs: ["core-all"],
+ java_libs: [
+ "framework-statsd",
+ "service-statsd",
+ ],
// prebuilts: ["my_prebuilt"],
-
- compile_multilib: "both",
-
+ name: "com.android.os.statsd-defaults",
key: "com.android.os.statsd.key",
certificate: ":com.android.os.statsd.certificate",
}
diff --git a/apex/statsd/aidl/Android.bp b/apex/statsd/aidl/Android.bp
index e6ca544c04be..aed6ad9fc08a 100644
--- a/apex/statsd/aidl/Android.bp
+++ b/apex/statsd/aidl/Android.bp
@@ -17,6 +17,18 @@
// TODO(b/145815909): move StatsDimensionsValue.aidl and StatsLogEventWrapper.aidl here
filegroup {
name: "statsd_aidl",
+ srcs: [
+ "android/os/IPullAtomCallback.aidl",
+ "android/os/IPullAtomResultReceiver.aidl",
+ "android/os/IStatsCompanionService.aidl",
+ "android/os/IStatsd.aidl",
+ "android/os/IStatsPullerCallback.aidl",
+ "android/util/StatsEventParcel.aidl",
+ ],
+}
+
+filegroup {
+ name: "statsd_java_aidl",
srcs: ["**/*.aidl"],
}
diff --git a/apex/statsd/aidl/android/os/IStatsManagerService.aidl b/apex/statsd/aidl/android/os/IStatsManagerService.aidl
new file mode 100644
index 000000000000..45ba3a21ed5b
--- /dev/null
+++ b/apex/statsd/aidl/android/os/IStatsManagerService.aidl
@@ -0,0 +1,65 @@
+/**
+ * Copyright (c) 2019, 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.os;
+
+import android.app.PendingIntent;
+
+/**
+ * Binder interface to communicate with the Java-based statistics service helper.
+ * Contains parcelable objects available only in Java.
+ * {@hide}
+ */
+interface IStatsManagerService {
+
+ /**
+ * Registers the given pending intent for this config key. This intent is invoked when the
+ * memory consumed by the metrics for this configuration approach the pre-defined limits. There
+ * can be at most one listener per config key.
+ *
+ * Requires Manifest.permission.DUMP.
+ */
+ void setDataFetchOperation(long configKey, in PendingIntent pendingIntent,
+ in String packageName);
+
+ /**
+ * Registers the given pending intent for this packagename. This intent is invoked when the
+ * active status of any of the configs sent by this package changes and will contain a list of
+ * config ids that are currently active. It also returns the list of configs that are currently
+ * active. There can be at most one active configs changed listener per package.
+ *
+ * Requires Manifest.permission.DUMP and Manifest.permission.PACKAGE_USAGE_STATS.
+ */
+ long[] setActiveConfigsChangedOperation(in PendingIntent pendingIntent, in String packageName);
+
+ /**
+ * Set the PendingIntent to be used when broadcasting subscriber
+ * information to the given subscriberId within the given config.
+ *
+ * Suppose that the calling uid has added a config with key configKey, and that in this config
+ * it is specified that when a particular anomaly is detected, a broadcast should be sent to
+ * a BroadcastSubscriber with id subscriberId. This function links the given pendingIntent with
+ * that subscriberId (for that config), so that this pendingIntent is used to send the broadcast
+ * when the anomaly is detected.
+ *
+ * This function can only be called by the owner (uid) of the config. It must be called each
+ * time statsd starts. Later calls overwrite previous calls; only one PendingIntent is stored.
+ *
+ * Requires Manifest.permission.DUMP.
+ */
+ void setBroadcastSubscriber(long configKey, long subscriberId, in PendingIntent pendingIntent,
+ in String packageName);
+} \ No newline at end of file
diff --git a/apex/statsd/aidl/android/os/IStatsManager.aidl b/apex/statsd/aidl/android/os/IStatsd.aidl
index cc62f07a3750..cffc6ce6e4df 100644
--- a/apex/statsd/aidl/android/os/IStatsManager.aidl
+++ b/apex/statsd/aidl/android/os/IStatsd.aidl
@@ -24,7 +24,7 @@ import android.os.ParcelFileDescriptor;
* Binder interface to communicate with the statistics management service.
* {@hide}
*/
-interface IStatsManager {
+interface IStatsd {
/**
* Tell the stats daemon that the android system server is up and running.
*/
diff --git a/apex/statsd/framework/Android.bp b/apex/statsd/framework/Android.bp
new file mode 100644
index 000000000000..37b07a6380aa
--- /dev/null
+++ b/apex/statsd/framework/Android.bp
@@ -0,0 +1,67 @@
+// Copyright (C) 2019 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.
+
+filegroup {
+ name: "framework-statsd-sources",
+ srcs: [
+ "java/**/*.java",
+ ],
+ path: "java",
+}
+
+java_library {
+ name: "framework-statsd",
+ installable: true,
+ // TODO(b/146209659): Use system_current instead.
+ sdk_version: "core_platform",
+ srcs: [
+ ":framework-statsd-sources",
+ ],
+ permitted_packages: [
+ "android.app",
+ "android.util",
+ ],
+ libs: [
+ "framework-annotations-lib",
+ // TODO(b/146230220): Use framework-system-stubs instead.
+ "android_system_stubs_current",
+ ],
+ // TODO:(b/146210774): Add apex_available field.
+}
+
+droidstubs {
+ name: "framework-statsd-stubs-docs",
+ defaults: [
+ "framework-module-stubs-defaults-publicapi"
+ ],
+ srcs: [
+ ":framework-statsd-sources",
+ ],
+ libs: [
+ "framework-all",
+ ],
+ sdk_version: "core_platform",
+}
+
+// TODO(b/146167933): Use these stubs in frameworks/base/Android.bp
+java_library {
+ name: "framework-statsd-stubs",
+ srcs: [
+ ":framework-statsd-stubs-docs",
+ ],
+ libs: [
+ "framework-all",
+ ],
+ sdk_version: "core_platform",
+}
diff --git a/core/java/android/util/StatsEvent.java b/apex/statsd/framework/java/android/util/StatsEvent.java
index 7e7164042781..c7659457bdf9 100644
--- a/core/java/android/util/StatsEvent.java
+++ b/apex/statsd/framework/java/android/util/StatsEvent.java
@@ -31,14 +31,23 @@ import com.android.internal.annotations.VisibleForTesting;
*
* <p>Usage:</p>
* <pre>
+ * // Pushed event
* StatsEvent statsEvent = StatsEvent.newBuilder()
* .setAtomId(atomId)
* .writeBoolean(false)
* .writeString("annotated String field")
* .addBooleanAnnotation(annotationId, true)
+ * .usePooledBuffer()
* .build();
- *
* StatsLog.write(statsEvent);
+ *
+ * // Pulled event
+ * StatsEvent statsEvent = StatsEvent.newBuilder()
+ * .setAtomId(atomId)
+ * .writeBoolean(false)
+ * .writeString("annotated String field")
+ * .addBooleanAnnotation(annotationId, true)
+ * .build();
* </pre>
* @hide
**/
@@ -210,12 +219,15 @@ public final class StatsEvent {
private static final int MAX_PAYLOAD_SIZE = LOGGER_ENTRY_MAX_PAYLOAD - 4;
private final int mAtomId;
- private final Buffer mBuffer;
+ private final byte[] mPayload;
+ private Buffer mBuffer;
private final int mNumBytes;
- private StatsEvent(final int atomId, @NonNull final Buffer buffer, final int numBytes) {
+ private StatsEvent(final int atomId, @Nullable final Buffer buffer,
+ @NonNull final byte[] payload, final int numBytes) {
mAtomId = atomId;
mBuffer = buffer;
+ mPayload = payload;
mNumBytes = numBytes;
}
@@ -243,7 +255,7 @@ public final class StatsEvent {
**/
@NonNull
public byte[] getBytes() {
- return mBuffer.getBytes();
+ return mPayload;
}
/**
@@ -256,10 +268,14 @@ public final class StatsEvent {
}
/**
- * Recycle this StatsEvent object.
+ * Recycle resources used by this StatsEvent object.
+ * No actions should be taken on this StatsEvent after release() is called.
**/
public void release() {
- mBuffer.release();
+ if (mBuffer != null) {
+ mBuffer.release();
+ mBuffer = null;
+ }
}
/**
@@ -280,7 +296,18 @@ public final class StatsEvent {
* optional string field3 = 3 [(annotation1) = true];
* }
*
- * // StatsEvent construction.
+ * // StatsEvent construction for pushed event.
+ * StatsEvent.newBuilder()
+ * StatsEvent statsEvent = StatsEvent.newBuilder()
+ * .setAtomId(atomId)
+ * .writeInt(3) // field1
+ * .writeLong(8L) // field2
+ * .writeString("foo") // field 3
+ * .addBooleanAnnotation(annotation1Id, true)
+ * .usePooledBuffer()
+ * .build();
+ *
+ * // StatsEvent construction for pulled event.
* StatsEvent.newBuilder()
* StatsEvent statsEvent = StatsEvent.newBuilder()
* .setAtomId(atomId)
@@ -306,6 +333,7 @@ public final class StatsEvent {
private byte mLastType;
private int mNumElements;
private int mErrorMask;
+ private boolean mUsePooledBuffer = false;
private Builder(final Buffer buffer) {
mBuffer = buffer;
@@ -569,6 +597,17 @@ public final class StatsEvent {
}
/**
+ * Indicates to reuse Buffer's byte array as the underlying payload in StatsEvent.
+ * This should be called for pushed events to reduce memory allocations and garbage
+ * collections.
+ **/
+ @NonNull
+ public Builder usePooledBuffer() {
+ mUsePooledBuffer = true;
+ return this;
+ }
+
+ /**
* Builds a StatsEvent object with values entered in this Builder.
**/
@NonNull
@@ -599,7 +638,18 @@ public final class StatsEvent {
size = mPos;
}
- return new StatsEvent(mAtomId, mBuffer, size);
+ if (mUsePooledBuffer) {
+ return new StatsEvent(mAtomId, mBuffer, mBuffer.getBytes(), size);
+ } else {
+ // Create a copy of the buffer with the required number of bytes.
+ final byte[] payload = new byte[size];
+ System.arraycopy(mBuffer.getBytes(), 0, payload, 0, size);
+
+ // Return Buffer instance to the pool.
+ mBuffer.release();
+
+ return new StatsEvent(mAtomId, null, payload, size);
+ }
}
private void writeTypeId(final byte typeId) {
diff --git a/apex/statsd/service/Android.bp b/apex/statsd/service/Android.bp
index f71d74fa03ff..f3a8989e633a 100644
--- a/apex/statsd/service/Android.bp
+++ b/apex/statsd/service/Android.bp
@@ -1,5 +1,5 @@
// Statsd Service jar, which will eventually be put in the statsd mainline apex.
-// service-statsd needs to be added to PRODUCT_SYSTEM_SERVER_JARS.
+// service-statsd needs to be added to PRODUCT_UPDATABLE_SYSTEM_SERVER_JARS.
// This jar will contain StatsCompanionService
java_library {
name: "service-statsd",
@@ -8,9 +8,9 @@ java_library {
srcs: [
"java/**/*.java",
],
-
+ // TODO: link against the proper stubs (b/146084685).
libs: [
- "framework",
+ "framework-minus-apex",
"services.core",
],
}
diff --git a/apex/statsd/service/java/com/android/server/stats/StatsCompanion.java b/apex/statsd/service/java/com/android/server/stats/StatsCompanion.java
new file mode 100644
index 000000000000..71b52e26b7db
--- /dev/null
+++ b/apex/statsd/service/java/com/android/server/stats/StatsCompanion.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.stats;
+
+import android.content.Context;
+import android.util.Slog;
+
+import com.android.server.SystemService;
+
+/**
+ * @hide
+ */
+public class StatsCompanion {
+ private static final String TAG = "StatsCompanion";
+ private static final boolean DEBUG = false;
+
+ /**
+ * Lifecycle class for both {@link StatsCompanionService} and {@link StatsManagerService}.
+ */
+ public static final class Lifecycle extends SystemService {
+ private StatsCompanionService mStatsCompanionService;
+ private StatsManagerService mStatsManagerService;
+
+ public Lifecycle(Context context) {
+ super(context);
+ }
+
+ @Override
+ public void onStart() {
+ mStatsCompanionService = new StatsCompanionService(getContext());
+ mStatsManagerService = new StatsManagerService(getContext());
+ mStatsCompanionService.setStatsManagerService(mStatsManagerService);
+ mStatsManagerService.setStatsCompanionService(mStatsCompanionService);
+
+ try {
+ publishBinderService(Context.STATS_COMPANION_SERVICE,
+ mStatsCompanionService);
+ if (DEBUG) Slog.d(TAG, "Published " + Context.STATS_COMPANION_SERVICE);
+ publishBinderService(Context.STATS_MANAGER_SERVICE,
+ mStatsManagerService);
+ if (DEBUG) Slog.d(TAG, "Published " + Context.STATS_MANAGER_SERVICE);
+ } catch (Exception e) {
+ Slog.e(TAG, "Failed to publishBinderService", e);
+ }
+ }
+
+ @Override
+ public void onBootPhase(int phase) {
+ super.onBootPhase(phase);
+ if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
+ mStatsCompanionService.systemReady();
+ mStatsManagerService.systemReady();
+ }
+ }
+ }
+}
diff --git a/apex/statsd/service/java/com/android/server/stats/StatsCompanionService.java b/apex/statsd/service/java/com/android/server/stats/StatsCompanionService.java
index 6fb3bc47859d..7c25c6c9f029 100644
--- a/apex/statsd/service/java/com/android/server/stats/StatsCompanionService.java
+++ b/apex/statsd/service/java/com/android/server/stats/StatsCompanionService.java
@@ -79,7 +79,7 @@ import android.os.HandlerThread;
import android.os.IBinder;
import android.os.IPullAtomCallback;
import android.os.IStatsCompanionService;
-import android.os.IStatsManager;
+import android.os.IStatsd;
import android.os.IStoraged;
import android.os.IThermalEventListener;
import android.os.IThermalService;
@@ -137,7 +137,6 @@ import com.android.internal.os.StoragedUidIoStatsReader;
import com.android.internal.util.DumpUtils;
import com.android.server.BinderCallsStatsService;
import com.android.server.LocalServices;
-import com.android.server.SystemService;
import com.android.server.SystemServiceManager;
import com.android.server.am.MemoryStatUtil.MemoryStat;
import com.android.server.notification.NotificationManagerService;
@@ -173,6 +172,7 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
+import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@@ -268,7 +268,7 @@ public class StatsCompanionService extends IStatsCompanionService.Stub {
private final AlarmManager mAlarmManager;
private final INetworkStatsService mNetworkStatsService;
@GuardedBy("sStatsdLock")
- private static IStatsManager sStatsd;
+ private static IStatsd sStatsd;
private static final Object sStatsdLock = new Object();
private final OnAlarmListener mAnomalyAlarmListener = new AnomalyAlarmListener();
@@ -278,6 +278,8 @@ public class StatsCompanionService extends IStatsCompanionService.Stub {
private final BroadcastReceiver mUserUpdateReceiver;
private final ShutdownEventReceiver mShutdownEventReceiver;
+ private StatsManagerService mStatsManagerService;
+
private static final class PullerKey {
private final int mUid;
private final int mAtomTag;
@@ -2135,8 +2137,8 @@ public class StatsCompanionService extends IStatsCompanionService.Stub {
pulledData.add(e);
}
- private void pullDangerousPermissionState(long elapsedNanos, final long wallClockNanos,
- List<StatsLogEventWrapper> pulledData) {
+ private void pullDangerousPermissionState(int atomId, long elapsedNanos,
+ final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
long token = Binder.clearCallingIdentity();
Set<Integer> reportedUids = new HashSet<>();
try {
@@ -2165,6 +2167,11 @@ public class StatsCompanionService extends IStatsCompanionService.Stub {
}
reportedUids.add(pkg.applicationInfo.uid);
+ if (atomId == StatsLog.DANGEROUS_PERMISSION_STATE_SAMPLED
+ && ThreadLocalRandom.current().nextFloat() > 0.2f) {
+ continue;
+ }
+
int numPerms = pkg.requestedPermissions.length;
for (int permNum = 0; permNum < numPerms; permNum++) {
String permName = pkg.requestedPermissions[permNum];
@@ -2174,7 +2181,7 @@ public class StatsCompanionService extends IStatsCompanionService.Stub {
try {
permissionInfo = pm.getPermissionInfo(permName, 0);
permissionFlags =
- pm.getPermissionFlags(permName, pkg.packageName, user);
+ pm.getPermissionFlags(permName, pkg.packageName, user);
} catch (PackageManager.NameNotFoundException ignored) {
continue;
@@ -2185,11 +2192,13 @@ public class StatsCompanionService extends IStatsCompanionService.Stub {
}
StatsLogEventWrapper e = new StatsLogEventWrapper(
- StatsLog.DANGEROUS_PERMISSION_STATE, elapsedNanos, wallClockNanos);
+ atomId, elapsedNanos, wallClockNanos);
e.writeString(permName);
e.writeInt(pkg.applicationInfo.uid);
- e.writeString(null);
+ if (atomId == StatsLog.DANGEROUS_PERMISSION_STATE) {
+ e.writeString(null);
+ }
e.writeBoolean((pkg.requestedPermissionsFlags[permNum]
& REQUESTED_PERMISSION_GRANTED) != 0);
e.writeInt(permissionFlags);
@@ -2639,7 +2648,13 @@ public class StatsCompanionService extends IStatsCompanionService.Stub {
break;
}
case StatsLog.DANGEROUS_PERMISSION_STATE: {
- pullDangerousPermissionState(elapsedNanos, wallClockNanos, ret);
+ pullDangerousPermissionState(StatsLog.DANGEROUS_PERMISSION_STATE, elapsedNanos,
+ wallClockNanos, ret);
+ break;
+ }
+ case StatsLog.DANGEROUS_PERMISSION_STATE_SAMPLED: {
+ pullDangerousPermissionState(StatsLog.DANGEROUS_PERMISSION_STATE_SAMPLED,
+ elapsedNanos, wallClockNanos, ret);
break;
}
case StatsLog.TIME_ZONE_DATA_INFO: {
@@ -2681,6 +2696,7 @@ public class StatsCompanionService extends IStatsCompanionService.Stub {
Slog.d(TAG, "learned that statsdReady");
}
sayHiToStatsd(); // tell statsd that we're ready too and link to it
+ mStatsManagerService.systemReady();
mContext.sendBroadcastAsUser(new Intent(StatsManager.ACTION_STATSD_STARTED)
.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND),
UserHandle.SYSTEM, android.Manifest.permission.DUMP);
@@ -2736,53 +2752,29 @@ public class StatsCompanionService extends IStatsCompanionService.Stub {
}
}
- // Lifecycle and related code
+ // Statsd related code
/**
* Fetches the statsd IBinder service.
* Note: This should only be called from sayHiToStatsd. All other clients should use the cached
* sStatsd with a null check.
*/
- private static IStatsManager fetchStatsdService() {
- return IStatsManager.Stub.asInterface(ServiceManager.getService("stats"));
- }
-
- public static final class Lifecycle extends SystemService {
- private StatsCompanionService mStatsCompanionService;
-
- public Lifecycle(Context context) {
- super(context);
- }
-
- @Override
- public void onStart() {
- mStatsCompanionService = new StatsCompanionService(getContext());
- try {
- publishBinderService(Context.STATS_COMPANION_SERVICE,
- mStatsCompanionService);
- if (DEBUG) Slog.d(TAG, "Published " + Context.STATS_COMPANION_SERVICE);
- } catch (Exception e) {
- Slog.e(TAG, "Failed to publishBinderService", e);
- }
- }
-
- @Override
- public void onBootPhase(int phase) {
- super.onBootPhase(phase);
- if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
- mStatsCompanionService.systemReady();
- }
- }
+ private static IStatsd fetchStatsdService() {
+ return IStatsd.Stub.asInterface(ServiceManager.getService("stats"));
}
/**
* Now that the android system is ready, StatsCompanion is ready too, so inform statsd.
*/
- private void systemReady() {
+ void systemReady() {
if (DEBUG) Slog.d(TAG, "Learned that systemReady");
sayHiToStatsd();
}
+ void setStatsManagerService(StatsManagerService statsManagerService) {
+ mStatsManagerService = statsManagerService;
+ }
+
/**
* Tells statsd that statscompanion is ready. If the binder call returns, link to
* statsd.
diff --git a/apex/statsd/service/java/com/android/server/stats/StatsManagerService.java b/apex/statsd/service/java/com/android/server/stats/StatsManagerService.java
new file mode 100644
index 000000000000..f3bf9099c893
--- /dev/null
+++ b/apex/statsd/service/java/com/android/server/stats/StatsManagerService.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.stats;
+
+import android.app.PendingIntent;
+import android.content.Context;
+import android.os.IBinder;
+import android.os.IStatsManagerService;
+import android.os.IStatsd;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.util.Slog;
+
+import com.android.internal.annotations.GuardedBy;
+
+/**
+ * @hide
+ */
+public class StatsManagerService extends IStatsManagerService.Stub {
+
+ private static final String TAG = "StatsManagerService";
+ private static final boolean DEBUG = false;
+
+ @GuardedBy("sStatsdLock")
+ private static IStatsd sStatsd;
+ private static final Object sStatsdLock = new Object();
+
+ private StatsCompanionService mStatsCompanionService;
+
+ public StatsManagerService(Context context) {
+ super();
+ }
+
+ @Override
+ public void setDataFetchOperation(long configKey, PendingIntent pendingIntent,
+ String packageName) {
+ // no-op
+ if (DEBUG) {
+ Slog.d(TAG, "setDataFetchOperation");
+ }
+ }
+
+ @Override
+ public long[] setActiveConfigsChangedOperation(PendingIntent pendingIntent,
+ String packageName) {
+ // no-op
+ if (DEBUG) {
+ Slog.d(TAG, "setActiveConfigsChangedOperation");
+ }
+ return new long[]{};
+ }
+
+ @Override
+ public void setBroadcastSubscriber(long configKey, long subscriberId,
+ PendingIntent pendingIntent, String packageName) {
+ //no-op
+ if (DEBUG) {
+ Slog.d(TAG, "setBroadcastSubscriber");
+ }
+ }
+
+ void setStatsCompanionService(StatsCompanionService statsCompanionService) {
+ mStatsCompanionService = statsCompanionService;
+ }
+
+ void systemReady() {
+ if (DEBUG) {
+ Slog.d(TAG, "statsdReady");
+ }
+ setupStatsManagerService();
+ }
+
+ private void setupStatsManagerService() {
+ synchronized (sStatsdLock) {
+ if (sStatsd != null) {
+ if (DEBUG) {
+ Slog.e(TAG, "Trying to fetch statsd, but it was already fetched",
+ new IllegalStateException(
+ "sStatsd is not null when being fetched"));
+ }
+ return;
+ }
+ sStatsd = IStatsd.Stub.asInterface(ServiceManager.getService("stats"));
+ // Assume statsd is ready since this is called form statscompanion, link to statsd.
+ try {
+ sStatsd.asBinder().linkToDeath((IBinder.DeathRecipient) () -> {
+ sStatsd = null;
+ }, 0);
+ } catch (RemoteException e) {
+ Slog.e(TAG, "linkToDeath(StatsdDeathRecipient) failed", e);
+ }
+ }
+ }
+}
diff --git a/apex/statsd/testing/Android.bp b/apex/statsd/testing/Android.bp
new file mode 100644
index 000000000000..22e73015ba39
--- /dev/null
+++ b/apex/statsd/testing/Android.bp
@@ -0,0 +1,25 @@
+// Copyright (C) 2019 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.
+
+apex {
+ name: "test_com.android.os.statsd",
+ visibility: [
+ "//system/apex/tests",
+ ],
+ defaults: ["com.android.os.statsd-defaults"],
+ manifest: "test_manifest.json",
+ file_contexts: ":com.android.os.statsd-file_contexts",
+ // Test APEX, should never be installed
+ installable: false,
+}
diff --git a/apex/statsd/testing/test_manifest.json b/apex/statsd/testing/test_manifest.json
new file mode 100644
index 000000000000..57343d3e6ae5
--- /dev/null
+++ b/apex/statsd/testing/test_manifest.json
@@ -0,0 +1,4 @@
+{
+ "name": "com.android.os.statsd",
+ "version": 2147483647
+}
diff --git a/api/current.txt b/api/current.txt
index 542267c416f6..39d526344d97 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -6732,6 +6732,7 @@ package android.app.admin {
method @Deprecated @Nullable public String getApplicationRestrictionsManagingPackage(@NonNull android.content.ComponentName);
method public boolean getAutoTime(@NonNull android.content.ComponentName);
method @Deprecated public boolean getAutoTimeRequired();
+ method public boolean getAutoTimeZone(@NonNull android.content.ComponentName);
method @NonNull public java.util.List<android.os.UserHandle> getBindDeviceAdminTargetUsers(@NonNull android.content.ComponentName);
method public boolean getBluetoothContactSharingDisabled(@NonNull android.content.ComponentName);
method public boolean getCameraDisabled(@Nullable android.content.ComponentName);
@@ -6739,6 +6740,7 @@ package android.app.admin {
method @Nullable public java.util.Set<java.lang.String> getCrossProfileCalendarPackages(@NonNull android.content.ComponentName);
method public boolean getCrossProfileCallerIdDisabled(@NonNull android.content.ComponentName);
method public boolean getCrossProfileContactsSearchDisabled(@NonNull android.content.ComponentName);
+ method @NonNull public java.util.Set<java.lang.String> getCrossProfilePackages(@NonNull android.content.ComponentName);
method @NonNull public java.util.List<java.lang.String> getCrossProfileWidgetProviders(@NonNull android.content.ComponentName);
method public int getCurrentFailedPasswordAttempts();
method @Nullable public java.util.List<java.lang.String> getDelegatePackages(@NonNull android.content.ComponentName, @NonNull String);
@@ -6849,6 +6851,7 @@ package android.app.admin {
method @Deprecated public void setApplicationRestrictionsManagingPackage(@NonNull android.content.ComponentName, @Nullable String) throws android.content.pm.PackageManager.NameNotFoundException;
method public void setAutoTime(@NonNull android.content.ComponentName, boolean);
method @Deprecated public void setAutoTimeRequired(@NonNull android.content.ComponentName, boolean);
+ method public void setAutoTimeZone(@NonNull android.content.ComponentName, boolean);
method public void setBackupServiceEnabled(@NonNull android.content.ComponentName, boolean);
method public void setBluetoothContactSharingDisabled(@NonNull android.content.ComponentName, boolean);
method public void setCameraDisabled(@NonNull android.content.ComponentName, boolean);
@@ -6856,6 +6859,7 @@ package android.app.admin {
method public void setCrossProfileCalendarPackages(@NonNull android.content.ComponentName, @Nullable java.util.Set<java.lang.String>);
method public void setCrossProfileCallerIdDisabled(@NonNull android.content.ComponentName, boolean);
method public void setCrossProfileContactsSearchDisabled(@NonNull android.content.ComponentName, boolean);
+ method public void setCrossProfilePackages(@NonNull android.content.ComponentName, @NonNull java.util.Set<java.lang.String>);
method public void setDefaultSmsApplication(@NonNull android.content.ComponentName, @NonNull String);
method public void setDelegatedScopes(@NonNull android.content.ComponentName, @NonNull String, @NonNull java.util.List<java.lang.String>);
method public void setDeviceOwnerLockScreenInfo(@NonNull android.content.ComponentName, CharSequence);
@@ -16776,16 +16780,29 @@ package android.hardware {
package android.hardware.biometrics {
public class BiometricManager {
- method @RequiresPermission(android.Manifest.permission.USE_BIOMETRIC) public int canAuthenticate();
+ method @Deprecated @RequiresPermission(android.Manifest.permission.USE_BIOMETRIC) public int canAuthenticate();
+ method @RequiresPermission(android.Manifest.permission.USE_BIOMETRIC) public int canAuthenticate(int);
field public static final int BIOMETRIC_ERROR_HW_UNAVAILABLE = 1; // 0x1
field public static final int BIOMETRIC_ERROR_NONE_ENROLLED = 11; // 0xb
field public static final int BIOMETRIC_ERROR_NO_HARDWARE = 12; // 0xc
field public static final int BIOMETRIC_SUCCESS = 0; // 0x0
}
+ public static interface BiometricManager.Authenticators {
+ field public static final int BIOMETRIC_STRONG = 15; // 0xf
+ field public static final int BIOMETRIC_WEAK = 255; // 0xff
+ field public static final int DEVICE_CREDENTIAL = 32768; // 0x8000
+ }
+
public class BiometricPrompt {
method @RequiresPermission(android.Manifest.permission.USE_BIOMETRIC) public void authenticate(@NonNull android.hardware.biometrics.BiometricPrompt.CryptoObject, @NonNull android.os.CancellationSignal, @NonNull java.util.concurrent.Executor, @NonNull android.hardware.biometrics.BiometricPrompt.AuthenticationCallback);
method @RequiresPermission(android.Manifest.permission.USE_BIOMETRIC) public void authenticate(@NonNull android.os.CancellationSignal, @NonNull java.util.concurrent.Executor, @NonNull android.hardware.biometrics.BiometricPrompt.AuthenticationCallback);
+ method @Nullable public int getAllowedAuthenticators();
+ method @Nullable public CharSequence getDescription();
+ method @Nullable public CharSequence getNegativeButtonText();
+ method @Nullable public CharSequence getSubtitle();
+ method @NonNull public CharSequence getTitle();
+ method public boolean isConfirmationRequired();
field public static final int BIOMETRIC_ACQUIRED_GOOD = 0; // 0x0
field public static final int BIOMETRIC_ACQUIRED_IMAGER_DIRTY = 3; // 0x3
field public static final int BIOMETRIC_ACQUIRED_INSUFFICIENT = 2; // 0x2
@@ -16821,9 +16838,10 @@ package android.hardware.biometrics {
public static class BiometricPrompt.Builder {
ctor public BiometricPrompt.Builder(android.content.Context);
method @NonNull public android.hardware.biometrics.BiometricPrompt build();
+ method @NonNull public android.hardware.biometrics.BiometricPrompt.Builder setAllowedAuthenticators(int);
method @NonNull public android.hardware.biometrics.BiometricPrompt.Builder setConfirmationRequired(boolean);
method @NonNull public android.hardware.biometrics.BiometricPrompt.Builder setDescription(@NonNull CharSequence);
- method @NonNull public android.hardware.biometrics.BiometricPrompt.Builder setDeviceCredentialAllowed(boolean);
+ method @Deprecated @NonNull public android.hardware.biometrics.BiometricPrompt.Builder setDeviceCredentialAllowed(boolean);
method @NonNull public android.hardware.biometrics.BiometricPrompt.Builder setNegativeButton(@NonNull CharSequence, @NonNull java.util.concurrent.Executor, @NonNull android.content.DialogInterface.OnClickListener);
method @NonNull public android.hardware.biometrics.BiometricPrompt.Builder setSubtitle(@NonNull CharSequence);
method @NonNull public android.hardware.biometrics.BiometricPrompt.Builder setTitle(@NonNull CharSequence);
@@ -16916,7 +16934,7 @@ package android.hardware.camera2 {
field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.Rational> CONTROL_AE_COMPENSATION_STEP;
field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Boolean> CONTROL_AE_LOCK_AVAILABLE;
field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AF_AVAILABLE_MODES;
- field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.CapabilityAndMaxSize[]> CONTROL_AVAILABLE_BOKEH_CAPABILITIES;
+ field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.hardware.camera2.params.Capability[]> CONTROL_AVAILABLE_BOKEH_CAPABILITIES;
field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AVAILABLE_EFFECTS;
field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AVAILABLE_MODES;
field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> CONTROL_AVAILABLE_SCENE_MODES;
@@ -16927,6 +16945,7 @@ package android.hardware.camera2 {
field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> CONTROL_MAX_REGIONS_AF;
field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> CONTROL_MAX_REGIONS_AWB;
field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.Range<java.lang.Integer>> CONTROL_POST_RAW_SENSITIVITY_BOOST_RANGE;
+ field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.util.Range<java.lang.Float>> CONTROL_ZOOM_RATIO_RANGE;
field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Boolean> DEPTH_DEPTH_IS_EXCLUSIVE;
field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> DISTORTION_CORRECTION_AVAILABLE_MODES;
field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> EDGE_AVAILABLE_EDGE_MODES;
@@ -17228,6 +17247,7 @@ package android.hardware.camera2 {
field public static final int REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR = 1; // 0x1
field public static final int REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME = 12; // 0xc
field public static final int REQUEST_AVAILABLE_CAPABILITIES_MOTION_TRACKING = 10; // 0xa
+ field public static final int REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING = 15; // 0xf
field public static final int REQUEST_AVAILABLE_CAPABILITIES_PRIVATE_REPROCESSING = 4; // 0x4
field public static final int REQUEST_AVAILABLE_CAPABILITIES_RAW = 3; // 0x3
field public static final int REQUEST_AVAILABLE_CAPABILITIES_READ_SENSOR_SETTINGS = 5; // 0x5
@@ -17338,6 +17358,7 @@ package android.hardware.camera2 {
field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_POST_RAW_SENSITIVITY_BOOST;
field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_SCENE_MODE;
field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_VIDEO_STABILIZATION_MODE;
+ field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Float> CONTROL_ZOOM_RATIO;
field @NonNull public static final android.os.Parcelable.Creator<android.hardware.camera2.CaptureRequest> CREATOR;
field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> DISTORTION_CORRECTION_MODE;
field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> EDGE_MODE;
@@ -17424,6 +17445,7 @@ package android.hardware.camera2 {
field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_POST_RAW_SENSITIVITY_BOOST;
field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_SCENE_MODE;
field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_VIDEO_STABILIZATION_MODE;
+ field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Float> CONTROL_ZOOM_RATIO;
field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> DISTORTION_CORRECTION_MODE;
field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> EDGE_MODE;
field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> FLASH_MODE;
@@ -17513,9 +17535,10 @@ package android.hardware.camera2.params {
field public static final int COUNT = 4; // 0x4
}
- public final class CapabilityAndMaxSize {
+ public final class Capability {
method @NonNull public android.util.Size getMaxStreamingSize();
method public int getMode();
+ method @NonNull public android.util.Range<java.lang.Float> getZoomRatioRange();
}
public final class ColorSpaceTransform {
@@ -22634,6 +22657,7 @@ package android.inputmethodservice {
method public void onConfigureWindow(android.view.Window, boolean, boolean);
method public android.view.View onCreateCandidatesView();
method public android.view.View onCreateExtractTextView();
+ method @Nullable public android.view.inputmethod.InlineSuggestionsRequest onCreateInlineSuggestionsRequest();
method public android.inputmethodservice.AbstractInputMethodService.AbstractInputMethodImpl onCreateInputMethodInterface();
method public android.inputmethodservice.AbstractInputMethodService.AbstractInputMethodSessionImpl onCreateInputMethodSessionInterface();
method public android.view.View onCreateInputView();
@@ -22650,6 +22674,7 @@ package android.inputmethodservice {
method public void onFinishInput();
method public void onFinishInputView(boolean);
method public void onInitializeInterface();
+ method public boolean onInlineSuggestionsResponse(@NonNull android.view.inputmethod.InlineSuggestionsResponse);
method public boolean onKeyDown(int, android.view.KeyEvent);
method public boolean onKeyLongPress(int, android.view.KeyEvent);
method public boolean onKeyMultiple(int, int, android.view.KeyEvent);
@@ -25367,6 +25392,8 @@ package android.media {
field public static final String KEY_COMPLEXITY = "complexity";
field public static final String KEY_CREATE_INPUT_SURFACE_SUSPENDED = "create-input-buffers-suspended";
field public static final String KEY_DURATION = "durationUs";
+ field public static final String KEY_ENCODER_DELAY = "encoder-delay";
+ field public static final String KEY_ENCODER_PADDING = "encoder-padding";
field public static final String KEY_FLAC_COMPRESSION_LEVEL = "flac-compression-level";
field public static final String KEY_FRAME_RATE = "frame-rate";
field public static final String KEY_GRID_COLUMNS = "grid-cols";
@@ -25395,6 +25422,8 @@ package android.media {
field public static final String KEY_OPERATING_RATE = "operating-rate";
field public static final String KEY_OUTPUT_REORDER_DEPTH = "output-reorder-depth";
field public static final String KEY_PCM_ENCODING = "pcm-encoding";
+ field public static final String KEY_PIXEL_ASPECT_RATIO_HEIGHT = "sar-height";
+ field public static final String KEY_PIXEL_ASPECT_RATIO_WIDTH = "sar-width";
field public static final String KEY_PREPEND_HEADER_TO_SYNC_FRAMES = "prepend-sps-pps-to-idr-frames";
field public static final String KEY_PRIORITY = "priority";
field public static final String KEY_PROFILE = "profile";
@@ -25637,14 +25666,14 @@ package android.media {
}
public static interface MediaParser.OutputConsumer {
- method public void onFormat(int, @NonNull android.media.MediaFormat);
method public void onSampleCompleted(int, long, int, int, int, @Nullable android.media.MediaCodec.CryptoInfo);
method public void onSampleData(int, @NonNull android.media.MediaParser.InputReader) throws java.io.IOException, java.lang.InterruptedException;
method public void onSeekMap(@NonNull android.media.MediaParser.SeekMap);
+ method public void onTrackData(int, @NonNull android.media.MediaParser.TrackData);
method public void onTracksFound(int);
}
- public static interface MediaParser.SeekMap {
+ public static final class MediaParser.SeekMap {
method public long getDurationUs();
method @NonNull public android.util.Pair<android.media.MediaParser.SeekPoint,android.media.MediaParser.SeekPoint> getSeekPoints(long);
method public boolean isSeekable();
@@ -25661,6 +25690,11 @@ package android.media {
method public void seekToPosition(long);
}
+ public static final class MediaParser.TrackData {
+ field @Nullable public final android.media.DrmInitData drmInitData;
+ field @NonNull public final android.media.MediaFormat mediaFormat;
+ }
+
public static final class MediaParser.UnrecognizedInputFormatException extends java.io.IOException {
}
@@ -27609,6 +27643,7 @@ package android.media.session {
method @Nullable public android.app.PendingIntent getSessionActivity();
method @NonNull public android.os.Bundle getSessionInfo();
method @NonNull public android.media.session.MediaSession.Token getSessionToken();
+ method @NonNull public String getTag();
method @NonNull public android.media.session.MediaController.TransportControls getTransportControls();
method public void registerCallback(@NonNull android.media.session.MediaController.Callback);
method public void registerCallback(@NonNull android.media.session.MediaController.Callback, @Nullable android.os.Handler);
@@ -29209,6 +29244,7 @@ package android.net {
public class NetworkRequest implements android.os.Parcelable {
method public int describeContents();
+ method @Nullable public android.net.NetworkSpecifier getNetworkSpecifier();
method public boolean hasCapability(int);
method public boolean hasTransport(int);
method public void writeToParcel(android.os.Parcel, int);
@@ -30010,6 +30046,7 @@ package android.net.wifi {
@Deprecated public static class WifiConfiguration.GroupCipher {
field @Deprecated public static final int CCMP = 3; // 0x3
field @Deprecated public static final int GCMP_256 = 5; // 0x5
+ field @Deprecated public static final int SMS4 = 6; // 0x6
field @Deprecated public static final int TKIP = 2; // 0x2
field @Deprecated public static final int WEP104 = 1; // 0x1
field @Deprecated public static final int WEP40 = 0; // 0x0
@@ -30039,6 +30076,7 @@ package android.net.wifi {
field @Deprecated public static final int CCMP = 2; // 0x2
field @Deprecated public static final int GCMP_256 = 3; // 0x3
field @Deprecated public static final int NONE = 0; // 0x0
+ field @Deprecated public static final int SMS4 = 4; // 0x4
field @Deprecated public static final int TKIP = 1; // 0x1
field @Deprecated public static final String[] strings;
field @Deprecated public static final String varName = "pairwise";
@@ -30046,6 +30084,7 @@ package android.net.wifi {
@Deprecated public static class WifiConfiguration.Protocol {
field @Deprecated public static final int RSN = 1; // 0x1
+ field @Deprecated public static final int WAPI = 3; // 0x3
field @Deprecated public static final int WPA = 0; // 0x0
field @Deprecated public static final String[] strings;
field @Deprecated public static final String varName = "proto";
@@ -30092,6 +30131,12 @@ package android.net.wifi {
method @Deprecated public void setSubjectMatch(String);
method public void writeToParcel(android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.WifiEnterpriseConfig> CREATOR;
+ field public static final String EXTRA_WAPI_AS_CERTIFICATE_DATA = "android.net.wifi.extra.WAPI_AS_CERTIFICATE_DATA";
+ field public static final String EXTRA_WAPI_AS_CERTIFICATE_NAME = "android.net.wifi.extra.WAPI_AS_CERTIFICATE_NAME";
+ field public static final String EXTRA_WAPI_USER_CERTIFICATE_DATA = "android.net.wifi.extra.WAPI_USER_CERTIFICATE_DATA";
+ field public static final String EXTRA_WAPI_USER_CERTIFICATE_NAME = "android.net.wifi.extra.WAPI_USER_CERTIFICATE_NAME";
+ field public static final String WAPI_AS_CERTIFICATE = "WAPIAS_";
+ field public static final String WAPI_USER_CERTIFICATE = "WAPIUSR_";
}
public static final class WifiEnterpriseConfig.Eap {
@@ -30104,6 +30149,7 @@ package android.net.wifi {
field public static final int TLS = 1; // 0x1
field public static final int TTLS = 2; // 0x2
field public static final int UNAUTH_TLS = 7; // 0x7
+ field public static final int WAPI_CERT = 8; // 0x8
}
public static final class WifiEnterpriseConfig.Phase2 {
@@ -30175,6 +30221,7 @@ package android.net.wifi {
method public boolean isPreferredNetworkOffloadSupported();
method @Deprecated public boolean isScanAlwaysAvailable();
method public boolean isTdlsSupported();
+ method public boolean isWapiSupported();
method public boolean isWifiEnabled();
method public boolean isWpa3SaeSupported();
method public boolean isWpa3SuiteBSupported();
@@ -30331,6 +30378,8 @@ package android.net.wifi {
method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setPasspointConfig(@NonNull android.net.wifi.hotspot2.PasspointConfiguration);
method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setPriority(@IntRange(from=0) int);
method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setSsid(@NonNull String);
+ method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setWapiEnterpriseConfig(@NonNull android.net.wifi.WifiEnterpriseConfig);
+ method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setWapiPassphrase(@NonNull String);
method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setWpa2EnterpriseConfig(@NonNull android.net.wifi.WifiEnterpriseConfig);
method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setWpa2Passphrase(@NonNull String);
method @NonNull public android.net.wifi.WifiNetworkSuggestion.Builder setWpa3EnterpriseConfig(@NonNull android.net.wifi.WifiEnterpriseConfig);
@@ -30617,6 +30666,10 @@ package android.net.wifi.p2p {
ctor public WifiP2pConfig();
ctor public WifiP2pConfig(android.net.wifi.p2p.WifiP2pConfig);
method public int describeContents();
+ method public int getGroupOwnerBand();
+ method public int getNetworkId();
+ method @Nullable public String getNetworkName();
+ method @Nullable public String getPassphrase();
method public void writeToParcel(android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.p2p.WifiP2pConfig> CREATOR;
field public static final int GROUP_OWNER_BAND_2GHZ = 1; // 0x1
@@ -30690,6 +30743,8 @@ package android.net.wifi.p2p {
method public boolean isGroupOwner();
method public void writeToParcel(android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.p2p.WifiP2pGroup> CREATOR;
+ field public static final int PERSISTENT_NET_ID = -2; // 0xfffffffe
+ field public static final int TEMPORARY_NET_ID = -1; // 0xffffffff
}
public class WifiP2pInfo implements android.os.Parcelable {
@@ -35000,6 +35055,7 @@ package android.os {
method public void dump(@NonNull java.io.FileDescriptor, @Nullable String[]) throws android.os.RemoteException;
method public void dumpAsync(@NonNull java.io.FileDescriptor, @Nullable String[]) throws android.os.RemoteException;
method @Nullable public String getInterfaceDescriptor() throws android.os.RemoteException;
+ method public static int getSuggestedMaxIpcSizeBytes();
method public boolean isBinderAlive();
method public void linkToDeath(@NonNull android.os.IBinder.DeathRecipient, int) throws android.os.RemoteException;
method public boolean pingBinder();
@@ -35196,6 +35252,7 @@ package android.os {
method public void readMap(@NonNull java.util.Map, @Nullable ClassLoader);
method @Nullable public <T extends android.os.Parcelable> T readParcelable(@Nullable ClassLoader);
method @Nullable public android.os.Parcelable[] readParcelableArray(@Nullable ClassLoader);
+ method @Nullable public android.os.Parcelable.Creator<?> readParcelableCreator(@Nullable ClassLoader);
method @NonNull public <T extends android.os.Parcelable> java.util.List<T> readParcelableList(@NonNull java.util.List<T>, @Nullable ClassLoader);
method @Nullable public android.os.PersistableBundle readPersistableBundle();
method @Nullable public android.os.PersistableBundle readPersistableBundle(@Nullable ClassLoader);
@@ -35243,6 +35300,7 @@ package android.os {
method public void writeNoException();
method public void writeParcelable(@Nullable android.os.Parcelable, int);
method public <T extends android.os.Parcelable> void writeParcelableArray(@Nullable T[], int);
+ method public void writeParcelableCreator(@NonNull android.os.Parcelable);
method public <T extends android.os.Parcelable> void writeParcelableList(@Nullable java.util.List<T>, int);
method public void writePersistableBundle(@Nullable android.os.PersistableBundle);
method public void writeSerializable(@Nullable java.io.Serializable);
@@ -35719,7 +35777,7 @@ package android.os {
method @Deprecated public void setUserRestrictions(android.os.Bundle, android.os.UserHandle);
method public static boolean supportsMultipleUsers();
field public static final String ALLOW_PARENT_PROFILE_APP_LINKING = "allow_parent_profile_app_linking";
- field public static final String DISALLOW_ADD_MANAGED_PROFILE = "no_add_managed_profile";
+ field @Deprecated public static final String DISALLOW_ADD_MANAGED_PROFILE = "no_add_managed_profile";
field public static final String DISALLOW_ADD_USER = "no_add_user";
field public static final String DISALLOW_ADJUST_VOLUME = "no_adjust_volume";
field public static final String DISALLOW_AIRPLANE_MODE = "no_airplane_mode";
@@ -35758,7 +35816,7 @@ package android.os {
field public static final String DISALLOW_OUTGOING_BEAM = "no_outgoing_beam";
field public static final String DISALLOW_OUTGOING_CALLS = "no_outgoing_calls";
field public static final String DISALLOW_PRINTING = "no_printing";
- field public static final String DISALLOW_REMOVE_MANAGED_PROFILE = "no_remove_managed_profile";
+ field @Deprecated public static final String DISALLOW_REMOVE_MANAGED_PROFILE = "no_remove_managed_profile";
field public static final String DISALLOW_REMOVE_USER = "no_remove_user";
field public static final String DISALLOW_SAFE_BOOT = "no_safe_boot";
field public static final String DISALLOW_SET_USER_ICON = "no_set_user_icon";
@@ -35993,7 +36051,8 @@ package android.os.storage {
method @WorkerThread public long getCacheSizeBytes(@NonNull java.util.UUID) throws java.io.IOException;
method public String getMountedObbPath(String);
method @NonNull public android.os.storage.StorageVolume getPrimaryStorageVolume();
- method @Nullable public android.os.storage.StorageVolume getStorageVolume(java.io.File);
+ method @NonNull public java.util.List<android.os.storage.StorageVolume> getRecentStorageVolumes();
+ method @Nullable public android.os.storage.StorageVolume getStorageVolume(@NonNull java.io.File);
method @NonNull public android.os.storage.StorageVolume getStorageVolume(@NonNull android.net.Uri);
method @NonNull public java.util.List<android.os.storage.StorageVolume> getStorageVolumes();
method @NonNull public java.util.UUID getUuidForPath(@NonNull java.io.File) throws java.io.IOException;
@@ -36019,6 +36078,8 @@ package android.os.storage {
method @NonNull public android.content.Intent createOpenDocumentTreeIntent();
method public int describeContents();
method public String getDescription(android.content.Context);
+ method @Nullable public java.io.File getDirectory();
+ method @Nullable public String getMediaStoreVolumeName();
method public String getState();
method @Nullable public String getUuid();
method public boolean isEmulated();
@@ -38342,6 +38403,8 @@ package android.provider {
public static final class ContactsContract.RawContacts implements android.provider.BaseColumns android.provider.ContactsContract.ContactNameColumns android.provider.ContactsContract.ContactOptionsColumns android.provider.ContactsContract.RawContactsColumns android.provider.ContactsContract.SyncColumns {
method public static android.net.Uri getContactLookupUri(android.content.ContentResolver, android.net.Uri);
+ method @Nullable public static String getLocalAccountName(@NonNull android.content.Context);
+ method @Nullable public static String getLocalAccountType(@NonNull android.content.Context);
method public static android.content.EntityIterator newEntityIterator(android.database.Cursor);
field public static final int AGGREGATION_MODE_DEFAULT = 0; // 0x0
field public static final int AGGREGATION_MODE_DISABLED = 3; // 0x3
@@ -38368,11 +38431,11 @@ package android.provider {
protected static interface ContactsContract.RawContactsColumns {
field public static final String ACCOUNT_TYPE_AND_DATA_SET = "account_type_and_data_set";
field public static final String AGGREGATION_MODE = "aggregation_mode";
- field public static final String BACKUP_ID = "backup_id";
+ field @Deprecated public static final String BACKUP_ID = "backup_id";
field public static final String CONTACT_ID = "contact_id";
field public static final String DATA_SET = "data_set";
field public static final String DELETED = "deleted";
- field public static final String METADATA_DIRTY = "metadata_dirty";
+ field @Deprecated public static final String METADATA_DIRTY = "metadata_dirty";
field public static final String RAW_CONTACT_IS_READ_ONLY = "raw_contact_is_read_only";
field public static final String RAW_CONTACT_IS_USER_PROFILE = "raw_contact_is_user_profile";
}
@@ -38679,19 +38742,21 @@ package android.provider {
public final class MediaStore {
ctor public MediaStore();
+ method @NonNull public static android.app.PendingIntent createDeleteRequest(@NonNull android.content.ContentResolver, @NonNull java.util.Collection<android.net.Uri>);
+ method @NonNull public static android.app.PendingIntent createFavoriteRequest(@NonNull android.content.ContentResolver, @NonNull java.util.Collection<android.net.Uri>, boolean);
+ method @NonNull public static android.app.PendingIntent createTrashRequest(@NonNull android.content.ContentResolver, @NonNull java.util.Collection<android.net.Uri>, boolean);
+ method @NonNull public static android.app.PendingIntent createWriteRequest(@NonNull android.content.ContentResolver, @NonNull java.util.Collection<android.net.Uri>);
method @Nullable public static android.net.Uri getDocumentUri(@NonNull android.content.Context, @NonNull android.net.Uri);
method @NonNull public static java.util.Set<java.lang.String> getExternalVolumeNames(@NonNull android.content.Context);
method public static android.net.Uri getMediaScannerUri();
method @Nullable public static android.net.Uri getMediaUri(@NonNull android.content.Context, @NonNull android.net.Uri);
+ method @NonNull public static java.util.Set<java.lang.String> getRecentExternalVolumeNames(@NonNull android.content.Context);
method public static boolean getRequireOriginal(@NonNull android.net.Uri);
method @NonNull public static String getVersion(@NonNull android.content.Context);
method @NonNull public static String getVersion(@NonNull android.content.Context, @NonNull String);
method @NonNull public static String getVolumeName(@NonNull android.net.Uri);
method @Deprecated @NonNull public static android.net.Uri setIncludePending(@NonNull android.net.Uri);
method @NonNull public static android.net.Uri setRequireOriginal(@NonNull android.net.Uri);
- method public static void trash(@NonNull android.content.Context, @NonNull android.net.Uri);
- method public static void trash(@NonNull android.content.Context, @NonNull android.net.Uri, long);
- method public static void untrash(@NonNull android.content.Context, @NonNull android.net.Uri);
field public static final String ACTION_IMAGE_CAPTURE = "android.media.action.IMAGE_CAPTURE";
field public static final String ACTION_IMAGE_CAPTURE_SECURE = "android.media.action.IMAGE_CAPTURE_SECURE";
field public static final String ACTION_REVIEW = "android.provider.action.REVIEW";
@@ -38951,6 +39016,7 @@ package android.provider {
method @Deprecated public static void cancelThumbnailRequest(android.content.ContentResolver, long);
method @Deprecated public static void cancelThumbnailRequest(android.content.ContentResolver, long, long);
method @Deprecated public static android.net.Uri getContentUri(String);
+ method @Deprecated @NonNull public static android.util.Size getKindSize(int);
method @Deprecated public static android.graphics.Bitmap getThumbnail(android.content.ContentResolver, long, int, android.graphics.BitmapFactory.Options);
method @Deprecated public static android.graphics.Bitmap getThumbnail(android.content.ContentResolver, long, long, int, android.graphics.BitmapFactory.Options);
method @Deprecated public static final android.database.Cursor query(android.content.ContentResolver, android.net.Uri, String[]);
@@ -39033,6 +39099,7 @@ package android.provider {
method @Deprecated public static void cancelThumbnailRequest(android.content.ContentResolver, long);
method @Deprecated public static void cancelThumbnailRequest(android.content.ContentResolver, long, long);
method @Deprecated public static android.net.Uri getContentUri(String);
+ method @Deprecated @NonNull public static android.util.Size getKindSize(int);
method @Deprecated public static android.graphics.Bitmap getThumbnail(android.content.ContentResolver, long, int, android.graphics.BitmapFactory.Options);
method @Deprecated public static android.graphics.Bitmap getThumbnail(android.content.ContentResolver, long, long, int, android.graphics.BitmapFactory.Options);
field @Deprecated public static final String DATA = "_data";
@@ -39096,6 +39163,7 @@ package android.provider {
field public static final String ACTION_APP_SEARCH_SETTINGS = "android.settings.APP_SEARCH_SETTINGS";
field public static final String ACTION_APP_USAGE_SETTINGS = "android.settings.action.APP_USAGE_SETTINGS";
field public static final String ACTION_BATTERY_SAVER_SETTINGS = "android.settings.BATTERY_SAVER_SETTINGS";
+ field public static final String ACTION_BIOMETRIC_ENROLL = "android.settings.BIOMETRIC_ENROLL";
field public static final String ACTION_BLUETOOTH_SETTINGS = "android.settings.BLUETOOTH_SETTINGS";
field public static final String ACTION_CAPTIONING_SETTINGS = "android.settings.CAPTIONING_SETTINGS";
field public static final String ACTION_CAST_SETTINGS = "android.settings.CAST_SETTINGS";
@@ -39107,7 +39175,7 @@ package android.provider {
field public static final String ACTION_DEVICE_INFO_SETTINGS = "android.settings.DEVICE_INFO_SETTINGS";
field public static final String ACTION_DISPLAY_SETTINGS = "android.settings.DISPLAY_SETTINGS";
field public static final String ACTION_DREAM_SETTINGS = "android.settings.DREAM_SETTINGS";
- field public static final String ACTION_FINGERPRINT_ENROLL = "android.settings.FINGERPRINT_ENROLL";
+ field @Deprecated public static final String ACTION_FINGERPRINT_ENROLL = "android.settings.FINGERPRINT_ENROLL";
field public static final String ACTION_HARD_KEYBOARD_SETTINGS = "android.settings.HARD_KEYBOARD_SETTINGS";
field public static final String ACTION_HOME_SETTINGS = "android.settings.HOME_SETTINGS";
field public static final String ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS = "android.settings.IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS";
@@ -39170,6 +39238,7 @@ package android.provider {
field public static final String EXTRA_APP_PACKAGE = "android.provider.extra.APP_PACKAGE";
field public static final String EXTRA_AUTHORITIES = "authorities";
field public static final String EXTRA_BATTERY_SAVER_MODE_ENABLED = "android.settings.extra.battery_saver_mode_enabled";
+ field public static final String EXTRA_BIOMETRIC_MINIMUM_STRENGTH_REQUIRED = "android.provider.extra.BIOMETRIC_MINIMUM_STRENGTH_REQUIRED";
field public static final String EXTRA_CHANNEL_ID = "android.provider.extra.CHANNEL_ID";
field public static final String EXTRA_DO_NOT_DISTURB_MODE_ENABLED = "android.settings.extra.do_not_disturb_mode_enabled";
field public static final String EXTRA_DO_NOT_DISTURB_MODE_MINUTES = "android.settings.extra.do_not_disturb_mode_minutes";
@@ -41539,7 +41608,8 @@ package android.service.autofill {
method @NonNull public java.util.List<android.service.autofill.FillContext> getFillContexts();
method public int getFlags();
method public int getId();
- method public void writeToParcel(android.os.Parcel, int);
+ method @Nullable public android.view.inputmethod.InlineSuggestionsRequest getInlineSuggestionsRequest();
+ method public void writeToParcel(@NonNull android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.FillRequest> CREATOR;
field public static final int FLAG_COMPATIBILITY_MODE_REQUEST = 2; // 0x2
field public static final int FLAG_MANUAL_REQUEST = 1; // 0x1
@@ -41556,6 +41626,7 @@ package android.service.autofill {
public static final class FillResponse.Builder {
ctor public FillResponse.Builder();
method @NonNull public android.service.autofill.FillResponse.Builder addDataset(@Nullable android.service.autofill.Dataset);
+ method @NonNull public android.service.autofill.FillResponse.Builder addInlineSuggestionSlice(@NonNull android.app.slice.Slice);
method @NonNull public android.service.autofill.FillResponse build();
method @NonNull public android.service.autofill.FillResponse.Builder disableAutofill(long);
method @NonNull public android.service.autofill.FillResponse.Builder setAuthentication(@NonNull android.view.autofill.AutofillId[], @Nullable android.content.IntentSender, @Nullable android.widget.RemoteViews);
@@ -43861,6 +43932,7 @@ package android.telecom {
field public static final String EVENT_CALL_PULL_FAILED = "android.telecom.event.CALL_PULL_FAILED";
field public static final String EVENT_CALL_REMOTELY_HELD = "android.telecom.event.CALL_REMOTELY_HELD";
field public static final String EVENT_CALL_REMOTELY_UNHELD = "android.telecom.event.CALL_REMOTELY_UNHELD";
+ field public static final String EVENT_CALL_SWITCH_FAILED = "android.telecom.event.CALL_SWITCH_FAILED";
field public static final String EVENT_MERGE_COMPLETE = "android.telecom.event.MERGE_COMPLETE";
field public static final String EVENT_MERGE_START = "android.telecom.event.MERGE_START";
field public static final String EVENT_ON_HOLD_TONE_END = "android.telecom.event.ON_HOLD_TONE_END";
@@ -44318,19 +44390,27 @@ package android.telecom {
field @Deprecated public static final String ACTION_INCOMING_CALL = "android.telecom.action.INCOMING_CALL";
field public static final String ACTION_PHONE_ACCOUNT_REGISTERED = "android.telecom.action.PHONE_ACCOUNT_REGISTERED";
field public static final String ACTION_PHONE_ACCOUNT_UNREGISTERED = "android.telecom.action.PHONE_ACCOUNT_UNREGISTERED";
+ field public static final String ACTION_POST_CALL = "android.telecom.action.POST_CALL";
field public static final String ACTION_SHOW_CALL_ACCESSIBILITY_SETTINGS = "android.telecom.action.SHOW_CALL_ACCESSIBILITY_SETTINGS";
field public static final String ACTION_SHOW_CALL_SETTINGS = "android.telecom.action.SHOW_CALL_SETTINGS";
field public static final String ACTION_SHOW_MISSED_CALLS_NOTIFICATION = "android.telecom.action.SHOW_MISSED_CALLS_NOTIFICATION";
field public static final String ACTION_SHOW_RESPOND_VIA_SMS_SETTINGS = "android.telecom.action.SHOW_RESPOND_VIA_SMS_SETTINGS";
field public static final char DTMF_CHARACTER_PAUSE = 44; // 0x002c ','
field public static final char DTMF_CHARACTER_WAIT = 59; // 0x003b ';'
+ field public static final int DURATION_LONG = 3; // 0x3
+ field public static final int DURATION_MEDIUM = 2; // 0x2
+ field public static final int DURATION_SHORT = 1; // 0x1
+ field public static final int DURATION_VERY_SHORT = 0; // 0x0
field public static final String EXTRA_CALL_BACK_NUMBER = "android.telecom.extra.CALL_BACK_NUMBER";
field public static final String EXTRA_CALL_DISCONNECT_CAUSE = "android.telecom.extra.CALL_DISCONNECT_CAUSE";
field public static final String EXTRA_CALL_DISCONNECT_MESSAGE = "android.telecom.extra.CALL_DISCONNECT_MESSAGE";
+ field public static final String EXTRA_CALL_DURATION = "android.telecom.extra.CALL_DURATION";
field public static final String EXTRA_CALL_NETWORK_TYPE = "android.telecom.extra.CALL_NETWORK_TYPE";
field public static final String EXTRA_CALL_SUBJECT = "android.telecom.extra.CALL_SUBJECT";
field public static final String EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME = "android.telecom.extra.CHANGE_DEFAULT_DIALER_PACKAGE_NAME";
field public static final String EXTRA_DEFAULT_CALL_SCREENING_APP_COMPONENT_NAME = "android.telecom.extra.DEFAULT_CALL_SCREENING_APP_COMPONENT_NAME";
+ field public static final String EXTRA_DISCONNECT_CAUSE = "android.telecom.extra.DISCONNECT_CAUSE";
+ field public static final String EXTRA_HANDLE = "android.telecom.extra.HANDLE";
field public static final String EXTRA_INCOMING_CALL_ADDRESS = "android.telecom.extra.INCOMING_CALL_ADDRESS";
field public static final String EXTRA_INCOMING_CALL_EXTRAS = "android.telecom.extra.INCOMING_CALL_EXTRAS";
field public static final String EXTRA_INCOMING_VIDEO_STATE = "android.telecom.extra.INCOMING_VIDEO_STATE";
@@ -44570,6 +44650,7 @@ package android.telephony {
method public void notifyConfigChangedForSubId(int);
field public static final String ACTION_CARRIER_CONFIG_CHANGED = "android.telephony.action.CARRIER_CONFIG_CHANGED";
field public static final int DATA_CYCLE_THRESHOLD_DISABLED = -2; // 0xfffffffe
+ field public static final int DATA_CYCLE_USE_PLATFORM_DEFAULT = -1; // 0xffffffff
field public static final String EXTRA_SLOT_INDEX = "android.telephony.extra.SLOT_INDEX";
field public static final String EXTRA_SUBSCRIPTION_INDEX = "android.telephony.extra.SUBSCRIPTION_INDEX";
field public static final String KEY_5G_NR_SSRSRP_THRESHOLDS_INT_ARRAY = "5g_nr_ssrsrp_thresholds_int_array";
@@ -44580,6 +44661,7 @@ package android.telephony {
field public static final String KEY_ALLOW_ADD_CALL_DURING_VIDEO_CALL_BOOL = "allow_add_call_during_video_call";
field public static final String KEY_ALLOW_EMERGENCY_NUMBERS_IN_CALL_LOG_BOOL = "allow_emergency_numbers_in_call_log_bool";
field public static final String KEY_ALLOW_EMERGENCY_VIDEO_CALLS_BOOL = "allow_emergency_video_calls_bool";
+ field public static final String KEY_ALLOW_HOLDING_VIDEO_CALL_BOOL = "allow_holding_video_call";
field public static final String KEY_ALLOW_HOLD_CALL_DURING_EMERGENCY_BOOL = "allow_hold_call_during_emergency_bool";
field public static final String KEY_ALLOW_LOCAL_DTMF_TONES_BOOL = "allow_local_dtmf_tones_bool";
field public static final String KEY_ALLOW_MERGE_WIFI_CALLS_WHEN_VOWIFI_OFF_BOOL = "allow_merge_wifi_calls_when_vowifi_off_bool";
@@ -44629,11 +44711,16 @@ package android.telephony {
field public static final String KEY_CI_ACTION_ON_SYS_UPDATE_EXTRA_STRING = "ci_action_on_sys_update_extra_string";
field public static final String KEY_CI_ACTION_ON_SYS_UPDATE_EXTRA_VAL_STRING = "ci_action_on_sys_update_extra_val_string";
field public static final String KEY_CI_ACTION_ON_SYS_UPDATE_INTENT_STRING = "ci_action_on_sys_update_intent_string";
- field public static final String KEY_CONFIG_IMS_PACKAGE_OVERRIDE_STRING = "config_ims_package_override_string";
+ field public static final String KEY_CONFIG_IMS_MMTEL_PACKAGE_OVERRIDE_STRING = "config_ims_mmtel_package_override_string";
+ field @Deprecated public static final String KEY_CONFIG_IMS_PACKAGE_OVERRIDE_STRING = "config_ims_package_override_string";
+ field public static final String KEY_CONFIG_IMS_RCS_PACKAGE_OVERRIDE_STRING = "config_ims_rcs_package_override_string";
field public static final String KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING = "config_plans_package_override_string";
field public static final String KEY_CONFIG_TELEPHONY_USE_OWN_NUMBER_FOR_VOICEMAIL_BOOL = "config_telephony_use_own_number_for_voicemail_bool";
field public static final String KEY_CSP_ENABLED_BOOL = "csp_enabled_bool";
+ field public static final String KEY_DATA_LIMIT_NOTIFICATION_BOOL = "data_limit_notification_bool";
field public static final String KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG = "data_limit_threshold_bytes_long";
+ field public static final String KEY_DATA_RAPID_NOTIFICATION_BOOL = "data_rapid_notification_bool";
+ field public static final String KEY_DATA_WARNING_NOTIFICATION_BOOL = "data_warning_notification_bool";
field public static final String KEY_DATA_WARNING_THRESHOLD_BYTES_LONG = "data_warning_threshold_bytes_long";
field public static final String KEY_DEFAULT_SIM_CALL_MANAGER_STRING = "default_sim_call_manager_string";
field public static final String KEY_DEFAULT_VM_NUMBER_ROAMING_AND_IMS_UNREGISTERED_STRING = "default_vm_number_roaming_and_ims_unregistered_string";
@@ -45193,6 +45280,7 @@ package android.telephony {
method public void onDataConnectionStateChanged(int);
method public void onDataConnectionStateChanged(int, int);
method public void onMessageWaitingIndicatorChanged(boolean);
+ method @RequiresPermission("android.permission.MODIFY_PHONE_STATE") public void onPreciseDataConnectionStateChanged(@NonNull android.telephony.PreciseDataConnectionState);
method public void onServiceStateChanged(android.telephony.ServiceState);
method @Deprecated public void onSignalStrengthChanged(int);
method public void onSignalStrengthsChanged(android.telephony.SignalStrength);
@@ -45207,12 +45295,23 @@ package android.telephony {
field public static final int LISTEN_EMERGENCY_NUMBER_LIST = 16777216; // 0x1000000
field public static final int LISTEN_MESSAGE_WAITING_INDICATOR = 4; // 0x4
field public static final int LISTEN_NONE = 0; // 0x0
+ field @RequiresPermission("android.permission.MODIFY_PHONE_STATE") public static final int LISTEN_PRECISE_DATA_CONNECTION_STATE = 4096; // 0x1000
field public static final int LISTEN_SERVICE_STATE = 1; // 0x1
field @Deprecated public static final int LISTEN_SIGNAL_STRENGTH = 2; // 0x2
field public static final int LISTEN_SIGNAL_STRENGTHS = 256; // 0x100
field public static final int LISTEN_USER_MOBILE_DATA_STATE = 524288; // 0x80000
}
+ public final class PreciseDataConnectionState implements android.os.Parcelable {
+ method public int describeContents();
+ method public int getLastCauseCode();
+ method @Nullable public android.net.LinkProperties getLinkProperties();
+ method public int getNetworkType();
+ method public int getState();
+ method public void writeToParcel(@NonNull android.os.Parcel, int);
+ field @NonNull public static final android.os.Parcelable.Creator<android.telephony.PreciseDataConnectionState> CREATOR;
+ }
+
public final class RadioAccessSpecifier implements android.os.Parcelable {
ctor public RadioAccessSpecifier(int, int[], int[]);
method public int describeContents();
@@ -45593,6 +45692,7 @@ package android.telephony {
method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public boolean doesSwitchMultiSimConfigTriggerReboot();
method public int getActiveModemCount();
method @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) public java.util.List<android.telephony.CellInfo> getAllCellInfo();
+ method @NonNull public static int[] getAllNetworkTypes();
method public int getCallState();
method public int getCardIdForDefaultEuicc();
method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) @WorkerThread public android.os.PersistableBundle getCarrierConfig();
@@ -45724,6 +45824,7 @@ package android.telephony {
field public static final int DATA_CONNECTED = 2; // 0x2
field public static final int DATA_CONNECTING = 1; // 0x1
field public static final int DATA_DISCONNECTED = 0; // 0x0
+ field public static final int DATA_DISCONNECTING = 4; // 0x4
field public static final int DATA_SUSPENDED = 3; // 0x3
field public static final int DATA_UNKNOWN = -1; // 0xffffffff
field public static final String EXTRA_CALL_VOICEMAIL_INTENT = "android.telephony.extra.CALL_VOICEMAIL_INTENT";
@@ -45965,6 +46066,7 @@ package android.telephony.data {
field public static final int TYPE_MCX = 1024; // 0x400
field public static final int TYPE_MMS = 2; // 0x2
field public static final int TYPE_SUPL = 4; // 0x4
+ field public static final int TYPE_XCAP = 2048; // 0x800
}
public static class ApnSetting.Builder {
@@ -46534,12 +46636,12 @@ package android.telephony.mbms {
package android.text {
- public class AlteredCharSequence implements java.lang.CharSequence android.text.GetChars {
- method public char charAt(int);
- method public void getChars(int, int, char[], int);
- method public int length();
- method public static android.text.AlteredCharSequence make(CharSequence, char[], int, int);
- method public CharSequence subSequence(int, int);
+ @Deprecated public class AlteredCharSequence implements java.lang.CharSequence android.text.GetChars {
+ method @Deprecated public char charAt(int);
+ method @Deprecated public void getChars(int, int, char[], int);
+ method @Deprecated public int length();
+ method @Deprecated public static android.text.AlteredCharSequence make(CharSequence, char[], int, int);
+ method @Deprecated public CharSequence subSequence(int, int);
}
@Deprecated public class AndroidCharacter {
@@ -47274,7 +47376,7 @@ package android.text.format {
field public static final long WEEK_IN_MILLIS = 604800000L; // 0x240c8400L
field public static final String YEAR_FORMAT = "%Y";
field public static final String YEAR_FORMAT_TWO_DIGITS = "%g";
- field public static final long YEAR_IN_MILLIS = 31449600000L; // 0x7528ad000L
+ field @Deprecated public static final long YEAR_IN_MILLIS = 31449600000L; // 0x7528ad000L
field @Deprecated public static final int[] sameMonthTable;
field @Deprecated public static final int[] sameYearTable;
}
@@ -48713,6 +48815,13 @@ package android.util {
ctor public Base64OutputStream(java.io.OutputStream, int);
}
+ public final class CloseGuard {
+ ctor public CloseGuard();
+ method public void close();
+ method public void open(@NonNull String);
+ method public void warnIfOpen();
+ }
+
@Deprecated public final class Config {
field @Deprecated public static final boolean DEBUG = false;
field @Deprecated public static final boolean LOGD = true;
@@ -51042,6 +51151,9 @@ package android.view {
method public boolean dispatchUnhandledMove(android.view.View, int);
method protected void dispatchVisibilityChanged(@NonNull android.view.View, int);
method public void dispatchWindowFocusChanged(boolean);
+ method public void dispatchWindowInsetsAnimationFinished(@NonNull android.view.WindowInsetsAnimationCallback.InsetsAnimation);
+ method @NonNull public android.view.WindowInsets dispatchWindowInsetsAnimationProgress(@NonNull android.view.WindowInsets);
+ method @NonNull public android.view.WindowInsetsAnimationCallback.AnimationBounds dispatchWindowInsetsAnimationStarted(@NonNull android.view.WindowInsetsAnimationCallback.InsetsAnimation, @NonNull android.view.WindowInsetsAnimationCallback.AnimationBounds);
method public void dispatchWindowSystemUiVisiblityChanged(int);
method public void dispatchWindowVisibilityChanged(int);
method @CallSuper public void draw(android.graphics.Canvas);
@@ -51222,6 +51334,7 @@ package android.view {
method @android.view.ViewDebug.ExportedProperty(category="layout") public final int getWidth();
method protected int getWindowAttachCount();
method public android.view.WindowId getWindowId();
+ method @Nullable public android.view.WindowInsetsController getWindowInsetsController();
method public int getWindowSystemUiVisibility();
method public android.os.IBinder getWindowToken();
method public int getWindowVisibility();
@@ -51560,6 +51673,7 @@ package android.view {
method public void setVisibility(int);
method @Deprecated public void setWillNotCacheDrawing(boolean);
method public void setWillNotDraw(boolean);
+ method public void setWindowInsetsAnimationCallback(@Nullable android.view.WindowInsetsAnimationCallback);
method public void setX(float);
method public void setY(float);
method public void setZ(float);
@@ -52446,6 +52560,7 @@ package android.view {
method public android.transition.Transition getExitTransition();
method protected final int getFeatures();
method protected final int getForcedWindowFlags();
+ method @Nullable public android.view.WindowInsetsController getInsetsController();
method @NonNull public abstract android.view.LayoutInflater getLayoutInflater();
method protected final int getLocalFeatures();
method public android.media.session.MediaController getMediaController();
@@ -52661,7 +52776,9 @@ package android.view {
method @NonNull public android.view.WindowInsets consumeStableInsets();
method @NonNull public android.view.WindowInsets consumeSystemWindowInsets();
method @Nullable public android.view.DisplayCutout getDisplayCutout();
+ method @NonNull public android.graphics.Insets getInsets(int);
method @NonNull public android.graphics.Insets getMandatorySystemGestureInsets();
+ method @NonNull public android.graphics.Insets getMaxInsets(int) throws java.lang.IllegalArgumentException;
method public int getStableInsetBottom();
method public int getStableInsetLeft();
method public int getStableInsetRight();
@@ -52680,6 +52797,7 @@ package android.view {
method @NonNull public android.view.WindowInsets inset(@IntRange(from=0) int, @IntRange(from=0) int, @IntRange(from=0) int, @IntRange(from=0) int);
method public boolean isConsumed();
method public boolean isRound();
+ method public boolean isVisible(int);
method @Deprecated @NonNull public android.view.WindowInsets replaceSystemWindowInsets(int, int, int, int);
method @Deprecated @NonNull public android.view.WindowInsets replaceSystemWindowInsets(android.graphics.Rect);
}
@@ -52689,11 +52807,78 @@ package android.view {
ctor public WindowInsets.Builder(@NonNull android.view.WindowInsets);
method @NonNull public android.view.WindowInsets build();
method @NonNull public android.view.WindowInsets.Builder setDisplayCutout(@Nullable android.view.DisplayCutout);
+ method @NonNull public android.view.WindowInsets.Builder setInsets(int, @NonNull android.graphics.Insets);
method @NonNull public android.view.WindowInsets.Builder setMandatorySystemGestureInsets(@NonNull android.graphics.Insets);
+ method @NonNull public android.view.WindowInsets.Builder setMaxInsets(int, @NonNull android.graphics.Insets) throws java.lang.IllegalArgumentException;
method @NonNull public android.view.WindowInsets.Builder setStableInsets(@NonNull android.graphics.Insets);
method @NonNull public android.view.WindowInsets.Builder setSystemGestureInsets(@NonNull android.graphics.Insets);
method @NonNull public android.view.WindowInsets.Builder setSystemWindowInsets(@NonNull android.graphics.Insets);
method @NonNull public android.view.WindowInsets.Builder setTappableElementInsets(@NonNull android.graphics.Insets);
+ method @NonNull public android.view.WindowInsets.Builder setVisible(int, boolean);
+ }
+
+ public static final class WindowInsets.Type {
+ method public static int all();
+ method public static int captionBar();
+ method public static int ime();
+ method public static int mandatorySystemGestures();
+ method public static int navigationBars();
+ method public static int statusBars();
+ method public static int systemBars();
+ method public static int systemGestures();
+ method public static int tappableElement();
+ method public static int windowDecor();
+ }
+
+ public interface WindowInsetsAnimationCallback {
+ method public default void onFinished(@NonNull android.view.WindowInsetsAnimationCallback.InsetsAnimation);
+ method @NonNull public android.view.WindowInsets onProgress(@NonNull android.view.WindowInsets);
+ method @NonNull public default android.view.WindowInsetsAnimationCallback.AnimationBounds onStarted(@NonNull android.view.WindowInsetsAnimationCallback.InsetsAnimation, @NonNull android.view.WindowInsetsAnimationCallback.AnimationBounds);
+ }
+
+ public static final class WindowInsetsAnimationCallback.AnimationBounds {
+ ctor public WindowInsetsAnimationCallback.AnimationBounds(@NonNull android.graphics.Insets, @NonNull android.graphics.Insets);
+ method @NonNull public android.graphics.Insets getLowerBound();
+ method @NonNull public android.graphics.Insets getUpperBound();
+ method @NonNull public android.view.WindowInsetsAnimationCallback.AnimationBounds inset(@NonNull android.graphics.Insets);
+ }
+
+ public static final class WindowInsetsAnimationCallback.InsetsAnimation {
+ ctor public WindowInsetsAnimationCallback.InsetsAnimation(int, @Nullable android.view.animation.Interpolator, long);
+ method @FloatRange(from=0.0f, to=1.0f) public float getAlpha();
+ method public long getDurationMillis();
+ method @FloatRange(from=0.0f, to=1.0f) public float getFraction();
+ method public float getInterpolatedFraction();
+ method @Nullable public android.view.animation.Interpolator getInterpolator();
+ method public int getTypeMask();
+ method public void setDuration(long);
+ method public void setFraction(@FloatRange(from=0.0f, to=1.0f) float);
+ }
+
+ public interface WindowInsetsAnimationControlListener {
+ method public void onCancelled();
+ method public void onReady(@NonNull android.view.WindowInsetsAnimationController, int);
+ }
+
+ public interface WindowInsetsAnimationController {
+ method public void finish(boolean);
+ method public float getCurrentAlpha();
+ method @FloatRange(from=0.0f, to=1.0f) public float getCurrentFraction();
+ method @NonNull public android.graphics.Insets getCurrentInsets();
+ method @NonNull public android.graphics.Insets getHiddenStateInsets();
+ method @NonNull public android.graphics.Insets getShownStateInsets();
+ method public int getTypes();
+ method public void setInsetsAndAlpha(@Nullable android.graphics.Insets, @FloatRange(from=0.0f, to=1.0f) float, @FloatRange(from=0.0f, to=1.0f) float);
+ }
+
+ public interface WindowInsetsController {
+ method public default void controlInputMethodAnimation(long, @NonNull android.view.WindowInsetsAnimationControlListener);
+ method public default void hideInputMethod();
+ method public void setSystemBarsAppearance(int);
+ method public void setSystemBarsBehavior(int);
+ method public default void showInputMethod();
+ field public static final int APPEARANCE_LIGHT_NAVIGATION_BARS = 16; // 0x10
+ field public static final int APPEARANCE_LIGHT_STATUS_BARS = 8; // 0x8
}
public interface WindowManager extends android.view.ViewManager {
diff --git a/api/removed.txt b/api/removed.txt
index 1a2f43450d7b..8b30d0a5cf39 100644
--- a/api/removed.txt
+++ b/api/removed.txt
@@ -436,11 +436,12 @@ package android.provider {
}
public final class MediaStore {
- method @Deprecated @NonNull public static android.net.Uri createPending(@NonNull android.content.Context, @NonNull android.provider.MediaStore.PendingParams);
method @Deprecated @NonNull public static java.util.Set<java.lang.String> getAllVolumeNames(@NonNull android.content.Context);
method @Deprecated public static boolean getIncludePending(@NonNull android.net.Uri);
- method @Deprecated @NonNull public static android.provider.MediaStore.PendingSession openPending(@NonNull android.content.Context, @NonNull android.net.Uri);
method @Deprecated @NonNull public static android.net.Uri setIncludeTrashed(@NonNull android.net.Uri);
+ method @Deprecated public static void trash(@NonNull android.content.Context, @NonNull android.net.Uri);
+ method @Deprecated public static void trash(@NonNull android.content.Context, @NonNull android.net.Uri, long);
+ method @Deprecated public static void untrash(@NonNull android.content.Context, @NonNull android.net.Uri);
}
public static interface MediaStore.Audio.AudioColumns extends android.provider.MediaStore.MediaColumns {
@@ -470,22 +471,6 @@ package android.provider {
field @Deprecated public static final String GROUP_ID = "group_id";
}
- @Deprecated public static class MediaStore.PendingParams {
- ctor public MediaStore.PendingParams(@NonNull android.net.Uri, @NonNull String, @NonNull String);
- method public void setDownloadUri(@Nullable android.net.Uri);
- method public void setRefererUri(@Nullable android.net.Uri);
- method public void setRelativePath(@Nullable String);
- }
-
- @Deprecated public static class MediaStore.PendingSession implements java.lang.AutoCloseable {
- method public void abandon();
- method public void close();
- method public void notifyProgress(@IntRange(from=0, to=100) int);
- method @NonNull public android.os.ParcelFileDescriptor open() throws java.io.FileNotFoundException;
- method @NonNull public java.io.OutputStream openOutputStream() throws java.io.FileNotFoundException;
- method @NonNull public android.net.Uri publish();
- }
-
public static interface MediaStore.Video.VideoColumns extends android.provider.MediaStore.MediaColumns {
field public static final String ALBUM = "album";
field public static final String ARTIST = "artist";
diff --git a/api/system-current.txt b/api/system-current.txt
index 217943c519af..07d76d7a614f 100644..100755
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -546,10 +546,12 @@ package android.app {
method public final android.os.IBinder onBind(android.content.Intent);
method @Deprecated public void onGetInstantAppIntentFilter(@Nullable int[], @NonNull String, @NonNull android.app.InstantAppResolverService.InstantAppResolutionCallback);
method @Deprecated public void onGetInstantAppIntentFilter(@NonNull android.content.Intent, @Nullable int[], @NonNull String, @NonNull android.app.InstantAppResolverService.InstantAppResolutionCallback);
- method public void onGetInstantAppIntentFilter(@NonNull android.content.Intent, @Nullable int[], @NonNull android.os.UserHandle, @NonNull String, @NonNull android.app.InstantAppResolverService.InstantAppResolutionCallback);
+ method @Deprecated public void onGetInstantAppIntentFilter(@NonNull android.content.Intent, @Nullable int[], @NonNull android.os.UserHandle, @NonNull String, @NonNull android.app.InstantAppResolverService.InstantAppResolutionCallback);
+ method public void onGetInstantAppIntentFilter(@NonNull android.content.pm.InstantAppRequestInfo, @NonNull android.app.InstantAppResolverService.InstantAppResolutionCallback);
method @Deprecated public void onGetInstantAppResolveInfo(@Nullable int[], @NonNull String, @NonNull android.app.InstantAppResolverService.InstantAppResolutionCallback);
method @Deprecated public void onGetInstantAppResolveInfo(@NonNull android.content.Intent, @Nullable int[], @NonNull String, @NonNull android.app.InstantAppResolverService.InstantAppResolutionCallback);
- method public void onGetInstantAppResolveInfo(@NonNull android.content.Intent, @Nullable int[], @NonNull android.os.UserHandle, @NonNull String, @NonNull android.app.InstantAppResolverService.InstantAppResolutionCallback);
+ method @Deprecated public void onGetInstantAppResolveInfo(@NonNull android.content.Intent, @Nullable int[], @NonNull android.os.UserHandle, @NonNull String, @NonNull android.app.InstantAppResolverService.InstantAppResolutionCallback);
+ method public void onGetInstantAppResolveInfo(@NonNull android.content.pm.InstantAppRequestInfo, @NonNull android.app.InstantAppResolverService.InstantAppResolutionCallback);
}
public static final class InstantAppResolverService.InstantAppResolutionCallback {
@@ -809,6 +811,14 @@ package android.app.admin {
}
+package android.app.appsearch {
+
+ public class AppSearchManagerFrameworkInitializer {
+ method public static void initialize();
+ }
+
+}
+
package android.app.assist {
public static class AssistStructure.ViewNode {
@@ -1305,6 +1315,7 @@ package android.app.usage {
method @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS) public int getAppStandbyBucket(String);
method @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS) public java.util.Map<java.lang.String,java.lang.Integer> getAppStandbyBuckets();
method public int getUsageSource();
+ method @RequiresPermission(android.Manifest.permission.BIND_CARRIER_SERVICES) public void onCarrierPrivilegedAppsChanged();
method @RequiresPermission(allOf={android.Manifest.permission.SUSPEND_APPS, android.Manifest.permission.OBSERVE_APP_USAGE}) public void registerAppUsageLimitObserver(int, @NonNull String[], @NonNull java.time.Duration, @NonNull java.time.Duration, @Nullable android.app.PendingIntent);
method @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE) public void registerAppUsageObserver(int, @NonNull String[], long, @NonNull java.util.concurrent.TimeUnit, @NonNull android.app.PendingIntent);
method @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE) public void registerUsageSessionObserver(int, @NonNull String[], @NonNull java.time.Duration, @NonNull java.time.Duration, @NonNull android.app.PendingIntent, @Nullable android.app.PendingIntent);
@@ -1349,6 +1360,14 @@ package android.bluetooth {
field public static final int OPTIONAL_CODECS_SUPPORT_UNKNOWN = -1; // 0xffffffff
}
+ public final class BluetoothA2dpSink implements android.bluetooth.BluetoothProfile {
+ method public void finalize();
+ method @RequiresPermission(android.Manifest.permission.BLUETOOTH) public int getConnectionPolicy(@Nullable android.bluetooth.BluetoothDevice);
+ method @RequiresPermission(android.Manifest.permission.BLUETOOTH) public boolean isAudioPlaying(@Nullable android.bluetooth.BluetoothDevice);
+ method @RequiresPermission(android.Manifest.permission.BLUETOOTH_ADMIN) public boolean setConnectionPolicy(@Nullable android.bluetooth.BluetoothDevice, int);
+ field @RequiresPermission(android.Manifest.permission.BLUETOOTH) public static final String ACTION_CONNECTION_STATE_CHANGED = "android.bluetooth.a2dp-sink.profile.action.CONNECTION_STATE_CHANGED";
+ }
+
public final class BluetoothAdapter {
method @RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED) public boolean addOnMetadataChangedListener(@NonNull android.bluetooth.BluetoothDevice, @NonNull java.util.concurrent.Executor, @NonNull android.bluetooth.BluetoothAdapter.OnMetadataChangedListener);
method @RequiresPermission(android.Manifest.permission.BLUETOOTH_ADMIN) public boolean connectAllEnabledProfiles(@NonNull android.bluetooth.BluetoothDevice);
@@ -1423,15 +1442,24 @@ package android.bluetooth {
public final class BluetoothDevice implements android.os.Parcelable {
method @RequiresPermission(android.Manifest.permission.BLUETOOTH_ADMIN) public boolean cancelBondProcess();
+ method public boolean cancelPairing();
+ method @RequiresPermission(android.Manifest.permission.BLUETOOTH) public int getBatteryLevel();
+ method @RequiresPermission(android.Manifest.permission.BLUETOOTH) public int getMessageAccessPermission();
method @Nullable @RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED) public byte[] getMetadata(int);
+ method @RequiresPermission(android.Manifest.permission.BLUETOOTH) public int getPhonebookAccessPermission();
+ method @RequiresPermission(android.Manifest.permission.BLUETOOTH) public int getSimAccessPermission();
+ method @RequiresPermission(android.Manifest.permission.BLUETOOTH) public boolean isBondingInitiatedLocally();
method @RequiresPermission(android.Manifest.permission.BLUETOOTH) public boolean isConnected();
method @RequiresPermission(android.Manifest.permission.BLUETOOTH) public boolean isEncrypted();
method @RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED) public boolean isInSilenceMode();
method @RequiresPermission(android.Manifest.permission.BLUETOOTH_ADMIN) public boolean removeBond();
method @RequiresPermission(android.Manifest.permission.BLUETOOTH) public boolean setAlias(@NonNull String);
+ method @RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED) public boolean setMessageAccessPermission(int);
method @RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED) public boolean setMetadata(int, @NonNull byte[]);
method @RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED) public boolean setPhonebookAccessPermission(int);
+ method @RequiresPermission(android.Manifest.permission.BLUETOOTH_ADMIN) public boolean setPin(@Nullable String);
method @RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED) public boolean setSilenceMode(boolean);
+ method @RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED) public boolean setSimAccessPermission(int);
field public static final int ACCESS_ALLOWED = 1; // 0x1
field public static final int ACCESS_REJECTED = 2; // 0x2
field public static final int ACCESS_UNKNOWN = 0; // 0x0
@@ -1466,7 +1494,9 @@ package android.bluetooth {
}
public final class BluetoothHearingAid implements android.bluetooth.BluetoothProfile {
+ method @NonNull @RequiresPermission(android.Manifest.permission.BLUETOOTH) public java.util.List<android.bluetooth.BluetoothDevice> getActiveDevices();
method @RequiresPermission(android.Manifest.permission.BLUETOOTH) public int getConnectionPolicy(@NonNull android.bluetooth.BluetoothDevice);
+ method @RequiresPermission(android.Manifest.permission.BLUETOOTH) public long getHiSyncId(@Nullable android.bluetooth.BluetoothDevice);
method @RequiresPermission(android.Manifest.permission.BLUETOOTH_ADMIN) public boolean setConnectionPolicy(@NonNull android.bluetooth.BluetoothDevice, int);
}
@@ -1485,6 +1515,11 @@ package android.bluetooth {
field public static final int REMOTE_PANU_ROLE = 2; // 0x2
}
+ public class BluetoothPbap implements android.bluetooth.BluetoothProfile {
+ method public int getConnectionState(@Nullable android.bluetooth.BluetoothDevice);
+ field public static final String ACTION_CONNECTION_STATE_CHANGED = "android.bluetooth.pbap.profile.action.CONNECTION_STATE_CHANGED";
+ }
+
public interface BluetoothProfile {
field public static final int CONNECTION_POLICY_ALLOWED = 100; // 0x64
field public static final int CONNECTION_POLICY_FORBIDDEN = 0; // 0x0
@@ -1616,6 +1651,7 @@ package android.content {
field public static final String STATS_MANAGER = "stats";
field public static final String STATUS_BAR_SERVICE = "statusbar";
field public static final String SYSTEM_UPDATE_SERVICE = "system_update";
+ field public static final String TELEPHONY_IMS_SERVICE = "telephony_ims";
field public static final String TELEPHONY_REGISTRY_SERVICE = "telephony_registry";
field public static final String VR_SERVICE = "vrmanager";
field @Deprecated public static final String WIFI_RTT_SERVICE = "rttmanager";
@@ -1686,9 +1722,25 @@ package android.content {
field public static final String EXTRA_REMOTE_CALLBACK = "android.intent.extra.REMOTE_CALLBACK";
field public static final String EXTRA_RESULT_NEEDED = "android.intent.extra.RESULT_NEEDED";
field public static final String EXTRA_ROLE_NAME = "android.intent.extra.ROLE_NAME";
+ field @Deprecated public static final String EXTRA_SIM_LOCKED_REASON = "reason";
+ field @Deprecated public static final String EXTRA_SIM_STATE = "ss";
field public static final String EXTRA_UNKNOWN_INSTANT_APP = "android.intent.extra.UNKNOWN_INSTANT_APP";
field public static final String EXTRA_VERIFICATION_BUNDLE = "android.intent.extra.VERIFICATION_BUNDLE";
field public static final String METADATA_SETUP_VERSION = "android.SETUP_VERSION";
+ field @Deprecated public static final String SIM_ABSENT_ON_PERM_DISABLED = "PERM_DISABLED";
+ field @Deprecated public static final String SIM_LOCKED_NETWORK = "NETWORK";
+ field @Deprecated public static final String SIM_LOCKED_ON_PIN = "PIN";
+ field @Deprecated public static final String SIM_LOCKED_ON_PUK = "PUK";
+ field @Deprecated public static final String SIM_STATE_ABSENT = "ABSENT";
+ field @Deprecated public static final String SIM_STATE_CARD_IO_ERROR = "CARD_IO_ERROR";
+ field @Deprecated public static final String SIM_STATE_CARD_RESTRICTED = "CARD_RESTRICTED";
+ field @Deprecated public static final String SIM_STATE_IMSI = "IMSI";
+ field @Deprecated public static final String SIM_STATE_LOADED = "LOADED";
+ field @Deprecated public static final String SIM_STATE_LOCKED = "LOCKED";
+ field @Deprecated public static final String SIM_STATE_NOT_READY = "NOT_READY";
+ field @Deprecated public static final String SIM_STATE_PRESENT = "PRESENT";
+ field @Deprecated public static final String SIM_STATE_READY = "READY";
+ field @Deprecated public static final String SIM_STATE_UNKNOWN = "UNKNOWN";
}
public class IntentFilter implements android.os.Parcelable {
@@ -1730,7 +1782,7 @@ package android.content.integrity {
}
public abstract class AtomicFormula implements android.content.integrity.Formula {
- ctor public AtomicFormula(@android.content.integrity.AtomicFormula.Key int);
+ ctor public AtomicFormula(int);
method public int getKey();
field public static final int APP_CERTIFICATE = 1; // 0x1
field public static final int EQ = 0; // 0x0
@@ -1746,7 +1798,7 @@ package android.content.integrity {
}
public static final class AtomicFormula.BooleanAtomicFormula extends android.content.integrity.AtomicFormula implements android.os.Parcelable {
- ctor public AtomicFormula.BooleanAtomicFormula(@android.content.integrity.AtomicFormula.Key int, boolean);
+ ctor public AtomicFormula.BooleanAtomicFormula(int, boolean);
method public int describeContents();
method public int getTag();
method public boolean getValue();
@@ -1756,7 +1808,7 @@ package android.content.integrity {
}
public static final class AtomicFormula.IntAtomicFormula extends android.content.integrity.AtomicFormula implements android.os.Parcelable {
- ctor public AtomicFormula.IntAtomicFormula(@android.content.integrity.AtomicFormula.Key int, @android.content.integrity.AtomicFormula.Operator int, int);
+ ctor public AtomicFormula.IntAtomicFormula(int, int, int);
method public int describeContents();
method public int getOperator();
method public int getTag();
@@ -1766,14 +1818,8 @@ package android.content.integrity {
field @NonNull public static final android.os.Parcelable.Creator<android.content.integrity.AtomicFormula.IntAtomicFormula> CREATOR;
}
- @IntDef({android.content.integrity.AtomicFormula.PACKAGE_NAME, android.content.integrity.AtomicFormula.APP_CERTIFICATE, android.content.integrity.AtomicFormula.INSTALLER_NAME, android.content.integrity.AtomicFormula.INSTALLER_CERTIFICATE, android.content.integrity.AtomicFormula.VERSION_CODE, android.content.integrity.AtomicFormula.PRE_INSTALLED}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface AtomicFormula.Key {
- }
-
- @IntDef({android.content.integrity.AtomicFormula.EQ, android.content.integrity.AtomicFormula.LT, android.content.integrity.AtomicFormula.LE, android.content.integrity.AtomicFormula.GT, android.content.integrity.AtomicFormula.GE}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface AtomicFormula.Operator {
- }
-
public static final class AtomicFormula.StringAtomicFormula extends android.content.integrity.AtomicFormula implements android.os.Parcelable {
- ctor public AtomicFormula.StringAtomicFormula(@android.content.integrity.AtomicFormula.Key int, @NonNull String, boolean);
+ ctor public AtomicFormula.StringAtomicFormula(int, @NonNull String, boolean);
method public int describeContents();
method public boolean getIsHashedValue();
method public int getTag();
@@ -1784,9 +1830,9 @@ package android.content.integrity {
}
public final class CompoundFormula implements android.content.integrity.Formula android.os.Parcelable {
- ctor public CompoundFormula(@android.content.integrity.CompoundFormula.Connector int, @NonNull java.util.List<android.content.integrity.Formula>);
+ ctor public CompoundFormula(int, @NonNull java.util.List<android.content.integrity.Formula>);
method public int describeContents();
- method @android.content.integrity.CompoundFormula.Connector public int getConnector();
+ method public int getConnector();
method @NonNull public java.util.List<android.content.integrity.Formula> getFormulas();
method public int getTag();
method public boolean isSatisfied(@NonNull android.content.integrity.AppInstallMetadata);
@@ -1797,11 +1843,8 @@ package android.content.integrity {
field public static final int OR = 1; // 0x1
}
- @IntDef({android.content.integrity.CompoundFormula.AND, android.content.integrity.CompoundFormula.OR, android.content.integrity.CompoundFormula.NOT}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface CompoundFormula.Connector {
- }
-
public interface Formula {
- method @android.content.integrity.Formula.Tag public int getTag();
+ method public int getTag();
method public boolean isSatisfied(@NonNull android.content.integrity.AppInstallMetadata);
method @NonNull public static android.content.integrity.Formula readFromParcel(@NonNull android.os.Parcel);
method public static void writeToParcel(@NonNull android.content.integrity.Formula, @NonNull android.os.Parcel, int);
@@ -1811,13 +1854,10 @@ package android.content.integrity {
field public static final int STRING_ATOMIC_FORMULA_TAG = 1; // 0x1
}
- @IntDef({android.content.integrity.Formula.COMPOUND_FORMULA_TAG, android.content.integrity.Formula.STRING_ATOMIC_FORMULA_TAG, android.content.integrity.Formula.INT_ATOMIC_FORMULA_TAG, android.content.integrity.Formula.BOOLEAN_ATOMIC_FORMULA_TAG}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface Formula.Tag {
- }
-
public final class Rule implements android.os.Parcelable {
- ctor public Rule(@NonNull android.content.integrity.Formula, @android.content.integrity.Rule.Effect int);
+ ctor public Rule(@NonNull android.content.integrity.Formula, int);
method public int describeContents();
- method @android.content.integrity.Rule.Effect public int getEffect();
+ method public int getEffect();
method @NonNull public android.content.integrity.Formula getFormula();
method public void writeToParcel(@NonNull android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.content.integrity.Rule> CREATOR;
@@ -1825,9 +1865,6 @@ package android.content.integrity {
field public static final int FORCE_ALLOW = 1; // 0x1
}
- @IntDef({android.content.integrity.Rule.DENY, android.content.integrity.Rule.FORCE_ALLOW}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface Rule.Effect {
- }
-
public class RuleSet {
method @NonNull public java.util.List<android.content.integrity.Rule> getRules();
method @NonNull public String getVersion();
@@ -1901,6 +1938,18 @@ package android.content.pm {
field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.InstantAppIntentFilter> CREATOR;
}
+ public final class InstantAppRequestInfo implements android.os.Parcelable {
+ ctor public InstantAppRequestInfo(@NonNull android.content.Intent, @Nullable int[], @NonNull android.os.UserHandle, boolean, @NonNull String);
+ method public int describeContents();
+ method public void writeToParcel(@NonNull android.os.Parcel, int);
+ field @NonNull public static final android.os.Parcelable.Creator<android.content.pm.InstantAppRequestInfo> CREATOR;
+ field @Nullable public final int[] hostDigestPrefix;
+ field @NonNull public final android.content.Intent intent;
+ field public final boolean isRequesterInstantApp;
+ field @NonNull public final String token;
+ field @NonNull public final android.os.UserHandle userHandle;
+ }
+
public final class InstantAppResolveInfo implements android.os.Parcelable {
ctor public InstantAppResolveInfo(@NonNull android.content.pm.InstantAppResolveInfo.InstantAppDigest, @Nullable String, @Nullable java.util.List<android.content.pm.InstantAppIntentFilter>, int);
ctor public InstantAppResolveInfo(@NonNull android.content.pm.InstantAppResolveInfo.InstantAppDigest, @Nullable String, @Nullable java.util.List<android.content.pm.InstantAppIntentFilter>, long, @Nullable android.os.Bundle);
@@ -2264,6 +2313,15 @@ package android.hardware {
}
+package android.hardware.biometrics {
+
+ public static interface BiometricManager.Authenticators {
+ field public static final int BIOMETRIC_CONVENIENCE = 4095; // 0xfff
+ field public static final int EMPTY_SET = 0; // 0x0
+ }
+
+}
+
package android.hardware.camera2 {
public abstract class CameraDevice implements java.lang.AutoCloseable {
@@ -3409,6 +3467,14 @@ package android.hardware.soundtrigger {
field public static final int STATUS_OK = 0; // 0x0
}
+ public static final class SoundTrigger.ModelParamRange implements android.os.Parcelable {
+ method public int describeContents();
+ method public void writeToParcel(@NonNull android.os.Parcel, int);
+ field @NonNull public static final android.os.Parcelable.Creator<android.hardware.soundtrigger.SoundTrigger.ModelParamRange> CREATOR;
+ field public final int end;
+ field public final int start;
+ }
+
public static final class SoundTrigger.ModuleProperties implements android.os.Parcelable {
method public int describeContents();
method public void writeToParcel(android.os.Parcel, int);
@@ -3878,6 +3944,7 @@ package android.media {
field public static final int FLAG_BYPASS_INTERRUPTION_POLICY = 64; // 0x40
field public static final int FLAG_BYPASS_MUTE = 128; // 0x80
field public static final int FLAG_HW_HOTWORD = 32; // 0x20
+ field @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public static final int USAGE_CALL_ASSISTANT = 17; // 0x11
}
public static class AudioAttributes.Builder {
@@ -3928,16 +3995,19 @@ package android.media {
method @NonNull @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public static java.util.List<android.media.audiopolicy.AudioVolumeGroup> getAudioVolumeGroups();
method @IntRange(from=0) @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public int getMaxVolumeIndexForAttributes(@NonNull android.media.AudioAttributes);
method @IntRange(from=0) @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public int getMinVolumeIndexForAttributes(@NonNull android.media.AudioAttributes);
+ method @Nullable @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public android.media.AudioDeviceAddress getPreferredDeviceForStrategy(@NonNull android.media.audiopolicy.AudioProductStrategy);
method @IntRange(from=0) @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public int getVolumeIndexForAttributes(@NonNull android.media.AudioAttributes);
method public boolean isAudioServerRunning();
method public boolean isHdmiSystemAudioSupported();
method @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public int registerAudioPolicy(@NonNull android.media.audiopolicy.AudioPolicy);
method public void registerVolumeGroupCallback(@NonNull java.util.concurrent.Executor, @NonNull android.media.AudioManager.VolumeGroupCallback);
+ method @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public boolean removePreferredDeviceForStrategy(@NonNull android.media.audiopolicy.AudioProductStrategy);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public int requestAudioFocus(android.media.AudioManager.OnAudioFocusChangeListener, @NonNull android.media.AudioAttributes, int, int) throws java.lang.IllegalArgumentException;
method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.MODIFY_PHONE_STATE, android.Manifest.permission.MODIFY_AUDIO_ROUTING}) public int requestAudioFocus(android.media.AudioManager.OnAudioFocusChangeListener, @NonNull android.media.AudioAttributes, int, int, android.media.audiopolicy.AudioPolicy) throws java.lang.IllegalArgumentException;
method @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public int requestAudioFocus(@NonNull android.media.AudioFocusRequest, @Nullable android.media.audiopolicy.AudioPolicy);
method public void setAudioServerStateCallback(@NonNull java.util.concurrent.Executor, @NonNull android.media.AudioManager.AudioServerStateCallback);
method @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public void setFocusRequestResult(@NonNull android.media.AudioFocusInfo, int, @NonNull android.media.audiopolicy.AudioPolicy);
+ method @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public boolean setPreferredDeviceForStrategy(@NonNull android.media.audiopolicy.AudioProductStrategy, @NonNull android.media.AudioDeviceAddress);
method @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public void setVolumeIndexForAttributes(@NonNull android.media.AudioAttributes, int, int);
method @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public void unregisterAudioPolicy(@NonNull android.media.audiopolicy.AudioPolicy);
method @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) public void unregisterAudioPolicyAsync(@NonNull android.media.audiopolicy.AudioPolicy);
@@ -4108,9 +4178,11 @@ package android.media.audiopolicy {
}
public final class AudioProductStrategy implements android.os.Parcelable {
+ method @NonNull public static android.media.audiopolicy.AudioProductStrategy createInvalidAudioProductStrategy(int);
method public int describeContents();
method @NonNull public android.media.AudioAttributes getAudioAttributes();
method public int getId();
+ method public boolean supportsAudioAttributes(@NonNull android.media.AudioAttributes);
method public void writeToParcel(@NonNull android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.media.audiopolicy.AudioProductStrategy> CREATOR;
}
@@ -4131,18 +4203,20 @@ package android.media.audiopolicy {
package android.media.session {
public final class MediaSessionManager {
- method @RequiresPermission(android.Manifest.permission.MEDIA_CONTENT_CONTROL) public void registerCallback(@NonNull java.util.concurrent.Executor, @NonNull android.media.session.MediaSessionManager.Callback);
+ method @RequiresPermission(android.Manifest.permission.MEDIA_CONTENT_CONTROL) public void addOnMediaKeyEventDispatchedListener(@NonNull java.util.concurrent.Executor, @NonNull android.media.session.MediaSessionManager.OnMediaKeyEventDispatchedListener);
+ method @RequiresPermission(android.Manifest.permission.MEDIA_CONTENT_CONTROL) public void addOnMediaKeyEventSessionChangedListener(@NonNull java.util.concurrent.Executor, @NonNull android.media.session.MediaSessionManager.OnMediaKeyEventSessionChangedListener);
+ method @RequiresPermission(android.Manifest.permission.MEDIA_CONTENT_CONTROL) public void removeOnMediaKeyEventDispatchedListener(@NonNull android.media.session.MediaSessionManager.OnMediaKeyEventDispatchedListener);
+ method @RequiresPermission(android.Manifest.permission.MEDIA_CONTENT_CONTROL) public void removeOnMediaKeyEventSessionChangedListener(@NonNull android.media.session.MediaSessionManager.OnMediaKeyEventSessionChangedListener);
method @RequiresPermission(android.Manifest.permission.SET_MEDIA_KEY_LISTENER) public void setOnMediaKeyListener(android.media.session.MediaSessionManager.OnMediaKeyListener, @Nullable android.os.Handler);
method @RequiresPermission(android.Manifest.permission.SET_VOLUME_KEY_LONG_PRESS_LISTENER) public void setOnVolumeKeyLongPressListener(android.media.session.MediaSessionManager.OnVolumeKeyLongPressListener, @Nullable android.os.Handler);
- method @RequiresPermission(android.Manifest.permission.MEDIA_CONTENT_CONTROL) public void unregisterCallback(@NonNull android.media.session.MediaSessionManager.Callback);
}
- public abstract static class MediaSessionManager.Callback {
- ctor public MediaSessionManager.Callback();
- method public abstract void onAddressedPlayerChanged(android.media.session.MediaSession.Token);
- method public abstract void onAddressedPlayerChanged(android.content.ComponentName);
- method public abstract void onMediaKeyEventDispatched(android.view.KeyEvent, android.media.session.MediaSession.Token);
- method public abstract void onMediaKeyEventDispatched(android.view.KeyEvent, android.content.ComponentName);
+ public static interface MediaSessionManager.OnMediaKeyEventDispatchedListener {
+ method public default void onMediaKeyEventDispatched(@NonNull android.view.KeyEvent, @NonNull String, @NonNull android.media.session.MediaSession.Token);
+ }
+
+ public static interface MediaSessionManager.OnMediaKeyEventSessionChangedListener {
+ method public default void onMediaKeyEventSessionChanged(@NonNull String, @Nullable android.media.session.MediaSession.Token);
}
public static interface MediaSessionManager.OnMediaKeyListener {
@@ -4192,8 +4266,11 @@ package android.media.soundtrigger {
method @Nullable @RequiresPermission(android.Manifest.permission.MANAGE_SOUND_TRIGGER) public android.media.soundtrigger.SoundTriggerDetector createSoundTriggerDetector(java.util.UUID, @NonNull android.media.soundtrigger.SoundTriggerDetector.Callback, @Nullable android.os.Handler);
method @RequiresPermission(android.Manifest.permission.MANAGE_SOUND_TRIGGER) public void deleteModel(java.util.UUID);
method public int getDetectionServiceOperationsTimeout();
- method @RequiresPermission(android.Manifest.permission.MANAGE_SOUND_TRIGGER) public android.media.soundtrigger.SoundTriggerManager.Model getModel(java.util.UUID);
+ method @Nullable @RequiresPermission(android.Manifest.permission.MANAGE_SOUND_TRIGGER) public android.media.soundtrigger.SoundTriggerManager.Model getModel(java.util.UUID);
method @Nullable @RequiresPermission(android.Manifest.permission.MANAGE_SOUND_TRIGGER) public android.hardware.soundtrigger.SoundTrigger.ModuleProperties getModuleProperties();
+ method @RequiresPermission(android.Manifest.permission.MANAGE_SOUND_TRIGGER) public int getParameter(@NonNull java.util.UUID, int) throws java.lang.IllegalArgumentException, java.lang.UnsupportedOperationException;
+ method @Nullable @RequiresPermission(android.Manifest.permission.MANAGE_SOUND_TRIGGER) public android.hardware.soundtrigger.SoundTrigger.ModelParamRange queryParameter(@Nullable java.util.UUID, int);
+ method @RequiresPermission(android.Manifest.permission.MANAGE_SOUND_TRIGGER) public int setParameter(@Nullable java.util.UUID, int, int) throws java.lang.IllegalArgumentException, java.lang.UnsupportedOperationException;
method @RequiresPermission(android.Manifest.permission.MANAGE_SOUND_TRIGGER) public void updateModel(android.media.soundtrigger.SoundTriggerManager.Model);
}
@@ -4350,6 +4427,7 @@ package android.media.tv {
method @Nullable public String onHardwareRemoved(android.media.tv.TvInputHardwareInfo);
method @Nullable public android.media.tv.TvInputInfo onHdmiDeviceAdded(android.hardware.hdmi.HdmiDeviceInfo);
method @Nullable public String onHdmiDeviceRemoved(android.hardware.hdmi.HdmiDeviceInfo);
+ method public void onHdmiDeviceUpdated(@NonNull android.hardware.hdmi.HdmiDeviceInfo);
}
public abstract static class TvInputService.RecordingSession {
@@ -4492,6 +4570,14 @@ package android.net {
method public void onUpstreamChanged(@Nullable android.net.Network);
}
+ public class InvalidPacketException extends java.lang.Exception {
+ ctor public InvalidPacketException(int);
+ field public static final int ERROR_INVALID_IP_ADDRESS = -21; // 0xffffffeb
+ field public static final int ERROR_INVALID_LENGTH = -23; // 0xffffffe9
+ field public static final int ERROR_INVALID_PORT = -22; // 0xffffffea
+ field public final int error;
+ }
+
public final class IpConfiguration implements android.os.Parcelable {
ctor public IpConfiguration();
ctor public IpConfiguration(@NonNull android.net.IpConfiguration);
@@ -4542,6 +4628,15 @@ package android.net {
method @NonNull @RequiresPermission(android.Manifest.permission.MANAGE_IPSEC_TUNNELS) public android.net.IpSecTransform buildTunnelModeTransform(@NonNull java.net.InetAddress, @NonNull android.net.IpSecManager.SecurityParameterIndex) throws java.io.IOException, android.net.IpSecManager.ResourceUnavailableException, android.net.IpSecManager.SpiUnavailableException;
}
+ public class KeepalivePacketData {
+ ctor protected KeepalivePacketData(@NonNull java.net.InetAddress, int, @NonNull java.net.InetAddress, int, @NonNull byte[]) throws android.net.InvalidPacketException;
+ method @NonNull public byte[] getPacket();
+ field @NonNull public final java.net.InetAddress dstAddress;
+ field public final int dstPort;
+ field @NonNull public final java.net.InetAddress srcAddress;
+ field public final int srcPort;
+ }
+
public class LinkAddress implements android.os.Parcelable {
ctor public LinkAddress(@NonNull java.net.InetAddress, @IntRange(from=0, to=128) int, int, int);
ctor public LinkAddress(@NonNull java.net.InetAddress, @IntRange(from=0, to=128) int);
@@ -4557,12 +4652,20 @@ package android.net {
ctor public LinkProperties(@Nullable android.net.LinkProperties);
method public boolean addDnsServer(@NonNull java.net.InetAddress);
method public boolean addLinkAddress(@NonNull android.net.LinkAddress);
+ method public boolean addPcscfServer(@NonNull java.net.InetAddress);
+ method @NonNull public java.util.List<java.net.InetAddress> getAddresses();
+ method @NonNull public java.util.List<java.lang.String> getAllInterfaceNames();
+ method @NonNull public java.util.List<android.net.LinkAddress> getAllLinkAddresses();
+ method @NonNull public java.util.List<android.net.RouteInfo> getAllRoutes();
method @NonNull public java.util.List<java.net.InetAddress> getPcscfServers();
method @Nullable public String getTcpBufferSizes();
method @NonNull public java.util.List<java.net.InetAddress> getValidatedPrivateDnsServers();
method public boolean hasGlobalIpv6Address();
method public boolean hasIpv4Address();
+ method public boolean hasIpv4DefaultRoute();
+ method public boolean hasIpv4DnsServer();
method public boolean hasIpv6DefaultRoute();
+ method public boolean hasIpv6DnsServer();
method public boolean isIpv4Provisioned();
method public boolean isIpv6Provisioned();
method public boolean isProvisioned();
@@ -4821,11 +4924,14 @@ package android.net.ipsec.ike {
method @NonNull public java.util.List<android.net.LinkAddress> getInternalAddresses();
method @NonNull public java.util.List<java.net.InetAddress> getInternalDhcpServers();
method @NonNull public java.util.List<java.net.InetAddress> getInternalDnsServers();
- method @NonNull public java.util.List<android.net.LinkAddress> getInternalSubnets();
+ method @NonNull public java.util.List<android.net.IpPrefix> getInternalSubnets();
method @NonNull public java.util.List<android.net.ipsec.ike.IkeTrafficSelector> getOutboundTrafficSelectors();
}
public abstract class ChildSessionParams {
+ method @NonNull public java.util.List<android.net.ipsec.ike.IkeTrafficSelector> getLocalTrafficSelectors();
+ method @NonNull public java.util.List<android.net.ipsec.ike.IkeTrafficSelector> getRemoteTrafficSelectors();
+ method @NonNull public java.util.List<android.net.ipsec.ike.ChildSaProposal> getSaProposals();
}
public class IkeFqdnIdentification extends android.net.ipsec.ike.IkeIdentification {
@@ -4887,21 +4993,29 @@ package android.net.ipsec.ike {
public final class IkeSessionConfiguration {
ctor public IkeSessionConfiguration();
method @NonNull public String getRemoteApplicationVersion();
+ method @NonNull public java.util.List<byte[]> getRemoteVendorIDs();
method public boolean isIkeExtensionEnabled(int);
field public static final int EXTENSION_TYPE_FRAGMENTATION = 1; // 0x1
field public static final int EXTENSION_TYPE_MOBIKE = 2; // 0x2
}
public final class IkeSessionParams {
+ method @NonNull public android.net.ipsec.ike.IkeSessionParams.IkeAuthConfig getLocalAuthConfig();
+ method @NonNull public android.net.ipsec.ike.IkeIdentification getLocalIdentification();
+ method @NonNull public android.net.ipsec.ike.IkeSessionParams.IkeAuthConfig getRemoteAuthConfig();
+ method @NonNull public android.net.ipsec.ike.IkeIdentification getRemoteIdentification();
+ method @NonNull public java.util.List<android.net.ipsec.ike.IkeSaProposal> getSaProposals();
+ method @NonNull public java.net.InetAddress getServerAddress();
+ method @NonNull public android.net.IpSecManager.UdpEncapsulationSocket getUdpEncapsulationSocket();
}
public static final class IkeSessionParams.Builder {
ctor public IkeSessionParams.Builder();
method @NonNull public android.net.ipsec.ike.IkeSessionParams.Builder addSaProposal(@NonNull android.net.ipsec.ike.IkeSaProposal);
method @NonNull public android.net.ipsec.ike.IkeSessionParams build();
- method @NonNull public android.net.ipsec.ike.IkeSessionParams.Builder setAuthDigitalSignature(@NonNull java.security.cert.X509Certificate, @NonNull java.security.cert.X509Certificate, @NonNull java.security.PrivateKey);
- method @NonNull public android.net.ipsec.ike.IkeSessionParams.Builder setAuthDigitalSignature(@NonNull java.security.cert.X509Certificate, @NonNull java.security.cert.X509Certificate, @NonNull java.util.List<java.security.cert.X509Certificate>, @NonNull java.security.PrivateKey);
- method @NonNull public android.net.ipsec.ike.IkeSessionParams.Builder setAuthEap(@NonNull java.security.cert.X509Certificate, @NonNull android.net.eap.EapSessionConfig);
+ method @NonNull public android.net.ipsec.ike.IkeSessionParams.Builder setAuthDigitalSignature(@Nullable java.security.cert.X509Certificate, @NonNull java.security.cert.X509Certificate, @NonNull java.security.PrivateKey);
+ method @NonNull public android.net.ipsec.ike.IkeSessionParams.Builder setAuthDigitalSignature(@Nullable java.security.cert.X509Certificate, @NonNull java.security.cert.X509Certificate, @NonNull java.util.List<java.security.cert.X509Certificate>, @NonNull java.security.PrivateKey);
+ method @NonNull public android.net.ipsec.ike.IkeSessionParams.Builder setAuthEap(@Nullable java.security.cert.X509Certificate, @NonNull android.net.eap.EapSessionConfig);
method @NonNull public android.net.ipsec.ike.IkeSessionParams.Builder setAuthPsk(@NonNull byte[]);
method @NonNull public android.net.ipsec.ike.IkeSessionParams.Builder setLocalIdentification(@NonNull android.net.ipsec.ike.IkeIdentification);
method @NonNull public android.net.ipsec.ike.IkeSessionParams.Builder setRemoteIdentification(@NonNull android.net.ipsec.ike.IkeIdentification);
@@ -4909,6 +5023,27 @@ package android.net.ipsec.ike {
method @NonNull public android.net.ipsec.ike.IkeSessionParams.Builder setUdpEncapsulationSocket(@NonNull android.net.IpSecManager.UdpEncapsulationSocket);
}
+ public abstract static class IkeSessionParams.IkeAuthConfig {
+ }
+
+ public static class IkeSessionParams.IkeAuthDigitalSignLocalConfig extends android.net.ipsec.ike.IkeSessionParams.IkeAuthConfig {
+ method @NonNull public java.security.cert.X509Certificate getClientEndCertificate();
+ method @NonNull public java.util.List<java.security.cert.X509Certificate> getIntermediateCertificates();
+ method @NonNull public java.security.PrivateKey getPrivateKey();
+ }
+
+ public static class IkeSessionParams.IkeAuthDigitalSignRemoteConfig extends android.net.ipsec.ike.IkeSessionParams.IkeAuthConfig {
+ method @Nullable public java.security.cert.X509Certificate getRemoteCaCert();
+ }
+
+ public static class IkeSessionParams.IkeAuthEapConfig extends android.net.ipsec.ike.IkeSessionParams.IkeAuthConfig {
+ method @NonNull public android.net.eap.EapSessionConfig getEapConfig();
+ }
+
+ public static class IkeSessionParams.IkeAuthPskConfig extends android.net.ipsec.ike.IkeSessionParams.IkeAuthConfig {
+ method @NonNull public byte[] getPsk();
+ }
+
public final class IkeTrafficSelector {
ctor public IkeTrafficSelector(int, int, @NonNull java.net.InetAddress, @NonNull java.net.InetAddress);
field public final int endPort;
@@ -4955,23 +5090,49 @@ package android.net.ipsec.ike {
}
public final class TunnelModeChildSessionParams extends android.net.ipsec.ike.ChildSessionParams {
+ method @NonNull public java.util.List<android.net.ipsec.ike.TunnelModeChildSessionParams.ConfigRequest> getConfigurationRequests();
}
public static final class TunnelModeChildSessionParams.Builder {
ctor public TunnelModeChildSessionParams.Builder();
method @NonNull public android.net.ipsec.ike.TunnelModeChildSessionParams.Builder addInboundTrafficSelectors(@NonNull android.net.ipsec.ike.IkeTrafficSelector);
method @NonNull public android.net.ipsec.ike.TunnelModeChildSessionParams.Builder addInternalAddressRequest(int);
- method @NonNull public android.net.ipsec.ike.TunnelModeChildSessionParams.Builder addInternalAddressRequest(@NonNull java.net.InetAddress, int);
+ method @NonNull public android.net.ipsec.ike.TunnelModeChildSessionParams.Builder addInternalAddressRequest(@NonNull java.net.Inet4Address);
+ method @NonNull public android.net.ipsec.ike.TunnelModeChildSessionParams.Builder addInternalAddressRequest(@NonNull java.net.Inet6Address, int);
method @NonNull public android.net.ipsec.ike.TunnelModeChildSessionParams.Builder addInternalDhcpServerRequest(int);
- method @NonNull public android.net.ipsec.ike.TunnelModeChildSessionParams.Builder addInternalDhcpServerRequest(@NonNull java.net.InetAddress);
method @NonNull public android.net.ipsec.ike.TunnelModeChildSessionParams.Builder addInternalDnsServerRequest(int);
- method @NonNull public android.net.ipsec.ike.TunnelModeChildSessionParams.Builder addInternalDnsServerRequest(@NonNull java.net.InetAddress);
- method @NonNull public android.net.ipsec.ike.TunnelModeChildSessionParams.Builder addInternalSubnetRequest(int);
method @NonNull public android.net.ipsec.ike.TunnelModeChildSessionParams.Builder addOutboundTrafficSelectors(@NonNull android.net.ipsec.ike.IkeTrafficSelector);
method @NonNull public android.net.ipsec.ike.TunnelModeChildSessionParams.Builder addSaProposal(@NonNull android.net.ipsec.ike.ChildSaProposal);
method @NonNull public android.net.ipsec.ike.TunnelModeChildSessionParams build();
}
+ public static interface TunnelModeChildSessionParams.ConfigRequest {
+ }
+
+ public static interface TunnelModeChildSessionParams.ConfigRequestIpv4Address extends android.net.ipsec.ike.TunnelModeChildSessionParams.ConfigRequest {
+ method @Nullable public java.net.Inet4Address getAddress();
+ }
+
+ public static interface TunnelModeChildSessionParams.ConfigRequestIpv4DhcpServer extends android.net.ipsec.ike.TunnelModeChildSessionParams.ConfigRequest {
+ method @Nullable public java.net.Inet4Address getAddress();
+ }
+
+ public static interface TunnelModeChildSessionParams.ConfigRequestIpv4DnsServer extends android.net.ipsec.ike.TunnelModeChildSessionParams.ConfigRequest {
+ method @Nullable public java.net.Inet4Address getAddress();
+ }
+
+ public static interface TunnelModeChildSessionParams.ConfigRequestIpv4Netmask extends android.net.ipsec.ike.TunnelModeChildSessionParams.ConfigRequest {
+ }
+
+ public static interface TunnelModeChildSessionParams.ConfigRequestIpv6Address extends android.net.ipsec.ike.TunnelModeChildSessionParams.ConfigRequest {
+ method @Nullable public java.net.Inet6Address getAddress();
+ method public int getPrefixLength();
+ }
+
+ public static interface TunnelModeChildSessionParams.ConfigRequestIpv6DnsServer extends android.net.ipsec.ike.TunnelModeChildSessionParams.ConfigRequest {
+ method @Nullable public java.net.Inet6Address getAddress();
+ }
+
}
package android.net.ipsec.ike.exceptions {
@@ -5389,6 +5550,11 @@ package android.net.wifi {
field @Deprecated public byte id;
}
+ public class ScanResult implements android.os.Parcelable {
+ field public static final int KEY_MGMT_WAPI_CERT = 14; // 0xe
+ field public static final int KEY_MGMT_WAPI_PSK = 13; // 0xd
+ }
+
public final class SoftApConfiguration implements android.os.Parcelable {
method public int describeContents();
method public int getBand();
@@ -5399,9 +5565,10 @@ package android.net.wifi {
method @Nullable public String getWpa2Passphrase();
method public boolean isHiddenSsid();
method public void writeToParcel(@NonNull android.os.Parcel, int);
- field public static final int BAND_2GHZ = 0; // 0x0
- field public static final int BAND_5GHZ = 1; // 0x1
- field public static final int BAND_ANY = -1; // 0xffffffff
+ field public static final int BAND_2GHZ = 1; // 0x1
+ field public static final int BAND_5GHZ = 2; // 0x2
+ field public static final int BAND_6GHZ = 4; // 0x4
+ field public static final int BAND_ANY = 7; // 0x7
field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.SoftApConfiguration> CREATOR;
field public static final int SECURITY_TYPE_OPEN = 0; // 0x0
field public static final int SECURITY_TYPE_WPA2_PSK = 1; // 0x1
@@ -5413,7 +5580,7 @@ package android.net.wifi {
method @NonNull public android.net.wifi.SoftApConfiguration build();
method @NonNull public android.net.wifi.SoftApConfiguration.Builder setBand(int);
method @NonNull public android.net.wifi.SoftApConfiguration.Builder setBssid(@Nullable android.net.MacAddress);
- method @NonNull public android.net.wifi.SoftApConfiguration.Builder setChannel(int);
+ method @NonNull public android.net.wifi.SoftApConfiguration.Builder setChannel(int, int);
method @NonNull public android.net.wifi.SoftApConfiguration.Builder setHiddenSsid(boolean);
method @NonNull public android.net.wifi.SoftApConfiguration.Builder setSsid(@Nullable String);
method @NonNull public android.net.wifi.SoftApConfiguration.Builder setWpa2Passphrase(@Nullable String);
@@ -5486,6 +5653,8 @@ package android.net.wifi {
}
@Deprecated public static class WifiConfiguration.KeyMgmt {
+ field @Deprecated public static final int WAPI_CERT = 14; // 0xe
+ field @Deprecated public static final int WAPI_PSK = 13; // 0xd
field @Deprecated public static final int WPA2_PSK = 4; // 0x4
}
@@ -5522,10 +5691,12 @@ package android.net.wifi {
method @NonNull public String getCaPath();
method @NonNull public String getClientCertificateAlias();
method public int getOcsp();
+ method @Nullable public String getWapiCertSuite();
method public void setCaCertificateAliases(@Nullable String[]);
method public void setCaPath(@Nullable String);
method public void setClientCertificateAlias(@Nullable String);
method public void setOcsp(int);
+ method public void setWapiCertSuite(@Nullable String);
field public static final int OCSP_NONE = 0; // 0x0
field public static final int OCSP_REQUEST_CERT_STATUS = 1; // 0x1
field public static final int OCSP_REQUIRE_ALL_NON_TRUSTED_CERTS_STATUS = 3; // 0x3
@@ -5576,7 +5747,6 @@ package android.net.wifi {
method public boolean isApMacRandomizationSupported();
method public boolean isConnectedMacRandomizationSupported();
method @Deprecated public boolean isDeviceToDeviceRttSupported();
- method public boolean isDualBandSupported();
method @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) public boolean isDualModeSupported();
method public boolean isPortableHotspotSupported();
method @RequiresPermission(android.Manifest.permission.ACCESS_WIFI_STATE) public boolean isWifiApEnabled();
@@ -5589,10 +5759,10 @@ package android.net.wifi {
method @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) public void registerTrafficStateCallback(@NonNull java.util.concurrent.Executor, @NonNull android.net.wifi.WifiManager.TrafficStateCallback);
method @RequiresPermission(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE) public void removeOnWifiUsabilityStatsListener(@NonNull android.net.wifi.WifiManager.OnWifiUsabilityStatsListener);
method @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) public void restoreBackupData(@NonNull byte[]);
- method @Nullable @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) public void restoreSoftApBackupData(@NonNull byte[]);
+ method @Nullable @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) public android.net.wifi.SoftApConfiguration restoreSoftApBackupData(@NonNull byte[]);
method @Deprecated @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) public void restoreSupplicantBackupData(@NonNull byte[], @NonNull byte[]);
method @NonNull @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) public byte[] retrieveBackupData();
- method @Nullable @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) public byte[] retrieveSoftApBackupData();
+ method @NonNull @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) public byte[] retrieveSoftApBackupData();
method @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_SETTINGS, android.Manifest.permission.NETWORK_SETUP_WIZARD, android.Manifest.permission.NETWORK_STACK}) public void save(@NonNull android.net.wifi.WifiConfiguration, @Nullable android.net.wifi.WifiManager.ActionListener);
method @RequiresPermission(android.Manifest.permission.WIFI_SET_DEVICE_MOBILITY_STATE) public void setDeviceMobilityState(int);
method @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) public boolean setSoftApConfiguration(@NonNull android.net.wifi.SoftApConfiguration);
@@ -6132,6 +6302,27 @@ package android.os {
method @RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS) public void noteWifiScanStoppedFromSource(@NonNull android.os.WorkSource);
method @RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS) public void noteWifiState(int, @Nullable String);
method @RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS) public void noteWifiSupplicantStateChanged(int, boolean);
+ field public static final int WIFI_STATE_OFF = 0; // 0x0
+ field public static final int WIFI_STATE_OFF_SCANNING = 1; // 0x1
+ field public static final int WIFI_STATE_ON_CONNECTED_P2P = 5; // 0x5
+ field public static final int WIFI_STATE_ON_CONNECTED_STA = 4; // 0x4
+ field public static final int WIFI_STATE_ON_CONNECTED_STA_P2P = 6; // 0x6
+ field public static final int WIFI_STATE_ON_DISCONNECTED = 3; // 0x3
+ field public static final int WIFI_STATE_ON_NO_NETWORKS = 2; // 0x2
+ field public static final int WIFI_STATE_SOFT_AP = 7; // 0x7
+ field public static final int WIFI_SUPPL_STATE_ASSOCIATED = 7; // 0x7
+ field public static final int WIFI_SUPPL_STATE_ASSOCIATING = 6; // 0x6
+ field public static final int WIFI_SUPPL_STATE_AUTHENTICATING = 5; // 0x5
+ field public static final int WIFI_SUPPL_STATE_COMPLETED = 10; // 0xa
+ field public static final int WIFI_SUPPL_STATE_DISCONNECTED = 1; // 0x1
+ field public static final int WIFI_SUPPL_STATE_DORMANT = 11; // 0xb
+ field public static final int WIFI_SUPPL_STATE_FOUR_WAY_HANDSHAKE = 8; // 0x8
+ field public static final int WIFI_SUPPL_STATE_GROUP_HANDSHAKE = 9; // 0x9
+ field public static final int WIFI_SUPPL_STATE_INACTIVE = 3; // 0x3
+ field public static final int WIFI_SUPPL_STATE_INTERFACE_DISABLED = 2; // 0x2
+ field public static final int WIFI_SUPPL_STATE_INVALID = 0; // 0x0
+ field public static final int WIFI_SUPPL_STATE_SCANNING = 4; // 0x4
+ field public static final int WIFI_SUPPL_STATE_UNINITIALIZED = 12; // 0xc
}
public class Binder implements android.os.IBinder {
@@ -6192,6 +6383,7 @@ package android.os {
}
public class Environment {
+ method @NonNull public static java.util.Collection<java.io.File> getInternalMediaDirectories();
method @NonNull public static java.io.File getOdmDirectory();
method @NonNull public static java.io.File getOemDirectory();
method @NonNull public static java.io.File getProductDirectory();
@@ -6523,6 +6715,21 @@ package android.os {
field public static final int STATUS_WAITING_REBOOT = 5; // 0x5
}
+ public class TelephonyServiceManager {
+ method @NonNull public android.os.TelephonyServiceManager.ServiceRegisterer getTelephonyServiceRegisterer();
+ }
+
+ public static class TelephonyServiceManager.ServiceNotFoundException extends java.lang.Exception {
+ ctor public TelephonyServiceManager.ServiceNotFoundException(@NonNull String);
+ }
+
+ public final class TelephonyServiceManager.ServiceRegisterer {
+ method @Nullable public android.os.IBinder get();
+ method @NonNull public android.os.IBinder getOrThrow() throws android.os.TelephonyServiceManager.ServiceNotFoundException;
+ method public void register(@NonNull android.os.IBinder);
+ method @Nullable public android.os.IBinder tryGet();
+ }
+
public class UpdateEngine {
ctor public UpdateEngine();
method public void applyPayload(String, long, long, String[]);
@@ -6731,6 +6938,14 @@ package android.os.connectivity {
}
+package android.os.ext {
+
+ public class SdkExtensions {
+ method public static int getExtensionVersion(int);
+ }
+
+}
+
package android.os.image {
public class DynamicSystemClient {
@@ -6806,7 +7021,7 @@ package android.permission {
method @BinderThread public abstract void onRevokeRuntimePermissions(@NonNull java.util.Map<java.lang.String,java.util.List<java.lang.String>>, boolean, int, @NonNull String, @NonNull java.util.function.Consumer<java.util.Map<java.lang.String,java.util.List<java.lang.String>>>);
method @BinderThread public abstract void onSetRuntimePermissionGrantStateByDeviceAdmin(@NonNull String, @NonNull String, @NonNull String, int, @NonNull java.util.function.Consumer<java.lang.Boolean>);
method @BinderThread public void onStageAndApplyRuntimePermissionsBackup(@NonNull android.os.UserHandle, @NonNull java.io.InputStream, @NonNull Runnable);
- method @BinderThread public void onUpdateUserSensitive();
+ method @BinderThread public void onUpdateUserSensitivePermissionFlags();
field public static final String SERVICE_INTERFACE = "android.permission.PermissionControllerService";
}
@@ -6939,34 +7154,34 @@ package android.provider {
field public static final int STATUS_NOT_BLOCKED = 0; // 0x0
}
- public static final class ContactsContract.MetadataSync implements android.provider.BaseColumns android.provider.ContactsContract.MetadataSyncColumns {
- field public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/contact_metadata";
- field public static final String CONTENT_TYPE = "vnd.android.cursor.dir/contact_metadata";
- field public static final android.net.Uri CONTENT_URI;
- field public static final String METADATA_AUTHORITY = "com.android.contacts.metadata";
- field public static final android.net.Uri METADATA_AUTHORITY_URI;
+ @Deprecated public static final class ContactsContract.MetadataSync implements android.provider.BaseColumns android.provider.ContactsContract.MetadataSyncColumns {
+ field @Deprecated public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/contact_metadata";
+ field @Deprecated public static final String CONTENT_TYPE = "vnd.android.cursor.dir/contact_metadata";
+ field @Deprecated public static final android.net.Uri CONTENT_URI;
+ field @Deprecated public static final String METADATA_AUTHORITY = "com.android.contacts.metadata";
+ field @Deprecated public static final android.net.Uri METADATA_AUTHORITY_URI;
}
- protected static interface ContactsContract.MetadataSyncColumns {
- field public static final String ACCOUNT_NAME = "account_name";
- field public static final String ACCOUNT_TYPE = "account_type";
- field public static final String DATA = "data";
- field public static final String DATA_SET = "data_set";
- field public static final String DELETED = "deleted";
- field public static final String RAW_CONTACT_BACKUP_ID = "raw_contact_backup_id";
+ @Deprecated protected static interface ContactsContract.MetadataSyncColumns {
+ field @Deprecated public static final String ACCOUNT_NAME = "account_name";
+ field @Deprecated public static final String ACCOUNT_TYPE = "account_type";
+ field @Deprecated public static final String DATA = "data";
+ field @Deprecated public static final String DATA_SET = "data_set";
+ field @Deprecated public static final String DELETED = "deleted";
+ field @Deprecated public static final String RAW_CONTACT_BACKUP_ID = "raw_contact_backup_id";
}
- public static final class ContactsContract.MetadataSyncState implements android.provider.BaseColumns android.provider.ContactsContract.MetadataSyncStateColumns {
- field public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/contact_metadata_sync_state";
- field public static final String CONTENT_TYPE = "vnd.android.cursor.dir/contact_metadata_sync_state";
- field public static final android.net.Uri CONTENT_URI;
+ @Deprecated public static final class ContactsContract.MetadataSyncState implements android.provider.BaseColumns android.provider.ContactsContract.MetadataSyncStateColumns {
+ field @Deprecated public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/contact_metadata_sync_state";
+ field @Deprecated public static final String CONTENT_TYPE = "vnd.android.cursor.dir/contact_metadata_sync_state";
+ field @Deprecated public static final android.net.Uri CONTENT_URI;
}
- protected static interface ContactsContract.MetadataSyncStateColumns {
- field public static final String ACCOUNT_NAME = "account_name";
- field public static final String ACCOUNT_TYPE = "account_type";
- field public static final String DATA_SET = "data_set";
- field public static final String STATE = "state";
+ @Deprecated protected static interface ContactsContract.MetadataSyncStateColumns {
+ field @Deprecated public static final String ACCOUNT_NAME = "account_name";
+ field @Deprecated public static final String ACCOUNT_TYPE = "account_type";
+ field @Deprecated public static final String DATA_SET = "data_set";
+ field @Deprecated public static final String STATE = "state";
}
public final class DeviceConfig {
@@ -6980,13 +7195,14 @@ package android.provider {
method @RequiresPermission(android.Manifest.permission.READ_DEVICE_CONFIG) public static String getString(@NonNull String, @NonNull String, @Nullable String);
method public static void removeOnPropertiesChangedListener(@NonNull android.provider.DeviceConfig.OnPropertiesChangedListener);
method @RequiresPermission(android.Manifest.permission.WRITE_DEVICE_CONFIG) public static void resetToDefaults(int, @Nullable String);
- method @RequiresPermission(android.Manifest.permission.WRITE_DEVICE_CONFIG) public static boolean setProperties(@NonNull android.provider.DeviceConfig.Properties);
+ method @RequiresPermission(android.Manifest.permission.WRITE_DEVICE_CONFIG) public static boolean setProperties(@NonNull android.provider.DeviceConfig.Properties) throws android.provider.DeviceConfig.BadConfigException;
method @RequiresPermission(android.Manifest.permission.WRITE_DEVICE_CONFIG) public static boolean setProperty(@NonNull String, @NonNull String, @Nullable String, boolean);
field public static final String NAMESPACE_ACTIVITY_MANAGER = "activity_manager";
field public static final String NAMESPACE_ACTIVITY_MANAGER_NATIVE_BOOT = "activity_manager_native_boot";
field public static final String NAMESPACE_APP_COMPAT = "app_compat";
field public static final String NAMESPACE_ATTENTION_MANAGER_SERVICE = "attention_manager_service";
field public static final String NAMESPACE_AUTOFILL = "autofill";
+ field public static final String NAMESPACE_BIOMETRICS = "biometrics";
field public static final String NAMESPACE_CONNECTIVITY = "connectivity";
field public static final String NAMESPACE_CONTENT_CAPTURE = "content_capture";
field @Deprecated public static final String NAMESPACE_DEX_BOOT = "dex_boot";
@@ -7012,6 +7228,10 @@ package android.provider {
field public static final String NAMESPACE_TEXTCLASSIFIER = "textclassifier";
}
+ public static class DeviceConfig.BadConfigException extends java.lang.Exception {
+ ctor public DeviceConfig.BadConfigException();
+ }
+
public static interface DeviceConfig.OnPropertiesChangedListener {
method public void onPropertiesChanged(@NonNull android.provider.DeviceConfig.Properties);
}
@@ -7026,6 +7246,16 @@ package android.provider {
method @Nullable public String getString(@NonNull String, @Nullable String);
}
+ public static final class DeviceConfig.Properties.Builder {
+ ctor public DeviceConfig.Properties.Builder(@NonNull String);
+ method @NonNull public android.provider.DeviceConfig.Properties build();
+ method @NonNull public android.provider.DeviceConfig.Properties.Builder setBoolean(@NonNull String, boolean);
+ method @NonNull public android.provider.DeviceConfig.Properties.Builder setFloat(@NonNull String, float);
+ method @NonNull public android.provider.DeviceConfig.Properties.Builder setInt(@NonNull String, int);
+ method @NonNull public android.provider.DeviceConfig.Properties.Builder setLong(@NonNull String, long);
+ method @NonNull public android.provider.DeviceConfig.Properties.Builder setString(@NonNull String, @Nullable String);
+ }
+
public final class DocumentsContract {
method public static boolean isManageMode(@NonNull android.net.Uri);
method @NonNull public static android.net.Uri setManageMode(@NonNull android.net.Uri);
@@ -7042,8 +7272,8 @@ package android.provider {
}
public final class MediaStore {
- method @NonNull @RequiresPermission(android.Manifest.permission.WRITE_MEDIA_STORAGE) public static java.util.Set<java.lang.String> getRecentExternalVolumeNames(@NonNull android.content.Context);
- method @NonNull @RequiresPermission(android.Manifest.permission.WRITE_MEDIA_STORAGE) public static java.util.Collection<java.io.File> getVolumeScanPaths(@NonNull String) throws java.io.FileNotFoundException;
+ method @NonNull public static android.net.Uri scanFile(@NonNull android.content.ContentResolver, @NonNull java.io.File);
+ method public static void scanVolume(@NonNull android.content.ContentResolver, @NonNull String);
}
public abstract class SearchIndexableData {
@@ -7159,6 +7389,7 @@ package android.provider {
public final class Settings {
field public static final String ACTION_ACCESSIBILITY_DETAILS_SETTINGS = "android.settings.ACCESSIBILITY_DETAILS_SETTINGS";
+ field public static final String ACTION_BUGREPORT_HANDLER_SETTINGS = "android.settings.BUGREPORT_HANDLER_SETTINGS";
field public static final String ACTION_ENTERPRISE_PRIVACY_SETTINGS = "android.settings.ENTERPRISE_PRIVACY_SETTINGS";
field public static final String ACTION_LOCATION_CONTROLLER_EXTRA_PACKAGE_SETTINGS = "android.settings.LOCATION_CONTROLLER_EXTRA_PACKAGE_SETTINGS";
field public static final String ACTION_MANAGE_APP_OVERLAY_PERMISSION = "android.settings.MANAGE_APP_OVERLAY_PERMISSION";
@@ -7835,6 +8066,7 @@ package android.service.notification {
field public static final String KEY_CONTEXTUAL_ACTIONS = "key_contextual_actions";
field public static final String KEY_IMPORTANCE = "key_importance";
field public static final String KEY_PEOPLE = "key_people";
+ field public static final String KEY_RANKING_SCORE = "key_ranking_score";
field public static final String KEY_SNOOZE_CRITERIA = "key_snooze_criteria";
field public static final String KEY_TEXT_REPLIES = "key_text_replies";
field public static final String KEY_USER_SENTIMENT = "key_user_sentiment";
@@ -8016,16 +8248,6 @@ package android.service.settings.suggestions {
}
-package android.service.sms {
-
- public abstract class FinancialSmsService extends android.app.Service {
- method public android.os.IBinder onBind(android.content.Intent);
- method @Nullable public abstract android.database.CursorWindow onGetSmsMessages(@NonNull android.os.Bundle);
- field public static final String ACTION_FINANCIAL_SERVICE_INTENT = "android.service.sms.action.FINANCIAL_SERVICE_INTENT";
- }
-
-}
-
package android.service.storage {
public abstract class ExternalStorageService extends android.app.Service {
@@ -8489,14 +8711,6 @@ package android.telephony {
field public static final String KEY_CARRIER_SETUP_APP_STRING = "carrier_setup_app_string";
}
- public static final class CarrierConfigManager.Wifi {
- field public static final String KEY_CARRIER_CONNECTION_MANAGER_PACKAGE_STRING = "wifi.carrier_connection_manager_package_string";
- field public static final String KEY_CARRIER_PROFILES_VERSION_INT = "wifi.carrier_profiles_version_int";
- field public static final String KEY_NETWORK_PROFILES_STRING_ARRAY = "wifi.network_profiles_string_array";
- field public static final String KEY_PASSPOINT_PROFILES_STRING_ARRAY = "wifi.passpoint_profiles_string_array";
- field public static final String KEY_PREFIX = "wifi.";
- }
-
public final class CarrierRestrictionRules implements android.os.Parcelable {
method @NonNull public java.util.List<java.lang.Boolean> areCarrierIdentifiersAllowed(@NonNull java.util.List<android.service.carrier.CarrierIdentifier>);
method public int describeContents();
@@ -8526,6 +8740,13 @@ package android.telephony {
public class CbGeoUtils {
}
+ public static class CbGeoUtils.Circle implements android.telephony.CbGeoUtils.Geometry {
+ ctor public CbGeoUtils.Circle(@NonNull android.telephony.CbGeoUtils.LatLng, double);
+ method public boolean contains(@NonNull android.telephony.CbGeoUtils.LatLng);
+ method @NonNull public android.telephony.CbGeoUtils.LatLng getCenter();
+ method public double getRadius();
+ }
+
public static interface CbGeoUtils.Geometry {
method public boolean contains(@NonNull android.telephony.CbGeoUtils.LatLng);
}
@@ -8538,6 +8759,12 @@ package android.telephony {
field public final double lng;
}
+ public static class CbGeoUtils.Polygon implements android.telephony.CbGeoUtils.Geometry {
+ ctor public CbGeoUtils.Polygon(@NonNull java.util.List<android.telephony.CbGeoUtils.LatLng>);
+ method public boolean contains(@NonNull android.telephony.CbGeoUtils.LatLng);
+ method @NonNull public java.util.List<android.telephony.CbGeoUtils.LatLng> getVertices();
+ }
+
public class CellBroadcastIntents {
method public static void sendOrderedBroadcastForBackgroundReceivers(@NonNull android.content.Context, @Nullable android.os.UserHandle, @NonNull android.content.Intent, @Nullable String, @Nullable String, @Nullable android.content.BroadcastReceiver, @Nullable android.os.Handler, int, @Nullable String, @Nullable android.os.Bundle);
}
@@ -8868,6 +9095,7 @@ package android.telephony {
field public static final int UE_SECURITY_CAPABILITIES_MISMATCH = 2185; // 0x889
field public static final int UMTS_HANDOVER_TO_IWLAN = 2199; // 0x897
field public static final int UMTS_REACTIVATION_REQ = 39; // 0x27
+ field public static final int UNACCEPTABLE_NETWORK_PARAMETER = 65538; // 0x10002
field public static final int UNACCEPTABLE_NON_EPS_AUTHENTICATION = 2187; // 0x88b
field public static final int UNKNOWN = 65536; // 0x10000
field public static final int UNKNOWN_INFO_ELEMENT = 99; // 0x63
@@ -9020,6 +9248,7 @@ package android.telephony {
method public int getSleepTimeMillis();
method public long getTimestamp();
method @NonNull public java.util.List<android.telephony.ModemActivityInfo.TransmitPower> getTransmitPowerInfo();
+ method public boolean isValid();
method public void writeToParcel(android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.telephony.ModemActivityInfo> CREATOR;
field public static final int TX_POWER_LEVELS = 5; // 0x5
@@ -9133,7 +9362,6 @@ package android.telephony {
method public void onOutgoingEmergencyCall(@NonNull android.telephony.emergency.EmergencyNumber);
method public void onOutgoingEmergencySms(@NonNull android.telephony.emergency.EmergencyNumber);
method @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public void onPreciseCallStateChanged(@NonNull android.telephony.PreciseCallState);
- method @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public void onPreciseDataConnectionStateChanged(@NonNull android.telephony.PreciseDataConnectionState);
method public void onRadioPowerStateChanged(int);
method public void onSrvccStateChanged(int);
method public void onVoiceActivationStateChanged(int);
@@ -9143,7 +9371,6 @@ package android.telephony {
field @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION) public static final int LISTEN_OUTGOING_EMERGENCY_CALL = 268435456; // 0x10000000
field @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION) public static final int LISTEN_OUTGOING_EMERGENCY_SMS = 536870912; // 0x20000000
field @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public static final int LISTEN_PRECISE_CALL_STATE = 2048; // 0x800
- field @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public static final int LISTEN_PRECISE_DATA_CONNECTION_STATE = 4096; // 0x1000
field public static final int LISTEN_RADIO_POWER_STATE_CHANGED = 8388608; // 0x800000
field @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public static final int LISTEN_SRVCC_STATE_CHANGED = 16384; // 0x4000
field public static final int LISTEN_VOICE_ACTIVATION_STATE = 131072; // 0x20000
@@ -9169,13 +9396,12 @@ package android.telephony {
}
public final class PreciseDataConnectionState implements android.os.Parcelable {
- method public int describeContents();
- method @Nullable public String getDataConnectionApn();
- method public int getDataConnectionApnTypeBitMask();
- method public int getDataConnectionFailCause();
- method public int getDataConnectionState();
- method public void writeToParcel(android.os.Parcel, int);
- field @NonNull public static final android.os.Parcelable.Creator<android.telephony.PreciseDataConnectionState> CREATOR;
+ method @Deprecated @NonNull public String getDataConnectionApn();
+ method @Deprecated public int getDataConnectionApnTypeBitMask();
+ method @Deprecated public int getDataConnectionFailCause();
+ method @Deprecated @Nullable public android.net.LinkProperties getDataConnectionLinkProperties();
+ method @Deprecated public int getDataConnectionNetworkType();
+ method @Deprecated public int getDataConnectionState();
}
public final class PreciseDisconnectCause {
@@ -9414,11 +9640,13 @@ package android.telephony {
public final class SmsManager {
method public boolean disableCellBroadcastRange(int, int, int);
method public boolean enableCellBroadcastRange(int, int, int);
+ method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public int getSmsCapacityOnIcc();
method public void sendMultipartTextMessage(@NonNull String, @NonNull String, @NonNull java.util.List<java.lang.String>, @Nullable java.util.List<android.app.PendingIntent>, @Nullable java.util.List<android.app.PendingIntent>, @NonNull String);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void sendMultipartTextMessageWithoutPersisting(String, String, java.util.List<java.lang.String>, java.util.List<android.app.PendingIntent>, java.util.List<android.app.PendingIntent>);
}
public class SubscriptionInfo implements android.os.Parcelable {
+ method public boolean areUiccApplicationsEnabled();
method @Nullable public java.util.List<android.telephony.UiccAccessRule> getAccessRules();
method public int getProfileClass();
method public boolean isGroupDisabled();
@@ -9458,6 +9686,7 @@ package android.telephony {
public class TelephonyFrameworkInitializer {
method public static void registerServiceWrappers();
+ method public static void setTelephonyServiceManager(@NonNull android.os.TelephonyServiceManager);
}
public final class TelephonyHistogram implements android.os.Parcelable {
@@ -9482,9 +9711,6 @@ package android.telephony {
public class TelephonyManager {
method @Deprecated @RequiresPermission(android.Manifest.permission.CALL_PHONE) public void call(String, String);
- method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void carrierActionReportDefaultNetworkStatus(int, boolean);
- method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void carrierActionResetAll(int);
- method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void carrierActionSetRadioEnabled(int, boolean);
method public int checkCarrierPrivilegesForPackage(String);
method public int checkCarrierPrivilegesForPackageAnyPhone(String);
method public void dial(String);
@@ -9497,6 +9723,7 @@ package android.telephony {
method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public android.telephony.ImsiEncryptionInfo getCarrierInfoForImsiEncryption(int);
method public java.util.List<java.lang.String> getCarrierPackageNamesForIntent(android.content.Intent);
method public java.util.List<java.lang.String> getCarrierPackageNamesForIntentAndPhone(android.content.Intent, int);
+ method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public int getCarrierPrivilegeStatus(int);
method @NonNull @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public java.util.List<java.lang.String> getCarrierPrivilegedPackagesForAllActiveSubscriptions();
method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public android.telephony.CarrierRestrictionRules getCarrierRestrictionRules();
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public String getCdmaMdn();
@@ -9538,6 +9765,8 @@ package android.telephony {
method @Nullable @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public android.telephony.IccOpenLogicalChannelResponse iccOpenLogicalChannelBySlot(int, @Nullable String, int);
method @NonNull @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public String iccTransmitApduBasicChannelBySlot(int, int, int, int, int, int, @Nullable String);
method @Nullable @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public String iccTransmitApduLogicalChannelBySlot(int, int, int, int, int, int, int, @Nullable String);
+ method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isAnyRadioPoweredOn();
+ method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isApnMetered(int);
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isApplicationOnUicc(int);
method public boolean isDataConnectivityPossible();
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isDataEnabledForApn(int);
@@ -9556,8 +9785,11 @@ package android.telephony {
method public boolean needsOtaServiceProvisioning();
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void notifyOtaEmergencyNumberDbInstalled();
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean rebootRadio();
+ method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void reportDefaultNetworkStatus(boolean);
method @RequiresPermission(allOf={android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.MODIFY_PHONE_STATE}) public void requestCellInfoUpdate(@NonNull android.os.WorkSource, @NonNull java.util.concurrent.Executor, @NonNull android.telephony.TelephonyManager.CellInfoCallback);
+ method public void requestModemActivityInfo(@NonNull android.os.ResultReceiver);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void requestNumberVerification(@NonNull android.telephony.PhoneNumberRange, long, @NonNull java.util.concurrent.Executor, @NonNull android.telephony.NumberVerificationCallback);
+ method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void resetAllCarrierActions();
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void resetCarrierKeysForImsiEncryption();
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean resetRadioConfig();
method @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL) public void resetSettings();
@@ -9571,11 +9803,13 @@ package android.telephony {
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean setOpportunisticNetworkState(boolean);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean setPreferredNetworkTypeBitmask(long);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean setRadio(boolean);
+ method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setRadioEnabled(boolean);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean setRadioPower(boolean);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setSimPowerState(int);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setSimPowerStateForSlot(int, int);
method @Deprecated public void setVisualVoicemailEnabled(android.telecom.PhoneAccountHandle, boolean);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setVoiceActivationState(int);
+ method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void shutdownAllRadios();
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean supplyPin(String);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public int[] supplyPinReportResult(String);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean supplyPuk(String, String);
@@ -9585,6 +9819,8 @@ package android.telephony {
method public void updateServiceLocation();
method @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION) public void updateTestOtaEmergencyNumberDbFilePath(@NonNull String);
field @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public static final String ACTION_ANOMALY_REPORTED = "android.telephony.action.ANOMALY_REPORTED";
+ field public static final String ACTION_EMERGENCY_ASSISTANCE = "android.telephony.action.EMERGENCY_ASSISTANCE";
+ field public static final String ACTION_NETWORK_SET_TIME = "android.telephony.action.NETWORK_SET_TIME";
field public static final String ACTION_SIM_APPLICATION_STATE_CHANGED = "android.telephony.action.SIM_APPLICATION_STATE_CHANGED";
field public static final String ACTION_SIM_CARD_STATE_CHANGED = "android.telephony.action.SIM_CARD_STATE_CHANGED";
field public static final String ACTION_SIM_SLOT_STATUS_CHANGED = "android.telephony.action.SIM_SLOT_STATUS_CHANGED";
@@ -10179,6 +10415,11 @@ package android.telephony.ims {
field @NonNull public static final android.os.Parcelable.Creator<android.telephony.ims.ImsExternalCallState> CREATOR;
}
+ public class ImsManager {
+ method @NonNull public android.telephony.ims.ImsMmTelManager getImsMmTelManager(int);
+ method @NonNull public android.telephony.ims.ImsRcsManager getImsRcsManager(int);
+ }
+
public class ImsMmTelManager implements android.telephony.ims.RegistrationManager {
method @NonNull public static android.telephony.ims.ImsMmTelManager createForSubscriptionId(int);
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void getFeatureState(@NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Integer>) throws android.telephony.ims.ImsException;
@@ -10222,6 +10463,22 @@ package android.telephony.ims {
ctor @Deprecated public ImsMmTelManager.RegistrationCallback();
}
+ public class ImsRcsManager implements android.telephony.ims.RegistrationManager {
+ method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void getRegistrationState(@NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Integer>);
+ method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void getRegistrationTransportType(@NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Integer>);
+ method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isAvailable(int) throws android.telephony.ims.ImsException;
+ method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isCapable(int, int) throws android.telephony.ims.ImsException;
+ method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void registerImsRegistrationCallback(@NonNull java.util.concurrent.Executor, @NonNull android.telephony.ims.RegistrationManager.RegistrationCallback) throws android.telephony.ims.ImsException;
+ method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void registerRcsAvailabilityCallback(@NonNull java.util.concurrent.Executor, @NonNull android.telephony.ims.ImsRcsManager.AvailabilityCallback) throws android.telephony.ims.ImsException;
+ method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void unregisterImsRegistrationCallback(@NonNull android.telephony.ims.RegistrationManager.RegistrationCallback);
+ method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void unregisterRcsAvailabilityCallback(@NonNull android.telephony.ims.ImsRcsManager.AvailabilityCallback) throws android.telephony.ims.ImsException;
+ }
+
+ public static class ImsRcsManager.AvailabilityCallback {
+ ctor public ImsRcsManager.AvailabilityCallback();
+ method public void onAvailabilityChanged(@NonNull android.telephony.ims.feature.RcsFeature.RcsImsCapabilities);
+ }
+
public final class ImsReasonInfo implements android.os.Parcelable {
field public static final String EXTRA_MSG_SERVICE_NOT_AUTHORIZED = "Forbidden. Not Authorized for Service";
}
@@ -10583,9 +10840,22 @@ package android.telephony.ims.feature {
public class RcsFeature extends android.telephony.ims.feature.ImsFeature {
ctor public RcsFeature();
- method public void changeEnabledCapabilities(android.telephony.ims.feature.CapabilityChangeRequest, android.telephony.ims.feature.ImsFeature.CapabilityCallbackProxy);
+ method public void changeEnabledCapabilities(@NonNull android.telephony.ims.feature.CapabilityChangeRequest, @NonNull android.telephony.ims.feature.ImsFeature.CapabilityCallbackProxy);
+ method public final void notifyCapabilitiesStatusChanged(@NonNull android.telephony.ims.feature.RcsFeature.RcsImsCapabilities);
method public void onFeatureReady();
method public void onFeatureRemoved();
+ method public boolean queryCapabilityConfiguration(int, int);
+ method @NonNull public final android.telephony.ims.feature.RcsFeature.RcsImsCapabilities queryCapabilityStatus();
+ }
+
+ public static class RcsFeature.RcsImsCapabilities extends android.telephony.ims.feature.ImsFeature.Capabilities {
+ ctor public RcsFeature.RcsImsCapabilities(int);
+ method public void addCapabilities(int);
+ method public boolean isCapable(int);
+ method public void removeCapabilities(int);
+ field public static final int CAPABILITY_TYPE_NONE = 0; // 0x0
+ field public static final int CAPABILITY_TYPE_OPTIONS_UCE = 1; // 0x1
+ field public static final int CAPABILITY_TYPE_PRESENCE_UCE = 2; // 0x2
}
}
diff --git a/api/system-lint-baseline.txt b/api/system-lint-baseline.txt
index fcf5178716e1..9a6357572d36 100644
--- a/api/system-lint-baseline.txt
+++ b/api/system-lint-baseline.txt
@@ -196,7 +196,6 @@ ProtectedMember: android.service.contentcapture.ContentCaptureService#dump(java.
ProtectedMember: android.service.notification.NotificationAssistantService#attachBaseContext(android.content.Context):
-
SamShouldBeLast: android.accounts.AccountManager#addAccount(String, String, String[], android.os.Bundle, android.app.Activity, android.accounts.AccountManagerCallback<android.os.Bundle>, android.os.Handler):
SamShouldBeLast: android.accounts.AccountManager#addOnAccountsUpdatedListener(android.accounts.OnAccountsUpdateListener, android.os.Handler, boolean):
diff --git a/api/test-current.txt b/api/test-current.txt
index 3e144697ee28..7deac26e4741 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -12,6 +12,7 @@ package android {
field public static final String CONFIGURE_DISPLAY_BRIGHTNESS = "android.permission.CONFIGURE_DISPLAY_BRIGHTNESS";
field public static final String FORCE_STOP_PACKAGES = "android.permission.FORCE_STOP_PACKAGES";
field public static final String MANAGE_ACTIVITY_STACKS = "android.permission.MANAGE_ACTIVITY_STACKS";
+ field public static final String MANAGE_CRATES = "android.permission.MANAGE_CRATES";
field public static final String MANAGE_ROLLBACKS = "android.permission.MANAGE_ROLLBACKS";
field public static final String READ_CELL_BROADCASTS = "android.permission.READ_CELL_BROADCASTS";
field public static final String REMOVE_TASKS = "android.permission.REMOVE_TASKS";
@@ -629,6 +630,9 @@ package android.app.usage {
public class StorageStatsManager {
method public boolean isQuotaSupported(@NonNull java.util.UUID);
method public boolean isReservedSupported(@NonNull java.util.UUID);
+ method @NonNull @WorkerThread public java.util.Collection<android.os.storage.CrateInfo> queryCratesForPackage(@NonNull java.util.UUID, @NonNull String, @NonNull android.os.UserHandle) throws java.io.IOException, android.content.pm.PackageManager.NameNotFoundException;
+ method @NonNull @WorkerThread public java.util.Collection<android.os.storage.CrateInfo> queryCratesForUid(@NonNull java.util.UUID, int) throws java.io.IOException, android.content.pm.PackageManager.NameNotFoundException;
+ method @NonNull @RequiresPermission(android.Manifest.permission.MANAGE_CRATES) @WorkerThread public java.util.Collection<android.os.storage.CrateInfo> queryCratesForUser(@NonNull java.util.UUID, @NonNull android.os.UserHandle) throws java.io.IOException, android.content.pm.PackageManager.NameNotFoundException;
}
public final class UsageStatsManager {
@@ -697,6 +701,7 @@ package android.content {
public abstract class Context {
method @NonNull public android.content.Context createContextAsUser(@NonNull android.os.UserHandle, int);
method @NonNull public android.content.Context createPackageContextAsUser(@NonNull String, int, @NonNull android.os.UserHandle) throws android.content.pm.PackageManager.NameNotFoundException;
+ method @NonNull public java.io.File getCrateDir(@NonNull String);
method public abstract android.view.Display getDisplay();
method public abstract int getDisplayId();
method public android.os.UserHandle getUser();
@@ -711,6 +716,7 @@ package android.content {
field public static final String POWER_WHITELIST_MANAGER = "power_whitelist";
field public static final String ROLLBACK_SERVICE = "rollback";
field public static final String STATUS_BAR_SERVICE = "statusbar";
+ field public static final String TELEPHONY_IMS_SERVICE = "telephony_ims";
field public static final String TEST_NETWORK_SERVICE = "test_network";
}
@@ -722,6 +728,7 @@ package android.content {
public class Intent implements java.lang.Cloneable android.os.Parcelable {
field @RequiresPermission("android.permission.MANAGE_ROLE_HOLDERS") public static final String ACTION_MANAGE_DEFAULT_APP = "android.intent.action.MANAGE_DEFAULT_APP";
field public static final String ACTION_ROLLBACK_COMMITTED = "android.intent.action.ROLLBACK_COMMITTED";
+ field public static final String EXTRA_ORIGINATING_UID = "android.intent.extra.ORIGINATING_UID";
field public static final String EXTRA_ROLE_NAME = "android.intent.extra.ROLE_NAME";
}
@@ -753,6 +760,7 @@ package android.content.pm {
method public void setEnableRollback(boolean);
method @RequiresPermission("android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS") public void setGrantedRuntimePermissions(String[]);
method @RequiresPermission(android.Manifest.permission.INSTALL_PACKAGES) public void setInstallAsApex();
+ method public void setInstallerPackageName(@Nullable String);
method public void setRequestDowngrade(boolean);
method @RequiresPermission(android.Manifest.permission.INSTALL_PACKAGES) public void setStaged();
}
@@ -1151,6 +1159,7 @@ package android.location {
method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestLocationUpdates(@Nullable android.location.LocationRequest, @NonNull java.util.concurrent.Executor, @NonNull android.location.LocationListener);
method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestLocationUpdates(@Nullable android.location.LocationRequest, @NonNull android.app.PendingIntent);
method @RequiresPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS) public void setLocationEnabledForUser(boolean, @NonNull android.os.UserHandle);
+ field public static final String FUSED_PROVIDER = "fused";
}
public final class LocationRequest implements android.os.Parcelable {
@@ -2309,6 +2318,17 @@ package android.os.image {
package android.os.storage {
+ public final class CrateInfo implements android.os.Parcelable {
+ ctor public CrateInfo(@NonNull CharSequence, long);
+ ctor public CrateInfo(@NonNull CharSequence);
+ method @Nullable public static android.os.storage.CrateInfo copyFrom(int, @Nullable String, @Nullable String);
+ method public int describeContents();
+ method public long getExpirationMillis();
+ method @NonNull public CharSequence getLabel();
+ method public void writeToParcel(@Nullable android.os.Parcel, int);
+ field @NonNull public static final android.os.Parcelable.Creator<android.os.storage.CrateInfo> CREATOR;
+ }
+
public class StorageManager {
method public static boolean hasIsolatedStorage();
}
@@ -2430,6 +2450,7 @@ package android.provider {
method @RequiresPermission(android.Manifest.permission.WRITE_DEVICE_CONFIG) public static boolean setProperty(@NonNull String, @NonNull String, @Nullable String, boolean);
field public static final String NAMESPACE_ANDROID = "android";
field public static final String NAMESPACE_AUTOFILL = "autofill";
+ field public static final String NAMESPACE_BIOMETRICS = "biometrics";
field public static final String NAMESPACE_CONTENT_CAPTURE = "content_capture";
field public static final String NAMESPACE_PERMISSIONS = "permissions";
field public static final String NAMESPACE_PRIVACY = "privacy";
@@ -2451,15 +2472,20 @@ package android.provider {
method @Nullable public String getString(@NonNull String, @Nullable String);
}
+ public static final class DeviceConfig.Properties.Builder {
+ ctor public DeviceConfig.Properties.Builder(@NonNull String);
+ method @NonNull public android.provider.DeviceConfig.Properties build();
+ method @NonNull public android.provider.DeviceConfig.Properties.Builder setBoolean(@NonNull String, boolean);
+ method @NonNull public android.provider.DeviceConfig.Properties.Builder setFloat(@NonNull String, float);
+ method @NonNull public android.provider.DeviceConfig.Properties.Builder setInt(@NonNull String, int);
+ method @NonNull public android.provider.DeviceConfig.Properties.Builder setLong(@NonNull String, long);
+ method @NonNull public android.provider.DeviceConfig.Properties.Builder setString(@NonNull String, @Nullable String);
+ }
+
public final class MediaStore {
- method @RequiresPermission(android.Manifest.permission.CLEAR_APP_USER_DATA) public static void deleteContributedMedia(android.content.Context, String, android.os.UserHandle) throws java.io.IOException;
- method @RequiresPermission(android.Manifest.permission.CLEAR_APP_USER_DATA) public static long getContributedMediaSize(android.content.Context, String, android.os.UserHandle) throws java.io.IOException;
- method @NonNull public static java.io.File getVolumePath(@NonNull String) throws java.io.FileNotFoundException;
- method @NonNull @RequiresPermission(android.Manifest.permission.WRITE_MEDIA_STORAGE) public static java.util.Collection<java.io.File> getVolumeScanPaths(@NonNull String) throws java.io.FileNotFoundException;
- method public static android.net.Uri scanFile(android.content.Context, java.io.File);
- method public static android.net.Uri scanFileFromShell(android.content.Context, java.io.File);
- method public static void scanVolume(android.content.Context, java.io.File);
- method public static void waitForIdle(android.content.Context);
+ method @NonNull public static android.net.Uri scanFile(@NonNull android.content.ContentResolver, @NonNull java.io.File);
+ method public static void scanVolume(@NonNull android.content.ContentResolver, @NonNull String);
+ method public static void waitForIdle(@NonNull android.content.ContentResolver);
}
public final class Settings {
@@ -2817,6 +2843,7 @@ package android.service.notification {
field @NonNull public static final android.os.Parcelable.Creator<android.service.notification.Adjustment> CREATOR;
field public static final String KEY_CONTEXTUAL_ACTIONS = "key_contextual_actions";
field public static final String KEY_IMPORTANCE = "key_importance";
+ field public static final String KEY_RANKING_SCORE = "key_ranking_score";
field public static final String KEY_SNOOZE_CRITERIA = "key_snooze_criteria";
field public static final String KEY_TEXT_REPLIES = "key_text_replies";
field public static final String KEY_USER_SENTIMENT = "key_user_sentiment";
@@ -3147,6 +3174,10 @@ package android.telephony {
field @RequiresPermission("android.permission.READ_ACTIVE_EMERGENCY_SESSION") public static final int LISTEN_OUTGOING_EMERGENCY_SMS = 536870912; // 0x20000000
}
+ public final class PreciseDataConnectionState implements android.os.Parcelable {
+ ctor @Deprecated public PreciseDataConnectionState(int, int, int, @NonNull String, @Nullable android.net.LinkProperties, int);
+ }
+
public class ServiceState implements android.os.Parcelable {
method public void addNetworkRegistrationInfo(android.telephony.NetworkRegistrationInfo);
method public void setCdmaSystemAndNetworkId(int, int);
@@ -3413,6 +3444,11 @@ package android.telephony.ims {
field @NonNull public static final android.os.Parcelable.Creator<android.telephony.ims.ImsExternalCallState> CREATOR;
}
+ public class ImsManager {
+ method @NonNull public android.telephony.ims.ImsMmTelManager getImsMmTelManager(int);
+ method @NonNull public android.telephony.ims.ImsRcsManager getImsRcsManager(int);
+ }
+
public class ImsMmTelManager implements android.telephony.ims.RegistrationManager {
method @NonNull public static android.telephony.ims.ImsMmTelManager createForSubscriptionId(int);
method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public void getFeatureState(@NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Integer>) throws android.telephony.ims.ImsException;
@@ -3456,6 +3492,22 @@ package android.telephony.ims {
ctor @Deprecated public ImsMmTelManager.RegistrationCallback();
}
+ public class ImsRcsManager implements android.telephony.ims.RegistrationManager {
+ method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public void getRegistrationState(@NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Integer>);
+ method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public void getRegistrationTransportType(@NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Integer>);
+ method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public boolean isAvailable(int) throws android.telephony.ims.ImsException;
+ method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public boolean isCapable(int, int) throws android.telephony.ims.ImsException;
+ method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public void registerImsRegistrationCallback(@NonNull java.util.concurrent.Executor, @NonNull android.telephony.ims.RegistrationManager.RegistrationCallback) throws android.telephony.ims.ImsException;
+ method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public void registerRcsAvailabilityCallback(@NonNull java.util.concurrent.Executor, @NonNull android.telephony.ims.ImsRcsManager.AvailabilityCallback) throws android.telephony.ims.ImsException;
+ method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public void unregisterImsRegistrationCallback(@NonNull android.telephony.ims.RegistrationManager.RegistrationCallback);
+ method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public void unregisterRcsAvailabilityCallback(@NonNull android.telephony.ims.ImsRcsManager.AvailabilityCallback) throws android.telephony.ims.ImsException;
+ }
+
+ public static class ImsRcsManager.AvailabilityCallback {
+ ctor public ImsRcsManager.AvailabilityCallback();
+ method public void onAvailabilityChanged(@NonNull android.telephony.ims.feature.RcsFeature.RcsImsCapabilities);
+ }
+
public class ImsService extends android.app.Service {
ctor public ImsService();
method public android.telephony.ims.feature.MmTelFeature createMmTelFeature(int);
@@ -3813,9 +3865,22 @@ package android.telephony.ims.feature {
public class RcsFeature extends android.telephony.ims.feature.ImsFeature {
ctor public RcsFeature();
- method public void changeEnabledCapabilities(android.telephony.ims.feature.CapabilityChangeRequest, android.telephony.ims.feature.ImsFeature.CapabilityCallbackProxy);
+ method public void changeEnabledCapabilities(@NonNull android.telephony.ims.feature.CapabilityChangeRequest, @NonNull android.telephony.ims.feature.ImsFeature.CapabilityCallbackProxy);
+ method public final void notifyCapabilitiesStatusChanged(@NonNull android.telephony.ims.feature.RcsFeature.RcsImsCapabilities);
method public void onFeatureReady();
method public void onFeatureRemoved();
+ method public boolean queryCapabilityConfiguration(int, int);
+ method @NonNull public final android.telephony.ims.feature.RcsFeature.RcsImsCapabilities queryCapabilityStatus();
+ }
+
+ public static class RcsFeature.RcsImsCapabilities extends android.telephony.ims.feature.ImsFeature.Capabilities {
+ ctor public RcsFeature.RcsImsCapabilities(int);
+ method public void addCapabilities(int);
+ method public boolean isCapable(int);
+ method public void removeCapabilities(int);
+ field public static final int CAPABILITY_TYPE_NONE = 0; // 0x0
+ field public static final int CAPABILITY_TYPE_OPTIONS_UCE = 1; // 0x1
+ field public static final int CAPABILITY_TYPE_PRESENCE_UCE = 2; // 0x2
}
}
@@ -4421,7 +4486,7 @@ package android.view {
field public static final int ACCESSIBILITY_TITLE_CHANGED = 33554432; // 0x2000000
field public static final int PRIVATE_FLAG_NO_MOVE_ANIMATION = 64; // 0x40
field public CharSequence accessibilityTitle;
- field @android.view.ViewDebug.ExportedProperty(flagMapping={@android.view.ViewDebug.FlagToString(mask=0x1, equals=0x1, name="FAKE_HARDWARE_ACCELERATED"), @android.view.ViewDebug.FlagToString(mask=0x2, equals=0x2, name="FORCE_HARDWARE_ACCELERATED"), @android.view.ViewDebug.FlagToString(mask=0x4, equals=0x4, name="WANTS_OFFSET_NOTIFICATIONS"), @android.view.ViewDebug.FlagToString(mask=0x10, equals=0x10, name="SHOW_FOR_ALL_USERS"), @android.view.ViewDebug.FlagToString(mask=android.view.WindowManager.LayoutParams.PRIVATE_FLAG_NO_MOVE_ANIMATION, equals=android.view.WindowManager.LayoutParams.PRIVATE_FLAG_NO_MOVE_ANIMATION, name="NO_MOVE_ANIMATION"), @android.view.ViewDebug.FlagToString(mask=0x80, equals=0x80, name="COMPATIBLE_WINDOW"), @android.view.ViewDebug.FlagToString(mask=0x100, equals=0x100, name="SYSTEM_ERROR"), @android.view.ViewDebug.FlagToString(mask=0x400, equals=0x400, name="KEYGUARD"), @android.view.ViewDebug.FlagToString(mask=0x800, equals=0x800, name="DISABLE_WALLPAPER_TOUCH_EVENTS"), @android.view.ViewDebug.FlagToString(mask=0x1000, equals=0x1000, name="FORCE_STATUS_BAR_VISIBLE_TRANSPARENT"), @android.view.ViewDebug.FlagToString(mask=0x2000, equals=0x2000, name="PRESERVE_GEOMETRY"), @android.view.ViewDebug.FlagToString(mask=0x4000, equals=0x4000, name="FORCE_DECOR_VIEW_VISIBILITY"), @android.view.ViewDebug.FlagToString(mask=0x8000, equals=0x8000, name="WILL_NOT_REPLACE_ON_RELAUNCH"), @android.view.ViewDebug.FlagToString(mask=0x10000, equals=0x10000, name="LAYOUT_CHILD_WINDOW_IN_PARENT_FRAME"), @android.view.ViewDebug.FlagToString(mask=0x20000, equals=0x20000, name="FORCE_DRAW_STATUS_BAR_BACKGROUND"), @android.view.ViewDebug.FlagToString(mask=0x40000, equals=0x40000, name="SUSTAINED_PERFORMANCE_MODE"), @android.view.ViewDebug.FlagToString(mask=0x80000, equals=0x80000, name="HIDE_NON_SYSTEM_OVERLAY_WINDOWS"), @android.view.ViewDebug.FlagToString(mask=0x100000, equals=0x100000, name="IS_ROUNDED_CORNERS_OVERLAY"), @android.view.ViewDebug.FlagToString(mask=0x400000, equals=0x400000, name="IS_SCREEN_DECOR"), @android.view.ViewDebug.FlagToString(mask=0x800000, equals=0x800000, name="STATUS_FORCE_SHOW_NAVIGATION"), @android.view.ViewDebug.FlagToString(mask=0x1000000, equals=0x1000000, name="COLOR_SPACE_AGNOSTIC")}) public int privateFlags;
+ field @android.view.ViewDebug.ExportedProperty(flagMapping={@android.view.ViewDebug.FlagToString(mask=0x1, equals=0x1, name="FAKE_HARDWARE_ACCELERATED"), @android.view.ViewDebug.FlagToString(mask=0x2, equals=0x2, name="FORCE_HARDWARE_ACCELERATED"), @android.view.ViewDebug.FlagToString(mask=0x4, equals=0x4, name="WANTS_OFFSET_NOTIFICATIONS"), @android.view.ViewDebug.FlagToString(mask=0x10, equals=0x10, name="SHOW_FOR_ALL_USERS"), @android.view.ViewDebug.FlagToString(mask=android.view.WindowManager.LayoutParams.PRIVATE_FLAG_NO_MOVE_ANIMATION, equals=android.view.WindowManager.LayoutParams.PRIVATE_FLAG_NO_MOVE_ANIMATION, name="NO_MOVE_ANIMATION"), @android.view.ViewDebug.FlagToString(mask=0x80, equals=0x80, name="COMPATIBLE_WINDOW"), @android.view.ViewDebug.FlagToString(mask=0x100, equals=0x100, name="SYSTEM_ERROR"), @android.view.ViewDebug.FlagToString(mask=0x400, equals=0x400, name="KEYGUARD"), @android.view.ViewDebug.FlagToString(mask=0x800, equals=0x800, name="DISABLE_WALLPAPER_TOUCH_EVENTS"), @android.view.ViewDebug.FlagToString(mask=0x1000, equals=0x1000, name="FORCE_STATUS_BAR_VISIBLE_TRANSPARENT"), @android.view.ViewDebug.FlagToString(mask=0x2000, equals=0x2000, name="PRESERVE_GEOMETRY"), @android.view.ViewDebug.FlagToString(mask=0x4000, equals=0x4000, name="FORCE_DECOR_VIEW_VISIBILITY"), @android.view.ViewDebug.FlagToString(mask=0x8000, equals=0x8000, name="WILL_NOT_REPLACE_ON_RELAUNCH"), @android.view.ViewDebug.FlagToString(mask=0x10000, equals=0x10000, name="LAYOUT_CHILD_WINDOW_IN_PARENT_FRAME"), @android.view.ViewDebug.FlagToString(mask=0x20000, equals=0x20000, name="FORCE_DRAW_STATUS_BAR_BACKGROUND"), @android.view.ViewDebug.FlagToString(mask=0x40000, equals=0x40000, name="SUSTAINED_PERFORMANCE_MODE"), @android.view.ViewDebug.FlagToString(mask=0x80000, equals=0x80000, name="HIDE_NON_SYSTEM_OVERLAY_WINDOWS"), @android.view.ViewDebug.FlagToString(mask=0x100000, equals=0x100000, name="IS_ROUNDED_CORNERS_OVERLAY"), @android.view.ViewDebug.FlagToString(mask=0x400000, equals=0x400000, name="IS_SCREEN_DECOR"), @android.view.ViewDebug.FlagToString(mask=0x800000, equals=0x800000, name="STATUS_FORCE_SHOW_NAVIGATION"), @android.view.ViewDebug.FlagToString(mask=0x1000000, equals=0x1000000, name="COLOR_SPACE_AGNOSTIC"), @android.view.ViewDebug.FlagToString(mask=0x4000000, equals=0x4000000, name="FIT_INSETS_CONTROLLED"), @android.view.ViewDebug.FlagToString(mask=0x8000000, equals=0x8000000, name="ONLY_DRAW_BOTTOM_BAR_BACKGROUND")}) public int privateFlags;
}
public class WindowlessViewRoot {
@@ -4437,7 +4502,7 @@ package android.view.accessibility {
public final class AccessibilityManager {
method public void addAccessibilityServicesStateChangeListener(@NonNull android.view.accessibility.AccessibilityManager.AccessibilityServicesStateChangeListener, @Nullable android.os.Handler);
- method @Nullable @RequiresPermission("android.permission.MANAGE_ACCESSIBILITY") public String getAccessibilityShortcutService();
+ method @NonNull @RequiresPermission("android.permission.MANAGE_ACCESSIBILITY") public java.util.List<java.lang.String> getAccessibilityShortcutTargets(int);
method @RequiresPermission("android.permission.MANAGE_ACCESSIBILITY") public void performAccessibilityShortcut();
method public void removeAccessibilityServicesStateChangeListener(@NonNull android.view.accessibility.AccessibilityManager.AccessibilityServicesStateChangeListener);
}
diff --git a/api/test-lint-baseline.txt b/api/test-lint-baseline.txt
index a8c4db38c841..ef8165fc6edb 100644
--- a/api/test-lint-baseline.txt
+++ b/api/test-lint-baseline.txt
@@ -2426,6 +2426,12 @@ ProtectedMember: android.view.View#resetResolvedDrawables():
ProtectedMember: android.view.ViewGroup#resetResolvedDrawables():
+PublicTypedef: android.os.HwParcel.Status: Don't expose @IntDef: @Status must be hidden.
+
+PublicTypedef: android.telephony.ims.feature.MmTelFeature.MmTelCapabilities.MmTelCapability: Don't expose @IntDef: @MmTelCapability must be hidden.
+
+PublicTypedef: android.telephony.ims.feature.MmTelFeature.ProcessCallResult: Don't expose @IntDef: @ProcessCallResult must be hidden.
+
RawAidl: android.telephony.mbms.vendor.MbmsDownloadServiceBase:
diff --git a/cmds/hid/jni/Android.bp b/cmds/hid/jni/Android.bp
index 095cfc6ceb53..2c07de04b6a7 100644
--- a/cmds/hid/jni/Android.bp
+++ b/cmds/hid/jni/Android.bp
@@ -5,6 +5,7 @@ cc_library_shared {
shared_libs: [
"libandroid",
+ "libbase",
"liblog",
"libnativehelper",
],
diff --git a/cmds/hid/jni/com_android_commands_hid_Device.cpp b/cmds/hid/jni/com_android_commands_hid_Device.cpp
index d4fdf85491d3..f56dd6e4968e 100644
--- a/cmds/hid/jni/com_android_commands_hid_Device.cpp
+++ b/cmds/hid/jni/com_android_commands_hid_Device.cpp
@@ -21,17 +21,21 @@
#include <linux/uhid.h>
#include <fcntl.h>
+#include <inttypes.h>
+#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <memory>
-#include <unistd.h>
+#include <android/log.h>
+#include <android/looper.h>
#include <jni.h>
#include <nativehelper/JNIHelp.h>
+#include <nativehelper/ScopedLocalRef.h>
#include <nativehelper/ScopedPrimitiveArray.h>
#include <nativehelper/ScopedUtfChars.h>
-#include <android/looper.h>
-#include <android/log.h>
+
+#include <android-base/stringprintf.h>
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,LOG_TAG,__VA_ARGS__)
@@ -46,6 +50,7 @@ static const char* UHID_PATH = "/dev/uhid";
static struct {
jmethodID onDeviceOpen;
jmethodID onDeviceGetReport;
+ jmethodID onDeviceOutput;
jmethodID onDeviceError;
} gDeviceCallbackClassInfo;
@@ -61,6 +66,26 @@ static void checkAndClearException(JNIEnv* env, const char* methodName) {
}
}
+static ScopedLocalRef<jbyteArray> toJbyteArray(JNIEnv* env, const std::vector<uint8_t>& vector) {
+ ScopedLocalRef<jbyteArray> array(env, env->NewByteArray(vector.size()));
+ if (array.get() == nullptr) {
+ jniThrowException(env, "java/lang/OutOfMemoryError", nullptr);
+ return array;
+ }
+ static_assert(sizeof(char) == sizeof(uint8_t));
+ env->SetByteArrayRegion(array.get(), 0, vector.size(),
+ reinterpret_cast<const signed char*>(vector.data()));
+ return array;
+}
+
+static std::string toString(const std::vector<uint8_t>& data) {
+ std::string s = "";
+ for (uint8_t b : data) {
+ s += android::base::StringPrintf("%x ", b);
+ }
+ return s;
+}
+
DeviceCallback::DeviceCallback(JNIEnv* env, jobject callback) :
mCallbackObject(env->NewGlobalRef(callback)) {
env->GetJavaVM(&mJavaVM);
@@ -90,23 +115,30 @@ void DeviceCallback::onDeviceGetReport(uint32_t requestId, uint8_t reportId) {
checkAndClearException(env, "onDeviceGetReport");
}
+void DeviceCallback::onDeviceOutput(const std::vector<uint8_t>& data) {
+ JNIEnv* env = getJNIEnv();
+ env->CallVoidMethod(mCallbackObject, gDeviceCallbackClassInfo.onDeviceOutput,
+ toJbyteArray(env, data).get());
+ checkAndClearException(env, "onDeviceOutput");
+}
+
JNIEnv* DeviceCallback::getJNIEnv() {
JNIEnv* env;
mJavaVM->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6);
return env;
}
-Device* Device::open(int32_t id, const char* name, int32_t vid, int32_t pid,
- std::vector<uint8_t> descriptor, std::unique_ptr<DeviceCallback> callback) {
-
+std::unique_ptr<Device> Device::open(int32_t id, const char* name, int32_t vid, int32_t pid,
+ const std::vector<uint8_t>& descriptor,
+ std::unique_ptr<DeviceCallback> callback) {
size_t size = descriptor.size();
if (size > HID_MAX_DESCRIPTOR_SIZE) {
LOGE("Received invalid hid report with descriptor size %zu, skipping", size);
return nullptr;
}
- int fd = ::open(UHID_PATH, O_RDWR | O_CLOEXEC);
- if (fd < 0) {
+ android::base::unique_fd fd(::open(UHID_PATH, O_RDWR | O_CLOEXEC));
+ if (!fd.ok()) {
LOGE("Failed to open uhid: %s", strerror(errno));
return nullptr;
}
@@ -114,8 +146,7 @@ Device* Device::open(int32_t id, const char* name, int32_t vid, int32_t pid,
struct uhid_event ev = {};
ev.type = UHID_CREATE2;
strlcpy(reinterpret_cast<char*>(ev.u.create2.name), name, sizeof(ev.u.create2.name));
- memcpy(&ev.u.create2.rd_data, descriptor.data(),
- size * sizeof(ev.u.create2.rd_data[0]));
+ memcpy(&ev.u.create2.rd_data, descriptor.data(), size * sizeof(ev.u.create2.rd_data[0]));
ev.u.create2.rd_size = size;
ev.u.create2.bus = BUS_BLUETOOTH;
ev.u.create2.vendor = vid;
@@ -126,7 +157,6 @@ Device* Device::open(int32_t id, const char* name, int32_t vid, int32_t pid,
errno = 0;
ssize_t ret = TEMP_FAILURE_RETRY(::write(fd, &ev, sizeof(ev)));
if (ret < 0 || ret != sizeof(ev)) {
- ::close(fd);
LOGE("Failed to create uhid node: %s", strerror(errno));
return nullptr;
}
@@ -134,21 +164,21 @@ Device* Device::open(int32_t id, const char* name, int32_t vid, int32_t pid,
// Wait for the device to actually be created.
ret = TEMP_FAILURE_RETRY(::read(fd, &ev, sizeof(ev)));
if (ret < 0 || ev.type != UHID_START) {
- ::close(fd);
LOGE("uhid node failed to start: %s", strerror(errno));
return nullptr;
}
- return new Device(id, fd, std::move(callback));
+ // using 'new' to access non-public constructor
+ return std::unique_ptr<Device>(new Device(id, std::move(fd), std::move(callback)));
}
-Device::Device(int32_t id, int fd, std::unique_ptr<DeviceCallback> callback) :
- mId(id), mFd(fd), mDeviceCallback(std::move(callback)) {
+Device::Device(int32_t id, android::base::unique_fd fd, std::unique_ptr<DeviceCallback> callback)
+ : mId(id), mFd(std::move(fd)), mDeviceCallback(std::move(callback)) {
ALooper* aLooper = ALooper_forThread();
if (aLooper == NULL) {
LOGE("Could not get ALooper, ALooper_forThread returned NULL");
aLooper = ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS);
}
- ALooper_addFd(aLooper, fd, 0, ALOOPER_EVENT_INPUT, handleLooperEvents,
+ ALooper_addFd(aLooper, mFd, 0, ALOOPER_EVENT_INPUT, handleLooperEvents,
reinterpret_cast<void*>(this));
}
@@ -162,8 +192,14 @@ Device::~Device() {
struct uhid_event ev = {};
ev.type = UHID_DESTROY;
TEMP_FAILURE_RETRY(::write(mFd, &ev, sizeof(ev)));
- ::close(mFd);
- mFd = -1;
+}
+
+// Send event over the fd.
+static void writeEvent(int fd, struct uhid_event& ev, const char* messageType) {
+ ssize_t ret = TEMP_FAILURE_RETRY(::write(fd, &ev, sizeof(ev)));
+ if (ret < 0 || ret != sizeof(ev)) {
+ LOGE("Failed to send uhid_event %s: %s", messageType, strerror(errno));
+ }
}
void Device::sendReport(const std::vector<uint8_t>& report) const {
@@ -176,10 +212,7 @@ void Device::sendReport(const std::vector<uint8_t>& report) const {
ev.type = UHID_INPUT2;
ev.u.input2.size = report.size();
memcpy(&ev.u.input2.data, report.data(), report.size() * sizeof(ev.u.input2.data[0]));
- ssize_t ret = TEMP_FAILURE_RETRY(::write(mFd, &ev, sizeof(ev)));
- if (ret < 0 || ret != sizeof(ev)) {
- LOGE("Failed to send hid event: %s", strerror(errno));
- }
+ writeEvent(mFd, ev, "UHID_INPUT2");
}
void Device::sendGetFeatureReportReply(uint32_t id, const std::vector<uint8_t>& report) const {
@@ -190,10 +223,7 @@ void Device::sendGetFeatureReportReply(uint32_t id, const std::vector<uint8_t>&
ev.u.get_report_reply.size = report.size();
memcpy(&ev.u.get_report_reply.data, report.data(),
report.size() * sizeof(ev.u.get_report_reply.data[0]));
- ssize_t ret = TEMP_FAILURE_RETRY(::write(mFd, &ev, sizeof(ev)));
- if (ret < 0 || ret != sizeof(ev)) {
- LOGE("Failed to send hid event (UHID_GET_REPORT_REPLY): %s", strerror(errno));
- }
+ writeEvent(mFd, ev, "UHID_GET_REPORT_REPLY");
}
int Device::handleEvents(int events) {
@@ -210,13 +240,37 @@ int Device::handleEvents(int events) {
return 0;
}
- if (ev.type == UHID_OPEN) {
- mDeviceCallback->onDeviceOpen();
- } else if (ev.type == UHID_GET_REPORT) {
- mDeviceCallback->onDeviceGetReport(ev.u.get_report.id, ev.u.get_report.rnum);
- } else if (ev.type == UHID_SET_REPORT) {
- LOGE("UHID_SET_REPORT is currently not supported");
- return 0;
+ switch (ev.type) {
+ case UHID_OPEN: {
+ mDeviceCallback->onDeviceOpen();
+ break;
+ }
+ case UHID_GET_REPORT: {
+ mDeviceCallback->onDeviceGetReport(ev.u.get_report.id, ev.u.get_report.rnum);
+ break;
+ }
+ case UHID_SET_REPORT: {
+ const struct uhid_set_report_req& set_report = ev.u.set_report;
+ if (set_report.size > UHID_DATA_MAX) {
+ LOGE("SET_REPORT contains too much data: size = %" PRIu16, set_report.size);
+ return 0;
+ }
+
+ std::vector<uint8_t> data(set_report.data, set_report.data + set_report.size);
+ LOGI("Received SET_REPORT: id=%" PRIu32 " rnum=%" PRIu8 " data=%s", set_report.id,
+ set_report.rnum, toString(data).c_str());
+ break;
+ }
+ case UHID_OUTPUT: {
+ struct uhid_output_req& output = ev.u.output;
+ std::vector<uint8_t> data(output.data, output.data + output.size);
+ mDeviceCallback->onDeviceOutput(data);
+ break;
+ }
+ default: {
+ LOGI("Unhandled event type: %" PRIu32, ev.type);
+ break;
+ }
}
return 1;
@@ -250,9 +304,10 @@ static jlong openDevice(JNIEnv* env, jclass /* clazz */, jstring rawName, jint i
std::unique_ptr<uhid::DeviceCallback> cb(new uhid::DeviceCallback(env, callback));
- uhid::Device* d = uhid::Device::open(
- id, reinterpret_cast<const char*>(name.c_str()), vid, pid, desc, std::move(cb));
- return reinterpret_cast<jlong>(d);
+ std::unique_ptr<uhid::Device> d =
+ uhid::Device::open(id, reinterpret_cast<const char*>(name.c_str()), vid, pid, desc,
+ std::move(cb));
+ return reinterpret_cast<jlong>(d.release());
}
static void sendReport(JNIEnv* env, jclass /* clazz */, jlong ptr, jbyteArray rawReport) {
@@ -304,6 +359,8 @@ int register_com_android_commands_hid_Device(JNIEnv* env) {
env->GetMethodID(clazz, "onDeviceOpen", "()V");
uhid::gDeviceCallbackClassInfo.onDeviceGetReport =
env->GetMethodID(clazz, "onDeviceGetReport", "(II)V");
+ uhid::gDeviceCallbackClassInfo.onDeviceOutput =
+ env->GetMethodID(clazz, "onDeviceOutput", "([B)V");
uhid::gDeviceCallbackClassInfo.onDeviceError =
env->GetMethodID(clazz, "onDeviceError", "()V");
if (uhid::gDeviceCallbackClassInfo.onDeviceOpen == NULL ||
diff --git a/cmds/hid/jni/com_android_commands_hid_Device.h b/cmds/hid/jni/com_android_commands_hid_Device.h
index 892c7cd12953..93ea881cfe28 100644
--- a/cmds/hid/jni/com_android_commands_hid_Device.h
+++ b/cmds/hid/jni/com_android_commands_hid_Device.h
@@ -19,6 +19,8 @@
#include <jni.h>
+#include <android-base/unique_fd.h>
+
namespace android {
namespace uhid {
@@ -29,6 +31,7 @@ public:
void onDeviceOpen();
void onDeviceGetReport(uint32_t requestId, uint8_t reportId);
+ void onDeviceOutput(const std::vector<uint8_t>& data);
void onDeviceError();
private:
@@ -39,10 +42,10 @@ private:
class Device {
public:
- static Device* open(int32_t id, const char* name, int32_t vid, int32_t pid,
- std::vector<uint8_t> descriptor, std::unique_ptr<DeviceCallback> callback);
+ static std::unique_ptr<Device> open(int32_t id, const char* name, int32_t vid, int32_t pid,
+ const std::vector<uint8_t>& descriptor,
+ std::unique_ptr<DeviceCallback> callback);
- Device(int32_t id, int fd, std::unique_ptr<DeviceCallback> callback);
~Device();
void sendReport(const std::vector<uint8_t>& report) const;
@@ -52,8 +55,9 @@ public:
int handleEvents(int events);
private:
+ Device(int32_t id, android::base::unique_fd fd, std::unique_ptr<DeviceCallback> callback);
int32_t mId;
- int mFd;
+ android::base::unique_fd mFd;
std::unique_ptr<DeviceCallback> mDeviceCallback;
};
diff --git a/cmds/hid/src/com/android/commands/hid/Device.java b/cmds/hid/src/com/android/commands/hid/Device.java
index 616d411ef7bb..874604ceb5e4 100644
--- a/cmds/hid/src/com/android/commands/hid/Device.java
+++ b/cmds/hid/src/com/android/commands/hid/Device.java
@@ -20,13 +20,16 @@ import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
-import android.os.MessageQueue;
import android.os.SystemClock;
import android.util.Log;
import android.util.SparseArray;
import com.android.internal.os.SomeArgs;
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+import java.util.Map;
+
public class Device {
private static final String TAG = "HidDevice";
@@ -40,6 +43,7 @@ public class Device {
private final DeviceHandler mHandler;
// mFeatureReports is limited to 256 entries, because the report number is 8-bit
private final SparseArray<byte[]> mFeatureReports;
+ private final Map<ByteBuffer, byte[]> mOutputs;
private long mTimeToSend;
private final Object mCond = new Object();
@@ -55,12 +59,13 @@ public class Device {
private static native void nativeCloseDevice(long ptr);
public Device(int id, String name, int vid, int pid, byte[] descriptor,
- byte[] report, SparseArray<byte[]> featureReports) {
+ byte[] report, SparseArray<byte[]> featureReports, Map<ByteBuffer, byte[]> outputs) {
mId = id;
mThread = new HandlerThread("HidDeviceHandler");
mThread.start();
mHandler = new DeviceHandler(mThread.getLooper());
mFeatureReports = featureReports;
+ mOutputs = outputs;
SomeArgs args = SomeArgs.obtain();
args.argi1 = id;
args.argi2 = vid;
@@ -160,6 +165,11 @@ public class Device {
}
public void onDeviceGetReport(int requestId, int reportId) {
+ if (mFeatureReports == null) {
+ Log.e(TAG, "Received GET_REPORT request for reportId=" + reportId
+ + ", but 'feature_reports' section is not found");
+ return;
+ }
byte[] report = mFeatureReports.get(reportId);
if (report == null) {
@@ -176,6 +186,29 @@ public class Device {
mHandler.sendMessageAtTime(msg, mTimeToSend);
}
+ // native callback
+ public void onDeviceOutput(byte[] data) {
+ if (mOutputs == null) {
+ Log.e(TAG, "Received OUTPUT request, but 'outputs' section is not found");
+ return;
+ }
+ byte[] response = mOutputs.get(ByteBuffer.wrap(data));
+ if (response == null) {
+ Log.i(TAG,
+ "Requested response for output " + Arrays.toString(data) + " is not found");
+ return;
+ }
+
+ Message msg;
+ msg = mHandler.obtainMessage(MSG_SEND_REPORT, response);
+
+ // Message is set to asynchronous so it won't be blocked by synchronization
+ // barrier during UHID_OPEN. This is necessary for drivers that do
+ // UHID_OUTPUT requests during probe, and expect a response right away.
+ msg.setAsynchronous(true);
+ mHandler.sendMessageAtTime(msg, mTimeToSend);
+ }
+
public void onDeviceError() {
Log.e(TAG, "Device error occurred, closing /dev/uhid");
Message msg = mHandler.obtainMessage(MSG_CLOSE_DEVICE);
diff --git a/cmds/hid/src/com/android/commands/hid/Event.java b/cmds/hid/src/com/android/commands/hid/Event.java
index 746e37289076..62587a70f10d 100644
--- a/cmds/hid/src/com/android/commands/hid/Event.java
+++ b/cmds/hid/src/com/android/commands/hid/Event.java
@@ -21,10 +21,13 @@ import android.util.JsonToken;
import android.util.Log;
import android.util.SparseArray;
-import java.io.InputStreamReader;
import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
public class Event {
private static final String TAG = "HidEvent";
@@ -41,6 +44,7 @@ public class Event {
private int mPid;
private byte[] mReport;
private SparseArray<byte[]> mFeatureReports;
+ private Map<ByteBuffer, byte[]> mOutputs;
private int mDuration;
public int getId() {
@@ -75,6 +79,10 @@ public class Event {
return mFeatureReports;
}
+ public Map<ByteBuffer, byte[]> getOutputs() {
+ return mOutputs;
+ }
+
public int getDuration() {
return mDuration;
}
@@ -88,6 +96,7 @@ public class Event {
+ ", pid=" + mPid
+ ", report=" + Arrays.toString(mReport)
+ ", feature_reports=" + mFeatureReports.toString()
+ + ", outputs=" + mOutputs.toString()
+ ", duration=" + mDuration
+ "}";
}
@@ -123,6 +132,10 @@ public class Event {
mEvent.mFeatureReports = reports;
}
+ public void setOutputs(Map<ByteBuffer, byte[]> outputs) {
+ mEvent.mOutputs = outputs;
+ }
+
public void setVid(int vid) {
mEvent.mVid = vid;
}
@@ -199,6 +212,9 @@ public class Event {
case "feature_reports":
eb.setFeatureReports(readFeatureReports());
break;
+ case "outputs":
+ eb.setOutputs(readOutputs());
+ break;
case "duration":
eb.setDuration(readInt());
break;
@@ -250,7 +266,7 @@ public class Event {
private SparseArray<byte[]> readFeatureReports()
throws IllegalStateException, IOException {
- SparseArray<byte[]> featureReports = new SparseArray();
+ SparseArray<byte[]> featureReports = new SparseArray<>();
try {
mReader.beginArray();
while (mReader.hasNext()) {
@@ -276,17 +292,60 @@ public class Event {
}
}
mReader.endObject();
- if (data != null)
+ if (data != null) {
featureReports.put(id, data);
+ }
}
mReader.endArray();
- } catch (IllegalStateException|NumberFormatException e) {
+ } catch (IllegalStateException | NumberFormatException e) {
+ consumeRemainingElements();
+ mReader.endArray();
+ throw new IllegalStateException("Encountered malformed data.", e);
+ }
+ return featureReports;
+ }
+
+ private Map<ByteBuffer, byte[]> readOutputs()
+ throws IllegalStateException, IOException {
+ Map<ByteBuffer, byte[]> outputs = new HashMap<>();
+
+ try {
+ mReader.beginArray();
+ while (mReader.hasNext()) {
+ byte[] output = null;
+ byte[] response = null;
+ mReader.beginObject();
+ while (mReader.hasNext()) {
+ String name = mReader.nextName();
+ switch (name) {
+ case "description":
+ // Description is only used to keep track of the output responses
+ mReader.nextString();
+ break;
+ case "output":
+ output = readData();
+ break;
+ case "response":
+ response = readData();
+ break;
+ default:
+ consumeRemainingElements();
+ mReader.endObject();
+ throw new IllegalStateException("Invalid key in outputs: " + name);
+ }
+ }
+ mReader.endObject();
+ if (output != null) {
+ outputs.put(ByteBuffer.wrap(output), response);
+ }
+ }
+ mReader.endArray();
+ } catch (IllegalStateException | NumberFormatException e) {
consumeRemainingElements();
mReader.endArray();
throw new IllegalStateException("Encountered malformed data.", e);
- } finally {
- return featureReports;
}
+ return outputs;
}
private void consumeRemainingElements() throws IOException {
@@ -296,10 +355,6 @@ public class Event {
}
}
- private static void error(String msg) {
- error(msg, null);
- }
-
private static void error(String msg, Exception e) {
System.out.println(msg);
Log.e(TAG, msg);
diff --git a/cmds/hid/src/com/android/commands/hid/Hid.java b/cmds/hid/src/com/android/commands/hid/Hid.java
index 54ac1b0733ff..0ee2cc45932f 100644
--- a/cmds/hid/src/com/android/commands/hid/Hid.java
+++ b/cmds/hid/src/com/android/commands/hid/Hid.java
@@ -16,22 +16,17 @@
package com.android.commands.hid;
-import android.util.JsonReader;
-import android.util.JsonToken;
import android.util.Log;
import android.util.SparseArray;
import libcore.io.IoUtils;
-import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileNotFoundException;
+import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
-import java.io.IOException;
import java.io.UnsupportedEncodingException;
-import java.util.ArrayList;
public class Hid {
private static final String TAG = "HID";
@@ -119,7 +114,7 @@ public class Hid {
}
int id = e.getId();
Device d = new Device(id, e.getName(), e.getVendorId(), e.getProductId(),
- e.getDescriptor(), e.getReport(), e.getFeatureReports());
+ e.getDescriptor(), e.getReport(), e.getFeatureReports(), e.getOutputs());
mDevices.append(id, d);
}
diff --git a/cmds/incident/main.cpp b/cmds/incident/main.cpp
index 6c3d19715c2e..eb2b98a666b9 100644
--- a/cmds/incident/main.cpp
+++ b/cmds/incident/main.cpp
@@ -375,7 +375,7 @@ main(int argc, char** argv)
if (destination == DEST_STDOUT) {
// Call into the service
sp<StatusListener> listener(new StatusListener());
- status = service->reportIncidentToStream(args, listener, writeEnd);
+ status = service->reportIncidentToStream(args, listener, std::move(writeEnd));
if (!status.isOk()) {
fprintf(stderr, "reportIncident returned \"%s\"\n", status.toString8().string());
@@ -388,7 +388,7 @@ main(int argc, char** argv)
} else if (destination == DEST_DUMPSTATE) {
// Call into the service
sp<StatusListener> listener(new StatusListener());
- status = service->reportIncidentToDumpstate(writeEnd, listener);
+ status = service->reportIncidentToDumpstate(std::move(writeEnd), listener);
if (!status.isOk()) {
fprintf(stderr, "reportIncident returned \"%s\"\n", status.toString8().string());
return 1;
diff --git a/cmds/incidentd/src/IncidentService.cpp b/cmds/incidentd/src/IncidentService.cpp
index 999936bda1d3..cfd77c2357cd 100644
--- a/cmds/incidentd/src/IncidentService.cpp
+++ b/cmds/incidentd/src/IncidentService.cpp
@@ -279,7 +279,7 @@ Status IncidentService::reportIncident(const IncidentReportArgs& args) {
Status IncidentService::reportIncidentToStream(const IncidentReportArgs& args,
const sp<IIncidentReportStatusListener>& listener,
- const unique_fd& stream) {
+ unique_fd stream) {
IncidentReportArgs argsCopy(args);
// Streaming reports can not also be broadcast.
@@ -306,7 +306,7 @@ Status IncidentService::reportIncidentToStream(const IncidentReportArgs& args,
return Status::ok();
}
-Status IncidentService::reportIncidentToDumpstate(const unique_fd& stream,
+Status IncidentService::reportIncidentToDumpstate(unique_fd stream,
const sp<IIncidentReportStatusListener>& listener) {
uid_t caller = IPCThreadState::self()->getCallingUid();
if (caller != AID_ROOT && caller != AID_SHELL) {
diff --git a/cmds/incidentd/src/IncidentService.h b/cmds/incidentd/src/IncidentService.h
index fb013d0bf92d..b2c7f233e11b 100644
--- a/cmds/incidentd/src/IncidentService.h
+++ b/cmds/incidentd/src/IncidentService.h
@@ -121,9 +121,9 @@ public:
virtual Status reportIncidentToStream(const IncidentReportArgs& args,
const sp<IIncidentReportStatusListener>& listener,
- const unique_fd& stream);
+ unique_fd stream);
- virtual Status reportIncidentToDumpstate(const unique_fd& stream,
+ virtual Status reportIncidentToDumpstate(unique_fd stream,
const sp<IIncidentReportStatusListener>& listener);
virtual Status systemRunning();
diff --git a/cmds/incidentd/src/WorkDirectory.cpp b/cmds/incidentd/src/WorkDirectory.cpp
index 7e7c6421e23f..9963533c08ac 100644
--- a/cmds/incidentd/src/WorkDirectory.cpp
+++ b/cmds/incidentd/src/WorkDirectory.cpp
@@ -666,7 +666,7 @@ int64_t WorkDirectory::make_timestamp_ns_locked() {
clock_gettime(CLOCK_REALTIME, &spec);
timestampNs = int64_t(spec.tv_sec) * 1000 + spec.tv_nsec;
} while (file_exists_locked(timestampNs));
- return timestampNs;
+ return (timestampNs >= 0)? timestampNs : -timestampNs;
}
/**
diff --git a/cmds/media/Android.bp b/cmds/media/Android.bp
deleted file mode 100644
index 7879c53684a7..000000000000
--- a/cmds/media/Android.bp
+++ /dev/null
@@ -1,8 +0,0 @@
-// Copyright 2013 The Android Open Source Project
-//
-
-java_binary {
- name: "media",
- wrapper: "media",
- srcs: ["**/*.java"],
-}
diff --git a/cmds/media/MODULE_LICENSE_APACHE2 b/cmds/media/MODULE_LICENSE_APACHE2
deleted file mode 100644
index e69de29bb2d1..000000000000
--- a/cmds/media/MODULE_LICENSE_APACHE2
+++ /dev/null
diff --git a/cmds/media/NOTICE b/cmds/media/NOTICE
deleted file mode 100644
index c5b1efa7aac7..000000000000
--- a/cmds/media/NOTICE
+++ /dev/null
@@ -1,190 +0,0 @@
-
- Copyright (c) 2005-2008, 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.
-
- 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.
-
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
diff --git a/cmds/media/media b/cmds/media/media
deleted file mode 100755
index 00c3915f2e65..000000000000
--- a/cmds/media/media
+++ /dev/null
@@ -1,3 +0,0 @@
-#!/system/bin/sh
-export CLASSPATH=/system/framework/media.jar
-exec app_process /system/bin com.android.commands.media.Media "$@"
diff --git a/cmds/statsd/Android.bp b/cmds/statsd/Android.bp
index 17427a20b90e..afff61497157 100644
--- a/cmds/statsd/Android.bp
+++ b/cmds/statsd/Android.bp
@@ -146,6 +146,7 @@ cc_defaults {
"libprotoutil",
"libservices",
"libstatslog",
+ "libstatsmetadata",
"libstatssocket",
"libsysutils",
"libtimestats_proto",
@@ -153,6 +154,63 @@ cc_defaults {
],
}
+// ================
+// libstatsmetadata
+// ================
+
+genrule {
+ name: "atoms_info.h",
+ tools: ["stats-log-api-gen"],
+ cmd: "$(location stats-log-api-gen) --atomsInfoHeader $(genDir)/atoms_info.h",
+ out: [
+ "atoms_info.h",
+ ],
+}
+
+genrule {
+ name: "atoms_info.cpp",
+ tools: ["stats-log-api-gen"],
+ cmd: "$(location stats-log-api-gen) --atomsInfoCpp $(genDir)/atoms_info.cpp",
+ out: [
+ "atoms_info.cpp",
+ ],
+}
+
+cc_library_shared {
+ name: "libstatsmetadata",
+ host_supported: true,
+ generated_sources: [
+ "atoms_info.cpp",
+ ],
+ generated_headers: [
+ "atoms_info.h",
+ ],
+ cflags: [
+ "-Wall",
+ "-Werror",
+ ],
+ export_generated_headers: [
+ "atoms_info.h",
+ ],
+ shared_libs: [
+ "libcutils",
+ "libstatslog",
+ ],
+ target: {
+ android: {
+ shared_libs: [
+ "libutils",
+ ],
+ },
+ host: {
+ static_libs: [
+ "libutils",
+ ],
+ },
+ },
+}
+
+
// =========
// statsd
// =========
@@ -250,6 +308,7 @@ cc_test {
"tests/external/GpuStatsPuller_test.cpp",
"tests/external/IncidentReportArgs_test.cpp",
"tests/external/puller_util_test.cpp",
+ "tests/external/StatsCallbackPuller_test.cpp",
"tests/external/StatsPuller_test.cpp",
"tests/external/SurfaceflingerStatsPuller_test.cpp",
"tests/FieldValue_test.cpp",
diff --git a/cmds/statsd/src/FieldValue.cpp b/cmds/statsd/src/FieldValue.cpp
index 84a06070e431..a545fc5718d0 100644
--- a/cmds/statsd/src/FieldValue.cpp
+++ b/cmds/statsd/src/FieldValue.cpp
@@ -18,8 +18,8 @@
#include "Log.h"
#include "FieldValue.h"
#include "HashableDimensionKey.h"
+#include "atoms_info.h"
#include "math.h"
-#include "statslog.h"
namespace android {
namespace os {
diff --git a/cmds/statsd/src/StatsLogProcessor.cpp b/cmds/statsd/src/StatsLogProcessor.cpp
index 98d41c22d540..34818145a922 100644
--- a/cmds/statsd/src/StatsLogProcessor.cpp
+++ b/cmds/statsd/src/StatsLogProcessor.cpp
@@ -27,6 +27,7 @@
#include <utils/SystemClock.h>
#include "android-base/stringprintf.h"
+#include "atoms_info.h"
#include "external/StatsPullerManager.h"
#include "guardrail/StatsdStats.h"
#include "metrics/CountMetricProducer.h"
diff --git a/cmds/statsd/src/StatsService.cpp b/cmds/statsd/src/StatsService.cpp
index 3c5ad4231133..4d38ba03b1df 100644
--- a/cmds/statsd/src/StatsService.cpp
+++ b/cmds/statsd/src/StatsService.cpp
@@ -272,7 +272,7 @@ status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* rep
}
return NO_ERROR;
}
- default: { return BnStatsManager::onTransact(code, data, reply, flags); }
+ default: { return BnStatsd::onTransact(code, data, reply, flags); }
}
}
@@ -862,13 +862,13 @@ status_t StatsService::cmd_log_binary_push(int out, const Vector<String8>& args)
int64_t trainVersion = strtoll(args[2].c_str(), nullptr, 10);
int options = 0;
if (args[3] == "1") {
- options = options | IStatsManager::FLAG_REQUIRE_STAGING;
+ options = options | IStatsd::FLAG_REQUIRE_STAGING;
}
if (args[4] == "1") {
- options = options | IStatsManager::FLAG_ROLLBACK_ENABLED;
+ options = options | IStatsd::FLAG_ROLLBACK_ENABLED;
}
if (args[5] == "1") {
- options = options | IStatsManager::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
+ options = options | IStatsd::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
}
int32_t state = atoi(args[6].c_str());
vector<int64_t> experimentIds;
@@ -1406,9 +1406,9 @@ Status StatsService::sendBinaryPushStateChangedAtom(const android::String16& tra
StorageManager::writeTrainInfo(trainVersionCode, trainNameUtf8, state, experimentIds);
userid_t userId = multiuser_get_user_id(uid);
- bool requiresStaging = options & IStatsManager::FLAG_REQUIRE_STAGING;
- bool rollbackEnabled = options & IStatsManager::FLAG_ROLLBACK_ENABLED;
- bool requiresLowLatencyMonitor = options & IStatsManager::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
+ bool requiresStaging = options & IStatsd::FLAG_REQUIRE_STAGING;
+ bool rollbackEnabled = options & IStatsd::FLAG_ROLLBACK_ENABLED;
+ bool requiresLowLatencyMonitor = options & IStatsd::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
LogEvent event(trainNameUtf8, trainVersionCode, requiresStaging, rollbackEnabled,
requiresLowLatencyMonitor, state, experimentIdsProtoBuffer, userId);
mProcessor->OnLogEvent(&event);
diff --git a/cmds/statsd/src/StatsService.h b/cmds/statsd/src/StatsService.h
index 50b1014f4e8a..9abf415ad91f 100644
--- a/cmds/statsd/src/StatsService.h
+++ b/cmds/statsd/src/StatsService.h
@@ -29,9 +29,9 @@
#include <android/frameworks/stats/1.0/IStats.h>
#include <android/frameworks/stats/1.0/types.h>
-#include <android/os/BnStatsManager.h>
+#include <android/os/BnStatsd.h>
#include <android/os/IStatsCompanionService.h>
-#include <android/os/IStatsManager.h>
+#include <android/os/IStatsd.h>
#include <binder/IResultReceiver.h>
#include <binder/ParcelFileDescriptor.h>
#include <utils/Looper.h>
@@ -52,7 +52,7 @@ namespace statsd {
using android::hardware::Return;
-class StatsService : public BnStatsManager,
+class StatsService : public BnStatsd,
public IStats,
public IBinder::DeathRecipient {
public:
diff --git a/cmds/statsd/src/atoms.proto b/cmds/statsd/src/atoms.proto
index 77ff707c1de5..a2cfff2ff02e 100644
--- a/cmds/statsd/src/atoms.proto
+++ b/cmds/statsd/src/atoms.proto
@@ -113,8 +113,8 @@ message Atom {
WakeupAlarmOccurred wakeup_alarm_occurred = 35;
KernelWakeupReported kernel_wakeup_reported = 36;
WifiLockStateChanged wifi_lock_state_changed = 37 [(log_from_module) = "wifi"];
- WifiSignalStrengthChanged wifi_signal_strength_changed = 38;
- WifiScanStateChanged wifi_scan_state_changed = 39;
+ WifiSignalStrengthChanged wifi_signal_strength_changed = 38 [(log_from_module) = "wifi"];
+ WifiScanStateChanged wifi_scan_state_changed = 39 [(log_from_module) = "wifi"];
PhoneSignalStrengthChanged phone_signal_strength_changed = 40;
SettingChanged setting_changed = 41;
ActivityForegroundStateChanged activity_foreground_state_changed = 42;
@@ -128,7 +128,7 @@ message Atom {
AppStartFullyDrawn app_start_fully_drawn = 50;
LmkKillOccurred lmk_kill_occurred = 51;
PictureInPictureStateChanged picture_in_picture_state_changed = 52;
- WifiMulticastLockStateChanged wifi_multicast_lock_state_changed = 53;
+ WifiMulticastLockStateChanged wifi_multicast_lock_state_changed = 53 [(log_from_module) = "wifi"];
LmkStateChanged lmk_state_changed = 54;
AppStartMemoryStateCaptured app_start_memory_state_captured = 55;
ShutdownSequenceReported shutdown_sequence_reported = 56;
@@ -356,7 +356,7 @@ message Atom {
}
// Pulled events will start at field 10000.
- // Next: 10067
+ // Next: 10068
oneof pulled {
WifiBytesTransfer wifi_bytes_transfer = 10000;
WifiBytesTransferByFgBg wifi_bytes_transfer_by_fg_bg = 10001;
@@ -424,6 +424,7 @@ message Atom {
ProcessMemorySnapshot process_memory_snapshot = 10064;
VmsClientStats vms_client_stats = 10065;
NotificationRemoteViews notification_remote_views = 10066;
+ DangerousPermissionStateSampled dangerous_permission_state_sampled = 10067;
}
// DO NOT USE field numbers above 100,000 in AOSP.
@@ -6490,7 +6491,8 @@ message MediametricsDrmManagerReported {
/**
* State of a dangerous permission requested by a package
- */
+ * Pulled from: StatsCompanionService
+*/
message DangerousPermissionState {
// Name of the permission
optional string permission_name = 1;
@@ -7541,3 +7543,22 @@ message VmsClientStats {
optional int64 dropped_bytes = 9;
optional int64 dropped_packets = 10;
}
+
+/**
+ * State of a dangerous permission requested by a package - sampled
+ * Pulled from: StatsCompanionService.java with data obtained from PackageManager API
+*/
+message DangerousPermissionStateSampled {
+ // Name of the permission
+ optional string permission_name = 1;
+
+ // Uid of the package
+ optional int32 uid = 2 [(is_uid) = true];
+
+ // If the permission is granted to the uid
+ optional bool is_granted = 3;
+
+ // Permission flags as per android.content.pm.PermissionFlags
+ optional int32 permission_flags = 4;
+}
+
diff --git a/cmds/statsd/src/external/PowerStatsPuller.cpp b/cmds/statsd/src/external/PowerStatsPuller.cpp
index b142caca3acc..dc69b78f0329 100644
--- a/cmds/statsd/src/external/PowerStatsPuller.cpp
+++ b/cmds/statsd/src/external/PowerStatsPuller.cpp
@@ -22,6 +22,7 @@
#include <vector>
#include "PowerStatsPuller.h"
+#include "statslog.h"
#include "stats_log_util.h"
using android::hardware::hidl_vec;
diff --git a/cmds/statsd/src/external/StatsCallbackPuller.cpp b/cmds/statsd/src/external/StatsCallbackPuller.cpp
index f5b1e7f78736..0e6b677abb46 100644
--- a/cmds/statsd/src/external/StatsCallbackPuller.cpp
+++ b/cmds/statsd/src/external/StatsCallbackPuller.cpp
@@ -35,8 +35,9 @@ namespace android {
namespace os {
namespace statsd {
-StatsCallbackPuller::StatsCallbackPuller(int tagId, const sp<IPullAtomCallback>& callback)
- : StatsPuller(tagId), mCallback(callback) {
+StatsCallbackPuller::StatsCallbackPuller(int tagId, const sp<IPullAtomCallback>& callback,
+ int64_t timeoutNs)
+ : StatsPuller(tagId), mCallback(callback), mTimeoutNs(timeoutNs) {
VLOG("StatsCallbackPuller created for tag %d", tagId);
}
@@ -64,10 +65,9 @@ bool StatsCallbackPuller::PullInternal(vector<shared_ptr<LogEvent>>* data) {
{
lock_guard<mutex> lk(*cv_mutex);
for (const StatsEventParcel& parcel: output) {
- shared_ptr<LogEvent> event =
- make_shared<LogEvent>(const_cast<uint8_t*>(parcel.buffer.data()),
- parcel.buffer.size(),
- /*uid=*/ -1);
+ shared_ptr<LogEvent> event = make_shared<LogEvent>(
+ const_cast<uint8_t*>(parcel.buffer.data()), parcel.buffer.size(),
+ /*uid=*/-1, /*useNewSchema=*/true);
sharedData->push_back(event);
}
*pullSuccess = success;
@@ -76,7 +76,8 @@ bool StatsCallbackPuller::PullInternal(vector<shared_ptr<LogEvent>>* data) {
cv->notify_one();
});
- // Initiate the pull.
+ // Initiate the pull. This is a oneway call to a different process, except
+ // in unit tests. In process calls are not oneway.
Status status = mCallback->onPullAtom(mTagId, resultReceiver);
if (!status.isOk()) {
return false;
@@ -84,10 +85,8 @@ bool StatsCallbackPuller::PullInternal(vector<shared_ptr<LogEvent>>* data) {
{
unique_lock<mutex> unique_lk(*cv_mutex);
- int64_t pullTimeoutNs =
- StatsPullerManager::kAllPullAtomInfo.at({.atomTag = mTagId}).pullTimeoutNs;
// Wait until the pull finishes, or until the pull timeout.
- cv->wait_for(unique_lk, chrono::nanoseconds(pullTimeoutNs),
+ cv->wait_for(unique_lk, chrono::nanoseconds(mTimeoutNs),
[pullFinish] { return *pullFinish; });
if (!*pullFinish) {
// Note: The parent stats puller will also note that there was a timeout and that the
@@ -96,7 +95,7 @@ bool StatsCallbackPuller::PullInternal(vector<shared_ptr<LogEvent>>* data) {
return true;
} else {
// Only copy the data if we did not timeout and the pull was successful.
- if (pullSuccess) {
+ if (*pullSuccess) {
*data = std::move(*sharedData);
}
VLOG("StatsCallbackPuller::pull succeeded for %d", mTagId);
diff --git a/cmds/statsd/src/external/StatsCallbackPuller.h b/cmds/statsd/src/external/StatsCallbackPuller.h
index ce506c7f9785..d943f9d189c5 100644
--- a/cmds/statsd/src/external/StatsCallbackPuller.h
+++ b/cmds/statsd/src/external/StatsCallbackPuller.h
@@ -27,11 +27,17 @@ namespace statsd {
class StatsCallbackPuller : public StatsPuller {
public:
- explicit StatsCallbackPuller(int tagId, const sp<IPullAtomCallback>& callback);
+ explicit StatsCallbackPuller(int tagId, const sp<IPullAtomCallback>& callback,
+ int64_t timeoutNs);
private:
bool PullInternal(vector<std::shared_ptr<LogEvent> >* data) override;
const sp<IPullAtomCallback> mCallback;
+ const int64_t mTimeoutNs;
+
+ FRIEND_TEST(StatsCallbackPullerTest, PullFail);
+ FRIEND_TEST(StatsCallbackPullerTest, PullSuccess);
+ FRIEND_TEST(StatsCallbackPullerTest, PullTimeout);
};
} // namespace statsd
diff --git a/cmds/statsd/src/external/StatsPullerManager.cpp b/cmds/statsd/src/external/StatsPullerManager.cpp
index 615af89e3186..f913118385a3 100644
--- a/cmds/statsd/src/external/StatsPullerManager.cpp
+++ b/cmds/statsd/src/external/StatsPullerManager.cpp
@@ -284,6 +284,10 @@ std::map<PullerKey, PullAtomInfo> StatsPullerManager::kAllPullAtomInfo = {
// NotiifcationRemoteViews.
{{.atomTag = android::util::NOTIFICATION_REMOTE_VIEWS},
{.puller = new StatsCompanionServicePuller(android::util::NOTIFICATION_REMOTE_VIEWS)}},
+ // PermissionStateSampled.
+ {{.atomTag = android::util::DANGEROUS_PERMISSION_STATE_SAMPLED},
+ {.puller =
+ new StatsCompanionServicePuller(android::util::DANGEROUS_PERMISSION_STATE_SAMPLED)}},
};
StatsPullerManager::StatsPullerManager() : mNextPullTimeNs(NO_ALARM_UPDATE) {
@@ -500,10 +504,11 @@ void StatsPullerManager::RegisterPullAtomCallback(const int uid, const int32_t a
VLOG("RegisterPullerCallback: adding puller for tag %d", atomTag);
// TODO: linkToDeath with the callback so that we can remove it and delete the puller.
StatsdStats::getInstance().notePullerCallbackRegistrationChanged(atomTag, /*registered=*/true);
- kAllPullAtomInfo[{.atomTag = atomTag}] = {.additiveFields = additiveFields,
- .coolDownNs = coolDownNs,
- .puller = new StatsCallbackPuller(atomTag, callback),
- .pullTimeoutNs = timeoutNs,
+ kAllPullAtomInfo[{.atomTag = atomTag}] = {
+ .additiveFields = additiveFields,
+ .coolDownNs = coolDownNs,
+ .puller = new StatsCallbackPuller(atomTag, callback, timeoutNs),
+ .pullTimeoutNs = timeoutNs,
};
}
diff --git a/cmds/statsd/src/external/puller_util.cpp b/cmds/statsd/src/external/puller_util.cpp
index 53fa6301a836..031c43740d9d 100644
--- a/cmds/statsd/src/external/puller_util.cpp
+++ b/cmds/statsd/src/external/puller_util.cpp
@@ -18,8 +18,8 @@
#include "Log.h"
#include "StatsPullerManager.h"
+#include "atoms_info.h"
#include "puller_util.h"
-#include "statslog.h"
namespace android {
namespace os {
diff --git a/cmds/statsd/src/guardrail/StatsdStats.h b/cmds/statsd/src/guardrail/StatsdStats.h
index 23d2aceb4fc3..564b9ee8051c 100644
--- a/cmds/statsd/src/guardrail/StatsdStats.h
+++ b/cmds/statsd/src/guardrail/StatsdStats.h
@@ -16,7 +16,7 @@
#pragma once
#include "config/ConfigKey.h"
-#include "statslog.h"
+#include "atoms_info.h"
#include <gtest/gtest_prod.h>
#include <log/log_time.h>
diff --git a/cmds/statsd/src/logd/LogEvent.cpp b/cmds/statsd/src/logd/LogEvent.cpp
index 67022a078b01..36f4623c4dcb 100644
--- a/cmds/statsd/src/logd/LogEvent.cpp
+++ b/cmds/statsd/src/logd/LogEvent.cpp
@@ -52,6 +52,17 @@ LogEvent::LogEvent(uint8_t* msg, uint32_t len, uint32_t uid)
#endif
}
+LogEvent::LogEvent(uint8_t* msg, uint32_t len, uint32_t uid, bool useNewSchema)
+ : mBuf(msg), mRemainingLen(len), mLogdTimestampNs(time(nullptr)), mLogUid(uid) {
+ if (useNewSchema) {
+ initNew();
+ } else {
+ mContext = create_android_log_parser((char*)msg, len);
+ init(mContext);
+ if (mContext) android_log_destroy(&mContext); // set mContext to NULL
+ }
+}
+
LogEvent::LogEvent(const LogEvent& event) {
mTagId = event.mTagId;
mLogUid = event.mLogUid;
diff --git a/cmds/statsd/src/logd/LogEvent.h b/cmds/statsd/src/logd/LogEvent.h
index 1ff95f7240ac..596d623debe5 100644
--- a/cmds/statsd/src/logd/LogEvent.h
+++ b/cmds/statsd/src/logd/LogEvent.h
@@ -75,6 +75,11 @@ public:
explicit LogEvent(uint8_t* msg, uint32_t len, uint32_t uid);
/**
+ * Temp constructor to use for pulled atoms until we flip the socket schema.
+ */
+ explicit LogEvent(uint8_t* msg, uint32_t len, uint32_t uid, bool useNewSchema);
+
+ /**
* Creates LogEvent from StatsLogEventWrapper.
*/
static void createLogEvents(const StatsLogEventWrapper& statsLogEventWrapper,
diff --git a/cmds/statsd/src/metrics/MetricsManager.cpp b/cmds/statsd/src/metrics/MetricsManager.cpp
index 464cec36d5e3..088f607ecfce 100644
--- a/cmds/statsd/src/metrics/MetricsManager.cpp
+++ b/cmds/statsd/src/metrics/MetricsManager.cpp
@@ -23,6 +23,7 @@
#include <utils/SystemClock.h>
#include "CountMetricProducer.h"
+#include "atoms_info.h"
#include "condition/CombinationConditionTracker.h"
#include "condition/SimpleConditionTracker.h"
#include "guardrail/StatsdStats.h"
diff --git a/cmds/statsd/src/metrics/metrics_manager_util.cpp b/cmds/statsd/src/metrics/metrics_manager_util.cpp
index 9131802c83e7..2ad8217c45d4 100644
--- a/cmds/statsd/src/metrics/metrics_manager_util.cpp
+++ b/cmds/statsd/src/metrics/metrics_manager_util.cpp
@@ -22,6 +22,7 @@
#include <inttypes.h>
+#include "atoms_info.h"
#include "condition/CombinationConditionTracker.h"
#include "condition/SimpleConditionTracker.h"
#include "condition/StateConditionTracker.h"
@@ -36,7 +37,6 @@
#include "metrics/ValueMetricProducer.h"
#include "state/StateManager.h"
#include "stats_util.h"
-#include "statslog.h"
using std::set;
using std::string;
diff --git a/cmds/statsd/src/state/StateManager.cpp b/cmds/statsd/src/state/StateManager.cpp
index 2fa28c9846fd..80d398339ebb 100644
--- a/cmds/statsd/src/state/StateManager.cpp
+++ b/cmds/statsd/src/state/StateManager.cpp
@@ -29,18 +29,15 @@ StateManager& StateManager::getInstance() {
}
void StateManager::onLogEvent(const LogEvent& event) {
- std::lock_guard<std::mutex> lock(mMutex);
if (mStateTrackers.find(event.GetTagId()) != mStateTrackers.end()) {
mStateTrackers[event.GetTagId()]->onLogEvent(event);
}
}
bool StateManager::registerListener(int32_t atomId, wp<StateListener> listener) {
- std::lock_guard<std::mutex> lock(mMutex);
-
- // Check if state tracker already exists
+ // Check if state tracker already exists.
if (mStateTrackers.find(atomId) == mStateTrackers.end()) {
- // Create a new state tracker iff atom is a state atom
+ // Create a new state tracker iff atom is a state atom.
auto it = android::util::AtomsInfo::kStateAtomsFieldOptions.find(atomId);
if (it != android::util::AtomsInfo::kStateAtomsFieldOptions.end()) {
mStateTrackers[atomId] = new StateTracker(atomId, it->second);
@@ -79,8 +76,6 @@ void StateManager::unregisterListener(int32_t atomId, wp<StateListener> listener
bool StateManager::getStateValue(int32_t atomId, const HashableDimensionKey& key,
FieldValue* output) const {
- std::lock_guard<std::mutex> lock(mMutex);
-
auto it = mStateTrackers.find(atomId);
if (it != mStateTrackers.end()) {
return it->second->getStateValue(key, output);
diff --git a/cmds/statsd/src/state/StateManager.h b/cmds/statsd/src/state/StateManager.h
index 272724ceeb08..a6053e6f317e 100644
--- a/cmds/statsd/src/state/StateManager.h
+++ b/cmds/statsd/src/state/StateManager.h
@@ -27,6 +27,10 @@ namespace android {
namespace os {
namespace statsd {
+/**
+ * This class is NOT thread safe.
+ * It should only be used while StatsLogProcessor's lock is held.
+ */
class StateManager : public virtual RefBase {
public:
StateManager(){};
@@ -56,13 +60,10 @@ public:
FieldValue* output) const;
inline int getStateTrackersCount() const {
- std::lock_guard<std::mutex> lock(mMutex);
return mStateTrackers.size();
}
inline int getListenersCount(int32_t atomId) const {
- std::lock_guard<std::mutex> lock(mMutex);
-
auto it = mStateTrackers.find(atomId);
if (it != mStateTrackers.end()) {
return it->second->getListenersCount();
@@ -71,10 +72,10 @@ public:
}
private:
- mutable std::mutex mMutex;
+ mutable std::mutex mMutex;
- // Maps state atom ids to StateTrackers
- std::unordered_map<int32_t, sp<StateTracker>> mStateTrackers;
+ // Maps state atom ids to StateTrackers
+ std::unordered_map<int32_t, sp<StateTracker>> mStateTrackers;
};
} // namespace statsd
diff --git a/cmds/statsd/src/state/StateTracker.h b/cmds/statsd/src/state/StateTracker.h
index e65325a52b98..7453370f25fd 100644
--- a/cmds/statsd/src/state/StateTracker.h
+++ b/cmds/statsd/src/state/StateTracker.h
@@ -15,7 +15,7 @@
*/
#pragma once
-#include <statslog.h>
+#include <atoms_info.h>
#include <utils/RefBase.h>
#include "HashableDimensionKey.h"
#include "logd/LogEvent.h"
diff --git a/cmds/statsd/src/stats_log_util.h b/cmds/statsd/src/stats_log_util.h
index 0a86363a7090..f3e94331a23e 100644
--- a/cmds/statsd/src/stats_log_util.h
+++ b/cmds/statsd/src/stats_log_util.h
@@ -19,9 +19,9 @@
#include <android/util/ProtoOutputStream.h>
#include "FieldValue.h"
#include "HashableDimensionKey.h"
+#include "atoms_info.h"
#include "frameworks/base/cmds/statsd/src/statsd_config.pb.h"
#include "guardrail/StatsdStats.h"
-#include "statslog.h"
namespace android {
namespace os {
diff --git a/cmds/statsd/tests/external/GpuStatsPuller_test.cpp b/cmds/statsd/tests/external/GpuStatsPuller_test.cpp
index e91fb0d4b27c..6abdfa3dbb24 100644
--- a/cmds/statsd/tests/external/GpuStatsPuller_test.cpp
+++ b/cmds/statsd/tests/external/GpuStatsPuller_test.cpp
@@ -24,6 +24,7 @@
#include <log/log.h>
#include "src/external/GpuStatsPuller.h"
+#include "statslog.h"
#ifdef __ANDROID__
diff --git a/cmds/statsd/tests/external/StatsCallbackPuller_test.cpp b/cmds/statsd/tests/external/StatsCallbackPuller_test.cpp
new file mode 100644
index 000000000000..2b0590d11f54
--- /dev/null
+++ b/cmds/statsd/tests/external/StatsCallbackPuller_test.cpp
@@ -0,0 +1,210 @@
+// Copyright (C) 2019 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.
+
+#include "src/external/StatsCallbackPuller.h"
+
+#include <android/os/BnPullAtomCallback.h>
+#include <android/os/IPullAtomResultReceiver.h>
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <stdio.h>
+
+#include <chrono>
+#include <thread>
+#include <vector>
+
+#include "../metrics/metrics_test_helper.h"
+#include "src/stats_log_util.h"
+#include "tests/statsd_test_util.h"
+
+#ifdef __ANDROID__
+
+namespace android {
+namespace os {
+namespace statsd {
+
+using namespace testing;
+using std::make_shared;
+using std::shared_ptr;
+using std::vector;
+using std::this_thread::sleep_for;
+using testing::Contains;
+
+namespace {
+int pullTagId = -12;
+bool pullSuccess;
+vector<int64_t> values;
+int64_t pullDelayNs;
+int64_t pullTimeoutNs;
+int64_t pullCoolDownNs;
+std::thread pullThread;
+
+stats_event* createSimpleEvent(int64_t value) {
+ stats_event* event = stats_event_obtain();
+ stats_event_set_atom_id(event, pullTagId);
+ stats_event_write_int64(event, value);
+ stats_event_build(event);
+ return event;
+}
+
+void executePull(const sp<IPullAtomResultReceiver>& resultReceiver) {
+ // Convert stats_events into StatsEventParcels.
+ std::vector<android::util::StatsEventParcel> parcels;
+ for (int i = 0; i < values.size(); i++) {
+ stats_event* event = createSimpleEvent(values[i]);
+ size_t size;
+ uint8_t* buffer = stats_event_get_buffer(event, &size);
+
+ android::util::StatsEventParcel p;
+ // vector.assign() creates a copy, but this is inevitable unless
+ // stats_event.h/c uses a vector as opposed to a buffer.
+ p.buffer.assign(buffer, buffer + size);
+ parcels.push_back(std::move(p));
+ stats_event_release(event);
+ }
+
+ sleep_for(std::chrono::nanoseconds(pullDelayNs));
+ resultReceiver->pullFinished(pullTagId, pullSuccess, parcels);
+}
+
+class FakePullAtomCallback : public BnPullAtomCallback {
+public:
+ binder::Status onPullAtom(int atomTag,
+ const sp<IPullAtomResultReceiver>& resultReceiver) override {
+ // Force pull to happen in separate thread to simulate binder.
+ pullThread = std::thread(executePull, resultReceiver);
+ return binder::Status::ok();
+ }
+};
+
+class StatsCallbackPullerTest : public ::testing::Test {
+public:
+ StatsCallbackPullerTest() {
+ }
+
+ void SetUp() override {
+ pullSuccess = false;
+ pullDelayNs = 0;
+ values.clear();
+ pullTimeoutNs = 10000000000LL; // 10 seconds.
+ pullCoolDownNs = 1000000000; // 1 second.
+ }
+
+ void TearDown() override {
+ if (pullThread.joinable()) {
+ pullThread.join();
+ }
+ values.clear();
+ }
+};
+} // Anonymous namespace.
+
+TEST_F(StatsCallbackPullerTest, PullSuccess) {
+ sp<FakePullAtomCallback> cb = new FakePullAtomCallback();
+ int64_t value = 43;
+ pullSuccess = true;
+ values.push_back(value);
+
+ StatsCallbackPuller puller(pullTagId, cb, pullTimeoutNs);
+
+ vector<std::shared_ptr<LogEvent>> dataHolder;
+ int64_t startTimeNs = getElapsedRealtimeNs();
+ EXPECT_TRUE(puller.PullInternal(&dataHolder));
+ int64_t endTimeNs = getElapsedRealtimeNs();
+
+ EXPECT_EQ(1, dataHolder.size());
+ EXPECT_EQ(pullTagId, dataHolder[0]->GetTagId());
+ EXPECT_LT(startTimeNs, dataHolder[0]->GetElapsedTimestampNs());
+ EXPECT_GT(endTimeNs, dataHolder[0]->GetElapsedTimestampNs());
+ EXPECT_EQ(1, dataHolder[0]->size());
+ EXPECT_EQ(value, dataHolder[0]->getValues()[0].mValue.int_value);
+}
+
+TEST_F(StatsCallbackPullerTest, PullFail) {
+ sp<FakePullAtomCallback> cb = new FakePullAtomCallback();
+ pullSuccess = false;
+ int64_t value = 1234;
+ values.push_back(value);
+
+ StatsCallbackPuller puller(pullTagId, cb, pullTimeoutNs);
+
+ vector<std::shared_ptr<LogEvent>> dataHolder;
+ EXPECT_FALSE(puller.PullInternal(&dataHolder));
+ EXPECT_EQ(0, dataHolder.size());
+}
+
+TEST_F(StatsCallbackPullerTest, PullTimeout) {
+ sp<FakePullAtomCallback> cb = new FakePullAtomCallback();
+ pullSuccess = true;
+ pullDelayNs = 500000000; // 500ms.
+ pullTimeoutNs = 10000; // 10 microseconds.
+ int64_t value = 4321;
+ values.push_back(value);
+
+ StatsCallbackPuller puller(pullTagId, cb, pullTimeoutNs);
+
+ vector<std::shared_ptr<LogEvent>> dataHolder;
+ int64_t startTimeNs = getElapsedRealtimeNs();
+ // Returns true to let StatsPuller code evaluate the timeout.
+ EXPECT_TRUE(puller.PullInternal(&dataHolder));
+ int64_t endTimeNs = getElapsedRealtimeNs();
+ int64_t actualPullDurationNs = endTimeNs - startTimeNs;
+
+ // Pull should take at least the timeout amount of time, but should stop early because the delay
+ // is bigger.
+ EXPECT_LT(pullTimeoutNs, actualPullDurationNs);
+ EXPECT_GT(pullDelayNs, actualPullDurationNs);
+ EXPECT_EQ(0, dataHolder.size());
+
+ // Let the pull return and make sure that the dataHolder is not modified.
+ pullThread.join();
+ EXPECT_EQ(0, dataHolder.size());
+}
+
+// Register a puller and ensure that the timeout logic works.
+TEST_F(StatsCallbackPullerTest, RegisterAndTimeout) {
+ sp<FakePullAtomCallback> cb = new FakePullAtomCallback();
+ pullSuccess = true;
+ pullDelayNs = 500000000; // 500 ms.
+ pullTimeoutNs = 10000; // 10 microsseconds.
+ int64_t value = 4321;
+ values.push_back(value);
+
+ StatsPullerManager pullerManager;
+ pullerManager.RegisterPullAtomCallback(/*uid=*/-1, pullTagId, pullCoolDownNs, pullTimeoutNs,
+ vector<int32_t>(), cb);
+ vector<std::shared_ptr<LogEvent>> dataHolder;
+ int64_t startTimeNs = getElapsedRealtimeNs();
+ // Returns false, since StatsPuller code will evaluate the timeout.
+ EXPECT_FALSE(pullerManager.Pull(pullTagId, &dataHolder));
+ int64_t endTimeNs = getElapsedRealtimeNs();
+ int64_t actualPullDurationNs = endTimeNs - startTimeNs;
+
+ // Pull should take at least the timeout amount of time, but should stop early because the delay
+ // is bigger.
+ EXPECT_LT(pullTimeoutNs, actualPullDurationNs);
+ EXPECT_GT(pullDelayNs, actualPullDurationNs);
+ EXPECT_EQ(0, dataHolder.size());
+
+ // Let the pull return and make sure that the dataHolder is not modified.
+ pullThread.join();
+ EXPECT_EQ(0, dataHolder.size());
+}
+
+} // namespace statsd
+} // namespace os
+} // namespace android
+#else
+GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
diff --git a/cmds/statsd/tests/external/StatsPuller_test.cpp b/cmds/statsd/tests/external/StatsPuller_test.cpp
index 76e2097a90b8..c40719a17f62 100644
--- a/cmds/statsd/tests/external/StatsPuller_test.cpp
+++ b/cmds/statsd/tests/external/StatsPuller_test.cpp
@@ -35,6 +35,7 @@ using std::vector;
using std::this_thread::sleep_for;
using testing::Contains;
+namespace {
// cooldown time 1sec.
int pullTagId = 10014;
@@ -76,7 +77,9 @@ public:
}
};
-TEST_F(StatsPullerTest, PullSucces) {
+} // Anonymous namespace.
+
+TEST_F(StatsPullerTest, PullSuccess) {
pullData.push_back(createSimpleEvent(1111L, 33));
pullSuccess = true;
diff --git a/cmds/statsd/tests/external/SurfaceflingerStatsPuller_test.cpp b/cmds/statsd/tests/external/SurfaceflingerStatsPuller_test.cpp
index 5c9636fa99cc..5b7a30d4a5aa 100644
--- a/cmds/statsd/tests/external/SurfaceflingerStatsPuller_test.cpp
+++ b/cmds/statsd/tests/external/SurfaceflingerStatsPuller_test.cpp
@@ -18,6 +18,7 @@
#define LOG_TAG "SurfaceflingerStatsPuller_test"
#include "src/external/SurfaceflingerStatsPuller.h"
+#include "statslog.h"
#include <gtest/gtest.h>
#include <log/log.h>
diff --git a/cmds/statsd/tests/external/puller_util_test.cpp b/cmds/statsd/tests/external/puller_util_test.cpp
index 266ea351b5d4..673082834e18 100644
--- a/cmds/statsd/tests/external/puller_util_test.cpp
+++ b/cmds/statsd/tests/external/puller_util_test.cpp
@@ -17,6 +17,7 @@
#include <gtest/gtest.h>
#include <stdio.h>
#include <vector>
+#include "statslog.h"
#include "../metrics/metrics_test_helper.h"
#ifdef __ANDROID__
diff --git a/cmds/uiautomator/library/Android.bp b/cmds/uiautomator/library/Android.bp
index 1173d57e5e3f..3a260639de0f 100644
--- a/cmds/uiautomator/library/Android.bp
+++ b/cmds/uiautomator/library/Android.bp
@@ -22,6 +22,7 @@ droiddoc {
"android.test.runner",
"junit",
"android.test.base",
+ "unsupportedappusage",
],
custom_template: "droiddoc-templates-sdk",
installable: false,
diff --git a/core/java/android/accessibilityservice/AccessibilityGestureEvent.java b/core/java/android/accessibilityservice/AccessibilityGestureEvent.java
index 8b62e2f83cff..d82b151e9ce9 100644
--- a/core/java/android/accessibilityservice/AccessibilityGestureEvent.java
+++ b/core/java/android/accessibilityservice/AccessibilityGestureEvent.java
@@ -17,6 +17,8 @@
package android.accessibilityservice;
+import static android.accessibilityservice.AccessibilityService.GESTURE_DOUBLE_TAP;
+import static android.accessibilityservice.AccessibilityService.GESTURE_DOUBLE_TAP_AND_HOLD;
import static android.accessibilityservice.AccessibilityService.GESTURE_SWIPE_DOWN;
import static android.accessibilityservice.AccessibilityService.GESTURE_SWIPE_DOWN_AND_LEFT;
import static android.accessibilityservice.AccessibilityService.GESTURE_SWIPE_DOWN_AND_RIGHT;
@@ -58,6 +60,8 @@ public final class AccessibilityGestureEvent implements Parcelable {
/** @hide */
@IntDef(prefix = { "GESTURE_" }, value = {
+ GESTURE_DOUBLE_TAP,
+ GESTURE_DOUBLE_TAP_AND_HOLD,
GESTURE_SWIPE_UP,
GESTURE_SWIPE_UP_AND_LEFT,
GESTURE_SWIPE_UP_AND_DOWN,
diff --git a/core/java/android/accessibilityservice/AccessibilityService.java b/core/java/android/accessibilityservice/AccessibilityService.java
index 47fdcdeafce9..c0fee6e9e5e9 100644
--- a/core/java/android/accessibilityservice/AccessibilityService.java
+++ b/core/java/android/accessibilityservice/AccessibilityService.java
@@ -21,8 +21,8 @@ import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.RequiresPermission;
-import android.annotation.UnsupportedAppUsage;
import android.app.Service;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ParceledListSlice;
@@ -300,6 +300,18 @@ public abstract class AccessibilityService extends Service {
public static final int GESTURE_SWIPE_DOWN_AND_RIGHT = 16;
/**
+ * The user has performed a double tap gesture on the touch screen.
+ * @hide
+ */
+ public static final int GESTURE_DOUBLE_TAP = 17;
+
+ /**
+ * The user has performed a double tap and hold gesture on the touch screen.
+ * @hide
+ */
+ public static final int GESTURE_DOUBLE_TAP_AND_HOLD = 18;
+
+ /**
* The {@link Intent} that must be declared as handled by the service.
*/
public static final String SERVICE_INTERFACE =
diff --git a/core/java/android/accessibilityservice/AccessibilityServiceInfo.java b/core/java/android/accessibilityservice/AccessibilityServiceInfo.java
index 7fd01dbf95fb..5e2c1faac156 100644
--- a/core/java/android/accessibilityservice/AccessibilityServiceInfo.java
+++ b/core/java/android/accessibilityservice/AccessibilityServiceInfo.java
@@ -22,9 +22,9 @@ import android.annotation.IntDef;
import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
import android.compat.annotation.ChangeId;
import android.compat.annotation.EnabledAfter;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageManager;
diff --git a/core/java/android/accessibilityservice/AccessibilityShortcutInfo.java b/core/java/android/accessibilityservice/AccessibilityShortcutInfo.java
index f4cadfd8bbc1..d79740b49b3d 100644
--- a/core/java/android/accessibilityservice/AccessibilityShortcutInfo.java
+++ b/core/java/android/accessibilityservice/AccessibilityShortcutInfo.java
@@ -141,6 +141,16 @@ public final class AccessibilityShortcutInfo {
}
/**
+ * The {@link ComponentName} of the accessibility shortcut target.
+ *
+ * @return The component name
+ */
+ @NonNull
+ public ComponentName getComponentName() {
+ return mComponentName;
+ }
+
+ /**
* The localized summary of the accessibility shortcut target.
*
* @return The localized summary if available, and {@code null} if a summary
diff --git a/core/java/android/accounts/Account.java b/core/java/android/accounts/Account.java
index c822d20445ec..9a18880a353b 100644
--- a/core/java/android/accounts/Account.java
+++ b/core/java/android/accounts/Account.java
@@ -18,7 +18,7 @@ package android.accounts;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/accounts/AccountAndUser.java b/core/java/android/accounts/AccountAndUser.java
index b0d53438d97c..fd6739410ce2 100644
--- a/core/java/android/accounts/AccountAndUser.java
+++ b/core/java/android/accounts/AccountAndUser.java
@@ -16,7 +16,7 @@
package android.accounts;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/**
* Used to store the Account and the UserId this account is associated with.
diff --git a/core/java/android/accounts/AccountAuthenticatorResponse.java b/core/java/android/accounts/AccountAuthenticatorResponse.java
index bb2e327a9be8..a2a57990297c 100644
--- a/core/java/android/accounts/AccountAuthenticatorResponse.java
+++ b/core/java/android/accounts/AccountAuthenticatorResponse.java
@@ -16,10 +16,10 @@
package android.accounts;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Bundle;
-import android.os.Parcelable;
import android.os.Parcel;
+import android.os.Parcelable;
import android.os.RemoteException;
import android.util.Log;
diff --git a/core/java/android/accounts/AccountManager.java b/core/java/android/accounts/AccountManager.java
index f4e465ab3adb..8fe2f12a1023 100644
--- a/core/java/android/accounts/AccountManager.java
+++ b/core/java/android/accounts/AccountManager.java
@@ -25,8 +25,8 @@ import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.Size;
import android.annotation.SystemApi;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
import android.app.Activity;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
@@ -1943,35 +1943,6 @@ public class AccountManager {
}
/**
- * @hide
- * Removes the shared account.
- * @param account the account to remove
- * @param user the user to remove the account from
- * @return
- */
- public boolean removeSharedAccount(final Account account, UserHandle user) {
- try {
- boolean val = mService.removeSharedAccountAsUser(account, user.getIdentifier());
- return val;
- } catch (RemoteException re) {
- throw re.rethrowFromSystemServer();
- }
- }
-
- /**
- * @hide
- * @param user
- * @return
- */
- public Account[] getSharedAccounts(UserHandle user) {
- try {
- return mService.getSharedAccountsAsUser(user.getIdentifier());
- } catch (RemoteException re) {
- throw re.rethrowFromSystemServer();
- }
- }
-
- /**
* Confirms that the user knows the password for an account to make extra
* sure they are the owner of the account. The user-entered password can
* be supplied directly, otherwise the authenticator for this account type
diff --git a/core/java/android/accounts/AuthenticatorDescription.java b/core/java/android/accounts/AuthenticatorDescription.java
index 555639445e85..b7bf11d4d5b6 100644
--- a/core/java/android/accounts/AuthenticatorDescription.java
+++ b/core/java/android/accounts/AuthenticatorDescription.java
@@ -16,10 +16,10 @@
package android.accounts;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
-import android.os.Parcelable;
import android.os.Parcel;
+import android.os.Parcelable;
/**
* A {@link Parcelable} value type that contains information about an account authenticator.
diff --git a/core/java/android/accounts/IAccountManager.aidl b/core/java/android/accounts/IAccountManager.aidl
index 4cf0a2089fe5..012713891d11 100644
--- a/core/java/android/accounts/IAccountManager.aidl
+++ b/core/java/android/accounts/IAccountManager.aidl
@@ -80,14 +80,11 @@ interface IAccountManager {
String authTokenType);
/* Shared accounts */
- Account[] getSharedAccountsAsUser(int userId);
- boolean removeSharedAccountAsUser(in Account account, int userId);
void addSharedAccountsFromParentUser(int parentUserId, int userId, String opPackageName);
/* Account renaming. */
void renameAccount(in IAccountManagerResponse response, in Account accountToRename, String newName);
String getPreviousName(in Account account);
- boolean renameSharedAccountAsUser(in Account accountToRename, String newName, int userId);
/* Add account in two steps. */
void startAddAccountSession(in IAccountManagerResponse response, String accountType,
diff --git a/core/java/android/animation/Animator.java b/core/java/android/animation/Animator.java
index 17d54d2455fe..3cdd691fd5dd 100644
--- a/core/java/android/animation/Animator.java
+++ b/core/java/android/animation/Animator.java
@@ -17,7 +17,7 @@
package android.animation;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo.Config;
import android.content.res.ConstantState;
diff --git a/core/java/android/animation/ArgbEvaluator.java b/core/java/android/animation/ArgbEvaluator.java
index 5b69d18a8386..9519ddde86f4 100644
--- a/core/java/android/animation/ArgbEvaluator.java
+++ b/core/java/android/animation/ArgbEvaluator.java
@@ -16,7 +16,7 @@
package android.animation;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/**
* This evaluator can be used to perform type interpolation between integer
diff --git a/core/java/android/animation/LayoutTransition.java b/core/java/android/animation/LayoutTransition.java
index c7537102d40c..21f0b6b2ae62 100644
--- a/core/java/android/animation/LayoutTransition.java
+++ b/core/java/android/animation/LayoutTransition.java
@@ -16,7 +16,7 @@
package android.animation;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
diff --git a/core/java/android/animation/ValueAnimator.java b/core/java/android/animation/ValueAnimator.java
index 764e5992fbd9..ca37e9b107a0 100644
--- a/core/java/android/animation/ValueAnimator.java
+++ b/core/java/android/animation/ValueAnimator.java
@@ -19,7 +19,7 @@ package android.animation;
import android.annotation.CallSuper;
import android.annotation.IntDef;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.Looper;
import android.os.Trace;
diff --git a/core/java/android/annotation/Hide.java b/core/java/android/annotation/Hide.java
new file mode 100644
index 000000000000..c8e5a4a97ae7
--- /dev/null
+++ b/core/java/android/annotation/Hide.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2019 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.annotation;
+
+import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
+import static java.lang.annotation.ElementType.CONSTRUCTOR;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.PACKAGE;
+import static java.lang.annotation.ElementType.TYPE;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Indicates that an API is hidden by default, in a similar fashion to the
+ * <pre>@hide</pre> javadoc tag.
+ *
+ * <p>Note that, in order for this to work, metalava has to be invoked with
+ * the flag {@code --hide-annotation android.annotation.Hide}.
+ * @hide
+ */
+@Target({TYPE, FIELD, METHOD, CONSTRUCTOR, ANNOTATION_TYPE, PACKAGE})
+@Retention(RetentionPolicy.CLASS)
+public @interface Hide {
+}
diff --git a/core/java/android/annotation/OWNERS b/core/java/android/annotation/OWNERS
index e07028bdb449..8aceb565315c 100644
--- a/core/java/android/annotation/OWNERS
+++ b/core/java/android/annotation/OWNERS
@@ -1,2 +1,3 @@
tnorbye@google.com
+aurimas@google.com
per-file UnsupportedAppUsage.java = mathewi@google.com, dbrazdil@google.com, atrost@google.com, andreionea@google.com
diff --git a/core/java/android/annotation/SystemApi.java b/core/java/android/annotation/SystemApi.java
index e96ff01d0850..2cb93e4f8cea 100644
--- a/core/java/android/annotation/SystemApi.java
+++ b/core/java/android/annotation/SystemApi.java
@@ -41,4 +41,49 @@ import java.lang.annotation.Target;
@Target({TYPE, FIELD, METHOD, CONSTRUCTOR, ANNOTATION_TYPE, PACKAGE})
@Retention(RetentionPolicy.RUNTIME)
public @interface SystemApi {
+ enum Client {
+ /**
+ * Specifies that the intended clients of a SystemApi are privileged apps.
+ * This is the default value for {@link #client}. This implies
+ * MODULE_APPS and MODULE_LIBRARIES as well, which means that APIs will also
+ * be available to module apps and jars.
+ */
+ PRIVILEGED_APPS,
+
+ /**
+ * Specifies that the intended clients of a SystemApi are modules implemented
+ * as apps, like the NetworkStack app. This implies MODULE_LIBRARIES as well,
+ * which means that APIs will also be available to module jars.
+ */
+ MODULE_APPS,
+
+ /**
+ * Specifies that the intended clients of a SystemApi are modules implemented
+ * as libraries, like the conscrypt.jar in the conscrypt APEX.
+ */
+ MODULE_LIBRARIES
+ }
+
+ enum Process {
+ /**
+ * Specifies that the SystemAPI is available in every Java processes.
+ * This is the default value for {@link #process}.
+ */
+ ALL,
+
+ /**
+ * Specifies that the SystemAPI is available only in the system server process.
+ */
+ SYSTEM_SERVER
+ }
+
+ /**
+ * The intended client of this SystemAPI.
+ */
+ Client client() default android.annotation.SystemApi.Client.PRIVILEGED_APPS;
+
+ /**
+ * The process(es) that this SystemAPI is available
+ */
+ Process process() default android.annotation.SystemApi.Process.ALL;
}
diff --git a/core/java/android/app/ActionBar.java b/core/java/android/app/ActionBar.java
index e57327991a82..504364c8c1d9 100644
--- a/core/java/android/app/ActionBar.java
+++ b/core/java/android/app/ActionBar.java
@@ -22,7 +22,7 @@ import android.annotation.LayoutRes;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.StringRes;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index 577272e38707..ff581c059935 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -33,10 +33,10 @@ import android.annotation.RequiresPermission;
import android.annotation.StyleRes;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.VoiceInteractor.Request;
import android.app.admin.DevicePolicyManager;
import android.app.assist.AssistContent;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentCallbacks2;
import android.content.ComponentName;
import android.content.ContentResolver;
@@ -766,9 +766,19 @@ public class Activity extends ContextThemeWrapper
private static final String REQUEST_PERMISSIONS_WHO_PREFIX = "@android:requestPermissions:";
private static final String AUTO_FILL_AUTH_WHO_PREFIX = "@android:autoFillAuth:";
-
private static final String KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME = "com.android.systemui";
+ private static final int LOG_AM_ON_CREATE_CALLED = 30057;
+ private static final int LOG_AM_ON_START_CALLED = 30059;
+ private static final int LOG_AM_ON_RESUME_CALLED = 30022;
+ private static final int LOG_AM_ON_PAUSE_CALLED = 30021;
+ private static final int LOG_AM_ON_STOP_CALLED = 30049;
+ private static final int LOG_AM_ON_RESTART_CALLED = 30058;
+ private static final int LOG_AM_ON_DESTROY_CALLED = 30060;
+ private static final int LOG_AM_ON_ACTIVITY_RESULT_CALLED = 30062;
+ private static final int LOG_AM_ON_TOP_RESUMED_GAINED_CALLED = 30064;
+ private static final int LOG_AM_ON_TOP_RESUMED_LOST_CALLED = 30065;
+
private static class ManagedDialog {
Dialog mDialog;
Bundle mArgs;
@@ -2439,8 +2449,11 @@ public class Activity extends ContextThemeWrapper
* {@link #onProvideKeyboardShortcuts} to retrieve the shortcuts for the foreground activity.
*/
public final void requestShowKeyboardShortcuts() {
+ final ComponentName sysuiComponent = ComponentName.unflattenFromString(
+ getResources().getString(
+ com.android.internal.R.string.config_systemUIServiceComponent));
Intent intent = new Intent(Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS);
- intent.setPackage(KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME);
+ intent.setPackage(sysuiComponent.getPackageName());
sendBroadcastAsUser(intent, Process.myUserHandle());
}
@@ -2448,8 +2461,11 @@ public class Activity extends ContextThemeWrapper
* Dismiss the Keyboard Shortcuts screen.
*/
public final void dismissKeyboardShortcutsHelper() {
+ final ComponentName sysuiComponent = ComponentName.unflattenFromString(
+ getResources().getString(
+ com.android.internal.R.string.config_systemUIServiceComponent));
Intent intent = new Intent(Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS);
- intent.setPackage(KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME);
+ intent.setPackage(sysuiComponent.getPackageName());
sendBroadcastAsUser(intent, Process.myUserHandle());
}
diff --git a/core/java/android/app/ActivityGroup.java b/core/java/android/app/ActivityGroup.java
index d4aa01b8f43e..cb06eea2059e 100644
--- a/core/java/android/app/ActivityGroup.java
+++ b/core/java/android/app/ActivityGroup.java
@@ -16,7 +16,7 @@
package android.app;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Intent;
import android.os.Bundle;
diff --git a/core/java/android/app/ActivityManager.java b/core/java/android/app/ActivityManager.java
index 590b3db5fe84..68bdfae218ae 100644
--- a/core/java/android/app/ActivityManager.java
+++ b/core/java/android/app/ActivityManager.java
@@ -28,7 +28,7 @@ import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
@@ -1120,8 +1120,8 @@ public class ActivityManager {
}
/**
- * Copies this the values from another TaskDescription, but preserves the hidden fields
- * if they weren't set on {@code other}
+ * Copies values from another TaskDescription, but preserves the hidden fields if they
+ * weren't set on {@code other}. Public fields will be overwritten anyway.
* @hide
*/
public void copyFromPreserveHiddenFields(TaskDescription other) {
@@ -1130,6 +1130,7 @@ public class ActivityManager {
mIconRes = other.mIconRes;
mIconFilename = other.mIconFilename;
mColorPrimary = other.mColorPrimary;
+
if (other.mColorBackground != 0) {
mColorBackground = other.mColorBackground;
}
@@ -1139,12 +1140,20 @@ public class ActivityManager {
if (other.mNavigationBarColor != 0) {
mNavigationBarColor = other.mNavigationBarColor;
}
+
mEnsureStatusBarContrastWhenTransparent = other.mEnsureStatusBarContrastWhenTransparent;
mEnsureNavigationBarContrastWhenTransparent =
other.mEnsureNavigationBarContrastWhenTransparent;
- mResizeMode = other.mResizeMode;
- mMinWidth = other.mMinWidth;
- mMinHeight = other.mMinHeight;
+
+ if (other.mResizeMode != RESIZE_MODE_RESIZEABLE) {
+ mResizeMode = other.mResizeMode;
+ }
+ if (other.mMinWidth != -1) {
+ mMinWidth = other.mMinWidth;
+ }
+ if (other.mMinHeight != -1) {
+ mMinHeight = other.mMinHeight;
+ }
}
private TaskDescription(Parcel source) {
@@ -2097,6 +2106,113 @@ public class ActivityManager {
return new TaskSnapshot[size];
}
};
+
+ /** Builder for a {@link TaskSnapshot} object */
+ public static final class Builder {
+ private long mId;
+ private ComponentName mTopActivity;
+ private GraphicBuffer mSnapshot;
+ private ColorSpace mColorSpace;
+ private int mOrientation;
+ private Rect mContentInsets;
+ private boolean mReducedResolution;
+ private float mScaleFraction;
+ private boolean mIsRealSnapshot;
+ private int mWindowingMode;
+ private int mSystemUiVisibility;
+ private boolean mIsTranslucent;
+ private int mPixelFormat;
+
+ public Builder setId(long id) {
+ mId = id;
+ return this;
+ }
+
+ public Builder setTopActivityComponent(ComponentName name) {
+ mTopActivity = name;
+ return this;
+ }
+
+ public Builder setSnapshot(GraphicBuffer buffer) {
+ mSnapshot = buffer;
+ return this;
+ }
+
+ public Builder setColorSpace(ColorSpace colorSpace) {
+ mColorSpace = colorSpace;
+ return this;
+ }
+
+ public Builder setOrientation(int orientation) {
+ mOrientation = orientation;
+ return this;
+ }
+
+ public Builder setContentInsets(Rect contentInsets) {
+ mContentInsets = contentInsets;
+ return this;
+ }
+
+ public Builder setReducedResolution(boolean reducedResolution) {
+ mReducedResolution = reducedResolution;
+ return this;
+ }
+
+ public float getScaleFraction() {
+ return mScaleFraction;
+ }
+
+ public Builder setScaleFraction(float scaleFraction) {
+ mScaleFraction = scaleFraction;
+ return this;
+ }
+
+ public Builder setIsRealSnapshot(boolean realSnapshot) {
+ mIsRealSnapshot = realSnapshot;
+ return this;
+ }
+
+ public Builder setWindowingMode(int windowingMode) {
+ mWindowingMode = windowingMode;
+ return this;
+ }
+
+ public Builder setSystemUiVisibility(int systemUiVisibility) {
+ mSystemUiVisibility = systemUiVisibility;
+ return this;
+ }
+
+ public Builder setIsTranslucent(boolean isTranslucent) {
+ mIsTranslucent = isTranslucent;
+ return this;
+ }
+
+ public int getPixelFormat() {
+ return mPixelFormat;
+ }
+
+ public Builder setPixelFormat(int pixelFormat) {
+ mPixelFormat = pixelFormat;
+ return this;
+ }
+
+ public TaskSnapshot build() {
+ return new TaskSnapshot(
+ mId,
+ mTopActivity,
+ mSnapshot,
+ mColorSpace,
+ mOrientation,
+ mContentInsets,
+ mReducedResolution,
+ mScaleFraction,
+ mIsRealSnapshot,
+ mWindowingMode,
+ mSystemUiVisibility,
+ mIsTranslucent);
+
+ }
+ }
}
/** @hide */
@@ -4417,4 +4533,18 @@ public class ActivityManager {
}
}
}
+
+ /**
+ * Get packages of bugreport-whitelisted apps to handle a bug report.
+ *
+ * @return packages of bugreport-whitelisted apps to handle a bug report.
+ * @hide
+ */
+ public List<String> getBugreportWhitelistedPackages() {
+ try {
+ return getService().getBugreportWhitelistedPackages();
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
}
diff --git a/core/java/android/app/ActivityManagerNative.java b/core/java/android/app/ActivityManagerNative.java
index 607ef185ae60..b9eb95739aa1 100644
--- a/core/java/android/app/ActivityManagerNative.java
+++ b/core/java/android/app/ActivityManagerNative.java
@@ -15,7 +15,7 @@
*/
package android.app;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Intent;
import android.os.IBinder;
diff --git a/core/java/android/app/ActivityOptions.java b/core/java/android/app/ActivityOptions.java
index f91453ea0811..4aacf4879c43 100644
--- a/core/java/android/app/ActivityOptions.java
+++ b/core/java/android/app/ActivityOptions.java
@@ -25,7 +25,7 @@ import static android.view.Display.INVALID_DISPLAY;
import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
diff --git a/core/java/android/app/ActivityTaskManager.java b/core/java/android/app/ActivityTaskManager.java
index ac8c9f466f33..122004cdcf1b 100644
--- a/core/java/android/app/ActivityTaskManager.java
+++ b/core/java/android/app/ActivityTaskManager.java
@@ -19,7 +19,7 @@ package android.app;
import android.annotation.RequiresPermission;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index 49a8e2f3f816..be145567fbcd 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -32,7 +32,6 @@ import static com.android.internal.annotations.VisibleForTesting.Visibility.PACK
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
import android.app.assist.AssistContent;
import android.app.assist.AssistStructure;
import android.app.backup.BackupAgent;
@@ -46,6 +45,7 @@ import android.app.servertransaction.PendingTransactionActions;
import android.app.servertransaction.PendingTransactionActions.StopInfo;
import android.app.servertransaction.TransactionExecutor;
import android.app.servertransaction.TransactionExecutorHelper;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.AutofillOptions;
import android.content.BroadcastReceiver;
import android.content.ComponentCallbacks2;
@@ -112,6 +112,7 @@ import android.os.ServiceManager;
import android.os.StrictMode;
import android.os.SystemClock;
import android.os.SystemProperties;
+import android.os.TelephonyServiceManager;
import android.os.Trace;
import android.os.UserHandle;
import android.permission.IPermissionManager;
@@ -128,6 +129,7 @@ import android.security.net.config.NetworkSecurityConfigProvider;
import android.system.ErrnoException;
import android.system.OsConstants;
import android.system.StructStat;
+import android.telephony.TelephonyFrameworkInitializer;
import android.util.AndroidRuntimeException;
import android.util.ArrayMap;
import android.util.DisplayMetrics;
@@ -3415,7 +3417,7 @@ public final class ActivityThread extends ClientTransactionHandler {
private ContextImpl createBaseContextForActivity(ActivityClientRecord r) {
final int displayId;
try {
- displayId = ActivityTaskManager.getService().getActivityDisplayId(r.token);
+ displayId = ActivityTaskManager.getService().getDisplayId(r.token);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -4405,7 +4407,9 @@ public final class ActivityThread extends ClientTransactionHandler {
r.newConfig = null;
}
if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward=" + isForward);
- WindowManager.LayoutParams l = r.window.getAttributes();
+ ViewRootImpl impl = r.window.getDecorView().getViewRootImpl();
+ WindowManager.LayoutParams l = impl != null
+ ? impl.mWindowAttributes : r.window.getAttributes();
if ((l.softInputMode
& WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
!= forwardBit) {
@@ -7395,6 +7399,24 @@ public final class ActivityThread extends ClientTransactionHandler {
super.remove(path);
}
}
+
+ @Override
+ public void rename(String oldPath, String newPath) throws ErrnoException {
+ try {
+ super.rename(oldPath, newPath);
+ } catch (ErrnoException e) {
+ if (e.errno == OsConstants.EXDEV && oldPath.startsWith("/storage/")) {
+ Log.v(TAG, "Recovering failed rename " + oldPath + " to " + newPath);
+ try {
+ Files.move(new File(oldPath).toPath(), new File(newPath).toPath());
+ } catch (IOException e2) {
+ throw e;
+ }
+ } else {
+ throw e;
+ }
+ }
+ }
}
public static void main(String[] args) {
@@ -7414,6 +7436,9 @@ public final class ActivityThread extends ClientTransactionHandler {
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
+ // Call per-process mainline module initialization.
+ initializeMainlineModules();
+
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
@@ -7448,6 +7473,14 @@ public final class ActivityThread extends ClientTransactionHandler {
throw new RuntimeException("Main thread loop unexpectedly exited");
}
+ /**
+ * Call various initializer APIs in mainline modules that need to be called when each process
+ * starts.
+ */
+ public static void initializeMainlineModules() {
+ TelephonyFrameworkInitializer.setTelephonyServiceManager(new TelephonyServiceManager());
+ }
+
private void purgePendingResources() {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "purgePendingResources");
nPurgePendingResources();
diff --git a/core/java/android/app/AlarmManager.java b/core/java/android/app/AlarmManager.java
index d8ddf218c6d4..c03413c80aa0 100644
--- a/core/java/android/app/AlarmManager.java
+++ b/core/java/android/app/AlarmManager.java
@@ -21,7 +21,7 @@ import android.annotation.RequiresPermission;
import android.annotation.SdkConstant;
import android.annotation.SystemApi;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
diff --git a/core/java/android/app/AlertDialog.java b/core/java/android/app/AlertDialog.java
index bfc216a24c1b..4c347373d642 100644
--- a/core/java/android/app/AlertDialog.java
+++ b/core/java/android/app/AlertDialog.java
@@ -21,7 +21,7 @@ import android.annotation.AttrRes;
import android.annotation.DrawableRes;
import android.annotation.StringRes;
import android.annotation.StyleRes;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.ResourceId;
diff --git a/core/java/android/app/AppGlobals.java b/core/java/android/app/AppGlobals.java
index 8312327a8c1d..81e1565ee86c 100644
--- a/core/java/android/app/AppGlobals.java
+++ b/core/java/android/app/AppGlobals.java
@@ -16,7 +16,7 @@
package android.app;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.IPackageManager;
import android.permission.IPermissionManager;
diff --git a/core/java/android/app/AppOpsManager.java b/core/java/android/app/AppOpsManager.java
index 5032f776f8f0..4ce91a6b98f1 100644
--- a/core/java/android/app/AppOpsManager.java
+++ b/core/java/android/app/AppOpsManager.java
@@ -26,8 +26,8 @@ import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.usage.UsageStatsManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
@@ -2008,7 +2008,7 @@ public class AppOpsManager {
false, // WRITE_MEDIA_VIDEO
false, // READ_MEDIA_IMAGES
false, // WRITE_MEDIA_IMAGES
- false, // LEGACY_STORAGE
+ true, // LEGACY_STORAGE
false, // ACCESS_ACCESSIBILITY
false, // READ_DEVICE_IDENTIFIERS
false, // ACCESS_MEDIA_LOCATION
diff --git a/core/java/android/app/Application.java b/core/java/android/app/Application.java
index e12942f248d4..941467fad736 100644
--- a/core/java/android/app/Application.java
+++ b/core/java/android/app/Application.java
@@ -19,7 +19,7 @@ package android.app;
import android.annotation.CallSuper;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentCallbacks;
import android.content.ComponentCallbacks2;
import android.content.Context;
diff --git a/core/java/android/app/ApplicationLoaders.java b/core/java/android/app/ApplicationLoaders.java
index 2e59b903f06d..bac432e42318 100644
--- a/core/java/android/app/ApplicationLoaders.java
+++ b/core/java/android/app/ApplicationLoaders.java
@@ -16,7 +16,7 @@
package android.app;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.SharedLibraryInfo;
import android.os.Build;
import android.os.GraphicsEnvironment;
diff --git a/core/java/android/app/ApplicationPackageManager.java b/core/java/android/app/ApplicationPackageManager.java
index 034826a8d5fa..7f26565d760a 100644
--- a/core/java/android/app/ApplicationPackageManager.java
+++ b/core/java/android/app/ApplicationPackageManager.java
@@ -20,9 +20,9 @@ import android.annotation.DrawableRes;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.StringRes;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.UserIdInt;
import android.annotation.XmlRes;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
diff --git a/core/java/android/app/ContentProviderHolder.java b/core/java/android/app/ContentProviderHolder.java
index 004dca1a708f..3d745831ce1c 100644
--- a/core/java/android/app/ContentProviderHolder.java
+++ b/core/java/android/app/ContentProviderHolder.java
@@ -16,7 +16,7 @@
package android.app;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentProviderNative;
import android.content.IContentProvider;
import android.content.pm.ProviderInfo;
diff --git a/core/java/android/app/ContextImpl.java b/core/java/android/app/ContextImpl.java
index 46f88d5c81e4..bd87fcd2565e 100644
--- a/core/java/android/app/ContextImpl.java
+++ b/core/java/android/app/ContextImpl.java
@@ -20,7 +20,7 @@ import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.AutofillOptions;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
@@ -99,6 +99,7 @@ import java.io.InputStream;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.nio.ByteOrder;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Objects;
import java.util.concurrent.Executor;
@@ -251,6 +252,8 @@ class ContextImpl extends Context {
@GuardedBy("mSync")
private File mFilesDir;
@GuardedBy("mSync")
+ private File mCratesDir;
+ @GuardedBy("mSync")
private File mNoBackupFilesDir;
@GuardedBy("mSync")
private File mCacheDir;
@@ -702,6 +705,24 @@ class ContextImpl extends Context {
}
@Override
+ public File getCrateDir(@NonNull String crateId) {
+ Preconditions.checkArgument(FileUtils.isValidExtFilename(crateId), "invalidated crateId");
+ final Path cratesRootPath = getDataDir().toPath().resolve("crates");
+ final Path absoluteNormalizedCratePath = cratesRootPath.resolve(crateId)
+ .toAbsolutePath().normalize();
+
+ synchronized (mSync) {
+ if (mCratesDir == null) {
+ mCratesDir = cratesRootPath.toFile();
+ }
+ ensurePrivateDirExists(mCratesDir);
+ }
+
+ File cratedDir = absoluteNormalizedCratePath.toFile();
+ return ensurePrivateDirExists(cratedDir);
+ }
+
+ @Override
public File getNoBackupFilesDir() {
synchronized (mSync) {
if (mNoBackupFilesDir == null) {
diff --git a/core/java/android/app/DatePickerDialog.java b/core/java/android/app/DatePickerDialog.java
index 9d82ffa838ca..195c3e1c296a 100644
--- a/core/java/android/app/DatePickerDialog.java
+++ b/core/java/android/app/DatePickerDialog.java
@@ -19,7 +19,7 @@ package android.app;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.StyleRes;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
diff --git a/core/java/android/app/Dialog.java b/core/java/android/app/Dialog.java
index 39f1e957cbfb..5e05506eb416 100644
--- a/core/java/android/app/Dialog.java
+++ b/core/java/android/app/Dialog.java
@@ -24,7 +24,7 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.StringRes;
import android.annotation.StyleRes;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
diff --git a/core/java/android/app/DialogFragment.java b/core/java/android/app/DialogFragment.java
index bfc15c221702..e4c84d7e7997 100644
--- a/core/java/android/app/DialogFragment.java
+++ b/core/java/android/app/DialogFragment.java
@@ -16,7 +16,7 @@
package android.app;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
diff --git a/core/java/android/app/DownloadManager.java b/core/java/android/app/DownloadManager.java
index 80c9ba2a9c48..49c389a0c4a7 100644
--- a/core/java/android/app/DownloadManager.java
+++ b/core/java/android/app/DownloadManager.java
@@ -22,7 +22,7 @@ import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.ContentUris;
@@ -1314,8 +1314,8 @@ public class DownloadManager {
// TODO: DownloadProvider.update() should take care of updating corresponding
// MediaProvider entries.
- MediaStore.scanFile(context, before);
- MediaStore.scanFile(context, after);
+ MediaStore.scanFile(mResolver, before);
+ MediaStore.scanFile(mResolver, after);
final ContentValues values = new ContentValues();
values.put(Downloads.Impl.COLUMN_TITLE, displayName);
diff --git a/core/java/android/app/Fragment.java b/core/java/android/app/Fragment.java
index 4f121aa35f7c..c6a0de458df0 100644
--- a/core/java/android/app/Fragment.java
+++ b/core/java/android/app/Fragment.java
@@ -21,7 +21,7 @@ import android.annotation.CallSuper;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.StringRes;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentCallbacks2;
import android.content.Context;
import android.content.Intent;
diff --git a/core/java/android/app/FragmentController.java b/core/java/android/app/FragmentController.java
index 9316be7a7968..f021f7690283 100644
--- a/core/java/android/app/FragmentController.java
+++ b/core/java/android/app/FragmentController.java
@@ -17,7 +17,7 @@
package android.app;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
diff --git a/core/java/android/app/FragmentHostCallback.java b/core/java/android/app/FragmentHostCallback.java
index 26b4a11f4c10..9e887b88c407 100644
--- a/core/java/android/app/FragmentHostCallback.java
+++ b/core/java/android/app/FragmentHostCallback.java
@@ -18,7 +18,7 @@ package android.app;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
diff --git a/core/java/android/app/FragmentManager.java b/core/java/android/app/FragmentManager.java
index 68daf44b19a5..904c4735e0ff 100644
--- a/core/java/android/app/FragmentManager.java
+++ b/core/java/android/app/FragmentManager.java
@@ -22,7 +22,7 @@ import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.res.Configuration;
diff --git a/core/java/android/app/IActivityManager.aidl b/core/java/android/app/IActivityManager.aidl
index aa8a3023a40f..112bd303a8b3 100644
--- a/core/java/android/app/IActivityManager.aidl
+++ b/core/java/android/app/IActivityManager.aidl
@@ -388,6 +388,7 @@ interface IActivityManager {
void requestFullBugReport();
void requestRemoteBugReport();
boolean launchBugReportHandlerApp();
+ List<String> getBugreportWhitelistedPackages();
@UnsupportedAppUsage
Intent getIntentForIntentSender(in IIntentSender sender);
diff --git a/core/java/android/app/IActivityTaskManager.aidl b/core/java/android/app/IActivityTaskManager.aidl
index 37136a110d38..e2b1b8664d75 100644
--- a/core/java/android/app/IActivityTaskManager.aidl
+++ b/core/java/android/app/IActivityTaskManager.aidl
@@ -164,7 +164,7 @@ interface IActivityTaskManager {
boolean convertToTranslucent(in IBinder token, in Bundle options);
void notifyActivityDrawn(in IBinder token);
void reportActivityFullyDrawn(in IBinder token, boolean restoredFromBundle);
- int getActivityDisplayId(in IBinder activityToken);
+ int getDisplayId(in IBinder activityToken);
boolean isImmersive(in IBinder token);
void setImmersive(in IBinder token, boolean immersive);
boolean isTopActivityImmersive();
@@ -405,6 +405,14 @@ interface IActivityTaskManager {
void setDisablePreviewScreenshots(IBinder token, boolean disable);
/**
+ * It should only be called from home activity to remove its outdated snapshot. The home
+ * snapshot is used to speed up entering home from screen off. If the content of home activity
+ * is significantly different from before taking the snapshot, then the home activity can use
+ * this method to avoid inconsistent transition.
+ */
+ void invalidateHomeTaskSnapshot(IBinder homeToken);
+
+ /**
* Return the user id of last resumed activity.
*/
int getLastResumedActivityUserId();
diff --git a/core/java/android/app/IBackupAgent.aidl b/core/java/android/app/IBackupAgent.aidl
index d3d7c68d0992..254657e26f3a 100644
--- a/core/java/android/app/IBackupAgent.aidl
+++ b/core/java/android/app/IBackupAgent.aidl
@@ -84,6 +84,19 @@ oneway interface IBackupAgent {
long appVersionCode, in ParcelFileDescriptor newState,
int token, IBackupManager callbackBinder);
+ /**
+ * Restore an entire data snapshot to the application and pass the list of excluded keys to the
+ * backup agent.
+ *
+ * @param excludedKeys List of keys to be excluded from the restore. It will be passed to the
+ * backup agent to make it aware of what data has been removed (in case it has any
+ * application-level implications) as well as the data that should be removed by the
+ * agent itself.
+ */
+ void doRestoreWithExcludedKeys(in ParcelFileDescriptor data,
+ long appVersionCode, in ParcelFileDescriptor newState,
+ int token, IBackupManager callbackBinder, in List<String> excludedKeys);
+
/**
* Perform a "full" backup to the given file descriptor. The output file is presumed
* to be a socket or other non-seekable, write-only data sink. When this method is
diff --git a/core/java/android/app/IInstantAppResolver.aidl b/core/java/android/app/IInstantAppResolver.aidl
index 7318762cfc63..8618fbb3bada 100644
--- a/core/java/android/app/IInstantAppResolver.aidl
+++ b/core/java/android/app/IInstantAppResolver.aidl
@@ -16,15 +16,13 @@
package android.app;
-import android.content.Intent;
+import android.content.pm.InstantAppRequestInfo;
import android.os.IRemoteCallback;
/** @hide */
oneway interface IInstantAppResolver {
- void getInstantAppResolveInfoList(in Intent sanitizedIntent, in int[] hostDigestPrefix,
- int userId, String token, int sequence, IRemoteCallback callback);
-
- void getInstantAppIntentFilterList(in Intent sanitizedIntent, in int[] hostDigestPrefix,
- int userId, String token, IRemoteCallback callback);
+ void getInstantAppResolveInfoList(in InstantAppRequestInfo request, int sequence,
+ IRemoteCallback callback);
+ void getInstantAppIntentFilterList(in InstantAppRequestInfo request, IRemoteCallback callback);
}
diff --git a/core/java/android/app/InstantAppResolverService.java b/core/java/android/app/InstantAppResolverService.java
index a7be5421adb2..a413c606b76f 100644
--- a/core/java/android/app/InstantAppResolverService.java
+++ b/core/java/android/app/InstantAppResolverService.java
@@ -21,6 +21,7 @@ import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.content.Context;
import android.content.Intent;
+import android.content.pm.InstantAppRequestInfo;
import android.content.pm.InstantAppResolveInfo;
import android.os.Build;
import android.os.Bundle;
@@ -59,8 +60,9 @@ public abstract class InstantAppResolverService extends Service {
* Called to retrieve resolve info for instant applications immediately.
*
* @param digestPrefix The hash prefix of the instant app's domain.
- * @deprecated Should implement {@link #onGetInstantAppResolveInfo(Intent, int[], UserHandle,
- * String, InstantAppResolutionCallback)}.
+ *
+ * @deprecated Should implement {@link #onGetInstantAppResolveInfo(InstantAppRequestInfo,
+ * InstantAppResolutionCallback)}
*/
@Deprecated
public void onGetInstantAppResolveInfo(@Nullable int[] digestPrefix, @NonNull String token,
@@ -73,8 +75,9 @@ public abstract class InstantAppResolverService extends Service {
* sources.
*
* @param digestPrefix The hash prefix of the instant app's domain.
- * @deprecated Should implement {@link #onGetInstantAppIntentFilter(Intent, int[], UserHandle,
- * String, InstantAppResolutionCallback)}.
+ *
+ * @deprecated Should implement {@link #onGetInstantAppIntentFilter(InstantAppRequestInfo,
+ * InstantAppResolutionCallback)}
*/
@Deprecated
public void onGetInstantAppIntentFilter(@Nullable int[] digestPrefix, @NonNull String token,
@@ -103,8 +106,8 @@ public abstract class InstantAppResolverService extends Service {
*
* @see InstantAppResolveInfo
*
- * @deprecated Should implement {@link #onGetInstantAppResolveInfo(Intent, int[], UserHandle,
- * String, InstantAppResolutionCallback)}.
+ * @deprecated Should implement {@link #onGetInstantAppResolveInfo(InstantAppRequestInfo,
+ * InstantAppResolutionCallback)}
*/
@Deprecated
public void onGetInstantAppResolveInfo(@NonNull Intent sanitizedIntent,
@@ -134,8 +137,8 @@ public abstract class InstantAppResolverService extends Service {
* {@link Intent#EXTRA_INSTANT_APP_TOKEN}.
* @param callback The {@link InstantAppResolutionCallback} to provide results to.
*
- * @deprecated Should implement {@link #onGetInstantAppIntentFilter(Intent, int[], UserHandle,
- * String, InstantAppResolutionCallback)}.
+ * @deprecated Should implement {@link #onGetInstantAppIntentFilter(InstantAppRequestInfo,
+ * InstantAppResolutionCallback)}
*/
@Deprecated
public void onGetInstantAppIntentFilter(@NonNull Intent sanitizedIntent,
@@ -170,7 +173,11 @@ public abstract class InstantAppResolverService extends Service {
* @param callback The {@link InstantAppResolutionCallback} to provide results to.
*
* @see InstantAppResolveInfo
+ *
+ * @deprecated Should implement {@link #onGetInstantAppResolveInfo(InstantAppRequestInfo,
+ * InstantAppResolutionCallback
*/
+ @Deprecated
public void onGetInstantAppResolveInfo(@NonNull Intent sanitizedIntent,
@Nullable int[] hostDigestPrefix, @NonNull UserHandle userHandle,
@NonNull String token, @NonNull InstantAppResolutionCallback callback) {
@@ -193,7 +200,11 @@ public abstract class InstantAppResolverService extends Service {
* Intent, int[], UserHandle, String, InstantAppResolutionCallback)} and provided
* to the currently visible installer via {@link Intent#EXTRA_INSTANT_APP_TOKEN}.
* @param callback The {@link InstantAppResolutionCallback} to provide results to.
+ *
+ * @deprecated Should implement {@link #onGetInstantAppIntentFilter(InstantAppRequestInfo,
+ * InstantAppResolutionCallback)}
*/
+ @Deprecated
public void onGetInstantAppIntentFilter(@NonNull Intent sanitizedIntent,
@Nullable int[] hostDigestPrefix, @NonNull UserHandle userHandle,
@NonNull String token, @NonNull InstantAppResolutionCallback callback) {
@@ -202,6 +213,41 @@ public abstract class InstantAppResolverService extends Service {
}
/**
+ * Called to retrieve resolve info for instant applications immediately. The response will be
+ * ignored if not provided within a reasonable time. {@link InstantAppResolveInfo}s provided
+ * in response to this method may be partial to request a second phase of resolution which will
+ * result in a subsequent call to {@link #onGetInstantAppIntentFilter(InstantAppRequestInfo,
+ * InstantAppResolutionCallback)}
+ *
+ * @param request The parameters for this resolution request
+ * @param callback The {@link InstantAppResolutionCallback} to provide results to.
+ *
+ * @see InstantAppResolveInfo
+ */
+ public void onGetInstantAppResolveInfo(@NonNull InstantAppRequestInfo request,
+ @NonNull InstantAppResolutionCallback callback) {
+ // If not overridden, forward to the old method.
+ onGetInstantAppResolveInfo(request.intent, request.hostDigestPrefix, request.userHandle,
+ request.token, callback);
+ }
+
+ /**
+ * Called to retrieve intent filters for potentially matching instant applications. Unlike
+ * {@link #onGetInstantAppResolveInfo(InstantAppRequestInfo, InstantAppResolutionCallback)},
+ * the response may take as long as necessary to respond. All {@link InstantAppResolveInfo}s
+ * provided in response to this method must be completely populated.
+ *
+ * @param request The parameters for this resolution request
+ * @param callback The {@link InstantAppResolutionCallback} to provide results to.
+ */
+ public void onGetInstantAppIntentFilter(@NonNull InstantAppRequestInfo request,
+ @NonNull InstantAppResolutionCallback callback) {
+ // If not overridden, forward to the old method.
+ onGetInstantAppIntentFilter(request.intent, request.hostDigestPrefix, request.userHandle,
+ request.token, callback);
+ }
+
+ /**
* Returns a {@link Looper} to perform service operations on.
*/
Looper getLooper() {
@@ -218,35 +264,29 @@ public abstract class InstantAppResolverService extends Service {
public final IBinder onBind(Intent intent) {
return new IInstantAppResolver.Stub() {
@Override
- public void getInstantAppResolveInfoList(Intent sanitizedIntent, int[] digestPrefix,
- int userId, String token, int sequence, IRemoteCallback callback) {
+ public void getInstantAppResolveInfoList(InstantAppRequestInfo request, int sequence,
+ IRemoteCallback callback) {
if (DEBUG_INSTANT) {
- Slog.v(TAG, "[" + token + "] Phase1 called; posting");
+ Slog.v(TAG, "[" + request.token + "] Phase1 called; posting");
}
final SomeArgs args = SomeArgs.obtain();
- args.arg1 = callback;
- args.arg2 = digestPrefix;
- args.arg3 = userId;
- args.arg4 = token;
- args.arg5 = sanitizedIntent;
- mHandler.obtainMessage(ServiceHandler.MSG_GET_INSTANT_APP_RESOLVE_INFO,
- sequence, 0, args).sendToTarget();
+ args.arg1 = request;
+ args.arg2 = callback;
+ mHandler.obtainMessage(ServiceHandler.MSG_GET_INSTANT_APP_RESOLVE_INFO, sequence,
+ 0, args).sendToTarget();
}
@Override
- public void getInstantAppIntentFilterList(Intent sanitizedIntent,
- int[] digestPrefix, int userId, String token, IRemoteCallback callback) {
+ public void getInstantAppIntentFilterList(InstantAppRequestInfo request,
+ IRemoteCallback callback) {
if (DEBUG_INSTANT) {
- Slog.v(TAG, "[" + token + "] Phase2 called; posting");
+ Slog.v(TAG, "[" + request.token + "] Phase2 called; posting");
}
final SomeArgs args = SomeArgs.obtain();
- args.arg1 = callback;
- args.arg2 = digestPrefix;
- args.arg3 = userId;
- args.arg4 = token;
- args.arg5 = sanitizedIntent;
- mHandler.obtainMessage(ServiceHandler.MSG_GET_INSTANT_APP_INTENT_FILTER,
- args).sendToTarget();
+ args.arg1 = request;
+ args.arg2 = callback;
+ mHandler.obtainMessage(ServiceHandler.MSG_GET_INSTANT_APP_INTENT_FILTER, args)
+ .sendToTarget();
}
};
}
@@ -287,36 +327,33 @@ public abstract class InstantAppResolverService extends Service {
switch (action) {
case MSG_GET_INSTANT_APP_RESOLVE_INFO: {
final SomeArgs args = (SomeArgs) message.obj;
- final IRemoteCallback callback = (IRemoteCallback) args.arg1;
- final int[] digestPrefix = (int[]) args.arg2;
- final int userId = (int) args.arg3;
- final String token = (String) args.arg4;
- final Intent intent = (Intent) args.arg5;
+ final InstantAppRequestInfo request = (InstantAppRequestInfo) args.arg1;
+ final IRemoteCallback callback = (IRemoteCallback) args.arg2;
+ args.recycle();
final int sequence = message.arg1;
if (DEBUG_INSTANT) {
- Slog.d(TAG, "[" + token + "] Phase1 request;"
- + " prefix: " + Arrays.toString(digestPrefix)
- + ", userId: " + userId);
+ Slog.d(TAG, "[" + request.token + "] Phase1 request;"
+ + " prefix: " + Arrays.toString(request.hostDigestPrefix)
+ + ", userId: " + request.userHandle.getIdentifier());
}
- onGetInstantAppResolveInfo(intent, digestPrefix, UserHandle.of(userId), token,
+ onGetInstantAppResolveInfo(request,
new InstantAppResolutionCallback(sequence, callback));
} break;
case MSG_GET_INSTANT_APP_INTENT_FILTER: {
final SomeArgs args = (SomeArgs) message.obj;
- final IRemoteCallback callback = (IRemoteCallback) args.arg1;
- final int[] digestPrefix = (int[]) args.arg2;
- final int userId = (int) args.arg3;
- final String token = (String) args.arg4;
- final Intent intent = (Intent) args.arg5;
+ final InstantAppRequestInfo request = (InstantAppRequestInfo) args.arg1;
+ final IRemoteCallback callback = (IRemoteCallback) args.arg2;
+ args.recycle();
if (DEBUG_INSTANT) {
- Slog.d(TAG, "[" + token + "] Phase2 request;"
- + " prefix: " + Arrays.toString(digestPrefix)
- + ", userId: " + userId);
+ Slog.d(TAG, "[" + request.token + "] Phase2 request;"
+ + " prefix: " + Arrays.toString(request.hostDigestPrefix)
+ + ", userId: " + request.userHandle.getIdentifier());
}
- onGetInstantAppIntentFilter(intent, digestPrefix, UserHandle.of(userId), token,
+ onGetInstantAppIntentFilter(request,
new InstantAppResolutionCallback(-1 /*sequence*/, callback));
- } break;
+ }
+ break;
default: {
throw new IllegalArgumentException("Unknown message: " + action);
diff --git a/core/java/android/app/Instrumentation.java b/core/java/android/app/Instrumentation.java
index 588aceecf4d8..9e552e609f0b 100644
--- a/core/java/android/app/Instrumentation.java
+++ b/core/java/android/app/Instrumentation.java
@@ -19,7 +19,7 @@ package android.app;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
@@ -493,6 +493,7 @@ public class Instrumentation {
public Activity startActivitySync(@NonNull Intent intent, @Nullable Bundle options) {
validateNotAppThread();
+ final Activity activity;
synchronized (mSync) {
intent = new Intent(intent);
@@ -527,16 +528,18 @@ public class Instrumentation {
} catch (InterruptedException e) {
}
} while (mWaitingActivities.contains(aw));
+ activity = aw.activity;
+ }
- waitForEnterAnimationComplete(aw.activity);
+ // Do not call this method within mSync, lest it could block the main thread.
+ waitForEnterAnimationComplete(activity);
- // Apply an empty transaction to ensure SF has a chance to update before
- // the Activity is ready (b/138263890).
- try (SurfaceControl.Transaction t = new SurfaceControl.Transaction()) {
- t.apply(true);
- }
- return aw.activity;
+ // Apply an empty transaction to ensure SF has a chance to update before
+ // the Activity is ready (b/138263890).
+ try (SurfaceControl.Transaction t = new SurfaceControl.Transaction()) {
+ t.apply(true);
}
+ return activity;
}
/**
diff --git a/core/java/android/app/IntentService.java b/core/java/android/app/IntentService.java
index 74fb99a0909f..71b28fba6019 100644
--- a/core/java/android/app/IntentService.java
+++ b/core/java/android/app/IntentService.java
@@ -16,9 +16,9 @@
package android.app;
-import android.annotation.UnsupportedAppUsage;
-import android.annotation.WorkerThread;
import android.annotation.Nullable;
+import android.annotation.WorkerThread;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
diff --git a/core/java/android/app/KeyguardManager.java b/core/java/android/app/KeyguardManager.java
index b1565ab8a501..ab3df70c743f 100644
--- a/core/java/android/app/KeyguardManager.java
+++ b/core/java/android/app/KeyguardManager.java
@@ -23,8 +23,8 @@ import android.annotation.RequiresFeature;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
import android.app.trust.ITrustManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
diff --git a/core/java/android/app/LoadedApk.java b/core/java/android/app/LoadedApk.java
index e858e6a976bc..453c600d49c7 100644
--- a/core/java/android/app/LoadedApk.java
+++ b/core/java/android/app/LoadedApk.java
@@ -18,7 +18,7 @@ package android.app;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
diff --git a/core/java/android/app/LocalActivityManager.java b/core/java/android/app/LocalActivityManager.java
index 87b064d1edc7..4033aea32b55 100644
--- a/core/java/android/app/LocalActivityManager.java
+++ b/core/java/android/app/LocalActivityManager.java
@@ -16,9 +16,9 @@
package android.app;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityThread.ActivityClientRecord;
import android.app.servertransaction.PendingTransactionActions;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Binder;
diff --git a/core/java/android/app/NativeActivity.java b/core/java/android/app/NativeActivity.java
index 25eb958b61e3..74bc9e215106 100644
--- a/core/java/android/app/NativeActivity.java
+++ b/core/java/android/app/NativeActivity.java
@@ -16,7 +16,7 @@
package android.app;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index e30714270d1d..6f63eea1163d 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -32,7 +32,7 @@ import android.annotation.RequiresPermission;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.Intent;
import android.content.LocusId;
diff --git a/core/java/android/app/NotificationChannel.java b/core/java/android/app/NotificationChannel.java
index 1fc8a2b38f95..3eee1ae5c00c 100644
--- a/core/java/android/app/NotificationChannel.java
+++ b/core/java/android/app/NotificationChannel.java
@@ -18,8 +18,8 @@ package android.app;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.NotificationManager.Importance;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
diff --git a/core/java/android/app/NotificationChannelGroup.java b/core/java/android/app/NotificationChannelGroup.java
index c4c1e4f98dc8..403fb3e3727c 100644
--- a/core/java/android/app/NotificationChannelGroup.java
+++ b/core/java/android/app/NotificationChannelGroup.java
@@ -17,7 +17,7 @@ package android.app;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Intent;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/app/NotificationManager.java b/core/java/android/app/NotificationManager.java
index 850645dd81e2..fdbb8bb0d4c5 100644
--- a/core/java/android/app/NotificationManager.java
+++ b/core/java/android/app/NotificationManager.java
@@ -23,8 +23,8 @@ import android.annotation.SdkConstant;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.Notification.Builder;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
diff --git a/core/java/android/app/PackageDeleteObserver.java b/core/java/android/app/PackageDeleteObserver.java
index b7b0b192e7ae..d8803aa13e42 100644
--- a/core/java/android/app/PackageDeleteObserver.java
+++ b/core/java/android/app/PackageDeleteObserver.java
@@ -16,7 +16,7 @@
package android.app;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Intent;
import android.content.pm.IPackageDeleteObserver2;
diff --git a/core/java/android/app/PackageInstallObserver.java b/core/java/android/app/PackageInstallObserver.java
index 50031e0e4d35..0820367db1f8 100644
--- a/core/java/android/app/PackageInstallObserver.java
+++ b/core/java/android/app/PackageInstallObserver.java
@@ -16,7 +16,7 @@
package android.app;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Intent;
import android.content.pm.IPackageInstallObserver2;
import android.os.Bundle;
diff --git a/core/java/android/app/PendingIntent.java b/core/java/android/app/PendingIntent.java
index 0407a8a05609..b8348c7d4f22 100644
--- a/core/java/android/app/PendingIntent.java
+++ b/core/java/android/app/PendingIntent.java
@@ -19,7 +19,7 @@ package android.app;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.IIntentReceiver;
import android.content.IIntentSender;
diff --git a/core/java/android/app/Presentation.java b/core/java/android/app/Presentation.java
index cb72d4d5dc2c..f864fb57d00a 100644
--- a/core/java/android/app/Presentation.java
+++ b/core/java/android/app/Presentation.java
@@ -20,24 +20,24 @@ import static android.content.Context.DISPLAY_SERVICE;
import static android.content.Context.WINDOW_SERVICE;
import static android.view.WindowManager.LayoutParams.TYPE_PRESENTATION;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.Resources;
import android.hardware.display.DisplayManager;
import android.hardware.display.DisplayManager.DisplayListener;
import android.os.Binder;
+import android.os.Handler;
import android.os.IBinder;
+import android.os.Message;
+import android.util.DisplayMetrics;
+import android.util.Log;
+import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import android.view.Display;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManagerImpl;
-import android.os.Handler;
-import android.os.Message;
-import android.util.DisplayMetrics;
-import android.util.Log;
-import android.util.TypedValue;
/**
* Base class for presentations.
diff --git a/core/java/android/app/ProgressDialog.java b/core/java/android/app/ProgressDialog.java
index 3193eb89ac80..432fae5e9033 100644
--- a/core/java/android/app/ProgressDialog.java
+++ b/core/java/android/app/ProgressDialog.java
@@ -16,9 +16,7 @@
package android.app;
-import com.android.internal.R;
-
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
@@ -34,6 +32,8 @@ import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
+import com.android.internal.R;
+
import java.text.NumberFormat;
/**
diff --git a/core/java/android/app/QueuedWork.java b/core/java/android/app/QueuedWork.java
index 76265390fe1a..82cc2c4daa0b 100644
--- a/core/java/android/app/QueuedWork.java
+++ b/core/java/android/app/QueuedWork.java
@@ -16,7 +16,7 @@
package android.app;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
diff --git a/core/java/android/app/ResourcesManager.java b/core/java/android/app/ResourcesManager.java
index 08a28f56021b..aa115984b5e1 100644
--- a/core/java/android/app/ResourcesManager.java
+++ b/core/java/android/app/ResourcesManager.java
@@ -21,7 +21,7 @@ import static android.app.ActivityThread.DEBUG_CONFIGURATION;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.res.ApkAssets;
diff --git a/core/java/android/app/ResultInfo.java b/core/java/android/app/ResultInfo.java
index 9ee0f3126432..979d3dbf36a7 100644
--- a/core/java/android/app/ResultInfo.java
+++ b/core/java/android/app/ResultInfo.java
@@ -16,7 +16,7 @@
package android.app;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Intent;
import android.os.Build;
import android.os.Parcel;
diff --git a/core/java/android/app/SearchDialog.java b/core/java/android/app/SearchDialog.java
index 8493fb25b8a5..9fe894b75455 100644
--- a/core/java/android/app/SearchDialog.java
+++ b/core/java/android/app/SearchDialog.java
@@ -17,7 +17,7 @@
package android.app;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
diff --git a/core/java/android/app/SearchManager.java b/core/java/android/app/SearchManager.java
index b10c3e2dd7df..95f55ab2fde9 100644
--- a/core/java/android/app/SearchManager.java
+++ b/core/java/android/app/SearchManager.java
@@ -19,7 +19,7 @@ package android.app;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.ContentResolver;
diff --git a/core/java/android/app/SearchableInfo.java b/core/java/android/app/SearchableInfo.java
index a01cec7aa944..83eb2ee1da14 100644
--- a/core/java/android/app/SearchableInfo.java
+++ b/core/java/android/app/SearchableInfo.java
@@ -16,17 +16,14 @@
package android.app;
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
import android.annotation.StringRes;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
-import android.content.pm.ProviderInfo;
import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.pm.ProviderInfo;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.os.Parcel;
@@ -38,6 +35,9 @@ import android.util.Log;
import android.util.Xml;
import android.view.inputmethod.EditorInfo;
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+
import java.io.IOException;
import java.util.HashMap;
diff --git a/core/java/android/app/Service.java b/core/java/android/app/Service.java
index 9b62e3b3af98..dc8269f900b7 100644
--- a/core/java/android/app/Service.java
+++ b/core/java/android/app/Service.java
@@ -21,7 +21,7 @@ import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentCallbacks2;
import android.content.ComponentName;
import android.content.Context;
diff --git a/core/java/android/app/SharedPreferencesImpl.java b/core/java/android/app/SharedPreferencesImpl.java
index 9f865b41afc6..abb0cfc73f35 100644
--- a/core/java/android/app/SharedPreferencesImpl.java
+++ b/core/java/android/app/SharedPreferencesImpl.java
@@ -17,10 +17,10 @@
package android.app;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
import android.compat.Compatibility;
import android.compat.annotation.ChangeId;
import android.compat.annotation.EnabledAfter;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.FileUtils;
diff --git a/core/java/android/app/StatsManager.java b/core/java/android/app/StatsManager.java
index 90cd51f8649f..cd855cf134d9 100644
--- a/core/java/android/app/StatsManager.java
+++ b/core/java/android/app/StatsManager.java
@@ -27,8 +27,9 @@ import android.os.IBinder;
import android.os.IPullAtomCallback;
import android.os.IPullAtomResultReceiver;
import android.os.IStatsCompanionService;
-import android.os.IStatsManager;
+import android.os.IStatsManagerService;
import android.os.IStatsPullerCallback;
+import android.os.IStatsd;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.util.AndroidException;
@@ -56,11 +57,14 @@ public final class StatsManager {
private final Context mContext;
@GuardedBy("sLock")
- private IStatsManager mService;
+ private IStatsd mService;
@GuardedBy("sLock")
private IStatsCompanionService mStatsCompanion;
+ @GuardedBy("sLock")
+ private IStatsManagerService mStatsManagerService;
+
/**
* Long extra of uid that added the relevant stats config.
*/
@@ -129,7 +133,7 @@ public final class StatsManager {
public void addConfig(long configKey, byte[] config) throws StatsUnavailableException {
synchronized (sLock) {
try {
- IStatsManager service = getIStatsManagerLocked();
+ IStatsd service = getIStatsdLocked();
// can throw IllegalArgumentException
service.addConfiguration(configKey, config, mContext.getOpPackageName());
} catch (RemoteException e) {
@@ -166,7 +170,7 @@ public final class StatsManager {
public void removeConfig(long configKey) throws StatsUnavailableException {
synchronized (sLock) {
try {
- IStatsManager service = getIStatsManagerLocked();
+ IStatsd service = getIStatsdLocked();
service.removeConfiguration(configKey, mContext.getOpPackageName());
} catch (RemoteException e) {
Slog.e(TAG, "Failed to connect to statsd when removing configuration");
@@ -227,7 +231,7 @@ public final class StatsManager {
throws StatsUnavailableException {
synchronized (sLock) {
try {
- IStatsManager service = getIStatsManagerLocked();
+ IStatsd service = getIStatsdLocked();
if (pendingIntent != null) {
// Extracts IIntentSender from the PendingIntent and turns it into an IBinder.
IBinder intentSender = pendingIntent.getTarget().asBinder();
@@ -281,7 +285,7 @@ public final class StatsManager {
throws StatsUnavailableException {
synchronized (sLock) {
try {
- IStatsManager service = getIStatsManagerLocked();
+ IStatsd service = getIStatsdLocked();
if (pendingIntent == null) {
service.removeDataFetchOperation(configKey, mContext.getOpPackageName());
} else {
@@ -319,7 +323,7 @@ public final class StatsManager {
throws StatsUnavailableException {
synchronized (sLock) {
try {
- IStatsManager service = getIStatsManagerLocked();
+ IStatsd service = getIStatsdLocked();
if (pendingIntent == null) {
service.removeActiveConfigsChangedOperation(mContext.getOpPackageName());
return new long[0];
@@ -367,7 +371,7 @@ public final class StatsManager {
public byte[] getReports(long configKey) throws StatsUnavailableException {
synchronized (sLock) {
try {
- IStatsManager service = getIStatsManagerLocked();
+ IStatsd service = getIStatsdLocked();
return service.getData(configKey, mContext.getOpPackageName());
} catch (RemoteException e) {
Slog.e(TAG, "Failed to connect to statsd when getting data");
@@ -404,7 +408,7 @@ public final class StatsManager {
public byte[] getStatsMetadata() throws StatsUnavailableException {
synchronized (sLock) {
try {
- IStatsManager service = getIStatsManagerLocked();
+ IStatsd service = getIStatsdLocked();
return service.getMetadata(mContext.getOpPackageName());
} catch (RemoteException e) {
Slog.e(TAG, "Failed to connect to statsd when getting metadata");
@@ -439,7 +443,7 @@ public final class StatsManager {
throws StatsUnavailableException {
synchronized (sLock) {
try {
- IStatsManager service = getIStatsManagerLocked();
+ IStatsd service = getIStatsdLocked();
if (service == null) {
if (DEBUG) {
Slog.d(TAG, "Failed to find statsd when getting experiment IDs");
@@ -476,7 +480,7 @@ public final class StatsManager {
throws StatsUnavailableException {
synchronized (sLock) {
try {
- IStatsManager service = getIStatsManagerLocked();
+ IStatsd service = getIStatsdLocked();
if (callback == null) {
service.unregisterPullerCallback(atomTag, mContext.getOpPackageName());
} else {
@@ -660,11 +664,11 @@ public final class StatsManager {
}
@GuardedBy("sLock")
- private IStatsManager getIStatsManagerLocked() throws StatsUnavailableException {
+ private IStatsd getIStatsdLocked() throws StatsUnavailableException {
if (mService != null) {
return mService;
}
- mService = IStatsManager.Stub.asInterface(ServiceManager.getService("stats"));
+ mService = IStatsd.Stub.asInterface(ServiceManager.getService("stats"));
if (mService == null) {
throw new StatsUnavailableException("could not be found");
}
@@ -686,6 +690,16 @@ public final class StatsManager {
return mStatsCompanion;
}
+ @GuardedBy("sLock")
+ private IStatsManagerService getIStatsManagerServiceLocked() {
+ if (mStatsManagerService != null) {
+ return mStatsManagerService;
+ }
+ mStatsManagerService = IStatsManagerService.Stub.asInterface(
+ ServiceManager.getService(Context.STATS_MANAGER_SERVICE));
+ return mStatsManagerService;
+ }
+
/**
* Exception thrown when communication with the stats service fails (eg if it is not available).
* This might be thrown early during boot before the stats service has started or if it crashed.
diff --git a/core/java/android/app/StatusBarManager.java b/core/java/android/app/StatusBarManager.java
index 28413be29a1d..a1765c85d57b 100644
--- a/core/java/android/app/StatusBarManager.java
+++ b/core/java/android/app/StatusBarManager.java
@@ -23,7 +23,7 @@ import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.Binder;
import android.os.IBinder;
diff --git a/core/java/android/app/SystemServiceRegistry.java b/core/java/android/app/SystemServiceRegistry.java
index 601b65863db1..ce21db335615 100644
--- a/core/java/android/app/SystemServiceRegistry.java
+++ b/core/java/android/app/SystemServiceRegistry.java
@@ -53,7 +53,9 @@ import android.content.RestrictionsManager;
import android.content.om.IOverlayManager;
import android.content.om.OverlayManager;
import android.content.pm.CrossProfileApps;
+import android.content.pm.DataLoaderManager;
import android.content.pm.ICrossProfileApps;
+import android.content.pm.IDataLoaderManager;
import android.content.pm.IPackageManager;
import android.content.pm.IShortcutService;
import android.content.pm.LauncherApps;
@@ -118,6 +120,7 @@ import android.net.lowpan.ILowpanManager;
import android.net.lowpan.LowpanManager;
import android.net.nsd.INsdManager;
import android.net.nsd.NsdManager;
+import android.net.wifi.WifiCondManager;
import android.net.wifi.WifiFrameworkInitializer;
import android.nfc.NfcManager;
import android.os.BatteryManager;
@@ -149,6 +152,8 @@ import android.os.Vibrator;
import android.os.health.SystemHealthManager;
import android.os.image.DynamicSystemManager;
import android.os.image.IDynamicSystemService;
+import android.os.incremental.IIncrementalManagerNative;
+import android.os.incremental.IncrementalManager;
import android.os.storage.StorageManager;
import android.permission.PermissionControllerManager;
import android.permission.PermissionManager;
@@ -694,6 +699,14 @@ public final class SystemServiceRegistry {
return new EthernetManager(ctx.getOuterContext(), service);
}});
+ registerService(Context.WIFI_COND_SERVICE, WifiCondManager.class,
+ new CachedServiceFetcher<WifiCondManager>() {
+ @Override
+ public WifiCondManager createService(ContextImpl ctx) {
+ return new WifiCondManager(ctx.getOuterContext());
+ }
+ });
+
registerService(Context.WINDOW_SERVICE, WindowManager.class,
new CachedServiceFetcher<WindowManager>() {
@Override
@@ -1134,6 +1147,14 @@ public final class SystemServiceRegistry {
return new TimeZoneDetector();
}});
+ registerService(Context.TELEPHONY_IMS_SERVICE, android.telephony.ims.ImsManager.class,
+ new CachedServiceFetcher<android.telephony.ims.ImsManager>() {
+ @Override
+ public android.telephony.ims.ImsManager createService(ContextImpl ctx) {
+ return new android.telephony.ims.ImsManager(ctx.getOuterContext());
+ }
+ });
+
registerService(Context.PERMISSION_SERVICE, PermissionManager.class,
new CachedServiceFetcher<PermissionManager>() {
@Override
@@ -1197,6 +1218,29 @@ public final class SystemServiceRegistry {
return new BatteryStatsManager(
IBatteryStats.Stub.asInterface(b));
}});
+ registerService(Context.DATA_LOADER_MANAGER_SERVICE, DataLoaderManager.class,
+ new CachedServiceFetcher<DataLoaderManager>() {
+ @Override
+ public DataLoaderManager createService(ContextImpl ctx)
+ throws ServiceNotFoundException {
+ IBinder b = ServiceManager.getServiceOrThrow(
+ Context.DATA_LOADER_MANAGER_SERVICE);
+ return new DataLoaderManager(IDataLoaderManager.Stub.asInterface(b));
+ }});
+ //TODO(b/136132412): refactor this: 1) merge IIncrementalManager.aidl and
+ //IIncrementalManagerNative.aidl, 2) implement the binder interface in
+ //IncrementalManagerService.java, 3) use JNI to call native functions
+ registerService(Context.INCREMENTAL_SERVICE, IncrementalManager.class,
+ new CachedServiceFetcher<IncrementalManager>() {
+ @Override
+ public IncrementalManager createService(ContextImpl ctx) {
+ IBinder b = ServiceManager.getService(Context.INCREMENTAL_SERVICE);
+ if (b == null) {
+ return null;
+ }
+ return new IncrementalManager(
+ IIncrementalManagerNative.Stub.asInterface(b));
+ }});
//CHECKSTYLE:ON IndentationCheck
sInitializing = true;
diff --git a/core/java/android/app/TaskEmbedder.java b/core/java/android/app/TaskEmbedder.java
index 79d88fd89716..e5707bb4a498 100644
--- a/core/java/android/app/TaskEmbedder.java
+++ b/core/java/android/app/TaskEmbedder.java
@@ -184,7 +184,7 @@ public class TaskEmbedder {
return false;
}
- // Create a container surface to which the ActivityDisplay will be reparented
+ // Create a container surface to which the DisplayContent will be reparented
final String name = "TaskEmbedder - " + Integer.toHexString(System.identityHashCode(this));
mSurfaceControl = new SurfaceControl.Builder()
.setContainerLayer()
@@ -276,7 +276,7 @@ public class TaskEmbedder {
* @see ActivityView.StateCallback
* @see #startActivity(Intent)
*/
- void setListener(TaskEmbedder.Listener listener) {
+ public void setListener(TaskEmbedder.Listener listener) {
mListener = listener;
if (mListener != null && isInitialized()) {
mListener.onInitialized();
diff --git a/core/java/android/app/TaskInfo.java b/core/java/android/app/TaskInfo.java
index de64db9def64..fe9c64038909 100644
--- a/core/java/android/app/TaskInfo.java
+++ b/core/java/android/app/TaskInfo.java
@@ -18,7 +18,7 @@ package android.app;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Intent;
import android.content.res.Configuration;
diff --git a/core/java/android/app/TaskStackListener.java b/core/java/android/app/TaskStackListener.java
index 40d10b7d8768..343b3869d354 100644
--- a/core/java/android/app/TaskStackListener.java
+++ b/core/java/android/app/TaskStackListener.java
@@ -16,8 +16,8 @@
package android.app;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityManager.TaskSnapshot;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.os.Binder;
import android.os.IBinder;
diff --git a/core/java/android/app/TimePickerDialog.java b/core/java/android/app/TimePickerDialog.java
index 1b281d521957..c529297b14db 100644
--- a/core/java/android/app/TimePickerDialog.java
+++ b/core/java/android/app/TimePickerDialog.java
@@ -17,7 +17,7 @@
package android.app;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
diff --git a/core/java/android/app/UiAutomation.java b/core/java/android/app/UiAutomation.java
index 13d566c0e04b..18a3e6e89552 100644
--- a/core/java/android/app/UiAutomation.java
+++ b/core/java/android/app/UiAutomation.java
@@ -25,7 +25,7 @@ import android.accessibilityservice.IAccessibilityServiceConnection;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
diff --git a/core/java/android/app/UiAutomationConnection.java b/core/java/android/app/UiAutomationConnection.java
index 1e9bbae91883..82e988109db8 100644
--- a/core/java/android/app/UiAutomationConnection.java
+++ b/core/java/android/app/UiAutomationConnection.java
@@ -19,6 +19,7 @@ package android.app;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.accessibilityservice.IAccessibilityServiceClient;
import android.annotation.Nullable;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
@@ -40,8 +41,6 @@ import android.view.WindowContentFrameStats;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.IAccessibilityManager;
-import dalvik.annotation.compat.UnsupportedAppUsage;
-
import libcore.io.IoUtils;
import java.io.FileInputStream;
diff --git a/core/java/android/app/UiModeManager.java b/core/java/android/app/UiModeManager.java
index d8c030d7aacf..363306483409 100644
--- a/core/java/android/app/UiModeManager.java
+++ b/core/java/android/app/UiModeManager.java
@@ -23,7 +23,7 @@ import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.Configuration;
import android.os.RemoteException;
diff --git a/core/java/android/app/UserSwitchObserver.java b/core/java/android/app/UserSwitchObserver.java
index 2f8ee744bfd6..6abc4f09ba38 100644
--- a/core/java/android/app/UserSwitchObserver.java
+++ b/core/java/android/app/UserSwitchObserver.java
@@ -16,7 +16,7 @@
package android.app;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.IRemoteCallback;
import android.os.RemoteException;
diff --git a/core/java/android/app/VrManager.java b/core/java/android/app/VrManager.java
index c74f8c389c20..08a210b069b9 100644
--- a/core/java/android/app/VrManager.java
+++ b/core/java/android/app/VrManager.java
@@ -6,7 +6,7 @@ import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.os.RemoteException;
diff --git a/core/java/android/app/WallpaperManager.java b/core/java/android/app/WallpaperManager.java
index 41604ec97867..ac8b40c7ed49 100644
--- a/core/java/android/app/WallpaperManager.java
+++ b/core/java/android/app/WallpaperManager.java
@@ -26,7 +26,7 @@ import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
diff --git a/core/java/android/app/WindowConfiguration.java b/core/java/android/app/WindowConfiguration.java
index aa6492e9d098..1e4f8f3f5b66 100644
--- a/core/java/android/app/WindowConfiguration.java
+++ b/core/java/android/app/WindowConfiguration.java
@@ -26,6 +26,7 @@ import static android.view.Surface.rotationToString;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.TestApi;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.os.Parcel;
@@ -35,8 +36,6 @@ import android.util.proto.ProtoOutputStream;
import android.util.proto.WireTypeMismatchException;
import android.view.DisplayInfo;
-import dalvik.annotation.compat.UnsupportedAppUsage;
-
import java.io.IOException;
/**
diff --git a/core/java/android/app/admin/DeviceAdminInfo.java b/core/java/android/app/admin/DeviceAdminInfo.java
index 63bc40b86aa7..a2f44149e853 100644
--- a/core/java/android/app/admin/DeviceAdminInfo.java
+++ b/core/java/android/app/admin/DeviceAdminInfo.java
@@ -17,7 +17,7 @@
package android.app.admin;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ActivityInfo;
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index 915e4572c035..3ca8f49e4d54 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -33,13 +33,13 @@ import android.annotation.SuppressLint;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.UserIdInt;
import android.annotation.WorkerThread;
import android.app.Activity;
import android.app.IServiceConnection;
import android.app.KeyguardManager;
import android.app.admin.SecurityLog.SecurityEvent;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
@@ -1349,6 +1349,9 @@ public class DevicePolicyManager {
* Broadcast action: send when any policy admin changes a policy.
* This is generally used to find out when a new policy is in effect.
*
+ * If the profile owner of an organization-owned managed profile changes some user
+ * restriction explicitly on the parent user, this broadcast will <em>not</em> be
+ * sent to the parent user.
* @hide
*/
@UnsupportedAppUsage
@@ -2324,6 +2327,11 @@ public class DevicePolicyManager {
/**
* Activity action: Starts the administrator to show policy compliance for the provisioning.
+ * This action is used any time that the administrator has an opportunity to show policy
+ * compliance before the end of setup wizard. This could happen as part of the admin-integrated
+ * provisioning flow (in which case this gets sent after {@link #ACTION_GET_PROVISIONING_MODE}),
+ * or it could happen during provisioning finalization if the administrator supports
+ * finalization during setup wizard.
*/
public static final String ACTION_ADMIN_POLICY_COMPLIANCE =
"android.app.action.ADMIN_POLICY_COMPLIANCE";
@@ -5805,6 +5813,49 @@ public class DevicePolicyManager {
}
/**
+ * Called by a device owner, a profile owner for the primary user or a profile
+ * owner of an organization-owned managed profile to turn auto time zone on and off.
+ * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
+ * to prevent the user from changing this setting.
+ * <p>
+ * If user restriction {@link UserManager#DISALLOW_CONFIG_DATE_TIME} is used,
+ * no user will be able set the date and time zone. Instead, the network date
+ * and time zone will be used.
+ *
+ * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
+ * @param enabled Whether time zone should be obtained automatically from the network or not.
+ * @throws SecurityException if caller is not a device owner, a profile owner for the
+ * primary user, or a profile owner of an organization-owned managed profile.
+ */
+ public void setAutoTimeZone(@NonNull ComponentName admin, boolean enabled) {
+ throwIfParentInstance("setAutoTimeZone");
+ if (mService != null) {
+ try {
+ mService.setAutoTimeZone(admin, enabled);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+ }
+
+ /**
+ * @return true if auto time zone is enabled on the device.
+ * @throws SecurityException if caller is not a device owner, a profile owner for the
+ * primary user, or a profile owner of an organization-owned managed profile.
+ */
+ public boolean getAutoTimeZone(@NonNull ComponentName admin) {
+ throwIfParentInstance("getAutoTimeZone");
+ if (mService != null) {
+ try {
+ return mService.getAutoTimeZone(admin);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+ return false;
+ }
+
+ /**
* Called by a device owner to set whether all users created on the device should be ephemeral.
* <p>
* The system user is exempt from this policy - it is never ephemeral.
@@ -7910,18 +7961,23 @@ public class DevicePolicyManager {
* <p>
* The calling device admin must be a profile or device owner; if it is not, a security
* exception will be thrown.
+ * <p>
+ * The profile owner of an organization-owned managed profile may invoke this method on
+ * the {@link DevicePolicyManager} instance it obtained from
+ * {@link #getParentProfileInstance(ComponentName)}, for enforcing device-wide restrictions.
+ * <p>
+ * See the constants in {@link android.os.UserManager} for the list of restrictions that can
+ * be enforced device-wide.
*
* @param admin Which {@link DeviceAdminReceiver} this request is associated with.
- * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
- * for the list of keys.
+ * @param key The key of the restriction.
* @throws SecurityException if {@code admin} is not a device or profile owner.
*/
public void addUserRestriction(@NonNull ComponentName admin,
@UserManager.UserRestrictionKey String key) {
- throwIfParentInstance("addUserRestriction");
if (mService != null) {
try {
- mService.setUserRestriction(admin, key, true);
+ mService.setUserRestriction(admin, key, true, mParentInstance);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -7933,18 +7989,22 @@ public class DevicePolicyManager {
* <p>
* The calling device admin must be a profile or device owner; if it is not, a security
* exception will be thrown.
+ * <p>
+ * The profile owner of an organization-owned managed profile may invoke this method on
+ * the {@link DevicePolicyManager} instance it obtained from
+ * {@link #getParentProfileInstance(ComponentName)}, for clearing device-wide restrictions.
+ * <p>
+ * See the constants in {@link android.os.UserManager} for the list of restrictions.
*
* @param admin Which {@link DeviceAdminReceiver} this request is associated with.
- * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
- * for the list of keys.
+ * @param key The key of the restriction.
* @throws SecurityException if {@code admin} is not a device or profile owner.
*/
public void clearUserRestriction(@NonNull ComponentName admin,
@UserManager.UserRestrictionKey String key) {
- throwIfParentInstance("clearUserRestriction");
if (mService != null) {
try {
- mService.setUserRestriction(admin, key, false);
+ mService.setUserRestriction(admin, key, false, mParentInstance);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -7958,16 +8018,20 @@ public class DevicePolicyManager {
* The target user may have more restrictions set by the system or other device owner / profile
* owner. To get all the user restrictions currently set, use
* {@link UserManager#getUserRestrictions()}.
+ * <p>
+ * The profile owner of an organization-owned managed profile may invoke this method on
+ * the {@link DevicePolicyManager} instance it obtained from
+ * {@link #getParentProfileInstance(ComponentName)}, for retrieving device-wide restrictions
+ * it previously set with {@link #addUserRestriction(ComponentName, String)}.
*
* @param admin Which {@link DeviceAdminReceiver} this request is associated with.
* @throws SecurityException if {@code admin} is not a device or profile owner.
*/
public @NonNull Bundle getUserRestrictions(@NonNull ComponentName admin) {
- throwIfParentInstance("getUserRestrictions");
Bundle ret = null;
if (mService != null) {
try {
- ret = mService.getUserRestrictions(admin);
+ ret = mService.getUserRestrictions(admin, mParentInstance);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -11085,6 +11149,53 @@ public class DevicePolicyManager {
}
/**
+ * Sets the set of package names that are allowed to request user consent for cross-profile
+ * communication.
+ *
+ * <p>Assumes that the caller is a profile owner and is the given {@code admin}.
+ *
+ * <p>Previous calls are overridden by each subsequent call to this method.
+ *
+ * @param admin the {@link DeviceAdminReceiver} this request is associated with
+ * @param packageNames the new cross-profile package names
+ */
+ public void setCrossProfilePackages(
+ @NonNull ComponentName admin, @NonNull Set<String> packageNames) {
+ throwIfParentInstance("setCrossProfilePackages");
+ if (mService != null) {
+ try {
+ mService.setCrossProfilePackages(admin, new ArrayList<>(packageNames));
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+ }
+
+ /**
+ * Returns the set of package names that the admin has previously set as allowed to request user
+ * consent for cross-profile communication, via {@link
+ * #setCrossProfilePackages(ComponentName, Set)}.
+ *
+ * <p>Assumes that the caller is a profile owner and is the given {@code admin}.
+ *
+ * @param admin the {@link DeviceAdminReceiver} this request is associated with
+ * @return the set of package names the admin has previously set as allowed to request user
+ * consent for cross-profile communication, via {@link
+ * #setCrossProfilePackages(ComponentName, Set)}
+ */
+ public @NonNull Set<String> getCrossProfilePackages(@NonNull ComponentName admin) {
+ throwIfParentInstance("getCrossProfilePackages");
+ if (mService != null) {
+ try {
+ return new ArraySet<>(mService.getCrossProfilePackages(admin));
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+ return Collections.emptySet();
+ }
+
+ /**
* Returns whether the device is being used as a managed kiosk. These requirements are as
* follows:
* <ul>
diff --git a/core/java/android/app/admin/IDevicePolicyManager.aidl b/core/java/android/app/admin/IDevicePolicyManager.aidl
index 34246fa808bd..9c82ff6f51ac 100644
--- a/core/java/android/app/admin/IDevicePolicyManager.aidl
+++ b/core/java/android/app/admin/IDevicePolicyManager.aidl
@@ -208,8 +208,8 @@ interface IDevicePolicyManager {
void setRestrictionsProvider(in ComponentName who, in ComponentName provider);
ComponentName getRestrictionsProvider(int userHandle);
- void setUserRestriction(in ComponentName who, in String key, boolean enable);
- Bundle getUserRestrictions(in ComponentName who);
+ void setUserRestriction(in ComponentName who, in String key, boolean enable, boolean parent);
+ Bundle getUserRestrictions(in ComponentName who, boolean parent);
void addCrossProfileIntentFilter(in ComponentName admin, in IntentFilter filter, int flags);
void clearCrossProfileIntentFilters(in ComponentName admin);
@@ -298,6 +298,9 @@ interface IDevicePolicyManager {
void setAutoTime(in ComponentName who, boolean enabled);
boolean getAutoTime(in ComponentName who);
+ void setAutoTimeZone(in ComponentName who, boolean enabled);
+ boolean getAutoTimeZone(in ComponentName who);
+
void setForceEphemeralUsers(in ComponentName who, boolean forceEpehemeralUsers);
boolean getForceEphemeralUsers(in ComponentName who);
@@ -438,6 +441,9 @@ interface IDevicePolicyManager {
boolean isPackageAllowedToAccessCalendarForUser(String packageName, int userHandle);
List<String> getCrossProfileCalendarPackagesForUser(int userHandle);
+ void setCrossProfilePackages(in ComponentName admin, in List<String> packageNames);
+ List<String> getCrossProfilePackages(in ComponentName admin);
+
boolean isManagedKiosk();
boolean isUnattendedManagedKiosk();
diff --git a/core/java/android/app/admin/SecurityLog.java b/core/java/android/app/admin/SecurityLog.java
index 972762152d3a..f0b87a8e2561 100644
--- a/core/java/android/app/admin/SecurityLog.java
+++ b/core/java/android/app/admin/SecurityLog.java
@@ -18,7 +18,7 @@ package android.app.admin;
import android.annotation.IntDef;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/app/assist/AssistContent.java b/core/java/android/app/assist/AssistContent.java
index db6ae4f2260a..e5316bc05749 100644
--- a/core/java/android/app/assist/AssistContent.java
+++ b/core/java/android/app/assist/AssistContent.java
@@ -1,6 +1,6 @@
package android.app.assist;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
diff --git a/core/java/android/app/backup/BackupAgent.java b/core/java/android/app/backup/BackupAgent.java
index 24580b40aa29..20aa0647d261 100644
--- a/core/java/android/app/backup/BackupAgent.java
+++ b/core/java/android/app/backup/BackupAgent.java
@@ -45,7 +45,10 @@ import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.util.Collections;
+import java.util.HashSet;
import java.util.LinkedList;
+import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
@@ -327,6 +330,28 @@ public abstract class BackupAgent extends ContextWrapper {
}
/**
+ * New version of {@link #onRestore(BackupDataInput, long, android.os.ParcelFileDescriptor)}
+ * that has a list of keys to be excluded from the restore. Key/value pairs for which the key
+ * is present in {@code excludedKeys} have already been excluded from the restore data by the
+ * system. The list is passed to the agent to make it aware of what data has been removed (in
+ * case it has any application-level consequences) as well as the data that should be removed
+ * by the agent itself.
+ *
+ * The default implementation calls {@link #onRestore(BackupDataInput, long,
+ * android.os.ParcelFileDescriptor)}.
+ *
+ * @param excludedKeys A list of keys to be excluded from restore.
+ *
+ * @hide
+ */
+ public void onRestore(BackupDataInput data, long appVersionCode,
+ ParcelFileDescriptor newState,
+ Set<String> excludedKeys)
+ throws IOException {
+ onRestore(data, appVersionCode, newState);
+ }
+
+ /**
* The application is having its entire file system contents backed up. {@code data}
* points to the backup destination, and the app has the opportunity to choose which
* files are to be stored. To commit a file as part of the backup, call the
@@ -1016,8 +1041,22 @@ public abstract class BackupAgent extends ContextWrapper {
@Override
public void doRestore(ParcelFileDescriptor data, long appVersionCode,
- ParcelFileDescriptor newState,
- int token, IBackupManager callbackBinder) throws RemoteException {
+ ParcelFileDescriptor newState, int token, IBackupManager callbackBinder)
+ throws RemoteException {
+ doRestoreInternal(data, appVersionCode, newState, token, callbackBinder,
+ /* excludedKeys */ null);
+ }
+
+ @Override
+ public void doRestoreWithExcludedKeys(ParcelFileDescriptor data, long appVersionCode,
+ ParcelFileDescriptor newState, int token, IBackupManager callbackBinder,
+ List<String> excludedKeys) throws RemoteException {
+ doRestoreInternal(data, appVersionCode, newState, token, callbackBinder, excludedKeys);
+ }
+
+ private void doRestoreInternal(ParcelFileDescriptor data, long appVersionCode,
+ ParcelFileDescriptor newState, int token, IBackupManager callbackBinder,
+ List<String> excludedKeys) throws RemoteException {
// Ensure that we're running with the app's normal permission level
long ident = Binder.clearCallingIdentity();
@@ -1029,7 +1068,9 @@ public abstract class BackupAgent extends ContextWrapper {
BackupDataInput input = new BackupDataInput(data.getFileDescriptor());
try {
- BackupAgent.this.onRestore(input, appVersionCode, newState);
+ BackupAgent.this.onRestore(input, appVersionCode, newState,
+ excludedKeys != null ? new HashSet<>(excludedKeys)
+ : Collections.emptySet());
} catch (IOException ex) {
Log.d(TAG, "onRestore (" + BackupAgent.this.getClass().getName() + ") threw", ex);
throw new RuntimeException(ex);
diff --git a/core/java/android/app/backup/BackupDataInput.java b/core/java/android/app/backup/BackupDataInput.java
index 2a98ca715a26..d1383c8d0a6a 100644
--- a/core/java/android/app/backup/BackupDataInput.java
+++ b/core/java/android/app/backup/BackupDataInput.java
@@ -17,7 +17,7 @@
package android.app.backup;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import java.io.FileDescriptor;
import java.io.IOException;
diff --git a/core/java/android/app/backup/BackupDataInputStream.java b/core/java/android/app/backup/BackupDataInputStream.java
index 08880665d921..11a3d0c3d725 100644
--- a/core/java/android/app/backup/BackupDataInputStream.java
+++ b/core/java/android/app/backup/BackupDataInputStream.java
@@ -16,9 +16,10 @@
package android.app.backup;
-import android.annotation.UnsupportedAppUsage;
-import java.io.InputStream;
+import android.compat.annotation.UnsupportedAppUsage;
+
import java.io.IOException;
+import java.io.InputStream;
/**
* Provides an {@link java.io.InputStream}-like interface for accessing an
diff --git a/core/java/android/app/backup/BackupDataOutput.java b/core/java/android/app/backup/BackupDataOutput.java
index 01961e78777f..fb161d41acd2 100644
--- a/core/java/android/app/backup/BackupDataOutput.java
+++ b/core/java/android/app/backup/BackupDataOutput.java
@@ -17,7 +17,7 @@
package android.app.backup;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.ParcelFileDescriptor;
import java.io.FileDescriptor;
diff --git a/core/java/android/app/backup/BackupHelperDispatcher.java b/core/java/android/app/backup/BackupHelperDispatcher.java
index e9acdbfb61b9..6faa887206c1 100644
--- a/core/java/android/app/backup/BackupHelperDispatcher.java
+++ b/core/java/android/app/backup/BackupHelperDispatcher.java
@@ -16,7 +16,7 @@
package android.app.backup;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.ParcelFileDescriptor;
import android.util.Log;
diff --git a/core/java/android/app/backup/BackupManager.java b/core/java/android/app/backup/BackupManager.java
index 93d1e7166708..beb444997fc7 100644
--- a/core/java/android/app/backup/BackupManager.java
+++ b/core/java/android/app/backup/BackupManager.java
@@ -21,7 +21,7 @@ import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
diff --git a/core/java/android/app/backup/FileBackupHelperBase.java b/core/java/android/app/backup/FileBackupHelperBase.java
index 0caab983448b..5ad5d0865e56 100644
--- a/core/java/android/app/backup/FileBackupHelperBase.java
+++ b/core/java/android/app/backup/FileBackupHelperBase.java
@@ -16,7 +16,7 @@
package android.app.backup;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.ParcelFileDescriptor;
import android.util.Log;
diff --git a/core/java/android/app/backup/FullBackup.java b/core/java/android/app/backup/FullBackup.java
index 9a595b2da59f..587e883edaf2 100644
--- a/core/java/android/app/backup/FullBackup.java
+++ b/core/java/android/app/backup/FullBackup.java
@@ -16,7 +16,7 @@
package android.app.backup;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.XmlResourceParser;
diff --git a/core/java/android/app/backup/FullBackupDataOutput.java b/core/java/android/app/backup/FullBackupDataOutput.java
index 0ce86534afdd..d8fa0f586b7a 100644
--- a/core/java/android/app/backup/FullBackupDataOutput.java
+++ b/core/java/android/app/backup/FullBackupDataOutput.java
@@ -1,6 +1,6 @@
package android.app.backup;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.ParcelFileDescriptor;
/**
diff --git a/core/java/android/app/backup/IBackupManager.aidl b/core/java/android/app/backup/IBackupManager.aidl
index 099272d8e3ec..4940976133c5 100644
--- a/core/java/android/app/backup/IBackupManager.aidl
+++ b/core/java/android/app/backup/IBackupManager.aidl
@@ -597,6 +597,12 @@ interface IBackupManager {
boolean isBackupServiceActive(int whichUser);
/**
+ * Checks if the user is ready for backup or not.
+ * @param userId User id for which this operation should be performed.
+ */
+ boolean isUserReadyForBackup(int userId);
+
+ /**
* Ask the framework which dataset, if any, the given package's data would be
* restored from if we were to install it right now.
*
diff --git a/core/java/android/app/role/RoleControllerService.java b/core/java/android/app/role/RoleControllerService.java
index 06623f93552a..d92c95691eea 100644
--- a/core/java/android/app/role/RoleControllerService.java
+++ b/core/java/android/app/role/RoleControllerService.java
@@ -35,6 +35,7 @@ import android.os.UserHandle;
import com.android.internal.util.Preconditions;
import com.android.internal.util.function.pooled.PooledLambda;
+import java.util.Objects;
import java.util.concurrent.Executor;
/**
@@ -82,7 +83,7 @@ public abstract class RoleControllerService extends Service {
public void grantDefaultRoles(RemoteCallback callback) {
enforceCallerSystemUid("grantDefaultRoles");
- Preconditions.checkNotNull(callback, "callback cannot be null");
+ Objects.requireNonNull(callback, "callback cannot be null");
mWorkerHandler.sendMessage(PooledLambda.obtainMessage(
RoleControllerService::grantDefaultRoles, RoleControllerService.this,
@@ -97,7 +98,7 @@ public abstract class RoleControllerService extends Service {
Preconditions.checkStringNotEmpty(roleName, "roleName cannot be null or empty");
Preconditions.checkStringNotEmpty(packageName,
"packageName cannot be null or empty");
- Preconditions.checkNotNull(callback, "callback cannot be null");
+ Objects.requireNonNull(callback, "callback cannot be null");
mWorkerHandler.sendMessage(PooledLambda.obtainMessage(
RoleControllerService::onAddRoleHolder, RoleControllerService.this,
@@ -112,7 +113,7 @@ public abstract class RoleControllerService extends Service {
Preconditions.checkStringNotEmpty(roleName, "roleName cannot be null or empty");
Preconditions.checkStringNotEmpty(packageName,
"packageName cannot be null or empty");
- Preconditions.checkNotNull(callback, "callback cannot be null");
+ Objects.requireNonNull(callback, "callback cannot be null");
mWorkerHandler.sendMessage(PooledLambda.obtainMessage(
RoleControllerService::onRemoveRoleHolder, RoleControllerService.this,
@@ -124,7 +125,7 @@ public abstract class RoleControllerService extends Service {
enforceCallerSystemUid("onClearRoleHolders");
Preconditions.checkStringNotEmpty(roleName, "roleName cannot be null or empty");
- Preconditions.checkNotNull(callback, "callback cannot be null");
+ Objects.requireNonNull(callback, "callback cannot be null");
mWorkerHandler.sendMessage(PooledLambda.obtainMessage(
RoleControllerService::onClearRoleHolders, RoleControllerService.this,
@@ -146,7 +147,7 @@ public abstract class RoleControllerService extends Service {
Preconditions.checkStringNotEmpty(roleName, "roleName cannot be null or empty");
Preconditions.checkStringNotEmpty(packageName,
"packageName cannot be null or empty");
- Preconditions.checkNotNull(callback, "callback cannot be null");
+ Objects.requireNonNull(callback, "callback cannot be null");
boolean qualified = onIsApplicationQualifiedForRole(roleName, packageName);
callback.sendResult(qualified ? Bundle.EMPTY : null);
@@ -160,7 +161,7 @@ public abstract class RoleControllerService extends Service {
Preconditions.checkStringNotEmpty(roleName, "roleName cannot be null or empty");
Preconditions.checkStringNotEmpty(packageName,
"packageName cannot be null or empty");
- Preconditions.checkNotNull(callback, "callback cannot be null");
+ Objects.requireNonNull(callback, "callback cannot be null");
boolean visible = onIsApplicationVisibleForRole(roleName, packageName);
callback.sendResult(visible ? Bundle.EMPTY : null);
@@ -171,7 +172,7 @@ public abstract class RoleControllerService extends Service {
enforceCallingPermission(Manifest.permission.MANAGE_ROLE_HOLDERS, null);
Preconditions.checkStringNotEmpty(roleName, "roleName cannot be null or empty");
- Preconditions.checkNotNull(callback, "callback cannot be null");
+ Objects.requireNonNull(callback, "callback cannot be null");
boolean visible = onIsRoleVisible(roleName);
callback.sendResult(visible ? Bundle.EMPTY : null);
diff --git a/core/java/android/app/role/RoleManager.java b/core/java/android/app/role/RoleManager.java
index bb04a2e52712..61eeacc7fd86 100644
--- a/core/java/android/app/role/RoleManager.java
+++ b/core/java/android/app/role/RoleManager.java
@@ -42,6 +42,7 @@ import com.android.internal.util.Preconditions;
import com.android.internal.util.function.pooled.PooledLambda;
import java.util.List;
+import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
@@ -284,7 +285,7 @@ public final class RoleManager {
@TestApi
public List<String> getRoleHoldersAsUser(@NonNull String roleName, @NonNull UserHandle user) {
Preconditions.checkStringNotEmpty(roleName, "roleName cannot be null or empty");
- Preconditions.checkNotNull(user, "user cannot be null");
+ Objects.requireNonNull(user, "user cannot be null");
try {
return mService.getRoleHoldersAsUser(roleName, user.getIdentifier());
} catch (RemoteException e) {
@@ -321,9 +322,9 @@ public final class RoleManager {
@CallbackExecutor @NonNull Executor executor, @NonNull Consumer<Boolean> callback) {
Preconditions.checkStringNotEmpty(roleName, "roleName cannot be null or empty");
Preconditions.checkStringNotEmpty(packageName, "packageName cannot be null or empty");
- Preconditions.checkNotNull(user, "user cannot be null");
- Preconditions.checkNotNull(executor, "executor cannot be null");
- Preconditions.checkNotNull(callback, "callback cannot be null");
+ Objects.requireNonNull(user, "user cannot be null");
+ Objects.requireNonNull(executor, "executor cannot be null");
+ Objects.requireNonNull(callback, "callback cannot be null");
try {
mService.addRoleHolderAsUser(roleName, packageName, flags, user.getIdentifier(),
createRemoteCallback(executor, callback));
@@ -360,9 +361,9 @@ public final class RoleManager {
@CallbackExecutor @NonNull Executor executor, @NonNull Consumer<Boolean> callback) {
Preconditions.checkStringNotEmpty(roleName, "roleName cannot be null or empty");
Preconditions.checkStringNotEmpty(packageName, "packageName cannot be null or empty");
- Preconditions.checkNotNull(user, "user cannot be null");
- Preconditions.checkNotNull(executor, "executor cannot be null");
- Preconditions.checkNotNull(callback, "callback cannot be null");
+ Objects.requireNonNull(user, "user cannot be null");
+ Objects.requireNonNull(executor, "executor cannot be null");
+ Objects.requireNonNull(callback, "callback cannot be null");
try {
mService.removeRoleHolderAsUser(roleName, packageName, flags, user.getIdentifier(),
createRemoteCallback(executor, callback));
@@ -397,9 +398,9 @@ public final class RoleManager {
@NonNull UserHandle user, @CallbackExecutor @NonNull Executor executor,
@NonNull Consumer<Boolean> callback) {
Preconditions.checkStringNotEmpty(roleName, "roleName cannot be null or empty");
- Preconditions.checkNotNull(user, "user cannot be null");
- Preconditions.checkNotNull(executor, "executor cannot be null");
- Preconditions.checkNotNull(callback, "callback cannot be null");
+ Objects.requireNonNull(user, "user cannot be null");
+ Objects.requireNonNull(executor, "executor cannot be null");
+ Objects.requireNonNull(callback, "callback cannot be null");
try {
mService.clearRoleHoldersAsUser(roleName, flags, user.getIdentifier(),
createRemoteCallback(executor, callback));
@@ -442,9 +443,9 @@ public final class RoleManager {
@TestApi
public void addOnRoleHoldersChangedListenerAsUser(@CallbackExecutor @NonNull Executor executor,
@NonNull OnRoleHoldersChangedListener listener, @NonNull UserHandle user) {
- Preconditions.checkNotNull(executor, "executor cannot be null");
- Preconditions.checkNotNull(listener, "listener cannot be null");
- Preconditions.checkNotNull(user, "user cannot be null");
+ Objects.requireNonNull(executor, "executor cannot be null");
+ Objects.requireNonNull(listener, "listener cannot be null");
+ Objects.requireNonNull(user, "user cannot be null");
int userId = user.getIdentifier();
synchronized (mListenersLock) {
ArrayMap<OnRoleHoldersChangedListener, OnRoleHoldersChangedListenerDelegate> listeners =
@@ -488,8 +489,8 @@ public final class RoleManager {
@TestApi
public void removeOnRoleHoldersChangedListenerAsUser(
@NonNull OnRoleHoldersChangedListener listener, @NonNull UserHandle user) {
- Preconditions.checkNotNull(listener, "listener cannot be null");
- Preconditions.checkNotNull(user, "user cannot be null");
+ Objects.requireNonNull(listener, "listener cannot be null");
+ Objects.requireNonNull(user, "user cannot be null");
int userId = user.getIdentifier();
synchronized (mListenersLock) {
ArrayMap<OnRoleHoldersChangedListener, OnRoleHoldersChangedListenerDelegate> listeners =
@@ -529,7 +530,7 @@ public final class RoleManager {
@SystemApi
@TestApi
public void setRoleNamesFromController(@NonNull List<String> roleNames) {
- Preconditions.checkNotNull(roleNames, "roleNames cannot be null");
+ Objects.requireNonNull(roleNames, "roleNames cannot be null");
try {
mService.setRoleNamesFromController(roleNames);
} catch (RemoteException e) {
diff --git a/core/java/android/app/servertransaction/ActivityResultItem.java b/core/java/android/app/servertransaction/ActivityResultItem.java
index 52ec3e60a9c7..4e743caccad6 100644
--- a/core/java/android/app/servertransaction/ActivityResultItem.java
+++ b/core/java/android/app/servertransaction/ActivityResultItem.java
@@ -18,9 +18,9 @@ package android.app.servertransaction;
import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
-import android.annotation.UnsupportedAppUsage;
import android.app.ClientTransactionHandler;
import android.app.ResultInfo;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.IBinder;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/app/servertransaction/ClientTransaction.java b/core/java/android/app/servertransaction/ClientTransaction.java
index b08e5973faa2..4d2e9a503ac5 100644
--- a/core/java/android/app/servertransaction/ClientTransaction.java
+++ b/core/java/android/app/servertransaction/ClientTransaction.java
@@ -17,9 +17,9 @@
package android.app.servertransaction;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
import android.app.ClientTransactionHandler;
import android.app.IApplicationThread;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.IBinder;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/app/servertransaction/LaunchActivityItem.java b/core/java/android/app/servertransaction/LaunchActivityItem.java
index 1236e0ac7401..6d674ae7df14 100644
--- a/core/java/android/app/servertransaction/LaunchActivityItem.java
+++ b/core/java/android/app/servertransaction/LaunchActivityItem.java
@@ -18,11 +18,11 @@ package android.app.servertransaction;
import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityThread.ActivityClientRecord;
import android.app.ClientTransactionHandler;
import android.app.ProfilerInfo;
import android.app.ResultInfo;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.CompatibilityInfo;
diff --git a/core/java/android/app/servertransaction/NewIntentItem.java b/core/java/android/app/servertransaction/NewIntentItem.java
index bb775fc4a5fb..6a4996da38ca 100644
--- a/core/java/android/app/servertransaction/NewIntentItem.java
+++ b/core/java/android/app/servertransaction/NewIntentItem.java
@@ -19,8 +19,8 @@ package android.app.servertransaction;
import static android.app.servertransaction.ActivityLifecycleItem.ON_RESUME;
import static android.app.servertransaction.ActivityLifecycleItem.UNDEFINED;
-import android.annotation.UnsupportedAppUsage;
import android.app.ClientTransactionHandler;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.IBinder;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/app/slice/SliceProvider.java b/core/java/android/app/slice/SliceProvider.java
index 5e530eedd818..bd1eea51f8af 100644
--- a/core/java/android/app/slice/SliceProvider.java
+++ b/core/java/android/app/slice/SliceProvider.java
@@ -515,8 +515,8 @@ public abstract class SliceProvider extends ContentProvider {
public static PendingIntent createPermissionIntent(Context context, Uri sliceUri,
String callingPackage) {
Intent intent = new Intent(SliceManager.ACTION_REQUEST_SLICE_PERMISSION);
- intent.setComponent(new ComponentName("com.android.systemui",
- "com.android.systemui.SlicePermissionActivity"));
+ intent.setComponent(ComponentName.unflattenFromString(context.getResources().getString(
+ com.android.internal.R.string.config_slicePermissionComponent)));
intent.putExtra(EXTRA_BIND_URI, sliceUri);
intent.putExtra(EXTRA_PKG, callingPackage);
intent.putExtra(EXTRA_PROVIDER_PKG, context.getPackageName());
diff --git a/core/java/android/app/timedetector/ManualTimeSuggestion.java b/core/java/android/app/timedetector/ManualTimeSuggestion.java
index 471606da4d75..55f92be14cd0 100644
--- a/core/java/android/app/timedetector/ManualTimeSuggestion.java
+++ b/core/java/android/app/timedetector/ManualTimeSuggestion.java
@@ -56,6 +56,7 @@ public final class ManualTimeSuggestion implements Parcelable {
public ManualTimeSuggestion(@NonNull TimestampedValue<Long> utcTime) {
mUtcTime = Objects.requireNonNull(utcTime);
+ Objects.requireNonNull(utcTime.getValue());
}
private static ManualTimeSuggestion createFromParcel(Parcel in) {
diff --git a/core/java/android/app/timedetector/PhoneTimeSuggestion.java b/core/java/android/app/timedetector/PhoneTimeSuggestion.java
index dd02af7a3ac7..4a89a1245473 100644
--- a/core/java/android/app/timedetector/PhoneTimeSuggestion.java
+++ b/core/java/android/app/timedetector/PhoneTimeSuggestion.java
@@ -166,7 +166,12 @@ public final class PhoneTimeSuggestion implements Parcelable {
}
/** Returns the builder for call chaining. */
- public Builder setUtcTime(TimestampedValue<Long> utcTime) {
+ public Builder setUtcTime(@Nullable TimestampedValue<Long> utcTime) {
+ if (utcTime != null) {
+ // utcTime can be null, but the value it holds cannot.
+ Objects.requireNonNull(utcTime.getValue());
+ }
+
mUtcTime = utcTime;
return this;
}
diff --git a/core/java/android/app/trust/TrustManager.java b/core/java/android/app/trust/TrustManager.java
index 27abdcfbefc9..65b2775fd66b 100644
--- a/core/java/android/app/trust/TrustManager.java
+++ b/core/java/android/app/trust/TrustManager.java
@@ -19,7 +19,7 @@ package android.app.trust;
import android.Manifest;
import android.annotation.RequiresPermission;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.hardware.biometrics.BiometricSourceType;
import android.os.Handler;
diff --git a/core/java/android/app/usage/ConfigurationStats.java b/core/java/android/app/usage/ConfigurationStats.java
index da3b76972ced..8a7107de8363 100644
--- a/core/java/android/app/usage/ConfigurationStats.java
+++ b/core/java/android/app/usage/ConfigurationStats.java
@@ -15,7 +15,7 @@
*/
package android.app.usage;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Parcel;
diff --git a/core/java/android/app/usage/IStorageStatsManager.aidl b/core/java/android/app/usage/IStorageStatsManager.aidl
index 7eacc8996bb9..b5036da33a95 100644
--- a/core/java/android/app/usage/IStorageStatsManager.aidl
+++ b/core/java/android/app/usage/IStorageStatsManager.aidl
@@ -18,6 +18,8 @@ package android.app.usage;
import android.app.usage.StorageStats;
import android.app.usage.ExternalStorageStats;
+import android.content.pm.ParceledListSlice;
+import android.os.storage.CrateInfo;
/** {@hide} */
interface IStorageStatsManager {
@@ -31,4 +33,10 @@ interface IStorageStatsManager {
StorageStats queryStatsForUid(String volumeUuid, int uid, String callingPackage);
StorageStats queryStatsForUser(String volumeUuid, int userId, String callingPackage);
ExternalStorageStats queryExternalStatsForUser(String volumeUuid, int userId, String callingPackage);
+ ParceledListSlice /* CrateInfo */ queryCratesForPackage(String volumeUuid, String packageName,
+ int userId, String callingPackage);
+ ParceledListSlice /* CrateInfo */ queryCratesForUid(String volumeUuid, int uid,
+ String callingPackage);
+ ParceledListSlice /* CrateInfo */ queryCratesForUser(String volumeUuid, int userId,
+ String callingPackage);
}
diff --git a/core/java/android/app/usage/NetworkStatsManager.java b/core/java/android/app/usage/NetworkStatsManager.java
index 6bade901826a..74129702b487 100644
--- a/core/java/android/app/usage/NetworkStatsManager.java
+++ b/core/java/android/app/usage/NetworkStatsManager.java
@@ -21,8 +21,8 @@ import static com.android.internal.util.Preconditions.checkNotNull;
import android.annotation.Nullable;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.usage.NetworkStats.Bucket;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DataUsageRequest;
diff --git a/core/java/android/app/usage/StorageStatsManager.java b/core/java/android/app/usage/StorageStatsManager.java
index a86c27a03358..eecf0920fd24 100644
--- a/core/java/android/app/usage/StorageStatsManager.java
+++ b/core/java/android/app/usage/StorageStatsManager.java
@@ -20,6 +20,7 @@ import static android.os.storage.StorageManager.convert;
import android.annotation.BytesLong;
import android.annotation.NonNull;
+import android.annotation.RequiresPermission;
import android.annotation.SystemService;
import android.annotation.TestApi;
import android.annotation.WorkerThread;
@@ -27,15 +28,19 @@ import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
+import android.content.pm.ParceledListSlice;
import android.os.ParcelableException;
import android.os.RemoteException;
import android.os.UserHandle;
+import android.os.storage.CrateInfo;
import android.os.storage.StorageManager;
import com.android.internal.util.Preconditions;
import java.io.File;
import java.io.IOException;
+import java.util.Collection;
+import java.util.Objects;
import java.util.UUID;
/**
@@ -347,4 +352,100 @@ public class StorageStatsManager {
throw e.rethrowFromSystemServer();
}
}
+
+ /**
+ * Return all of crate information for the specified storageUuid, packageName, and
+ * userHandle.
+ *
+ * @param storageUuid the UUID of the storage volume you're interested in,
+ * such as {@link StorageManager#UUID_DEFAULT}.
+ * @param uid the uid you're interested in.
+ * @return the collection of crate information.
+ * @throws PackageManager.NameNotFoundException when the package name is not found.
+ * @throws IOException cause by IO, not support, or the other reasons.
+ * @hide
+ */
+ @TestApi
+ @WorkerThread
+ @NonNull
+ public Collection<CrateInfo> queryCratesForUid(@NonNull UUID storageUuid,
+ int uid) throws IOException, PackageManager.NameNotFoundException {
+ try {
+ ParceledListSlice<CrateInfo> crateInfoList =
+ mService.queryCratesForUid(convert(storageUuid), uid,
+ mContext.getOpPackageName());
+ return Objects.requireNonNull(crateInfoList).getList();
+ } catch (ParcelableException e) {
+ e.maybeRethrow(PackageManager.NameNotFoundException.class);
+ e.maybeRethrow(IOException.class);
+ throw new RuntimeException(e);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Return all of crates information for the specified storageUuid, packageName, and
+ * userHandle.
+ *
+ * @param storageUuid the UUID of the storage volume you're interested in,
+ * such as {@link StorageManager#UUID_DEFAULT}.
+ * @param packageName the package name you're interested in.
+ * @param user the user you're interested in.
+ * @return the collection of crate information.
+ * @throws PackageManager.NameNotFoundException when the package name is not found.
+ * @throws IOException cause by IO, not support, or the other reasons.
+ * @hide
+ */
+ @WorkerThread
+ @TestApi
+ @NonNull
+ public Collection<CrateInfo> queryCratesForPackage(@NonNull UUID storageUuid,
+ @NonNull String packageName, @NonNull UserHandle user)
+ throws PackageManager.NameNotFoundException, IOException {
+ try {
+ ParceledListSlice<CrateInfo> crateInfoList =
+ mService.queryCratesForPackage(convert(storageUuid), packageName,
+ user.getIdentifier(), mContext.getOpPackageName());
+ return Objects.requireNonNull(crateInfoList).getList();
+ } catch (ParcelableException e) {
+ e.maybeRethrow(PackageManager.NameNotFoundException.class);
+ e.maybeRethrow(IOException.class);
+ throw new RuntimeException(e);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Return all of crate information for the specified storageUuid, packageName, and
+ * userHandle.
+ *
+ * @param storageUuid the UUID of the storage volume you're interested in,
+ * such as {@link StorageManager#UUID_DEFAULT}.
+ * @param user the user you're interested in.
+ * @return the collection of crate information.
+ * @throws PackageManager.NameNotFoundException when the package name is not found.
+ * @throws IOException cause by IO, not support, or the other reasons.
+ * @hide
+ */
+ @WorkerThread
+ @TestApi
+ @RequiresPermission(android.Manifest.permission.MANAGE_CRATES)
+ @NonNull
+ public Collection<CrateInfo> queryCratesForUser(@NonNull UUID storageUuid,
+ @NonNull UserHandle user) throws PackageManager.NameNotFoundException, IOException {
+ try {
+ ParceledListSlice<CrateInfo> crateInfoList =
+ mService.queryCratesForUser(convert(storageUuid), user.getIdentifier(),
+ mContext.getOpPackageName());
+ return Objects.requireNonNull(crateInfoList).getList();
+ } catch (ParcelableException e) {
+ e.maybeRethrow(PackageManager.NameNotFoundException.class);
+ e.maybeRethrow(IOException.class);
+ throw new RuntimeException(e);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
}
diff --git a/core/java/android/app/usage/UsageEvents.java b/core/java/android/app/usage/UsageEvents.java
index 4bf9c04dfade..d840c1cc7248 100644
--- a/core/java/android/app/usage/UsageEvents.java
+++ b/core/java/android/app/usage/UsageEvents.java
@@ -18,7 +18,7 @@ package android.app.usage;
import android.annotation.IntDef;
import android.annotation.Nullable;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Parcel;
diff --git a/core/java/android/app/usage/UsageStats.java b/core/java/android/app/usage/UsageStats.java
index 9d43dd34d558..d06baed1a35d 100644
--- a/core/java/android/app/usage/UsageStats.java
+++ b/core/java/android/app/usage/UsageStats.java
@@ -29,7 +29,7 @@ import static android.app.usage.UsageEvents.Event.FOREGROUND_SERVICE_STOP;
import static android.app.usage.UsageEvents.Event.ROLLOVER_FOREGROUND_SERVICE;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
diff --git a/core/java/android/app/usage/UsageStatsManager.java b/core/java/android/app/usage/UsageStatsManager.java
index fb5645a2137f..176a181965ed 100644
--- a/core/java/android/app/usage/UsageStatsManager.java
+++ b/core/java/android/app/usage/UsageStatsManager.java
@@ -23,9 +23,9 @@ import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.Activity;
import android.app.PendingIntent;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.ParceledListSlice;
import android.os.Build;
@@ -1125,8 +1125,11 @@ public final class UsageStatsManager {
/**
* Inform usage stats that the carrier privileged apps access rules have changed.
+ * <p> The caller must have {@link android.Manifest.permission#BIND_CARRIER_SERVICES} </p>
* @hide
*/
+ @SystemApi
+ @RequiresPermission(android.Manifest.permission.BIND_CARRIER_SERVICES)
public void onCarrierPrivilegedAppsChanged() {
try {
mService.onCarrierPrivilegedAppsChanged();
diff --git a/core/java/android/appwidget/AppWidgetHost.java b/core/java/android/appwidget/AppWidgetHost.java
index c20cb253a6be..467b2fba1102 100644
--- a/core/java/android/appwidget/AppWidgetHost.java
+++ b/core/java/android/appwidget/AppWidgetHost.java
@@ -18,8 +18,8 @@ package android.appwidget;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
import android.app.Activity;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.IntentSender;
diff --git a/core/java/android/appwidget/AppWidgetHostView.java b/core/java/android/appwidget/AppWidgetHostView.java
index 85f0e2342412..09d56ec70e56 100644
--- a/core/java/android/appwidget/AppWidgetHostView.java
+++ b/core/java/android/appwidget/AppWidgetHostView.java
@@ -16,9 +16,9 @@
package android.appwidget;
-import android.annotation.UnsupportedAppUsage;
import android.app.Activity;
import android.app.ActivityOptions;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
diff --git a/core/java/android/appwidget/AppWidgetManager.java b/core/java/android/appwidget/AppWidgetManager.java
index dbc1c199cb4d..6dea1c69ce86 100644
--- a/core/java/android/appwidget/AppWidgetManager.java
+++ b/core/java/android/appwidget/AppWidgetManager.java
@@ -23,9 +23,9 @@ import android.annotation.RequiresFeature;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
import android.app.IServiceConnection;
import android.app.PendingIntent;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
diff --git a/core/java/android/appwidget/AppWidgetProviderInfo.java b/core/java/android/appwidget/AppWidgetProviderInfo.java
index 2faa9007fc29..130a20dfb07b 100644
--- a/core/java/android/appwidget/AppWidgetProviderInfo.java
+++ b/core/java/android/appwidget/AppWidgetProviderInfo.java
@@ -18,8 +18,8 @@ package android.appwidget;
import android.annotation.IntDef;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
import android.app.PendingIntent;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ActivityInfo;
diff --git a/core/java/android/bluetooth/BluetoothA2dp.java b/core/java/android/bluetooth/BluetoothA2dp.java
index 64df0e84f6dc..d8c653c6d0d5 100644
--- a/core/java/android/bluetooth/BluetoothA2dp.java
+++ b/core/java/android/bluetooth/BluetoothA2dp.java
@@ -24,7 +24,7 @@ import android.annotation.RequiresPermission;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.Binder;
import android.os.Build;
diff --git a/core/java/android/bluetooth/BluetoothA2dpSink.java b/core/java/android/bluetooth/BluetoothA2dpSink.java
index cf3367602aa9..8993de0939e6 100755
--- a/core/java/android/bluetooth/BluetoothA2dpSink.java
+++ b/core/java/android/bluetooth/BluetoothA2dpSink.java
@@ -17,9 +17,11 @@
package android.bluetooth;
import android.Manifest;
+import android.annotation.Nullable;
import android.annotation.RequiresPermission;
+import android.annotation.SuppressLint;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.Binder;
import android.os.IBinder;
@@ -39,6 +41,7 @@ import java.util.List;
*
* @hide
*/
+@SystemApi
public final class BluetoothA2dpSink implements BluetoothProfile {
private static final String TAG = "BluetoothA2dpSink";
private static final boolean DBG = true;
@@ -59,71 +62,14 @@ public final class BluetoothA2dpSink implements BluetoothProfile {
* {@link #STATE_DISCONNECTED}, {@link #STATE_CONNECTING},
* {@link #STATE_CONNECTED}, {@link #STATE_DISCONNECTING}.
*
- * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission to
- * receive.
+ * @hide
*/
+ @SystemApi
+ @SuppressLint("ActionValue")
+ @RequiresPermission(Manifest.permission.BLUETOOTH)
public static final String ACTION_CONNECTION_STATE_CHANGED =
"android.bluetooth.a2dp-sink.profile.action.CONNECTION_STATE_CHANGED";
- /**
- * Intent used to broadcast the change in the Playing state of the A2DP Sink
- * profile.
- *
- * <p>This intent will have 3 extras:
- * <ul>
- * <li> {@link #EXTRA_STATE} - The current state of the profile. </li>
- * <li> {@link #EXTRA_PREVIOUS_STATE}- The previous state of the profile. </li>
- * <li> {@link BluetoothDevice#EXTRA_DEVICE} - The remote device. </li>
- * </ul>
- *
- * <p>{@link #EXTRA_STATE} or {@link #EXTRA_PREVIOUS_STATE} can be any of
- * {@link #STATE_PLAYING}, {@link #STATE_NOT_PLAYING},
- *
- * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission to
- * receive.
- */
- public static final String ACTION_PLAYING_STATE_CHANGED =
- "android.bluetooth.a2dp-sink.profile.action.PLAYING_STATE_CHANGED";
-
- /**
- * A2DP sink device is streaming music. This state can be one of
- * {@link #EXTRA_STATE} or {@link #EXTRA_PREVIOUS_STATE} of
- * {@link #ACTION_PLAYING_STATE_CHANGED} intent.
- */
- public static final int STATE_PLAYING = 10;
-
- /**
- * A2DP sink device is NOT streaming music. This state can be one of
- * {@link #EXTRA_STATE} or {@link #EXTRA_PREVIOUS_STATE} of
- * {@link #ACTION_PLAYING_STATE_CHANGED} intent.
- */
- public static final int STATE_NOT_PLAYING = 11;
-
- /**
- * Intent used to broadcast the change in the Playing state of the A2DP Sink
- * profile.
- *
- * <p>This intent will have 3 extras:
- * <ul>
- * <li> {@link #EXTRA_AUDIO_CONFIG} - The audio configuration for the remote device. </li>
- * <li> {@link BluetoothDevice#EXTRA_DEVICE} - The remote device. </li>
- * </ul>
- *
- * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission to
- * receive.
- */
- public static final String ACTION_AUDIO_CONFIG_CHANGED =
- "android.bluetooth.a2dp-sink.profile.action.AUDIO_CONFIG_CHANGED";
-
- /**
- * Extra for the {@link #ACTION_AUDIO_CONFIG_CHANGED} intent.
- *
- * This extra represents the current audio configuration of the A2DP source device.
- * {@see BluetoothAudioConfig}
- */
- public static final String EXTRA_AUDIO_CONFIG =
- "android.bluetooth.a2dp-sink.profile.extra.AUDIO_CONFIG";
-
private BluetoothAdapter mAdapter;
private final BluetoothProfileConnector<IBluetoothA2dpSink> mProfileConnector =
new BluetoothProfileConnector(this, BluetoothProfile.A2DP_SINK,
@@ -170,13 +116,11 @@ public final class BluetoothA2dpSink implements BluetoothProfile {
* the state. Users can get the connection state of the profile
* from this intent.
*
- * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
- * permission.
- *
* @param device Remote Bluetooth Device
* @return false on immediate error, true otherwise
* @hide
*/
+ @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
public boolean connect(BluetoothDevice device) {
if (DBG) log("connect(" + device + ")");
final IBluetoothA2dpSink service = getService();
@@ -210,14 +154,12 @@ public final class BluetoothA2dpSink implements BluetoothProfile {
* {@link #STATE_DISCONNECTING} can be used to distinguish between the
* two scenarios.
*
- * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
- * permission.
- *
* @param device Remote Bluetooth Device
* @return false on immediate error, true otherwise
* @hide
*/
@UnsupportedAppUsage
+ @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
public boolean disconnect(BluetoothDevice device) {
if (DBG) log("disconnect(" + device + ")");
final IBluetoothA2dpSink service = getService();
@@ -235,6 +177,8 @@ public final class BluetoothA2dpSink implements BluetoothProfile {
/**
* {@inheritDoc}
+ *
+ * @hide
*/
@Override
public List<BluetoothDevice> getConnectedDevices() {
@@ -254,6 +198,8 @@ public final class BluetoothA2dpSink implements BluetoothProfile {
/**
* {@inheritDoc}
+ *
+ * @hide
*/
@Override
public List<BluetoothDevice> getDevicesMatchingConnectionStates(int[] states) {
@@ -273,6 +219,8 @@ public final class BluetoothA2dpSink implements BluetoothProfile {
/**
* {@inheritDoc}
+ *
+ * @hide
*/
@Override
public int getConnectionState(BluetoothDevice device) {
@@ -300,6 +248,8 @@ public final class BluetoothA2dpSink implements BluetoothProfile {
* @return audio configuration for the device, or null
*
* {@see BluetoothAudioConfig}
+ *
+ * @hide
*/
public BluetoothAudioConfig getAudioConfig(BluetoothDevice device) {
if (VDBG) log("getAudioConfig(" + device + ")");
@@ -347,7 +297,7 @@ public final class BluetoothA2dpSink implements BluetoothProfile {
*/
@SystemApi
@RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
- public boolean setConnectionPolicy(BluetoothDevice device, int connectionPolicy) {
+ public boolean setConnectionPolicy(@Nullable BluetoothDevice device, int connectionPolicy) {
if (DBG) log("setConnectionPolicy(" + device + ", " + connectionPolicy + ")");
final IBluetoothA2dpSink service = getService();
if (service != null && isEnabled() && isValidDevice(device)) {
@@ -395,7 +345,7 @@ public final class BluetoothA2dpSink implements BluetoothProfile {
*/
@SystemApi
@RequiresPermission(Manifest.permission.BLUETOOTH)
- public int getConnectionPolicy(BluetoothDevice device) {
+ public int getConnectionPolicy(@Nullable BluetoothDevice device) {
if (VDBG) log("getConnectionPolicy(" + device + ")");
final IBluetoothA2dpSink service = getService();
if (service != null && isEnabled() && isValidDevice(device)) {
@@ -411,13 +361,16 @@ public final class BluetoothA2dpSink implements BluetoothProfile {
}
/**
- * Check if A2DP profile is streaming music.
- *
- * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
+ * Check if audio is playing on the bluetooth device (A2DP profile is streaming music).
*
* @param device BluetoothDevice device
+ * @return true if audio is playing (A2dp is streaming music), false otherwise
+ *
+ * @hide
*/
- public boolean isA2dpPlaying(BluetoothDevice device) {
+ @SystemApi
+ @RequiresPermission(Manifest.permission.BLUETOOTH)
+ public boolean isAudioPlaying(@Nullable BluetoothDevice device) {
final IBluetoothA2dpSink service = getService();
if (service != null && isEnabled() && isValidDevice(device)) {
try {
@@ -448,9 +401,9 @@ public final class BluetoothA2dpSink implements BluetoothProfile {
return "connected";
case STATE_DISCONNECTING:
return "disconnecting";
- case STATE_PLAYING:
+ case BluetoothA2dp.STATE_PLAYING:
return "playing";
- case STATE_NOT_PLAYING:
+ case BluetoothA2dp.STATE_NOT_PLAYING:
return "not playing";
default:
return "<unknown state " + state + ">";
diff --git a/core/java/android/bluetooth/BluetoothAdapter.java b/core/java/android/bluetooth/BluetoothAdapter.java
index 3f8cb627e382..b1b6f0d61f9f 100644
--- a/core/java/android/bluetooth/BluetoothAdapter.java
+++ b/core/java/android/bluetooth/BluetoothAdapter.java
@@ -25,7 +25,6 @@ import android.annotation.RequiresPermission;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityThread;
import android.bluetooth.BluetoothProfile.ConnectionPolicy;
import android.bluetooth.le.BluetoothLeAdvertiser;
@@ -36,6 +35,7 @@ import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanRecord;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.BatteryStats;
import android.os.Binder;
@@ -847,7 +847,8 @@ public final class BluetoothAdapter {
}
synchronized (mLock) {
if (sBluetoothLeScanner == null) {
- sBluetoothLeScanner = new BluetoothLeScanner(mManagerService);
+ sBluetoothLeScanner = new BluetoothLeScanner(mManagerService, getOpPackageName(),
+ getFeatureId());
}
}
return sBluetoothLeScanner;
@@ -1637,6 +1638,15 @@ public final class BluetoothAdapter {
return ActivityThread.currentOpPackageName();
}
+ private String getFeatureId() {
+ // Workaround for legacy API for getting a BluetoothAdapter not
+ // passing a context
+ if (mContext != null) {
+ return mContext.getFeatureId();
+ }
+ return null;
+ }
+
/**
* Start the remote device discovery process.
* <p>The discovery process usually involves an inquiry scan of about 12
@@ -1674,7 +1684,7 @@ public final class BluetoothAdapter {
try {
mServiceLock.readLock().lock();
if (mService != null) {
- return mService.startDiscovery(getOpPackageName());
+ return mService.startDiscovery(getOpPackageName(), getFeatureId());
}
} catch (RemoteException e) {
Log.e(TAG, "", e);
diff --git a/core/java/android/bluetooth/BluetoothClass.java b/core/java/android/bluetooth/BluetoothClass.java
index 260e2fb1b80c..905b0ceec4ee 100755
--- a/core/java/android/bluetooth/BluetoothClass.java
+++ b/core/java/android/bluetooth/BluetoothClass.java
@@ -17,7 +17,7 @@
package android.bluetooth;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/bluetooth/BluetoothCodecConfig.java b/core/java/android/bluetooth/BluetoothCodecConfig.java
index 08d0797997b5..93e76fa5ba7d 100644
--- a/core/java/android/bluetooth/BluetoothCodecConfig.java
+++ b/core/java/android/bluetooth/BluetoothCodecConfig.java
@@ -19,7 +19,7 @@ package android.bluetooth;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/bluetooth/BluetoothDevice.java b/core/java/android/bluetooth/BluetoothDevice.java
index 49187dcde342..9fe4dd66b874 100644
--- a/core/java/android/bluetooth/BluetoothDevice.java
+++ b/core/java/android/bluetooth/BluetoothDevice.java
@@ -17,13 +17,14 @@
package android.bluetooth;
import android.Manifest;
+import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.Handler;
import android.os.Parcel;
@@ -33,8 +34,12 @@ import android.os.Process;
import android.os.RemoteException;
import android.util.Log;
+import com.android.internal.annotations.VisibleForTesting;
+
import java.io.IOException;
import java.io.UnsupportedEncodingException;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
import java.util.UUID;
/**
@@ -771,6 +776,13 @@ public final class BluetoothDevice implements Parcelable {
@UnsupportedAppUsage
public static final String EXTRA_SDP_SEARCH_STATUS =
"android.bluetooth.device.extra.SDP_SEARCH_STATUS";
+
+ /** @hide */
+ @IntDef(prefix = "ACCESS_", value = {ACCESS_UNKNOWN,
+ ACCESS_ALLOWED, ACCESS_REJECTED})
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface AccessPermission{}
+
/**
* For {@link #getPhonebookAccessPermission}, {@link #setPhonebookAccessPermission},
* {@link #getMessageAccessPermission} and {@link #setMessageAccessPermission}.
@@ -1096,15 +1108,14 @@ public final class BluetoothDevice implements Parcelable {
/**
* Get the most recent identified battery level of this Bluetooth device
- * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
*
* @return Battery level in percents from 0 to 100, or {@link #BATTERY_LEVEL_UNKNOWN} if
* Bluetooth is disabled, or device is disconnected, or does not have any battery reporting
* service, or return value is invalid
* @hide
*/
+ @SystemApi
@RequiresPermission(Manifest.permission.BLUETOOTH)
- @UnsupportedAppUsage
public int getBatteryLevel() {
final IBluetooth service = sService;
if (service == null) {
@@ -1187,8 +1198,15 @@ public final class BluetoothDevice implements Parcelable {
return false;
}
- /** @hide */
- @UnsupportedAppUsage
+ /**
+ * Gets whether bonding was initiated locally
+ *
+ * @return true if bonding is initiated locally, false otherwise
+ *
+ * @hide
+ */
+ @SystemApi
+ @RequiresPermission(Manifest.permission.BLUETOOTH)
public boolean isBondingInitiatedLocally() {
final IBluetooth service = sService;
if (service == null) {
@@ -1480,15 +1498,20 @@ public final class BluetoothDevice implements Parcelable {
return false;
}
- /** @hide */
- @UnsupportedAppUsage
- public boolean setPasskey(int passkey) {
- //TODO(BT)
- /*
- try {
- return sService.setPasskey(this, true, 4, passkey);
- } catch (RemoteException e) {Log.e(TAG, "", e);}*/
- return false;
+ /**
+ * Set the pin during pairing when the pairing method is {@link #PAIRING_VARIANT_PIN}
+ *
+ * @return true pin has been set false for error
+ * @hide
+ */
+ @SystemApi
+ @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
+ public boolean setPin(@Nullable String pin) {
+ byte[] pinBytes = convertPinToBytes(pin);
+ if (pinBytes == null) {
+ return false;
+ }
+ return setPin(pinBytes);
}
/**
@@ -1511,22 +1534,18 @@ public final class BluetoothDevice implements Parcelable {
return false;
}
- /** @hide */
- public boolean setRemoteOutOfBandData() {
- // TODO(BT)
- /*
- try {
- return sService.setRemoteOutOfBandData(this);
- } catch (RemoteException e) {Log.e(TAG, "", e);}*/
- return false;
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public boolean cancelPairingUserInput() {
+ /**
+ * Cancels pairing to this device
+ *
+ * @return true if pairing cancelled successfully, false otherwise
+ *
+ * @hide
+ */
+ @SystemApi
+ public boolean cancelPairing() {
final IBluetooth service = sService;
if (service == null) {
- Log.e(TAG, "BT not enabled. Cannot create pairing user input");
+ Log.e(TAG, "BT not enabled. Cannot cancel pairing");
return false;
}
try {
@@ -1537,17 +1556,6 @@ public final class BluetoothDevice implements Parcelable {
return false;
}
- /** @hide */
- @UnsupportedAppUsage
- public boolean isBluetoothDock() {
- // TODO(BT)
- /*
- try {
- return sService.isBluetoothDock(this);
- } catch (RemoteException e) {Log.e(TAG, "", e);}*/
- return false;
- }
-
boolean isBluetoothEnabled() {
boolean ret = false;
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
@@ -1558,13 +1566,14 @@ public final class BluetoothDevice implements Parcelable {
}
/**
- * Requires {@link android.Manifest.permission#BLUETOOTH}.
+ * Gets whether the phonebook access is allowed for this bluetooth device
*
* @return Whether the phonebook access is allowed to this device. Can be {@link
* #ACCESS_UNKNOWN}, {@link #ACCESS_ALLOWED} or {@link #ACCESS_REJECTED}.
* @hide
*/
- @UnsupportedAppUsage
+ @SystemApi
+ @RequiresPermission(Manifest.permission.BLUETOOTH)
public int getPhonebookAccessPermission() {
final IBluetooth service = sService;
if (service == null) {
@@ -1667,14 +1676,14 @@ public final class BluetoothDevice implements Parcelable {
}
/**
- * Requires {@link android.Manifest.permission#BLUETOOTH}.
+ * Gets whether message access is allowed to this bluetooth device
*
- * @return Whether the message access is allowed to this device. Can be {@link #ACCESS_UNKNOWN},
- * {@link #ACCESS_ALLOWED} or {@link #ACCESS_REJECTED}.
+ * @return Whether the message access is allowed to this device.
* @hide
*/
- @UnsupportedAppUsage
- public int getMessageAccessPermission() {
+ @SystemApi
+ @RequiresPermission(Manifest.permission.BLUETOOTH)
+ public @AccessPermission int getMessageAccessPermission() {
final IBluetooth service = sService;
if (service == null) {
return ACCESS_UNKNOWN;
@@ -1689,15 +1698,18 @@ public final class BluetoothDevice implements Parcelable {
/**
* Sets whether the message access is allowed to this device.
- * <p>Requires {@link android.Manifest.permission#BLUETOOTH_PRIVILEGED}.
*
- * @param value Can be {@link #ACCESS_UNKNOWN}, {@link #ACCESS_ALLOWED} or {@link
- * #ACCESS_REJECTED}.
+ * @param value is the value we are setting the message access permission to
* @return Whether the value has been successfully set.
* @hide
*/
- @UnsupportedAppUsage
- public boolean setMessageAccessPermission(int value) {
+ @SystemApi
+ @RequiresPermission(Manifest.permission.BLUETOOTH_PRIVILEGED)
+ public boolean setMessageAccessPermission(@AccessPermission int value) {
+ // Validates param value is one of the accepted constants
+ if (value != ACCESS_ALLOWED && value != ACCESS_REJECTED && value != ACCESS_UNKNOWN) {
+ throw new IllegalArgumentException(value + "is not a valid AccessPermission value");
+ }
final IBluetooth service = sService;
if (service == null) {
return false;
@@ -1711,13 +1723,14 @@ public final class BluetoothDevice implements Parcelable {
}
/**
- * Requires {@link android.Manifest.permission#BLUETOOTH}.
+ * Gets whether sim access is allowed for this bluetooth device
*
- * @return Whether the Sim access is allowed to this device. Can be {@link #ACCESS_UNKNOWN},
- * {@link #ACCESS_ALLOWED} or {@link #ACCESS_REJECTED}.
+ * @return Whether the Sim access is allowed to this device.
* @hide
*/
- public int getSimAccessPermission() {
+ @SystemApi
+ @RequiresPermission(Manifest.permission.BLUETOOTH)
+ public @AccessPermission int getSimAccessPermission() {
final IBluetooth service = sService;
if (service == null) {
return ACCESS_UNKNOWN;
@@ -1732,14 +1745,14 @@ public final class BluetoothDevice implements Parcelable {
/**
* Sets whether the Sim access is allowed to this device.
- * <p>Requires {@link android.Manifest.permission#BLUETOOTH_PRIVILEGED}.
*
* @param value Can be {@link #ACCESS_UNKNOWN}, {@link #ACCESS_ALLOWED} or {@link
* #ACCESS_REJECTED}.
* @return Whether the value has been successfully set.
* @hide
*/
- @UnsupportedAppUsage
+ @SystemApi
+ @RequiresPermission(Manifest.permission.BLUETOOTH_PRIVILEGED)
public boolean setSimAccessPermission(int value) {
final IBluetooth service = sService;
if (service == null) {
@@ -1970,7 +1983,7 @@ public final class BluetoothDevice implements Parcelable {
* @return the pin code as a UTF-8 byte array, or null if it is an invalid Bluetooth pin.
* @hide
*/
- @UnsupportedAppUsage
+ @VisibleForTesting
public static byte[] convertPinToBytes(String pin) {
if (pin == null) {
return null;
diff --git a/core/java/android/bluetooth/BluetoothGatt.java b/core/java/android/bluetooth/BluetoothGatt.java
index d616b8f92d3a..f877f04626da 100644
--- a/core/java/android/bluetooth/BluetoothGatt.java
+++ b/core/java/android/bluetooth/BluetoothGatt.java
@@ -16,7 +16,7 @@
package android.bluetooth;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.Handler;
import android.os.ParcelUuid;
diff --git a/core/java/android/bluetooth/BluetoothGattCharacteristic.java b/core/java/android/bluetooth/BluetoothGattCharacteristic.java
index edacf3e0b706..7066f470aa96 100644
--- a/core/java/android/bluetooth/BluetoothGattCharacteristic.java
+++ b/core/java/android/bluetooth/BluetoothGattCharacteristic.java
@@ -15,7 +15,7 @@
*/
package android.bluetooth;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.ParcelUuid;
import android.os.Parcelable;
diff --git a/core/java/android/bluetooth/BluetoothGattDescriptor.java b/core/java/android/bluetooth/BluetoothGattDescriptor.java
index 0783cd2b73cc..7cc2d6bc53fb 100644
--- a/core/java/android/bluetooth/BluetoothGattDescriptor.java
+++ b/core/java/android/bluetooth/BluetoothGattDescriptor.java
@@ -16,7 +16,7 @@
package android.bluetooth;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.ParcelUuid;
import android.os.Parcelable;
diff --git a/core/java/android/bluetooth/BluetoothGattService.java b/core/java/android/bluetooth/BluetoothGattService.java
index c20faf9db698..13d6d7021ec8 100644
--- a/core/java/android/bluetooth/BluetoothGattService.java
+++ b/core/java/android/bluetooth/BluetoothGattService.java
@@ -15,7 +15,7 @@
*/
package android.bluetooth;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.ParcelUuid;
import android.os.Parcelable;
diff --git a/core/java/android/bluetooth/BluetoothHeadset.java b/core/java/android/bluetooth/BluetoothHeadset.java
index 0955b103a8e8..1ba2bb5e31ad 100644
--- a/core/java/android/bluetooth/BluetoothHeadset.java
+++ b/core/java/android/bluetooth/BluetoothHeadset.java
@@ -23,7 +23,7 @@ import android.annotation.RequiresPermission;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.os.Binder;
diff --git a/core/java/android/bluetooth/BluetoothHeadsetClient.java b/core/java/android/bluetooth/BluetoothHeadsetClient.java
index 7ee29ff1c50b..6de1ffb6344e 100644
--- a/core/java/android/bluetooth/BluetoothHeadsetClient.java
+++ b/core/java/android/bluetooth/BluetoothHeadsetClient.java
@@ -19,7 +19,7 @@ package android.bluetooth;
import android.Manifest;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.Binder;
import android.os.Bundle;
diff --git a/core/java/android/bluetooth/BluetoothHeadsetClientCall.java b/core/java/android/bluetooth/BluetoothHeadsetClientCall.java
index 7165dd56a213..d1a096e605dd 100644
--- a/core/java/android/bluetooth/BluetoothHeadsetClientCall.java
+++ b/core/java/android/bluetooth/BluetoothHeadsetClientCall.java
@@ -16,7 +16,7 @@
package android.bluetooth;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
diff --git a/core/java/android/bluetooth/BluetoothHearingAid.java b/core/java/android/bluetooth/BluetoothHearingAid.java
index ead8429e4a75..83eaa728d54c 100644
--- a/core/java/android/bluetooth/BluetoothHearingAid.java
+++ b/core/java/android/bluetooth/BluetoothHearingAid.java
@@ -23,7 +23,7 @@ import android.annotation.RequiresPermission;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.Binder;
import android.os.IBinder;
@@ -335,9 +335,9 @@ public final class BluetoothHearingAid implements BluetoothProfile {
* is not active, it will be null on that position. Returns empty list on error.
* @hide
*/
- @UnsupportedAppUsage
+ @SystemApi
@RequiresPermission(Manifest.permission.BLUETOOTH)
- public List<BluetoothDevice> getActiveDevices() {
+ public @NonNull List<BluetoothDevice> getActiveDevices() {
if (VDBG) log("getActiveDevices()");
final IBluetoothHearingAid service = getService();
try {
@@ -559,8 +559,9 @@ public final class BluetoothHearingAid implements BluetoothProfile {
* @return the CustomerId of the device
* @hide
*/
+ @SystemApi
@RequiresPermission(Manifest.permission.BLUETOOTH)
- public long getHiSyncId(BluetoothDevice device) {
+ public long getHiSyncId(@Nullable BluetoothDevice device) {
if (VDBG) {
log("getCustomerId(" + device + ")");
}
diff --git a/core/java/android/bluetooth/BluetoothManager.java b/core/java/android/bluetooth/BluetoothManager.java
index adedff3e9386..7ff64663349b 100644
--- a/core/java/android/bluetooth/BluetoothManager.java
+++ b/core/java/android/bluetooth/BluetoothManager.java
@@ -22,7 +22,9 @@ import android.annotation.RequiresPermission;
import android.annotation.SystemService;
import android.content.Context;
import android.content.pm.PackageManager;
+import android.os.IBinder;
import android.os.RemoteException;
+import android.os.ServiceManager;
import android.util.Log;
import java.util.ArrayList;
@@ -60,22 +62,34 @@ public final class BluetoothManager {
* @hide
*/
public BluetoothManager(Context context) {
- context = context.getApplicationContext();
- if (context == null) {
- throw new IllegalArgumentException(
- "context not associated with any application (using a mock context?)");
+ if (context.getFeatureId() == null) {
+ context = context.getApplicationContext();
+ if (context == null) {
+ throw new IllegalArgumentException(
+ "context not associated with any application (using a mock context?)");
+ }
+
+ mAdapter = BluetoothAdapter.getDefaultAdapter();
+ } else {
+ IBinder b = ServiceManager.getService(BluetoothAdapter.BLUETOOTH_MANAGER_SERVICE);
+ if (b != null) {
+ mAdapter = new BluetoothAdapter(IBluetoothManager.Stub.asInterface(b));
+ } else {
+ Log.e(TAG, "Bluetooth binder is null");
+ mAdapter = null;
+ }
}
- // Legacy api - getDefaultAdapter does not take in the context
- mAdapter = BluetoothAdapter.getDefaultAdapter();
+
+ // Context is not initialized in constructor
if (mAdapter != null) {
mAdapter.setContext(context);
}
}
/**
- * Get the default BLUETOOTH Adapter for this device.
+ * Get the BLUETOOTH Adapter for this device.
*
- * @return the default BLUETOOTH Adapter
+ * @return the BLUETOOTH Adapter
*/
public BluetoothAdapter getAdapter() {
return mAdapter;
diff --git a/core/java/android/bluetooth/BluetoothMap.java b/core/java/android/bluetooth/BluetoothMap.java
index 979dfd4e3ba5..917e7fa04e4c 100644
--- a/core/java/android/bluetooth/BluetoothMap.java
+++ b/core/java/android/bluetooth/BluetoothMap.java
@@ -19,7 +19,7 @@ package android.bluetooth;
import android.Manifest;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.Binder;
import android.os.IBinder;
diff --git a/core/java/android/bluetooth/BluetoothMapClient.java b/core/java/android/bluetooth/BluetoothMapClient.java
index 0ec473c85adc..0aa5aac5d8f6 100644
--- a/core/java/android/bluetooth/BluetoothMapClient.java
+++ b/core/java/android/bluetooth/BluetoothMapClient.java
@@ -19,8 +19,8 @@ package android.bluetooth;
import android.Manifest;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.PendingIntent;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.net.Uri;
import android.os.Binder;
diff --git a/core/java/android/bluetooth/BluetoothPan.java b/core/java/android/bluetooth/BluetoothPan.java
index 4e9762737c07..42f27f2a9c98 100644
--- a/core/java/android/bluetooth/BluetoothPan.java
+++ b/core/java/android/bluetooth/BluetoothPan.java
@@ -23,7 +23,7 @@ import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.SuppressLint;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.Binder;
import android.os.IBinder;
diff --git a/core/java/android/bluetooth/BluetoothPbap.java b/core/java/android/bluetooth/BluetoothPbap.java
index d94c65742e6c..c579fdf5048f 100644
--- a/core/java/android/bluetooth/BluetoothPbap.java
+++ b/core/java/android/bluetooth/BluetoothPbap.java
@@ -16,8 +16,11 @@
package android.bluetooth;
+import android.annotation.Nullable;
import android.annotation.SdkConstant;
-import android.annotation.UnsupportedAppUsage;
+import android.annotation.SuppressLint;
+import android.annotation.SystemApi;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
@@ -54,6 +57,7 @@ import java.util.List;
*
* @hide
*/
+@SystemApi
public class BluetoothPbap implements BluetoothProfile {
private static final String TAG = "BluetoothPbap";
@@ -75,7 +79,11 @@ public class BluetoothPbap implements BluetoothProfile {
* {@link BluetoothProfile#STATE_DISCONNECTING}.
* <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission to
* receive.
+ *
+ * @hide
*/
+ @SuppressLint("ActionValue")
+ @SystemApi
@SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String ACTION_CONNECTION_STATE_CHANGED =
"android.bluetooth.pbap.profile.action.CONNECTION_STATE_CHANGED";
@@ -85,33 +93,16 @@ public class BluetoothPbap implements BluetoothProfile {
private ServiceListener mServiceListener;
private BluetoothAdapter mAdapter;
+ /** @hide */
public static final int RESULT_FAILURE = 0;
+ /** @hide */
public static final int RESULT_SUCCESS = 1;
- /** Connection canceled before completion. */
- public static final int RESULT_CANCELED = 2;
-
/**
- * An interface for notifying Bluetooth PCE IPC clients when they have
- * been connected to the BluetoothPbap service.
+ * Connection canceled before completion.
+ *
+ * @hide
*/
- public interface ServiceListener {
- /**
- * Called to notify the client when this proxy object has been
- * connected to the BluetoothPbap service. Clients must wait for
- * this callback before making IPC calls on the BluetoothPbap
- * service.
- */
- public void onServiceConnected(BluetoothPbap proxy);
-
- /**
- * Called to notify the client that this proxy object has been
- * disconnected from the BluetoothPbap service. Clients must not
- * make IPC calls on the BluetoothPbap service after this callback.
- * This callback will currently only occur if the application hosting
- * the BluetoothPbap service, but may be called more often in future.
- */
- public void onServiceDisconnected();
- }
+ public static final int RESULT_CANCELED = 2;
private final IBluetoothStateChangeCallback mBluetoothStateChangeCallback =
new IBluetoothStateChangeCallback.Stub() {
@@ -127,6 +118,8 @@ public class BluetoothPbap implements BluetoothProfile {
/**
* Create a BluetoothPbap proxy object.
+ *
+ * @hide
*/
public BluetoothPbap(Context context, ServiceListener l) {
mContext = context;
@@ -181,6 +174,7 @@ public class BluetoothPbap implements BluetoothProfile {
}
}
+ /** @hide */
protected void finalize() throws Throwable {
try {
close();
@@ -194,6 +188,8 @@ public class BluetoothPbap implements BluetoothProfile {
* Other public functions of BluetoothPbap will return default error
* results once close() has been called. Multiple invocations of close()
* are ok.
+ *
+ * @hide
*/
public synchronized void close() {
IBluetoothManager mgr = mAdapter.getBluetoothManager();
@@ -210,6 +206,8 @@ public class BluetoothPbap implements BluetoothProfile {
/**
* {@inheritDoc}
+ *
+ * @hide
*/
@Override
public List<BluetoothDevice> getConnectedDevices() {
@@ -229,17 +227,22 @@ public class BluetoothPbap implements BluetoothProfile {
/**
* {@inheritDoc}
+ *
+ * @hide
*/
+ @SystemApi
@Override
- public int getConnectionState(BluetoothDevice device) {
+ public int getConnectionState(@Nullable BluetoothDevice device) {
log("getConnectionState: device=" + device);
- final IBluetoothPbap service = mService;
- if (service == null) {
- Log.w(TAG, "Proxy not attached to service");
- return BluetoothProfile.STATE_DISCONNECTED;
- }
try {
- return service.getConnectionState(device);
+ final IBluetoothPbap service = mService;
+ if (service != null && isEnabled() && isValidDevice(device)) {
+ return service.getConnectionState(device);
+ }
+ if (service == null) {
+ Log.w(TAG, "Proxy not attached to service");
+ }
+ return BluetoothProfile.STATE_DISCONNECTED;
} catch (RemoteException e) {
Log.e(TAG, e.toString());
}
@@ -248,6 +251,8 @@ public class BluetoothPbap implements BluetoothProfile {
/**
* {@inheritDoc}
+ *
+ * @hide
*/
@Override
public List<BluetoothDevice> getDevicesMatchingConnectionStates(int[] states) {
@@ -266,22 +271,12 @@ public class BluetoothPbap implements BluetoothProfile {
}
/**
- * Returns true if the specified Bluetooth device is connected (does not
- * include connecting). Returns false if not connected, or if this proxy
- * object is not currently connected to the Pbap service.
- */
- // TODO: This is currently being used by SettingsLib and internal app.
- public boolean isConnected(BluetoothDevice device) {
- return getConnectionState(device) == BluetoothAdapter.STATE_CONNECTED;
- }
-
- /**
* Disconnects the current Pbap client (PCE). Currently this call blocks,
* it may soon be made asynchronous. Returns false if this proxy object is
* not currently connected to the Pbap service.
+ *
+ * @hide
*/
- // TODO: This is currently being used by SettingsLib and will be used in the future.
- // TODO: Must specify target device. Implement this in the service.
@UnsupportedAppUsage
public boolean disconnect(BluetoothDevice device) {
log("disconnect()");
@@ -304,7 +299,7 @@ public class BluetoothPbap implements BluetoothProfile {
log("Proxy object connected");
mService = IBluetoothPbap.Stub.asInterface(service);
if (mServiceListener != null) {
- mServiceListener.onServiceConnected(BluetoothPbap.this);
+ mServiceListener.onServiceConnected(BluetoothProfile.PBAP, BluetoothPbap.this);
}
}
@@ -312,11 +307,23 @@ public class BluetoothPbap implements BluetoothProfile {
log("Proxy object disconnected");
doUnbind();
if (mServiceListener != null) {
- mServiceListener.onServiceDisconnected();
+ mServiceListener.onServiceDisconnected(BluetoothProfile.PBAP);
}
}
};
+ private boolean isEnabled() {
+ if (mAdapter.getState() == BluetoothAdapter.STATE_ON) return true;
+ return false;
+ }
+
+ private boolean isValidDevice(BluetoothDevice device) {
+ if (device == null) return false;
+
+ if (BluetoothAdapter.checkBluetoothAddress(device.getAddress())) return true;
+ return false;
+ }
+
private static void log(String msg) {
if (DBG) {
Log.d(TAG, msg);
diff --git a/core/java/android/bluetooth/BluetoothProfile.java b/core/java/android/bluetooth/BluetoothProfile.java
index 097a3677ac4b..638e6de06be7 100644
--- a/core/java/android/bluetooth/BluetoothProfile.java
+++ b/core/java/android/bluetooth/BluetoothProfile.java
@@ -22,7 +22,7 @@ import android.annotation.IntDef;
import android.annotation.RequiresPermission;
import android.annotation.SuppressLint;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
diff --git a/core/java/android/bluetooth/BluetoothSap.java b/core/java/android/bluetooth/BluetoothSap.java
index 9b4dabcdcfdc..8bf1b588c89a 100644
--- a/core/java/android/bluetooth/BluetoothSap.java
+++ b/core/java/android/bluetooth/BluetoothSap.java
@@ -19,7 +19,7 @@ package android.bluetooth;
import android.Manifest;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.Binder;
import android.os.IBinder;
diff --git a/core/java/android/bluetooth/BluetoothServerSocket.java b/core/java/android/bluetooth/BluetoothServerSocket.java
index 3a23808f3617..88c186c88aaf 100644
--- a/core/java/android/bluetooth/BluetoothServerSocket.java
+++ b/core/java/android/bluetooth/BluetoothServerSocket.java
@@ -16,7 +16,7 @@
package android.bluetooth;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Handler;
import android.os.ParcelUuid;
import android.util.Log;
diff --git a/core/java/android/bluetooth/BluetoothSocket.java b/core/java/android/bluetooth/BluetoothSocket.java
index 760166bfcc5d..f77436965537 100644
--- a/core/java/android/bluetooth/BluetoothSocket.java
+++ b/core/java/android/bluetooth/BluetoothSocket.java
@@ -16,7 +16,7 @@
package android.bluetooth;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.net.LocalSocket;
import android.os.ParcelFileDescriptor;
import android.os.ParcelUuid;
diff --git a/core/java/android/bluetooth/BluetoothUuid.java b/core/java/android/bluetooth/BluetoothUuid.java
index 7e96c23af4b9..e274af1b5c5d 100644
--- a/core/java/android/bluetooth/BluetoothUuid.java
+++ b/core/java/android/bluetooth/BluetoothUuid.java
@@ -19,7 +19,7 @@ package android.bluetooth;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.ParcelUuid;
import java.nio.ByteBuffer;
diff --git a/core/java/android/bluetooth/le/BluetoothLeScanner.java b/core/java/android/bluetooth/le/BluetoothLeScanner.java
index ac126ae0969d..9a17346334d1 100644
--- a/core/java/android/bluetooth/le/BluetoothLeScanner.java
+++ b/core/java/android/bluetooth/le/BluetoothLeScanner.java
@@ -21,7 +21,6 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
-import android.app.ActivityThread;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
@@ -84,17 +83,25 @@ public final class BluetoothLeScanner {
private BluetoothAdapter mBluetoothAdapter;
private final Map<ScanCallback, BleScanCallbackWrapper> mLeScanClients;
+ private final String mOpPackageName;
+ private final String mFeatureId;
+
/**
* Use {@link BluetoothAdapter#getBluetoothLeScanner()} instead.
*
* @param bluetoothManager BluetoothManager that conducts overall Bluetooth Management.
+ * @param opPackageName The opPackageName of the context this object was created from
+ * @param featureId The featureId of the context this object was created from
* @hide
*/
- public BluetoothLeScanner(IBluetoothManager bluetoothManager) {
+ public BluetoothLeScanner(IBluetoothManager bluetoothManager,
+ @NonNull String opPackageName, @Nullable String featureId) {
mBluetoothManager = bluetoothManager;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mHandler = new Handler(Looper.getMainLooper());
mLeScanClients = new HashMap<ScanCallback, BleScanCallbackWrapper>();
+ mOpPackageName = opPackageName;
+ mFeatureId = featureId;
}
/**
@@ -246,8 +253,8 @@ public final class BluetoothLeScanner {
wrapper.startRegistration();
} else {
try {
- gatt.startScanForIntent(callbackIntent, settings, filters,
- ActivityThread.currentOpPackageName());
+ gatt.startScanForIntent(callbackIntent, settings, filters, mOpPackageName,
+ mFeatureId);
} catch (RemoteException e) {
return ScanCallback.SCAN_FAILED_INTERNAL_ERROR;
}
@@ -288,7 +295,7 @@ public final class BluetoothLeScanner {
IBluetoothGatt gatt;
try {
gatt = mBluetoothManager.getBluetoothGatt();
- gatt.stopScanForIntent(callbackIntent, ActivityThread.currentOpPackageName());
+ gatt.stopScanForIntent(callbackIntent, mOpPackageName);
} catch (RemoteException e) {
}
}
@@ -448,8 +455,7 @@ public final class BluetoothLeScanner {
} else {
mScannerId = scannerId;
mBluetoothGatt.startScan(mScannerId, mSettings, mFilters,
- mResultStorages,
- ActivityThread.currentOpPackageName());
+ mResultStorages, mOpPackageName, mFeatureId);
}
} catch (RemoteException e) {
Log.e(TAG, "fail to start le scan: " + e);
diff --git a/core/java/android/bluetooth/le/ScanRecord.java b/core/java/android/bluetooth/le/ScanRecord.java
index 97e3f5221c72..c0c1aa1634ff 100644
--- a/core/java/android/bluetooth/le/ScanRecord.java
+++ b/core/java/android/bluetooth/le/ScanRecord.java
@@ -18,8 +18,8 @@ package android.bluetooth.le;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
import android.bluetooth.BluetoothUuid;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.ParcelUuid;
import android.util.ArrayMap;
import android.util.Log;
diff --git a/core/java/android/companion/AssociationRequest.java b/core/java/android/companion/AssociationRequest.java
index ac40150376da..1f57c7d9d2f1 100644
--- a/core/java/android/companion/AssociationRequest.java
+++ b/core/java/android/companion/AssociationRequest.java
@@ -18,7 +18,7 @@ package android.companion;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.OneTimeUseBuilder;
diff --git a/core/java/android/companion/BluetoothDeviceFilter.java b/core/java/android/companion/BluetoothDeviceFilter.java
index fe0123c56e57..2649fbee4246 100644
--- a/core/java/android/companion/BluetoothDeviceFilter.java
+++ b/core/java/android/companion/BluetoothDeviceFilter.java
@@ -25,8 +25,8 @@ import static android.companion.BluetoothDeviceFilterUtils.patternToString;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
import android.bluetooth.BluetoothDevice;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.ParcelUuid;
import android.provider.OneTimeUseBuilder;
diff --git a/core/java/android/companion/BluetoothDeviceFilterUtils.java b/core/java/android/companion/BluetoothDeviceFilterUtils.java
index 0f67f6b50251..24be45cb20fe 100644
--- a/core/java/android/companion/BluetoothDeviceFilterUtils.java
+++ b/core/java/android/companion/BluetoothDeviceFilterUtils.java
@@ -21,9 +21,9 @@ import static android.text.TextUtils.firstNotEmpty;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.ScanFilter;
+import android.compat.annotation.UnsupportedAppUsage;
import android.net.wifi.ScanResult;
import android.os.ParcelUuid;
import android.os.Parcelable;
diff --git a/core/java/android/companion/BluetoothLeDeviceFilter.java b/core/java/android/companion/BluetoothLeDeviceFilter.java
index 2701619112c5..730bc60e331c 100644
--- a/core/java/android/companion/BluetoothLeDeviceFilter.java
+++ b/core/java/android/companion/BluetoothLeDeviceFilter.java
@@ -25,11 +25,11 @@ import static com.android.internal.util.Preconditions.checkState;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanRecord;
import android.bluetooth.le.ScanResult;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.provider.OneTimeUseBuilder;
import android.text.TextUtils;
diff --git a/core/java/android/companion/DeviceFilter.java b/core/java/android/companion/DeviceFilter.java
index dc7cf82613e6..c9cb072904b4 100644
--- a/core/java/android/companion/DeviceFilter.java
+++ b/core/java/android/companion/DeviceFilter.java
@@ -19,7 +19,7 @@ package android.companion;
import android.annotation.IntDef;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcelable;
import java.lang.annotation.Retention;
diff --git a/core/java/android/content/AsyncTaskLoader.java b/core/java/android/content/AsyncTaskLoader.java
index bb7d5e49ccfb..14c3387d47dc 100644
--- a/core/java/android/content/AsyncTaskLoader.java
+++ b/core/java/android/content/AsyncTaskLoader.java
@@ -16,7 +16,7 @@
package android.content;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.OperationCanceledException;
diff --git a/core/java/android/content/BroadcastReceiver.java b/core/java/android/content/BroadcastReceiver.java
index f73a376dfc69..1d4d30d87560 100644
--- a/core/java/android/content/BroadcastReceiver.java
+++ b/core/java/android/content/BroadcastReceiver.java
@@ -18,11 +18,11 @@ package android.content;
import android.annotation.NonNull;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityManager;
import android.app.ActivityThread;
import android.app.IActivityManager;
import android.app.QueuedWork;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
diff --git a/core/java/android/content/ClipData.java b/core/java/android/content/ClipData.java
index 999ec372e9c5..9c806fa286bc 100644
--- a/core/java/android/content/ClipData.java
+++ b/core/java/android/content/ClipData.java
@@ -21,7 +21,7 @@ import static android.content.ContentResolver.SCHEME_ANDROID_RESOURCE;
import static android.content.ContentResolver.SCHEME_CONTENT;
import static android.content.ContentResolver.SCHEME_FILE;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.net.Uri;
diff --git a/core/java/android/content/ClipboardManager.java b/core/java/android/content/ClipboardManager.java
index dc1c700f5d08..dec9589981c6 100644
--- a/core/java/android/content/ClipboardManager.java
+++ b/core/java/android/content/ClipboardManager.java
@@ -19,7 +19,7 @@ package android.content;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Handler;
import android.os.RemoteException;
import android.os.ServiceManager;
diff --git a/core/java/android/content/ComponentName.java b/core/java/android/content/ComponentName.java
index 33216d74b184..27960b0dd9f0 100644
--- a/core/java/android/content/ComponentName.java
+++ b/core/java/android/content/ComponentName.java
@@ -18,7 +18,7 @@ package android.content;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
diff --git a/core/java/android/content/ContentProvider.java b/core/java/android/content/ContentProvider.java
index 2240823ebe92..393d48891d64 100644
--- a/core/java/android/content/ContentProvider.java
+++ b/core/java/android/content/ContentProvider.java
@@ -27,8 +27,8 @@ import static android.os.Trace.TRACE_TAG_DATABASE;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
import android.app.AppOpsManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.PackageManager;
import android.content.pm.PathPermission;
import android.content.pm.ProviderInfo;
diff --git a/core/java/android/content/ContentProviderClient.java b/core/java/android/content/ContentProviderClient.java
index bb65aa013f72..4008f2b8c168 100644
--- a/core/java/android/content/ContentProviderClient.java
+++ b/core/java/android/content/ContentProviderClient.java
@@ -22,7 +22,7 @@ import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.res.AssetFileDescriptor;
import android.database.CrossProcessCursorWrapper;
import android.database.Cursor;
diff --git a/core/java/android/content/ContentProviderNative.java b/core/java/android/content/ContentProviderNative.java
index dfa71f88fa0a..45ace4010961 100644
--- a/core/java/android/content/ContentProviderNative.java
+++ b/core/java/android/content/ContentProviderNative.java
@@ -17,7 +17,7 @@
package android.content;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.res.AssetFileDescriptor;
import android.database.BulkCursorDescriptor;
import android.database.BulkCursorToCursorAdaptor;
diff --git a/core/java/android/content/ContentResolver.java b/core/java/android/content/ContentResolver.java
index d4280f8992c2..ede668a6b5c3 100644
--- a/core/java/android/content/ContentResolver.java
+++ b/core/java/android/content/ContentResolver.java
@@ -25,12 +25,12 @@ import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.UserIdInt;
import android.app.ActivityManager;
import android.app.ActivityThread;
import android.app.AppGlobals;
import android.app.UriGrantsManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetFileDescriptor;
diff --git a/core/java/android/content/ContentValues.java b/core/java/android/content/ContentValues.java
index bdd1f4ce815f..f9f4c5dc0d62 100644
--- a/core/java/android/content/ContentValues.java
+++ b/core/java/android/content/ContentValues.java
@@ -16,9 +16,8 @@
package android.content;
-import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.ArrayMap;
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index d370a380bc3b..66abf5d4eb6f 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -32,12 +32,12 @@ import android.annotation.StyleRes;
import android.annotation.StyleableRes;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.UserIdInt;
import android.app.ActivityManager;
import android.app.IApplicationThread;
import android.app.IServiceConnection;
import android.app.VrManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
@@ -1060,6 +1060,31 @@ public abstract class Context {
public abstract File getFilesDir();
/**
+ * Returns the absolute path to the directory that is related to the crate on the filesystem.
+ * <p>
+ * The crateId require a validated file name. It can't contain any "..", ".",
+ * {@link File#separatorChar} etc..
+ * </p>
+ * <p>
+ * The returned path may change over time if the calling app is moved to an
+ * adopted storage device, so only relative paths should be persisted.
+ * </p>
+ * <p>
+ * No additional permissions are required for the calling app to read or
+ * write files under the returned path.
+ *</p>
+ *
+ * @param crateId the relative validated file name under {@link Context#getDataDir()}/crates
+ * @return the crate directory file.
+ * @hide
+ */
+ @NonNull
+ @TestApi
+ public File getCrateDir(@NonNull String crateId) {
+ throw new RuntimeException("Not implemented. Must override in a subclass.");
+ }
+
+ /**
* Returns the absolute path to the directory on the filesystem similar to
* {@link #getFilesDir()}. The difference is that files placed under this
* directory will be excluded from automatic backup to remote storage. See
@@ -3973,6 +3998,17 @@ public abstract class Context {
public static final String WIFI_SERVICE = "wifi";
/**
+ * Use with {@link #getSystemService(String)} to retrieve a
+ * {@link android.net.wifi.WifiCondManager} for handling management of the Wi-Fi control
+ * daemon.
+ *
+ * @see #getSystemService(String)
+ * @see android.net.wifi.WifiCondManager
+ * @hide
+ */
+ public static final String WIFI_COND_SERVICE = "wificond";
+
+ /**
* Use with {@link #getSystemService(String)} to retrieve a {@link
* android.net.wifi.p2p.WifiP2pManager} for handling management of
* Wi-Fi peer-to-peer connections.
@@ -4325,6 +4361,15 @@ public abstract class Context {
public static final String SOUND_TRIGGER_SERVICE = "soundtrigger";
/**
+ * Use with {@link #getSystemService(String)} to access the
+ * {@link com.android.server.soundtrigger_middleware.SoundTriggerMiddlewareService}.
+ *
+ * @hide
+ * @see #getSystemService(String)
+ */
+ public static final String SOUND_TRIGGER_MIDDLEWARE_SERVICE = "soundtrigger_middleware";
+
+ /**
* Official published name of the (internal) permission service.
*
* @see #getSystemService(String)
@@ -4783,6 +4828,12 @@ public abstract class Context {
public static final String INCIDENT_COMPANION_SERVICE = "incidentcompanion";
/**
+ * Service to assist {@link android.app.StatsManager} that lives in system server.
+ * @hide
+ */
+ public static final String STATS_MANAGER_SERVICE = "statsmanager";
+
+ /**
* Service to assist statsd in obtaining general stats.
* @hide
*/
@@ -4905,6 +4956,8 @@ public abstract class Context {
* {@link android.telephony.ims.ImsManager}.
* @hide
*/
+ @SystemApi
+ @TestApi
public static final String TELEPHONY_IMS_SERVICE = "telephony_ims";
/**
@@ -4973,14 +5026,14 @@ public abstract class Context {
* {@link android.content.pm.DataLoaderManager}.
* @hide
*/
- public static final String DATA_LOADER_MANAGER_SERVICE = "dataloadermanager";
+ public static final String DATA_LOADER_MANAGER_SERVICE = "dataloader_manager";
/**
* Use with {@link #getSystemService(String)} to retrieve an
* {@link android.os.incremental.IncrementalManager}.
* @hide
*/
- public static final String INCREMENTAL_SERVICE = "incremental";
+ public static final String INCREMENTAL_SERVICE = "incremental_service";
/**
* Determine whether the given permission is allowed for a particular
diff --git a/core/java/android/content/ContextWrapper.java b/core/java/android/content/ContextWrapper.java
index d6442e28439f..6fe11873d327 100644
--- a/core/java/android/content/ContextWrapper.java
+++ b/core/java/android/content/ContextWrapper.java
@@ -21,9 +21,9 @@ import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.IApplicationThread;
import android.app.IServiceConnection;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
@@ -252,6 +252,16 @@ public class ContextWrapper extends Context {
return mBase.getFilesDir();
}
+ /**
+ * {@inheritDoc Context#getCrateDir()}
+ * @hide
+ */
+ @NonNull
+ @Override
+ public File getCrateDir(@NonNull String cratedId) {
+ return mBase.getCrateDir(cratedId);
+ }
+
@Override
public File getNoBackupFilesDir() {
return mBase.getNoBackupFilesDir();
diff --git a/core/java/android/content/CursorEntityIterator.java b/core/java/android/content/CursorEntityIterator.java
index 2c630d29621b..952366d1cd75 100644
--- a/core/java/android/content/CursorEntityIterator.java
+++ b/core/java/android/content/CursorEntityIterator.java
@@ -16,7 +16,7 @@
package android.content;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.database.Cursor;
import android.os.RemoteException;
diff --git a/core/java/android/content/CursorLoader.java b/core/java/android/content/CursorLoader.java
index 4ccafab741d8..4ff5ccabbcb7 100644
--- a/core/java/android/content/CursorLoader.java
+++ b/core/java/android/content/CursorLoader.java
@@ -16,7 +16,7 @@
package android.content;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.database.Cursor;
import android.net.Uri;
import android.os.CancellationSignal;
diff --git a/core/java/android/content/Entity.java b/core/java/android/content/Entity.java
index ff4f15006280..13137c48e7f2 100644
--- a/core/java/android/content/Entity.java
+++ b/core/java/android/content/Entity.java
@@ -16,7 +16,7 @@
package android.content;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.net.Uri;
import android.os.Build;
diff --git a/core/java/android/content/IContentProvider.java b/core/java/android/content/IContentProvider.java
index 1fb29586e15b..6f477ff17c67 100644
--- a/core/java/android/content/IContentProvider.java
+++ b/core/java/android/content/IContentProvider.java
@@ -17,7 +17,7 @@
package android.content;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java
index 7815a330217f..c5a147af3137 100644
--- a/core/java/android/content/Intent.java
+++ b/core/java/android/content/Intent.java
@@ -28,8 +28,8 @@ import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.AppGlobals;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.ComponentInfo;
@@ -1728,6 +1728,7 @@ public class Intent implements Parcelable, Cloneable {
* @hide
*/
@SystemApi
+ @TestApi
public static final String EXTRA_ORIGINATING_UID
= "android.intent.extra.ORIGINATING_UID";
@@ -4000,9 +4001,15 @@ public class Intent implements Parcelable, Cloneable {
* Broadcast Action: The sim card state has changed.
* For more details see TelephonyIntents.ACTION_SIM_STATE_CHANGED. This is here
* because TelephonyIntents is an internal class.
- * @hide
+ * The intent will have following extras.</p>
+ * <p>
+ * @see #EXTRA_SIM_STATE
+ * @see #EXTRA_SIM_LOCKED_REASON
+ *
* @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED} or
* {@link #ACTION_SIM_APPLICATION_STATE_CHANGED}
+ *
+ * @hide
*/
@Deprecated
@SystemApi
@@ -4010,6 +4017,170 @@ public class Intent implements Parcelable, Cloneable {
public static final String ACTION_SIM_STATE_CHANGED = "android.intent.action.SIM_STATE_CHANGED";
/**
+ * The extra used with {@link #ACTION_SIM_STATE_CHANGED} for broadcasting SIM STATE.
+ * This will have one of the following intent values.
+ * @see #SIM_STATE_UNKNOWN
+ * @see #SIM_STATE_NOT_READY
+ * @see #SIM_STATE_ABSENT
+ * @see #SIM_STATE_PRESENT
+ * @see #SIM_STATE_CARD_IO_ERROR
+ * @see #SIM_STATE_CARD_RESTRICTED
+ * @see #SIM_STATE_LOCKED
+ * @see #SIM_STATE_READY
+ * @see #SIM_STATE_IMSI
+ * @see #SIM_STATE_LOADED
+ * @hide
+ * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+ */
+ @Deprecated
+ @SystemApi
+ public static final String EXTRA_SIM_STATE = "ss";
+
+ /**
+ * The intent value UNKNOWN represents the SIM state unknown
+ * @hide
+ * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+ */
+ @Deprecated
+ @SystemApi
+ public static final String SIM_STATE_UNKNOWN = "UNKNOWN";
+
+ /**
+ * The intent value NOT_READY means that the SIM is not ready eg. radio is off or powering on
+ * @hide
+ * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+ */
+ @Deprecated
+ @SystemApi
+ public static final String SIM_STATE_NOT_READY = "NOT_READY";
+
+ /**
+ * The intent value ABSENT means the SIM card is missing
+ * @hide
+ * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+ */
+ @Deprecated
+ @SystemApi
+ public static final String SIM_STATE_ABSENT = "ABSENT";
+
+ /**
+ * The intent value PRESENT means the device has a SIM card inserted
+ * @hide
+ * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+ */
+ @Deprecated
+ @SystemApi
+ public static final String SIM_STATE_PRESENT = "PRESENT";
+
+ /**
+ * The intent value CARD_IO_ERROR means for three consecutive times there was SIM IO error
+ * @hide
+ * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+ */
+ @Deprecated
+ @SystemApi
+ static public final String SIM_STATE_CARD_IO_ERROR = "CARD_IO_ERROR";
+
+ /**
+ * The intent value CARD_RESTRICTED means card is present but not usable due to carrier
+ * restrictions
+ * @hide
+ * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+ */
+ @Deprecated
+ @SystemApi
+ static public final String SIM_STATE_CARD_RESTRICTED = "CARD_RESTRICTED";
+
+ /**
+ * The intent value LOCKED means the SIM is locked by PIN or by network
+ * @hide
+ * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+ */
+ @Deprecated
+ @SystemApi
+ public static final String SIM_STATE_LOCKED = "LOCKED";
+
+ /**
+ * The intent value READY means the SIM is ready to be accessed
+ * @hide
+ * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+ */
+ @Deprecated
+ @SystemApi
+ public static final String SIM_STATE_READY = "READY";
+
+ /**
+ * The intent value IMSI means the SIM IMSI is ready in property
+ * @hide
+ * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+ */
+ @Deprecated
+ @SystemApi
+ public static final String SIM_STATE_IMSI = "IMSI";
+
+ /**
+ * The intent value LOADED means all SIM records, including IMSI, are loaded
+ * @hide
+ * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+ */
+ @Deprecated
+ @SystemApi
+ public static final String SIM_STATE_LOADED = "LOADED";
+
+ /**
+ * The extra used with {@link #ACTION_SIM_STATE_CHANGED} for broadcasting SIM STATE.
+ * This extra will have one of the following intent values.
+ * <p>
+ * @see #SIM_LOCKED_ON_PIN
+ * @see #SIM_LOCKED_ON_PUK
+ * @see #SIM_LOCKED_NETWORK
+ * @see #SIM_ABSENT_ON_PERM_DISABLED
+ *
+ * @hide
+ * @deprecated Use {@link #ACTION_SIM_APPLICATION_STATE_CHANGED}
+ */
+ @Deprecated
+ @SystemApi
+ public static final String EXTRA_SIM_LOCKED_REASON = "reason";
+
+ /**
+ * The intent value PIN means the SIM is locked on PIN1
+ * @hide
+ * @deprecated Use {@link #ACTION_SIM_APPLICATION_STATE_CHANGED}
+ */
+ @Deprecated
+ @SystemApi
+ public static final String SIM_LOCKED_ON_PIN = "PIN";
+
+ /**
+ * The intent value PUK means the SIM is locked on PUK1
+ * @hide
+ * @deprecated Use {@link #ACTION_SIM_APPLICATION_STATE_CHANGED}
+ */
+ /* PUK means ICC is locked on PUK1 */
+ @Deprecated
+ @SystemApi
+ public static final String SIM_LOCKED_ON_PUK = "PUK";
+
+ /**
+ * The intent value NETWORK means the SIM is locked on NETWORK PERSONALIZATION
+ * @hide
+ * @deprecated Use {@link #ACTION_SIM_APPLICATION_STATE_CHANGED}
+ */
+ @Deprecated
+ @SystemApi
+ public static final String SIM_LOCKED_NETWORK = "NETWORK";
+
+ /**
+ * The intent value PERM_DISABLED means SIM is permanently disabled due to puk fails
+ * @hide
+ * @deprecated Use {@link #ACTION_SIM_APPLICATION_STATE_CHANGED}
+ */
+ @Deprecated
+ @SystemApi
+ public static final String SIM_ABSENT_ON_PERM_DISABLED = "PERM_DISABLED";
+
+ /**
* Broadcast Action: indicate that the phone service state has changed.
* The intent will have the following extra values:</p>
* <p>
diff --git a/core/java/android/content/IntentFilter.java b/core/java/android/content/IntentFilter.java
index 93390bd9f750..73c1e2fb9f38 100644
--- a/core/java/android/content/IntentFilter.java
+++ b/core/java/android/content/IntentFilter.java
@@ -18,7 +18,7 @@ package android.content;
import android.annotation.IntDef;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.net.Uri;
import android.os.Build;
import android.os.Parcel;
diff --git a/core/java/android/content/IntentSender.java b/core/java/android/content/IntentSender.java
index ec0bac486c65..f40dc298d560 100644
--- a/core/java/android/content/IntentSender.java
+++ b/core/java/android/content/IntentSender.java
@@ -16,14 +16,14 @@
package android.content;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Bundle;
-import android.os.RemoteException;
import android.os.Handler;
import android.os.IBinder;
import android.os.Parcel;
import android.os.Parcelable;
+import android.os.RemoteException;
import android.os.UserHandle;
import android.util.AndroidException;
diff --git a/core/java/android/content/RestrictionsManager.java b/core/java/android/content/RestrictionsManager.java
index bbdab048207b..885eb708d92c 100644
--- a/core/java/android/content/RestrictionsManager.java
+++ b/core/java/android/content/RestrictionsManager.java
@@ -17,9 +17,9 @@
package android.content;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
import android.app.Activity;
import android.app.admin.DevicePolicyManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
diff --git a/core/java/android/content/SearchRecentSuggestionsProvider.java b/core/java/android/content/SearchRecentSuggestionsProvider.java
index 8ee7b9e403b4..fc3ddf6148de 100644
--- a/core/java/android/content/SearchRecentSuggestionsProvider.java
+++ b/core/java/android/content/SearchRecentSuggestionsProvider.java
@@ -16,8 +16,8 @@
package android.content;
-import android.annotation.UnsupportedAppUsage;
import android.app.SearchManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
diff --git a/core/java/android/content/SyncAdapterType.java b/core/java/android/content/SyncAdapterType.java
index 8c8fe5a06888..7bcdbfd1085c 100644
--- a/core/java/android/content/SyncAdapterType.java
+++ b/core/java/android/content/SyncAdapterType.java
@@ -17,11 +17,11 @@
package android.content;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
-import android.text.TextUtils;
-import android.os.Parcelable;
import android.os.Parcel;
+import android.os.Parcelable;
+import android.text.TextUtils;
/**
* Value type that represents a SyncAdapterType. This object overrides {@link #equals} and
diff --git a/core/java/android/content/SyncAdaptersCache.java b/core/java/android/content/SyncAdaptersCache.java
index d4e52175f9b5..58445a7f9242 100644
--- a/core/java/android/content/SyncAdaptersCache.java
+++ b/core/java/android/content/SyncAdaptersCache.java
@@ -16,7 +16,7 @@
package android.content;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.RegisteredServicesCache;
import android.content.pm.XmlSerializerAndParser;
import android.content.res.Resources;
@@ -29,8 +29,8 @@ import android.util.SparseArray;
import com.android.internal.annotations.GuardedBy;
import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlSerializer;
import org.xmlpull.v1.XmlPullParserException;
+import org.xmlpull.v1.XmlSerializer;
import java.io.IOException;
import java.util.ArrayList;
diff --git a/core/java/android/content/SyncContext.java b/core/java/android/content/SyncContext.java
index 50d1dc96fc0a..4a9f66c474db 100644
--- a/core/java/android/content/SyncContext.java
+++ b/core/java/android/content/SyncContext.java
@@ -16,10 +16,10 @@
package android.content;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
+import android.os.IBinder;
import android.os.RemoteException;
import android.os.SystemClock;
-import android.os.IBinder;
public class SyncContext {
private ISyncContext mSyncContext;
diff --git a/core/java/android/content/SyncInfo.java b/core/java/android/content/SyncInfo.java
index d3f2eed8126f..017a92b1e8bb 100644
--- a/core/java/android/content/SyncInfo.java
+++ b/core/java/android/content/SyncInfo.java
@@ -17,7 +17,7 @@
package android.content;
import android.accounts.Account;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/content/SyncRequest.java b/core/java/android/content/SyncRequest.java
index 5f1f18016e0d..9e568a40e0ee 100644
--- a/core/java/android/content/SyncRequest.java
+++ b/core/java/android/content/SyncRequest.java
@@ -17,7 +17,7 @@
package android.content;
import android.accounts.Account;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
diff --git a/core/java/android/content/SyncStatusInfo.java b/core/java/android/content/SyncStatusInfo.java
index 0eea47a248af..b72eb040ea92 100644
--- a/core/java/android/content/SyncStatusInfo.java
+++ b/core/java/android/content/SyncStatusInfo.java
@@ -16,7 +16,7 @@
package android.content;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
diff --git a/core/java/android/content/UndoManager.java b/core/java/android/content/UndoManager.java
index f9c58d624a2f..ed9cd86927ae 100644
--- a/core/java/android/content/UndoManager.java
+++ b/core/java/android/content/UndoManager.java
@@ -16,7 +16,7 @@
package android.content;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.text.TextUtils;
import android.util.ArrayMap;
diff --git a/core/java/android/content/UndoOperation.java b/core/java/android/content/UndoOperation.java
index a425486e5739..235d72123ff6 100644
--- a/core/java/android/content/UndoOperation.java
+++ b/core/java/android/content/UndoOperation.java
@@ -16,7 +16,7 @@
package android.content;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/content/UriMatcher.java b/core/java/android/content/UriMatcher.java
index 208bc01aef9d..7fa48f0e9a78 100644
--- a/core/java/android/content/UriMatcher.java
+++ b/core/java/android/content/UriMatcher.java
@@ -16,7 +16,7 @@
package android.content;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.net.Uri;
import java.util.ArrayList;
diff --git a/core/java/android/content/integrity/AtomicFormula.java b/core/java/android/content/integrity/AtomicFormula.java
index c8e164f1f232..574a93ff9355 100644
--- a/core/java/android/content/integrity/AtomicFormula.java
+++ b/core/java/android/content/integrity/AtomicFormula.java
@@ -44,6 +44,7 @@ public abstract class AtomicFormula implements Formula {
private static final String TAG = "AtomicFormula";
+ /** @hide */
@IntDef(
value = {
PACKAGE_NAME,
@@ -56,6 +57,7 @@ public abstract class AtomicFormula implements Formula {
@Retention(RetentionPolicy.SOURCE)
public @interface Key {}
+ /** @hide */
@IntDef(value = {EQ, LT, LE, GT, GE})
@Retention(RetentionPolicy.SOURCE)
public @interface Operator {}
diff --git a/core/java/android/content/integrity/CompoundFormula.java b/core/java/android/content/integrity/CompoundFormula.java
index 53a99534906c..2a651d9e90d8 100644
--- a/core/java/android/content/integrity/CompoundFormula.java
+++ b/core/java/android/content/integrity/CompoundFormula.java
@@ -47,6 +47,7 @@ import java.util.Objects;
public final class CompoundFormula implements Formula, Parcelable {
private static final String TAG = "OpenFormula";
+ /** @hide */
@IntDef(
value = {
AND, OR, NOT,
diff --git a/core/java/android/content/integrity/Formula.java b/core/java/android/content/integrity/Formula.java
index 030ff6b66e1f..b092a22c0191 100644
--- a/core/java/android/content/integrity/Formula.java
+++ b/core/java/android/content/integrity/Formula.java
@@ -38,6 +38,7 @@ import java.lang.annotation.RetentionPolicy;
@SystemApi
@VisibleForTesting
public interface Formula {
+ /** @hide */
@IntDef(
value = {
COMPOUND_FORMULA_TAG,
diff --git a/core/java/android/content/integrity/Rule.java b/core/java/android/content/integrity/Rule.java
index 914f1479edf3..39a0909321d0 100644
--- a/core/java/android/content/integrity/Rule.java
+++ b/core/java/android/content/integrity/Rule.java
@@ -42,6 +42,7 @@ import java.util.Objects;
@VisibleForTesting
public final class Rule implements Parcelable {
+ /** @hide */
@IntDef(
value = {
DENY,
diff --git a/core/java/android/content/om/OverlayInfo.java b/core/java/android/content/om/OverlayInfo.java
index 1a78f793c008..a3487be3cb81 100644
--- a/core/java/android/content/om/OverlayInfo.java
+++ b/core/java/android/content/om/OverlayInfo.java
@@ -20,8 +20,8 @@ import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.UserIdInt;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/content/pm/ActivityInfo.java b/core/java/android/content/pm/ActivityInfo.java
index 26193f6ebb3d..5b1f92642ee2 100644
--- a/core/java/android/content/pm/ActivityInfo.java
+++ b/core/java/android/content/pm/ActivityInfo.java
@@ -18,7 +18,7 @@ package android.content.pm;
import android.annotation.IntDef;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Intent;
import android.content.res.Configuration;
diff --git a/core/java/android/content/pm/ApplicationInfo.java b/core/java/android/content/pm/ApplicationInfo.java
index 552c8ac03071..1aed9772700b 100644
--- a/core/java/android/content/pm/ApplicationInfo.java
+++ b/core/java/android/content/pm/ApplicationInfo.java
@@ -22,7 +22,7 @@ import android.annotation.IntDef;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
diff --git a/core/java/android/content/pm/AuxiliaryResolveInfo.java b/core/java/android/content/pm/AuxiliaryResolveInfo.java
index 202df50dda6f..7d07e1dc6361 100644
--- a/core/java/android/content/pm/AuxiliaryResolveInfo.java
+++ b/core/java/android/content/pm/AuxiliaryResolveInfo.java
@@ -46,17 +46,21 @@ public final class AuxiliaryResolveInfo {
public final Intent failureIntent;
/** The matching filters for this resolve info. */
public final List<AuxiliaryFilter> filters;
+ /** Stored {@link InstantAppRequest#hostDigestPrefixSecure} to prevent re-generation */
+ public final int[] hostDigestPrefixSecure;
/** Create a response for installing an instant application. */
public AuxiliaryResolveInfo(@NonNull String token,
boolean needsPhase2,
@Nullable Intent failureIntent,
- @Nullable List<AuxiliaryFilter> filters) {
+ @Nullable List<AuxiliaryFilter> filters,
+ @Nullable int[] hostDigestPrefix) {
this.token = token;
this.needsPhaseTwo = needsPhase2;
this.failureIntent = failureIntent;
this.filters = filters;
this.installFailureActivity = null;
+ this.hostDigestPrefixSecure = hostDigestPrefix;
}
/** Create a response for installing a split on demand. */
@@ -69,6 +73,7 @@ public final class AuxiliaryResolveInfo {
this.token = null;
this.needsPhaseTwo = false;
this.failureIntent = failureIntent;
+ this.hostDigestPrefixSecure = null;
}
/** Create a response for installing a split on demand. */
@@ -126,4 +131,4 @@ public final class AuxiliaryResolveInfo {
+ ", splitName='" + splitName + '\'' + '}';
}
}
-} \ No newline at end of file
+}
diff --git a/core/java/android/content/pm/BaseParceledListSlice.java b/core/java/android/content/pm/BaseParceledListSlice.java
index 4178309450bd..bd847bfdb719 100644
--- a/core/java/android/content/pm/BaseParceledListSlice.java
+++ b/core/java/android/content/pm/BaseParceledListSlice.java
@@ -16,7 +16,7 @@
package android.content.pm;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
@@ -47,7 +47,7 @@ abstract class BaseParceledListSlice<T> implements Parcelable {
* TODO get this number from somewhere else. For now set it to a quarter of
* the 1MB limit.
*/
- private static final int MAX_IPC_SIZE = IBinder.MAX_IPC_SIZE;
+ private static final int MAX_IPC_SIZE = IBinder.getSuggestedMaxIpcSizeBytes();
private final List<T> mList;
diff --git a/core/java/android/content/pm/ComponentInfo.java b/core/java/android/content/pm/ComponentInfo.java
index 10f0df7a7c42..8b41c04b3549 100644
--- a/core/java/android/content/pm/ComponentInfo.java
+++ b/core/java/android/content/pm/ComponentInfo.java
@@ -16,7 +16,7 @@
package android.content.pm;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
diff --git a/core/java/android/os/incremental/IncrementalDataLoaderParams.java b/core/java/android/content/pm/DataLoaderParams.java
index 701f1cc8de02..b163861c53b5 100644
--- a/core/java/android/os/incremental/IncrementalDataLoaderParams.java
+++ b/core/java/android/content/pm/DataLoaderParams.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package android.os.incremental;
+package android.content.pm;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -29,12 +29,12 @@ import java.util.stream.Collectors;
* Hide for now.
* @hide
*/
-public class IncrementalDataLoaderParams {
- @NonNull private final IncrementalDataLoaderParamsParcel mData;
+public class DataLoaderParams {
+ @NonNull private final DataLoaderParamsParcel mData;
- public IncrementalDataLoaderParams(@NonNull String url, @NonNull String packageName,
+ public DataLoaderParams(@NonNull String url, @NonNull String packageName,
@Nullable Map<String, ParcelFileDescriptor> namedFds) {
- IncrementalDataLoaderParamsParcel data = new IncrementalDataLoaderParamsParcel();
+ DataLoaderParamsParcel data = new DataLoaderParamsParcel();
data.staticArgs = url;
data.packageName = packageName;
if (namedFds == null || namedFds.isEmpty()) {
@@ -52,7 +52,7 @@ public class IncrementalDataLoaderParams {
mData = data;
}
- public IncrementalDataLoaderParams(@NonNull IncrementalDataLoaderParamsParcel data) {
+ public DataLoaderParams(@NonNull DataLoaderParamsParcel data) {
mData = data;
}
@@ -70,7 +70,7 @@ public class IncrementalDataLoaderParams {
return mData.packageName;
}
- public final @NonNull IncrementalDataLoaderParamsParcel getData() {
+ public final @NonNull DataLoaderParamsParcel getData() {
return mData;
}
diff --git a/core/java/android/os/incremental/IncrementalDataLoaderParamsParcel.aidl b/core/java/android/content/pm/DataLoaderParamsParcel.aidl
index cd988dcace5b..33163980b915 100644
--- a/core/java/android/os/incremental/IncrementalDataLoaderParamsParcel.aidl
+++ b/core/java/android/content/pm/DataLoaderParamsParcel.aidl
@@ -14,15 +14,15 @@
* limitations under the License.
*/
-package android.os.incremental;
+package android.content.pm;
-import android.os.incremental.NamedParcelFileDescriptor;
+import android.content.pm.NamedParcelFileDescriptor;
/**
* Class for holding data loader configuration parameters.
* @hide
*/
-parcelable IncrementalDataLoaderParamsParcel {
+parcelable DataLoaderParamsParcel {
@utf8InCpp String packageName;
@utf8InCpp String staticArgs;
NamedParcelFileDescriptor[] dynamicArgs;
diff --git a/core/java/android/content/pm/FileSystemControlParcel.aidl b/core/java/android/content/pm/FileSystemControlParcel.aidl
new file mode 100644
index 000000000000..f00feaeb2f5a
--- /dev/null
+++ b/core/java/android/content/pm/FileSystemControlParcel.aidl
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2019 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.content.pm;
+
+import android.content.pm.IPackageInstallerSessionFileSystemConnector;
+import android.os.incremental.IncrementalFileSystemControlParcel;
+
+/**
+ * Wraps info needed for DataLoader to provide data.
+ * @hide
+ */
+parcelable FileSystemControlParcel {
+ // Incremental FS control descriptors.
+ @nullable IncrementalFileSystemControlParcel incremental;
+ // Callback-based installation connector.
+ @nullable IPackageInstallerSessionFileSystemConnector callback;
+}
diff --git a/core/java/android/content/pm/IDataLoader.aidl b/core/java/android/content/pm/IDataLoader.aidl
index 60cc9ba9e141..c65bd6acbaf8 100644
--- a/core/java/android/content/pm/IDataLoader.aidl
+++ b/core/java/android/content/pm/IDataLoader.aidl
@@ -30,5 +30,4 @@ oneway interface IDataLoader {
void start(in List<InstallationFile> fileInfos);
void stop();
void destroy();
- void onFileCreated(long inode, in byte[] metadata);
}
diff --git a/core/java/android/content/pm/IPackageInstallerSession.aidl b/core/java/android/content/pm/IPackageInstallerSession.aidl
index 0b3c7654f4fb..e9546353d5f3 100644
--- a/core/java/android/content/pm/IPackageInstallerSession.aidl
+++ b/core/java/android/content/pm/IPackageInstallerSession.aidl
@@ -39,6 +39,9 @@ interface IPackageInstallerSession {
void transfer(in String packageName, in IntentSender statusReceiver);
void abandon();
+ void addFile(String name, long lengthBytes, in byte[] metadata);
+ void removeFile(String name);
+
boolean isMultiPackage();
int[] getChildSessionIds();
void addChildSessionId(in int sessionId);
@@ -46,5 +49,4 @@ interface IPackageInstallerSession {
int getParentSessionId();
boolean isStaged();
- void addFile(in String name, long size, in byte[] metadata);
}
diff --git a/core/java/android/content/pm/IPackageInstallerSessionFileSystemConnector.aidl b/core/java/android/content/pm/IPackageInstallerSessionFileSystemConnector.aidl
new file mode 100644
index 000000000000..4b2f29e5ae78
--- /dev/null
+++ b/core/java/android/content/pm/IPackageInstallerSessionFileSystemConnector.aidl
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2019 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.content.pm;
+
+import android.os.ParcelFileDescriptor;
+
+/** {@hide} */
+interface IPackageInstallerSessionFileSystemConnector {
+ void writeData(String name, long offsetBytes, long lengthBytes, in ParcelFileDescriptor fd);
+}
diff --git a/core/java/android/content/pm/InstantAppRequest.java b/core/java/android/content/pm/InstantAppRequest.java
index 361d4e4acb3b..f692db1f0443 100644
--- a/core/java/android/content/pm/InstantAppRequest.java
+++ b/core/java/android/content/pm/InstantAppRequest.java
@@ -16,9 +16,10 @@
package android.content.pm;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.content.Intent;
import android.os.Bundle;
-import android.text.TextUtils;
/**
* Information needed to make an instant application resolution request.
@@ -34,32 +35,40 @@ public final class InstantAppRequest {
public final String resolvedType;
/** The name of the package requesting the instant application */
public final String callingPackage;
+ /** Whether or not the requesting package was an instant app */
+ public final boolean isRequesterInstantApp;
/** ID of the user requesting the instant application */
public final int userId;
/**
* Optional extra bundle provided by the source application to the installer for additional
- * verification. */
+ * verification.
+ */
public final Bundle verificationBundle;
/** Whether resolution occurs because an application is starting */
public final boolean resolveForStart;
- /** The instant app digest for this request */
- public final InstantAppResolveInfo.InstantAppDigest digest;
+ /**
+ * The hash prefix of an instant app's domain or null if no host is defined.
+ * Secure version that should be carried through for external use.
+ */
+ @Nullable
+ public final int[] hostDigestPrefixSecure;
+ /** A unique identifier */
+ @NonNull
+ public final String token;
public InstantAppRequest(AuxiliaryResolveInfo responseObj, Intent origIntent,
- String resolvedType, String callingPackage, int userId, Bundle verificationBundle,
- boolean resolveForStart) {
+ String resolvedType, String callingPackage, boolean isRequesterInstantApp,
+ int userId, Bundle verificationBundle, boolean resolveForStart,
+ @Nullable int[] hostDigestPrefixSecure, @NonNull String token) {
this.responseObj = responseObj;
this.origIntent = origIntent;
this.resolvedType = resolvedType;
this.callingPackage = callingPackage;
+ this.isRequesterInstantApp = isRequesterInstantApp;
this.userId = userId;
this.verificationBundle = verificationBundle;
this.resolveForStart = resolveForStart;
- if (origIntent.getData() != null && !TextUtils.isEmpty(origIntent.getData().getHost())) {
- digest = new InstantAppResolveInfo.InstantAppDigest(
- origIntent.getData().getHost(), 5 /*maxDigests*/);
- } else {
- digest = InstantAppResolveInfo.InstantAppDigest.UNDEFINED;
- }
+ this.hostDigestPrefixSecure = hostDigestPrefixSecure;
+ this.token = token;
}
}
diff --git a/core/java/android/content/pm/InstantAppRequestInfo.aidl b/core/java/android/content/pm/InstantAppRequestInfo.aidl
new file mode 100644
index 000000000000..0f94220bc5da
--- /dev/null
+++ b/core/java/android/content/pm/InstantAppRequestInfo.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2019 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.content.pm;
+
+parcelable InstantAppRequestInfo;
diff --git a/core/java/android/content/pm/InstantAppRequestInfo.java b/core/java/android/content/pm/InstantAppRequestInfo.java
new file mode 100644
index 000000000000..83d55361ff2a
--- /dev/null
+++ b/core/java/android/content/pm/InstantAppRequestInfo.java
@@ -0,0 +1,188 @@
+/*
+ * Copyright (C) 2019 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.content.pm;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.SystemApi;
+import android.content.Intent;
+import android.os.Parcelable;
+import android.os.UserHandle;
+
+import com.android.internal.util.DataClass;
+
+/**
+ * Information exposed to {@link android.app.InstantAppResolverService} to complete
+ * an instant application resolution request.
+ * @hide
+ */
+@SystemApi
+@DataClass(genParcelable = true, genConstructor = true, genAidl = true)
+public final class InstantAppRequestInfo implements Parcelable {
+
+ /**
+ * The sanitized {@link Intent} used for resolution. A sanitized Intent is an intent with
+ * potential PII removed from the original intent. Fields removed include extras and the
+ * host + path of the data, if defined.
+ */
+ @NonNull
+ public final Intent intent;
+
+ /** The hash prefix of the instant app's domain or null if no host is defined. */
+ @Nullable
+ public final int[] hostDigestPrefix;
+
+ /** The user requesting the instant application */
+ @NonNull
+ public final UserHandle userHandle;
+
+ /** Whether or not the requesting package was an instant app itself */
+ public final boolean isRequesterInstantApp;
+
+ /** A unique identifier */
+ @NonNull
+ public final String token;
+
+
+
+ // Code below generated by codegen v1.0.13.
+ //
+ // DO NOT MODIFY!
+ // CHECKSTYLE:OFF Generated code
+ //
+ // To regenerate run:
+ // $ codegen $ANDROID_BUILD_TOP/frameworks/base/core/java/android/content/pm/InstantAppRequestInfo.java
+ //
+ // To exclude the generated code from IntelliJ auto-formatting enable (one-time):
+ // Settings > Editor > Code Style > Formatter Control
+ //@formatter:off
+
+
+ /**
+ * Creates a new InstantAppRequestInfo.
+ *
+ * @param intent
+ * The sanitized {@link Intent} used for resolution. A sanitized Intent is an intent with
+ * potential PII removed from the original intent. Fields removed include extras and the
+ * host + path of the data, if defined.
+ * @param hostDigestPrefix
+ * The hash prefix of the instant app's domain or null if no host is defined.
+ * @param userHandle
+ * The user requesting the instant application
+ * @param isRequesterInstantApp
+ * Whether or not the requesting package was an instant app itself
+ * @param token
+ * A unique identifier
+ */
+ @DataClass.Generated.Member
+ public InstantAppRequestInfo(
+ @NonNull Intent intent,
+ @Nullable int[] hostDigestPrefix,
+ @NonNull UserHandle userHandle,
+ boolean isRequesterInstantApp,
+ @NonNull String token) {
+ this.intent = intent;
+ com.android.internal.util.AnnotationValidations.validate(
+ NonNull.class, null, intent);
+ this.hostDigestPrefix = hostDigestPrefix;
+ this.userHandle = userHandle;
+ com.android.internal.util.AnnotationValidations.validate(
+ NonNull.class, null, userHandle);
+ this.isRequesterInstantApp = isRequesterInstantApp;
+ this.token = token;
+ com.android.internal.util.AnnotationValidations.validate(
+ NonNull.class, null, token);
+
+ // onConstructed(); // You can define this method to get a callback
+ }
+
+ @Override
+ @DataClass.Generated.Member
+ public void writeToParcel(@NonNull android.os.Parcel dest, int flags) {
+ // You can override field parcelling by defining methods like:
+ // void parcelFieldName(Parcel dest, int flags) { ... }
+
+ byte flg = 0;
+ if (isRequesterInstantApp) flg |= 0x8;
+ if (hostDigestPrefix != null) flg |= 0x2;
+ dest.writeByte(flg);
+ dest.writeTypedObject(intent, flags);
+ if (hostDigestPrefix != null) dest.writeIntArray(hostDigestPrefix);
+ dest.writeTypedObject(userHandle, flags);
+ dest.writeString(token);
+ }
+
+ @Override
+ @DataClass.Generated.Member
+ public int describeContents() { return 0; }
+
+ /** @hide */
+ @SuppressWarnings({"unchecked", "RedundantCast"})
+ @DataClass.Generated.Member
+ /* package-private */ InstantAppRequestInfo(@NonNull android.os.Parcel in) {
+ // You can override field unparcelling by defining methods like:
+ // static FieldType unparcelFieldName(Parcel in) { ... }
+
+ byte flg = in.readByte();
+ boolean _isRequesterInstantApp = (flg & 0x8) != 0;
+ Intent _intent = (Intent) in.readTypedObject(Intent.CREATOR);
+ int[] _hostDigestPrefix = (flg & 0x2) == 0 ? null : in.createIntArray();
+ UserHandle _userHandle = (UserHandle) in.readTypedObject(UserHandle.CREATOR);
+ String _token = in.readString();
+
+ this.intent = _intent;
+ com.android.internal.util.AnnotationValidations.validate(
+ NonNull.class, null, intent);
+ this.hostDigestPrefix = _hostDigestPrefix;
+ this.userHandle = _userHandle;
+ com.android.internal.util.AnnotationValidations.validate(
+ NonNull.class, null, userHandle);
+ this.isRequesterInstantApp = _isRequesterInstantApp;
+ this.token = _token;
+ com.android.internal.util.AnnotationValidations.validate(
+ NonNull.class, null, token);
+
+ // onConstructed(); // You can define this method to get a callback
+ }
+
+ @DataClass.Generated.Member
+ public static final @NonNull Parcelable.Creator<InstantAppRequestInfo> CREATOR
+ = new Parcelable.Creator<InstantAppRequestInfo>() {
+ @Override
+ public InstantAppRequestInfo[] newArray(int size) {
+ return new InstantAppRequestInfo[size];
+ }
+
+ @Override
+ public InstantAppRequestInfo createFromParcel(@NonNull android.os.Parcel in) {
+ return new InstantAppRequestInfo(in);
+ }
+ };
+
+ @DataClass.Generated(
+ time = 1574373347443L,
+ codegenVersion = "1.0.13",
+ sourceFile = "frameworks/base/core/java/android/content/pm/InstantAppRequestInfo.java",
+ inputSignatures = "public final @android.annotation.NonNull android.content.Intent intent\npublic final @android.annotation.Nullable int[] hostDigestPrefix\npublic final @android.annotation.NonNull android.os.UserHandle userHandle\npublic final boolean isRequesterInstantApp\npublic final @android.annotation.NonNull java.lang.String token\nclass InstantAppRequestInfo extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genParcelable=true, genConstructor=true, genAidl=true)")
+ @Deprecated
+ private void __metadata() {}
+
+
+ //@formatter:on
+ // End of generated code
+
+}
diff --git a/core/java/android/content/pm/LauncherActivityInfo.java b/core/java/android/content/pm/LauncherActivityInfo.java
index 1451431b7852..67deb82f1fbb 100644
--- a/core/java/android/content/pm/LauncherActivityInfo.java
+++ b/core/java/android/content/pm/LauncherActivityInfo.java
@@ -16,7 +16,7 @@
package android.content.pm;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
diff --git a/core/java/android/content/pm/LauncherApps.java b/core/java/android/content/pm/LauncherApps.java
index d2a40304e078..94a537583b77 100644
--- a/core/java/android/content/pm/LauncherApps.java
+++ b/core/java/android/content/pm/LauncherApps.java
@@ -25,10 +25,10 @@ import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
diff --git a/core/java/android/os/incremental/NamedParcelFileDescriptor.aidl b/core/java/android/content/pm/NamedParcelFileDescriptor.aidl
index 038ced1744a1..68dd5f54654b 100644
--- a/core/java/android/os/incremental/NamedParcelFileDescriptor.aidl
+++ b/core/java/android/content/pm/NamedParcelFileDescriptor.aidl
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package android.os.incremental;
+package android.content.pm;
import android.os.ParcelFileDescriptor;
diff --git a/core/java/android/content/pm/PackageInfo.java b/core/java/android/content/pm/PackageInfo.java
index aa0002df2c3a..36fa5728b34e 100644
--- a/core/java/android/content/pm/PackageInfo.java
+++ b/core/java/android/content/pm/PackageInfo.java
@@ -17,7 +17,7 @@
package android.content.pm;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/content/pm/PackageInfoLite.java b/core/java/android/content/pm/PackageInfoLite.java
index f5442ec48d19..6743a3f86944 100644
--- a/core/java/android/content/pm/PackageInfoLite.java
+++ b/core/java/android/content/pm/PackageInfoLite.java
@@ -16,7 +16,7 @@
package android.content.pm;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/content/pm/PackageInstaller.java b/core/java/android/content/pm/PackageInstaller.java
index f017aad25c0c..5386422480a0 100644
--- a/core/java/android/content/pm/PackageInstaller.java
+++ b/core/java/android/content/pm/PackageInstaller.java
@@ -26,9 +26,9 @@ import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityManager;
import android.app.AppGlobals;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.IIntentReceiver;
import android.content.IIntentSender;
import android.content.Intent;
@@ -50,8 +50,6 @@ import android.os.ParcelableException;
import android.os.RemoteException;
import android.os.SystemProperties;
import android.os.UserHandle;
-import android.os.incremental.IncrementalDataLoaderParams;
-import android.os.incremental.IncrementalDataLoaderParamsParcel;
import android.system.ErrnoException;
import android.system.Os;
import android.util.ArraySet;
@@ -231,6 +229,15 @@ public class PackageInstaller {
public static final String EXTRA_CALLBACK = "android.content.pm.extra.CALLBACK";
/**
+ * Streaming installation pending.
+ * Caller should make sure DataLoader is able to prepare image and reinitiate the operation.
+ *
+ * @see #EXTRA_SESSION_ID
+ * {@hide}
+ */
+ public static final int STATUS_PENDING_STREAMING = -2;
+
+ /**
* User action is currently required to proceed. You can launch the intent
* activity described by {@link Intent#EXTRA_INTENT} to involve the user and
* continue.
@@ -1059,13 +1066,56 @@ public class PackageInstaller {
}
}
+
+ /**
+ * Adds a file to session. On commit this file will be pulled from dataLoader.
+ *
+ * @param name arbitrary, unique name of your choosing to identify the
+ * APK being written. You can open a file again for
+ * additional writes (such as after a reboot) by using the
+ * same name. This name is only meaningful within the context
+ * of a single install session.
+ * @param lengthBytes total size of the file being written.
+ * The system may clear various caches as needed to allocate
+ * this space.
+ * @param metadata additional info use by dataLoader to pull data for the file.
+ * @throws SecurityException if called after the session has been
+ * sealed or abandoned
+ * @throws IllegalStateException if called for non-callback session
+ * {@hide}
+ */
+ public void addFile(@NonNull String name, long lengthBytes, @NonNull byte[] metadata) {
+ try {
+ mSession.addFile(name, lengthBytes, metadata);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Removes a file.
+ *
+ * @param name name of a file, e.g. split.
+ * @throws SecurityException if called after the session has been
+ * sealed or abandoned
+ * @throws IllegalStateException if called for non-callback session
+ * {@hide}
+ */
+ public void removeFile(@NonNull String name) {
+ try {
+ mSession.removeFile(name);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
/**
* Attempt to commit everything staged in this session. This may require
* user intervention, and so it may not happen immediately. The final
* result of the commit will be reported through the given callback.
* <p>
- * Once this method is called, the session is sealed and no additional
- * mutations may be performed on the session. If the device reboots
+ * Once this method is called, the session is sealed and no additional mutations may be
+ * performed on the session. In case of device reboot or data loader transient failure
* before the session has been finalized, you may commit the session again.
* <p>
* If the installer is the device owner or the affiliated profile owner, there will be no
@@ -1220,27 +1270,6 @@ public class PackageInstaller {
}
/**
- * Configure files for an installation session.
- *
- * Currently only for Incremental installation session. Once this method is called,
- * the files and their paths, as specified in the parameters, will be created and properly
- * configured in the Incremental File System.
- *
- * TODO(b/136132412): update this and InstallationFile class with latest API design.
- *
- * @throws IllegalStateException if {@link SessionParams#incrementalParams} is null.
- *
- * @hide
- */
- public void addFile(@NonNull String name, long size, @NonNull byte[] metadata) {
- try {
- mSession.addFile(name, size, metadata);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
* Release this session object. You can open the session again if it
* hasn't been finalized.
*/
@@ -1428,7 +1457,10 @@ public class PackageInstaller {
/** {@hide} */
public long requiredInstalledVersionCode = PackageManager.VERSION_CODE_HIGHEST;
/** {@hide} */
- public IncrementalDataLoaderParams incrementalParams;
+ public DataLoaderParams incrementalParams;
+ /** TODO(b/146080380): add a class name to make it fully compatible with ComponentName.
+ * {@hide} */
+ public String dataLoaderPackageName;
/**
* Construct parameters for a new package install session.
@@ -1462,12 +1494,13 @@ public class PackageInstaller {
isMultiPackage = source.readBoolean();
isStaged = source.readBoolean();
requiredInstalledVersionCode = source.readLong();
- IncrementalDataLoaderParamsParcel dataLoaderParamsParcel = source.readParcelable(
- IncrementalDataLoaderParamsParcel.class.getClassLoader());
+ DataLoaderParamsParcel dataLoaderParamsParcel = source.readParcelable(
+ DataLoaderParamsParcel.class.getClassLoader());
if (dataLoaderParamsParcel != null) {
- incrementalParams = new IncrementalDataLoaderParams(
+ incrementalParams = new DataLoaderParams(
dataLoaderParamsParcel);
}
+ dataLoaderPackageName = source.readString();
}
/** {@hide} */
@@ -1492,6 +1525,7 @@ public class PackageInstaller {
ret.isStaged = isStaged;
ret.requiredInstalledVersionCode = requiredInstalledVersionCode;
ret.incrementalParams = incrementalParams;
+ ret.dataLoaderPackageName = dataLoaderPackageName;
return ret;
}
@@ -1770,7 +1804,8 @@ public class PackageInstaller {
* @param installerPackageName name of the installer package
* {@hide}
*/
- public void setInstallerPackageName(String installerPackageName) {
+ @TestApi
+ public void setInstallerPackageName(@Nullable String installerPackageName) {
this.installerPackageName = installerPackageName;
}
@@ -1826,10 +1861,24 @@ public class PackageInstaller {
* {@hide}
*/
@RequiresPermission(Manifest.permission.INSTALL_PACKAGES)
- public void setIncrementalParams(@NonNull IncrementalDataLoaderParams incrementalParams) {
+ public void setIncrementalParams(@NonNull DataLoaderParams incrementalParams) {
this.incrementalParams = incrementalParams;
}
+ /**
+ * Set the data provider params for the session.
+ * This also switches installation into callback mode and disallow direct writes into
+ * staging folder.
+ * TODO(b/146080380): unify dataprovider params with Incremental.
+ *
+ * @param dataLoaderPackageName name of the dataLoader package
+ * {@hide}
+ */
+ @RequiresPermission(Manifest.permission.INSTALL_PACKAGES)
+ public void setDataLoaderPackageName(String dataLoaderPackageName) {
+ this.dataLoaderPackageName = dataLoaderPackageName;
+ }
+
/** {@hide} */
public void dump(IndentingPrintWriter pw) {
pw.printPair("mode", mode);
@@ -1850,6 +1899,7 @@ public class PackageInstaller {
pw.printPair("isMultiPackage", isMultiPackage);
pw.printPair("isStaged", isStaged);
pw.printPair("requiredInstalledVersionCode", requiredInstalledVersionCode);
+ pw.printPair("dataLoaderPackageName", dataLoaderPackageName);
pw.println();
}
@@ -1884,6 +1934,7 @@ public class PackageInstaller {
} else {
dest.writeParcelable(null, flags);
}
+ dest.writeString(dataLoaderPackageName);
}
public static final Parcelable.Creator<SessionParams>
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index 6e890ba0d827..21c9739dd1ee 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -29,7 +29,6 @@ import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.StringRes;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.UserIdInt;
import android.annotation.XmlRes;
import android.app.ActivityManager;
@@ -40,6 +39,7 @@ import android.app.admin.DevicePolicyManager;
import android.app.usage.StorageStatsManager;
import android.compat.annotation.ChangeId;
import android.compat.annotation.Disabled;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
@@ -946,7 +946,8 @@ public abstract class PackageManager {
INSTALL_REASON_POLICY,
INSTALL_REASON_DEVICE_RESTORE,
INSTALL_REASON_DEVICE_SETUP,
- INSTALL_REASON_USER
+ INSTALL_REASON_USER,
+ INSTALL_REASON_ROLLBACK
})
@Retention(RetentionPolicy.SOURCE)
public @interface InstallReason {}
@@ -977,6 +978,13 @@ public abstract class PackageManager {
public static final int INSTALL_REASON_USER = 4;
/**
+ * Code indicating that the package installation was a rollback initiated by RollbackManager.
+ *
+ * @hide
+ */
+ public static final int INSTALL_REASON_ROLLBACK = 5;
+
+ /**
* @hide
*/
public static final int INSTALL_UNKNOWN = 0;
@@ -1505,16 +1513,6 @@ public abstract class PackageManager {
public static final int DELETE_DONT_KILL_APP = 0x00000008;
/**
- * Flag parameter for {@link #deletePackage} to indicate that any
- * contributed media should also be deleted during this uninstall. The
- * meaning of "contributed" means it won't automatically be deleted when the
- * app is uninstalled.
- *
- * @hide
- */
- public static final int DELETE_CONTRIBUTED_MEDIA = 0x00000010;
-
- /**
* Flag parameter for {@link #deletePackage} to indicate that package deletion
* should be chatty.
*
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index 65ee1e5f0370..47edf2e6fd3a 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -47,11 +47,11 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.StringRes;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.apex.ApexInfo;
import android.app.ActivityTaskManager;
import android.app.ActivityThread;
import android.app.ResourcesManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
diff --git a/core/java/android/content/pm/PackageStats.java b/core/java/android/content/pm/PackageStats.java
index b0fecfac2471..7c1252737f09 100644
--- a/core/java/android/content/pm/PackageStats.java
+++ b/core/java/android/content/pm/PackageStats.java
@@ -16,8 +16,8 @@
package android.content.pm;
-import android.annotation.UnsupportedAppUsage;
import android.app.usage.StorageStatsManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/content/pm/PackageUserState.java b/core/java/android/content/pm/PackageUserState.java
index 55574c3cb880..f0f6753fc93e 100644
--- a/core/java/android/content/pm/PackageUserState.java
+++ b/core/java/android/content/pm/PackageUserState.java
@@ -27,7 +27,7 @@ import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
import static android.content.pm.PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS;
import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.parsing.ComponentParseUtils;
import android.os.BaseBundle;
import android.os.Debug;
diff --git a/core/java/android/content/pm/ParceledListSlice.aidl b/core/java/android/content/pm/ParceledListSlice.aidl
index c02cc6a5472e..5031fbaca9e6 100644
--- a/core/java/android/content/pm/ParceledListSlice.aidl
+++ b/core/java/android/content/pm/ParceledListSlice.aidl
@@ -16,4 +16,4 @@
package android.content.pm;
-parcelable ParceledListSlice;
+parcelable ParceledListSlice<T>;
diff --git a/core/java/android/content/pm/ParceledListSlice.java b/core/java/android/content/pm/ParceledListSlice.java
index dccc52494f59..73119e05095b 100644
--- a/core/java/android/content/pm/ParceledListSlice.java
+++ b/core/java/android/content/pm/ParceledListSlice.java
@@ -16,7 +16,7 @@
package android.content.pm;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/content/pm/PermissionInfo.java b/core/java/android/content/pm/PermissionInfo.java
index c77c53f387e2..89a1c6ad9241 100644
--- a/core/java/android/content/pm/PermissionInfo.java
+++ b/core/java/android/content/pm/PermissionInfo.java
@@ -22,7 +22,7 @@ import android.annotation.Nullable;
import android.annotation.StringRes;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
diff --git a/core/java/android/content/pm/RegisteredServicesCache.java b/core/java/android/content/pm/RegisteredServicesCache.java
index 23fbefb73c50..bd909c7a3f59 100644
--- a/core/java/android/content/pm/RegisteredServicesCache.java
+++ b/core/java/android/content/pm/RegisteredServicesCache.java
@@ -17,7 +17,7 @@
package android.content.pm;
import android.Manifest;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
@@ -43,11 +43,11 @@ import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.ArrayUtils;
import com.android.internal.util.FastXmlSerializer;
+import libcore.io.IoUtils;
+
import com.google.android.collect.Lists;
import com.google.android.collect.Maps;
-import libcore.io.IoUtils;
-
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;
diff --git a/core/java/android/content/pm/ResolveInfo.java b/core/java/android/content/pm/ResolveInfo.java
index 4d3e1f72676b..55846adf2f1f 100644
--- a/core/java/android/content/pm/ResolveInfo.java
+++ b/core/java/android/content/pm/ResolveInfo.java
@@ -17,7 +17,7 @@
package android.content.pm;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
diff --git a/core/java/android/content/pm/ShortcutInfo.java b/core/java/android/content/pm/ShortcutInfo.java
index 5a80079695d3..2c4ccbf2a502 100644
--- a/core/java/android/content/pm/ShortcutInfo.java
+++ b/core/java/android/content/pm/ShortcutInfo.java
@@ -20,11 +20,11 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.UserIdInt;
import android.app.Notification;
import android.app.Person;
import android.app.TaskStackBuilder;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
diff --git a/core/java/android/content/pm/ShortcutManager.java b/core/java/android/content/pm/ShortcutManager.java
index f85179942938..dde8865467a1 100644
--- a/core/java/android/content/pm/ShortcutManager.java
+++ b/core/java/android/content/pm/ShortcutManager.java
@@ -22,9 +22,9 @@ import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.UserIdInt;
import android.app.usage.UsageStatsManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
diff --git a/core/java/android/content/pm/Signature.java b/core/java/android/content/pm/Signature.java
index 25a4dca4d815..3b84ae775ad1 100644
--- a/core/java/android/content/pm/Signature.java
+++ b/core/java/android/content/pm/Signature.java
@@ -16,7 +16,7 @@
package android.content.pm;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/content/pm/UserInfo.java b/core/java/android/content/pm/UserInfo.java
index fff9cf399b67..008cfa5e9423 100644
--- a/core/java/android/content/pm/UserInfo.java
+++ b/core/java/android/content/pm/UserInfo.java
@@ -18,8 +18,8 @@ package android.content.pm;
import android.annotation.IntDef;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.UserIdInt;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.UserHandle;
diff --git a/core/java/android/content/pm/VerifierInfo.java b/core/java/android/content/pm/VerifierInfo.java
index 224ca628cf27..5f8855572ef0 100644
--- a/core/java/android/content/pm/VerifierInfo.java
+++ b/core/java/android/content/pm/VerifierInfo.java
@@ -16,7 +16,7 @@
package android.content.pm;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/content/pm/XmlSerializerAndParser.java b/core/java/android/content/pm/XmlSerializerAndParser.java
index 6d24800edb07..5dce83902f78 100644
--- a/core/java/android/content/pm/XmlSerializerAndParser.java
+++ b/core/java/android/content/pm/XmlSerializerAndParser.java
@@ -16,11 +16,12 @@
package android.content.pm;
-import org.xmlpull.v1.XmlSerializer;
+import android.compat.annotation.UnsupportedAppUsage;
+
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
+import org.xmlpull.v1.XmlSerializer;
-import android.annotation.UnsupportedAppUsage;
import java.io.IOException;
/** @hide */
diff --git a/core/java/android/content/pm/parsing/ApkParseUtils.java b/core/java/android/content/pm/parsing/ApkParseUtils.java
index ffddbb6c2c47..773231682fe4 100644
--- a/core/java/android/content/pm/parsing/ApkParseUtils.java
+++ b/core/java/android/content/pm/parsing/ApkParseUtils.java
@@ -2338,7 +2338,7 @@ public class ApkParseUtils {
parsingPackage.setProfileableByShell(true);
}
XmlUtils.skipCurrentTag(parser);
-
+ break;
default:
if (!PackageParser.RIGID_PARSER) {
Slog.w(TAG, "Unknown element under <application>: " + tagName
diff --git a/core/java/android/content/pm/parsing/ComponentParseUtils.java b/core/java/android/content/pm/parsing/ComponentParseUtils.java
index 5364313f5760..fc210b266040 100644
--- a/core/java/android/content/pm/parsing/ComponentParseUtils.java
+++ b/core/java/android/content/pm/parsing/ComponentParseUtils.java
@@ -768,6 +768,10 @@ public class ComponentParseUtils {
protected PatternMatcher[] uriPermissionPatterns;
protected PathPermission[] pathPermissions;
+ public ParsedProvider(ParsedProvider other) {
+ this.setFrom(other);
+ }
+
protected void setFrom(ParsedProvider other) {
super.setFrom(other);
this.exported = other.exported;
@@ -823,6 +827,10 @@ public class ComponentParseUtils {
return authority;
}
+ public void setSyncable(boolean isSyncable) {
+ this.isSyncable = isSyncable;
+ }
+
public boolean isSyncable() {
return isSyncable;
}
diff --git a/core/java/android/content/pm/parsing/PackageInfoUtils.java b/core/java/android/content/pm/parsing/PackageInfoUtils.java
index 28f0bc4e431f..f2cf9a484c6e 100644
--- a/core/java/android/content/pm/parsing/PackageInfoUtils.java
+++ b/core/java/android/content/pm/parsing/PackageInfoUtils.java
@@ -436,7 +436,7 @@ public class PackageInfoUtils {
ii.functionalTest = i.functionalTest;
ii.sourceDir = pkg.getBaseCodePath();
- ii.publicSourceDir = pkg.getCodePath();
+ ii.publicSourceDir = pkg.getBaseCodePath();
ii.splitNames = pkg.getSplitNames();
ii.splitSourceDirs = pkg.getSplitCodePaths();
ii.splitPublicSourceDirs = pkg.getSplitCodePaths();
@@ -485,6 +485,7 @@ public class PackageInfoUtils {
pg.backgroundRequestDetailResourceId
);
assignSharedFieldsForPackageItemInfo(pgi, pg);
+ pgi.descriptionRes = pg.descriptionRes;
pgi.priority = pg.priority;
pgi.requestRes = pg.requestRes;
pgi.flags = pg.flags;
diff --git a/core/java/android/content/res/ApkAssets.java b/core/java/android/content/res/ApkAssets.java
index ad375552837d..0e4a8e633005 100644
--- a/core/java/android/content/res/ApkAssets.java
+++ b/core/java/android/content/res/ApkAssets.java
@@ -17,7 +17,7 @@ package android.content.res;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.om.OverlayableInfo;
import android.content.res.loader.ResourcesProvider;
import android.text.TextUtils;
diff --git a/core/java/android/content/res/AssetFileDescriptor.java b/core/java/android/content/res/AssetFileDescriptor.java
index 2ba55798d665..e93ec00468f5 100644
--- a/core/java/android/content/res/AssetFileDescriptor.java
+++ b/core/java/android/content/res/AssetFileDescriptor.java
@@ -16,7 +16,7 @@
package android.content.res;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Bundle;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
diff --git a/core/java/android/content/res/AssetManager.java b/core/java/android/content/res/AssetManager.java
index 168eae65ddf2..d20dca19d101 100644
--- a/core/java/android/content/res/AssetManager.java
+++ b/core/java/android/content/res/AssetManager.java
@@ -24,7 +24,7 @@ import android.annotation.Nullable;
import android.annotation.StringRes;
import android.annotation.StyleRes;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration.NativeConfig;
import android.content.res.loader.ResourceLoader;
diff --git a/core/java/android/content/res/ColorStateList.java b/core/java/android/content/res/ColorStateList.java
index b5b097b33ef3..f23c802d98e2 100644
--- a/core/java/android/content/res/ColorStateList.java
+++ b/core/java/android/content/res/ColorStateList.java
@@ -19,9 +19,18 @@ package android.content.res;
import android.annotation.ColorInt;
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo.Config;
import android.content.res.Resources.Theme;
import android.graphics.Color;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.util.MathUtils;
+import android.util.SparseArray;
+import android.util.StateSet;
+import android.util.Xml;
import com.android.internal.R;
import com.android.internal.util.ArrayUtils;
@@ -30,16 +39,6 @@ import com.android.internal.util.GrowingArrayUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
-import android.annotation.UnsupportedAppUsage;
-import android.util.AttributeSet;
-import android.util.Log;
-import android.util.MathUtils;
-import android.util.SparseArray;
-import android.util.StateSet;
-import android.util.Xml;
-import android.os.Parcel;
-import android.os.Parcelable;
-
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Arrays;
diff --git a/core/java/android/content/res/CompatibilityInfo.java b/core/java/android/content/res/CompatibilityInfo.java
index f3b7553577ca..c66c70a20729 100644
--- a/core/java/android/content/res/CompatibilityInfo.java
+++ b/core/java/android/content/res/CompatibilityInfo.java
@@ -16,7 +16,7 @@
package android.content.res;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ApplicationInfo;
import android.graphics.Canvas;
import android.graphics.PointF;
diff --git a/core/java/android/content/res/Configuration.java b/core/java/android/content/res/Configuration.java
index 090629fe77cb..8c358cc522d6 100644
--- a/core/java/android/content/res/Configuration.java
+++ b/core/java/android/content/res/Configuration.java
@@ -45,8 +45,8 @@ import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.WindowConfiguration;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.LocaleProto;
import android.content.pm.ActivityInfo;
import android.content.pm.ActivityInfo.Config;
@@ -452,6 +452,9 @@ public final class Configuration implements Parcelable, Comparable<Configuration
if ((diff & ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE) != 0) {
list.add("CONFIG_SMALLEST_SCREEN_SIZE");
}
+ if ((diff & ActivityInfo.CONFIG_DENSITY) != 0) {
+ list.add("CONFIG_DENSITY");
+ }
if ((diff & ActivityInfo.CONFIG_LAYOUT_DIRECTION) != 0) {
list.add("CONFIG_LAYOUT_DIRECTION");
}
@@ -461,6 +464,9 @@ public final class Configuration implements Parcelable, Comparable<Configuration
if ((diff & ActivityInfo.CONFIG_ASSETS_PATHS) != 0) {
list.add("CONFIG_ASSETS_PATHS");
}
+ if ((diff & ActivityInfo.CONFIG_WINDOW_CONFIGURATION) != 0) {
+ list.add("CONFIG_WINDOW_CONFIGURATION");
+ }
StringBuilder builder = new StringBuilder("{");
for (int i = 0, n = list.size(); i < n; i++) {
builder.append(list.get(i));
diff --git a/core/java/android/content/res/ConfigurationBoundResourceCache.java b/core/java/android/content/res/ConfigurationBoundResourceCache.java
index 848790f46734..5e10a5768358 100644
--- a/core/java/android/content/res/ConfigurationBoundResourceCache.java
+++ b/core/java/android/content/res/ConfigurationBoundResourceCache.java
@@ -16,7 +16,7 @@
package android.content.res;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo.Config;
/**
diff --git a/core/java/android/content/res/DrawableCache.java b/core/java/android/content/res/DrawableCache.java
index 90604b8d536a..5497e61fa2e9 100644
--- a/core/java/android/content/res/DrawableCache.java
+++ b/core/java/android/content/res/DrawableCache.java
@@ -16,7 +16,7 @@
package android.content.res;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.drawable.Drawable;
/**
diff --git a/core/java/android/content/res/ObbInfo.java b/core/java/android/content/res/ObbInfo.java
index 8af27ca825d0..c477abcea8ba 100644
--- a/core/java/android/content/res/ObbInfo.java
+++ b/core/java/android/content/res/ObbInfo.java
@@ -16,7 +16,7 @@
package android.content.res;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/content/res/Resources.java b/core/java/android/content/res/Resources.java
index 2698c2de4c61..4725e0af4eec 100644
--- a/core/java/android/content/res/Resources.java
+++ b/core/java/android/content/res/Resources.java
@@ -40,9 +40,9 @@ import android.annotation.RawRes;
import android.annotation.StringRes;
import android.annotation.StyleRes;
import android.annotation.StyleableRes;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.XmlRes;
import android.app.ResourcesManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo;
import android.content.pm.ActivityInfo.Config;
import android.content.res.loader.ResourceLoader;
@@ -1859,6 +1859,7 @@ public class Resources {
mResId = other.mResId == null ? null : other.mResId.clone();
mForce = other.mForce == null ? null : other.mForce.clone();
mCount = other.mCount;
+ mHashCode = other.mHashCode;
}
@Override
diff --git a/core/java/android/content/res/ResourcesImpl.java b/core/java/android/content/res/ResourcesImpl.java
index 84489cfb768c..acdd47a4d61e 100644
--- a/core/java/android/content/res/ResourcesImpl.java
+++ b/core/java/android/content/res/ResourcesImpl.java
@@ -27,7 +27,7 @@ import android.annotation.PluralsRes;
import android.annotation.RawRes;
import android.annotation.StyleRes;
import android.annotation.StyleableRes;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo;
import android.content.pm.ActivityInfo.Config;
import android.content.res.AssetManager.AssetInputStream;
@@ -344,7 +344,7 @@ public class ResourcesImpl {
try {
return mAssets.openNonAssetFd(tempValue.assetCookie, tempValue.string.toString());
} catch (Exception e) {
- throw new NotFoundException("File " + tempValue.string.toString() + " from drawable "
+ throw new NotFoundException("File " + tempValue.string.toString() + " from "
+ "resource ID #0x" + Integer.toHexString(id), e);
}
}
@@ -359,7 +359,7 @@ public class ResourcesImpl {
// Note: value.string might be null
NotFoundException rnf = new NotFoundException("File "
+ (value.string == null ? "(null)" : value.string.toString())
- + " from drawable resource ID #0x" + Integer.toHexString(id));
+ + " from resource ID #0x" + Integer.toHexString(id));
rnf.initCause(e);
throw rnf;
}
diff --git a/core/java/android/content/res/ResourcesKey.java b/core/java/android/content/res/ResourcesKey.java
index 1db2dd85fb37..a29fea09c5ce 100644
--- a/core/java/android/content/res/ResourcesKey.java
+++ b/core/java/android/content/res/ResourcesKey.java
@@ -18,7 +18,7 @@ package android.content.res;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.text.TextUtils;
import java.util.Arrays;
diff --git a/core/java/android/content/res/StringBlock.java b/core/java/android/content/res/StringBlock.java
index d43bd36b4c74..8f3f77b99739 100644
--- a/core/java/android/content/res/StringBlock.java
+++ b/core/java/android/content/res/StringBlock.java
@@ -16,7 +16,7 @@
package android.content.res;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
diff --git a/core/java/android/content/res/ThemedResourceCache.java b/core/java/android/content/res/ThemedResourceCache.java
index 968ab401ccba..3270944ce7e3 100644
--- a/core/java/android/content/res/ThemedResourceCache.java
+++ b/core/java/android/content/res/ThemedResourceCache.java
@@ -18,7 +18,7 @@ package android.content.res;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo.Config;
import android.content.res.Resources.Theme;
import android.content.res.Resources.ThemeKey;
diff --git a/core/java/android/content/res/TypedArray.java b/core/java/android/content/res/TypedArray.java
index 38df317575d7..29c5c935c1bf 100644
--- a/core/java/android/content/res/TypedArray.java
+++ b/core/java/android/content/res/TypedArray.java
@@ -20,7 +20,7 @@ import android.annotation.AnyRes;
import android.annotation.ColorInt;
import android.annotation.Nullable;
import android.annotation.StyleableRes;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo;
import android.content.pm.ActivityInfo.Config;
import android.graphics.Typeface;
diff --git a/core/java/android/content/res/XmlBlock.java b/core/java/android/content/res/XmlBlock.java
index 626bf77046bf..cb93cbfcbfc9 100644
--- a/core/java/android/content/res/XmlBlock.java
+++ b/core/java/android/content/res/XmlBlock.java
@@ -20,7 +20,7 @@ import static android.content.res.Resources.ID_NULL;
import android.annotation.AnyRes;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.util.TypedValue;
import com.android.internal.util.XmlUtils;
diff --git a/core/java/android/content/rollback/IRollbackManager.aidl b/core/java/android/content/rollback/IRollbackManager.aidl
index 8c2a65faf8ed..cda0e9865054 100644
--- a/core/java/android/content/rollback/IRollbackManager.aidl
+++ b/core/java/android/content/rollback/IRollbackManager.aidl
@@ -44,9 +44,10 @@ interface IRollbackManager {
// Used by the staging manager to notify the RollbackManager that a session is
// being staged. In the case of multi-package sessions, the specified sessionId
// is that of the parent session.
+ // Returns the rollback id if rollback was enabled successfully, or -1 if not.
//
// NOTE: This call is synchronous.
- boolean notifyStagedSession(int sessionId);
+ int notifyStagedSession(int sessionId);
// Used by the staging manager to notify the RollbackManager of the apk
// session for a staged session.
diff --git a/core/java/android/database/sqlite/SQLiteQueryBuilder.java b/core/java/android/database/sqlite/SQLiteQueryBuilder.java
index 48d88678f721..39c1daca1bfd 100644
--- a/core/java/android/database/sqlite/SQLiteQueryBuilder.java
+++ b/core/java/android/database/sqlite/SQLiteQueryBuilder.java
@@ -823,6 +823,7 @@ public class SQLiteQueryBuilder {
switch (token.toUpperCase(Locale.US)) {
case "COLLATE": case "ASC": case "DESC":
case "BINARY": case "RTRIM": case "NOCASE":
+ case "LOCALIZED": case "UNICODE":
return;
}
throw new IllegalArgumentException("Invalid token " + token);
diff --git a/core/java/android/hardware/biometrics/BiometricConstants.java b/core/java/android/hardware/biometrics/BiometricConstants.java
index 191516b5b992..d28b7c531430 100644
--- a/core/java/android/hardware/biometrics/BiometricConstants.java
+++ b/core/java/android/hardware/biometrics/BiometricConstants.java
@@ -16,8 +16,9 @@
package android.hardware.biometrics;
+import static android.hardware.biometrics.BiometricManager.Authenticators;
+
import android.annotation.UnsupportedAppUsage;
-import android.app.KeyguardManager;
/**
@@ -126,8 +127,8 @@ public interface BiometricConstants {
/**
* The device does not have pin, pattern, or password set up. See
- * {@link BiometricPrompt.Builder#setDeviceCredentialAllowed(boolean)} and
- * {@link KeyguardManager#isDeviceSecure()}
+ * {@link BiometricPrompt.Builder#setAllowedAuthenticators(int)},
+ * {@link Authenticators#DEVICE_CREDENTIAL}, and {@link BiometricManager#canAuthenticate(int)}.
*/
int BIOMETRIC_ERROR_NO_DEVICE_CREDENTIAL = 14;
diff --git a/core/java/android/hardware/biometrics/BiometricManager.java b/core/java/android/hardware/biometrics/BiometricManager.java
index f17b3ae2052f..7e1506f61a51 100644
--- a/core/java/android/hardware/biometrics/BiometricManager.java
+++ b/core/java/android/hardware/biometrics/BiometricManager.java
@@ -21,6 +21,7 @@ import static android.Manifest.permission.USE_BIOMETRIC_INTERNAL;
import android.annotation.IntDef;
import android.annotation.RequiresPermission;
+import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.content.Context;
import android.content.pm.PackageManager;
@@ -65,6 +66,77 @@ public class BiometricManager {
BIOMETRIC_ERROR_NO_HARDWARE})
@interface BiometricError {}
+ /**
+ * Types of authenticators, defined at a level of granularity supported by
+ * {@link BiometricManager} and {@link BiometricPrompt}.
+ *
+ * <p>Types may combined via bitwise OR into a single integer representing multiple
+ * authenticators (e.g. <code>DEVICE_CREDENTIAL | BIOMETRIC_WEAK</code>).
+ */
+ public interface Authenticators {
+ /**
+ * An {@link IntDef} representing valid combinations of authenticator types.
+ * @hide
+ */
+ @IntDef(flag = true, value = {
+ BIOMETRIC_STRONG,
+ BIOMETRIC_WEAK,
+ DEVICE_CREDENTIAL,
+ })
+ @interface Types {}
+
+ /**
+ * Empty set with no authenticators specified.
+ * @hide
+ */
+ @SystemApi
+ int EMPTY_SET = 0x0;
+
+ /**
+ * Placeholder for the theoretical strongest biometric security tier.
+ * @hide
+ */
+ int BIOMETRIC_MAX_STRENGTH = 0x001;
+
+ /**
+ * Any biometric (e.g. fingerprint, iris, or face) on the device that meets or exceeds the
+ * requirements for <strong>Strong</strong>, as defined by the Android CDD.
+ */
+ int BIOMETRIC_STRONG = 0x00F;
+
+ /**
+ * Any biometric (e.g. fingerprint, iris, or face) on the device that meets or exceeds the
+ * requirements for <strong>Weak</strong>, as defined by the Android CDD.
+ *
+ * <p>Note that this is a superset of {@link #BIOMETRIC_STRONG} and is defined such that
+ * <code>BIOMETRIC_STRONG | BIOMETRIC_WEAK == BIOMETRIC_WEAK</code>.
+ */
+ int BIOMETRIC_WEAK = 0x0FF;
+
+ /**
+ * Any biometric (e.g. fingerprint, iris, or face) on the device that meets or exceeds the
+ * requirements for <strong>Convenience</strong>, as defined by the Android CDD. This
+ * is not a valid parameter to any of the {@link android.hardware.biometrics} APIs, since
+ * the CDD allows only {@link #BIOMETRIC_WEAK} and stronger authenticators to participate.
+ * @hide
+ */
+ @SystemApi
+ int BIOMETRIC_CONVENIENCE = 0xFFF;
+
+ /**
+ * Placeholder for the theoretical weakest biometric security tier.
+ * @hide
+ */
+ int BIOMETRIC_MIN_STRENGTH = 0x7FFF;
+
+ /**
+ * The non-biometric credential used to secure the device (i.e., PIN, pattern, or password).
+ * This should typically only be used in combination with a biometric auth type, such as
+ * {@link #BIOMETRIC_WEAK}.
+ */
+ int DEVICE_CREDENTIAL = 1 << 15;
+ }
+
private final Context mContext;
private final IAuthService mService;
private final boolean mHasHardware;
@@ -94,27 +166,64 @@ public class BiometricManager {
}
/**
- * Determine if biometrics can be used. In other words, determine if {@link BiometricPrompt}
- * can be expected to be shown (hardware available, templates enrolled, user-enabled).
+ * Determine if biometrics can be used. In other words, determine if
+ * {@link BiometricPrompt} can be expected to be shown (hardware available, templates enrolled,
+ * user-enabled). This is the equivalent of {@link #canAuthenticate(int)} with
+ * {@link Authenticators#BIOMETRIC_WEAK}
+ *
+ * @return {@link #BIOMETRIC_ERROR_NONE_ENROLLED} if the user does not have any strong
+ * biometrics enrolled, or {@link #BIOMETRIC_ERROR_HW_UNAVAILABLE} if none are currently
+ * supported/enabled. Returns {@link #BIOMETRIC_SUCCESS} if a strong biometric can currently
+ * be used (enrolled and available).
*
- * @return Returns {@link #BIOMETRIC_ERROR_NONE_ENROLLED} if the user does not have any
- * enrolled, or {@link #BIOMETRIC_ERROR_HW_UNAVAILABLE} if none are currently
- * supported/enabled. Returns {@link #BIOMETRIC_SUCCESS} if a biometric can currently be
- * used (enrolled and available).
+ * @deprecated See {@link #canAuthenticate(int)}.
*/
+ @Deprecated
@RequiresPermission(USE_BIOMETRIC)
public @BiometricError int canAuthenticate() {
- return canAuthenticate(mContext.getUserId());
+ return canAuthenticate(Authenticators.BIOMETRIC_WEAK);
+ }
+
+ /**
+ * Determine if any of the provided authenticators can be used. In other words, determine if
+ * {@link BiometricPrompt} can be expected to be shown (hardware available, templates enrolled,
+ * user-enabled).
+ *
+ * For biometric authenticators, determine if the device can currently authenticate with at
+ * least the requested strength. For example, invoking this API with
+ * {@link Authenticators#BIOMETRIC_WEAK} on a device that currently only has
+ * {@link Authenticators#BIOMETRIC_STRONG} enrolled will return {@link #BIOMETRIC_SUCCESS}.
+ *
+ * Invoking this API with {@link Authenticators#DEVICE_CREDENTIAL} can be used to determine
+ * if the user has a PIN/Pattern/Password set up.
+ *
+ * @param authenticators bit field consisting of constants defined in {@link Authenticators}.
+ * If multiple authenticators are queried, a logical OR will be applied.
+ * For example, if {@link Authenticators#DEVICE_CREDENTIAL} |
+ * {@link Authenticators#BIOMETRIC_STRONG} is queried and only
+ * {@link Authenticators#DEVICE_CREDENTIAL} is set up, this API will
+ * return {@link #BIOMETRIC_SUCCESS}
+ *
+ * @return {@link #BIOMETRIC_ERROR_NONE_ENROLLED} if the user does not have any of the
+ * requested authenticators enrolled, or {@link #BIOMETRIC_ERROR_HW_UNAVAILABLE} if none are
+ * currently supported/enabled. Returns {@link #BIOMETRIC_SUCCESS} if one of the requested
+ * authenticators can currently be used (enrolled and available).
+ */
+ @RequiresPermission(USE_BIOMETRIC)
+ public @BiometricError int canAuthenticate(@Authenticators.Types int authenticators) {
+ return canAuthenticate(mContext.getUserId(), authenticators);
}
/**
* @hide
*/
@RequiresPermission(USE_BIOMETRIC_INTERNAL)
- public @BiometricError int canAuthenticate(int userId) {
+ public @BiometricError int canAuthenticate(int userId,
+ @Authenticators.Types int authenticators) {
if (mService != null) {
try {
- return mService.canAuthenticate(mContext.getOpPackageName(), userId);
+ final String opPackageName = mContext.getOpPackageName();
+ return mService.canAuthenticate(opPackageName, userId, authenticators);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
diff --git a/core/java/android/hardware/biometrics/BiometricPrompt.java b/core/java/android/hardware/biometrics/BiometricPrompt.java
index 9c51b5246749..6f9c9e6db025 100644
--- a/core/java/android/hardware/biometrics/BiometricPrompt.java
+++ b/core/java/android/hardware/biometrics/BiometricPrompt.java
@@ -18,6 +18,7 @@ package android.hardware.biometrics;
import static android.Manifest.permission.USE_BIOMETRIC;
import static android.Manifest.permission.USE_BIOMETRIC_INTERNAL;
+import static android.hardware.biometrics.BiometricManager.Authenticators;
import android.annotation.CallbackExecutor;
import android.annotation.NonNull;
@@ -149,7 +150,7 @@ public class BiometricPrompt implements BiometricAuthenticator, BiometricConstan
/**
* A builder that collects arguments to be shown on the system-provided biometric dialog.
- **/
+ */
public static class Builder {
private final Bundle mBundle;
private ButtonInfo mPositiveButtonInfo;
@@ -157,8 +158,8 @@ public class BiometricPrompt implements BiometricAuthenticator, BiometricConstan
private Context mContext;
/**
- * Creates a builder for a biometric dialog.
- * @param context
+ * Creates a builder for a {@link BiometricPrompt} dialog.
+ * @param context The {@link Context} that will be used to build the prompt.
*/
public Builder(Context context) {
mBundle = new Bundle();
@@ -166,58 +167,67 @@ public class BiometricPrompt implements BiometricAuthenticator, BiometricConstan
}
/**
- * Required: Set the title to display.
- * @param title
- * @return
+ * Required: Sets the title that will be shown on the prompt.
+ * @param title The title to display.
+ * @return This builder.
*/
- @NonNull public Builder setTitle(@NonNull CharSequence title) {
+ @NonNull
+ public Builder setTitle(@NonNull CharSequence title) {
mBundle.putCharSequence(KEY_TITLE, title);
return this;
}
/**
- * For internal use currently. Only takes effect if title is null/empty. Shows a default
- * modality-specific title.
+ * Shows a default, modality-specific title for the prompt if the title would otherwise be
+ * null or empty. Currently for internal use only.
+ * @return This builder.
* @hide
*/
@RequiresPermission(USE_BIOMETRIC_INTERNAL)
- @NonNull public Builder setUseDefaultTitle() {
+ @NonNull
+ public Builder setUseDefaultTitle() {
mBundle.putBoolean(KEY_USE_DEFAULT_TITLE, true);
return this;
}
/**
- * Optional: Set the subtitle to display.
- * @param subtitle
- * @return
+ * Optional: Sets a subtitle that will be shown on the prompt.
+ * @param subtitle The subtitle to display.
+ * @return This builder.
*/
- @NonNull public Builder setSubtitle(@NonNull CharSequence subtitle) {
+ @NonNull
+ public Builder setSubtitle(@NonNull CharSequence subtitle) {
mBundle.putCharSequence(KEY_SUBTITLE, subtitle);
return this;
}
/**
- * Optional: Set the description to display.
- * @param description
- * @return
+ * Optional: Sets a description that will be shown on the prompt.
+ * @param description The description to display.
+ * @return This builder.
*/
- @NonNull public Builder setDescription(@NonNull CharSequence description) {
+ @NonNull
+ public Builder setDescription(@NonNull CharSequence description) {
mBundle.putCharSequence(KEY_DESCRIPTION, description);
return this;
}
/**
- * Required: Set the text for the negative button. This would typically be used as a
- * "Cancel" button, but may be also used to show an alternative method for authentication,
- * such as screen that asks for a backup password.
+ * Required: Sets the text, executor, and click listener for the negative button on the
+ * prompt. This is typically a cancel button, but may be also used to show an alternative
+ * method for authentication, such as a screen that asks for a backup password.
*
- * Note that this should not be set if {@link #setDeviceCredentialAllowed(boolean)}(boolean)
- * is set to true.
+ * <p>Note that this setting is not required, and in fact is explicitly disallowed, if
+ * device credential authentication is enabled via {@link #setAllowedAuthenticators(int)} or
+ * {@link #setDeviceCredentialAllowed(boolean)}.
*
- * @param text
- * @return
+ * @param text Text to be shown on the negative button for the prompt.
+ * @param executor Executor that will be used to run the on click callback.
+ * @param listener Listener containing a callback to be run when the button is pressed.
+ * @return This builder.
*/
- @NonNull public Builder setNegativeButton(@NonNull CharSequence text,
+ @NonNull
+ public Builder setNegativeButton(@NonNull CharSequence text,
@NonNull @CallbackExecutor Executor executor,
@NonNull DialogInterface.OnClickListener listener) {
if (TextUtils.isEmpty(text)) {
@@ -235,70 +245,112 @@ public class BiometricPrompt implements BiometricAuthenticator, BiometricConstan
}
/**
- * Optional: A hint to the system to require user confirmation after a biometric has been
- * authenticated. For example, implicit modalities like Face and Iris authentication are
- * passive, meaning they don't require an explicit user action to complete. When set to
- * 'false', the user action (e.g. pressing a button) will not be required. BiometricPrompt
- * will require confirmation by default.
+ * Optional: Sets a hint to the system for whether to require user confirmation after
+ * authentication. For example, implicit modalities like face and iris are passive, meaning
+ * they don't require an explicit user action to complete authentication. If set to true,
+ * these modalities should require the user to take some action (e.g. press a button)
+ * before {@link AuthenticationCallback#onAuthenticationSucceeded(AuthenticationResult)} is
+ * called. Defaults to true.
*
- * A typical use case for not requiring confirmation would be for low-risk transactions,
+ * <p>A typical use case for not requiring confirmation would be for low-risk transactions,
* such as re-authenticating a recently authenticated application. A typical use case for
* requiring confirmation would be for authorizing a purchase.
*
- * Note that this is a hint to the system. The system may choose to ignore the flag. For
- * example, if the user disables implicit authentication in Settings, or if it does not
- * apply to a modality (e.g. Fingerprint). When ignored, the system will default to
- * requiring confirmation.
+ * <p>Note that this just passes a hint to the system, which the system may then ignore. For
+ * example, a value of false may be ignored if the user has disabled implicit authentication
+ * in Settings, or if it does not apply to a particular modality (e.g. fingerprint).
*
- * @param requireConfirmation
+ * @param requireConfirmation true if explicit user confirmation should be required, or
+ * false otherwise.
+ * @return This builder.
*/
- @NonNull public Builder setConfirmationRequired(boolean requireConfirmation) {
+ @NonNull
+ public Builder setConfirmationRequired(boolean requireConfirmation) {
mBundle.putBoolean(KEY_REQUIRE_CONFIRMATION, requireConfirmation);
return this;
}
/**
- * The user will first be prompted to authenticate with biometrics, but also given the
- * option to authenticate with their device PIN, pattern, or password. Developers should
- * first check {@link KeyguardManager#isDeviceSecure()} before enabling this. If the device
- * is not secure, {@link BiometricPrompt#BIOMETRIC_ERROR_NO_DEVICE_CREDENTIAL} will be
- * returned in {@link AuthenticationCallback#onAuthenticationError(int, CharSequence)}}.
+ * Optional: If enabled, the user will first be prompted to authenticate with biometrics,
+ * but also given the option to authenticate with their device PIN, pattern, or password.
+ * Developers should first check {@link KeyguardManager#isDeviceSecure()} before enabling.
+ * If the device is not secure, {@link BiometricPrompt#BIOMETRIC_ERROR_NO_DEVICE_CREDENTIAL}
+ * will be given to {@link AuthenticationCallback#onAuthenticationError(int, CharSequence)}.
* Defaults to false.
*
- * Note that {@link #setNegativeButton(CharSequence, Executor,
- * DialogInterface.OnClickListener)} should not be set if this is set to true.
+ * <p>Note that enabling this option replaces the negative button on the prompt with one
+ * that allows the user to authenticate with their device credential, making it an error to
+ * call {@link #setNegativeButton(CharSequence, Executor, DialogInterface.OnClickListener)}.
+ *
+ * @param allowed true if the prompt should fall back to asking for the user's device
+ * credential (PIN/pattern/password), or false otherwise.
+ * @return This builder.
*
- * @param allowed When true, the prompt will fall back to ask for the user's device
- * credentials (PIN, pattern, or password).
- * @return
+ * @deprecated Replaced by {@link #setAllowedAuthenticators(int)}.
*/
- @NonNull public Builder setDeviceCredentialAllowed(boolean allowed) {
+ @Deprecated
+ @NonNull
+ public Builder setDeviceCredentialAllowed(boolean allowed) {
mBundle.putBoolean(KEY_ALLOW_DEVICE_CREDENTIAL, allowed);
return this;
}
/**
+ * Optional: Specifies the type(s) of authenticators that may be invoked by
+ * {@link BiometricPrompt} to authenticate the user. Available authenticator types are
+ * defined in {@link Authenticators} and can be combined via bitwise OR. Defaults to:
+ * <ul>
+ * <li>{@link Authenticators#BIOMETRIC_WEAK} for non-crypto authentication, or</li>
+ * <li>{@link Authenticators#BIOMETRIC_STRONG} for crypto-based authentication.</li>
+ * </ul>
+ *
+ * <p>If this method is used and no authenticator of any of the specified types is available
+ * at the time <code>BiometricPrompt#authenticate(...)</code> is called, authentication will
+ * be canceled and {@link AuthenticationCallback#onAuthenticationError(int, CharSequence)}
+ * will be invoked with an appropriate error code.
+ *
+ * <p>This method should be preferred over {@link #setDeviceCredentialAllowed(boolean)} and
+ * overrides the latter if both are used. Using this method to enable device credential
+ * authentication (with {@link Authenticators#DEVICE_CREDENTIAL}) will replace the negative
+ * button on the prompt, making it an error to also call
+ * {@link #setNegativeButton(CharSequence, Executor, DialogInterface.OnClickListener)}.
+ *
+ * @param authenticators A bit field representing all valid authenticator types that may be
+ * invoked by the prompt.
+ * @return This builder.
+ */
+ @NonNull
+ public Builder setAllowedAuthenticators(@Authenticators.Types int authenticators) {
+ mBundle.putInt(KEY_AUTHENTICATORS_ALLOWED, authenticators);
+ return this;
+ }
+
+ /**
* Creates a {@link BiometricPrompt}.
- * @return a {@link BiometricPrompt}
- * @throws IllegalArgumentException if any of the required fields are not set.
+ *
+ * @return An instance of {@link BiometricPrompt}.
+ *
+ * @throws IllegalArgumentException If any required fields are unset, or if given any
+ * invalid combination of field values.
*/
- @NonNull public BiometricPrompt build() {
+ @NonNull
+ public BiometricPrompt build() {
final CharSequence title = mBundle.getCharSequence(KEY_TITLE);
final CharSequence negative = mBundle.getCharSequence(KEY_NEGATIVE_TEXT);
- final boolean useDefaultTitle = mBundle.getBoolean(KEY_USE_DEFAULT_TITLE);
- final boolean allowCredential = mBundle.getBoolean(KEY_ALLOW_DEVICE_CREDENTIAL);
- final Object authenticatorsAllowed = mBundle.get(KEY_AUTHENTICATORS_ALLOWED);
+ final boolean useDefaultTitle = mBundle.getBoolean(KEY_USE_DEFAULT_TITLE, false);
+ final boolean deviceCredentialAllowed = mBundle.getBoolean(KEY_ALLOW_DEVICE_CREDENTIAL);
+ final @Authenticators.Types int authenticators =
+ mBundle.getInt(KEY_AUTHENTICATORS_ALLOWED, 0);
+ final boolean willShowDeviceCredentialButton = deviceCredentialAllowed
+ || (authenticators & Authenticators.DEVICE_CREDENTIAL) != 0;
if (TextUtils.isEmpty(title) && !useDefaultTitle) {
throw new IllegalArgumentException("Title must be set and non-empty");
- } else if (TextUtils.isEmpty(negative) && !allowCredential) {
+ } else if (TextUtils.isEmpty(negative) && !willShowDeviceCredentialButton) {
throw new IllegalArgumentException("Negative text must be set and non-empty");
- } else if (!TextUtils.isEmpty(negative) && allowCredential) {
+ } else if (!TextUtils.isEmpty(negative) && willShowDeviceCredentialButton) {
throw new IllegalArgumentException("Can't have both negative button behavior"
+ " and device credential enabled");
- } else if (authenticatorsAllowed != null && allowCredential) {
- throw new IllegalArgumentException("setAuthenticatorsAllowed and"
- + " setDeviceCredentialAllowed should not be used simultaneously");
}
return new BiometricPrompt(mContext, mBundle, mPositiveButtonInfo, mNegativeButtonInfo);
}
@@ -394,6 +446,75 @@ public class BiometricPrompt implements BiometricAuthenticator, BiometricConstan
}
/**
+ * Gets the title for the prompt, as set by {@link Builder#setTitle(CharSequence)}.
+ * @return The title of the prompt, which is guaranteed to be non-null.
+ */
+ @NonNull
+ public CharSequence getTitle() {
+ return mBundle.getCharSequence(KEY_TITLE, "");
+ }
+
+ /**
+ * Whether to use a default modality-specific title. For internal use only.
+ * @return See {@link Builder#setUseDefaultTitle()}.
+ * @hide
+ */
+ @RequiresPermission(USE_BIOMETRIC_INTERNAL)
+ public boolean shouldUseDefaultTitle() {
+ return mBundle.getBoolean(KEY_USE_DEFAULT_TITLE, false);
+ }
+
+ /**
+ * Gets the subtitle for the prompt, as set by {@link Builder#setSubtitle(CharSequence)}.
+ * @return The subtitle for the prompt, or null if the prompt has no subtitle.
+ */
+ @Nullable
+ public CharSequence getSubtitle() {
+ return mBundle.getCharSequence(KEY_SUBTITLE);
+ }
+
+ /**
+ * Gets the description for the prompt, as set by {@link Builder#setDescription(CharSequence)}.
+ * @return The description for the prompt, or null if the prompt has no description.
+ */
+ @Nullable
+ public CharSequence getDescription() {
+ return mBundle.getCharSequence(KEY_DESCRIPTION);
+ }
+
+ /**
+ * Gets the negative button text for the prompt, as set by
+ * {@link Builder#setNegativeButton(CharSequence, Executor, DialogInterface.OnClickListener)}.
+ * @return The negative button text for the prompt, or null if no negative button text was set.
+ */
+ @Nullable
+ public CharSequence getNegativeButtonText() {
+ return mBundle.getCharSequence(KEY_NEGATIVE_TEXT);
+ }
+
+ /**
+ * Determines if explicit user confirmation is required by the prompt, as set by
+ * {@link Builder#setConfirmationRequired(boolean)}.
+ *
+ * @return true if explicit user confirmation is required, or false otherwise.
+ */
+ public boolean isConfirmationRequired() {
+ return mBundle.getBoolean(KEY_REQUIRE_CONFIRMATION, true);
+ }
+
+ /**
+ * Gets the type(s) of authenticators that may be invoked by the prompt to authenticate the
+ * user, as set by {@link Builder#setAllowedAuthenticators(int)}.
+ *
+ * @return A bit field representing the type(s) of authenticators that may be invoked by the
+ * prompt (as defined by {@link Authenticators}), or 0 if this field was not set.
+ */
+ @Nullable
+ public int getAllowedAuthenticators() {
+ return mBundle.getInt(KEY_AUTHENTICATORS_ALLOWED, 0);
+ }
+
+ /**
* A wrapper class for the crypto objects supported by BiometricPrompt. Currently the framework
* supports {@link Signature}, {@link Cipher} and {@link Mac} objects.
*/
@@ -509,10 +630,12 @@ public class BiometricPrompt implements BiometricAuthenticator, BiometricConstan
/**
* Authenticates for the given user.
+ *
* @param cancel An object that can be used to cancel authentication
* @param executor An executor to handle callback events
* @param callback An object to receive authentication events
* @param userId The user to authenticate
+ *
* @hide
*/
@RequiresPermission(USE_BIOMETRIC_INTERNAL)
@@ -542,23 +665,33 @@ public class BiometricPrompt implements BiometricAuthenticator, BiometricConstan
* authentication errors through {@link AuthenticationCallback}, and button events through the
* corresponding callback set in {@link Builder#setNegativeButton(CharSequence, Executor,
* DialogInterface.OnClickListener)}. It is safe to reuse the {@link BiometricPrompt} object,
- * and calling {@link BiometricPrompt#authenticate( CancellationSignal, Executor,
+ * and calling {@link BiometricPrompt#authenticate(CancellationSignal, Executor,
* AuthenticationCallback)} while an existing authentication attempt is occurring will stop the
* previous client and start a new authentication. The interrupted client will receive a
* cancelled notification through {@link AuthenticationCallback#onAuthenticationError(int,
* CharSequence)}.
*
- * Note: Applications generally should not cancel and start authentication in quick succession.
- * For example, to properly handle authentication across configuration changes, it's recommended
- * to use BiometricPrompt in a fragment with setRetainInstance(true). By doing so, the
- * application will not need to cancel/restart authentication during the configuration change.
+ * <p>Note: Applications generally should not cancel and start authentication in quick
+ * succession. For example, to properly handle authentication across configuration changes, it's
+ * recommended to use BiometricPrompt in a fragment with setRetainInstance(true). By doing so,
+ * the application will not need to cancel/restart authentication during the configuration
+ * change.
*
- * @throws IllegalArgumentException If any of the arguments are null
+ * <p>Per the Android CDD, only biometric authenticators that meet or exceed the requirements
+ * for <strong>Strong</strong> are permitted to integrate with Keystore to perform related
+ * cryptographic operations. Therefore, it is an error to call this method after explicitly
+ * calling {@link Builder#setAllowedAuthenticators(int)} with any value other than
+ * {@link Authenticators#BIOMETRIC_STRONG}.
*
- * @param crypto Object associated with the call
- * @param cancel An object that can be used to cancel authentication
- * @param executor An executor to handle callback events
- * @param callback An object to receive authentication events
+ * @throws IllegalArgumentException If any of the arguments are null, if
+ * {@link Builder#setDeviceCredentialAllowed(boolean)} was explicitly set to true, or if
+ * {@link Builder#setAllowedAuthenticators(int)} was explicitly called with any value other than
+ * {@link Authenticators#BIOMETRIC_STRONG}.
+ *
+ * @param crypto A cryptographic operation to be unlocked after successful authentication.
+ * @param cancel An object that can be used to cancel authentication.
+ * @param executor An executor to handle callback events.
+ * @param callback An object to receive authentication events.
*/
@RequiresPermission(USE_BIOMETRIC)
public void authenticate(@NonNull CryptoObject crypto,
@@ -577,9 +710,20 @@ public class BiometricPrompt implements BiometricAuthenticator, BiometricConstan
if (callback == null) {
throw new IllegalArgumentException("Must supply a callback");
}
- if (mBundle.getBoolean(KEY_ALLOW_DEVICE_CREDENTIAL)) {
+
+ @Authenticators.Types int authenticators = mBundle.getInt(
+ KEY_AUTHENTICATORS_ALLOWED, Authenticators.BIOMETRIC_STRONG);
+
+ if (mBundle.getBoolean(KEY_ALLOW_DEVICE_CREDENTIAL)
+ || (authenticators & Authenticators.DEVICE_CREDENTIAL) != 0) {
throw new IllegalArgumentException("Device credential not supported with crypto");
}
+
+ // Disallow any non-Strong biometric authenticator types.
+ if ((authenticators & ~Authenticators.BIOMETRIC_STRONG) != 0) {
+ throw new IllegalArgumentException("Only Strong biometrics supported with crypto");
+ }
+
authenticateInternal(crypto, cancel, executor, callback, mContext.getUserId());
}
@@ -598,16 +742,17 @@ public class BiometricPrompt implements BiometricAuthenticator, BiometricConstan
* authentication. The interrupted client will receive a cancelled notification through {@link
* AuthenticationCallback#onAuthenticationError(int, CharSequence)}.
*
- * Note: Applications generally should not cancel and start authentication in quick succession.
- * For example, to properly handle authentication across configuration changes, it's recommended
- * to use BiometricPrompt in a fragment with setRetainInstance(true). By doing so, the
- * application will not need to cancel/restart authentication during the configuration change.
+ * <p>Note: Applications generally should not cancel and start authentication in quick
+ * succession. For example, to properly handle authentication across configuration changes, it's
+ * recommended to use BiometricPrompt in a fragment with setRetainInstance(true). By doing so,
+ * the application will not need to cancel/restart authentication during the configuration
+ * change.
*
- * @throws IllegalArgumentException If any of the arguments are null
+ * @throws IllegalArgumentException If any of the arguments are null.
*
- * @param cancel An object that can be used to cancel authentication
- * @param executor An executor to handle callback events
- * @param callback An object to receive authentication events
+ * @param cancel An object that can be used to cancel authentication.
+ * @param executor An executor to handle callback events.
+ * @param callback An object to receive authentication events.
*/
@RequiresPermission(USE_BIOMETRIC)
public void authenticate(@NonNull CancellationSignal cancel,
@@ -653,8 +798,22 @@ public class BiometricPrompt implements BiometricAuthenticator, BiometricConstan
mAuthenticationCallback = callback;
final long sessionId = crypto != null ? crypto.getOpId() : 0;
if (BiometricManager.hasBiometrics(mContext)) {
+ final Bundle bundle;
+ if (crypto != null) {
+ // Allowed authenticators should default to BIOMETRIC_STRONG for crypto auth.
+ // Note that we use a new bundle here so as to not overwrite the application's
+ // preference, since it is possible that the same prompt configuration be used
+ // without a crypto object later.
+ bundle = new Bundle(mBundle);
+ bundle.putInt(KEY_AUTHENTICATORS_ALLOWED,
+ mBundle.getInt(KEY_AUTHENTICATORS_ALLOWED,
+ Authenticators.BIOMETRIC_STRONG));
+ } else {
+ bundle = mBundle;
+ }
+
mService.authenticate(mToken, sessionId, userId, mBiometricServiceReceiver,
- mContext.getOpPackageName(), mBundle);
+ mContext.getOpPackageName(), bundle);
} else {
mExecutor.execute(() -> {
callback.onAuthenticationError(BiometricPrompt.BIOMETRIC_ERROR_HW_NOT_PRESENT,
diff --git a/core/java/android/hardware/biometrics/IAuthService.aidl b/core/java/android/hardware/biometrics/IAuthService.aidl
index 516a25d0b9b1..d482198b82b3 100644
--- a/core/java/android/hardware/biometrics/IAuthService.aidl
+++ b/core/java/android/hardware/biometrics/IAuthService.aidl
@@ -35,7 +35,7 @@ interface IAuthService {
// TODO(b/141025588): Make userId the first arg to be consistent with hasEnrolledBiometrics.
// Checks if biometrics can be used.
- int canAuthenticate(String opPackageName, int userId);
+ int canAuthenticate(String opPackageName, int userId, int authenticators);
// Checks if any biometrics are enrolled.
boolean hasEnrolledBiometrics(int userId, String opPackageName);
diff --git a/core/java/android/hardware/biometrics/IBiometricService.aidl b/core/java/android/hardware/biometrics/IBiometricService.aidl
index ca024215f782..8a6be18e403d 100644
--- a/core/java/android/hardware/biometrics/IBiometricService.aidl
+++ b/core/java/android/hardware/biometrics/IBiometricService.aidl
@@ -35,7 +35,7 @@ interface IBiometricService {
void cancelAuthentication(IBinder token, String opPackageName);
// Checks if biometrics can be used.
- int canAuthenticate(String opPackageName, int userId);
+ int canAuthenticate(String opPackageName, int userId, int authenticators);
// Checks if any biometrics are enrolled.
boolean hasEnrolledBiometrics(int userId, String opPackageName);
@@ -43,7 +43,8 @@ interface IBiometricService {
// Registers an authenticator (e.g. face, fingerprint, iris).
// Id must be unique, whereas strength and modality don't need to be.
// TODO(b/123321528): Turn strength and modality into enums.
- void registerAuthenticator(int id, int strength, int modality, IBiometricAuthenticator authenticator);
+ void registerAuthenticator(int id, int modality, int strength,
+ IBiometricAuthenticator authenticator);
// Register callback for when keyguard biometric eligibility changes.
void registerEnabledOnKeyguardCallback(IBiometricEnabledOnKeyguardCallback callback);
diff --git a/core/java/android/hardware/camera2/CameraCharacteristics.java b/core/java/android/hardware/camera2/CameraCharacteristics.java
index 1f29d1a22325..b60586655dc8 100644
--- a/core/java/android/hardware/camera2/CameraCharacteristics.java
+++ b/core/java/android/hardware/camera2/CameraCharacteristics.java
@@ -935,7 +935,7 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
/**
* <p>List of the maximum number of regions that can be used for metering in
* auto-exposure (AE), auto-white balance (AWB), and auto-focus (AF);
- * this corresponds to the the maximum number of elements in
+ * this corresponds to the maximum number of elements in
* {@link CaptureRequest#CONTROL_AE_REGIONS android.control.aeRegions}, {@link CaptureRequest#CONTROL_AWB_REGIONS android.control.awbRegions},
* and {@link CaptureRequest#CONTROL_AF_REGIONS android.control.afRegions}.</p>
* <p><b>Range of valid values:</b><br></p>
@@ -955,7 +955,7 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
/**
* <p>The maximum number of metering regions that can be used by the auto-exposure (AE)
* routine.</p>
- * <p>This corresponds to the the maximum allowed number of elements in
+ * <p>This corresponds to the maximum allowed number of elements in
* {@link CaptureRequest#CONTROL_AE_REGIONS android.control.aeRegions}.</p>
* <p><b>Range of valid values:</b><br>
* Value will be &gt;= 0. For FULL-capability devices, this
@@ -973,7 +973,7 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
/**
* <p>The maximum number of metering regions that can be used by the auto-white balance (AWB)
* routine.</p>
- * <p>This corresponds to the the maximum allowed number of elements in
+ * <p>This corresponds to the maximum allowed number of elements in
* {@link CaptureRequest#CONTROL_AWB_REGIONS android.control.awbRegions}.</p>
* <p><b>Range of valid values:</b><br>
* Value will be &gt;= 0.</p>
@@ -989,7 +989,7 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
/**
* <p>The maximum number of metering regions that can be used by the auto-focus (AF) routine.</p>
- * <p>This corresponds to the the maximum allowed number of elements in
+ * <p>This corresponds to the maximum allowed number of elements in
* {@link CaptureRequest#CONTROL_AF_REGIONS android.control.afRegions}.</p>
* <p><b>Range of valid values:</b><br>
* Value will be &gt;= 0. For FULL-capability devices, this
@@ -1125,8 +1125,8 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
new Key<android.util.Range<Integer>>("android.control.postRawSensitivityBoostRange", new TypeReference<android.util.Range<Integer>>() {{ }});
/**
- * <p>The list of bokeh modes that are supported by this camera device, and each bokeh mode's
- * maximum streaming (non-stall) size with bokeh effect.</p>
+ * <p>The list of bokeh modes for {@link CaptureRequest#CONTROL_BOKEH_MODE android.control.bokehMode} that are supported by this camera
+ * device, and each bokeh mode's maximum streaming (non-stall) size with bokeh effect.</p>
* <p>For OFF mode, the camera behaves normally with no bokeh effect.</p>
* <p>For STILL_CAPTURE mode, the maximum streaming dimension specifies the limit under which
* bokeh is effective when capture intent is PREVIEW. Note that when capture intent is
@@ -1148,12 +1148,86 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
* Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
* {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
*
+ * @see CaptureRequest#CONTROL_BOKEH_MODE
+ * @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
+ * @hide
+ */
+ public static final Key<int[]> CONTROL_AVAILABLE_BOKEH_MAX_SIZES =
+ new Key<int[]>("android.control.availableBokehMaxSizes", int[].class);
+
+ /**
+ * <p>The ranges of supported zoom ratio for non-OFF {@link CaptureRequest#CONTROL_BOKEH_MODE android.control.bokehMode}.</p>
+ * <p>When bokeh mode is enabled, the camera device may have limited range of zoom ratios
+ * compared to when bokeh mode is disabled. This tag lists the zoom ratio ranges for all
+ * supported non-OFF bokeh modes, in the same order as in
+ * {@link CameraCharacteristics#CONTROL_AVAILABLE_BOKEH_CAPABILITIES android.control.availableBokehCapabilities}.</p>
+ * <p>Range [1.0, 1.0] means that no zoom (optical or digital) is supported.</p>
+ * <p><b>Units</b>: (minZoom, maxZoom)</p>
+ * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
+ * <p><b>Limited capability</b> -
+ * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
+ * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
+ *
+ * @see CameraCharacteristics#CONTROL_AVAILABLE_BOKEH_CAPABILITIES
+ * @see CaptureRequest#CONTROL_BOKEH_MODE
+ * @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
+ * @hide
+ */
+ public static final Key<float[]> CONTROL_AVAILABLE_BOKEH_ZOOM_RATIO_RANGES =
+ new Key<float[]>("android.control.availableBokehZoomRatioRanges", float[].class);
+
+ /**
+ * <p>The list of bokeh modes for {@link CaptureRequest#CONTROL_BOKEH_MODE android.control.bokehMode} that are supported by
+ * this camera device, and each bokeh mode's capabilities such as maximum streaming size
+ * with bokeh effect, and supported zoom ratio ranges.</p>
+ * <p>For OFF mode, the camera behaves normally with no bokeh effect.</p>
+ * <p>For STILL_CAPTURE mode, the maximum streaming dimension specifies the limit under which
+ * bokeh is effective when capture intent is PREVIEW. Note that when capture intent is
+ * PREVIEW, the bokeh effect may not be as high quality compared to STILL_CAPTURE intent
+ * in order to maintain reasonable frame rate. The maximum streaming dimension must be one
+ * of the YUV_420_888 or PRIVATE resolutions in availableStreamConfigurations, or (0, 0)
+ * if preview bokeh is not supported. If the application configures a stream larger than
+ * the maximum streaming dimension, bokeh effect may not be applied for this stream for
+ * PREVIEW intent.</p>
+ * <p>For CONTINUOUS mode, the maximum streaming dimension specifies the limit under which
+ * bokeh is effective. This dimension must be one of the YUV_420_888 or PRIVATE resolutions
+ * in availableStreamConfigurations, and if the sensor maximum resolution is larger than or
+ * equal to 1080p, the maximum streaming dimension must be at least 1080p. If the
+ * application configures a stream with larger dimension, the stream may not have bokeh
+ * effect applied.</p>
+ * <p>When bokeh mode is enabled, the camera device may have limited range of zoom ratios
+ * compared to when bokeh mode is disabled. availableBokehCapabilities lists the zoom
+ * ranges for all supported bokeh modes. A range of (1.0, 1.0) means that no zoom
+ * (optical or digital) is supported.</p>
+ * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
+ *
+ * @see CaptureRequest#CONTROL_BOKEH_MODE
+ */
+ @PublicKey
+ @NonNull
+ @SyntheticKey
+ public static final Key<android.hardware.camera2.params.Capability[]> CONTROL_AVAILABLE_BOKEH_CAPABILITIES =
+ new Key<android.hardware.camera2.params.Capability[]>("android.control.availableBokehCapabilities", android.hardware.camera2.params.Capability[].class);
+
+ /**
+ * <p>Minimum and maximum zoom ratios supported by this camera device.</p>
+ * <p>If the camera device supports zoom-out from 1x zoom, minZoom will be less than 1.0, and
+ * setting android.control.zoomRation to values less than 1.0 increases the camera's field
+ * of view.</p>
+ * <p><b>Units</b>: A pair of zoom ratio in floating points: (minZoom, maxZoom)</p>
+ * <p><b>Range of valid values:</b><br></p>
+ * <p>maxZoom &gt;= 1.0 &gt;= minZoom</p>
+ * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
+ * <p><b>Limited capability</b> -
+ * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
+ * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
+ *
* @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
*/
@PublicKey
@NonNull
- public static final Key<android.hardware.camera2.params.CapabilityAndMaxSize[]> CONTROL_AVAILABLE_BOKEH_CAPABILITIES =
- new Key<android.hardware.camera2.params.CapabilityAndMaxSize[]>("android.control.availableBokehCapabilities", android.hardware.camera2.params.CapabilityAndMaxSize[].class);
+ public static final Key<android.util.Range<Float>> CONTROL_ZOOM_RATIO_RANGE =
+ new Key<android.util.Range<Float>>("android.control.zoomRatioRange", new TypeReference<android.util.Range<Float>>() {{ }});
/**
* <p>List of edge enhancement modes for {@link CaptureRequest#EDGE_MODE android.edge.mode} that are supported by this camera
@@ -1987,6 +2061,7 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
* <li>{@link #REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME MONOCHROME}</li>
* <li>{@link #REQUEST_AVAILABLE_CAPABILITIES_SECURE_IMAGE_DATA SECURE_IMAGE_DATA}</li>
* <li>{@link #REQUEST_AVAILABLE_CAPABILITIES_SYSTEM_CAMERA SYSTEM_CAMERA}</li>
+ * <li>{@link #REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING OFFLINE_PROCESSING}</li>
* </ul></p>
* <p>This key is available on all devices.</p>
*
@@ -2006,6 +2081,7 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
* @see #REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME
* @see #REQUEST_AVAILABLE_CAPABILITIES_SECURE_IMAGE_DATA
* @see #REQUEST_AVAILABLE_CAPABILITIES_SYSTEM_CAMERA
+ * @see #REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING
*/
@PublicKey
@NonNull
@@ -2213,11 +2289,16 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
* <p>Crop regions that have a width or height that is smaller
* than this ratio allows will be rounded up to the minimum
* allowed size by the camera device.</p>
+ * <p>Starting from API level 30, when using {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} to zoom in or out,
+ * the application must use {@link CameraCharacteristics#CONTROL_ZOOM_RATIO_RANGE android.control.zoomRatioRange} to query both the minimum and
+ * maximum zoom ratio.</p>
* <p><b>Units</b>: Zoom scale factor</p>
* <p><b>Range of valid values:</b><br>
* &gt;=1</p>
* <p>This key is available on all devices.</p>
*
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
+ * @see CameraCharacteristics#CONTROL_ZOOM_RATIO_RANGE
* @see CaptureRequest#SCALER_CROP_REGION
*/
@PublicKey
@@ -2665,6 +2746,21 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
* <p>Camera devices that support FREEFORM cropping will support any crop region that
* is inside of the active array. The camera device will apply the same crop region and
* return the final used crop region in capture result metadata {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion}.</p>
+ * <p>Starting from API level 30,</p>
+ * <ul>
+ * <li>If the camera device supports FREEFORM cropping, in order to do FREEFORM cropping, the
+ * application must set {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} to 1.0, and use {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion}
+ * for zoom.</li>
+ * <li>To do CENTER_ONLY zoom, the application has below 2 options:<ol>
+ * <li>Set {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} to 1.0; adjust zoom by {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion}.</li>
+ * <li>Adjust zoom by {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}; use {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion} to crop
+ * the field of view vertically (letterboxing) or horizontally (pillarboxing), but not
+ * windowboxing.</li>
+ * </ol>
+ * </li>
+ * <li>Setting {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} to values different than 1.0 and
+ * {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion} to be windowboxing at the same time is undefined behavior.</li>
+ * </ul>
* <p>LEGACY capability devices will only support CENTER_ONLY cropping.</p>
* <p><b>Possible values:</b>
* <ul>
@@ -2673,6 +2769,7 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
* </ul></p>
* <p>This key is available on all devices.</p>
*
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
* @see CaptureRequest#SCALER_CROP_REGION
* @see CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE
* @see #SCALER_CROPPING_TYPE_CENTER_ONLY
diff --git a/core/java/android/hardware/camera2/CameraMetadata.java b/core/java/android/hardware/camera2/CameraMetadata.java
index 799c71683d8a..8e0a46d52dd6 100644
--- a/core/java/android/hardware/camera2/CameraMetadata.java
+++ b/core/java/android/hardware/camera2/CameraMetadata.java
@@ -764,6 +764,7 @@ public abstract class CameraMetadata<TKey> {
* <li>{@link CaptureRequest#CONTROL_AWB_REGIONS android.control.awbRegions}</li>
* <li>{@link CaptureRequest#CONTROL_AF_TRIGGER android.control.afTrigger}</li>
* <li>{@link CaptureRequest#CONTROL_AE_PRECAPTURE_TRIGGER android.control.aePrecaptureTrigger}</li>
+ * <li>{@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}</li>
* </ul>
* <p>Outside of android.control.*, the following controls will work:</p>
* <ul>
@@ -812,6 +813,7 @@ public abstract class CameraMetadata<TKey> {
* @see CaptureRequest#CONTROL_AWB_REGIONS
* @see CaptureRequest#CONTROL_EFFECT_MODE
* @see CaptureRequest#CONTROL_MODE
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
* @see CaptureRequest#FLASH_MODE
* @see CaptureRequest#LENS_OPTICAL_STABILIZATION_MODE
* @see CaptureRequest#SCALER_CROP_REGION
@@ -1004,6 +1006,51 @@ public abstract class CameraMetadata<TKey> {
*/
public static final int REQUEST_AVAILABLE_CAPABILITIES_SYSTEM_CAMERA = 14;
+ /**
+ * <p>The camera device supports the OFFLINE_PROCESSING use case.</p>
+ * <p>With OFFLINE_PROCESSING capability, the application can switch an ongoing
+ * capture session to offline mode by calling the
+ * CameraCaptureSession#switchToOffline method and specify streams to be kept in offline
+ * mode. The camera will then stop currently active repeating requests, prepare for
+ * some requests to go into offline mode, and return an offline session object. After
+ * the switchToOffline call returns, the original capture session is in closed state as
+ * if the CameraCaptureSession#close method has been called.
+ * In the offline mode, all inflight requests will continue to be processed in the
+ * background, and the application can immediately close the camera or create a new
+ * capture session without losing those requests' output images and capture results.</p>
+ * <p>While the camera device is processing offline requests, it
+ * might not be able to support all stream configurations it can support
+ * without offline requests. When that happens, the createCaptureSession
+ * method call will fail. The following stream configurations are guaranteed to work
+ * without hitting the resource busy exception:</p>
+ * <ul>
+ * <li>One ongoing offline session: target one output surface of YUV or
+ * JPEG format, any resolution.</li>
+ * <li>The active camera capture session:<ol>
+ * <li>One preview surface (SurfaceView or SurfaceTexture) up to 1920 width</li>
+ * <li>One YUV ImageReader surface up to 1920 width</li>
+ * <li>One Jpeg ImageReader, any resolution: the camera device is
+ * allowed to slow down JPEG output speed by 50% if there is any ongoing offline
+ * session.</li>
+ * <li>One ImageWriter surface of private format, any resolution if the device supports
+ * PRIVATE_REPROCESSING capability</li>
+ * </ol>
+ * </li>
+ * <li>Alternatively, the active camera session above can be replaced by an legacy
+ * {@link android.hardware.Camera Camera} with the following parameter settings:<ol>
+ * <li>Preview size up to 1920 width</li>
+ * <li>Preview callback size up to 1920 width</li>
+ * <li>Video size up to 1920 width</li>
+ * <li>Picture size, any resolution: the camera device is
+ * allowed to slow down JPEG output speed by 50% if there is any ongoing offline
+ * session.</li>
+ * </ol>
+ * </li>
+ * </ul>
+ * @see CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES
+ */
+ public static final int REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING = 15;
+
//
// Enumeration values for CameraCharacteristics#SCALER_CROPPING_TYPE
//
@@ -2271,6 +2318,7 @@ public abstract class CameraMetadata<TKey> {
* <li>{@link CaptureRequest#CONTROL_AWB_REGIONS android.control.awbRegions}</li>
* <li>{@link CaptureRequest#CONTROL_AF_TRIGGER android.control.afTrigger}</li>
* <li>{@link CaptureRequest#CONTROL_AE_PRECAPTURE_TRIGGER android.control.aePrecaptureTrigger}</li>
+ * <li>{@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}</li>
* </ul>
* <p>Outside of android.control.*, the following controls will work:</p>
* <ul>
@@ -2317,6 +2365,7 @@ public abstract class CameraMetadata<TKey> {
* @see CaptureRequest#CONTROL_AWB_REGIONS
* @see CaptureRequest#CONTROL_EFFECT_MODE
* @see CaptureRequest#CONTROL_MODE
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
* @see CaptureRequest#FLASH_MODE
* @see CaptureRequest#LENS_OPTICAL_STABILIZATION_MODE
* @see CaptureRequest#SCALER_CROP_REGION
diff --git a/core/java/android/hardware/camera2/CaptureRequest.java b/core/java/android/hardware/camera2/CaptureRequest.java
index 5c76dff85a84..6bf57834ae6c 100644
--- a/core/java/android/hardware/camera2/CaptureRequest.java
+++ b/core/java/android/hardware/camera2/CaptureRequest.java
@@ -1376,6 +1376,16 @@ public final class CaptureRequest extends CameraMetadata<CaptureRequest.Key<?>>
* region and output only the intersection rectangle as the metering region in the result
* metadata. If the region is entirely outside the crop region, it will be ignored and
* not reported in the result metadata.</p>
+ * <p>Starting from API level 30, the coordinate system of activeArraySize or
+ * preCorrectionActiveArraySize is used to represent post-zoomRatio field of view, not
+ * pre-zoom field of view. This means that the same aeRegions values at different
+ * {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} represent different parts of the scene. The aeRegions
+ * coordinates are relative to the activeArray/preCorrectionActiveArray representing the
+ * zoomed field of view. If {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} is set to 1.0 (default), the same
+ * aeRegions at different {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion} still represent the same parts of the
+ * scene as they do before. See {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} for details. Whether to use
+ * activeArraySize or preCorrectionActiveArraySize still depends on distortion correction
+ * mode.</p>
* <p><b>Units</b>: Pixel coordinates within {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize} or
* {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize} depending on
* distortion correction capability and mode</p>
@@ -1386,6 +1396,7 @@ public final class CaptureRequest extends CameraMetadata<CaptureRequest.Key<?>>
* <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
*
* @see CameraCharacteristics#CONTROL_MAX_REGIONS_AE
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
* @see CaptureRequest#DISTORTION_CORRECTION_MODE
* @see CaptureRequest#SCALER_CROP_REGION
* @see CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE
@@ -1575,6 +1586,16 @@ public final class CaptureRequest extends CameraMetadata<CaptureRequest.Key<?>>
* region and output only the intersection rectangle as the metering region in the result
* metadata. If the region is entirely outside the crop region, it will be ignored and
* not reported in the result metadata.</p>
+ * <p>Starting from API level 30, the coordinate system of activeArraySize or
+ * preCorrectionActiveArraySize is used to represent post-zoomRatio field of view, not
+ * pre-zoom field of view. This means that the same afRegions values at different
+ * {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} represent different parts of the scene. The afRegions
+ * coordinates are relative to the activeArray/preCorrectionActiveArray representing the
+ * zoomed field of view. If {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} is set to 1.0 (default), the same
+ * afRegions at different {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion} still represent the same parts of the
+ * scene as they do before. See {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} for details. Whether to use
+ * activeArraySize or preCorrectionActiveArraySize still depends on distortion correction
+ * mode.</p>
* <p><b>Units</b>: Pixel coordinates within {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize} or
* {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize} depending on
* distortion correction capability and mode</p>
@@ -1585,6 +1606,7 @@ public final class CaptureRequest extends CameraMetadata<CaptureRequest.Key<?>>
* <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
*
* @see CameraCharacteristics#CONTROL_MAX_REGIONS_AF
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
* @see CaptureRequest#DISTORTION_CORRECTION_MODE
* @see CaptureRequest#SCALER_CROP_REGION
* @see CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE
@@ -1767,6 +1789,16 @@ public final class CaptureRequest extends CameraMetadata<CaptureRequest.Key<?>>
* region and output only the intersection rectangle as the metering region in the result
* metadata. If the region is entirely outside the crop region, it will be ignored and
* not reported in the result metadata.</p>
+ * <p>Starting from API level 30, the coordinate system of activeArraySize or
+ * preCorrectionActiveArraySize is used to represent post-zoomRatio field of view, not
+ * pre-zoom field of view. This means that the same awbRegions values at different
+ * {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} represent different parts of the scene. The awbRegions
+ * coordinates are relative to the activeArray/preCorrectionActiveArray representing the
+ * zoomed field of view. If {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} is set to 1.0 (default), the same
+ * awbRegions at different {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion} still represent the same parts of
+ * the scene as they do before. See {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} for details. Whether to use
+ * activeArraySize or preCorrectionActiveArraySize still depends on distortion correction
+ * mode.</p>
* <p><b>Units</b>: Pixel coordinates within {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize} or
* {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize} depending on
* distortion correction capability and mode</p>
@@ -1777,6 +1809,7 @@ public final class CaptureRequest extends CameraMetadata<CaptureRequest.Key<?>>
* <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
*
* @see CameraCharacteristics#CONTROL_MAX_REGIONS_AWB
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
* @see CaptureRequest#DISTORTION_CORRECTION_MODE
* @see CaptureRequest#SCALER_CROP_REGION
* @see CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE
@@ -2140,6 +2173,56 @@ public final class CaptureRequest extends CameraMetadata<CaptureRequest.Key<?>>
new Key<Integer>("android.control.bokehMode", int.class);
/**
+ * <p>The desired zoom ratio</p>
+ * <p>Instead of using {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion} with dual purposes of crop and zoom, the
+ * application can now choose to use this tag to specify the desired zoom level. The
+ * {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion} can still be used to specify the horizontal or vertical
+ * crop to achieve aspect ratios different than the native camera sensor.</p>
+ * <p>By using this control, the application gains a simpler way to control zoom, which can
+ * be a combination of optical and digital zoom. More specifically, for a logical
+ * multi-camera with more than one focal length, using a floating point zoom ratio offers
+ * more zoom precision when a telephoto lens is used, as well as allowing zoom ratio of
+ * less than 1.0 to zoom out to a wide field of view.</p>
+ * <p>Note that the coordinate system of cropRegion, AE/AWB/AF regions, and faces now changes
+ * to the effective after-zoom field-of-view represented by rectangle of (0, 0,
+ * activeArrayWidth, activeArrayHeight).</p>
+ * <p>For example, if {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize} is 4032*3024, and the preview stream
+ * is configured to the same 4:3 aspect ratio, the application can achieve 2.0x zoom in
+ * one of two ways:</p>
+ * <ul>
+ * <li>zoomRatio = 2.0, scaler.cropRegion = (0, 0, 4032, 3024)</li>
+ * <li>zoomRatio = 1.0 (default), scaler.cropRegion = (1008, 756, 3024, 2268)</li>
+ * </ul>
+ * <p>If the application intends to set aeRegions to be top-left quarter of the preview
+ * field-of-view, the {@link CaptureRequest#CONTROL_AE_REGIONS android.control.aeRegions} should be set to (0, 0, 2016, 1512) with
+ * zoomRatio set to 2.0. Alternatively, the application can set aeRegions to the equivalent
+ * region of (1008, 756, 2016, 1512) for zoomRatio of 1.0. If the application doesn't
+ * explicitly set {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}, its value defaults to 1.0.</p>
+ * <p>This coordinate system change isn't applicable to RAW capture and its related metadata
+ * such as intrinsicCalibration and lensShadingMap.</p>
+ * <p>One limitation of controlling zoom using zoomRatio is that the {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion}
+ * must only be used for letterboxing or pillarboxing of the sensor active array, and no
+ * FREEFORM cropping can be used with {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} other than 1.0.</p>
+ * <p><b>Range of valid values:</b><br>
+ * {@link CameraCharacteristics#CONTROL_ZOOM_RATIO_RANGE android.control.zoomRatioRange}</p>
+ * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
+ * <p><b>Limited capability</b> -
+ * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
+ * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
+ *
+ * @see CaptureRequest#CONTROL_AE_REGIONS
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
+ * @see CameraCharacteristics#CONTROL_ZOOM_RATIO_RANGE
+ * @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
+ * @see CaptureRequest#SCALER_CROP_REGION
+ * @see CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE
+ */
+ @PublicKey
+ @NonNull
+ public static final Key<Float> CONTROL_ZOOM_RATIO =
+ new Key<Float>("android.control.zoomRatio", float.class);
+
+ /**
* <p>Operation mode for edge
* enhancement.</p>
* <p>Edge enhancement improves sharpness and details in the captured image. OFF means
@@ -2697,12 +2780,21 @@ public final class CaptureRequest extends CameraMetadata<CaptureRequest.Key<?>>
* for rounding and other hardware requirements; the final
* crop region used will be included in the output capture
* result.</p>
+ * <p>Starting from API level 30, it's strongly recommended to use {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}
+ * to take advantage of better support for zoom with logical multi-camera. The benefits
+ * include better precision with optical-digital zoom combination, and ability to do
+ * zoom-out from 1.0x. When using {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} for zoom, the crop region in
+ * the capture request must be either letterboxing or pillarboxing (but not both). The
+ * coordinate system is post-zoom, meaning that the activeArraySize or
+ * preCorrectionActiveArraySize covers the camera device's field of view "after" zoom.
+ * See {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} for details.</p>
* <p><b>Units</b>: Pixel coordinates relative to
* {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize} or
* {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize} depending on distortion correction
* capability and mode</p>
* <p>This key is available on all devices.</p>
*
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
* @see CaptureRequest#DISTORTION_CORRECTION_MODE
* @see CameraCharacteristics#SCALER_AVAILABLE_MAX_DIGITAL_ZOOM
* @see CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE
diff --git a/core/java/android/hardware/camera2/CaptureResult.java b/core/java/android/hardware/camera2/CaptureResult.java
index 2d0ec6d19286..c9956231f34c 100644
--- a/core/java/android/hardware/camera2/CaptureResult.java
+++ b/core/java/android/hardware/camera2/CaptureResult.java
@@ -780,6 +780,16 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> {
* region and output only the intersection rectangle as the metering region in the result
* metadata. If the region is entirely outside the crop region, it will be ignored and
* not reported in the result metadata.</p>
+ * <p>Starting from API level 30, the coordinate system of activeArraySize or
+ * preCorrectionActiveArraySize is used to represent post-zoomRatio field of view, not
+ * pre-zoom field of view. This means that the same aeRegions values at different
+ * {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} represent different parts of the scene. The aeRegions
+ * coordinates are relative to the activeArray/preCorrectionActiveArray representing the
+ * zoomed field of view. If {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} is set to 1.0 (default), the same
+ * aeRegions at different {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion} still represent the same parts of the
+ * scene as they do before. See {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} for details. Whether to use
+ * activeArraySize or preCorrectionActiveArraySize still depends on distortion correction
+ * mode.</p>
* <p><b>Units</b>: Pixel coordinates within {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize} or
* {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize} depending on
* distortion correction capability and mode</p>
@@ -790,6 +800,7 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> {
* <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
*
* @see CameraCharacteristics#CONTROL_MAX_REGIONS_AE
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
* @see CaptureRequest#DISTORTION_CORRECTION_MODE
* @see CaptureRequest#SCALER_CROP_REGION
* @see CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE
@@ -1228,6 +1239,16 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> {
* region and output only the intersection rectangle as the metering region in the result
* metadata. If the region is entirely outside the crop region, it will be ignored and
* not reported in the result metadata.</p>
+ * <p>Starting from API level 30, the coordinate system of activeArraySize or
+ * preCorrectionActiveArraySize is used to represent post-zoomRatio field of view, not
+ * pre-zoom field of view. This means that the same afRegions values at different
+ * {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} represent different parts of the scene. The afRegions
+ * coordinates are relative to the activeArray/preCorrectionActiveArray representing the
+ * zoomed field of view. If {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} is set to 1.0 (default), the same
+ * afRegions at different {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion} still represent the same parts of the
+ * scene as they do before. See {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} for details. Whether to use
+ * activeArraySize or preCorrectionActiveArraySize still depends on distortion correction
+ * mode.</p>
* <p><b>Units</b>: Pixel coordinates within {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize} or
* {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize} depending on
* distortion correction capability and mode</p>
@@ -1238,6 +1259,7 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> {
* <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
*
* @see CameraCharacteristics#CONTROL_MAX_REGIONS_AF
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
* @see CaptureRequest#DISTORTION_CORRECTION_MODE
* @see CaptureRequest#SCALER_CROP_REGION
* @see CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE
@@ -1830,6 +1852,16 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> {
* region and output only the intersection rectangle as the metering region in the result
* metadata. If the region is entirely outside the crop region, it will be ignored and
* not reported in the result metadata.</p>
+ * <p>Starting from API level 30, the coordinate system of activeArraySize or
+ * preCorrectionActiveArraySize is used to represent post-zoomRatio field of view, not
+ * pre-zoom field of view. This means that the same awbRegions values at different
+ * {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} represent different parts of the scene. The awbRegions
+ * coordinates are relative to the activeArray/preCorrectionActiveArray representing the
+ * zoomed field of view. If {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} is set to 1.0 (default), the same
+ * awbRegions at different {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion} still represent the same parts of
+ * the scene as they do before. See {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} for details. Whether to use
+ * activeArraySize or preCorrectionActiveArraySize still depends on distortion correction
+ * mode.</p>
* <p><b>Units</b>: Pixel coordinates within {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize} or
* {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize} depending on
* distortion correction capability and mode</p>
@@ -1840,6 +1872,7 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> {
* <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
*
* @see CameraCharacteristics#CONTROL_MAX_REGIONS_AWB
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
* @see CaptureRequest#DISTORTION_CORRECTION_MODE
* @see CaptureRequest#SCALER_CROP_REGION
* @see CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE
@@ -2370,6 +2403,56 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> {
new Key<Integer>("android.control.bokehMode", int.class);
/**
+ * <p>The desired zoom ratio</p>
+ * <p>Instead of using {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion} with dual purposes of crop and zoom, the
+ * application can now choose to use this tag to specify the desired zoom level. The
+ * {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion} can still be used to specify the horizontal or vertical
+ * crop to achieve aspect ratios different than the native camera sensor.</p>
+ * <p>By using this control, the application gains a simpler way to control zoom, which can
+ * be a combination of optical and digital zoom. More specifically, for a logical
+ * multi-camera with more than one focal length, using a floating point zoom ratio offers
+ * more zoom precision when a telephoto lens is used, as well as allowing zoom ratio of
+ * less than 1.0 to zoom out to a wide field of view.</p>
+ * <p>Note that the coordinate system of cropRegion, AE/AWB/AF regions, and faces now changes
+ * to the effective after-zoom field-of-view represented by rectangle of (0, 0,
+ * activeArrayWidth, activeArrayHeight).</p>
+ * <p>For example, if {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize} is 4032*3024, and the preview stream
+ * is configured to the same 4:3 aspect ratio, the application can achieve 2.0x zoom in
+ * one of two ways:</p>
+ * <ul>
+ * <li>zoomRatio = 2.0, scaler.cropRegion = (0, 0, 4032, 3024)</li>
+ * <li>zoomRatio = 1.0 (default), scaler.cropRegion = (1008, 756, 3024, 2268)</li>
+ * </ul>
+ * <p>If the application intends to set aeRegions to be top-left quarter of the preview
+ * field-of-view, the {@link CaptureRequest#CONTROL_AE_REGIONS android.control.aeRegions} should be set to (0, 0, 2016, 1512) with
+ * zoomRatio set to 2.0. Alternatively, the application can set aeRegions to the equivalent
+ * region of (1008, 756, 2016, 1512) for zoomRatio of 1.0. If the application doesn't
+ * explicitly set {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}, its value defaults to 1.0.</p>
+ * <p>This coordinate system change isn't applicable to RAW capture and its related metadata
+ * such as intrinsicCalibration and lensShadingMap.</p>
+ * <p>One limitation of controlling zoom using zoomRatio is that the {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion}
+ * must only be used for letterboxing or pillarboxing of the sensor active array, and no
+ * FREEFORM cropping can be used with {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} other than 1.0.</p>
+ * <p><b>Range of valid values:</b><br>
+ * {@link CameraCharacteristics#CONTROL_ZOOM_RATIO_RANGE android.control.zoomRatioRange}</p>
+ * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
+ * <p><b>Limited capability</b> -
+ * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
+ * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
+ *
+ * @see CaptureRequest#CONTROL_AE_REGIONS
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
+ * @see CameraCharacteristics#CONTROL_ZOOM_RATIO_RANGE
+ * @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
+ * @see CaptureRequest#SCALER_CROP_REGION
+ * @see CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE
+ */
+ @PublicKey
+ @NonNull
+ public static final Key<Float> CONTROL_ZOOM_RATIO =
+ new Key<Float>("android.control.zoomRatio", float.class);
+
+ /**
* <p>Operation mode for edge
* enhancement.</p>
* <p>Edge enhancement improves sharpness and details in the captured image. OFF means
@@ -3336,12 +3419,21 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> {
* for rounding and other hardware requirements; the final
* crop region used will be included in the output capture
* result.</p>
+ * <p>Starting from API level 30, it's strongly recommended to use {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}
+ * to take advantage of better support for zoom with logical multi-camera. The benefits
+ * include better precision with optical-digital zoom combination, and ability to do
+ * zoom-out from 1.0x. When using {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} for zoom, the crop region in
+ * the capture request must be either letterboxing or pillarboxing (but not both). The
+ * coordinate system is post-zoom, meaning that the activeArraySize or
+ * preCorrectionActiveArraySize covers the camera device's field of view "after" zoom.
+ * See {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} for details.</p>
* <p><b>Units</b>: Pixel coordinates relative to
* {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize} or
* {@link CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE android.sensor.info.preCorrectionActiveArraySize} depending on distortion correction
* capability and mode</p>
* <p>This key is available on all devices.</p>
*
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
* @see CaptureRequest#DISTORTION_CORRECTION_MODE
* @see CameraCharacteristics#SCALER_AVAILABLE_MAX_DIGITAL_ZOOM
* @see CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE
@@ -3877,10 +3969,21 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> {
* When the distortion correction mode is not OFF, the coordinate system follows
* {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize}, with
* <code>(0, 0)</code> being the top-left pixel of the active array.</p>
- * <p>Only available if {@link CaptureRequest#STATISTICS_FACE_DETECT_MODE android.statistics.faceDetectMode} == FULL
- * This key is available on all devices.</p>
+ * <p>Only available if {@link CaptureRequest#STATISTICS_FACE_DETECT_MODE android.statistics.faceDetectMode} == FULL.</p>
+ * <p>Starting from API level 30, the coordinate system of activeArraySize or
+ * preCorrectionActiveArraySize is used to represent post-zoomRatio field of view, not
+ * pre-zoomRatio field of view. This means that if the relative position of faces and
+ * the camera device doesn't change, when zooming in by increasing
+ * {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}, the face landmarks move farther away from the center of the
+ * activeArray or preCorrectionActiveArray. If {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} is set to 1.0
+ * (default), the face landmarks coordinates won't change as {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion}
+ * changes. See {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} for details. Whether to use activeArraySize or
+ * preCorrectionActiveArraySize still depends on distortion correction mode.</p>
+ * <p>This key is available on all devices.</p>
*
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
* @see CaptureRequest#DISTORTION_CORRECTION_MODE
+ * @see CaptureRequest#SCALER_CROP_REGION
* @see CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE
* @see CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
* @see CaptureRequest#STATISTICS_FACE_DETECT_MODE
@@ -3903,10 +4006,21 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> {
* When the distortion correction mode is not OFF, the coordinate system follows
* {@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize}, with
* <code>(0, 0)</code> being the top-left pixel of the active array.</p>
- * <p>Only available if {@link CaptureRequest#STATISTICS_FACE_DETECT_MODE android.statistics.faceDetectMode} != OFF
- * This key is available on all devices.</p>
+ * <p>Only available if {@link CaptureRequest#STATISTICS_FACE_DETECT_MODE android.statistics.faceDetectMode} != OFF.</p>
+ * <p>Starting from API level 30, the coordinate system of activeArraySize or
+ * preCorrectionActiveArraySize is used to represent post-zoomRatio field of view, not
+ * pre-zoomRatio field of view. This means that if the relative position of faces and
+ * the camera device doesn't change, when zooming in by increasing
+ * {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}, the face rectangles grow larger and move farther away from
+ * the center of the activeArray or preCorrectionActiveArray. If {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}
+ * is set to 1.0 (default), the face rectangles won't change as {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion}
+ * changes. See {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} for details. Whether to use activeArraySize or
+ * preCorrectionActiveArraySize still depends on distortion correction mode.</p>
+ * <p>This key is available on all devices.</p>
*
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
* @see CaptureRequest#DISTORTION_CORRECTION_MODE
+ * @see CaptureRequest#SCALER_CROP_REGION
* @see CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE
* @see CameraCharacteristics#SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
* @see CaptureRequest#STATISTICS_FACE_DETECT_MODE
diff --git a/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java b/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
index bcbc33780ec4..41435c9b6a40 100644
--- a/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
+++ b/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
@@ -29,6 +29,7 @@ import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.ICameraDeviceCallbacks;
import android.hardware.camera2.ICameraDeviceUser;
+import android.hardware.camera2.ICameraOfflineSession;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.InputConfiguration;
import android.hardware.camera2.params.OutputConfiguration;
@@ -866,6 +867,38 @@ public class CameraDeviceImpl extends CameraDevice
}
}
+ public void switchToOffline(ICameraDeviceCallbacks cbs, Surface[] offlineOutputs)
+ throws CameraAccessException {
+ if ((offlineOutputs == null) || (offlineOutputs.length == 0)) {
+ throw new IllegalArgumentException("Invalid offline outputs!");
+ }
+ if (cbs == null) {
+ throw new IllegalArgumentException("Invalid device callbacks!");
+ }
+
+ ICameraOfflineSession offlineSession = null;
+ synchronized(mInterfaceLock) {
+ int streamId = -1;
+ for (Surface surface : offlineOutputs) {
+ for (int i = 0; i < mConfiguredOutputs.size(); i++) {
+ if (surface == mConfiguredOutputs.valueAt(i).getSurface()) {
+ streamId = mConfiguredOutputs.keyAt(i);
+ break;
+ }
+ }
+ if (streamId == -1) {
+ throw new IllegalArgumentException("Offline surface is not part of this" +
+ " session");
+ }
+ }
+
+ offlineSession = mRemoteDevice.switchToOffline(cbs,
+ offlineOutputs);
+ // TODO: Initialize CameraOfflineSession wrapper, clear 'mConfiguredOutputs',
+ // and update request tracking
+ }
+ }
+
public void tearDown(Surface surface) throws CameraAccessException {
if (surface == null) throw new IllegalArgumentException("Surface is null");
diff --git a/core/java/android/hardware/camera2/impl/CameraMetadataNative.java b/core/java/android/hardware/camera2/impl/CameraMetadataNative.java
index 7c1ddad5fe12..c3ebe434ca05 100644
--- a/core/java/android/hardware/camera2/impl/CameraMetadataNative.java
+++ b/core/java/android/hardware/camera2/impl/CameraMetadataNative.java
@@ -30,7 +30,6 @@ import android.hardware.camera2.marshal.MarshalRegistry;
import android.hardware.camera2.marshal.Marshaler;
import android.hardware.camera2.marshal.impl.MarshalQueryableArray;
import android.hardware.camera2.marshal.impl.MarshalQueryableBlackLevelPattern;
-import android.hardware.camera2.marshal.impl.MarshalQueryableCapabilityAndMaxSize;
import android.hardware.camera2.marshal.impl.MarshalQueryableBoolean;
import android.hardware.camera2.marshal.impl.MarshalQueryableColorSpaceTransform;
import android.hardware.camera2.marshal.impl.MarshalQueryableEnum;
@@ -50,7 +49,7 @@ import android.hardware.camera2.marshal.impl.MarshalQueryableSizeF;
import android.hardware.camera2.marshal.impl.MarshalQueryableStreamConfiguration;
import android.hardware.camera2.marshal.impl.MarshalQueryableStreamConfigurationDuration;
import android.hardware.camera2.marshal.impl.MarshalQueryableString;
-import android.hardware.camera2.params.CapabilityAndMaxSize;
+import android.hardware.camera2.params.Capability;
import android.hardware.camera2.params.Face;
import android.hardware.camera2.params.HighSpeedVideoConfiguration;
import android.hardware.camera2.params.LensShadingMap;
@@ -71,6 +70,7 @@ import android.os.Parcel;
import android.os.Parcelable;
import android.os.ServiceSpecificException;
import android.util.Log;
+import android.util.Range;
import android.util.Size;
import com.android.internal.util.Preconditions;
@@ -1385,22 +1385,57 @@ public class CameraMetadataNative implements Parcelable {
return samples;
}
- private CapabilityAndMaxSize[] getBokehCapabilities() {
- CapabilityAndMaxSize[] bcs = getBase(
- CameraCharacteristics.CONTROL_AVAILABLE_BOKEH_CAPABILITIES);
+ private Capability[] getBokehCapabilities() {
+ int[] bokehMaxSizes = getBase(CameraCharacteristics.CONTROL_AVAILABLE_BOKEH_MAX_SIZES);
+ float[] bokehZoomRanges = getBase(
+ CameraCharacteristics.CONTROL_AVAILABLE_BOKEH_ZOOM_RATIO_RANGES);
+ Range<Float> zoomRange = getBase(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE);
+ float maxDigitalZoom = getBase(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM);
- if (bcs != null) {
- for (CapabilityAndMaxSize bc : bcs) {
- if (bc.getMode() < CameraMetadata.CONTROL_BOKEH_MODE_OFF ||
- bc.getMode() > CameraMetadata.CONTROL_BOKEH_MODE_CONTINUOUS) {
- throw new AssertionError(String.format(
- "bokehMode %d is out of valid range [%d, %d]", bc.getMode(),
- CameraMetadata.CONTROL_BOKEH_MODE_OFF,
- CameraMetadata.CONTROL_BOKEH_MODE_CONTINUOUS));
- }
+ if (bokehMaxSizes == null) {
+ return null;
+ }
+ if (bokehMaxSizes.length % 3 != 0) {
+ throw new AssertionError("availableBokehMaxSizes must be tuples of " +
+ "[mode, width, height]");
+ }
+ int numBokehModes = bokehMaxSizes.length / 3;
+ int numBokehZoomRanges = 0;
+ if (bokehZoomRanges != null) {
+ if (bokehZoomRanges.length % 2 != 0) {
+ throw new AssertionError("availableBokehZoomRanges must be tuples of " +
+ "[minZoom, maxZoom]");
+ }
+ numBokehZoomRanges = bokehZoomRanges.length / 2;
+ if (numBokehModes - numBokehZoomRanges != 1) {
+ throw new AssertionError("Number of bokeh zoom ranges must be 1 less than " +
+ "number of supported bokeh modes");
+ }
+ }
+
+ float bokehOffMinZoomRatio = 1.0f;
+ float bokehOffMaxZoomRatio = maxDigitalZoom;
+ if (zoomRange != null) {
+ bokehOffMinZoomRatio = zoomRange.getLower();
+ bokehOffMaxZoomRatio = zoomRange.getUpper();
+ }
+
+ Capability[] capabilities = new Capability[numBokehModes];
+ for (int i = 0, j = 0; i < numBokehModes; i++) {
+ int mode = bokehMaxSizes[3 * i];
+ int width = bokehMaxSizes[3 * i + 1];
+ int height = bokehMaxSizes[3 * i + 2];
+ if (mode != CameraMetadata.CONTROL_BOKEH_MODE_OFF && j < numBokehZoomRanges) {
+ capabilities[i] = new Capability(mode, width, height, bokehZoomRanges[2 * j],
+ bokehZoomRanges[2 * j + 1]);
+ j++;
+ } else {
+ capabilities[i] = new Capability(mode, width, height, bokehOffMinZoomRatio,
+ bokehOffMaxZoomRatio);
}
}
- return bcs;
+
+ return capabilities;
}
private <T> void setBase(CameraCharacteristics.Key<T> key, T value) {
@@ -1780,7 +1815,6 @@ public class CameraMetadataNative implements Parcelable {
new MarshalQueryableBlackLevelPattern(),
new MarshalQueryableHighSpeedVideoConfiguration(),
new MarshalQueryableRecommendedStreamConfiguration(),
- new MarshalQueryableCapabilityAndMaxSize(),
// generic parcelable marshaler (MUST BE LAST since it has lowest priority)
new MarshalQueryableParcelable(),
diff --git a/core/java/android/hardware/camera2/impl/ICameraDeviceUserWrapper.java b/core/java/android/hardware/camera2/impl/ICameraDeviceUserWrapper.java
index 3660f29f68d1..397417ba5b4f 100644
--- a/core/java/android/hardware/camera2/impl/ICameraDeviceUserWrapper.java
+++ b/core/java/android/hardware/camera2/impl/ICameraDeviceUserWrapper.java
@@ -28,6 +28,8 @@ import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.ICameraDeviceUser;
+import android.hardware.camera2.ICameraDeviceCallbacks;
+import android.hardware.camera2.ICameraOfflineSession;
import android.hardware.camera2.impl.CameraMetadataNative;
import android.hardware.camera2.params.OutputConfiguration;
import android.hardware.camera2.params.SessionConfiguration;
@@ -248,6 +250,17 @@ public class ICameraDeviceUserWrapper {
}
}
+ public ICameraOfflineSession switchToOffline(ICameraDeviceCallbacks cbs,
+ Surface[] offlineOutputs)
+ throws CameraAccessException {
+ try {
+ return mRemoteDevice.switchToOffline(cbs, offlineOutputs);
+ } catch (Throwable t) {
+ CameraManager.throwAsPublicException(t);
+ throw new UnsupportedOperationException("Unexpected exception", t);
+ }
+ }
+
public void finalizeOutputConfigurations(int streamId, OutputConfiguration deferredConfig)
throws CameraAccessException {
try {
diff --git a/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java b/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java
index 5d1435ab4c8d..6ab0c294f5e4 100644
--- a/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java
+++ b/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java
@@ -24,6 +24,7 @@ import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.ICameraDeviceCallbacks;
import android.hardware.camera2.ICameraDeviceUser;
+import android.hardware.camera2.ICameraOfflineSession;
import android.hardware.camera2.impl.CameraMetadataNative;
import android.hardware.camera2.impl.CaptureResultExtras;
import android.hardware.camera2.impl.PhysicalCaptureResultInfo;
@@ -789,6 +790,12 @@ public class CameraDeviceUserShim implements ICameraDeviceUser {
}
@Override
+ public ICameraOfflineSession switchToOffline(ICameraDeviceCallbacks cbs,
+ Surface[] offlineOutputs) {
+ throw new UnsupportedOperationException("Legacy device does not support switchToOffline");
+ }
+
+ @Override
public IBinder asBinder() {
// This is solely intended to be used for in-process binding.
return null;
diff --git a/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableCapabilityAndMaxSize.java b/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableCapabilityAndMaxSize.java
deleted file mode 100644
index 5c1f301369e1..000000000000
--- a/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableCapabilityAndMaxSize.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2019 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.hardware.camera2.marshal.impl;
-
-import android.hardware.camera2.marshal.MarshalQueryable;
-import android.hardware.camera2.marshal.Marshaler;
-import android.hardware.camera2.params.CapabilityAndMaxSize;
-import android.hardware.camera2.utils.TypeReference;
-import android.util.Size;
-
-import java.nio.ByteBuffer;
-
-import static android.hardware.camera2.impl.CameraMetadataNative.TYPE_INT32;
-import static android.hardware.camera2.marshal.MarshalHelpers.SIZEOF_INT32;
-
-/**
- * Marshal {@link CapabilityAndMaxSize} to/from {@link #TYPE_INT32} {@code x CapabilityAndMaxSize.COUNT}
- */
-public class MarshalQueryableCapabilityAndMaxSize implements MarshalQueryable<CapabilityAndMaxSize> {
- private static final int SIZE = SIZEOF_INT32 * CapabilityAndMaxSize.COUNT;
-
- private class MarshalerCapabilityAndMaxSize extends Marshaler<CapabilityAndMaxSize> {
- protected MarshalerCapabilityAndMaxSize(TypeReference<CapabilityAndMaxSize> typeReference,
- int nativeType) {
- super(MarshalQueryableCapabilityAndMaxSize.this, typeReference, nativeType);
- }
-
- @Override
- public void marshal(CapabilityAndMaxSize value, ByteBuffer buffer) {
- Size maxStreamingSize = value.getMaxStreamingSize();
-
- buffer.putInt(value.getMode());
- buffer.putInt(maxStreamingSize.getWidth());
- buffer.putInt(maxStreamingSize.getHeight());
- }
-
- @Override
- public CapabilityAndMaxSize unmarshal(ByteBuffer buffer) {
- int mode = buffer.getInt();
- int maxWidth = buffer.getInt();
- int maxHeight = buffer.getInt();
-
- return new CapabilityAndMaxSize(mode, maxWidth, maxHeight);
- }
-
- @Override
- public int getNativeSize() {
- return SIZE;
- }
- }
-
- @Override
- public Marshaler<CapabilityAndMaxSize> createMarshaler(
- TypeReference<CapabilityAndMaxSize> managedType, int nativeType) {
- return new MarshalerCapabilityAndMaxSize(managedType, nativeType);
- }
-
- @Override
- public boolean isTypeMappingSupported(
- TypeReference<CapabilityAndMaxSize> managedType, int nativeType) {
- return nativeType == TYPE_INT32 &&
- (CapabilityAndMaxSize.class.equals(managedType.getType()));
- }
-}
diff --git a/core/java/android/hardware/camera2/params/CapabilityAndMaxSize.java b/core/java/android/hardware/camera2/params/Capability.java
index be0829934a4b..367690c37960 100644
--- a/core/java/android/hardware/camera2/params/CapabilityAndMaxSize.java
+++ b/core/java/android/hardware/camera2/params/Capability.java
@@ -23,16 +23,17 @@ import android.annotation.NonNull;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.utils.HashCodeHelpers;
+import android.util.Range;
import android.util.Size;
/**
- * Immutable class to store the available camera capability and its
- * corresponding maximum streaming dimensions.
+ * Immutable class to store the camera capability, its corresponding maximum
+ * streaming dimension and zoom range.
*
* @see CameraCharacteristics#CONTROL_AVAILABLE_BOKEH_CAPABILITIES
*/
-public final class CapabilityAndMaxSize {
+public final class Capability {
/**
* @hide
*/
@@ -41,22 +42,31 @@ public final class CapabilityAndMaxSize {
private final int mMode;
private final int mMaxStreamingWidth;
private final int mMaxStreamingHeight;
+ private final float mMinZoomRatio;
+ private final float mMaxZoomRatio;
/**
- * Create a new CapabilityAndMaxSize object.
+ * Create a new Capability object.
*
* @param mode supported mode for a camera capability.
- * @param maxStreamingWidth width >= 0
- * @param maxStreamingHeight height >= 0
+ * @param maxStreamingWidth The width of the maximum streaming size for this mode
+ * @param maxStreamingHeight The height of the maximum streaming size for this mode
+ * @param minZoomRatio the minimum zoom ratio this mode supports
+ * @param maxZoomRatio the maximum zoom ratio this mode supports
*
+ * @throws IllegalArgumentException if any of the argument is not valid
* @hide
*/
- public CapabilityAndMaxSize(int mode, int maxStreamingWidth, int maxStreamingHeight) {
+ public Capability(int mode, int maxStreamingWidth, int maxStreamingHeight,
+ float minZoomRatio, float maxZoomRatio) {
mMode = mode;
mMaxStreamingWidth = checkArgumentNonnegative(maxStreamingWidth,
"maxStreamingWidth must be nonnegative");
mMaxStreamingHeight = checkArgumentNonnegative(maxStreamingHeight,
"maxStreamingHeight must be nonnegative");
+ mMinZoomRatio = checkArgumentInRange(minZoomRatio, 0.0f, 1.0f,
+ "minZoomRatio must be between 0.0f and 1.0f");
+ mMaxZoomRatio = maxZoomRatio;
}
/**
@@ -81,11 +91,22 @@ public final class CapabilityAndMaxSize {
}
/**
- * Compare two CapabilityAndMaxSize objects to see if they are equal.
+ * Return the zoom ratio range of this capability.
*
- * @param obj Another CapabilityAndMaxSize object
+ * @return The supported zoom ratio range supported by this capability
+ */
+ public @NonNull Range<Float> getZoomRatioRange() {
+ return new Range<Float>(mMinZoomRatio, mMaxZoomRatio);
+ }
+
+
+ /**
+ * Compare two Capability objects to see if they are equal.
+ *
+ * @param obj Another Capability object
*
- * @return {@code true} if the mode and max size are equal, {@code false} otherwise
+ * @return {@code true} if the mode, max size and zoom ratio range are equal,
+ * {@code false} otherwise
*/
@Override
public boolean equals(final Object obj) {
@@ -95,11 +116,13 @@ public final class CapabilityAndMaxSize {
if (this == obj) {
return true;
}
- if (obj instanceof CapabilityAndMaxSize) {
- final CapabilityAndMaxSize other = (CapabilityAndMaxSize) obj;
+ if (obj instanceof Capability) {
+ final Capability other = (Capability) obj;
return (mMode == other.mMode
&& mMaxStreamingWidth == other.mMaxStreamingWidth
- && mMaxStreamingHeight == other.mMaxStreamingHeight);
+ && mMaxStreamingHeight == other.mMaxStreamingHeight
+ && mMinZoomRatio == other.mMinZoomRatio
+ && mMaxZoomRatio == other.mMaxZoomRatio);
}
return false;
}
@@ -109,18 +132,20 @@ public final class CapabilityAndMaxSize {
*/
@Override
public int hashCode() {
- return HashCodeHelpers.hashCode(mMode, mMaxStreamingWidth, mMaxStreamingHeight);
+ return HashCodeHelpers.hashCode(mMode, mMaxStreamingWidth, mMaxStreamingHeight,
+ mMinZoomRatio, mMaxZoomRatio);
}
/**
- * Return the CapabilityAndMaxSize as a string representation
- * {@code "(mode:%d, maxStreamingSize:%d x %d)"}.
+ * Return the Capability as a string representation
+ * {@code "(mode:%d, maxStreamingSize:%d x %d, zoomRatio: %f-%f)"}.
*
* @return string representation of the capability and max streaming size.
*/
@Override
public String toString() {
- return String.format("(mode:%d, maxStreamingSize:%d x %d)",
- mMode, mMaxStreamingWidth, mMaxStreamingHeight);
+ return String.format("(mode:%d, maxStreamingSize:%d x %d, zoomRatio: %f-%f)",
+ mMode, mMaxStreamingWidth, mMaxStreamingHeight, mMinZoomRatio,
+ mMaxZoomRatio);
}
}
diff --git a/core/java/android/hardware/camera2/params/MandatoryStreamCombination.java b/core/java/android/hardware/camera2/params/MandatoryStreamCombination.java
index 6eaf54bd0d4d..23f18a80caf8 100644
--- a/core/java/android/hardware/camera2/params/MandatoryStreamCombination.java
+++ b/core/java/android/hardware/camera2/params/MandatoryStreamCombination.java
@@ -1163,7 +1163,7 @@ public final class MandatoryStreamCombination {
if (orderedPreviewSizes != null) {
for (Size size : orderedPreviewSizes) {
if ((mDisplaySize.getWidth() >= size.getWidth()) &&
- (mDisplaySize.getWidth() >= size.getHeight())) {
+ (mDisplaySize.getHeight() >= size.getHeight())) {
return size;
}
}
diff --git a/core/java/android/hardware/soundtrigger/ConversionUtil.java b/core/java/android/hardware/soundtrigger/ConversionUtil.java
new file mode 100644
index 000000000000..8231c58a105e
--- /dev/null
+++ b/core/java/android/hardware/soundtrigger/ConversionUtil.java
@@ -0,0 +1,329 @@
+/*
+ * Copyright (C) 2019 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.hardware.soundtrigger;
+
+import android.hardware.soundtrigger.ModelParams;
+import android.media.AudioFormat;
+import android.media.audio.common.AudioConfig;
+import android.media.soundtrigger_middleware.ConfidenceLevel;
+import android.media.soundtrigger_middleware.ModelParameterRange;
+import android.media.soundtrigger_middleware.Phrase;
+import android.media.soundtrigger_middleware.PhraseRecognitionEvent;
+import android.media.soundtrigger_middleware.PhraseRecognitionExtra;
+import android.media.soundtrigger_middleware.PhraseSoundModel;
+import android.media.soundtrigger_middleware.RecognitionConfig;
+import android.media.soundtrigger_middleware.RecognitionEvent;
+import android.media.soundtrigger_middleware.RecognitionMode;
+import android.media.soundtrigger_middleware.SoundModel;
+import android.media.soundtrigger_middleware.SoundTriggerModuleDescriptor;
+import android.media.soundtrigger_middleware.SoundTriggerModuleProperties;
+
+import android.annotation.Nullable;
+
+import java.util.Arrays;
+import java.util.UUID;
+
+/** @hide */
+class ConversionUtil {
+ public static SoundTrigger.ModuleProperties aidl2apiModuleDescriptor(
+ SoundTriggerModuleDescriptor aidlDesc) {
+ SoundTriggerModuleProperties properties = aidlDesc.properties;
+ return new SoundTrigger.ModuleProperties(
+ aidlDesc.handle,
+ properties.implementor,
+ properties.description,
+ properties.uuid,
+ properties.version,
+ properties.maxSoundModels,
+ properties.maxKeyPhrases,
+ properties.maxUsers,
+ aidl2apiRecognitionModes(properties.recognitionModes),
+ properties.captureTransition,
+ properties.maxBufferMs,
+ properties.concurrentCapture,
+ properties.powerConsumptionMw,
+ properties.triggerInEvent
+ );
+ }
+
+ public static int aidl2apiRecognitionModes(int aidlModes) {
+ int result = 0;
+ if ((aidlModes & RecognitionMode.VOICE_TRIGGER) != 0) {
+ result |= SoundTrigger.RECOGNITION_MODE_VOICE_TRIGGER;
+ }
+ if ((aidlModes & RecognitionMode.USER_IDENTIFICATION) != 0) {
+ result |= SoundTrigger.RECOGNITION_MODE_USER_IDENTIFICATION;
+ }
+ if ((aidlModes & RecognitionMode.USER_AUTHENTICATION) != 0) {
+ result |= SoundTrigger.RECOGNITION_MODE_USER_AUTHENTICATION;
+ }
+ if ((aidlModes & RecognitionMode.GENERIC_TRIGGER) != 0) {
+ result |= SoundTrigger.RECOGNITION_MODE_GENERIC;
+ }
+ return result;
+ }
+
+ public static int api2aidlRecognitionModes(int apiModes) {
+ int result = 0;
+ if ((apiModes & SoundTrigger.RECOGNITION_MODE_VOICE_TRIGGER) != 0) {
+ result |= RecognitionMode.VOICE_TRIGGER;
+ }
+ if ((apiModes & SoundTrigger.RECOGNITION_MODE_USER_IDENTIFICATION) != 0) {
+ result |= RecognitionMode.USER_IDENTIFICATION;
+ }
+ if ((apiModes & SoundTrigger.RECOGNITION_MODE_USER_AUTHENTICATION) != 0) {
+ result |= RecognitionMode.USER_AUTHENTICATION;
+ }
+ if ((apiModes & SoundTrigger.RECOGNITION_MODE_GENERIC) != 0) {
+ result |= RecognitionMode.GENERIC_TRIGGER;
+ }
+ return result;
+ }
+
+
+ public static SoundModel api2aidlGenericSoundModel(SoundTrigger.GenericSoundModel apiModel) {
+ return api2aidlSoundModel(apiModel);
+ }
+
+ public static SoundModel api2aidlSoundModel(SoundTrigger.SoundModel apiModel) {
+ SoundModel aidlModel = new SoundModel();
+ aidlModel.type = apiModel.type;
+ aidlModel.uuid = api2aidlUuid(apiModel.uuid);
+ aidlModel.vendorUuid = api2aidlUuid(apiModel.vendorUuid);
+ aidlModel.data = Arrays.copyOf(apiModel.data, apiModel.data.length);
+ return aidlModel;
+ }
+
+ public static String api2aidlUuid(UUID apiUuid) {
+ return apiUuid.toString();
+ }
+
+ public static PhraseSoundModel api2aidlPhraseSoundModel(
+ SoundTrigger.KeyphraseSoundModel apiModel) {
+ PhraseSoundModel aidlModel = new PhraseSoundModel();
+ aidlModel.common = api2aidlSoundModel(apiModel);
+ aidlModel.phrases = new Phrase[apiModel.keyphrases.length];
+ for (int i = 0; i < apiModel.keyphrases.length; ++i) {
+ aidlModel.phrases[i] = api2aidlPhrase(apiModel.keyphrases[i]);
+ }
+ return aidlModel;
+ }
+
+ public static Phrase api2aidlPhrase(SoundTrigger.Keyphrase apiPhrase) {
+ Phrase aidlPhrase = new Phrase();
+ aidlPhrase.id = apiPhrase.id;
+ aidlPhrase.recognitionModes = api2aidlRecognitionModes(apiPhrase.recognitionModes);
+ aidlPhrase.users = Arrays.copyOf(apiPhrase.users, apiPhrase.users.length);
+ aidlPhrase.locale = apiPhrase.locale;
+ aidlPhrase.text = apiPhrase.text;
+ return aidlPhrase;
+ }
+
+ public static RecognitionConfig api2aidlRecognitionConfig(
+ SoundTrigger.RecognitionConfig apiConfig) {
+ RecognitionConfig aidlConfig = new RecognitionConfig();
+ aidlConfig.captureRequested = apiConfig.captureRequested;
+ // apiConfig.allowMultipleTriggers is ignored by the lower layers.
+ aidlConfig.phraseRecognitionExtras =
+ new PhraseRecognitionExtra[apiConfig.keyphrases.length];
+ for (int i = 0; i < apiConfig.keyphrases.length; ++i) {
+ aidlConfig.phraseRecognitionExtras[i] = api2aidlPhraseRecognitionExtra(
+ apiConfig.keyphrases[i]);
+ }
+ aidlConfig.data = Arrays.copyOf(apiConfig.data, apiConfig.data.length);
+ return aidlConfig;
+ }
+
+ public static PhraseRecognitionExtra api2aidlPhraseRecognitionExtra(
+ SoundTrigger.KeyphraseRecognitionExtra apiExtra) {
+ PhraseRecognitionExtra aidlExtra = new PhraseRecognitionExtra();
+ aidlExtra.id = apiExtra.id;
+ aidlExtra.recognitionModes = api2aidlRecognitionModes(apiExtra.recognitionModes);
+ aidlExtra.confidenceLevel = apiExtra.coarseConfidenceLevel;
+ aidlExtra.levels = new ConfidenceLevel[apiExtra.confidenceLevels.length];
+ for (int i = 0; i < apiExtra.confidenceLevels.length; ++i) {
+ aidlExtra.levels[i] = api2aidlConfidenceLevel(apiExtra.confidenceLevels[i]);
+ }
+ return aidlExtra;
+ }
+
+ public static SoundTrigger.KeyphraseRecognitionExtra aidl2apiPhraseRecognitionExtra(
+ PhraseRecognitionExtra aidlExtra) {
+ SoundTrigger.ConfidenceLevel[] apiLevels =
+ new SoundTrigger.ConfidenceLevel[aidlExtra.levels.length];
+ for (int i = 0; i < aidlExtra.levels.length; ++i) {
+ apiLevels[i] = aidl2apiConfidenceLevel(aidlExtra.levels[i]);
+ }
+ return new SoundTrigger.KeyphraseRecognitionExtra(aidlExtra.id,
+ aidl2apiRecognitionModes(aidlExtra.recognitionModes),
+ aidlExtra.confidenceLevel, apiLevels);
+ }
+
+ public static ConfidenceLevel api2aidlConfidenceLevel(
+ SoundTrigger.ConfidenceLevel apiLevel) {
+ ConfidenceLevel aidlLevel = new ConfidenceLevel();
+ aidlLevel.levelPercent = apiLevel.confidenceLevel;
+ aidlLevel.userId = apiLevel.userId;
+ return aidlLevel;
+ }
+
+ public static SoundTrigger.ConfidenceLevel aidl2apiConfidenceLevel(
+ ConfidenceLevel apiLevel) {
+ return new SoundTrigger.ConfidenceLevel(apiLevel.userId, apiLevel.levelPercent);
+ }
+
+ public static SoundTrigger.RecognitionEvent aidl2apiRecognitionEvent(
+ int modelHandle, RecognitionEvent aidlEvent) {
+ return new SoundTrigger.GenericRecognitionEvent(
+ aidlEvent.status,
+ modelHandle, aidlEvent.captureAvailable, aidlEvent.captureSession,
+ aidlEvent.captureDelayMs, aidlEvent.capturePreambleMs, aidlEvent.triggerInData,
+ aidl2apiAudioFormat(aidlEvent.audioConfig), aidlEvent.data);
+ }
+
+ public static SoundTrigger.RecognitionEvent aidl2apiPhraseRecognitionEvent(
+ int modelHandle,
+ PhraseRecognitionEvent aidlEvent) {
+ SoundTrigger.KeyphraseRecognitionExtra[] apiExtras =
+ new SoundTrigger.KeyphraseRecognitionExtra[aidlEvent.phraseExtras.length];
+ for (int i = 0; i < aidlEvent.phraseExtras.length; ++i) {
+ apiExtras[i] = aidl2apiPhraseRecognitionExtra(aidlEvent.phraseExtras[i]);
+ }
+ return new SoundTrigger.KeyphraseRecognitionEvent(aidlEvent.common.status, modelHandle,
+ aidlEvent.common.captureAvailable,
+ aidlEvent.common.captureSession, aidlEvent.common.captureDelayMs,
+ aidlEvent.common.capturePreambleMs, aidlEvent.common.triggerInData,
+ aidl2apiAudioFormat(aidlEvent.common.audioConfig), aidlEvent.common.data,
+ apiExtras);
+ }
+
+ public static AudioFormat aidl2apiAudioFormat(AudioConfig audioConfig) {
+ AudioFormat.Builder apiBuilder = new AudioFormat.Builder();
+ apiBuilder.setSampleRate(audioConfig.sampleRateHz);
+ apiBuilder.setChannelMask(aidl2apiChannelInMask(audioConfig.channelMask));
+ apiBuilder.setEncoding(aidl2apiEncoding(audioConfig.format));
+ return apiBuilder.build();
+ }
+
+ public static int aidl2apiEncoding(int aidlFormat) {
+ switch (aidlFormat) {
+ case android.media.audio.common.AudioFormat.PCM
+ | android.media.audio.common.AudioFormat.PCM_SUB_16_BIT:
+ return AudioFormat.ENCODING_PCM_16BIT;
+
+ case android.media.audio.common.AudioFormat.PCM
+ | android.media.audio.common.AudioFormat.PCM_SUB_8_BIT:
+ return AudioFormat.ENCODING_PCM_8BIT;
+
+ case android.media.audio.common.AudioFormat.PCM
+ | android.media.audio.common.AudioFormat.PCM_SUB_FLOAT:
+ case android.media.audio.common.AudioFormat.PCM
+ | android.media.audio.common.AudioFormat.PCM_SUB_8_24_BIT:
+ case android.media.audio.common.AudioFormat.PCM
+ | android.media.audio.common.AudioFormat.PCM_SUB_24_BIT_PACKED:
+ case android.media.audio.common.AudioFormat.PCM
+ | android.media.audio.common.AudioFormat.PCM_SUB_32_BIT:
+ return AudioFormat.ENCODING_PCM_FLOAT;
+
+ case android.media.audio.common.AudioFormat.AC3:
+ return AudioFormat.ENCODING_AC3;
+
+ case android.media.audio.common.AudioFormat.E_AC3:
+ return AudioFormat.ENCODING_E_AC3;
+
+ case android.media.audio.common.AudioFormat.DTS:
+ return AudioFormat.ENCODING_DTS;
+
+ case android.media.audio.common.AudioFormat.DTS_HD:
+ return AudioFormat.ENCODING_DTS_HD;
+
+ case android.media.audio.common.AudioFormat.MP3:
+ return AudioFormat.ENCODING_MP3;
+
+ case android.media.audio.common.AudioFormat.AAC
+ | android.media.audio.common.AudioFormat.AAC_SUB_LC:
+ return AudioFormat.ENCODING_AAC_LC;
+
+ case android.media.audio.common.AudioFormat.AAC
+ | android.media.audio.common.AudioFormat.AAC_SUB_HE_V1:
+ return AudioFormat.ENCODING_AAC_HE_V1;
+
+ case android.media.audio.common.AudioFormat.AAC
+ | android.media.audio.common.AudioFormat.AAC_SUB_HE_V2:
+ return AudioFormat.ENCODING_AAC_HE_V2;
+
+ case android.media.audio.common.AudioFormat.IEC61937:
+ return AudioFormat.ENCODING_IEC61937;
+
+ case android.media.audio.common.AudioFormat.DOLBY_TRUEHD:
+ return AudioFormat.ENCODING_DOLBY_TRUEHD;
+
+ case android.media.audio.common.AudioFormat.AAC
+ | android.media.audio.common.AudioFormat.AAC_SUB_ELD:
+ return AudioFormat.ENCODING_AAC_ELD;
+
+ case android.media.audio.common.AudioFormat.AAC
+ | android.media.audio.common.AudioFormat.AAC_SUB_XHE:
+ return AudioFormat.ENCODING_AAC_XHE;
+
+ case android.media.audio.common.AudioFormat.AC4:
+ return AudioFormat.ENCODING_AC4;
+
+ case android.media.audio.common.AudioFormat.E_AC3
+ | android.media.audio.common.AudioFormat.E_AC3_SUB_JOC:
+ return AudioFormat.ENCODING_E_AC3_JOC;
+
+ case android.media.audio.common.AudioFormat.MAT:
+ case android.media.audio.common.AudioFormat.MAT
+ | android.media.audio.common.AudioFormat.MAT_SUB_1_0:
+ case android.media.audio.common.AudioFormat.MAT
+ | android.media.audio.common.AudioFormat.MAT_SUB_2_0:
+ case android.media.audio.common.AudioFormat.MAT
+ | android.media.audio.common.AudioFormat.MAT_SUB_2_1:
+ return AudioFormat.ENCODING_DOLBY_MAT;
+
+ case android.media.audio.common.AudioFormat.DEFAULT:
+ return AudioFormat.ENCODING_DEFAULT;
+
+ default:
+ return AudioFormat.ENCODING_INVALID;
+ }
+ }
+
+ public static int api2aidlModelParameter(int apiParam) {
+ switch (apiParam) {
+ case ModelParams.THRESHOLD_FACTOR:
+ return android.media.soundtrigger_middleware.ModelParameter.THRESHOLD_FACTOR;
+ default:
+ return android.media.soundtrigger_middleware.ModelParameter.INVALID;
+ }
+ }
+
+ public static int aidl2apiChannelInMask(int aidlMask) {
+ // We're assuming AudioFormat.CHANNEL_IN_* constants are kept in sync with
+ // android.media.audio.common.AudioChannelMask.
+ return aidlMask;
+ }
+
+ public static SoundTrigger.ModelParamRange aidl2apiModelParameterRange(
+ @Nullable ModelParameterRange aidlRange) {
+ if (aidlRange == null) {
+ return null;
+ }
+ return new SoundTrigger.ModelParamRange(aidlRange.minInclusive, aidlRange.maxInclusive);
+ }
+}
diff --git a/core/java/android/hardware/soundtrigger/ModelParams.aidl b/core/java/android/hardware/soundtrigger/ModelParams.aidl
new file mode 100644
index 000000000000..d90dc811fc32
--- /dev/null
+++ b/core/java/android/hardware/soundtrigger/ModelParams.aidl
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2019 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.hardware.soundtrigger;
+
+/**
+ * Model specific parameters to be used with parameter set and get APIs
+ * {@hide}
+ */
+@Backing(type="int")
+enum ModelParams {
+ /**
+ * Placeholder for invalid model parameter used for returning error or
+ * passing an invalid value.
+ */
+ INVALID = -1,
+ /**
+ * Controls the sensitivity threshold adjustment factor for a given model.
+ * Negative value corresponds to less sensitive model (high threshold) and
+ * a positive value corresponds to a more sensitive model (low threshold).
+ * Default value is 0.
+ */
+ THRESHOLD_FACTOR = 0,
+}
diff --git a/core/java/android/hardware/soundtrigger/SoundTrigger.aidl b/core/java/android/hardware/soundtrigger/SoundTrigger.aidl
index 325a9addc8ff..94c4216227bc 100644
--- a/core/java/android/hardware/soundtrigger/SoundTrigger.aidl
+++ b/core/java/android/hardware/soundtrigger/SoundTrigger.aidl
@@ -24,5 +24,6 @@ parcelable SoundTrigger.GenericRecognitionEvent;
parcelable SoundTrigger.KeyphraseRecognitionExtra;
parcelable SoundTrigger.KeyphraseSoundModel;
parcelable SoundTrigger.GenericSoundModel;
+parcelable SoundTrigger.ModelParamRange;
parcelable SoundTrigger.ModuleProperties;
parcelable SoundTrigger.RecognitionConfig;
diff --git a/core/java/android/hardware/soundtrigger/SoundTrigger.java b/core/java/android/hardware/soundtrigger/SoundTrigger.java
index b1134e120df2..5484df416e79 100644
--- a/core/java/android/hardware/soundtrigger/SoundTrigger.java
+++ b/core/java/android/hardware/soundtrigger/SoundTrigger.java
@@ -22,18 +22,29 @@ import static android.system.OsConstants.ENOSYS;
import static android.system.OsConstants.EPERM;
import static android.system.OsConstants.EPIPE;
+import static java.util.Objects.requireNonNull;
+
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.annotation.UnsupportedAppUsage;
import android.app.ActivityThread;
+import android.content.Context;
import android.media.AudioFormat;
+import android.media.soundtrigger_middleware.ISoundTriggerMiddlewareService;
+import android.media.soundtrigger_middleware.SoundTriggerModuleDescriptor;
import android.os.Handler;
+import android.os.IBinder;
+import android.os.Looper;
import android.os.Parcel;
import android.os.Parcelable;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.util.Log;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.List;
import java.util.UUID;
/**
@@ -44,6 +55,7 @@ import java.util.UUID;
*/
@SystemApi
public class SoundTrigger {
+ private static final String TAG = "SoundTrigger";
private SoundTrigger() {
}
@@ -119,15 +131,15 @@ public class SoundTrigger {
* recognition callback event */
public final boolean returnsTriggerInEvent;
- ModuleProperties(int id, String implementor, String description,
- String uuid, int version, int maxSoundModels, int maxKeyphrases,
+ ModuleProperties(int id, @NonNull String implementor, @NonNull String description,
+ @NonNull String uuid, int version, int maxSoundModels, int maxKeyphrases,
int maxUsers, int recognitionModes, boolean supportsCaptureTransition,
int maxBufferMs, boolean supportsConcurrentCapture,
int powerConsumptionMw, boolean returnsTriggerInEvent) {
this.id = id;
- this.implementor = implementor;
- this.description = description;
- this.uuid = UUID.fromString(uuid);
+ this.implementor = requireNonNull(implementor);
+ this.description = requireNonNull(description);
+ this.uuid = UUID.fromString(requireNonNull(uuid));
this.version = version;
this.maxSoundModels = maxSoundModels;
this.maxKeyphrases = maxKeyphrases;
@@ -231,6 +243,7 @@ public class SoundTrigger {
/** Unique sound model identifier */
@UnsupportedAppUsage
+ @NonNull
public final UUID uuid;
/** Sound model type (e.g. TYPE_KEYPHRASE); */
@@ -238,17 +251,20 @@ public class SoundTrigger {
/** Unique sound model vendor identifier */
@UnsupportedAppUsage
+ @NonNull
public final UUID vendorUuid;
/** Opaque data. For use by vendor implementation and enrollment application */
@UnsupportedAppUsage
+ @NonNull
public final byte[] data;
- public SoundModel(UUID uuid, UUID vendorUuid, int type, byte[] data) {
- this.uuid = uuid;
- this.vendorUuid = vendorUuid;
+ public SoundModel(@NonNull UUID uuid, @Nullable UUID vendorUuid, int type,
+ @Nullable byte[] data) {
+ this.uuid = requireNonNull(uuid);
+ this.vendorUuid = vendorUuid != null ? vendorUuid : new UUID(0, 0);
this.type = type;
- this.data = data;
+ this.data = data != null ? data : new byte[0];
}
@Override
@@ -271,8 +287,6 @@ public class SoundTrigger {
if (!(obj instanceof SoundModel))
return false;
SoundModel other = (SoundModel) obj;
- if (!Arrays.equals(data, other.data))
- return false;
if (type != other.type)
return false;
if (uuid == null) {
@@ -285,6 +299,8 @@ public class SoundTrigger {
return false;
} else if (!vendorUuid.equals(other.vendorUuid))
return false;
+ if (!Arrays.equals(data, other.data))
+ return false;
return true;
}
}
@@ -306,24 +322,28 @@ public class SoundTrigger {
/** Locale of the keyphrase. JAVA Locale string e.g en_US */
@UnsupportedAppUsage
+ @NonNull
public final String locale;
/** Key phrase text */
@UnsupportedAppUsage
+ @NonNull
public final String text;
/** Users this key phrase has been trained for. countains sound trigger specific user IDs
* derived from system user IDs {@link android.os.UserHandle#getIdentifier()}. */
@UnsupportedAppUsage
+ @NonNull
public final int[] users;
@UnsupportedAppUsage
- public Keyphrase(int id, int recognitionModes, String locale, String text, int[] users) {
+ public Keyphrase(int id, int recognitionModes, @NonNull String locale, @NonNull String text,
+ @Nullable int[] users) {
this.id = id;
this.recognitionModes = recognitionModes;
- this.locale = locale;
- this.text = text;
- this.users = users;
+ this.locale = requireNonNull(locale);
+ this.text = requireNonNull(text);
+ this.users = users != null ? users : new int[0];
}
public static final @android.annotation.NonNull Parcelable.Creator<Keyphrase> CREATOR
@@ -427,13 +447,15 @@ public class SoundTrigger {
public static class KeyphraseSoundModel extends SoundModel implements Parcelable {
/** Key phrases in this sound model */
@UnsupportedAppUsage
+ @NonNull
public final Keyphrase[] keyphrases; // keyword phrases in model
@UnsupportedAppUsage
public KeyphraseSoundModel(
- UUID uuid, UUID vendorUuid, byte[] data, Keyphrase[] keyphrases) {
+ @NonNull UUID uuid, @NonNull UUID vendorUuid, @Nullable byte[] data,
+ @Nullable Keyphrase[] keyphrases) {
super(uuid, vendorUuid, TYPE_KEYPHRASE, data);
- this.keyphrases = keyphrases;
+ this.keyphrases = keyphrases != null ? keyphrases : new Keyphrase[0];
}
public static final @android.annotation.NonNull Parcelable.Creator<KeyphraseSoundModel> CREATOR
@@ -528,7 +550,8 @@ public class SoundTrigger {
};
@UnsupportedAppUsage
- public GenericSoundModel(UUID uuid, UUID vendorUuid, byte[] data) {
+ public GenericSoundModel(@NonNull UUID uuid, @NonNull UUID vendorUuid,
+ @Nullable byte[] data) {
super(uuid, vendorUuid, TYPE_GENERIC_SOUND, data);
}
@@ -567,6 +590,65 @@ public class SoundTrigger {
}
}
+ /*****************************************************************************
+ * A ModelParamRange is a representation of supported parameter range for a
+ * given loaded model.
+ ****************************************************************************/
+ public static final class ModelParamRange implements Parcelable {
+
+ /**
+ * start of supported range inclusive
+ */
+ public final int start;
+
+ /**
+ * end of supported range inclusive
+ */
+ public final int end;
+
+ ModelParamRange(int start, int end) {
+ this.start = start;
+ this.end = end;
+ }
+
+ private ModelParamRange(@NonNull Parcel in) {
+ this.start = in.readInt();
+ this.end = in.readInt();
+ }
+
+ @NonNull
+ public static final Creator<ModelParamRange> CREATOR = new Creator<ModelParamRange>() {
+ @Override
+ @NonNull
+ public ModelParamRange createFromParcel(@NonNull Parcel in) {
+ return new ModelParamRange(in);
+ }
+
+ @Override
+ @NonNull
+ public ModelParamRange[] newArray(int size) {
+ return new ModelParamRange[size];
+ }
+ };
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ dest.writeInt(start);
+ dest.writeInt(end);
+ }
+
+ @Override
+ @NonNull
+ public String toString() {
+ return "ModelParamRange [start=" + start + ", end=" + end + "]";
+ }
+ }
+
/**
* Modes for key phrase recognition
*/
@@ -589,6 +671,12 @@ public class SoundTrigger {
* @hide
*/
public static final int RECOGNITION_MODE_USER_AUTHENTICATION = 0x4;
+ /**
+ * Generic (non-speech) recognition.
+ *
+ * @hide
+ */
+ public static final int RECOGNITION_MODE_GENERIC = 0x8;
/**
* Status codes for {@link RecognitionEvent}
@@ -680,6 +768,7 @@ public class SoundTrigger {
*
* @hide
*/
+ @NonNull
public final AudioFormat captureFormat;
/**
* Opaque data for use by system applications who know about voice engine internals,
@@ -688,13 +777,14 @@ public class SoundTrigger {
* @hide
*/
@UnsupportedAppUsage
+ @NonNull
public final byte[] data;
/** @hide */
@UnsupportedAppUsage
public RecognitionEvent(int status, int soundModelHandle, boolean captureAvailable,
int captureSession, int captureDelayMs, int capturePreambleMs,
- boolean triggerInData, AudioFormat captureFormat, byte[] data) {
+ boolean triggerInData, @NonNull AudioFormat captureFormat, @Nullable byte[] data) {
this.status = status;
this.soundModelHandle = soundModelHandle;
this.captureAvailable = captureAvailable;
@@ -702,8 +792,8 @@ public class SoundTrigger {
this.captureDelayMs = captureDelayMs;
this.capturePreambleMs = capturePreambleMs;
this.triggerInData = triggerInData;
- this.captureFormat = captureFormat;
- this.data = data;
+ this.captureFormat = requireNonNull(captureFormat);
+ this.data = data != null ? data : new byte[0];
}
/**
@@ -906,19 +996,21 @@ public class SoundTrigger {
/** List of all keyphrases in the sound model for which recognition should be performed with
* options for each keyphrase. */
@UnsupportedAppUsage
+ @NonNull
public final KeyphraseRecognitionExtra keyphrases[];
/** Opaque data for use by system applications who know about voice engine internals,
* typically during enrollment. */
@UnsupportedAppUsage
+ @NonNull
public final byte[] data;
@UnsupportedAppUsage
public RecognitionConfig(boolean captureRequested, boolean allowMultipleTriggers,
- KeyphraseRecognitionExtra[] keyphrases, byte[] data) {
+ @Nullable KeyphraseRecognitionExtra[] keyphrases, @Nullable byte[] data) {
this.captureRequested = captureRequested;
this.allowMultipleTriggers = allowMultipleTriggers;
- this.keyphrases = keyphrases;
- this.data = data;
+ this.keyphrases = keyphrases != null ? keyphrases : new KeyphraseRecognitionExtra[0];
+ this.data = data != null ? data : new byte[0];
}
public static final @android.annotation.NonNull Parcelable.Creator<RecognitionConfig> CREATOR
@@ -1067,15 +1159,17 @@ public class SoundTrigger {
/** Confidence levels for all users recognized (KeyphraseRecognitionEvent) or to
* be recognized (RecognitionConfig) */
@UnsupportedAppUsage
+ @NonNull
public final ConfidenceLevel[] confidenceLevels;
@UnsupportedAppUsage
public KeyphraseRecognitionExtra(int id, int recognitionModes, int coarseConfidenceLevel,
- ConfidenceLevel[] confidenceLevels) {
+ @Nullable ConfidenceLevel[] confidenceLevels) {
this.id = id;
this.recognitionModes = recognitionModes;
this.coarseConfidenceLevel = coarseConfidenceLevel;
- this.confidenceLevels = confidenceLevels;
+ this.confidenceLevels =
+ confidenceLevels != null ? confidenceLevels : new ConfidenceLevel[0];
}
public static final @android.annotation.NonNull Parcelable.Creator<KeyphraseRecognitionExtra> CREATOR
@@ -1158,16 +1252,18 @@ public class SoundTrigger {
public static class KeyphraseRecognitionEvent extends RecognitionEvent implements Parcelable {
/** Indicates if the key phrase is present in the buffered audio available for capture */
@UnsupportedAppUsage
+ @NonNull
public final KeyphraseRecognitionExtra[] keyphraseExtras;
@UnsupportedAppUsage
public KeyphraseRecognitionEvent(int status, int soundModelHandle, boolean captureAvailable,
int captureSession, int captureDelayMs, int capturePreambleMs,
- boolean triggerInData, AudioFormat captureFormat, byte[] data,
- KeyphraseRecognitionExtra[] keyphraseExtras) {
+ boolean triggerInData, @NonNull AudioFormat captureFormat, @Nullable byte[] data,
+ @Nullable KeyphraseRecognitionExtra[] keyphraseExtras) {
super(status, soundModelHandle, captureAvailable, captureSession, captureDelayMs,
capturePreambleMs, triggerInData, captureFormat, data);
- this.keyphraseExtras = keyphraseExtras;
+ this.keyphraseExtras =
+ keyphraseExtras != null ? keyphraseExtras : new KeyphraseRecognitionExtra[0];
}
public static final @android.annotation.NonNull Parcelable.Creator<KeyphraseRecognitionEvent> CREATOR
@@ -1284,8 +1380,8 @@ public class SoundTrigger {
@UnsupportedAppUsage
public GenericRecognitionEvent(int status, int soundModelHandle,
boolean captureAvailable, int captureSession, int captureDelayMs,
- int capturePreambleMs, boolean triggerInData, AudioFormat captureFormat,
- byte[] data) {
+ int capturePreambleMs, boolean triggerInData, @NonNull AudioFormat captureFormat,
+ @Nullable byte[] data) {
super(status, soundModelHandle, captureAvailable, captureSession,
captureDelayMs, capturePreambleMs, triggerInData, captureFormat,
data);
@@ -1349,13 +1445,14 @@ public class SoundTrigger {
/** The updated sound model handle */
public final int soundModelHandle;
/** New sound model data */
+ @NonNull
public final byte[] data;
@UnsupportedAppUsage
- SoundModelEvent(int status, int soundModelHandle, byte[] data) {
+ SoundModelEvent(int status, int soundModelHandle, @Nullable byte[] data) {
this.status = status;
this.soundModelHandle = soundModelHandle;
- this.data = data;
+ this.data = data != null ? data : new byte[0];
}
public static final @android.annotation.NonNull Parcelable.Creator<SoundModelEvent> CREATOR
@@ -1439,8 +1536,9 @@ public class SoundTrigger {
* @hide
*/
public static final int SERVICE_STATE_DISABLED = 1;
-
- /**
+ private static Object mServiceLock = new Object();
+ private static ISoundTriggerMiddlewareService mService;
+ /**
* @return returns current package name.
*/
static String getCurrentOpPackageName() {
@@ -1464,25 +1562,22 @@ public class SoundTrigger {
* @hide
*/
@UnsupportedAppUsage
- public static int listModules(ArrayList<ModuleProperties> modules) {
- return listModules(getCurrentOpPackageName(), modules);
+ public static int listModules(@NonNull ArrayList<ModuleProperties> modules) {
+ try {
+ SoundTriggerModuleDescriptor[] descs = getService().listModules();
+ modules.clear();
+ modules.ensureCapacity(descs.length);
+ for (SoundTriggerModuleDescriptor desc : descs) {
+ modules.add(ConversionUtil.aidl2apiModuleDescriptor(desc));
+ }
+ return STATUS_OK;
+ } catch (RemoteException e) {
+ Log.e(TAG, "Exception caught", e);
+ return STATUS_DEAD_OBJECT;
+ }
}
/**
- * Returns a list of descriptors for all hardware modules loaded.
- * @param opPackageName
- * @param modules A ModuleProperties array where the list will be returned.
- * @return - {@link #STATUS_OK} in case of success
- * - {@link #STATUS_ERROR} in case of unspecified error
- * - {@link #STATUS_PERMISSION_DENIED} if the caller does not have system permission
- * - {@link #STATUS_NO_INIT} if the native service cannot be reached
- * - {@link #STATUS_BAD_VALUE} if modules is null
- * - {@link #STATUS_DEAD_OBJECT} if the binder transaction to the native service fails
- */
- private static native int listModules(String opPackageName,
- ArrayList<ModuleProperties> modules);
-
- /**
* Get an interface on a hardware module to control sound models and recognition on
* this module.
* @param moduleId Sound module system identifier {@link ModuleProperties#id}. mandatory.
@@ -1494,14 +1589,40 @@ public class SoundTrigger {
* @hide
*/
@UnsupportedAppUsage
- public static SoundTriggerModule attachModule(int moduleId,
- StatusListener listener,
- Handler handler) {
- if (listener == null) {
+ public static @NonNull SoundTriggerModule attachModule(int moduleId,
+ @NonNull StatusListener listener,
+ @Nullable Handler handler) {
+ Looper looper = handler != null ? handler.getLooper() : Looper.getMainLooper();
+ try {
+ return new SoundTriggerModule(getService(), moduleId, listener, looper);
+ } catch (RemoteException e) {
+ Log.e(TAG, "", e);
return null;
}
- SoundTriggerModule module = new SoundTriggerModule(moduleId, listener, handler);
- return module;
+ }
+
+ private static ISoundTriggerMiddlewareService getService() {
+ synchronized (mServiceLock) {
+ while (true) {
+ IBinder binder = null;
+ try {
+ binder =
+ ServiceManager.getServiceOrThrow(
+ Context.SOUND_TRIGGER_MIDDLEWARE_SERVICE);
+ binder.linkToDeath(() -> {
+ synchronized (mServiceLock) {
+ mService = null;
+ }
+ }, 0);
+ mService = ISoundTriggerMiddlewareService.Stub.asInterface(binder);
+ break;
+ } catch (Exception e) {
+ Log.e(TAG, "Failed to bind to soundtrigger service", e);
+ }
+ }
+ return mService;
+ }
+
}
/**
diff --git a/core/java/android/hardware/soundtrigger/SoundTriggerModule.java b/core/java/android/hardware/soundtrigger/SoundTriggerModule.java
index 911354862ff4..7cf560019239 100644
--- a/core/java/android/hardware/soundtrigger/SoundTriggerModule.java
+++ b/core/java/android/hardware/soundtrigger/SoundTriggerModule.java
@@ -16,12 +16,23 @@
package android.hardware.soundtrigger;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.annotation.UnsupportedAppUsage;
+import android.media.soundtrigger_middleware.ISoundTriggerCallback;
+import android.media.soundtrigger_middleware.ISoundTriggerMiddlewareService;
+import android.media.soundtrigger_middleware.ISoundTriggerModule;
+import android.media.soundtrigger_middleware.ModelParameterRange;
+import android.media.soundtrigger_middleware.PhraseRecognitionEvent;
+import android.media.soundtrigger_middleware.PhraseSoundModel;
+import android.media.soundtrigger_middleware.RecognitionEvent;
+import android.media.soundtrigger_middleware.SoundModel;
import android.os.Handler;
+import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
-
-import java.lang.ref.WeakReference;
+import android.os.RemoteException;
+import android.util.Log;
/**
* The SoundTriggerModule provides APIs to control sound models and sound detection
@@ -30,39 +41,47 @@ import java.lang.ref.WeakReference;
* @hide
*/
public class SoundTriggerModule {
- @UnsupportedAppUsage
- private long mNativeContext;
+ private static final String TAG = "SoundTriggerModule";
- @UnsupportedAppUsage
- private int mId;
- private NativeEventHandlerDelegate mEventHandlerDelegate;
-
- // to be kept in sync with core/jni/android_hardware_SoundTrigger.cpp
private static final int EVENT_RECOGNITION = 1;
private static final int EVENT_SERVICE_DIED = 2;
- private static final int EVENT_SOUNDMODEL = 3;
- private static final int EVENT_SERVICE_STATE_CHANGE = 4;
+ private static final int EVENT_SERVICE_STATE_CHANGE = 3;
+ @UnsupportedAppUsage
+ private int mId;
+ private EventHandlerDelegate mEventHandlerDelegate;
+ private ISoundTriggerModule mService;
- SoundTriggerModule(int moduleId, SoundTrigger.StatusListener listener, Handler handler) {
+ SoundTriggerModule(@NonNull ISoundTriggerMiddlewareService service,
+ int moduleId, @NonNull SoundTrigger.StatusListener listener, @NonNull Looper looper)
+ throws RemoteException {
mId = moduleId;
- mEventHandlerDelegate = new NativeEventHandlerDelegate(listener, handler);
- native_setup(SoundTrigger.getCurrentOpPackageName(),
- new WeakReference<SoundTriggerModule>(this));
+ mEventHandlerDelegate = new EventHandlerDelegate(listener, looper);
+ mService = service.attach(moduleId, mEventHandlerDelegate);
+ mService.asBinder().linkToDeath(mEventHandlerDelegate, 0);
}
- private native void native_setup(String opPackageName, Object moduleThis);
@Override
protected void finalize() {
- native_finalize();
+ detach();
}
- private native void native_finalize();
/**
* Detach from this module. The {@link SoundTrigger.StatusListener} callback will not be called
* anymore and associated resources will be released.
- * */
+ * All models must have been unloaded prior to detaching.
+ */
@UnsupportedAppUsage
- public native void detach();
+ public synchronized void detach() {
+ try {
+ if (mService != null) {
+ mService.asBinder().unlinkToDeath(mEventHandlerDelegate, 0);
+ mService.detach();
+ mService = null;
+ }
+ } catch (Exception e) {
+ handleException(e);
+ }
+ }
/**
* Load a {@link SoundTrigger.SoundModel} to the hardware. A sound model must be loaded in
@@ -80,7 +99,26 @@ public class SoundTriggerModule {
* - {@link SoundTrigger#STATUS_INVALID_OPERATION} if the call is out of sequence
*/
@UnsupportedAppUsage
- public native int loadSoundModel(SoundTrigger.SoundModel model, int[] soundModelHandle);
+ public synchronized int loadSoundModel(@NonNull SoundTrigger.SoundModel model,
+ @NonNull int[] soundModelHandle) {
+ try {
+ if (model instanceof SoundTrigger.GenericSoundModel) {
+ SoundModel aidlModel = ConversionUtil.api2aidlGenericSoundModel(
+ (SoundTrigger.GenericSoundModel) model);
+ soundModelHandle[0] = mService.loadModel(aidlModel);
+ return SoundTrigger.STATUS_OK;
+ }
+ if (model instanceof SoundTrigger.KeyphraseSoundModel) {
+ PhraseSoundModel aidlModel = ConversionUtil.api2aidlPhraseSoundModel(
+ (SoundTrigger.KeyphraseSoundModel) model);
+ soundModelHandle[0] = mService.loadPhraseModel(aidlModel);
+ return SoundTrigger.STATUS_OK;
+ }
+ return SoundTrigger.STATUS_BAD_VALUE;
+ } catch (Exception e) {
+ return handleException(e);
+ }
+ }
/**
* Unload a {@link SoundTrigger.SoundModel} and abort any pendiong recognition
@@ -95,7 +133,14 @@ public class SoundTriggerModule {
* service fails
*/
@UnsupportedAppUsage
- public native int unloadSoundModel(int soundModelHandle);
+ public synchronized int unloadSoundModel(int soundModelHandle) {
+ try {
+ mService.unloadModel(soundModelHandle);
+ return SoundTrigger.STATUS_OK;
+ } catch (Exception e) {
+ return handleException(e);
+ }
+ }
/**
* Start listening to all key phrases in a {@link SoundTrigger.SoundModel}.
@@ -115,7 +160,16 @@ public class SoundTriggerModule {
* - {@link SoundTrigger#STATUS_INVALID_OPERATION} if the call is out of sequence
*/
@UnsupportedAppUsage
- public native int startRecognition(int soundModelHandle, SoundTrigger.RecognitionConfig config);
+ public synchronized int startRecognition(int soundModelHandle,
+ SoundTrigger.RecognitionConfig config) {
+ try {
+ mService.startRecognition(soundModelHandle,
+ ConversionUtil.api2aidlRecognitionConfig(config));
+ return SoundTrigger.STATUS_OK;
+ } catch (Exception e) {
+ return handleException(e);
+ }
+ }
/**
* Stop listening to all key phrases in a {@link SoundTrigger.SoundModel}
@@ -131,12 +185,20 @@ public class SoundTriggerModule {
* - {@link SoundTrigger#STATUS_INVALID_OPERATION} if the call is out of sequence
*/
@UnsupportedAppUsage
- public native int stopRecognition(int soundModelHandle);
+ public synchronized int stopRecognition(int soundModelHandle) {
+ try {
+ mService.stopRecognition(soundModelHandle);
+ return SoundTrigger.STATUS_OK;
+ } catch (Exception e) {
+ return handleException(e);
+ }
+ }
/**
* Get the current state of a {@link SoundTrigger.SoundModel}.
- * The state will be returned asynchronously as a {@link SoundTrigger#RecognitionEvent}
- * in the callback registered in the {@link SoundTrigger.startRecognition} method.
+ * The state will be returned asynchronously as a {@link SoundTrigger.RecognitionEvent}
+ * in the callback registered in the
+ * {@link SoundTrigger#attachModule(int, SoundTrigger.StatusListener, Handler)} method.
* @param soundModelHandle The sound model handle indicating which model's state to return
* @return - {@link SoundTrigger#STATUS_OK} in case of success
* - {@link SoundTrigger#STATUS_ERROR} in case of unspecified error
@@ -148,81 +210,170 @@ public class SoundTriggerModule {
* service fails
* - {@link SoundTrigger#STATUS_INVALID_OPERATION} if the call is out of sequence
*/
- public native int getModelState(int soundModelHandle);
+ public synchronized int getModelState(int soundModelHandle) {
+ try {
+ mService.forceRecognitionEvent(soundModelHandle);
+ return SoundTrigger.STATUS_OK;
+ } catch (Exception e) {
+ return handleException(e);
+ }
+ }
- private class NativeEventHandlerDelegate {
+ /**
+ * Set a model specific {@link ModelParams} with the given value. This
+ * parameter will keep its value for the duration the model is loaded regardless of starting
+ * and
+ * stopping recognition. Once the model is unloaded, the value will be lost.
+ * {@link SoundTriggerModule#queryParameter(int, int)} should be checked first before calling
+ * this method.
+ *
+ * @param soundModelHandle handle of model to apply parameter
+ * @param modelParam {@link ModelParams}
+ * @param value Value to set
+ * @return - {@link SoundTrigger#STATUS_OK} in case of success
+ * - {@link SoundTrigger#STATUS_NO_INIT} if the native service cannot be reached
+ * - {@link SoundTrigger#STATUS_BAD_VALUE} invalid input parameter
+ * - {@link SoundTrigger#STATUS_INVALID_OPERATION} if the call is out of sequence or
+ * if API is not supported by HAL
+ */
+ public synchronized int setParameter(int soundModelHandle, @ModelParams int modelParam,
+ int value) {
+ try {
+ mService.setModelParameter(soundModelHandle,
+ ConversionUtil.api2aidlModelParameter(modelParam), value);
+ return SoundTrigger.STATUS_OK;
+ } catch (Exception e) {
+ return handleException(e);
+ }
+ }
+
+ /**
+ * Get a model specific {@link ModelParams}. This parameter will keep its value
+ * for the duration the model is loaded regardless of starting and stopping recognition.
+ * Once the model is unloaded, the value will be lost. If the value is not set, a default
+ * value is returned. See {@link ModelParams} for parameter default values.
+ * {@link SoundTriggerModule#queryParameter(int, int)} should be checked first before
+ * calling this method. Otherwise, an exception can be thrown.
+ *
+ * @param soundModelHandle handle of model to get parameter
+ * @param modelParam {@link ModelParams}
+ * @return value of parameter
+ * @throws UnsupportedOperationException if hal or model do not support this API.
+ * {@link SoundTriggerModule#queryParameter(int, int)}
+ * should
+ * be checked first.
+ * @throws IllegalArgumentException if invalid model handle or parameter is passed.
+ * {@link SoundTriggerModule#queryParameter(int, int)}
+ * should be checked first.
+ */
+ public synchronized int getParameter(int soundModelHandle, @ModelParams int modelParam)
+ throws UnsupportedOperationException, IllegalArgumentException {
+ try {
+ return mService.getModelParameter(soundModelHandle,
+ ConversionUtil.api2aidlModelParameter(modelParam));
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Determine if parameter control is supported for the given model handle.
+ * This method should be checked prior to calling {@link SoundTriggerModule#setParameter} or
+ * {@link SoundTriggerModule#getParameter}.
+ *
+ * @param soundModelHandle handle of model to get parameter
+ * @param modelParam {@link ModelParams}
+ * @return supported range of parameter, null if not supported
+ */
+ @Nullable
+ public synchronized SoundTrigger.ModelParamRange queryParameter(int soundModelHandle,
+ @ModelParams int modelParam) {
+ try {
+ return ConversionUtil.aidl2apiModelParameterRange(mService.queryModelParameterSupport(
+ soundModelHandle,
+ ConversionUtil.api2aidlModelParameter(modelParam)));
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ private int handleException(Exception e) {
+ Log.e(TAG, "", e);
+ if (e instanceof NullPointerException) {
+ return SoundTrigger.STATUS_NO_INIT;
+ }
+ if (e instanceof RemoteException) {
+ return SoundTrigger.STATUS_DEAD_OBJECT;
+ }
+ if (e instanceof IllegalArgumentException) {
+ return SoundTrigger.STATUS_BAD_VALUE;
+ }
+ if (e instanceof IllegalStateException) {
+ return SoundTrigger.STATUS_INVALID_OPERATION;
+ }
+ return SoundTrigger.STATUS_ERROR;
+ }
+
+ private class EventHandlerDelegate extends ISoundTriggerCallback.Stub implements
+ IBinder.DeathRecipient {
private final Handler mHandler;
- NativeEventHandlerDelegate(final SoundTrigger.StatusListener listener,
- Handler handler) {
- // find the looper for our new event handler
- Looper looper;
- if (handler != null) {
- looper = handler.getLooper();
- } else {
- looper = Looper.getMainLooper();
- }
+ EventHandlerDelegate(@NonNull final SoundTrigger.StatusListener listener,
+ @NonNull Looper looper) {
// construct the event handler with this looper
- if (looper != null) {
- // implement the event handler delegate
- mHandler = new Handler(looper) {
- @Override
- public void handleMessage(Message msg) {
- switch(msg.what) {
+ // implement the event handler delegate
+ mHandler = new Handler(looper) {
+ @Override
+ public void handleMessage(Message msg) {
+ switch (msg.what) {
case EVENT_RECOGNITION:
- if (listener != null) {
- listener.onRecognition(
- (SoundTrigger.RecognitionEvent)msg.obj);
- }
- break;
- case EVENT_SOUNDMODEL:
- if (listener != null) {
- listener.onSoundModelUpdate(
- (SoundTrigger.SoundModelEvent)msg.obj);
- }
+ listener.onRecognition(
+ (SoundTrigger.RecognitionEvent) msg.obj);
break;
case EVENT_SERVICE_STATE_CHANGE:
- if (listener != null) {
- listener.onServiceStateChange(msg.arg1);
- }
+ listener.onServiceStateChange(msg.arg1);
break;
case EVENT_SERVICE_DIED:
- if (listener != null) {
- listener.onServiceDied();
- }
+ listener.onServiceDied();
break;
default:
+ Log.e(TAG, "Unknown message: " + msg.toString());
break;
- }
}
- };
- } else {
- mHandler = null;
- }
+ }
+ };
}
- Handler handler() {
- return mHandler;
+ @Override
+ public synchronized void onRecognition(int handle, RecognitionEvent event)
+ throws RemoteException {
+ Message m = mHandler.obtainMessage(EVENT_RECOGNITION,
+ ConversionUtil.aidl2apiRecognitionEvent(handle, event));
+ mHandler.sendMessage(m);
}
- }
- @SuppressWarnings("unused")
- @UnsupportedAppUsage
- private static void postEventFromNative(Object module_ref,
- int what, int arg1, int arg2, Object obj) {
- SoundTriggerModule module = (SoundTriggerModule)((WeakReference)module_ref).get();
- if (module == null) {
- return;
- }
-
- NativeEventHandlerDelegate delegate = module.mEventHandlerDelegate;
- if (delegate != null) {
- Handler handler = delegate.handler();
- if (handler != null) {
- Message m = handler.obtainMessage(what, arg1, arg2, obj);
- handler.sendMessage(m);
- }
+ @Override
+ public synchronized void onPhraseRecognition(int handle, PhraseRecognitionEvent event)
+ throws RemoteException {
+ Message m = mHandler.obtainMessage(EVENT_RECOGNITION,
+ ConversionUtil.aidl2apiPhraseRecognitionEvent(handle, event));
+ mHandler.sendMessage(m);
+ }
+
+ @Override
+ public synchronized void onRecognitionAvailabilityChange(boolean available)
+ throws RemoteException {
+ Message m = mHandler.obtainMessage(EVENT_SERVICE_STATE_CHANGE,
+ available ? SoundTrigger.SERVICE_STATE_ENABLED
+ : SoundTrigger.SERVICE_STATE_DISABLED);
+ mHandler.sendMessage(m);
+ }
+
+ @Override
+ public synchronized void binderDied() {
+ Message m = mHandler.obtainMessage(EVENT_SERVICE_DIED);
+ mHandler.sendMessage(m);
}
}
}
diff --git a/core/java/android/inputmethodservice/IInputMethodWrapper.java b/core/java/android/inputmethodservice/IInputMethodWrapper.java
index a47f601033cf..62f0196693ea 100644
--- a/core/java/android/inputmethodservice/IInputMethodWrapper.java
+++ b/core/java/android/inputmethodservice/IInputMethodWrapper.java
@@ -19,6 +19,7 @@ package android.inputmethodservice;
import android.annotation.BinderThread;
import android.annotation.MainThread;
import android.annotation.UnsupportedAppUsage;
+import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Binder;
@@ -28,6 +29,7 @@ import android.os.RemoteException;
import android.os.ResultReceiver;
import android.util.Log;
import android.view.InputChannel;
+import android.view.autofill.AutofillId;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputBinding;
import android.view.inputmethod.InputConnection;
@@ -39,6 +41,7 @@ import android.view.inputmethod.InputMethodSubtype;
import com.android.internal.inputmethod.IInputMethodPrivilegedOperations;
import com.android.internal.os.HandlerCaller;
import com.android.internal.os.SomeArgs;
+import com.android.internal.view.IInlineSuggestionsRequestCallback;
import com.android.internal.view.IInputContext;
import com.android.internal.view.IInputMethod;
import com.android.internal.view.IInputMethodSession;
@@ -72,6 +75,7 @@ class IInputMethodWrapper extends IInputMethod.Stub
private static final int DO_SHOW_SOFT_INPUT = 60;
private static final int DO_HIDE_SOFT_INPUT = 70;
private static final int DO_CHANGE_INPUTMETHOD_SUBTYPE = 80;
+ private static final int DO_CREATE_INLINE_SUGGESTIONS_REQUEST = 90;
final WeakReference<AbstractInputMethodService> mTarget;
final Context mContext;
@@ -225,6 +229,11 @@ class IInputMethodWrapper extends IInputMethod.Stub
case DO_CHANGE_INPUTMETHOD_SUBTYPE:
inputMethod.changeInputMethodSubtype((InputMethodSubtype)msg.obj);
return;
+ case DO_CREATE_INLINE_SUGGESTIONS_REQUEST:
+ SomeArgs args = (SomeArgs) msg.obj;
+ inputMethod.onCreateInlineSuggestionsRequest((ComponentName) args.arg1,
+ (AutofillId) args.arg2, (IInlineSuggestionsRequestCallback) args.arg3);
+ return;
}
Log.w(TAG, "Unhandled message code: " + msg.what);
}
@@ -267,6 +276,15 @@ class IInputMethodWrapper extends IInputMethod.Stub
@BinderThread
@Override
+ public void onCreateInlineSuggestionsRequest(ComponentName componentName, AutofillId autofillId,
+ IInlineSuggestionsRequestCallback cb) {
+ mCaller.executeOrSendMessage(
+ mCaller.obtainMessageOOO(DO_CREATE_INLINE_SUGGESTIONS_REQUEST, componentName,
+ autofillId, cb));
+ }
+
+ @BinderThread
+ @Override
public void bindInput(InputBinding binding) {
if (mIsUnbindIssued != null) {
Log.e(TAG, "bindInput must be paired with unbindInput.");
diff --git a/core/java/android/inputmethodservice/InputMethodService.java b/core/java/android/inputmethodservice/InputMethodService.java
index 43842c5c3403..7da7dc120dcb 100644
--- a/core/java/android/inputmethodservice/InputMethodService.java
+++ b/core/java/android/inputmethodservice/InputMethodService.java
@@ -21,6 +21,9 @@ import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static android.view.ViewRootImpl.NEW_INSETS_MODE_NONE;
import static android.view.WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
+import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_ONLY_DRAW_BOTTOM_BAR_BACKGROUND;
+
+import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage;
import static java.lang.annotation.RetentionPolicy.SOURCE;
@@ -34,6 +37,7 @@ import android.annotation.Nullable;
import android.annotation.UnsupportedAppUsage;
import android.app.ActivityManager;
import android.app.Dialog;
+import android.content.ComponentName;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
@@ -46,6 +50,8 @@ import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
+import android.os.Looper;
+import android.os.RemoteException;
import android.os.ResultReceiver;
import android.os.SystemClock;
import android.provider.Settings;
@@ -66,13 +72,17 @@ import android.view.ViewGroup;
import android.view.ViewRootImpl;
import android.view.ViewTreeObserver;
import android.view.Window;
+import android.view.WindowInsets;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
+import android.view.autofill.AutofillId;
import android.view.inputmethod.CompletionInfo;
import android.view.inputmethod.CursorAnchorInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
+import android.view.inputmethod.InlineSuggestionsRequest;
+import android.view.inputmethod.InlineSuggestionsResponse;
import android.view.inputmethod.InputBinding;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputContentInfo;
@@ -89,11 +99,14 @@ import com.android.internal.inputmethod.IInputContentUriToken;
import com.android.internal.inputmethod.IInputMethodPrivilegedOperations;
import com.android.internal.inputmethod.InputMethodPrivilegedOperations;
import com.android.internal.inputmethod.InputMethodPrivilegedOperationsRegistry;
+import com.android.internal.view.IInlineSuggestionsRequestCallback;
+import com.android.internal.view.IInlineSuggestionsResponseCallback;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
+import java.lang.ref.WeakReference;
import java.util.Collections;
/**
@@ -434,6 +447,14 @@ public class InputMethodService extends AbstractInputMethodService {
final Insets mTmpInsets = new Insets();
final int[] mTmpLocation = new int[2];
+ @Nullable
+ private InlineSuggestionsRequestInfo mInlineSuggestionsRequestInfo = null;
+
+ @Nullable
+ private InlineSuggestionsResponseCallbackImpl mInlineSuggestionsResponseCallback = null;
+
+ private final Handler mHandler = new Handler(Looper.getMainLooper(), null, true);
+
final ViewTreeObserver.OnComputeInternalInsetsListener mInsetsComputer = info -> {
onComputeInsets(mTmpInsets);
if (isExtractViewShown()) {
@@ -493,6 +514,18 @@ public class InputMethodService extends AbstractInputMethodService {
/**
* {@inheritDoc}
+ * @hide
+ */
+ @MainThread
+ @Override
+ public void onCreateInlineSuggestionsRequest(ComponentName componentName,
+ AutofillId autofillId, IInlineSuggestionsRequestCallback cb) {
+ Log.d(TAG, "InputMethodService received onCreateInlineSuggestionsRequest()");
+ handleOnCreateInlineSuggestionsRequest(componentName, autofillId, cb);
+ }
+
+ /**
+ * {@inheritDoc}
*/
@MainThread
@Override
@@ -668,6 +701,103 @@ public class InputMethodService extends AbstractInputMethodService {
}
}
+ // TODO(b/137800469): Add detailed docs explaining the inline suggestions process.
+ /**
+ * Returns an {@link InlineSuggestionsRequest} to be sent to Autofill.
+ *
+ * <p>Should be implemented by subclasses.</p>
+ */
+ public @Nullable InlineSuggestionsRequest onCreateInlineSuggestionsRequest() {
+ return null;
+ }
+
+ /**
+ * Called when Autofill responds back with {@link InlineSuggestionsResponse} containing
+ * inline suggestions.
+ *
+ * <p>Should be implemented by subclasses.</p>
+ *
+ * @param response {@link InlineSuggestionsResponse} passed back by Autofill.
+ * @return Whether the IME will use and render the inline suggestions.
+ */
+ public boolean onInlineSuggestionsResponse(@NonNull InlineSuggestionsResponse response) {
+ return false;
+ }
+
+ /**
+ * Returns whether inline suggestions are enabled on this service.
+ *
+ * TODO(b/137800469): check XML for value.
+ */
+ private boolean isInlineSuggestionsEnabled() {
+ return true;
+ }
+
+ /**
+ * Sends an {@link InlineSuggestionsRequest} obtained from
+ * {@link #onCreateInlineSuggestionsRequest()} to the current Autofill Session through
+ * {@link IInlineSuggestionsRequestCallback#onInlineSuggestionsRequest}.
+ */
+ private void makeInlineSuggestionsRequest() {
+ if (mInlineSuggestionsRequestInfo == null) {
+ Log.w(TAG, "makeInlineSuggestionsRequest() called with null requestInfo cache");
+ return;
+ }
+
+ final IInlineSuggestionsRequestCallback requestCallback =
+ mInlineSuggestionsRequestInfo.mCallback;
+ try {
+ final InlineSuggestionsRequest request = onCreateInlineSuggestionsRequest();
+ if (request == null) {
+ Log.w(TAG, "onCreateInlineSuggestionsRequest() returned null request");
+ requestCallback.onInlineSuggestionsUnsupported();
+ } else {
+ if (mInlineSuggestionsResponseCallback == null) {
+ mInlineSuggestionsResponseCallback =
+ new InlineSuggestionsResponseCallbackImpl(this,
+ mInlineSuggestionsRequestInfo.mComponentName,
+ mInlineSuggestionsRequestInfo.mFocusedId);
+ }
+ requestCallback.onInlineSuggestionsRequest(request,
+ mInlineSuggestionsResponseCallback);
+ }
+ } catch (RemoteException e) {
+ Log.w(TAG, "makeInlinedSuggestionsRequest() remote exception:" + e);
+ }
+ }
+
+ private void handleOnCreateInlineSuggestionsRequest(@NonNull ComponentName componentName,
+ @NonNull AutofillId autofillId, @NonNull IInlineSuggestionsRequestCallback callback) {
+ mInlineSuggestionsRequestInfo = new InlineSuggestionsRequestInfo(componentName, autofillId,
+ callback);
+
+ if (!isInlineSuggestionsEnabled()) {
+ try {
+ callback.onInlineSuggestionsUnsupported();
+ } catch (RemoteException e) {
+ Log.w(TAG, "handleMakeInlineSuggestionsRequest() RemoteException:" + e);
+ }
+ return;
+ }
+
+ if (!mInputStarted) {
+ Log.w(TAG, "onStartInput() not called yet");
+ return;
+ }
+
+ makeInlineSuggestionsRequest();
+ }
+
+ private void handleOnInlineSuggestionsResponse(@NonNull ComponentName componentName,
+ @NonNull AutofillId autofillId, @NonNull InlineSuggestionsResponse response) {
+ if (!mInlineSuggestionsRequestInfo.validate(componentName)) {
+ Log.d(TAG, "Response component=" + componentName + " differs from request component="
+ + mInlineSuggestionsRequestInfo.mComponentName + ", ignoring response");
+ return;
+ }
+ onInlineSuggestionsResponse(response);
+ }
+
private void notifyImeHidden() {
setImeWindowStatus(IME_ACTIVE | IME_INVISIBLE, mBackDisposition);
onPreRenderedWindowVisibilityChanged(false /* setVisible */);
@@ -686,6 +816,63 @@ public class InputMethodService extends AbstractInputMethodService {
}
/**
+ * Internal implementation of {@link IInlineSuggestionsResponseCallback}.
+ */
+ private static final class InlineSuggestionsResponseCallbackImpl
+ extends IInlineSuggestionsResponseCallback.Stub {
+ private final WeakReference<InputMethodService> mInputMethodService;
+
+ private final ComponentName mRequestComponentName;
+ private final AutofillId mRequestAutofillId;
+
+ private InlineSuggestionsResponseCallbackImpl(InputMethodService inputMethodService,
+ ComponentName componentName, AutofillId autofillId) {
+ mInputMethodService = new WeakReference<>(inputMethodService);
+ mRequestComponentName = componentName;
+ mRequestAutofillId = autofillId;
+ }
+
+ @Override
+ public void onInlineSuggestionsResponse(InlineSuggestionsResponse response)
+ throws RemoteException {
+ final InputMethodService service = mInputMethodService.get();
+ if (service != null) {
+ service.mHandler.sendMessage(obtainMessage(
+ InputMethodService::handleOnInlineSuggestionsResponse, service,
+ mRequestComponentName, mRequestAutofillId, response));
+ }
+ }
+ }
+
+ /**
+ * Information about incoming requests from Autofill Frameworks for inline suggestions.
+ */
+ private static final class InlineSuggestionsRequestInfo {
+ final ComponentName mComponentName;
+ final AutofillId mFocusedId;
+ final IInlineSuggestionsRequestCallback mCallback;
+
+ InlineSuggestionsRequestInfo(ComponentName componentName, AutofillId focusedId,
+ IInlineSuggestionsRequestCallback callback) {
+ this.mComponentName = componentName;
+ this.mFocusedId = focusedId;
+ this.mCallback = callback;
+ }
+
+ /**
+ * Returns whether the cached {@link ComponentName} matches the passed in activity.
+ */
+ public boolean validate(ComponentName componentName) {
+ final boolean result = componentName.equals(mComponentName);
+ if (!result) {
+ Log.d(TAG, "Cached request info ComponentName=" + mComponentName
+ + " differs from received ComponentName=" + componentName);
+ }
+ return result;
+ }
+ }
+
+ /**
* Concrete implementation of
* {@link AbstractInputMethodService.AbstractInputMethodSessionImpl} that provides
* all of the standard behavior for an input method session.
@@ -1019,6 +1206,16 @@ public class InputMethodService extends AbstractInputMethodService {
Context.LAYOUT_INFLATER_SERVICE);
mWindow = new SoftInputWindow(this, "InputMethod", mTheme, null, null, mDispatcherState,
WindowManager.LayoutParams.TYPE_INPUT_METHOD, Gravity.BOTTOM, false);
+ mWindow.getWindow().setFitWindowInsetsTypes(WindowInsets.Type.systemBars());
+ mWindow.getWindow().addPrivateFlags(PRIVATE_FLAG_ONLY_DRAW_BOTTOM_BAR_BACKGROUND);
+ mWindow.getWindow().getDecorView().setOnApplyWindowInsetsListener(
+ (v, insets) -> v.onApplyWindowInsets(
+ new WindowInsets.Builder(insets).setSystemWindowInsets(
+ android.graphics.Insets.of(
+ insets.getSystemWindowInsetLeft(),
+ insets.getSystemWindowInsetTop(),
+ insets.getSystemWindowInsetRight(),
+ insets.getStableInsetBottom())).build()));
// For ColorView in DecorView to work, FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS needs to be set
// by default (but IME developers can opt this out later if they want a new behavior).
mWindow.getWindow().setFlags(
diff --git a/core/java/android/net/InterfaceConfiguration.java b/core/java/android/net/InterfaceConfiguration.java
index c9a999cfdf17..1ae44e169851 100644
--- a/core/java/android/net/InterfaceConfiguration.java
+++ b/core/java/android/net/InterfaceConfiguration.java
@@ -20,8 +20,6 @@ import android.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
-import com.google.android.collect.Sets;
-
import java.util.HashSet;
/**
@@ -32,7 +30,7 @@ import java.util.HashSet;
public class InterfaceConfiguration implements Parcelable {
private String mHwAddr;
private LinkAddress mAddr;
- private HashSet<String> mFlags = Sets.newHashSet();
+ private HashSet<String> mFlags = new HashSet<>();
// Must be kept in sync with constant in INetd.aidl
private static final String FLAG_UP = "up";
diff --git a/core/java/android/net/InvalidPacketException.java b/core/java/android/net/InvalidPacketException.java
new file mode 100644
index 000000000000..909998d4562c
--- /dev/null
+++ b/core/java/android/net/InvalidPacketException.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2019 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.net;
+
+import android.annotation.IntDef;
+import android.annotation.SystemApi;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Thrown when a packet is invalid.
+ * @hide
+ */
+@SystemApi
+public class InvalidPacketException extends Exception {
+ public final int error;
+
+ // Must match SocketKeepalive#ERROR_INVALID_IP_ADDRESS.
+ /** Invalid IP address. */
+ public static final int ERROR_INVALID_IP_ADDRESS = -21;
+
+ // Must match SocketKeepalive#ERROR_INVALID_PORT.
+ /** Invalid port number. */
+ public static final int ERROR_INVALID_PORT = -22;
+
+ // Must match SocketKeepalive#ERROR_INVALID_LENGTH.
+ /** Invalid packet length. */
+ public static final int ERROR_INVALID_LENGTH = -23;
+
+ /** @hide */
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(prefix = { "ERROR_" }, value = {
+ ERROR_INVALID_IP_ADDRESS,
+ ERROR_INVALID_PORT,
+ ERROR_INVALID_LENGTH
+ })
+ public @interface ErrorCode {}
+
+ /**
+ * This packet is invalid.
+ * See the error code for details.
+ */
+ public InvalidPacketException(@ErrorCode final int error) {
+ this.error = error;
+ }
+}
diff --git a/core/java/android/net/KeepalivePacketData.java b/core/java/android/net/KeepalivePacketData.java
index 9b8b7322cd23..2b8b7e69dec9 100644
--- a/core/java/android/net/KeepalivePacketData.java
+++ b/core/java/android/net/KeepalivePacketData.java
@@ -16,13 +16,13 @@
package android.net;
-import static android.net.SocketKeepalive.ERROR_INVALID_IP_ADDRESS;
-import static android.net.SocketKeepalive.ERROR_INVALID_PORT;
+import static android.net.InvalidPacketException.ERROR_INVALID_IP_ADDRESS;
+import static android.net.InvalidPacketException.ERROR_INVALID_PORT;
-import android.net.SocketKeepalive.InvalidPacketException;
+import android.annotation.NonNull;
+import android.annotation.SystemApi;
import android.net.util.IpUtils;
import android.os.Parcel;
-import android.os.Parcelable;
import android.util.Log;
import java.net.InetAddress;
@@ -33,13 +33,16 @@ import java.net.InetAddress;
*
* @hide
*/
-public class KeepalivePacketData implements Parcelable {
+@SystemApi
+public class KeepalivePacketData {
private static final String TAG = "KeepalivePacketData";
/** Source IP address */
+ @NonNull
public final InetAddress srcAddress;
/** Destination IP address */
+ @NonNull
public final InetAddress dstAddress;
/** Source port */
@@ -51,13 +54,14 @@ public class KeepalivePacketData implements Parcelable {
/** Packet data. A raw byte string of packet data, not including the link-layer header. */
private final byte[] mPacket;
- protected static final int IPV4_HEADER_LENGTH = 20;
- protected static final int UDP_HEADER_LENGTH = 8;
-
// This should only be constructed via static factory methods, such as
- // nattKeepalivePacket
- protected KeepalivePacketData(InetAddress srcAddress, int srcPort,
- InetAddress dstAddress, int dstPort, byte[] data) throws InvalidPacketException {
+ // nattKeepalivePacket.
+ /**
+ * A holding class for data necessary to build a keepalive packet.
+ */
+ protected KeepalivePacketData(@NonNull InetAddress srcAddress, int srcPort,
+ @NonNull InetAddress dstAddress, int dstPort,
+ @NonNull byte[] data) throws InvalidPacketException {
this.srcAddress = srcAddress;
this.dstAddress = dstAddress;
this.srcPort = srcPort;
@@ -78,16 +82,12 @@ public class KeepalivePacketData implements Parcelable {
}
}
+ @NonNull
public byte[] getPacket() {
return mPacket.clone();
}
- /* Parcelable Implementation */
- public int describeContents() {
- return 0;
- }
-
- /** Write to parcel */
+ /** @hide */
public void writeToParcel(Parcel out, int flags) {
out.writeString(srcAddress.getHostAddress());
out.writeString(dstAddress.getHostAddress());
@@ -96,6 +96,7 @@ public class KeepalivePacketData implements Parcelable {
out.writeByteArray(mPacket);
}
+ /** @hide */
protected KeepalivePacketData(Parcel in) {
srcAddress = NetworkUtils.numericToInetAddress(in.readString());
dstAddress = NetworkUtils.numericToInetAddress(in.readString());
@@ -103,17 +104,4 @@ public class KeepalivePacketData implements Parcelable {
dstPort = in.readInt();
mPacket = in.createByteArray();
}
-
- /** Parcelable Creator */
- public static final @android.annotation.NonNull Parcelable.Creator<KeepalivePacketData> CREATOR =
- new Parcelable.Creator<KeepalivePacketData>() {
- public KeepalivePacketData createFromParcel(Parcel in) {
- return new KeepalivePacketData(in);
- }
-
- public KeepalivePacketData[] newArray(int size) {
- return new KeepalivePacketData[size];
- }
- };
-
}
diff --git a/core/java/android/net/LinkProperties.java b/core/java/android/net/LinkProperties.java
index 8e1834113486..ed509cb3da34 100644
--- a/core/java/android/net/LinkProperties.java
+++ b/core/java/android/net/LinkProperties.java
@@ -74,6 +74,8 @@ public final class LinkProperties implements Parcelable {
private static final int MIN_MTU_V6 = 1280;
private static final int MAX_MTU = 10000;
+ private static final int INET6_ADDR_LENGTH = 16;
+
// Stores the properties of links that are "stacked" above this link.
// Indexed by interface name to allow modification and to prevent duplicates being added.
private Hashtable<String, LinkProperties> mStackedLinks = new Hashtable<>();
@@ -227,7 +229,7 @@ public final class LinkProperties implements Parcelable {
/**
* @hide
*/
- @UnsupportedAppUsage
+ @SystemApi
public @NonNull List<String> getAllInterfaceNames() {
List<String> interfaceNames = new ArrayList<>(mStackedLinks.size() + 1);
if (mIfaceName != null) interfaceNames.add(mIfaceName);
@@ -247,7 +249,7 @@ public final class LinkProperties implements Parcelable {
* @return An unmodifiable {@link List} of {@link InetAddress} for this link.
* @hide
*/
- @UnsupportedAppUsage
+ @SystemApi
public @NonNull List<InetAddress> getAddresses() {
final List<InetAddress> addresses = new ArrayList<>();
for (LinkAddress linkAddress : mLinkAddresses) {
@@ -342,8 +344,8 @@ public final class LinkProperties implements Parcelable {
* Returns all the addresses on this link and all the links stacked above it.
* @hide
*/
- @UnsupportedAppUsage
- public List<LinkAddress> getAllLinkAddresses() {
+ @SystemApi
+ public @NonNull List<LinkAddress> getAllLinkAddresses() {
List<LinkAddress> addresses = new ArrayList<>(mLinkAddresses);
for (LinkProperties stacked: mStackedLinks.values()) {
addresses.addAll(stacked.getAllLinkAddresses());
@@ -542,6 +544,7 @@ public final class LinkProperties implements Parcelable {
* @return true if the PCSCF server was added, false otherwise.
* @hide
*/
+ @SystemApi
public boolean addPcscfServer(@NonNull InetAddress pcscfServer) {
if (pcscfServer != null && !mPcscfs.contains(pcscfServer)) {
mPcscfs.add(pcscfServer);
@@ -729,7 +732,7 @@ public final class LinkProperties implements Parcelable {
* Returns all the routes on this link and all the links stacked above it.
* @hide
*/
- @UnsupportedAppUsage
+ @SystemApi
public @NonNull List<RouteInfo> getAllRoutes() {
List<RouteInfo> routes = new ArrayList<>(mRoutes);
for (LinkProperties stacked: mStackedLinks.values()) {
@@ -1025,7 +1028,7 @@ public final class LinkProperties implements Parcelable {
* @return {@code true} if there is an IPv4 default route, {@code false} otherwise.
* @hide
*/
- @UnsupportedAppUsage
+ @SystemApi
public boolean hasIpv4DefaultRoute() {
for (RouteInfo r : mRoutes) {
if (r.isIPv4Default()) {
@@ -1082,7 +1085,7 @@ public final class LinkProperties implements Parcelable {
* @return {@code true} if there is an IPv4 DNS server, {@code false} otherwise.
* @hide
*/
- @UnsupportedAppUsage
+ @SystemApi
public boolean hasIpv4DnsServer() {
for (InetAddress ia : mDnses) {
if (ia instanceof Inet4Address) {
@@ -1110,7 +1113,7 @@ public final class LinkProperties implements Parcelable {
* @return {@code true} if there is an IPv6 DNS server, {@code false} otherwise.
* @hide
*/
- @UnsupportedAppUsage
+ @SystemApi
public boolean hasIpv6DnsServer() {
for (InetAddress ia : mDnses) {
if (ia instanceof Inet6Address) {
@@ -1626,20 +1629,11 @@ public final class LinkProperties implements Parcelable {
dest.writeParcelable(linkAddress, flags);
}
- dest.writeInt(mDnses.size());
- for (InetAddress d : mDnses) {
- dest.writeByteArray(d.getAddress());
- }
- dest.writeInt(mValidatedPrivateDnses.size());
- for (InetAddress d : mValidatedPrivateDnses) {
- dest.writeByteArray(d.getAddress());
- }
+ writeAddresses(dest, mDnses);
+ writeAddresses(dest, mValidatedPrivateDnses);
dest.writeBoolean(mUsePrivateDns);
dest.writeString(mPrivateDnsServerName);
- dest.writeInt(mPcscfs.size());
- for (InetAddress d : mPcscfs) {
- dest.writeByteArray(d.getAddress());
- }
+ writeAddresses(dest, mPcscfs);
dest.writeString(mDomains);
dest.writeInt(mMtu);
dest.writeString(mTcpBufferSizes);
@@ -1662,6 +1656,35 @@ public final class LinkProperties implements Parcelable {
dest.writeBoolean(mWakeOnLanSupported);
}
+ private static void writeAddresses(@NonNull Parcel dest, @NonNull List<InetAddress> list) {
+ dest.writeInt(list.size());
+ for (InetAddress d : list) {
+ writeAddress(dest, d);
+ }
+ }
+
+ private static void writeAddress(@NonNull Parcel dest, @NonNull InetAddress addr) {
+ dest.writeByteArray(addr.getAddress());
+ if (addr instanceof Inet6Address) {
+ final Inet6Address v6Addr = (Inet6Address) addr;
+ final boolean hasScopeId = v6Addr.getScopeId() != 0;
+ dest.writeBoolean(hasScopeId);
+ if (hasScopeId) dest.writeInt(v6Addr.getScopeId());
+ }
+ }
+
+ @NonNull
+ private static InetAddress readAddress(@NonNull Parcel p) throws UnknownHostException {
+ final byte[] addr = p.createByteArray();
+ if (addr.length == INET6_ADDR_LENGTH) {
+ final boolean hasScopeId = p.readBoolean();
+ final int scopeId = hasScopeId ? p.readInt() : 0;
+ return Inet6Address.getByAddress(null /* host */, addr, scopeId);
+ }
+
+ return InetAddress.getByAddress(addr);
+ }
+
/**
* Implement the Parcelable interface.
*/
@@ -1681,14 +1704,13 @@ public final class LinkProperties implements Parcelable {
addressCount = in.readInt();
for (int i = 0; i < addressCount; i++) {
try {
- netProp.addDnsServer(InetAddress.getByAddress(in.createByteArray()));
+ netProp.addDnsServer(readAddress(in));
} catch (UnknownHostException e) { }
}
addressCount = in.readInt();
for (int i = 0; i < addressCount; i++) {
try {
- netProp.addValidatedPrivateDnsServer(
- InetAddress.getByAddress(in.createByteArray()));
+ netProp.addValidatedPrivateDnsServer(readAddress(in));
} catch (UnknownHostException e) { }
}
netProp.setUsePrivateDns(in.readBoolean());
@@ -1696,7 +1718,7 @@ public final class LinkProperties implements Parcelable {
addressCount = in.readInt();
for (int i = 0; i < addressCount; i++) {
try {
- netProp.addPcscfServer(InetAddress.getByAddress(in.createByteArray()));
+ netProp.addPcscfServer(readAddress(in));
} catch (UnknownHostException e) { }
}
netProp.setDomains(in.readString());
diff --git a/core/java/android/net/NattKeepalivePacketData.java b/core/java/android/net/NattKeepalivePacketData.java
index a77c244d6b40..3fb52f12a88d 100644
--- a/core/java/android/net/NattKeepalivePacketData.java
+++ b/core/java/android/net/NattKeepalivePacketData.java
@@ -19,7 +19,6 @@ package android.net;
import static android.net.SocketKeepalive.ERROR_INVALID_IP_ADDRESS;
import static android.net.SocketKeepalive.ERROR_INVALID_PORT;
-import android.net.SocketKeepalive.InvalidPacketException;
import android.net.util.IpUtils;
import android.os.Parcel;
import android.os.Parcelable;
@@ -32,6 +31,9 @@ import java.nio.ByteOrder;
/** @hide */
public final class NattKeepalivePacketData extends KeepalivePacketData implements Parcelable {
+ private static final int IPV4_HEADER_LENGTH = 20;
+ private static final int UDP_HEADER_LENGTH = 8;
+
// This should only be constructed via static factory methods, such as
// nattKeepalivePacket
private NattKeepalivePacketData(InetAddress srcAddress, int srcPort,
diff --git a/core/java/android/net/NetworkRequest.java b/core/java/android/net/NetworkRequest.java
index adc497a6d67d..299212735410 100644
--- a/core/java/android/net/NetworkRequest.java
+++ b/core/java/android/net/NetworkRequest.java
@@ -17,6 +17,7 @@
package android.net;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.UnsupportedAppUsage;
@@ -461,6 +462,14 @@ public class NetworkRequest implements Parcelable {
return networkCapabilities.hasTransport(transportType);
}
+ /**
+ * @see Builder#setNetworkSpecifier(NetworkSpecifier)
+ */
+ @Nullable
+ public NetworkSpecifier getNetworkSpecifier() {
+ return networkCapabilities.getNetworkSpecifier();
+ }
+
public String toString() {
return "NetworkRequest [ " + type + " id=" + requestId +
(legacyType != ConnectivityManager.TYPE_NONE ? ", legacyType=" + legacyType : "") +
diff --git a/core/java/android/net/SocketKeepalive.java b/core/java/android/net/SocketKeepalive.java
index ec73866a647d..fb224fbe1318 100644
--- a/core/java/android/net/SocketKeepalive.java
+++ b/core/java/android/net/SocketKeepalive.java
@@ -147,17 +147,6 @@ public abstract class SocketKeepalive implements AutoCloseable {
}
}
- /**
- * This packet is invalid.
- * See the error code for details.
- * @hide
- */
- public static class InvalidPacketException extends ErrorCodeException {
- public InvalidPacketException(final int error) {
- super(error);
- }
- }
-
@NonNull final IConnectivityManager mService;
@NonNull final Network mNetwork;
@NonNull final ParcelFileDescriptor mPfd;
diff --git a/core/java/android/net/nsd/NsdServiceInfo.java b/core/java/android/net/nsd/NsdServiceInfo.java
index 459b1409807b..0946499f164f 100644
--- a/core/java/android/net/nsd/NsdServiceInfo.java
+++ b/core/java/android/net/nsd/NsdServiceInfo.java
@@ -17,13 +17,13 @@
package android.net.nsd;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
-import android.os.Parcelable;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
+import android.os.Parcelable;
import android.text.TextUtils;
+import android.util.ArrayMap;
import android.util.Base64;
import android.util.Log;
-import android.util.ArrayMap;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
diff --git a/core/java/android/nfc/ErrorCodes.java b/core/java/android/nfc/ErrorCodes.java
index 98e31ad53be3..d2c81cd27d90 100644
--- a/core/java/android/nfc/ErrorCodes.java
+++ b/core/java/android/nfc/ErrorCodes.java
@@ -16,7 +16,7 @@
package android.nfc;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/**
* This class defines all the error codes that can be returned by the service
diff --git a/core/java/android/nfc/NdefRecord.java b/core/java/android/nfc/NdefRecord.java
index 5044a860b50c..fe316c45fb55 100644
--- a/core/java/android/nfc/NdefRecord.java
+++ b/core/java/android/nfc/NdefRecord.java
@@ -16,7 +16,7 @@
package android.nfc;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Intent;
import android.net.Uri;
import android.os.Parcel;
diff --git a/core/java/android/nfc/NfcActivityManager.java b/core/java/android/nfc/NfcActivityManager.java
index abfa133a2f39..935374d15d9b 100644
--- a/core/java/android/nfc/NfcActivityManager.java
+++ b/core/java/android/nfc/NfcActivityManager.java
@@ -16,9 +16,9 @@
package android.nfc;
-import android.annotation.UnsupportedAppUsage;
import android.app.Activity;
import android.app.Application;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentProvider;
import android.content.Intent;
import android.net.Uri;
@@ -26,7 +26,6 @@ import android.nfc.NfcAdapter.ReaderCallback;
import android.os.Binder;
import android.os.Bundle;
import android.os.RemoteException;
-import android.os.UserHandle;
import android.util.Log;
import java.util.ArrayList;
diff --git a/core/java/android/nfc/NfcAdapter.java b/core/java/android/nfc/NfcAdapter.java
index 875d17a436a9..5715c9ab43a5 100644
--- a/core/java/android/nfc/NfcAdapter.java
+++ b/core/java/android/nfc/NfcAdapter.java
@@ -21,11 +21,11 @@ import android.annotation.RequiresPermission;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.Activity;
import android.app.ActivityThread;
import android.app.OnActivityPausedListener;
import android.app.PendingIntent;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.IPackageManager;
diff --git a/core/java/android/nfc/NfcManager.java b/core/java/android/nfc/NfcManager.java
index 030066eb80a4..644e3122774b 100644
--- a/core/java/android/nfc/NfcManager.java
+++ b/core/java/android/nfc/NfcManager.java
@@ -17,7 +17,7 @@
package android.nfc;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.Build;
diff --git a/core/java/android/nfc/Tag.java b/core/java/android/nfc/Tag.java
index 5a4c465f76d8..8bb2df0bba58 100644
--- a/core/java/android/nfc/Tag.java
+++ b/core/java/android/nfc/Tag.java
@@ -16,7 +16,7 @@
package android.nfc;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.nfc.tech.IsoDep;
import android.nfc.tech.MifareClassic;
diff --git a/core/java/android/nfc/cardemulation/AidGroup.java b/core/java/android/nfc/cardemulation/AidGroup.java
index 77b5552cd27b..c4f5e0b2ddf2 100644
--- a/core/java/android/nfc/cardemulation/AidGroup.java
+++ b/core/java/android/nfc/cardemulation/AidGroup.java
@@ -16,18 +16,18 @@
package android.nfc.cardemulation;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
+import android.compat.annotation.UnsupportedAppUsage;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;
-import android.annotation.UnsupportedAppUsage;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.util.Log;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
/**
* The AidGroup class represents a group of Application Identifiers (AIDs).
diff --git a/core/java/android/nfc/cardemulation/ApduServiceInfo.java b/core/java/android/nfc/cardemulation/ApduServiceInfo.java
index d9000e43be0b..8da9db17252f 100644
--- a/core/java/android/nfc/cardemulation/ApduServiceInfo.java
+++ b/core/java/android/nfc/cardemulation/ApduServiceInfo.java
@@ -16,7 +16,7 @@
package android.nfc.cardemulation;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
diff --git a/core/java/android/os/AsyncResult.java b/core/java/android/os/AsyncResult.java
index 58a27015f2df..e80528b10aaf 100644
--- a/core/java/android/os/AsyncResult.java
+++ b/core/java/android/os/AsyncResult.java
@@ -16,8 +16,7 @@
package android.os;
-import android.annotation.UnsupportedAppUsage;
-import android.os.Message;
+import android.compat.annotation.UnsupportedAppUsage;
/** @hide */
public class AsyncResult
diff --git a/core/java/android/os/AsyncTask.java b/core/java/android/os/AsyncTask.java
index b37e176ddb6e..e1dabd345027 100644
--- a/core/java/android/os/AsyncTask.java
+++ b/core/java/android/os/AsyncTask.java
@@ -18,8 +18,8 @@ package android.os;
import android.annotation.MainThread;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.WorkerThread;
+import android.compat.annotation.UnsupportedAppUsage;
import java.util.ArrayDeque;
import java.util.concurrent.Callable;
diff --git a/core/java/android/os/BaseBundle.java b/core/java/android/os/BaseBundle.java
index 9d9c683ee794..6453af802623 100644
--- a/core/java/android/os/BaseBundle.java
+++ b/core/java/android/os/BaseBundle.java
@@ -18,7 +18,7 @@ package android.os;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.util.ArrayMap;
import android.util.Log;
import android.util.MathUtils;
diff --git a/core/java/android/os/BatteryManager.java b/core/java/android/os/BatteryManager.java
index 5ced86c9e79a..12ec0a0c21d5 100644
--- a/core/java/android/os/BatteryManager.java
+++ b/core/java/android/os/BatteryManager.java
@@ -21,7 +21,7 @@ import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.Intent;
import android.hardware.health.V1_0.Constants;
diff --git a/core/java/android/os/BatteryStats.java b/core/java/android/os/BatteryStats.java
index 9fed26916899..fbe6a5052f3d 100644
--- a/core/java/android/os/BatteryStats.java
+++ b/core/java/android/os/BatteryStats.java
@@ -17,13 +17,17 @@
package android.os;
import static android.app.ActivityManager.PROCESS_STATE_BOUND_TOP;
+import static android.os.BatteryStatsManager.NUM_WIFI_STATES;
+import static android.os.BatteryStatsManager.NUM_WIFI_SUPPL_STATES;
import android.annotation.IntDef;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityManager;
import android.app.job.JobParameters;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.ApplicationInfo;
+import android.os.BatteryStatsManager.WifiState;
+import android.os.BatteryStatsManager.WifiSupplState;
import android.server.ServerProtoEnums;
import android.service.batterystats.BatteryStatsServiceDumpHistoryProto;
import android.service.batterystats.BatteryStatsServiceDumpProto;
@@ -2422,7 +2426,7 @@ public abstract class BatteryStats implements Parcelable {
public static final int DATA_CONNECTION_OUT_OF_SERVICE = 0;
public static final int DATA_CONNECTION_EMERGENCY_SERVICE =
- TelephonyManager.MAX_NETWORK_TYPE + 1;
+ TelephonyManager.getAllNetworkTypes().length + 1;
public static final int DATA_CONNECTION_OTHER = DATA_CONNECTION_EMERGENCY_SERVICE + 1;
@@ -2458,41 +2462,6 @@ public abstract class BatteryStats implements Parcelable {
*/
public abstract Timer getPhoneDataConnectionTimer(int dataType);
- public static final int WIFI_SUPPL_STATE_INVALID = 0;
- public static final int WIFI_SUPPL_STATE_DISCONNECTED = 1;
- public static final int WIFI_SUPPL_STATE_INTERFACE_DISABLED = 2;
- public static final int WIFI_SUPPL_STATE_INACTIVE = 3;
- public static final int WIFI_SUPPL_STATE_SCANNING = 4;
- public static final int WIFI_SUPPL_STATE_AUTHENTICATING = 5;
- public static final int WIFI_SUPPL_STATE_ASSOCIATING = 6;
- public static final int WIFI_SUPPL_STATE_ASSOCIATED = 7;
- public static final int WIFI_SUPPL_STATE_FOUR_WAY_HANDSHAKE = 8;
- public static final int WIFI_SUPPL_STATE_GROUP_HANDSHAKE = 9;
- public static final int WIFI_SUPPL_STATE_COMPLETED = 10;
- public static final int WIFI_SUPPL_STATE_DORMANT = 11;
- public static final int WIFI_SUPPL_STATE_UNINITIALIZED = 12;
-
- public static final int NUM_WIFI_SUPPL_STATES = WIFI_SUPPL_STATE_UNINITIALIZED+1;
-
- /** @hide */
- @IntDef(flag = true, prefix = { "WIFI_SUPPL_STATE_" }, value = {
- WIFI_SUPPL_STATE_INVALID,
- WIFI_SUPPL_STATE_DISCONNECTED,
- WIFI_SUPPL_STATE_INTERFACE_DISABLED,
- WIFI_SUPPL_STATE_INACTIVE,
- WIFI_SUPPL_STATE_SCANNING,
- WIFI_SUPPL_STATE_AUTHENTICATING,
- WIFI_SUPPL_STATE_ASSOCIATING,
- WIFI_SUPPL_STATE_ASSOCIATED,
- WIFI_SUPPL_STATE_FOUR_WAY_HANDSHAKE,
- WIFI_SUPPL_STATE_GROUP_HANDSHAKE,
- WIFI_SUPPL_STATE_COMPLETED,
- WIFI_SUPPL_STATE_DORMANT,
- WIFI_SUPPL_STATE_UNINITIALIZED,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface WifiSupplState {}
-
static final String[] WIFI_SUPPL_STATE_NAMES = {
"invalid", "disconn", "disabled", "inactive", "scanning",
"authenticating", "associating", "associated", "4-way-handshake",
@@ -2635,31 +2604,6 @@ public abstract class BatteryStats implements Parcelable {
@UnsupportedAppUsage
public abstract long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which);
- public static final int WIFI_STATE_OFF = 0;
- public static final int WIFI_STATE_OFF_SCANNING = 1;
- public static final int WIFI_STATE_ON_NO_NETWORKS = 2;
- public static final int WIFI_STATE_ON_DISCONNECTED = 3;
- public static final int WIFI_STATE_ON_CONNECTED_STA = 4;
- public static final int WIFI_STATE_ON_CONNECTED_P2P = 5;
- public static final int WIFI_STATE_ON_CONNECTED_STA_P2P = 6;
- public static final int WIFI_STATE_SOFT_AP = 7;
-
- public static final int NUM_WIFI_STATES = WIFI_STATE_SOFT_AP + 1;
-
- /** @hide */
- @IntDef(flag = true, prefix = { "WIFI_STATE_" }, value = {
- WIFI_STATE_OFF,
- WIFI_STATE_OFF_SCANNING,
- WIFI_STATE_ON_NO_NETWORKS,
- WIFI_STATE_ON_DISCONNECTED,
- WIFI_STATE_ON_CONNECTED_STA,
- WIFI_STATE_ON_CONNECTED_P2P,
- WIFI_STATE_ON_CONNECTED_STA_P2P,
- WIFI_STATE_SOFT_AP
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface WifiState {}
-
static final String[] WIFI_STATE_NAMES = {
"off", "scanning", "no_net", "disconn",
"sta", "p2p", "sta_p2p", "soft_ap"
diff --git a/core/java/android/os/BatteryStatsManager.java b/core/java/android/os/BatteryStatsManager.java
index e5650aea0522..0545666ca743 100644
--- a/core/java/android/os/BatteryStatsManager.java
+++ b/core/java/android/os/BatteryStatsManager.java
@@ -16,6 +16,7 @@
package android.os;
+import android.annotation.IntDef;
import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -28,6 +29,9 @@ import android.os.connectivity.WifiBatteryStats;
import com.android.internal.app.IBatteryStats;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
/**
* This class provides an API surface for internal system components to report events that are
* needed for battery usage/estimation and battery blaming for apps.
@@ -39,6 +43,116 @@ import com.android.internal.app.IBatteryStats;
@SystemApi
@SystemService(Context.BATTERY_STATS_SERVICE)
public class BatteryStatsManager {
+ /**
+ * Wifi states.
+ *
+ * @see #noteWifiState(int, String)
+ */
+ /**
+ * Wifi fully off.
+ */
+ public static final int WIFI_STATE_OFF = 0;
+ /**
+ * Wifi connectivity off, but scanning enabled.
+ */
+ public static final int WIFI_STATE_OFF_SCANNING = 1;
+ /**
+ * Wifi on, but no saved infrastructure networks to connect to.
+ */
+ public static final int WIFI_STATE_ON_NO_NETWORKS = 2;
+ /**
+ * Wifi on, but not connected to any infrastructure networks.
+ */
+ public static final int WIFI_STATE_ON_DISCONNECTED = 3;
+ /**
+ * Wifi on and connected to a infrastructure network.
+ */
+ public static final int WIFI_STATE_ON_CONNECTED_STA = 4;
+ /**
+ * Wifi on and connected to a P2P device, but no infrastructure connection to a network.
+ */
+ public static final int WIFI_STATE_ON_CONNECTED_P2P = 5;
+ /**
+ * Wifi on and connected to both a P2P device and infrastructure connection to a network.
+ */
+ public static final int WIFI_STATE_ON_CONNECTED_STA_P2P = 6;
+ /**
+ * SoftAp/Hotspot turned on.
+ */
+ public static final int WIFI_STATE_SOFT_AP = 7;
+
+ /** @hide */
+ public static final int NUM_WIFI_STATES = WIFI_STATE_SOFT_AP + 1;
+
+ /** @hide */
+ @IntDef(flag = true, prefix = { "WIFI_STATE_" }, value = {
+ WIFI_STATE_OFF,
+ WIFI_STATE_OFF_SCANNING,
+ WIFI_STATE_ON_NO_NETWORKS,
+ WIFI_STATE_ON_DISCONNECTED,
+ WIFI_STATE_ON_CONNECTED_STA,
+ WIFI_STATE_ON_CONNECTED_P2P,
+ WIFI_STATE_ON_CONNECTED_STA_P2P,
+ WIFI_STATE_SOFT_AP
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface WifiState {}
+
+ /**
+ * Wifi supplicant daemon states.
+ *
+ * @see android.net.wifi.SupplicantState for detailed description of states.
+ * @see #noteWifiSupplicantStateChanged(int)
+ */
+ /** @see android.net.wifi.SupplicantState#INVALID */
+ public static final int WIFI_SUPPL_STATE_INVALID = 0;
+ /** @see android.net.wifi.SupplicantState#DISCONNECTED*/
+ public static final int WIFI_SUPPL_STATE_DISCONNECTED = 1;
+ /** @see android.net.wifi.SupplicantState#INTERFACE_DISABLED */
+ public static final int WIFI_SUPPL_STATE_INTERFACE_DISABLED = 2;
+ /** @see android.net.wifi.SupplicantState#INACTIVE*/
+ public static final int WIFI_SUPPL_STATE_INACTIVE = 3;
+ /** @see android.net.wifi.SupplicantState#SCANNING*/
+ public static final int WIFI_SUPPL_STATE_SCANNING = 4;
+ /** @see android.net.wifi.SupplicantState#AUTHENTICATING */
+ public static final int WIFI_SUPPL_STATE_AUTHENTICATING = 5;
+ /** @see android.net.wifi.SupplicantState#ASSOCIATING */
+ public static final int WIFI_SUPPL_STATE_ASSOCIATING = 6;
+ /** @see android.net.wifi.SupplicantState#ASSOCIATED */
+ public static final int WIFI_SUPPL_STATE_ASSOCIATED = 7;
+ /** @see android.net.wifi.SupplicantState#FOUR_WAY_HANDSHAKE */
+ public static final int WIFI_SUPPL_STATE_FOUR_WAY_HANDSHAKE = 8;
+ /** @see android.net.wifi.SupplicantState#GROUP_HANDSHAKE */
+ public static final int WIFI_SUPPL_STATE_GROUP_HANDSHAKE = 9;
+ /** @see android.net.wifi.SupplicantState#COMPLETED */
+ public static final int WIFI_SUPPL_STATE_COMPLETED = 10;
+ /** @see android.net.wifi.SupplicantState#DORMANT */
+ public static final int WIFI_SUPPL_STATE_DORMANT = 11;
+ /** @see android.net.wifi.SupplicantState#UNINITIALIZED */
+ public static final int WIFI_SUPPL_STATE_UNINITIALIZED = 12;
+
+ /** @hide */
+ public static final int NUM_WIFI_SUPPL_STATES = WIFI_SUPPL_STATE_UNINITIALIZED + 1;
+
+ /** @hide */
+ @IntDef(flag = true, prefix = { "WIFI_SUPPL_STATE_" }, value = {
+ WIFI_SUPPL_STATE_INVALID,
+ WIFI_SUPPL_STATE_DISCONNECTED,
+ WIFI_SUPPL_STATE_INTERFACE_DISABLED,
+ WIFI_SUPPL_STATE_INACTIVE,
+ WIFI_SUPPL_STATE_SCANNING,
+ WIFI_SUPPL_STATE_AUTHENTICATING,
+ WIFI_SUPPL_STATE_ASSOCIATING,
+ WIFI_SUPPL_STATE_ASSOCIATED,
+ WIFI_SUPPL_STATE_FOUR_WAY_HANDSHAKE,
+ WIFI_SUPPL_STATE_GROUP_HANDSHAKE,
+ WIFI_SUPPL_STATE_COMPLETED,
+ WIFI_SUPPL_STATE_DORMANT,
+ WIFI_SUPPL_STATE_UNINITIALIZED,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface WifiSupplState {}
+
private final IBatteryStats mBatteryStats;
/** @hide */
@@ -91,7 +205,7 @@ public class BatteryStatsManager {
* @param accessPoint SSID of the network if wifi is connected to STA, else null.
*/
@RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS)
- public void noteWifiState(@BatteryStats.WifiState int newWifiState,
+ public void noteWifiState(@WifiState int newWifiState,
@Nullable String accessPoint) {
try {
mBatteryStats.noteWifiState(newWifiState, accessPoint);
@@ -224,7 +338,7 @@ public class BatteryStatsManager {
* authentication failure.
*/
@RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS)
- public void noteWifiSupplicantStateChanged(@BatteryStats.WifiSupplState int newSupplState,
+ public void noteWifiSupplicantStateChanged(@WifiSupplState int newSupplState,
boolean failedAuth) {
try {
mBatteryStats.noteWifiSupplicantStateChanged(newSupplState, failedAuth);
diff --git a/core/java/android/os/Binder.java b/core/java/android/os/Binder.java
index a9c5a9118a31..a90ab8564100 100644
--- a/core/java/android/os/Binder.java
+++ b/core/java/android/os/Binder.java
@@ -19,8 +19,8 @@ package android.os;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.AppOpsManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.util.ExceptionUtils;
import android.util.Log;
import android.util.Slog;
diff --git a/core/java/android/os/BinderProxy.java b/core/java/android/os/BinderProxy.java
index ee95fcee1f7a..b0c2546e0300 100644
--- a/core/java/android/os/BinderProxy.java
+++ b/core/java/android/os/BinderProxy.java
@@ -479,8 +479,14 @@ public final class BinderProxy implements IBinder {
// For now, avoid spamming the log by disabling after we've logged
// about this interface at least once
mWarnOnBlocking = false;
- Log.w(Binder.TAG, "Outgoing transactions from this process must be FLAG_ONEWAY",
- new Throwable());
+ if (Build.IS_USERDEBUG) {
+ // Log this as a WTF on userdebug builds.
+ Log.wtf(Binder.TAG, "Outgoing transactions from this process must be FLAG_ONEWAY",
+ new Throwable());
+ } else {
+ Log.w(Binder.TAG, "Outgoing transactions from this process must be FLAG_ONEWAY",
+ new Throwable());
+ }
}
final boolean tracingEnabled = Binder.isTracingEnabled();
diff --git a/core/java/android/os/Broadcaster.java b/core/java/android/os/Broadcaster.java
index 6ac7f1a9c970..d1a953f23f7f 100644
--- a/core/java/android/os/Broadcaster.java
+++ b/core/java/android/os/Broadcaster.java
@@ -16,7 +16,7 @@
package android.os;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/** @hide */
public class Broadcaster
diff --git a/core/java/android/os/Build.java b/core/java/android/os/Build.java
index 6eaea99d5c49..a29173469ffb 100755
--- a/core/java/android/os/Build.java
+++ b/core/java/android/os/Build.java
@@ -22,9 +22,9 @@ import android.annotation.RequiresPermission;
import android.annotation.SuppressAutoDoc;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityThread;
import android.app.Application;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.sysprop.TelephonyProperties;
import android.text.TextUtils;
diff --git a/core/java/android/os/Bundle.java b/core/java/android/os/Bundle.java
index c5b422230c73..f8f8bf746afd 100644
--- a/core/java/android/os/Bundle.java
+++ b/core/java/android/os/Bundle.java
@@ -17,7 +17,7 @@
package android.os;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.util.ArrayMap;
import android.util.Size;
import android.util.SizeF;
diff --git a/core/java/android/os/CancellationSignal.java b/core/java/android/os/CancellationSignal.java
index 99fb9982e706..260f7ade8ab7 100644
--- a/core/java/android/os/CancellationSignal.java
+++ b/core/java/android/os/CancellationSignal.java
@@ -16,9 +16,7 @@
package android.os;
-import android.os.ICancellationSignal;
-
-import dalvik.annotation.compat.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/**
* Provides the ability to cancel an operation in progress.
diff --git a/core/java/android/os/Debug.java b/core/java/android/os/Debug.java
index 563492925ff0..1c4ef382ca34 100644
--- a/core/java/android/os/Debug.java
+++ b/core/java/android/os/Debug.java
@@ -18,8 +18,8 @@ package android.os;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
import android.app.AppGlobals;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.util.Log;
@@ -1938,8 +1938,14 @@ public final class Debug
public static final int MEMINFO_PAGE_TABLES = 13;
/** @hide */
public static final int MEMINFO_KERNEL_STACK = 14;
+ /**
+ * Note: MEMINFO_KRECLAIMABLE includes MEMINFO_SLAB_RECLAIMABLE (see KReclaimable field
+ * description in kernel documentation).
+ * @hide
+ */
+ public static final int MEMINFO_KRECLAIMABLE = 15;
/** @hide */
- public static final int MEMINFO_COUNT = 15;
+ public static final int MEMINFO_COUNT = 16;
/**
* Retrieves /proc/meminfo. outSizes is filled with fields
@@ -2561,4 +2567,27 @@ public final class Debug
* @hide
*/
public static native long getZramFreeKb();
+
+ /**
+ * Return memory size in kilobytes allocated for ION heaps.
+ *
+ * @hide
+ */
+ public static native long getIonHeapsSizeKb();
+
+ /**
+ * Return memory size in kilobytes allocated for ION pools.
+ *
+ * @hide
+ */
+ public static native long getIonPoolsSizeKb();
+
+ /**
+ * Return ION memory mapped by processes in kB.
+ * Notes:
+ * * Warning: Might impact performance as it reads /proc/<pid>/maps files for each process.
+ *
+ * @hide
+ */
+ public static native long getIonMappedSizeKb();
}
diff --git a/core/java/android/os/DropBoxManager.java b/core/java/android/os/DropBoxManager.java
index b7cccc66294a..18ba5a8a4a34 100644
--- a/core/java/android/os/DropBoxManager.java
+++ b/core/java/android/os/DropBoxManager.java
@@ -24,7 +24,7 @@ import android.annotation.RequiresPermission;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.util.Log;
diff --git a/core/java/android/os/Environment.java b/core/java/android/os/Environment.java
index a92237b9f17f..44f12a6adf60 100644
--- a/core/java/android/os/Environment.java
+++ b/core/java/android/os/Environment.java
@@ -20,10 +20,10 @@ import android.Manifest;
import android.annotation.NonNull;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.AppGlobals;
import android.app.AppOpsManager;
import android.app.admin.DevicePolicyManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
@@ -34,6 +34,8 @@ import android.text.TextUtils;
import android.util.Log;
import java.io.File;
+import java.util.ArrayList;
+import java.util.Collection;
import java.util.LinkedList;
/**
@@ -528,6 +530,22 @@ public class Environment {
}
/**
+ * Return locations where media files (such as ringtones, notification
+ * sounds, or alarm sounds) may be located on internal storage. These are
+ * typically indexed under {@link MediaStore#VOLUME_INTERNAL}.
+ *
+ * @hide
+ */
+ @SystemApi
+ public static @NonNull Collection<File> getInternalMediaDirectories() {
+ final ArrayList<File> res = new ArrayList<>();
+ res.add(new File(Environment.getRootDirectory(), "media"));
+ res.add(new File(Environment.getOemDirectory(), "media"));
+ res.add(new File(Environment.getProductDirectory(), "media"));
+ return res;
+ }
+
+ /**
* Return the primary shared/external storage directory. This directory may
* not currently be accessible if it has been mounted by the user on their
* computer, has been removed from the device, or some other problem has
diff --git a/core/java/android/os/FileObserver.java b/core/java/android/os/FileObserver.java
index 5b715c0dcb3c..ca303d973235 100644
--- a/core/java/android/os/FileObserver.java
+++ b/core/java/android/os/FileObserver.java
@@ -19,7 +19,7 @@ package android.os;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.util.Log;
import java.io.File;
diff --git a/core/java/android/os/FileUtils.java b/core/java/android/os/FileUtils.java
index 2ac3def3a3f9..a47fbbaab9dd 100644
--- a/core/java/android/os/FileUtils.java
+++ b/core/java/android/os/FileUtils.java
@@ -40,7 +40,7 @@ import static android.system.OsConstants.W_OK;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentResolver;
import android.provider.DocumentsContract.Document;
import android.system.ErrnoException;
diff --git a/core/java/android/os/Handler.java b/core/java/android/os/Handler.java
index 928df3c4ff97..af776d154c8f 100644
--- a/core/java/android/os/Handler.java
+++ b/core/java/android/os/Handler.java
@@ -18,7 +18,7 @@ package android.os;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.util.Log;
import android.util.Printer;
diff --git a/core/java/android/os/HwBinder.java b/core/java/android/os/HwBinder.java
index 09afdc7f934e..7c42c36e7747 100644
--- a/core/java/android/os/HwBinder.java
+++ b/core/java/android/os/HwBinder.java
@@ -18,7 +18,7 @@ package android.os;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import libcore.util.NativeAllocationRegistry;
diff --git a/core/java/android/os/HwParcel.java b/core/java/android/os/HwParcel.java
index 9786f16bebaa..fb36e6f6978f 100644
--- a/core/java/android/os/HwParcel.java
+++ b/core/java/android/os/HwParcel.java
@@ -21,7 +21,7 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import dalvik.annotation.optimization.FastNative;
diff --git a/core/java/android/os/HwRemoteBinder.java b/core/java/android/os/HwRemoteBinder.java
index 72ec958ca6d6..756202e88518 100644
--- a/core/java/android/os/HwRemoteBinder.java
+++ b/core/java/android/os/HwRemoteBinder.java
@@ -16,7 +16,8 @@
package android.os;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
+
import libcore.util.NativeAllocationRegistry;
/** @hide */
diff --git a/core/java/android/os/IBinder.java b/core/java/android/os/IBinder.java
index 12bce8a305f2..f336fdab5941 100644
--- a/core/java/android/os/IBinder.java
+++ b/core/java/android/os/IBinder.java
@@ -18,7 +18,7 @@ package android.os;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import java.io.FileDescriptor;
@@ -182,6 +182,14 @@ public interface IBinder {
public static final int MAX_IPC_SIZE = 64 * 1024;
/**
+ * Limit that should be placed on IPC sizes, in bytes, to keep them safely under the transaction
+ * buffer limit.
+ */
+ static int getSuggestedMaxIpcSizeBytes() {
+ return MAX_IPC_SIZE;
+ }
+
+ /**
* Get the canonical name of the interface supported by this binder.
*/
public @Nullable String getInterfaceDescriptor() throws RemoteException;
diff --git a/core/java/android/os/IVibratorService.aidl b/core/java/android/os/IVibratorService.aidl
index 1456ff7e6c5e..6b881fecad56 100644
--- a/core/java/android/os/IVibratorService.aidl
+++ b/core/java/android/os/IVibratorService.aidl
@@ -24,6 +24,7 @@ interface IVibratorService
{
boolean hasVibrator();
boolean hasAmplitudeControl();
+ boolean setAlwaysOnEffect(int id, in VibrationEffect effect, in AudioAttributes attributes);
void vibrate(int uid, String opPkg, in VibrationEffect effect, in AudioAttributes attributes,
String reason, IBinder token);
void cancelVibrate(IBinder token);
diff --git a/core/java/android/os/LocaleList.java b/core/java/android/os/LocaleList.java
index 0de09efad8ea..0bf387e6d0a6 100644
--- a/core/java/android/os/LocaleList.java
+++ b/core/java/android/os/LocaleList.java
@@ -20,7 +20,7 @@ import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.Size;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.icu.util.ULocale;
import com.android.internal.annotations.GuardedBy;
diff --git a/core/java/android/os/Looper.java b/core/java/android/os/Looper.java
index df16ffee7549..b478dbe2555d 100644
--- a/core/java/android/os/Looper.java
+++ b/core/java/android/os/Looper.java
@@ -18,7 +18,7 @@ package android.os;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.util.Log;
import android.util.Printer;
import android.util.Slog;
diff --git a/core/java/android/os/MemoryFile.java b/core/java/android/os/MemoryFile.java
index 5a1e3d429830..f84f9f05b13e 100644
--- a/core/java/android/os/MemoryFile.java
+++ b/core/java/android/os/MemoryFile.java
@@ -16,7 +16,7 @@
package android.os;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.system.ErrnoException;
import java.io.FileDescriptor;
diff --git a/core/java/android/os/Message.java b/core/java/android/os/Message.java
index 9d101e51afbf..c62df407ca77 100644
--- a/core/java/android/os/Message.java
+++ b/core/java/android/os/Message.java
@@ -16,7 +16,7 @@
package android.os;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.util.TimeUtils;
import android.util.proto.ProtoOutputStream;
diff --git a/core/java/android/os/MessageQueue.java b/core/java/android/os/MessageQueue.java
index b5f4bc693d3f..a72795daf7e5 100644
--- a/core/java/android/os/MessageQueue.java
+++ b/core/java/android/os/MessageQueue.java
@@ -19,8 +19,7 @@ package android.os;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
-import android.os.MessageQueueProto;
+import android.compat.annotation.UnsupportedAppUsage;
import android.util.Log;
import android.util.Printer;
import android.util.SparseArray;
diff --git a/core/java/android/os/Parcel.java b/core/java/android/os/Parcel.java
index 9eb6445d5931..c9ebed3bd0a2 100644
--- a/core/java/android/os/Parcel.java
+++ b/core/java/android/os/Parcel.java
@@ -19,8 +19,8 @@ package android.os;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.AppOpsManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.ArraySet;
@@ -1815,8 +1815,12 @@ public final class Parcel {
p.writeToParcel(this, parcelableFlags);
}
- /** @hide */
- @UnsupportedAppUsage
+ /**
+ * Flatten the name of the class of the Parcelable into this Parcel.
+ *
+ * @param p The Parcelable object to be written.
+ * @see #readParcelableCreator
+ */
public final void writeParcelableCreator(@NonNull Parcelable p) {
String name = p.getClass().getName();
writeString(name);
@@ -3011,8 +3015,19 @@ public final class Parcel {
return (T) creator.createFromParcel(this);
}
- /** @hide */
- @UnsupportedAppUsage
+ /**
+ * Read and return a Parcelable.Creator from the parcel. The given class loader will be used to
+ * load the {@link Parcelable.Creator}. If it is null, the default class loader will be used.
+ *
+ * @param loader A ClassLoader from which to instantiate the {@link Parcelable.Creator}
+ * object, or null for the default class loader.
+ * @return the previously written {@link Parcelable.Creator}, or null if a null Creator was
+ * written.
+ * @throws BadParcelableException Throws BadParcelableException if there was an error trying to
+ * read the {@link Parcelable.Creator}.
+ *
+ * @see #writeParcelableCreator
+ */
@Nullable
public final Parcelable.Creator<?> readParcelableCreator(@Nullable ClassLoader loader) {
String name = readString();
diff --git a/core/java/android/os/ParcelFileDescriptor.java b/core/java/android/os/ParcelFileDescriptor.java
index fdb44e7050e1..983053bbe7fd 100644
--- a/core/java/android/os/ParcelFileDescriptor.java
+++ b/core/java/android/os/ParcelFileDescriptor.java
@@ -32,7 +32,7 @@ import static android.system.OsConstants.S_ISREG;
import static android.system.OsConstants.S_IWOTH;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.BroadcastReceiver;
import android.content.ContentProvider;
import android.content.ContentResolver;
diff --git a/core/java/android/os/ParcelUuid.java b/core/java/android/os/ParcelUuid.java
index cc50c8996ba7..0b52c7501d5b 100644
--- a/core/java/android/os/ParcelUuid.java
+++ b/core/java/android/os/ParcelUuid.java
@@ -16,7 +16,7 @@
package android.os;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import java.util.UUID;
diff --git a/core/java/android/os/ParcelableParcel.java b/core/java/android/os/ParcelableParcel.java
index 61f39686c9e6..38d980ecb0f1 100644
--- a/core/java/android/os/ParcelableParcel.java
+++ b/core/java/android/os/ParcelableParcel.java
@@ -16,7 +16,7 @@
package android.os;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.util.MathUtils;
/**
diff --git a/core/java/android/os/PerformanceCollector.java b/core/java/android/os/PerformanceCollector.java
index 33c86b8b05b9..27de48d40188 100644
--- a/core/java/android/os/PerformanceCollector.java
+++ b/core/java/android/os/PerformanceCollector.java
@@ -17,7 +17,8 @@
package android.os;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
+
import java.util.ArrayList;
/**
diff --git a/core/java/android/os/PowerManager.java b/core/java/android/os/PowerManager.java
index 725e0fb901f2..2f8e30e42b7e 100644
--- a/core/java/android/os/PowerManager.java
+++ b/core/java/android/os/PowerManager.java
@@ -25,7 +25,7 @@ import android.annotation.SdkConstant;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.service.dreams.Sandman;
import android.util.ArrayMap;
@@ -44,70 +44,10 @@ import java.util.concurrent.Executor;
* <p>
* <b>Device battery life will be significantly affected by the use of this API.</b>
* Do not acquire {@link WakeLock}s unless you really need them, use the minimum levels
- * possible, and be sure to release them as soon as possible.
- * </p><p>
- * The primary API you'll use is {@link #newWakeLock(int, String) newWakeLock()}.
- * This will create a {@link PowerManager.WakeLock} object. You can then use methods
- * on the wake lock object to control the power state of the device.
- * </p><p>
- * In practice it's quite simple:
- * {@samplecode
- * PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
- * PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
- * wl.acquire();
- * ..screen will stay on during this section..
- * wl.release();
- * }
- * </p><p>
- * The following wake lock levels are defined, with varying effects on system power.
- * <i>These levels are mutually exclusive - you may only specify one of them.</i>
+ * possible, and be sure to release them as soon as possible. In most cases,
+ * you'll want to use
+ * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead.
*
- * <table>
- * <tr><th>Flag Value</th>
- * <th>CPU</th> <th>Screen</th> <th>Keyboard</th></tr>
- *
- * <tr><td>{@link #PARTIAL_WAKE_LOCK}</td>
- * <td>On*</td> <td>Off</td> <td>Off</td>
- * </tr>
- *
- * <tr><td>{@link #SCREEN_DIM_WAKE_LOCK}</td>
- * <td>On</td> <td>Dim</td> <td>Off</td>
- * </tr>
- *
- * <tr><td>{@link #SCREEN_BRIGHT_WAKE_LOCK}</td>
- * <td>On</td> <td>Bright</td> <td>Off</td>
- * </tr>
- *
- * <tr><td>{@link #FULL_WAKE_LOCK}</td>
- * <td>On</td> <td>Bright</td> <td>Bright</td>
- * </tr>
- * </table>
- * </p><p>
- * *<i>If you hold a partial wake lock, the CPU will continue to run, regardless of any
- * display timeouts or the state of the screen and even after the user presses the power button.
- * In all other wake locks, the CPU will run, but the user can still put the device to sleep
- * using the power button.</i>
- * </p><p>
- * In addition, you can add two more flags, which affect behavior of the screen only.
- * <i>These flags have no effect when combined with a {@link #PARTIAL_WAKE_LOCK}.</i></p>
- *
- * <table>
- * <tr><th>Flag Value</th> <th>Description</th></tr>
- *
- * <tr><td>{@link #ACQUIRE_CAUSES_WAKEUP}</td>
- * <td>Normal wake locks don't actually turn on the illumination. Instead, they cause
- * the illumination to remain on once it turns on (e.g. from user activity). This flag
- * will force the screen and/or keyboard to turn on immediately, when the WakeLock is
- * acquired. A typical use would be for notifications which are important for the user to
- * see immediately.</td>
- * </tr>
- *
- * <tr><td>{@link #ON_AFTER_RELEASE}</td>
- * <td>If this flag is set, the user activity timer will be reset when the WakeLock is
- * released, causing the illumination to remain on a bit longer. This can be used to
- * reduce flicker if you are cycling between wake lock conditions.</td>
- * </tr>
- * </table>
* <p>
* Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
* permission in an {@code <uses-permission>} element of the application's manifest.
@@ -931,7 +871,8 @@ public final class PowerManager {
* {@link #FULL_WAKE_LOCK}, {@link #SCREEN_DIM_WAKE_LOCK}
* and {@link #SCREEN_BRIGHT_WAKE_LOCK}. Exactly one wake lock level must be
* specified as part of the {@code levelAndFlags} parameter.
- * </p><p>
+ * </p>
+ * <p>
* The wake lock flags are: {@link #ACQUIRE_CAUSES_WAKEUP}
* and {@link #ON_AFTER_RELEASE}. Multiple flags can be combined as part of the
* {@code levelAndFlags} parameters.
diff --git a/core/java/android/os/Process.java b/core/java/android/os/Process.java
index 6408f6170fce..94623bc71346 100644
--- a/core/java/android/os/Process.java
+++ b/core/java/android/os/Process.java
@@ -19,13 +19,16 @@ package android.os;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.system.Os;
import android.system.OsConstants;
+import android.util.Pair;
import android.webkit.WebViewZygote;
import dalvik.system.VMRuntime;
+import java.util.Map;
+
/**
* Tools for managing OS processes.
*/
@@ -519,11 +522,14 @@ public class Process {
* @param invokeWith null-ok the command to invoke with.
* @param packageName null-ok the name of the package this process belongs to.
* @param isTopApp whether the process starts for high priority application.
- *
+ * @param disabledCompatChanges null-ok list of disabled compat changes for the process being
+ * started.
+ * @param pkgDataInfoMap Map from related package names to private data directory
+ * volume UUID and inode number.
* @param zygoteArgs Additional arguments to supply to the zygote process.
* @return An object that describes the result of the attempt to start the process.
* @throws RuntimeException on fatal start failure
- *
+ *
* {@hide}
*/
public static ProcessStartResult start(@NonNull final String processClass,
@@ -539,11 +545,15 @@ public class Process {
@Nullable String invokeWith,
@Nullable String packageName,
boolean isTopApp,
+ @Nullable long[] disabledCompatChanges,
+ @Nullable Map<String, Pair<String, Long>>
+ pkgDataInfoMap,
@Nullable String[] zygoteArgs) {
return ZYGOTE_PROCESS.start(processClass, niceName, uid, gid, gids,
runtimeFlags, mountExternal, targetSdkVersion, seInfo,
abi, instructionSet, appDataDir, invokeWith, packageName,
- /*useUsapPool=*/ true, isTopApp, zygoteArgs);
+ /*useUsapPool=*/ true, isTopApp, disabledCompatChanges,
+ pkgDataInfoMap, zygoteArgs);
}
/** @hide */
@@ -559,11 +569,15 @@ public class Process {
@Nullable String appDataDir,
@Nullable String invokeWith,
@Nullable String packageName,
+ @Nullable long[] disabledCompatChanges,
@Nullable String[] zygoteArgs) {
+ // Webview zygote can't access app private data files, so doesn't need to know its data
+ // info.
return WebViewZygote.getProcess().start(processClass, niceName, uid, gid, gids,
runtimeFlags, mountExternal, targetSdkVersion, seInfo,
abi, instructionSet, appDataDir, invokeWith, packageName,
- /*useUsapPool=*/ false, /*isTopApp=*/ false, zygoteArgs);
+ /*useUsapPool=*/ false, /*isTopApp=*/ false, disabledCompatChanges,
+ /* pkgDataInfoMap */ null, zygoteArgs);
}
/**
diff --git a/core/java/android/os/RecoverySystem.java b/core/java/android/os/RecoverySystem.java
index e3f6e120d9c6..190182072356 100644
--- a/core/java/android/os/RecoverySystem.java
+++ b/core/java/android/os/RecoverySystem.java
@@ -22,8 +22,8 @@ import android.annotation.RequiresPermission;
import android.annotation.SuppressLint;
import android.annotation.SystemApi;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
import android.app.PendingIntent;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
diff --git a/core/java/android/os/Registrant.java b/core/java/android/os/Registrant.java
index 572b975fbafd..d6afd049f156 100644
--- a/core/java/android/os/Registrant.java
+++ b/core/java/android/os/Registrant.java
@@ -16,9 +16,7 @@
package android.os;
-import android.annotation.UnsupportedAppUsage;
-import android.os.Handler;
-import android.os.Message;
+import android.compat.annotation.UnsupportedAppUsage;
import java.lang.ref.WeakReference;
diff --git a/core/java/android/os/RegistrantList.java b/core/java/android/os/RegistrantList.java
index 9c017dfff967..98f949bbfd84 100644
--- a/core/java/android/os/RegistrantList.java
+++ b/core/java/android/os/RegistrantList.java
@@ -16,7 +16,7 @@
package android.os;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import java.util.ArrayList;
diff --git a/core/java/android/os/RemoteCallback.java b/core/java/android/os/RemoteCallback.java
index da58d0fac160..373060f4ff4b 100644
--- a/core/java/android/os/RemoteCallback.java
+++ b/core/java/android/os/RemoteCallback.java
@@ -20,8 +20,7 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-
-import dalvik.annotation.compat.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/**
* @hide
diff --git a/core/java/android/os/RemoteCallbackList.java b/core/java/android/os/RemoteCallbackList.java
index 6165146ece0a..df4ade09753b 100644
--- a/core/java/android/os/RemoteCallbackList.java
+++ b/core/java/android/os/RemoteCallbackList.java
@@ -16,7 +16,7 @@
package android.os;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.util.ArrayMap;
import android.util.Slog;
diff --git a/core/java/android/os/SELinux.java b/core/java/android/os/SELinux.java
index 34809e76c91b..f64a81177ce2 100644
--- a/core/java/android/os/SELinux.java
+++ b/core/java/android/os/SELinux.java
@@ -16,7 +16,7 @@
package android.os;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.util.Slog;
import java.io.File;
diff --git a/core/java/android/os/ServiceManager.java b/core/java/android/os/ServiceManager.java
index bf9225a2780a..74ff310ad3af 100644
--- a/core/java/android/os/ServiceManager.java
+++ b/core/java/android/os/ServiceManager.java
@@ -16,7 +16,7 @@
package android.os;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.util.ArrayMap;
import android.util.Log;
@@ -140,7 +140,7 @@ public final class ServiceManager {
/**
* Returns a reference to a service with the given name, or throws
- * {@link NullPointerException} if none is found.
+ * {@link ServiceNotFoundException} if none is found.
*
* @hide
*/
diff --git a/core/java/android/os/ServiceManagerNative.java b/core/java/android/os/ServiceManagerNative.java
index 124b6c6f7377..ba4042dd49fa 100644
--- a/core/java/android/os/ServiceManagerNative.java
+++ b/core/java/android/os/ServiceManagerNative.java
@@ -16,7 +16,7 @@
package android.os;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/**
* Native implementation of the service manager. Most clients will only
diff --git a/core/java/android/os/SharedMemory.java b/core/java/android/os/SharedMemory.java
index 57a88012a31a..26d9c7d687eb 100644
--- a/core/java/android/os/SharedMemory.java
+++ b/core/java/android/os/SharedMemory.java
@@ -18,7 +18,7 @@ package android.os;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.system.ErrnoException;
import android.system.Os;
import android.system.OsConstants;
diff --git a/core/java/android/os/ShellCommand.java b/core/java/android/os/ShellCommand.java
index f3a6869687dc..0be3d681c80a 100644
--- a/core/java/android/os/ShellCommand.java
+++ b/core/java/android/os/ShellCommand.java
@@ -16,7 +16,7 @@
package android.os;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.util.Slog;
import com.android.internal.util.FastPrintWriter;
diff --git a/core/java/android/os/StatFs.java b/core/java/android/os/StatFs.java
index 881d0b4d9c8e..6d1a1164abb4 100644
--- a/core/java/android/os/StatFs.java
+++ b/core/java/android/os/StatFs.java
@@ -16,7 +16,7 @@
package android.os;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.system.ErrnoException;
import android.system.Os;
import android.system.StructStatVfs;
diff --git a/core/java/android/os/StrictMode.java b/core/java/android/os/StrictMode.java
index 0bf634e799cd..3faaff73a0ea 100644
--- a/core/java/android/os/StrictMode.java
+++ b/core/java/android/os/StrictMode.java
@@ -20,10 +20,10 @@ import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityManager;
import android.app.ActivityThread;
import android.app.IActivityManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
diff --git a/core/java/android/os/SystemClock.java b/core/java/android/os/SystemClock.java
index c104abdcb097..fd68c2b9b5fd 100644
--- a/core/java/android/os/SystemClock.java
+++ b/core/java/android/os/SystemClock.java
@@ -17,8 +17,8 @@
package android.os;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
import android.app.IAlarmManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.location.ILocationManager;
import android.location.LocationTime;
diff --git a/core/java/android/os/SystemProperties.java b/core/java/android/os/SystemProperties.java
index e7a271cbbb8e..c5e5cc40d54e 100644
--- a/core/java/android/os/SystemProperties.java
+++ b/core/java/android/os/SystemProperties.java
@@ -20,7 +20,7 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.util.Log;
import android.util.MutableInt;
diff --git a/core/java/android/os/SystemService.java b/core/java/android/os/SystemService.java
index 968c761c5ff0..5871d2d9b58f 100644
--- a/core/java/android/os/SystemService.java
+++ b/core/java/android/os/SystemService.java
@@ -16,9 +16,10 @@
package android.os;
+import android.compat.annotation.UnsupportedAppUsage;
+
import com.google.android.collect.Maps;
-import android.annotation.UnsupportedAppUsage;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;
diff --git a/core/java/android/os/SystemVibrator.java b/core/java/android/os/SystemVibrator.java
index a5188e7cd58d..f585c75b6bb7 100644
--- a/core/java/android/os/SystemVibrator.java
+++ b/core/java/android/os/SystemVibrator.java
@@ -16,7 +16,7 @@
package android.os;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.media.AudioAttributes;
import android.util.Log;
@@ -70,6 +70,20 @@ public class SystemVibrator extends Vibrator {
}
@Override
+ public boolean setAlwaysOnEffect(int id, VibrationEffect effect, AudioAttributes attributes) {
+ if (mService == null) {
+ Log.w(TAG, "Failed to set always-on effect; no vibrator service.");
+ return false;
+ }
+ try {
+ return mService.setAlwaysOnEffect(id, effect, attributes);
+ } catch (RemoteException e) {
+ Log.w(TAG, "Failed to set always-on effect.", e);
+ }
+ return false;
+ }
+
+ @Override
public void vibrate(int uid, String opPkg, VibrationEffect effect,
String reason, AudioAttributes attributes) {
if (mService == null) {
diff --git a/core/java/android/os/TelephonyServiceManager.java b/core/java/android/os/TelephonyServiceManager.java
new file mode 100644
index 000000000000..1211dd60f591
--- /dev/null
+++ b/core/java/android/os/TelephonyServiceManager.java
@@ -0,0 +1,138 @@
+/*
+ * Copyright (C) 2019 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.os;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.SystemApi;
+
+/**
+ * Provides a way to register and obtain the system service binder objects managed by the telephony
+ * service.
+ *
+ * <p>Only the telephony mainline module will be able to access an instance of this class.
+ *
+ * @hide
+ */
+@SystemApi
+public class TelephonyServiceManager {
+ /**
+ * @hide
+ */
+ public TelephonyServiceManager() {
+ }
+
+ /**
+ * A class that exposes the methods to register and obtain each system service.
+ */
+ public final class ServiceRegisterer {
+ private final String mServiceName;
+
+ /**
+ * @hide
+ */
+ public ServiceRegisterer(String serviceName) {
+ mServiceName = serviceName;
+ }
+
+ /**
+ * Register a system server binding object for a service.
+ */
+ public void register(@NonNull IBinder binder) {
+ ServiceManager.addService(mServiceName, binder);
+ }
+
+ /**
+ * Get the system server binding object for a service.
+ *
+ * <p>This blocks until the service instance is ready,
+ * or a timeout happens, in which case it returns null.
+ */
+ @Nullable
+ public IBinder get() {
+ return ServiceManager.getService(mServiceName);
+ }
+
+ /**
+ * Get the system server binding object for a service.
+ *
+ * <p>This blocks until the service instance is ready,
+ * or a timeout happens, in which case it throws {@link ServiceNotFoundException}.
+ */
+ @NonNull
+ public IBinder getOrThrow() throws ServiceNotFoundException {
+ try {
+ return ServiceManager.getServiceOrThrow(mServiceName);
+ } catch (ServiceManager.ServiceNotFoundException e) {
+ throw new ServiceNotFoundException(mServiceName);
+ }
+ }
+
+ /**
+ * Get the system server binding object for a service. If the specified service is
+ * not available, it returns null.
+ */
+ @Nullable
+ public IBinder tryGet() {
+ return ServiceManager.checkService(mServiceName);
+ }
+ }
+
+ /**
+ * See {@link ServiceRegisterer#getOrThrow}.
+ *
+ * @hide
+ */
+ @SystemApi
+ public static class ServiceNotFoundException extends ServiceManager.ServiceNotFoundException {
+ /**
+ * Constructor.
+ *
+ * @param name the name of the binder service that cannot be found.
+ *
+ */
+ public ServiceNotFoundException(@NonNull String name) {
+ super(name);
+ }
+ }
+
+ /**
+ * Returns {@link ServiceRegisterer} for the "telephony" service.
+ */
+ @NonNull
+ public ServiceRegisterer getTelephonyServiceRegisterer() {
+ return new ServiceRegisterer("phone");
+ }
+
+
+// TODO: Add more services...
+//
+// /**
+// * Returns {@link ServiceRegisterer} for the "subscription" service.
+// */
+// @NonNull
+// public ServiceRegisterer getSubscriptionServiceRegisterer() {
+// return new ServiceRegisterer("isub");
+// }
+//
+// /**
+// * Returns {@link ServiceRegisterer} for the "SMS" service.
+// */
+// @NonNull
+// public ServiceRegisterer getSmsServiceRegisterer() {
+// return new ServiceRegisterer("isms");
+// }
+}
diff --git a/core/java/android/os/Trace.java b/core/java/android/os/Trace.java
index 1456a734394d..25584f156084 100644
--- a/core/java/android/os/Trace.java
+++ b/core/java/android/os/Trace.java
@@ -17,10 +17,9 @@
package android.os;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
-
-import com.android.internal.os.Zygote;
+import android.compat.annotation.UnsupportedAppUsage;
+import dalvik.annotation.optimization.CriticalNative;
import dalvik.annotation.optimization.FastNative;
/**
@@ -107,12 +106,15 @@ public final class Trace {
private static final int MAX_SECTION_NAME_LEN = 127;
// Must be volatile to avoid word tearing.
+ // This is only kept in case any apps get this by reflection but do not
+ // check the return value for null.
@UnsupportedAppUsage
private static volatile long sEnabledTags = TRACE_TAG_NOT_READY;
private static int sZygoteDebugFlags = 0;
@UnsupportedAppUsage
+ @CriticalNative
private static native long nativeGetEnabledTags();
private static native void nativeSetAppTracingAllowed(boolean allowed);
private static native void nativeSetTracingEnabled(boolean allowed);
@@ -128,47 +130,10 @@ public final class Trace {
@FastNative
private static native void nativeAsyncTraceEnd(long tag, String name, int cookie);
- static {
- // We configure two separate change callbacks, one in Trace.cpp and one here. The
- // native callback reads the tags from the system property, and this callback
- // reads the value that the native code retrieved. It's essential that the native
- // callback executes first.
- //
- // The system provides ordering through a priority level. Callbacks made through
- // SystemProperties.addChangeCallback currently have a negative priority, while
- // our native code is using a priority of zero.
- SystemProperties.addChangeCallback(() -> {
- cacheEnabledTags();
- if ((sZygoteDebugFlags & Zygote.DEBUG_JAVA_DEBUGGABLE) != 0) {
- traceCounter(TRACE_TAG_ALWAYS, "java_debuggable", 1);
- }
- });
- }
-
private Trace() {
}
/**
- * Caches a copy of the enabled-tag bits. The "master" copy is held by the native code,
- * and comes from the PROPERTY_TRACE_TAG_ENABLEFLAGS property.
- * <p>
- * If the native code hasn't yet read the property, we will cause it to do one-time
- * initialization. We don't want to do this during class init, because this class is
- * preloaded, so all apps would be stuck with whatever the zygote saw. (The zygote
- * doesn't see the system-property update broadcasts.)
- * <p>
- * We want to defer initialization until the first use by an app, post-zygote.
- * <p>
- * We're okay if multiple threads call here simultaneously -- the native state is
- * synchronized, and sEnabledTags is volatile (prevents word tearing).
- */
- private static long cacheEnabledTags() {
- long tags = nativeGetEnabledTags();
- sEnabledTags = tags;
- return tags;
- }
-
- /**
* Returns true if a trace tag is enabled.
*
* @param traceTag The trace tag to check.
@@ -178,10 +143,7 @@ public final class Trace {
*/
@UnsupportedAppUsage
public static boolean isTagEnabled(long traceTag) {
- long tags = sEnabledTags;
- if (tags == TRACE_TAG_NOT_READY) {
- tags = cacheEnabledTags();
- }
+ long tags = nativeGetEnabledTags();
return (tags & traceTag) != 0;
}
@@ -210,10 +172,6 @@ public final class Trace {
@UnsupportedAppUsage
public static void setAppTracingAllowed(boolean allowed) {
nativeSetAppTracingAllowed(allowed);
-
- // Setting whether app tracing is allowed may change the tags, so we update the cached
- // tags here.
- cacheEnabledTags();
}
/**
@@ -227,10 +185,6 @@ public final class Trace {
public static void setTracingEnabled(boolean enabled, int debugFlags) {
nativeSetTracingEnabled(enabled);
sZygoteDebugFlags = debugFlags;
-
- // Setting whether tracing is enabled may change the tags, so we update the cached tags
- // here.
- cacheEnabledTags();
}
/**
diff --git a/core/java/android/os/UEventObserver.java b/core/java/android/os/UEventObserver.java
index dc98c4267a37..fa30e509f8cc 100644
--- a/core/java/android/os/UEventObserver.java
+++ b/core/java/android/os/UEventObserver.java
@@ -16,7 +16,7 @@
package android.os;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.util.Log;
import java.util.ArrayList;
diff --git a/core/java/android/os/UpdateLock.java b/core/java/android/os/UpdateLock.java
index ea273cea8835..036d0951c19a 100644
--- a/core/java/android/os/UpdateLock.java
+++ b/core/java/android/os/UpdateLock.java
@@ -16,7 +16,7 @@
package android.os;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.util.Log;
diff --git a/core/java/android/os/UserHandle.java b/core/java/android/os/UserHandle.java
index 62e83aa192aa..b92fb47d1112 100644
--- a/core/java/android/os/UserHandle.java
+++ b/core/java/android/os/UserHandle.java
@@ -20,8 +20,8 @@ import android.annotation.AppIdInt;
import android.annotation.NonNull;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.UserIdInt;
+import android.compat.annotation.UnsupportedAppUsage;
import java.io.PrintWriter;
diff --git a/core/java/android/os/UserManager.java b/core/java/android/os/UserManager.java
index 137f53782124..7efe0b7ce389 100644
--- a/core/java/android/os/UserManager.java
+++ b/core/java/android/os/UserManager.java
@@ -28,12 +28,12 @@ import android.annotation.StringDef;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.UserIdInt;
import android.annotation.WorkerThread;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
@@ -442,7 +442,13 @@ public class UserManager {
* @see DevicePolicyManager#addUserRestriction(ComponentName, String)
* @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
* @see #getUserRestrictions()
+ * @deprecated As the ability to have a managed profile on a fully-managed device has been
+ * removed from the platform, this restriction will be silently ignored when applied by the
+ * device owner.
+ * When the device is provisioned with a managed profile on an organization-owned device,
+ * the managed profile could not be removed anyway.
*/
+ @Deprecated
public static final String DISALLOW_REMOVE_MANAGED_PROFILE = "no_remove_managed_profile";
/**
@@ -589,7 +595,11 @@ public class UserManager {
* @see DevicePolicyManager#addUserRestriction(ComponentName, String)
* @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
* @see #getUserRestrictions()
+ * @deprecated As the ability to have a managed profile on a fully-managed device has been
+ * removed from the platform, this restriction will be silently ignored when applied by the
+ * device owner.
*/
+ @Deprecated
public static final String DISALLOW_ADD_MANAGED_PROFILE = "no_add_managed_profile";
/**
@@ -2391,19 +2401,11 @@ public class UserManager {
*/
public @Nullable UserInfo createUser(@Nullable String name, @NonNull String userType,
@UserInfoFlag int flags) {
- UserInfo user = null;
- try {
- user = mService.createUser(name, userType, flags);
- // TODO: Keep this in sync with
- // UserManagerService.LocalService.createUserEvenWhenDisallowed
- if (user != null && !user.isAdmin() && !user.isDemo()) {
- mService.setUserRestriction(DISALLOW_SMS, true, user.id);
- mService.setUserRestriction(DISALLOW_OUTGOING_CALLS, true, user.id);
- }
+ try {
+ return mService.createUser(name, userType, flags);
} catch (RemoteException re) {
throw re.rethrowFromSystemServer();
}
- return user;
}
/**
@@ -2748,8 +2750,7 @@ public class UserManager {
/**
* Assigns admin privileges to the user, if such a user exists.
*
- * <p>Requires {@link android.Manifest.permission#MANAGE_USERS} and
- * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permissions.
+ * <p>Note that this does not alter the user's pre-existing user restrictions.
*
* @param userId the id of the user to become admin
* @hide
diff --git a/core/java/android/os/VibrationEffect.java b/core/java/android/os/VibrationEffect.java
index 5769c34c6d20..75b4724c7d26 100644
--- a/core/java/android/os/VibrationEffect.java
+++ b/core/java/android/os/VibrationEffect.java
@@ -20,6 +20,7 @@ import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentResolver;
import android.content.Context;
import android.hardware.vibrator.V1_0.EffectStrength;
@@ -27,8 +28,6 @@ import android.hardware.vibrator.V1_3.Effect;
import android.net.Uri;
import android.util.MathUtils;
-import dalvik.annotation.compat.UnsupportedAppUsage;
-
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
diff --git a/core/java/android/os/Vibrator.java b/core/java/android/os/Vibrator.java
index 28909c88a734..ccbb0f191f6f 100644
--- a/core/java/android/os/Vibrator.java
+++ b/core/java/android/os/Vibrator.java
@@ -17,10 +17,11 @@
package android.os;
import android.annotation.IntDef;
+import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityThread;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.media.AudioAttributes;
import android.util.Log;
@@ -152,6 +153,24 @@ public abstract class Vibrator {
public abstract boolean hasAmplitudeControl();
/**
+ * Configure an always-on haptics effect.
+ *
+ * @param id The board-specific always-on ID to configure.
+ * @param effect Vibration effect to assign to always-on id. Passing null will disable it.
+ * @param attributes {@link AudioAttributes} corresponding to the vibration. For example,
+ * specify {@link AudioAttributes#USAGE_ALARM} for alarm vibrations or
+ * {@link AudioAttributes#USAGE_NOTIFICATION_RINGTONE} for
+ * vibrations associated with incoming calls. May only be null when effect is null.
+ * @hide
+ */
+ @RequiresPermission(android.Manifest.permission.VIBRATE_ALWAYS_ON)
+ public boolean setAlwaysOnEffect(int id, @Nullable VibrationEffect effect,
+ @Nullable AudioAttributes attributes) {
+ Log.w(TAG, "Always-on effects aren't supported");
+ return false;
+ }
+
+ /**
* Vibrate constantly for the specified period of time.
*
* @param milliseconds The number of milliseconds to vibrate.
diff --git a/core/java/android/os/WorkSource.java b/core/java/android/os/WorkSource.java
index 397c2a96c48e..7161b07cee3c 100644
--- a/core/java/android/os/WorkSource.java
+++ b/core/java/android/os/WorkSource.java
@@ -4,9 +4,8 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
-import android.os.WorkSourceProto;
import android.provider.Settings;
import android.provider.Settings.Global;
import android.util.Log;
diff --git a/core/java/android/os/ZygoteProcess.java b/core/java/android/os/ZygoteProcess.java
index 907eae87bcb2..62b8953b158a 100644
--- a/core/java/android/os/ZygoteProcess.java
+++ b/core/java/android/os/ZygoteProcess.java
@@ -18,11 +18,12 @@ package android.os;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ApplicationInfo;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.util.Log;
+import android.util.Pair;
import android.util.Slog;
import com.android.internal.annotations.GuardedBy;
@@ -39,6 +40,7 @@ import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
+import java.util.Map;
import java.util.UUID;
/*package*/ class ZygoteStartFailedEx extends Exception {
@@ -306,8 +308,12 @@ public class ZygoteProcess {
* @param appDataDir null-ok the data directory of the app.
* @param invokeWith null-ok the command to invoke with.
* @param packageName null-ok the name of the package this process belongs to.
+ * @param disabledCompatChanges null-ok list of disabled compat changes for the process being
+ * started.
* @param zygoteArgs Additional arguments to supply to the zygote process.
* @param isTopApp Whether the process starts for high priority application.
+ * @param pkgDataInfoMap Map from related package names to private data directory
+ * volume UUID and inode number.
*
* @return An object that describes the result of the attempt to start the process.
* @throws RuntimeException on fatal start failure
@@ -325,6 +331,9 @@ public class ZygoteProcess {
@Nullable String packageName,
boolean useUsapPool,
boolean isTopApp,
+ @Nullable long[] disabledCompatChanges,
+ @Nullable Map<String, Pair<String, Long>>
+ pkgDataInfoMap,
@Nullable String[] zygoteArgs) {
// TODO (chriswailes): Is there a better place to check this value?
if (fetchUsapPoolEnabledPropWithMinInterval()) {
@@ -335,7 +344,8 @@ public class ZygoteProcess {
return startViaZygote(processClass, niceName, uid, gid, gids,
runtimeFlags, mountExternal, targetSdkVersion, seInfo,
abi, instructionSet, appDataDir, invokeWith, /*startChildZygote=*/ false,
- packageName, useUsapPool, isTopApp, zygoteArgs);
+ packageName, useUsapPool, isTopApp, disabledCompatChanges,
+ pkgDataInfoMap, zygoteArgs);
} catch (ZygoteStartFailedEx ex) {
Log.e(LOG_TAG,
"Starting VM process through Zygote failed");
@@ -535,6 +545,9 @@ public class ZygoteProcess {
* that has its state cloned from this zygote process.
* @param packageName null-ok the name of the package this process belongs to.
* @param isTopApp Whether the process starts for high priority application.
+ * @param disabledCompatChanges a list of disabled compat changes for the process being started.
+ * @param pkgDataInfoMap Map from related package names to private data directory volume UUID
+ * and inode number.
* @param extraArgs Additional arguments to supply to the zygote process.
* @return An object that describes the result of the attempt to start the process.
* @throws ZygoteStartFailedEx if process start failed for any reason
@@ -554,6 +567,9 @@ public class ZygoteProcess {
@Nullable String packageName,
boolean useUsapPool,
boolean isTopApp,
+ @Nullable long[] disabledCompatChanges,
+ @Nullable Map<String, Pair<String, Long>>
+ pkgDataInfoMap,
@Nullable String[] extraArgs)
throws ZygoteStartFailedEx {
ArrayList<String> argsForZygote = new ArrayList<>();
@@ -584,10 +600,10 @@ public class ZygoteProcess {
// --setgroups is a comma-separated list
if (gids != null && gids.length > 0) {
- StringBuilder sb = new StringBuilder();
+ final StringBuilder sb = new StringBuilder();
sb.append("--setgroups=");
- int sz = gids.length;
+ final int sz = gids.length;
for (int i = 0; i < sz; i++) {
if (i != 0) {
sb.append(',');
@@ -630,6 +646,39 @@ public class ZygoteProcess {
if (isTopApp) {
argsForZygote.add(Zygote.START_AS_TOP_APP_ARG);
}
+ if (pkgDataInfoMap != null && pkgDataInfoMap.size() > 0) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(Zygote.PKG_DATA_INFO_MAP);
+ sb.append("=");
+ boolean started = false;
+ for (Map.Entry<String, Pair<String, Long>> entry : pkgDataInfoMap.entrySet()) {
+ if (started) {
+ sb.append(',');
+ }
+ started = true;
+ sb.append(entry.getKey());
+ sb.append(',');
+ sb.append(entry.getValue().first);
+ sb.append(',');
+ sb.append(entry.getValue().second);
+ }
+ argsForZygote.add(sb.toString());
+ }
+
+ if (disabledCompatChanges != null && disabledCompatChanges.length > 0) {
+ StringBuilder sb = new StringBuilder();
+ sb.append("--disabled-compat-changes=");
+
+ int sz = disabledCompatChanges.length;
+ for (int i = 0; i < sz; i++) {
+ if (i != 0) {
+ sb.append(',');
+ }
+ sb.append(disabledCompatChanges[i]);
+ }
+
+ argsForZygote.add(sb.toString());
+ }
argsForZygote.add(processClass);
@@ -1162,11 +1211,14 @@ public class ZygoteProcess {
Process.ProcessStartResult result;
try {
+ // As app zygote is for generating isolated process, at the end it can't access
+ // apps data, so doesn't need to its data info.
result = startViaZygote(processClass, niceName, uid, gid,
gids, runtimeFlags, 0 /* mountExternal */, 0 /* targetSdkVersion */, seInfo,
abi, instructionSet, null /* appDataDir */, null /* invokeWith */,
true /* startChildZygote */, null /* packageName */,
- false /* useUsapPool */, false /* isTopApp */, extraArgs);
+ false /* useUsapPool */, false /* isTopApp */,
+ null /* disabledCompatChanges */, null /* pkgDataInfoMap */, extraArgs);
} catch (ZygoteStartFailedEx ex) {
throw new RuntimeException("Starting child-zygote through Zygote failed", ex);
}
diff --git a/core/java/android/os/connectivity/WifiBatteryStats.java b/core/java/android/os/connectivity/WifiBatteryStats.java
index e9b3837c8853..895d837a359e 100644
--- a/core/java/android/os/connectivity/WifiBatteryStats.java
+++ b/core/java/android/os/connectivity/WifiBatteryStats.java
@@ -19,6 +19,7 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.os.BatteryStats;
+import android.os.BatteryStatsManager;
import android.os.Parcel;
import android.os.Parcelable;
@@ -46,9 +47,9 @@ public final class WifiBatteryStats implements Parcelable {
private long mEnergyConsumedMaMillis = 0;
private long mNumAppScanRequest = 0;
private long[] mTimeInStateMillis =
- new long[BatteryStats.NUM_WIFI_STATES];
+ new long[BatteryStatsManager.NUM_WIFI_STATES];
private long[] mTimeInSupplicantStateMillis =
- new long[BatteryStats.NUM_WIFI_SUPPL_STATES];
+ new long[BatteryStatsManager.NUM_WIFI_SUPPL_STATES];
private long[] mTimeInRxSignalStrengthLevelMillis =
new long[BatteryStats.NUM_WIFI_SIGNAL_STRENGTH_BINS];
private long mMonitoredRailChargeConsumedMaMillis = 0;
@@ -369,7 +370,7 @@ public final class WifiBatteryStats implements Parcelable {
/** @hide */
public void setTimeInStateMillis(long[] t) {
mTimeInStateMillis = Arrays.copyOfRange(t, 0,
- Math.min(t.length, BatteryStats.NUM_WIFI_STATES));
+ Math.min(t.length, BatteryStatsManager.NUM_WIFI_STATES));
return;
}
@@ -383,7 +384,7 @@ public final class WifiBatteryStats implements Parcelable {
/** @hide */
public void setTimeInSupplicantStateMillis(long[] t) {
mTimeInSupplicantStateMillis = Arrays.copyOfRange(
- t, 0, Math.min(t.length, BatteryStats.NUM_WIFI_SUPPL_STATES));
+ t, 0, Math.min(t.length, BatteryStatsManager.NUM_WIFI_SUPPL_STATES));
return;
}
diff --git a/core/java/android/os/health/HealthStatsParceler.java b/core/java/android/os/health/HealthStatsParceler.java
index 384342c894d5..f28a9747bc44 100644
--- a/core/java/android/os/health/HealthStatsParceler.java
+++ b/core/java/android/os/health/HealthStatsParceler.java
@@ -17,11 +17,10 @@
package android.os.health;
import android.annotation.TestApi;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
-import dalvik.annotation.compat.UnsupportedAppUsage;
-
/**
* Class to allow sending the HealthStats through aidl generated glue.
*
diff --git a/core/java/android/os/health/SystemHealthManager.java b/core/java/android/os/health/SystemHealthManager.java
index a92e28a47660..6e259ea2642c 100644
--- a/core/java/android/os/health/SystemHealthManager.java
+++ b/core/java/android/os/health/SystemHealthManager.java
@@ -17,14 +17,13 @@
package android.os.health;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.BatteryStats;
import android.os.Build;
import android.os.Process;
import android.os.RemoteException;
import android.os.ServiceManager;
-import android.os.ServiceManager.ServiceNotFoundException;
import com.android.internal.app.IBatteryStats;
diff --git a/core/java/android/os/incremental/IIncrementalManager.aidl b/core/java/android/os/incremental/IIncrementalManager.aidl
index d6446d485af5..17a310a5beb0 100644
--- a/core/java/android/os/incremental/IIncrementalManager.aidl
+++ b/core/java/android/os/incremental/IIncrementalManager.aidl
@@ -16,89 +16,22 @@
package android.os.incremental;
-import android.os.incremental.IncrementalDataLoaderParamsParcel;
-
-/** @hide */
+import android.content.pm.FileSystemControlParcel;
+import android.content.pm.DataLoaderParamsParcel;
+import android.content.pm.IDataLoaderStatusListener;
+
+/**
+ * Binder service to receive calls from native Incremental Service and handle Java tasks such as
+ * looking up data loader service package names, binding and talking to the data loader service.
+ * @hide
+ */
interface IIncrementalManager {
- /**
- * A set of flags for the |createMode| parameters when creating a new Incremental storage.
- */
- const int CREATE_MODE_TEMPORARY_BIND = 1;
- const int CREATE_MODE_PERMANENT_BIND = 2;
- const int CREATE_MODE_CREATE = 4;
- const int CREATE_MODE_OPEN_EXISTING = 8;
-
- /**
- * Opens or creates a storage given a target path and data loader params. Returns the storage ID.
- */
- int openStorage(in @utf8InCpp String path);
- int createStorage(in @utf8InCpp String path, in IncrementalDataLoaderParamsParcel params, int createMode);
- int createLinkedStorage(in @utf8InCpp String path, int otherStorageId, int createMode);
-
- /**
- * Bind-mounts a path under a storage to a full path. Can be permanent or temporary.
- */
- const int BIND_TEMPORARY = 0;
- const int BIND_PERMANENT = 1;
- int makeBindMount(int storageId, in @utf8InCpp String pathUnderStorage, in @utf8InCpp String targetFullPath, int bindType);
-
- /**
- * Deletes an existing bind mount on a path under a storage. Returns 0 on success, and -errno on failure.
- */
- int deleteBindMount(int storageId, in @utf8InCpp String targetFullPath);
-
- /**
- * Creates a directory under a storage. The target directory is specified by its relative path under the storage.
- */
- int makeDirectory(int storageId, in @utf8InCpp String pathUnderStorage);
-
- /**
- * Recursively creates a directory under a storage. The target directory is specified by its relative path under the storage.
- * All the parent directories of the target directory will be created if they do not exist already.
- */
- int makeDirectories(int storageId, in @utf8InCpp String pathUnderStorage);
-
- /**
- * Creates a file under a storage, specifying its name, size and metadata.
- */
- int makeFile(int storageId, in @utf8InCpp String pathUnderStorage, long size, in byte[] metadata);
-
- /**
- * Creates a file under a storage. Content of the file is from a range inside another file.
- * Both files are specified by relative paths under storage.
- */
- int makeFileFromRange(int storageId, in @utf8InCpp String targetPathUnderStorage, in @utf8InCpp String sourcePathUnderStorage, long start, long end);
-
- /**
- * Creates a hard link between two files in two storage instances.
- * Source and dest specified by parent storage IDs and their relative paths under the storage.
- * The source and dest storage instances should be in the same fs mount.
- * Note: destStorageId can be the same as sourceStorageId.
- */
- int makeLink(int sourceStorageId, in @utf8InCpp String sourcePathUnderStorage, int destStorageId, in @utf8InCpp String destPathUnderStorage);
-
- /**
- * Deletes a hard link in a storage, specified by the relative path of the link target under storage.
- */
- int unlink(int storageId, in @utf8InCpp String pathUnderStorage);
-
- /**
- * Checks if a file's certain range is loaded. File is specified by relative file path under storage.
- */
- boolean isFileRangeLoaded(int storageId, in @utf8InCpp String pathUnderStorage, long start, long end);
-
- /**
- * Reads the metadata of a file. File is specified by relative path under storage.
- */
- byte[] getFileMetadata(int storageId, in @utf8InCpp String pathUnderStorage);
-
- /**
- * Starts loading data for a storage.
- */
- boolean startLoading(int storageId);
-
- /**
- * Deletes a storage given its ID. Deletes its bind mounts and unmount it. Stop its data loader.
- */
- void deleteStorage(int storageId);
+ boolean prepareDataLoader(int mountId,
+ in FileSystemControlParcel control,
+ in DataLoaderParamsParcel params,
+ in IDataLoaderStatusListener listener);
+ boolean startDataLoader(int mountId);
+ void showHealthBlockedUI(int mountId);
+ void destroyDataLoader(int mountId);
+ void newFileForDataLoader(int mountId, long inode, in byte[] metadata);
}
diff --git a/core/java/android/os/incremental/IIncrementalManagerNative.aidl b/core/java/android/os/incremental/IIncrementalManagerNative.aidl
new file mode 100644
index 000000000000..14215b1ea84d
--- /dev/null
+++ b/core/java/android/os/incremental/IIncrementalManagerNative.aidl
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2019 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.os.incremental;
+
+import android.content.pm.DataLoaderParamsParcel;
+
+/** @hide */
+interface IIncrementalManagerNative {
+ /**
+ * A set of flags for the |createMode| parameters when creating a new Incremental storage.
+ */
+ const int CREATE_MODE_TEMPORARY_BIND = 1;
+ const int CREATE_MODE_PERMANENT_BIND = 2;
+ const int CREATE_MODE_CREATE = 4;
+ const int CREATE_MODE_OPEN_EXISTING = 8;
+
+ /**
+ * Opens or creates a storage given a target path and data loader params. Returns the storage ID.
+ */
+ int openStorage(in @utf8InCpp String path);
+ int createStorage(in @utf8InCpp String path, in DataLoaderParamsParcel params, int createMode);
+ int createLinkedStorage(in @utf8InCpp String path, int otherStorageId, int createMode);
+
+ /**
+ * Bind-mounts a path under a storage to a full path. Can be permanent or temporary.
+ */
+ const int BIND_TEMPORARY = 0;
+ const int BIND_PERMANENT = 1;
+ int makeBindMount(int storageId, in @utf8InCpp String pathUnderStorage, in @utf8InCpp String targetFullPath, int bindType);
+
+ /**
+ * Deletes an existing bind mount on a path under a storage. Returns 0 on success, and -errno on failure.
+ */
+ int deleteBindMount(int storageId, in @utf8InCpp String targetFullPath);
+
+ /**
+ * Creates a directory under a storage. The target directory is specified by its relative path under the storage.
+ */
+ int makeDirectory(int storageId, in @utf8InCpp String pathUnderStorage);
+
+ /**
+ * Recursively creates a directory under a storage. The target directory is specified by its relative path under the storage.
+ * All the parent directories of the target directory will be created if they do not exist already.
+ */
+ int makeDirectories(int storageId, in @utf8InCpp String pathUnderStorage);
+
+ /**
+ * Creates a file under a storage, specifying its name, size and metadata.
+ */
+ int makeFile(int storageId, in @utf8InCpp String pathUnderStorage, long size, in byte[] metadata);
+
+ /**
+ * Creates a file under a storage. Content of the file is from a range inside another file.
+ * Both files are specified by relative paths under storage.
+ */
+ int makeFileFromRange(int storageId, in @utf8InCpp String targetPathUnderStorage, in @utf8InCpp String sourcePathUnderStorage, long start, long end);
+
+ /**
+ * Creates a hard link between two files in two storage instances.
+ * Source and dest specified by parent storage IDs and their relative paths under the storage.
+ * The source and dest storage instances should be in the same fs mount.
+ * Note: destStorageId can be the same as sourceStorageId.
+ */
+ int makeLink(int sourceStorageId, in @utf8InCpp String sourcePathUnderStorage, int destStorageId, in @utf8InCpp String destPathUnderStorage);
+
+ /**
+ * Deletes a hard link in a storage, specified by the relative path of the link target under storage.
+ */
+ int unlink(int storageId, in @utf8InCpp String pathUnderStorage);
+
+ /**
+ * Checks if a file's certain range is loaded. File is specified by relative file path under storage.
+ */
+ boolean isFileRangeLoaded(int storageId, in @utf8InCpp String pathUnderStorage, long start, long end);
+
+ /**
+ * Reads the metadata of a file. File is specified by relative path under storage.
+ */
+ byte[] getFileMetadata(int storageId, in @utf8InCpp String pathUnderStorage);
+
+ /**
+ * Starts loading data for a storage.
+ */
+ boolean startLoading(int storageId);
+
+ /**
+ * Deletes a storage given its ID. Deletes its bind mounts and unmount it. Stop its data loader.
+ */
+ void deleteStorage(int storageId);
+}
diff --git a/core/java/android/os/incremental/IIncrementalServiceProxy.aidl b/core/java/android/os/incremental/IIncrementalServiceProxy.aidl
deleted file mode 100644
index ffff52e5aac9..000000000000
--- a/core/java/android/os/incremental/IIncrementalServiceProxy.aidl
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2019 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.os.incremental;
-
-import android.os.incremental.IncrementalFileSystemControlParcel;
-import android.os.incremental.IncrementalDataLoaderParamsParcel;
-import android.content.pm.IDataLoaderStatusListener;
-
-/**
- * Binder service to receive calls from native Incremental Service and handle Java tasks such as
- * looking up data loader service package names, binding and talking to the data loader service.
- * @hide
- */
-interface IIncrementalServiceProxy {
- boolean prepareDataLoader(int mountId,
- in IncrementalFileSystemControlParcel control,
- in IncrementalDataLoaderParamsParcel params,
- in IDataLoaderStatusListener listener);
- boolean startDataLoader(int mountId);
- void showHealthBlockedUI(int mountId);
- void destroyDataLoader(int mountId);
- void newFileForDataLoader(int mountId, long inode, in byte[] metadata);
-}
diff --git a/core/java/android/os/incremental/IncrementalFileStorages.java b/core/java/android/os/incremental/IncrementalFileStorages.java
index 5bd0748b8d97..fb94fc9bd719 100644
--- a/core/java/android/os/incremental/IncrementalFileStorages.java
+++ b/core/java/android/os/incremental/IncrementalFileStorages.java
@@ -35,6 +35,7 @@ import static dalvik.system.VMRuntime.getInstructionSet;
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.content.pm.DataLoaderParams;
import android.content.pm.InstallationFile;
import android.os.IVold;
import android.os.RemoteException;
@@ -82,12 +83,12 @@ public final class IncrementalFileStorages {
public IncrementalFileStorages(@NonNull String packageName,
@NonNull File stageDir,
@NonNull IncrementalManager incrementalManager,
- @NonNull IncrementalDataLoaderParams incrementalDataLoaderParams) {
+ @NonNull DataLoaderParams dataLoaderParams) {
mPackageName = packageName;
mStageDir = stageDir;
mIncrementalManager = incrementalManager;
- if (incrementalDataLoaderParams.getPackageName().equals("local")) {
- final String incrementalPath = incrementalDataLoaderParams.getStaticArgs();
+ if (dataLoaderParams.getPackageName().equals("local")) {
+ final String incrementalPath = dataLoaderParams.getStaticArgs();
mDefaultStorage = mIncrementalManager.openStorage(incrementalPath);
mDefaultDir = incrementalPath;
return;
@@ -97,7 +98,7 @@ public final class IncrementalFileStorages {
return;
}
mDefaultStorage = mIncrementalManager.createStorage(mDefaultDir,
- incrementalDataLoaderParams,
+ dataLoaderParams,
IncrementalManager.CREATE_MODE_CREATE
| IncrementalManager.CREATE_MODE_TEMPORARY_BIND, false);
}
@@ -265,7 +266,7 @@ public final class IncrementalFileStorages {
}
private String getTempDir() {
- final String tmpDirRoot = "/data/tmp";
+ final String tmpDirRoot = "/data/incremental/tmp";
final Random random = new Random();
final Path tmpDir =
Paths.get(tmpDirRoot, String.valueOf(random.nextInt(Integer.MAX_VALUE - 1)));
diff --git a/core/java/android/os/incremental/IncrementalManager.java b/core/java/android/os/incremental/IncrementalManager.java
index 5aabf86e17e6..c72228708b4c 100644
--- a/core/java/android/os/incremental/IncrementalManager.java
+++ b/core/java/android/os/incremental/IncrementalManager.java
@@ -21,6 +21,7 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemService;
import android.content.Context;
+import android.content.pm.DataLoaderParams;
import android.os.RemoteException;
import android.system.ErrnoException;
import android.system.Os;
@@ -36,31 +37,28 @@ import java.nio.file.Path;
import java.nio.file.Paths;
/**
- * Provides operations to open or create an IncrementalStorage, using IIncrementalManager service.
- * Example Usage:
+ * Provides operations to open or create an IncrementalStorage, using IIncrementalManagerNative
+ * service. Example Usage:
*
* <blockquote><pre>
- * IncrementalManager manager = (IncrementalManager) getSystemService(Context.INCREMENTAL_MANAGER);
+ * IncrementalManager manager = (IncrementalManager) getSystemService(Context.INCREMENTAL_SERVICE);
* IncrementalStorage storage = manager.openStorage("/path/to/incremental/dir");
* </pre></blockquote>
*
* @hide
*/
@SystemService(Context.INCREMENTAL_SERVICE)
-public class IncrementalManager {
+public final class IncrementalManager {
private static final String TAG = "IncrementalManager";
- private final IIncrementalManager mService;
- @GuardedBy("mStorages")
- private final SparseArray<IncrementalStorage> mStorages = new SparseArray<>();
public static final int CREATE_MODE_TEMPORARY_BIND =
- IIncrementalManager.CREATE_MODE_TEMPORARY_BIND;
+ IIncrementalManagerNative.CREATE_MODE_TEMPORARY_BIND;
public static final int CREATE_MODE_PERMANENT_BIND =
- IIncrementalManager.CREATE_MODE_PERMANENT_BIND;
+ IIncrementalManagerNative.CREATE_MODE_PERMANENT_BIND;
public static final int CREATE_MODE_CREATE =
- IIncrementalManager.CREATE_MODE_CREATE;
+ IIncrementalManagerNative.CREATE_MODE_CREATE;
public static final int CREATE_MODE_OPEN_EXISTING =
- IIncrementalManager.CREATE_MODE_OPEN_EXISTING;
+ IIncrementalManagerNative.CREATE_MODE_OPEN_EXISTING;
@Retention(RetentionPolicy.SOURCE)
@IntDef(prefix = {"CREATE_MODE_"}, value = {
@@ -72,8 +70,12 @@ public class IncrementalManager {
public @interface CreateMode {
}
- public IncrementalManager(@NonNull IIncrementalManager is) {
- mService = is;
+ private final @Nullable IIncrementalManagerNative mNativeService;
+ @GuardedBy("mStorages")
+ private final SparseArray<IncrementalStorage> mStorages = new SparseArray<>();
+
+ public IncrementalManager(IIncrementalManagerNative nativeService) {
+ mNativeService = nativeService;
}
/**
@@ -82,6 +84,7 @@ public class IncrementalManager {
* @param storageId The storage ID to identify the storage object.
* @return IncrementalStorage object corresponding to storage ID.
*/
+ // TODO(b/136132412): remove this
@Nullable
public IncrementalStorage getStorage(int storageId) {
synchronized (mStorages) {
@@ -95,21 +98,21 @@ public class IncrementalManager {
*
* @param path Absolute path to mount Incremental File System on.
* @param params IncrementalDataLoaderParams object to configure data loading.
- * @param createMode Mode for opening an old Incremental File System mount or
- * creating a new mount.
+ * @param createMode Mode for opening an old Incremental File System mount or creating
+ * a new mount.
* @param autoStartDataLoader Set true to immediately start data loader after creating storage.
* @return IncrementalStorage object corresponding to the mounted directory.
*/
@Nullable
public IncrementalStorage createStorage(@NonNull String path,
- @NonNull IncrementalDataLoaderParams params, @CreateMode int createMode,
+ @NonNull DataLoaderParams params, @CreateMode int createMode,
boolean autoStartDataLoader) {
try {
- final int id = mService.createStorage(path, params.getData(), createMode);
+ final int id = mNativeService.createStorage(path, params.getData(), createMode);
if (id < 0) {
return null;
}
- final IncrementalStorage storage = new IncrementalStorage(mService, id);
+ final IncrementalStorage storage = new IncrementalStorage(mNativeService, id);
synchronized (mStorages) {
mStorages.put(id, storage);
}
@@ -123,8 +126,8 @@ public class IncrementalManager {
}
/**
- * Opens an existing Incremental File System mounted directory and returns an
- * IncrementalStorage object.
+ * Opens an existing Incremental File System mounted directory and returns an IncrementalStorage
+ * object.
*
* @param path Absolute target path that Incremental File System has been mounted on.
* @return IncrementalStorage object corresponding to the mounted directory.
@@ -132,11 +135,11 @@ public class IncrementalManager {
@Nullable
public IncrementalStorage openStorage(@NonNull String path) {
try {
- final int id = mService.openStorage(path);
+ final int id = mNativeService.openStorage(path);
if (id < 0) {
return null;
}
- final IncrementalStorage storage = new IncrementalStorage(mService, id);
+ final IncrementalStorage storage = new IncrementalStorage(mNativeService, id);
synchronized (mStorages) {
mStorages.put(id, storage);
}
@@ -155,11 +158,12 @@ public class IncrementalManager {
public IncrementalStorage createStorage(@NonNull String path,
@NonNull IncrementalStorage linkedStorage, @CreateMode int createMode) {
try {
- final int id = mService.createLinkedStorage(path, linkedStorage.getId(), createMode);
+ final int id = mNativeService.createLinkedStorage(
+ path, linkedStorage.getId(), createMode);
if (id < 0) {
return null;
}
- final IncrementalStorage storage = new IncrementalStorage(mService, id);
+ final IncrementalStorage storage = new IncrementalStorage(mNativeService, id);
synchronized (mStorages) {
mStorages.put(id, storage);
}
@@ -175,6 +179,7 @@ public class IncrementalManager {
* @param file Target file to search storage for.
* @return Absolute path which is a bind-mount point of Incremental File System.
*/
+ @Nullable
private Path getStoragePathForFile(File file) {
File currentPath = new File(file.getParent());
while (currentPath.getParent() != null) {
@@ -198,18 +203,19 @@ public class IncrementalManager {
* </li>
* </ol>
*
- * @param sourcePath Absolute path to the source. Should be the same type as the destPath
- * (file or dir). Expected to already exist and is an Incremental path.
- * @param destPath Absolute path to the destination.
- * @throws IllegalArgumentException when 1) source does not exist,
- * or 2) source and dest type mismatch (one is file and the other is dir),
- * or 3) source path is not on Incremental File System,
- * @throws IOException when 1) cannot find the root path of the Incremental storage of source,
- * or 2) cannot retrieve the Incremental storage instance of the source,
- * or 3) renaming a file, but dest is not on the same Incremental Storage,
- * or 4) renaming a dir, dest dir does not exist but fails to be created.
- *
- * TODO(b/136132412): add unit tests
+ * @param sourcePath Absolute path to the source. Should be the same type as the destPath (file
+ * or dir). Expected to already exist and is an Incremental path.
+ * @param destPath Absolute path to the destination.
+ * @throws IllegalArgumentException when 1) source does not exist, or 2) source and dest type
+ * mismatch (one is file and the other is dir), or 3) source
+ * path is not on Incremental File System,
+ * @throws IOException when 1) cannot find the root path of the Incremental storage
+ * of source, or 2) cannot retrieve the Incremental storage
+ * instance of the source, or 3) renaming a file, but dest is
+ * not on the same Incremental Storage, or 4) renaming a dir,
+ * dest dir does not exist but fails to be created.
+ * <p>
+ * TODO(b/136132412): add unit tests
*/
public void rename(@NonNull String sourcePath, @NonNull String destPath) throws IOException {
final File source = new File(sourcePath);
@@ -243,6 +249,7 @@ public class IncrementalManager {
if (storage == null) {
throw new IOException("Failed to retrieve storage from Incremental Service.");
}
+
if (source.isFile()) {
renameFile(storage, storagePath, source, dest);
} else {
@@ -304,11 +311,11 @@ public class IncrementalManager {
*/
public void closeStorage(@NonNull String path) {
try {
- final int id = mService.openStorage(path);
+ final int id = mNativeService.openStorage(path);
if (id < 0) {
return;
}
- mService.deleteStorage(id);
+ mNativeService.deleteStorage(id);
synchronized (mStorages) {
mStorages.remove(id);
}
@@ -321,7 +328,7 @@ public class IncrementalManager {
* Checks if path is mounted on Incremental File System.
*/
public static boolean isIncrementalPath(@NonNull String path) {
- // TODO(b/136132412): implement native method
+ // TODO(b/136132412): add jni implementation
return false;
}
}
diff --git a/core/java/android/os/incremental/IncrementalStorage.java b/core/java/android/os/incremental/IncrementalStorage.java
index 2bf89ed7f7e8..275086832c51 100644
--- a/core/java/android/os/incremental/IncrementalStorage.java
+++ b/core/java/android/os/incremental/IncrementalStorage.java
@@ -24,11 +24,11 @@ import java.io.File;
import java.io.IOException;
/**
- * Provides operations on an Incremental File System directory, using IncrementalService. Example
- * usage:
+ * Provides operations on an Incremental File System directory, using IncrementalServiceNative.
+ * Example usage:
*
* <blockquote><pre>
- * IncrementalManager manager = (IncrementalManager) getSystemService(Context.INCREMENTAL_MANAGER);
+ * IncrementalManager manager = (IncrementalManager) getSystemService(Context.INCREMENTAL_SERVICE);
* IncrementalStorage storage = manager.openStorage("/path/to/incremental/dir");
* storage.makeDirectory("subdir");
* </pre></blockquote>
@@ -38,10 +38,10 @@ import java.io.IOException;
public final class IncrementalStorage {
private static final String TAG = "IncrementalStorage";
private final int mId;
- private final IIncrementalManager mService;
+ private final IIncrementalManagerNative mService;
- public IncrementalStorage(@NonNull IIncrementalManager is, int id) {
+ public IncrementalStorage(@NonNull IIncrementalManagerNative is, int id) {
mService = is;
mId = id;
}
@@ -72,7 +72,7 @@ public final class IncrementalStorage {
throws IOException {
try {
int res = mService.makeBindMount(mId, sourcePathUnderStorage, targetPath,
- IIncrementalManager.BIND_TEMPORARY);
+ IIncrementalManagerNative.BIND_TEMPORARY);
if (res < 0) {
throw new IOException("bind() failed with errno " + -res);
}
@@ -103,7 +103,7 @@ public final class IncrementalStorage {
throws IOException {
try {
int res = mService.makeBindMount(mId, sourcePathUnderStorage, targetPath,
- IIncrementalManager.BIND_PERMANENT);
+ IIncrementalManagerNative.BIND_PERMANENT);
if (res < 0) {
throw new IOException("bind() permanent failed with errno " + -res);
}
@@ -274,7 +274,8 @@ public final class IncrementalStorage {
throw new IOException("moveDir() requires that destination dir already exists.");
}
try {
- int res = mService.makeBindMount(mId, "", destPath, IIncrementalManager.BIND_PERMANENT);
+ int res = mService.makeBindMount(mId, "", destPath,
+ IIncrementalManagerNative.BIND_PERMANENT);
if (res < 0) {
throw new IOException("moveDir() failed at making bind mount, errno " + -res);
}
diff --git a/core/java/android/util/StatsEvent.aidl b/core/java/android/os/storage/CrateInfo.aidl
index deac873b0a04..dd910532c0a7 100644
--- a/core/java/android/util/StatsEvent.aidl
+++ b/core/java/android/os/storage/CrateInfo.aidl
@@ -1,11 +1,11 @@
-/**
- * Copyright (c) 2019, The Android Open Source Project
+/*
+ * Copyright (C) 2019 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
+ * 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,
@@ -13,7 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+package android.os.storage;
-package android.util;
-
-parcelable StatsEvent cpp_header "android/util/StatsEvent.h";
+/**
+ * @hide
+ */
+parcelable CrateInfo;
diff --git a/core/java/android/os/storage/CrateInfo.java b/core/java/android/os/storage/CrateInfo.java
new file mode 100644
index 000000000000..418d39e0c495
--- /dev/null
+++ b/core/java/android/os/storage/CrateInfo.java
@@ -0,0 +1,282 @@
+/*
+ * Copyright (C) 2019 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.os.storage;
+
+import android.annotation.CurrentTimeMillisLong;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.TestApi;
+import android.app.usage.StorageStatsManager;
+import android.content.Context;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.os.UserHandle;
+import android.text.TextUtils;
+
+import com.android.internal.util.Preconditions;
+
+import java.util.UUID;
+
+/**
+ * The CrateInfo describe the crate information.
+ * <p>
+ * It describe the following items.
+ * <ul>
+ * <li>The crate id that is the name of the child directory in
+ * {@link Context#getCrateDir(String)}</li>
+ * <li>Label to provide human readable text for the users.</li>
+ * <li>Expiration information. When the crate is expired and the run .</li>
+ *
+ * </ul>for the directory
+ * </p>
+ * @hide
+ */
+@TestApi
+public final class CrateInfo implements Parcelable {
+ private static final String TAG = "CrateInfo";
+
+ /**
+ * The following member fields whose value are set by apps and retrieved by system_server.
+ */
+ private CharSequence mLabel;
+ @CurrentTimeMillisLong
+ private long mExpiration;
+
+ /**
+ * The following member fields whose value are retrieved by installd.
+ * <p>{@link android.app.usage.StorageStatsManager#queryCratesForUser(UUID, UserHandle)} query
+ * all of crates for the specified UserHandle. That means the return crate list whose elements
+ * may have the same userId but different package name. Each crate needs the information to tell
+ * the caller from where package comes.
+ * </p>
+ */
+ private int mUid;
+
+ /**
+ * The following member fields whose value are retrieved by installd.
+ * <p>Both {@link StorageStatsManager#queryCratesForUid(UUID, int)} and
+ * {@link android.app.usage.StorageStatsManager#queryCratesForUser(UUID, UserHandle)} query
+ * all of crates for the specified uid or userId. That means the return crate list whose
+ * elements may have the same uid or userId but different package name. Each crate needs the
+ * information to tell the caller from where package comes.
+ * </p>
+ */
+ @Nullable
+ private String mPackageName;
+
+ /**
+ * The following member fields whose value are retrieved by system_server.
+ * <p>
+ * The child directories in {@link Context#getCrateDir(String)} are crates. Each directories
+ * is a crate. The folder name is the crate id.
+ * </p><p>
+ * Can't apply check if the path is validated or not because it need pass through the
+ * parcel.
+ * </p>
+ */
+ @Nullable
+ private String mId;
+
+ private CrateInfo() {
+ mExpiration = 0;
+ }
+
+ /**
+ * To create the crateInfo by passing validated label.
+ * @param label a display name for the crate
+ * @param expiration It's positive integer. if current time is larger than the expiration, the
+ * files under this crate will be considered to be deleted. Default value is 0.
+ * @throws IllegalArgumentException cause IllegalArgumentException when label is null
+ * or empty string
+ */
+ public CrateInfo(@NonNull CharSequence label, @CurrentTimeMillisLong long expiration) {
+ Preconditions.checkStringNotEmpty(label,
+ "Label should not be either null or empty string");
+ Preconditions.checkArgumentNonnegative(expiration,
+ "Expiration should be non negative number");
+
+ mLabel = label;
+ mExpiration = expiration;
+ }
+
+ /**
+ * To create the crateInfo by passing validated label.
+ * @param label a display name for the crate
+ * @throws IllegalArgumentException cause IllegalArgumentException when label is null
+ * or empty string
+ */
+ public CrateInfo(@NonNull CharSequence label) {
+ this(label, 0);
+ }
+
+ /**
+ * To get the meaningful text of the crate for the users.
+ * @return the meaningful text
+ */
+ @NonNull
+ public CharSequence getLabel() {
+ if (TextUtils.isEmpty(mLabel)) {
+ return mId;
+ }
+ return mLabel;
+ }
+
+
+ /**
+ * To return the expiration time.
+ * <p>
+ * If the current time is larger than expiration time, the crate files are considered to be
+ * deleted.
+ * </p>
+ * @return the expiration time
+ */
+ @CurrentTimeMillisLong
+ public long getExpirationMillis() {
+ return mExpiration;
+ }
+
+ /**
+ * To set the expiration time.
+ * @param expiration the expiration time
+ * @hide
+ */
+ public void setExpiration(@CurrentTimeMillisLong long expiration) {
+ Preconditions.checkArgumentNonnegative(expiration);
+ mExpiration = expiration;
+ }
+
+ @Override
+ public int hashCode() {
+ return super.hashCode();
+ }
+
+ /**
+ * To compare with crateinfo when selves' mId is validated.
+ * <p>The validated crateinfo.mId must be validated the following items.
+ * <ul>
+ * <li>mId is not null</li>
+ * <li>mId is not empty string</li>
+ * </ul>
+ * </p>
+ * @param obj the reference object with which to compare.
+ * @return true when selves's mId is validated and equal to crateinfo.mId.
+ */
+ @Override
+ public boolean equals(@Nullable Object obj) {
+ if (obj == null) {
+ return false;
+ }
+
+ if (obj instanceof CrateInfo) {
+ CrateInfo crateInfo = (CrateInfo) obj;
+ if (!TextUtils.isEmpty(mId)
+ && TextUtils.equals(mId, crateInfo.mId)) {
+ return true;
+ }
+ }
+
+ return super.equals(obj);
+ }
+
+
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(@Nullable Parcel dest, int flags) {
+ if (dest == null) {
+ return;
+ }
+
+ dest.writeCharSequence(mLabel);
+ dest.writeLong(mExpiration);
+
+ dest.writeInt(mUid);
+ dest.writeString(mPackageName);
+ dest.writeString(mId);
+ }
+
+ /**
+ * To read the data from parcel.
+ * <p>
+ * It's called by StorageStatsService.
+ * </p>
+ * @hide
+ */
+ public void readFromParcel(@Nullable Parcel in) {
+ if (in == null) {
+ return;
+ }
+
+ mLabel = in.readCharSequence();
+ mExpiration = in.readLong();
+
+ mUid = in.readInt();
+ mPackageName = in.readString();
+ mId = in.readString();
+ }
+
+ @NonNull
+ public static final Creator<CrateInfo> CREATOR = new Creator<CrateInfo>() {
+ @NonNull
+ @Override
+ public CrateInfo createFromParcel(@NonNull Parcel in) {
+ CrateInfo crateInfo = new CrateInfo();
+ crateInfo.readFromParcel(in);
+ return crateInfo;
+ }
+
+ @NonNull
+ @Override
+ public CrateInfo[] newArray(int size) {
+ return new CrateInfo[size];
+ }
+ };
+
+ /**
+ * To copy the information from service into crateinfo.
+ * <p>
+ * This function is called in system_server. The copied information includes
+ * <ul>
+ * <li>uid</li>
+ * <li>package name</li>
+ * <li>crate id</li>
+ * </ul>
+ * </p>
+ * @param uid the uid that the crate belong to
+ * @param packageName the package name that the crate belong to
+ * @param id the crate dir
+ * @return the CrateInfo instance
+ * @hide
+ */
+ @TestApi
+ @Nullable
+ public static CrateInfo copyFrom(int uid, @Nullable String packageName, @Nullable String id) {
+ if (!UserHandle.isApp(uid) || TextUtils.isEmpty(packageName) || TextUtils.isEmpty(id)) {
+ return null;
+ }
+
+ CrateInfo crateInfo = new CrateInfo(id /* default label = id */, 0);
+ crateInfo.mUid = uid;
+ crateInfo.mPackageName = packageName;
+ crateInfo.mId = id;
+ return crateInfo;
+ }
+}
diff --git a/core/java/android/os/storage/DiskInfo.java b/core/java/android/os/storage/DiskInfo.java
index b797324c8007..df3c4d55d979 100644
--- a/core/java/android/os/storage/DiskInfo.java
+++ b/core/java/android/os/storage/DiskInfo.java
@@ -18,7 +18,7 @@ package android.os.storage;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.res.Resources;
import android.os.Build;
import android.os.Parcel;
diff --git a/core/java/android/os/storage/StorageEventListener.java b/core/java/android/os/storage/StorageEventListener.java
index 39d5b4529745..9fd9e4e4067d 100644
--- a/core/java/android/os/storage/StorageEventListener.java
+++ b/core/java/android/os/storage/StorageEventListener.java
@@ -16,7 +16,7 @@
package android.os.storage;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/**
* Used for receiving notifications from the StorageManager
diff --git a/core/java/android/os/storage/StorageManager.java b/core/java/android/os/storage/StorageManager.java
index 2d70986dddee..8959fcf7ac18 100644
--- a/core/java/android/os/storage/StorageManager.java
+++ b/core/java/android/os/storage/StorageManager.java
@@ -40,12 +40,12 @@ import android.annotation.SuppressLint;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.WorkerThread;
import android.app.Activity;
import android.app.ActivityThread;
import android.app.AppGlobals;
import android.app.AppOpsManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
@@ -80,6 +80,7 @@ import android.system.Os;
import android.system.OsConstants;
import android.text.TextUtils;
import android.util.DataUnit;
+import android.util.FeatureFlagUtils;
import android.util.Log;
import android.util.Pair;
import android.util.Slog;
@@ -156,7 +157,8 @@ public class StorageManager {
/** {@hide} */
public static final String PROP_FUSE = "persist.sys.fuse";
/** {@hide} */
- public static final String PROP_FUSE_SNAPSHOT = "sys.fuse_snapshot";
+ public static final String PROP_SETTINGS_FUSE = FeatureFlagUtils.PERSIST_PREFIX
+ + FeatureFlagUtils.SETTINGS_FUSE_FLAG;
/** {@hide} */
@@ -262,6 +264,8 @@ public class StorageManager {
public static final int FLAG_REAL_STATE = 1 << 9;
/** {@hide} */
public static final int FLAG_INCLUDE_INVISIBLE = 1 << 10;
+ /** {@hide} */
+ public static final int FLAG_INCLUDE_RECENT = 1 << 11;
/** {@hide} */
public static final int FSTRIM_FLAG_DEEP = IVold.FSTRIM_FLAG_DEEP_TRIM;
@@ -1123,7 +1127,7 @@ public class StorageManager {
* Return the {@link StorageVolume} that contains the given file, or
* {@code null} if none.
*/
- public @Nullable StorageVolume getStorageVolume(File file) {
+ public @Nullable StorageVolume getStorageVolume(@NonNull File file) {
return getStorageVolume(getVolumeList(), file);
}
@@ -1138,7 +1142,7 @@ public class StorageManager {
return getPrimaryStorageVolume();
default:
for (StorageVolume vol : getStorageVolumes()) {
- if (Objects.equals(vol.getNormalizedUuid(), volumeName)) {
+ if (Objects.equals(vol.getMediaStoreVolumeName(), volumeName)) {
return vol;
}
}
@@ -1199,12 +1203,13 @@ public class StorageManager {
}
/**
- * Return the list of shared/external storage volumes available to the
- * current user. This includes both the primary shared storage device and
- * any attached external volumes including SD cards and USB drives.
- *
- * @see Environment#getExternalStorageDirectory()
- * @see StorageVolume#createAccessIntent(String)
+ * Return the list of shared/external storage volumes currently available to
+ * the calling user.
+ * <p>
+ * These storage volumes are actively attached to the device, but may be in
+ * any mount state, as returned by {@link StorageVolume#getState()}. Returns
+ * both the primary shared storage device and any attached external volumes,
+ * including SD cards and USB drives.
*/
public @NonNull List<StorageVolume> getStorageVolumes() {
final ArrayList<StorageVolume> res = new ArrayList<>();
@@ -1214,6 +1219,22 @@ public class StorageManager {
}
/**
+ * Return the list of shared/external storage volumes both currently and
+ * recently available to the calling user.
+ * <p>
+ * Recently available storage volumes are likely to reappear in the future,
+ * so apps are encouraged to preserve any indexed metadata related to these
+ * volumes to optimize user experiences.
+ */
+ public @NonNull List<StorageVolume> getRecentStorageVolumes() {
+ final ArrayList<StorageVolume> res = new ArrayList<>();
+ Collections.addAll(res,
+ getVolumeList(mContext.getUserId(),
+ FLAG_REAL_STATE | FLAG_INCLUDE_INVISIBLE | FLAG_INCLUDE_RECENT));
+ return res;
+ }
+
+ /**
* Return the primary shared/external storage volume available to the
* current user. This volume is the same storage device returned by
* {@link Environment#getExternalStorageDirectory()} and
diff --git a/core/java/android/os/storage/StorageManagerInternal.java b/core/java/android/os/storage/StorageManagerInternal.java
index 14c299d11a94..5cac5f580af1 100644
--- a/core/java/android/os/storage/StorageManagerInternal.java
+++ b/core/java/android/os/storage/StorageManagerInternal.java
@@ -109,4 +109,13 @@ public abstract class StorageManagerInternal {
*/
public abstract void onAppOpsChanged(int code, int uid,
@Nullable String packageName, int mode);
+
+ /**
+ * Asks the StorageManager to reset all state for the provided user; this will result
+ * in the unmounting for all volumes of the user, and, if the user is still running, the
+ * volumes will be re-mounted as well.
+ *
+ * @param userId the userId for which to reset storage
+ */
+ public abstract void resetUser(int userId);
}
diff --git a/core/java/android/os/storage/StorageVolume.java b/core/java/android/os/storage/StorageVolume.java
index aefe8430f9de..2ab226f81bb4 100644
--- a/core/java/android/os/storage/StorageVolume.java
+++ b/core/java/android/os/storage/StorageVolume.java
@@ -19,7 +19,7 @@ package android.os.storage;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
@@ -29,6 +29,7 @@ import android.os.Parcel;
import android.os.Parcelable;
import android.os.UserHandle;
import android.provider.DocumentsContract;
+import android.provider.MediaStore;
import com.android.internal.util.IndentingPrintWriter;
import com.android.internal.util.Preconditions;
@@ -173,7 +174,7 @@ public final class StorageVolume implements Parcelable {
* @return the mount path
* @hide
*/
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.Q, publicAlternatives = "{@link StorageVolume#getDirectory()}")
@TestApi
public String getPath() {
return mPath.toString();
@@ -190,12 +191,35 @@ public final class StorageVolume implements Parcelable {
}
/** {@hide} */
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.Q, publicAlternatives = "{@link StorageVolume#getDirectory()}")
public File getPathFile() {
return mPath;
}
/**
+ * Returns the directory where this volume is currently mounted.
+ * <p>
+ * Direct filesystem access via this path has significant emulation
+ * overhead, and apps are instead strongly encouraged to interact with media
+ * on storage volumes via the {@link MediaStore} APIs.
+ * <p>
+ * This directory does not give apps any additional access beyond what they
+ * already have via {@link MediaStore}.
+ *
+ * @return directory where this volume is mounted, or {@code null} if the
+ * volume is not currently mounted.
+ */
+ public @Nullable File getDirectory() {
+ switch (mState) {
+ case Environment.MEDIA_MOUNTED:
+ case Environment.MEDIA_MOUNTED_READ_ONLY:
+ return mPath;
+ default:
+ return null;
+ }
+ }
+
+ /**
* Returns a user-visible description of the volume.
*
* @return the volume description
@@ -265,6 +289,24 @@ public final class StorageVolume implements Parcelable {
return mFsUuid;
}
+ /**
+ * Return the volume name that can be used to interact with this storage
+ * device through {@link MediaStore}.
+ *
+ * @return opaque volume name, or {@code null} if this volume is not indexed
+ * by {@link MediaStore}.
+ * @see android.provider.MediaStore.Audio.Media#getContentUri(String)
+ * @see android.provider.MediaStore.Video.Media#getContentUri(String)
+ * @see android.provider.MediaStore.Images.Media#getContentUri(String)
+ */
+ public @Nullable String getMediaStoreVolumeName() {
+ if (isPrimary()) {
+ return MediaStore.VOLUME_EXTERNAL_PRIMARY;
+ } else {
+ return getNormalizedUuid();
+ }
+ }
+
/** {@hide} */
public static @Nullable String normalizeUuid(@Nullable String fsUuid) {
return fsUuid != null ? fsUuid.toLowerCase(Locale.US) : null;
diff --git a/core/java/android/os/storage/VolumeInfo.java b/core/java/android/os/storage/VolumeInfo.java
index d6ec52fac8a5..fb9065568e9b 100644
--- a/core/java/android/os/storage/VolumeInfo.java
+++ b/core/java/android/os/storage/VolumeInfo.java
@@ -18,7 +18,7 @@ package android.os.storage;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
diff --git a/core/java/android/os/storage/VolumeRecord.java b/core/java/android/os/storage/VolumeRecord.java
index 1a794ebf2a59..60df9819f591 100644
--- a/core/java/android/os/storage/VolumeRecord.java
+++ b/core/java/android/os/storage/VolumeRecord.java
@@ -16,15 +16,19 @@
package android.os.storage;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
+import android.content.Context;
+import android.os.Environment;
import android.os.Parcel;
import android.os.Parcelable;
+import android.os.UserHandle;
import android.util.DebugUtils;
import android.util.TimeUtils;
import com.android.internal.util.IndentingPrintWriter;
import com.android.internal.util.Preconditions;
+import java.io.File;
import java.util.Locale;
import java.util.Objects;
@@ -92,6 +96,27 @@ public class VolumeRecord implements Parcelable {
return (userFlags & USER_FLAG_SNOOZED) != 0;
}
+ public StorageVolume buildStorageVolume(Context context) {
+ final String id = "unknown:" + fsUuid;
+ final File userPath = new File("/dev/null");
+ final File internalPath = new File("/dev/null");
+ final boolean primary = false;
+ final boolean removable = true;
+ final boolean emulated = false;
+ final boolean allowMassStorage = false;
+ final long maxFileSize = 0;
+ final UserHandle user = new UserHandle(UserHandle.USER_NULL);
+ final String envState = Environment.MEDIA_UNKNOWN;
+
+ String description = nickname;
+ if (description == null) {
+ description = context.getString(android.R.string.unknownName);
+ }
+
+ return new StorageVolume(id, userPath, internalPath, description, primary, removable,
+ emulated, allowMassStorage, maxFileSize, user, fsUuid, envState);
+ }
+
public void dump(IndentingPrintWriter pw) {
pw.println("VolumeRecord:");
pw.increaseIndent();
diff --git a/core/java/android/permission/PermissionControllerService.java b/core/java/android/permission/PermissionControllerService.java
index 8f765faa1a0b..f9146637c8cb 100644
--- a/core/java/android/permission/PermissionControllerService.java
+++ b/core/java/android/permission/PermissionControllerService.java
@@ -221,7 +221,7 @@ public abstract class PermissionControllerService extends Service {
* permission controller package.
*/
@BinderThread
- public void onUpdateUserSensitive() {
+ public void onUpdateUserSensitivePermissionFlags() {
throw new AbstractMethodError("Must be overridden in implementing class");
}
@@ -449,7 +449,7 @@ public abstract class PermissionControllerService extends Service {
public void updateUserSensitive(AndroidFuture callback) {
Preconditions.checkNotNull(callback, "callback cannot be null");
- onUpdateUserSensitive();
+ onUpdateUserSensitivePermissionFlags();
callback.complete(null);
}
};
diff --git a/core/java/android/preference/DialogPreference.java b/core/java/android/preference/DialogPreference.java
index 32511e9afbea..dfdb57c4e3f8 100644
--- a/core/java/android/preference/DialogPreference.java
+++ b/core/java/android/preference/DialogPreference.java
@@ -21,9 +21,9 @@ import android.annotation.CallSuper;
import android.annotation.DrawableRes;
import android.annotation.Nullable;
import android.annotation.StringRes;
-import android.annotation.UnsupportedAppUsage;
import android.app.AlertDialog;
import android.app.Dialog;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
diff --git a/core/java/android/preference/EditTextPreference.java b/core/java/android/preference/EditTextPreference.java
index 74c5e3e49d63..af6f18416870 100644
--- a/core/java/android/preference/EditTextPreference.java
+++ b/core/java/android/preference/EditTextPreference.java
@@ -17,7 +17,7 @@
package android.preference;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
diff --git a/core/java/android/preference/ListPreference.java b/core/java/android/preference/ListPreference.java
index 830de52576d8..0b648094150f 100644
--- a/core/java/android/preference/ListPreference.java
+++ b/core/java/android/preference/ListPreference.java
@@ -17,8 +17,8 @@
package android.preference;
import android.annotation.ArrayRes;
-import android.annotation.UnsupportedAppUsage;
import android.app.AlertDialog.Builder;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
diff --git a/core/java/android/preference/Preference.java b/core/java/android/preference/Preference.java
index e82e60dfe1c4..f508dda00c55 100644
--- a/core/java/android/preference/Preference.java
+++ b/core/java/android/preference/Preference.java
@@ -21,7 +21,7 @@ import android.annotation.DrawableRes;
import android.annotation.LayoutRes;
import android.annotation.Nullable;
import android.annotation.StringRes;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
diff --git a/core/java/android/preference/PreferenceActivity.java b/core/java/android/preference/PreferenceActivity.java
index 47509713d335..ae4a626cdd5d 100644
--- a/core/java/android/preference/PreferenceActivity.java
+++ b/core/java/android/preference/PreferenceActivity.java
@@ -19,13 +19,13 @@ package android.preference;
import android.animation.LayoutTransition;
import android.annotation.Nullable;
import android.annotation.StringRes;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.XmlRes;
import android.app.Fragment;
import android.app.FragmentBreadCrumbs;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ListActivity;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
diff --git a/core/java/android/preference/PreferenceFragment.java b/core/java/android/preference/PreferenceFragment.java
index d6c069f07d22..3f6e5051a3f8 100644
--- a/core/java/android/preference/PreferenceFragment.java
+++ b/core/java/android/preference/PreferenceFragment.java
@@ -17,10 +17,10 @@
package android.preference;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.XmlRes;
import android.app.Activity;
import android.app.Fragment;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
diff --git a/core/java/android/preference/PreferenceGroupAdapter.java b/core/java/android/preference/PreferenceGroupAdapter.java
index dcc5d4c58784..b263f5041fd6 100644
--- a/core/java/android/preference/PreferenceGroupAdapter.java
+++ b/core/java/android/preference/PreferenceGroupAdapter.java
@@ -16,7 +16,7 @@
package android.preference;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.preference.Preference.OnPreferenceChangeInternalListener;
diff --git a/core/java/android/preference/PreferenceManager.java b/core/java/android/preference/PreferenceManager.java
index f741bd686beb..9d3f349320ad 100644
--- a/core/java/android/preference/PreferenceManager.java
+++ b/core/java/android/preference/PreferenceManager.java
@@ -18,9 +18,9 @@ package android.preference;
import android.annotation.Nullable;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.XmlRes;
import android.app.Activity;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
diff --git a/core/java/android/preference/PreferenceScreen.java b/core/java/android/preference/PreferenceScreen.java
index a353dbc8af1b..01fe2f3f6b3a 100644
--- a/core/java/android/preference/PreferenceScreen.java
+++ b/core/java/android/preference/PreferenceScreen.java
@@ -16,8 +16,8 @@
package android.preference;
-import android.annotation.UnsupportedAppUsage;
import android.app.Dialog;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
diff --git a/core/java/android/preference/RingtonePreference.java b/core/java/android/preference/RingtonePreference.java
index 025aad0fcaac..c6d8c08c9141 100644
--- a/core/java/android/preference/RingtonePreference.java
+++ b/core/java/android/preference/RingtonePreference.java
@@ -16,7 +16,7 @@
package android.preference;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
diff --git a/core/java/android/preference/SeekBarDialogPreference.java b/core/java/android/preference/SeekBarDialogPreference.java
index 32ef82103f6c..46be12211fe4 100644
--- a/core/java/android/preference/SeekBarDialogPreference.java
+++ b/core/java/android/preference/SeekBarDialogPreference.java
@@ -16,7 +16,7 @@
package android.preference;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
diff --git a/core/java/android/preference/SeekBarPreference.java b/core/java/android/preference/SeekBarPreference.java
index 99ab9dbeb280..a2852bc2cce3 100644
--- a/core/java/android/preference/SeekBarPreference.java
+++ b/core/java/android/preference/SeekBarPreference.java
@@ -16,7 +16,7 @@
package android.preference;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Parcel;
diff --git a/core/java/android/preference/SeekBarVolumizer.java b/core/java/android/preference/SeekBarVolumizer.java
index 4dd9baba3e5f..0cdad9f8de93 100644
--- a/core/java/android/preference/SeekBarVolumizer.java
+++ b/core/java/android/preference/SeekBarVolumizer.java
@@ -17,8 +17,8 @@
package android.preference;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
import android.app.NotificationManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
diff --git a/core/java/android/preference/SwitchPreference.java b/core/java/android/preference/SwitchPreference.java
index 9dea1c829713..baa023e41aad 100644
--- a/core/java/android/preference/SwitchPreference.java
+++ b/core/java/android/preference/SwitchPreference.java
@@ -17,7 +17,7 @@
package android.preference;
import android.annotation.StringRes;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
diff --git a/core/java/android/preference/TwoStatePreference.java b/core/java/android/preference/TwoStatePreference.java
index bb771d721d83..5eb5d17d9bc8 100644
--- a/core/java/android/preference/TwoStatePreference.java
+++ b/core/java/android/preference/TwoStatePreference.java
@@ -17,7 +17,7 @@
package android.preference;
import android.annotation.StringRes;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
diff --git a/core/java/android/preference/VolumePreference.java b/core/java/android/preference/VolumePreference.java
index a2d5a2312047..6eb524a3886c 100644
--- a/core/java/android/preference/VolumePreference.java
+++ b/core/java/android/preference/VolumePreference.java
@@ -16,8 +16,8 @@
package android.preference;
-import android.annotation.UnsupportedAppUsage;
import android.app.Dialog;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Parcel;
diff --git a/core/java/android/print/PrintDocumentAdapter.java b/core/java/android/print/PrintDocumentAdapter.java
index d1b6efc70a2a..7ea5655169e9 100644
--- a/core/java/android/print/PrintDocumentAdapter.java
+++ b/core/java/android/print/PrintDocumentAdapter.java
@@ -16,7 +16,7 @@
package android.print;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
diff --git a/core/java/android/print/PrintJobInfo.java b/core/java/android/print/PrintJobInfo.java
index 25f383c09ad1..63f38f8a7b4c 100644
--- a/core/java/android/print/PrintJobInfo.java
+++ b/core/java/android/print/PrintJobInfo.java
@@ -23,7 +23,7 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.StringRes;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Bundle;
diff --git a/core/java/android/print/PrintManager.java b/core/java/android/print/PrintManager.java
index e1ede93a9ac5..9abce5d46ac6 100644
--- a/core/java/android/print/PrintManager.java
+++ b/core/java/android/print/PrintManager.java
@@ -22,9 +22,9 @@ import android.annotation.RequiresFeature;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
import android.app.Activity;
import android.app.Application.ActivityLifecycleCallbacks;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.IntentSender;
diff --git a/core/java/android/print/PrinterId.java b/core/java/android/print/PrinterId.java
index 42570c69650f..75ca7507450f 100644
--- a/core/java/android/print/PrinterId.java
+++ b/core/java/android/print/PrinterId.java
@@ -17,7 +17,7 @@
package android.print;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/provider/BaseColumns.java b/core/java/android/provider/BaseColumns.java
index 00c9e72df880..b216e2b7ed8d 100644
--- a/core/java/android/provider/BaseColumns.java
+++ b/core/java/android/provider/BaseColumns.java
@@ -16,13 +16,11 @@
package android.provider;
-import android.database.Cursor;
-
public interface BaseColumns {
/**
* The unique ID for a row.
*/
- @Column(Cursor.FIELD_TYPE_INTEGER)
+ // @Column(Cursor.FIELD_TYPE_INTEGER)
public static final String _ID = "_id";
/**
diff --git a/core/java/android/provider/Browser.java b/core/java/android/provider/Browser.java
index 30021b488dc5..afa7b80f58a0 100644
--- a/core/java/android/provider/Browser.java
+++ b/core/java/android/provider/Browser.java
@@ -16,10 +16,8 @@
package android.provider;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentResolver;
-import android.content.ContentUris;
-import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
@@ -30,8 +28,6 @@ import android.net.Uri;
import android.provider.BrowserContract.Bookmarks;
import android.provider.BrowserContract.Combined;
import android.provider.BrowserContract.History;
-import android.provider.BrowserContract.Searches;
-import android.util.Log;
import android.webkit.WebIconDatabase;
public class Browser {
diff --git a/core/java/android/provider/BrowserContract.java b/core/java/android/provider/BrowserContract.java
index 57dde6693001..5083b8b254ab 100644
--- a/core/java/android/provider/BrowserContract.java
+++ b/core/java/android/provider/BrowserContract.java
@@ -17,7 +17,7 @@
package android.provider;
import android.accounts.Account;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentProviderClient;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
diff --git a/core/java/android/provider/CalendarContract.java b/core/java/android/provider/CalendarContract.java
index 7285166cdd5f..9c6c92ace483 100644
--- a/core/java/android/provider/CalendarContract.java
+++ b/core/java/android/provider/CalendarContract.java
@@ -20,11 +20,11 @@ import android.annotation.NonNull;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.admin.DevicePolicyManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
diff --git a/core/java/android/provider/CallLog.java b/core/java/android/provider/CallLog.java
index 30db6382fcd6..a0e92b398c4e 100644
--- a/core/java/android/provider/CallLog.java
+++ b/core/java/android/provider/CallLog.java
@@ -17,7 +17,7 @@
package android.provider;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentValues;
diff --git a/core/java/android/provider/ContactsContract.java b/core/java/android/provider/ContactsContract.java
index f10e184ccf5a..e383a371eb41 100644
--- a/core/java/android/provider/ContactsContract.java
+++ b/core/java/android/provider/ContactsContract.java
@@ -17,12 +17,14 @@
package android.provider;
import android.accounts.Account;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.Activity;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentProviderClient;
@@ -2379,7 +2381,11 @@ public final class ContactsContract {
* This id is provided by its own data source, and can be used to backup metadata
* to the server.
* This should be unique within each set of account_name/account_type/data_set
+ *
+ * @deprecated This column is no longer supported as of Android version
+ * {@link android.os.Build.VERSION_CODES#R}.
*/
+ @Deprecated
public static final String BACKUP_ID = "backup_id";
/**
@@ -2443,7 +2449,11 @@ public final class ContactsContract {
* Flag indicating that a raw contact's metadata has changed, and its metadata
* needs to be synchronized by the server.
* <P>Type: INTEGER (boolean)</P>
+ *
+ * @deprecated This column is no longer supported as of Android version
+ * {@link android.os.Build.VERSION_CODES#R}.
*/
+ @Deprecated
public static final String METADATA_DIRTY = "metadata_dirty";
}
@@ -2902,6 +2912,44 @@ public final class ContactsContract {
}
/**
+ * The default value used for {@link #ACCOUNT_NAME} of raw contacts when they are inserted
+ * without a value for this column.
+ *
+ * <p>This account is used to identify contacts that are only stored locally in the
+ * contacts database instead of being associated with an {@link Account} managed by an
+ * installed application.
+ *
+ * <p>When this returns null then {@link #getLocalAccountType} will also return null and
+ * when it is non-null {@link #getLocalAccountType} will also return a non-null value.
+ */
+ @Nullable
+ public static String getLocalAccountName(@NonNull Context context) {
+ // config_rawContactsLocalAccountName is defined in
+ // platform/frameworks/base/core/res/res/values/config.xml
+ return TextUtils.nullIfEmpty(context.getString(
+ com.android.internal.R.string.config_rawContactsLocalAccountName));
+ }
+
+ /**
+ * The default value used for {@link #ACCOUNT_TYPE} of raw contacts when they are inserted
+ * without a value for this column.
+ *
+ * <p>This account is used to identify contacts that are only stored locally in the
+ * contacts database instead of being associated with an {@link Account} managed by an
+ * installed application.
+ *
+ * <p>When this returns null then {@link #getLocalAccountName} will also return null and
+ * when it is non-null {@link #getLocalAccountName} will also return a non-null value.
+ */
+ @Nullable
+ public static String getLocalAccountType(@NonNull Context context) {
+ // config_rawContactsLocalAccountType is defined in
+ // platform/frameworks/base/core/res/res/values/config.xml
+ return TextUtils.nullIfEmpty(context.getString(
+ com.android.internal.R.string.config_rawContactsLocalAccountType));
+ }
+
+ /**
* A sub-directory of a single raw contact that contains all of its
* {@link ContactsContract.Data} rows. To access this directory
* append {@link Data#CONTENT_DIRECTORY} to the raw contact URI.
@@ -4148,7 +4196,10 @@ public final class ContactsContract {
* Hash id on the data fields, used for backup and restore.
*
* @hide
+ * @deprecated This column is no longer supported as of Android version
+ * {@link android.os.Build.VERSION_CODES#R}.
*/
+ @Deprecated
public static final String HASH_ID = "hash_id";
/**
@@ -9455,7 +9506,10 @@ public final class ContactsContract {
/**
* @hide
+ * @deprecated These columns are no longer supported as of Android version
+ * {@link android.os.Build.VERSION_CODES#R}.
*/
+ @Deprecated
@SystemApi
protected interface MetadataSyncColumns {
@@ -9562,7 +9616,10 @@ public final class ContactsContract {
* from server before it is merged into other CP2 tables.
*
* @hide
+ * @deprecated These columns are no longer supported as of Android version
+ * {@link android.os.Build.VERSION_CODES#R}.
*/
+ @Deprecated
@SystemApi
public static final class MetadataSync implements BaseColumns, MetadataSyncColumns {
@@ -9598,7 +9655,10 @@ public final class ContactsContract {
/**
* @hide
+ * @deprecated These columns are no longer supported as of Android version
+ * {@link android.os.Build.VERSION_CODES#R}.
*/
+ @Deprecated
@SystemApi
protected interface MetadataSyncStateColumns {
@@ -9632,7 +9692,10 @@ public final class ContactsContract {
* sync state for a set of accounts.
*
* @hide
+ * @deprecated These columns are no longer supported as of Android version
+ * {@link android.os.Build.VERSION_CODES#R}.
*/
+ @Deprecated
@SystemApi
public static final class MetadataSyncState implements BaseColumns, MetadataSyncStateColumns {
diff --git a/core/java/android/provider/DeviceConfig.java b/core/java/android/provider/DeviceConfig.java
index abf34ca2d21a..6650cf23d611 100644
--- a/core/java/android/provider/DeviceConfig.java
+++ b/core/java/android/provider/DeviceConfig.java
@@ -40,6 +40,7 @@ import com.android.internal.annotations.GuardedBy;
import com.android.internal.util.Preconditions;
import java.util.Arrays;
+import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -349,6 +350,15 @@ public final class DeviceConfig {
public static final String NAMESPACE_PRIVACY = "privacy";
/**
+ * Namespace for biometrics related features
+ *
+ * @hide
+ */
+ @SystemApi
+ @TestApi
+ public static final String NAMESPACE_BIOMETRICS = "biometrics";
+
+ /**
* Permission related properties definitions.
*
* @hide
@@ -357,6 +367,13 @@ public final class DeviceConfig {
@TestApi
public static final String NAMESPACE_PERMISSIONS = "permissions";
+ /**
+ * Namespace for all widget related features.
+ *
+ * @hide
+ */
+ public static final String NAMESPACE_WIDGET = "widget";
+
private static final Object sLock = new Object();
@GuardedBy("sLock")
private static ArrayMap<OnPropertiesChangedListener, Pair<String, Executor>> sListeners =
@@ -571,11 +588,13 @@ public final class DeviceConfig {
* none or all of this update is picked up, but never only part of it.
*
* @param properties the complete set of properties to set for a specific namespace.
+ * @throws BadConfigException if the provided properties are banned by RescueParty.
+ * @return True if the values were set, false otherwise.
* @hide
*/
@SystemApi
@RequiresPermission(WRITE_DEVICE_CONFIG)
- public static boolean setProperties(@NonNull Properties properties) {
+ public static boolean setProperties(@NonNull Properties properties) throws BadConfigException {
ContentResolver contentResolver = ActivityThread.currentApplication().getContentResolver();
return Settings.Config.setStrings(contentResolver, properties.getNamespace(),
properties.mMap);
@@ -725,19 +744,19 @@ public final class DeviceConfig {
List<String> pathSegments = uri.getPathSegments();
// pathSegments(0) is "config"
final String namespace = pathSegments.get(1);
- Map<String, String> propertyMap = new ArrayMap<>();
+ Properties.Builder propBuilder = new Properties.Builder(namespace);
try {
Properties allProperties = getProperties(namespace);
for (int i = 2; i < pathSegments.size(); ++i) {
String key = pathSegments.get(i);
- propertyMap.put(key, allProperties.getString(key, null));
+ propBuilder.setString(key, allProperties.getString(key, null));
}
} catch (SecurityException e) {
// Silently failing to not crash binder or listener threads.
Log.e(TAG, "OnPropertyChangedListener update failed: permission violation.");
return;
}
- Properties properties = new Properties(namespace, propertyMap);
+ Properties properties = propBuilder.build();
synchronized (sLock) {
for (int i = 0; i < sListeners.size(); i++) {
@@ -792,6 +811,15 @@ public final class DeviceConfig {
}
/**
+ * Thrown by {@link #setProperties(Properties)} when a configuration is rejected. This
+ * happens if RescueParty has identified a bad configuration and reset the namespace.
+ *
+ * @hide
+ */
+ @SystemApi
+ public static class BadConfigException extends Exception {}
+
+ /**
* A mapping of properties to values, as well as a single namespace which they all belong to.
*
* @hide
@@ -801,6 +829,7 @@ public final class DeviceConfig {
public static class Properties {
private final String mNamespace;
private final HashMap<String, String> mMap;
+ private Set<String> mKeyset;
/**
* Create a mapping of properties to values and the namespace they belong to.
@@ -831,7 +860,10 @@ public final class DeviceConfig {
*/
@NonNull
public Set<String> getKeyset() {
- return mMap.keySet();
+ if (mKeyset == null) {
+ mKeyset = Collections.unmodifiableSet(mMap.keySet());
+ }
+ return mKeyset;
}
/**
@@ -926,5 +958,93 @@ public final class DeviceConfig {
return defaultValue;
}
}
+
+ /**
+ * Builder class for the construction of {@link Properties} objects.
+ */
+ public static final class Builder {
+ @NonNull
+ private final String mNamespace;
+ @NonNull
+ private final Map<String, String> mKeyValues = new HashMap<>();
+
+ /**
+ * Create a new Builders for the specified namespace.
+ * @param namespace non null namespace.
+ */
+ public Builder(@NonNull String namespace) {
+ mNamespace = namespace;
+ }
+
+ /**
+ * Add a new property with the specified key and value.
+ * @param name non null name of the property.
+ * @param value nullable string value of the property.
+ * @return this Builder object
+ */
+ @NonNull
+ public Builder setString(@NonNull String name, @Nullable String value) {
+ mKeyValues.put(name, value);
+ return this;
+ }
+
+ /**
+ * Add a new property with the specified key and value.
+ * @param name non null name of the property.
+ * @param value nullable string value of the property.
+ * @return this Builder object
+ */
+ @NonNull
+ public Builder setBoolean(@NonNull String name, boolean value) {
+ mKeyValues.put(name, Boolean.toString(value));
+ return this;
+ }
+
+ /**
+ * Add a new property with the specified key and value.
+ * @param name non null name of the property.
+ * @param value int value of the property.
+ * @return this Builder object
+ */
+ @NonNull
+ public Builder setInt(@NonNull String name, int value) {
+ mKeyValues.put(name, Integer.toString(value));
+ return this;
+ }
+
+ /**
+ * Add a new property with the specified key and value.
+ * @param name non null name of the property.
+ * @param value long value of the property.
+ * @return this Builder object
+ */
+ @NonNull
+ public Builder setLong(@NonNull String name, long value) {
+ mKeyValues.put(name, Long.toString(value));
+ return this;
+ }
+
+ /**
+ * Add a new property with the specified key and value.
+ * @param name non null name of the property.
+ * @param value float value of the property.
+ * @return this Builder object
+ */
+ @NonNull
+ public Builder setFloat(@NonNull String name, float value) {
+ mKeyValues.put(name, Float.toString(value));
+ return this;
+ }
+
+ /**
+ * Create a new {@link Properties} object.
+ * @return non null Properties.
+ */
+ @NonNull
+ public Properties build() {
+ return new Properties(mNamespace, mKeyValues);
+ }
+ }
}
+
}
diff --git a/core/java/android/provider/MediaStore.java b/core/java/android/provider/MediaStore.java
index 2fa3386bccb8..63204d36f396 100644
--- a/core/java/android/provider/MediaStore.java
+++ b/core/java/android/provider/MediaStore.java
@@ -21,17 +21,16 @@ import android.annotation.CurrentTimeMillisLong;
import android.annotation.CurrentTimeSecondsLong;
import android.annotation.DurationMillisLong;
import android.annotation.IntDef;
-import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.RequiresPermission;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
+import android.annotation.SuppressLint;
import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.annotation.UnsupportedAppUsage;
import android.app.Activity;
-import android.app.AppGlobals;
+import android.app.PendingIntent;
import android.content.ClipData;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
@@ -44,39 +43,28 @@ import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageDecoder;
-import android.graphics.Point;
import android.graphics.PostProcessor;
import android.media.ExifInterface;
-import android.media.MediaFile;
import android.media.MediaFormat;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.Environment;
-import android.os.FileUtils;
import android.os.OperationCanceledException;
-import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
-import android.os.UserHandle;
-import android.os.UserManager;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
-import android.os.storage.VolumeInfo;
-import android.os.storage.VolumeRecord;
-import android.service.media.CameraPrewarmService;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.Log;
-
-import com.android.internal.annotations.GuardedBy;
+import android.util.Size;
import libcore.util.HexEncoding;
import java.io.File;
-import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
@@ -86,6 +74,7 @@ import java.lang.annotation.RetentionPolicy;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
@@ -160,44 +149,34 @@ public final class MediaStore {
/** {@hide} */
public static final String SCAN_VOLUME_CALL = "scan_volume";
/** {@hide} */
- public static final String SUICIDE_CALL = "suicide";
-
- /**
- * Extra used with {@link #SCAN_FILE_CALL} or {@link #SCAN_VOLUME_CALL} to indicate that
- * the file path originated from shell.
- *
- * {@hide}
- */
- public static final String EXTRA_ORIGINATED_FROM_SHELL =
- "android.intent.extra.originated_from_shell";
-
- /**
- * The method name used by the media scanner and mtp to tell the media provider to
- * rescan and reclassify that have become unhidden because of renaming folders or
- * removing nomedia files
- * @hide
- */
- @Deprecated
- public static final String UNHIDE_CALL = "unhide";
+ public static final String CREATE_WRITE_REQUEST_CALL = "create_write_request";
+ /** {@hide} */
+ public static final String CREATE_TRASH_REQUEST_CALL = "create_trash_request";
+ /** {@hide} */
+ public static final String CREATE_FAVORITE_REQUEST_CALL = "create_favorite_request";
+ /** {@hide} */
+ public static final String CREATE_DELETE_REQUEST_CALL = "create_delete_request";
- /**
- * The method name used by the media scanner service to reload all localized ringtone titles due
- * to a locale change.
- * @hide
- */
- public static final String RETRANSLATE_CALL = "update_titles";
/** {@hide} */
public static final String GET_VERSION_CALL = "get_version";
+
/** {@hide} */
public static final String GET_DOCUMENT_URI_CALL = "get_document_uri";
/** {@hide} */
public static final String GET_MEDIA_URI_CALL = "get_media_uri";
/** {@hide} */
- public static final String GET_CONTRIBUTED_MEDIA_CALL = "get_contributed_media";
+ public static final String EXTRA_URI = "uri";
/** {@hide} */
- public static final String DELETE_CONTRIBUTED_MEDIA_CALL = "delete_contributed_media";
+ public static final String EXTRA_URI_PERMISSIONS = "uriPermissions";
+
+ /** {@hide} */
+ public static final String EXTRA_CLIP_DATA = "clip_data";
+ /** {@hide} */
+ public static final String EXTRA_CONTENT_VALUES = "content_values";
+ /** {@hide} */
+ public static final String EXTRA_RESULT = "result";
/**
* This is for internal use by the media scanner only.
@@ -373,10 +352,10 @@ public final class MediaStore {
* service.
* <p>
* This meta-data should reference the fully qualified class name of the prewarm service
- * extending {@link CameraPrewarmService}.
+ * extending {@code CameraPrewarmService}.
* <p>
* The prewarm service will get bound and receive a prewarm signal
- * {@link CameraPrewarmService#onPrewarm()} when a camera launch intent fire might be imminent.
+ * {@code CameraPrewarmService#onPrewarm()} when a camera launch intent fire might be imminent.
* An application implementing a prewarm service should do the absolute minimum amount of work
* to initialize the camera in order to reduce startup time in likely case that shortly after a
* camera launch intent would be sent.
@@ -606,6 +585,10 @@ public final class MediaStore {
* {@link ContentResolver#delete}.
* <p>
* By default, trashed items are filtered away from operations.
+ *
+ * @see MediaColumns#IS_TRASHED
+ * @see MediaStore#QUERY_ARG_MATCH_TRASHED
+ * @see MediaStore#createTrashRequest
*/
@Match
public static final String QUERY_ARG_MATCH_TRASHED = "android:query-arg-match-trashed";
@@ -620,6 +603,10 @@ public final class MediaStore {
* <p>
* By default, favorite items are <em>not</em> filtered away from
* operations.
+ *
+ * @see MediaColumns#IS_FAVORITE
+ * @see MediaStore#QUERY_ARG_MATCH_FAVORITE
+ * @see MediaStore#createFavoriteRequest
*/
@Match
public static final String QUERY_ARG_MATCH_FAVORITE = "android:query-arg-match-favorite";
@@ -749,197 +736,6 @@ public final class MediaStore {
}
/**
- * Create a new pending media item using the given parameters. Pending items
- * are expected to have a short lifetime, and owners should either
- * {@link PendingSession#publish()} or {@link PendingSession#abandon()} a
- * pending item within a few hours after first creating it.
- *
- * @return token which can be passed to {@link #openPending(Context, Uri)}
- * to work with this pending item.
- * @see MediaColumns#IS_PENDING
- * @see MediaStore#setIncludePending(Uri)
- * @see MediaStore#createPending(Context, PendingParams)
- * @removed
- */
- @Deprecated
- public static @NonNull Uri createPending(@NonNull Context context,
- @NonNull PendingParams params) {
- return context.getContentResolver().insert(params.insertUri, params.insertValues);
- }
-
- /**
- * Open a pending media item to make progress on it. You can open a pending
- * item multiple times before finally calling either
- * {@link PendingSession#publish()} or {@link PendingSession#abandon()}.
- *
- * @param uri token which was previously returned from
- * {@link #createPending(Context, PendingParams)}.
- * @removed
- */
- @Deprecated
- public static @NonNull PendingSession openPending(@NonNull Context context, @NonNull Uri uri) {
- return new PendingSession(context, uri);
- }
-
- /**
- * Parameters that describe a pending media item.
- *
- * @removed
- */
- @Deprecated
- public static class PendingParams {
- /** {@hide} */
- public final Uri insertUri;
- /** {@hide} */
- public final ContentValues insertValues;
-
- /**
- * Create parameters that describe a pending media item.
- *
- * @param insertUri the {@code content://} Uri where this pending item
- * should be inserted when finally published. For example, to
- * publish an image, use
- * {@link MediaStore.Images.Media#getContentUri(String)}.
- */
- public PendingParams(@NonNull Uri insertUri, @NonNull String displayName,
- @NonNull String mimeType) {
- this.insertUri = Objects.requireNonNull(insertUri);
- final long now = System.currentTimeMillis() / 1000;
- this.insertValues = new ContentValues();
- this.insertValues.put(MediaColumns.DISPLAY_NAME, Objects.requireNonNull(displayName));
- this.insertValues.put(MediaColumns.MIME_TYPE, Objects.requireNonNull(mimeType));
- this.insertValues.put(MediaColumns.DATE_ADDED, now);
- this.insertValues.put(MediaColumns.DATE_MODIFIED, now);
- this.insertValues.put(MediaColumns.IS_PENDING, 1);
- this.insertValues.put(MediaColumns.DATE_EXPIRES,
- (System.currentTimeMillis() + DateUtils.DAY_IN_MILLIS) / 1000);
- }
-
- public void setRelativePath(@Nullable String relativePath) {
- if (relativePath == null) {
- this.insertValues.remove(MediaColumns.RELATIVE_PATH);
- } else {
- this.insertValues.put(MediaColumns.RELATIVE_PATH, relativePath);
- }
- }
-
- /**
- * Optionally set the Uri from where the file has been downloaded. This is used
- * for files being added to {@link Downloads} table.
- *
- * @see DownloadColumns#DOWNLOAD_URI
- */
- public void setDownloadUri(@Nullable Uri downloadUri) {
- if (downloadUri == null) {
- this.insertValues.remove(DownloadColumns.DOWNLOAD_URI);
- } else {
- this.insertValues.put(DownloadColumns.DOWNLOAD_URI, downloadUri.toString());
- }
- }
-
- /**
- * Optionally set the Uri indicating HTTP referer of the file. This is used for
- * files being added to {@link Downloads} table.
- *
- * @see DownloadColumns#REFERER_URI
- */
- public void setRefererUri(@Nullable Uri refererUri) {
- if (refererUri == null) {
- this.insertValues.remove(DownloadColumns.REFERER_URI);
- } else {
- this.insertValues.put(DownloadColumns.REFERER_URI, refererUri.toString());
- }
- }
- }
-
- /**
- * Session actively working on a pending media item. Pending items are
- * expected to have a short lifetime, and owners should either
- * {@link PendingSession#publish()} or {@link PendingSession#abandon()} a
- * pending item within a few hours after first creating it.
- *
- * @removed
- */
- @Deprecated
- public static class PendingSession implements AutoCloseable {
- /** {@hide} */
- private final Context mContext;
- /** {@hide} */
- private final Uri mUri;
-
- /** {@hide} */
- public PendingSession(Context context, Uri uri) {
- mContext = Objects.requireNonNull(context);
- mUri = Objects.requireNonNull(uri);
- }
-
- /**
- * Open the underlying file representing this media item. When a media
- * item is successfully completed, you should
- * {@link ParcelFileDescriptor#close()} and then {@link #publish()} it.
- *
- * @see #notifyProgress(int)
- */
- public @NonNull ParcelFileDescriptor open() throws FileNotFoundException {
- return mContext.getContentResolver().openFileDescriptor(mUri, "rw");
- }
-
- /**
- * Open the underlying file representing this media item. When a media
- * item is successfully completed, you should
- * {@link OutputStream#close()} and then {@link #publish()} it.
- *
- * @see #notifyProgress(int)
- */
- public @NonNull OutputStream openOutputStream() throws FileNotFoundException {
- return mContext.getContentResolver().openOutputStream(mUri);
- }
-
- /**
- * Notify of current progress on this pending media item. Gallery
- * applications may choose to surface progress information of this
- * pending item.
- *
- * @param progress a percentage between 0 and 100.
- */
- public void notifyProgress(@IntRange(from = 0, to = 100) int progress) {
- final Uri withProgress = mUri.buildUpon()
- .appendQueryParameter(PARAM_PROGRESS, Integer.toString(progress)).build();
- mContext.getContentResolver().notifyChange(withProgress, null, 0);
- }
-
- /**
- * When this media item is successfully completed, call this method to
- * publish and make the final item visible to the user.
- *
- * @return the final {@code content://} Uri representing the newly
- * published media.
- */
- public @NonNull Uri publish() {
- final ContentValues values = new ContentValues();
- values.put(MediaColumns.IS_PENDING, 0);
- values.putNull(MediaColumns.DATE_EXPIRES);
- mContext.getContentResolver().update(mUri, values, null, null);
- return mUri;
- }
-
- /**
- * When this media item has failed to be completed, call this method to
- * destroy the pending item record and any data related to it.
- */
- public void abandon() {
- mContext.getContentResolver().delete(mUri, null, null);
- }
-
- @Override
- public void close() {
- // No resources to close, but at least we can inform people that no
- // progress is being actively made.
- notifyProgress(-1);
- }
- }
-
- /**
* Mark the given item as being "trashed", meaning it should be deleted at
* some point in the future. This is a more gentle operation than simply
* calling {@link ContentResolver#delete(Uri, String, String[])}, which
@@ -952,7 +748,9 @@ public final class MediaStore {
* @see MediaStore#setIncludeTrashed(Uri)
* @see MediaStore#trash(Context, Uri)
* @see MediaStore#untrash(Context, Uri)
+ * @removed
*/
+ @Deprecated
public static void trash(@NonNull Context context, @NonNull Uri uri) {
trash(context, uri, 48 * DateUtils.HOUR_IN_MILLIS);
}
@@ -970,7 +768,9 @@ public final class MediaStore {
* @see MediaStore#setIncludeTrashed(Uri)
* @see MediaStore#trash(Context, Uri)
* @see MediaStore#untrash(Context, Uri)
+ * @removed
*/
+ @Deprecated
public static void trash(@NonNull Context context, @NonNull Uri uri,
@DurationMillisLong long timeoutMillis) {
if (timeoutMillis < 0) {
@@ -992,7 +792,9 @@ public final class MediaStore {
* @see MediaStore#setIncludeTrashed(Uri)
* @see MediaStore#trash(Context, Uri)
* @see MediaStore#untrash(Context, Uri)
+ * @removed
*/
+ @Deprecated
public static void untrash(@NonNull Context context, @NonNull Uri uri) {
final ContentValues values = new ContentValues();
values.put(MediaColumns.IS_TRASHED, 0);
@@ -1010,6 +812,180 @@ public final class MediaStore {
return uri.buildUpon().authority(MediaStore.AUTHORITY_LEGACY).build();
}
+ private static @NonNull PendingIntent createRequest(@NonNull ContentResolver resolver,
+ @NonNull String method, @NonNull Collection<Uri> uris, @Nullable ContentValues values) {
+ Objects.requireNonNull(resolver);
+ Objects.requireNonNull(uris);
+
+ final Iterator<Uri> it = uris.iterator();
+ final ClipData clipData = ClipData.newRawUri(null, it.next());
+ while (it.hasNext()) {
+ clipData.addItem(new ClipData.Item(it.next()));
+ }
+
+ final Bundle extras = new Bundle();
+ extras.putParcelable(EXTRA_CLIP_DATA, clipData);
+ extras.putParcelable(EXTRA_CONTENT_VALUES, values);
+ return resolver.call(AUTHORITY, method, null, extras).getParcelable(EXTRA_RESULT);
+ }
+
+ /**
+ * Create a {@link PendingIntent} that will prompt the user to grant your
+ * app write access for the requested media items.
+ * <p>
+ * This call only generates the request for a prompt; to display the prompt,
+ * call {@link Activity#startIntentSenderForResult} with
+ * {@link PendingIntent#getIntentSender()}. You can then determine if the
+ * user granted your request by testing for {@link Activity#RESULT_OK} in
+ * {@link Activity#onActivityResult}.
+ * <p>
+ * Permissions granted through this mechanism are tied to the lifecycle of
+ * the {@link Activity} that requests them. If you need to retain
+ * longer-term access for background actions, you can place items into a
+ * {@link ClipData} or {@link Intent} which can then be passed to
+ * {@link Context#startService} or
+ * {@link android.app.job.JobInfo.Builder#setClipData}. Be sure to include
+ * any relevant access modes you want to retain, such as
+ * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}.
+ * <p>
+ * The displayed prompt will reflect all the media items you're requesting,
+ * including those for which you already hold write access. If you want to
+ * determine if you already hold write access before requesting access, use
+ * {@code ContentResolver#checkUriPermission(Uri, int, int)} with
+ * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}.
+ * <p>
+ * For security and performance reasons this method does not support
+ * {@link Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION} or
+ * {@link Intent#FLAG_GRANT_PREFIX_URI_PERMISSION}.
+ *
+ * @param resolver Used to connect with {@link MediaStore#AUTHORITY}.
+ * Typically this value is {@link Context#getContentResolver()},
+ * but if you need more explicit lifecycle controls, you can
+ * obtain a {@link ContentProviderClient} and wrap it using
+ * {@link ContentResolver#wrap(ContentProviderClient)}.
+ * @param uris The set of media items to include in this request. Each item
+ * must be hosted by {@link MediaStore#AUTHORITY} and must
+ * reference a specific media item by {@link BaseColumns#_ID}.
+ */
+ public static @NonNull PendingIntent createWriteRequest(@NonNull ContentResolver resolver,
+ @NonNull Collection<Uri> uris) {
+ return createRequest(resolver, CREATE_WRITE_REQUEST_CALL, uris, null);
+ }
+
+ /**
+ * Create a {@link PendingIntent} that will prompt the user to trash the
+ * requested media items. When the user approves this request,
+ * {@link MediaColumns#IS_TRASHED} is set on these items.
+ * <p>
+ * This call only generates the request for a prompt; to display the prompt,
+ * call {@link Activity#startIntentSenderForResult} with
+ * {@link PendingIntent#getIntentSender()}. You can then determine if the
+ * user granted your request by testing for {@link Activity#RESULT_OK} in
+ * {@link Activity#onActivityResult}.
+ * <p>
+ * The displayed prompt will reflect all the media items you're requesting,
+ * including those for which you already hold write access. If you want to
+ * determine if you already hold write access before requesting access, use
+ * {@code ContentResolver#checkUriPermission(Uri, int, int)} with
+ * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}.
+ *
+ * @param resolver Used to connect with {@link MediaStore#AUTHORITY}.
+ * Typically this value is {@link Context#getContentResolver()},
+ * but if you need more explicit lifecycle controls, you can
+ * obtain a {@link ContentProviderClient} and wrap it using
+ * {@link ContentResolver#wrap(ContentProviderClient)}.
+ * @param uris The set of media items to include in this request. Each item
+ * must be hosted by {@link MediaStore#AUTHORITY} and must
+ * reference a specific media item by {@link BaseColumns#_ID}.
+ * @param value The {@link MediaColumns#IS_TRASHED} value to apply.
+ * @see MediaColumns#IS_TRASHED
+ * @see MediaStore#QUERY_ARG_MATCH_TRASHED
+ */
+ public static @NonNull PendingIntent createTrashRequest(@NonNull ContentResolver resolver,
+ @NonNull Collection<Uri> uris, boolean value) {
+ final ContentValues values = new ContentValues();
+ if (value) {
+ values.put(MediaColumns.IS_TRASHED, 1);
+ values.put(MediaColumns.DATE_EXPIRES,
+ (System.currentTimeMillis() + DateUtils.WEEK_IN_MILLIS) / 1000);
+ } else {
+ values.put(MediaColumns.IS_TRASHED, 0);
+ values.putNull(MediaColumns.DATE_EXPIRES);
+ }
+ return createRequest(resolver, CREATE_TRASH_REQUEST_CALL, uris, values);
+ }
+
+ /**
+ * Create a {@link PendingIntent} that will prompt the user to favorite the
+ * requested media items. When the user approves this request,
+ * {@link MediaColumns#IS_FAVORITE} is set on these items.
+ * <p>
+ * This call only generates the request for a prompt; to display the prompt,
+ * call {@link Activity#startIntentSenderForResult} with
+ * {@link PendingIntent#getIntentSender()}. You can then determine if the
+ * user granted your request by testing for {@link Activity#RESULT_OK} in
+ * {@link Activity#onActivityResult}.
+ * <p>
+ * The displayed prompt will reflect all the media items you're requesting,
+ * including those for which you already hold write access. If you want to
+ * determine if you already hold write access before requesting access, use
+ * {@code ContentResolver#checkUriPermission(Uri, int, int)} with
+ * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}.
+ *
+ * @param resolver Used to connect with {@link MediaStore#AUTHORITY}.
+ * Typically this value is {@link Context#getContentResolver()},
+ * but if you need more explicit lifecycle controls, you can
+ * obtain a {@link ContentProviderClient} and wrap it using
+ * {@link ContentResolver#wrap(ContentProviderClient)}.
+ * @param uris The set of media items to include in this request. Each item
+ * must be hosted by {@link MediaStore#AUTHORITY} and must
+ * reference a specific media item by {@link BaseColumns#_ID}.
+ * @param value The {@link MediaColumns#IS_FAVORITE} value to apply.
+ * @see MediaColumns#IS_FAVORITE
+ * @see MediaStore#QUERY_ARG_MATCH_FAVORITE
+ */
+ public static @NonNull PendingIntent createFavoriteRequest(@NonNull ContentResolver resolver,
+ @NonNull Collection<Uri> uris, boolean value) {
+ final ContentValues values = new ContentValues();
+ if (value) {
+ values.put(MediaColumns.IS_FAVORITE, 1);
+ } else {
+ values.put(MediaColumns.IS_FAVORITE, 0);
+ }
+ return createRequest(resolver, CREATE_FAVORITE_REQUEST_CALL, uris, values);
+ }
+
+ /**
+ * Create a {@link PendingIntent} that will prompt the user to permanently
+ * delete the requested media items. When the user approves this request,
+ * {@link ContentResolver#delete} will be called on these items.
+ * <p>
+ * This call only generates the request for a prompt; to display the prompt,
+ * call {@link Activity#startIntentSenderForResult} with
+ * {@link PendingIntent#getIntentSender()}. You can then determine if the
+ * user granted your request by testing for {@link Activity#RESULT_OK} in
+ * {@link Activity#onActivityResult}.
+ * <p>
+ * The displayed prompt will reflect all the media items you're requesting,
+ * including those for which you already hold write access. If you want to
+ * determine if you already hold write access before requesting access, use
+ * {@code ContentResolver#checkUriPermission(Uri, int, int)} with
+ * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}.
+ *
+ * @param resolver Used to connect with {@link MediaStore#AUTHORITY}.
+ * Typically this value is {@link Context#getContentResolver()},
+ * but if you need more explicit lifecycle controls, you can
+ * obtain a {@link ContentProviderClient} and wrap it using
+ * {@link ContentResolver#wrap(ContentProviderClient)}.
+ * @param uris The set of media items to include in this request. Each item
+ * must be hosted by {@link MediaStore#AUTHORITY} and must
+ * reference a specific media item by {@link BaseColumns#_ID}.
+ */
+ public static @NonNull PendingIntent createDeleteRequest(@NonNull ContentResolver resolver,
+ @NonNull Collection<Uri> uris) {
+ return createRequest(resolver, CREATE_DELETE_REQUEST_CALL, uris, null);
+ }
+
/**
* Common media metadata columns.
*/
@@ -1127,9 +1103,9 @@ public final class MediaStore {
* Trashed items are retained until they expire as defined by
* {@link #DATE_EXPIRES}.
*
+ * @see MediaColumns#IS_TRASHED
* @see MediaStore#QUERY_ARG_MATCH_TRASHED
- * @see MediaStore#trash(Context, Uri)
- * @see MediaStore#untrash(Context, Uri)
+ * @see MediaStore#createTrashRequest
*/
@Column(Cursor.FIELD_TYPE_INTEGER)
public static final String IS_TRASHED = "is_trashed";
@@ -1302,7 +1278,9 @@ public final class MediaStore {
* Flag indicating if the media item has been marked as being a
* "favorite" by the user.
*
+ * @see MediaColumns#IS_FAVORITE
* @see MediaStore#QUERY_ARG_MATCH_FAVORITE
+ * @see MediaStore#createFavoriteRequest
*/
@Column(Cursor.FIELD_TYPE_INTEGER)
public static final String IS_FAVORITE = "is_favorite";
@@ -1493,34 +1471,22 @@ public final class MediaStore {
return ContentUris.withAppendedId(getContentUri(volumeName), rowId);
}
- /**
- * For use only by the MTP implementation.
- * @hide
- */
+ /** {@hide} */
@UnsupportedAppUsage
- public static Uri getMtpObjectsUri(String volumeName) {
- return AUTHORITY_URI.buildUpon().appendPath(volumeName).appendPath("object").build();
+ public static Uri getMtpObjectsUri(@NonNull String volumeName) {
+ return MediaStore.Files.getContentUri(volumeName);
}
- /**
- * For use only by the MTP implementation.
- * @hide
- */
+ /** {@hide} */
@UnsupportedAppUsage
- public static final Uri getMtpObjectsUri(String volumeName,
- long fileId) {
- return ContentUris.withAppendedId(getMtpObjectsUri(volumeName), fileId);
+ public static final Uri getMtpObjectsUri(@NonNull String volumeName, long fileId) {
+ return MediaStore.Files.getContentUri(volumeName, fileId);
}
- /**
- * Used to implement the MTP GetObjectReferences and SetObjectReferences commands.
- * @hide
- */
+ /** {@hide} */
@UnsupportedAppUsage
- public static final Uri getMtpReferencesUri(String volumeName,
- long fileId) {
- return getMtpObjectsUri(volumeName, fileId).buildUpon().appendPath("references")
- .build();
+ public static final Uri getMtpReferencesUri(@NonNull String volumeName, long fileId) {
+ return MediaStore.Files.getContentUri(volumeName, fileId);
}
/**
@@ -1643,9 +1609,21 @@ public final class MediaStore {
public static final int FULL_SCREEN_KIND = 2;
public static final int MICRO_KIND = 3;
- public static final Point MINI_SIZE = new Point(512, 384);
- public static final Point FULL_SCREEN_SIZE = new Point(1024, 786);
- public static final Point MICRO_SIZE = new Point(96, 96);
+ public static final Size MINI_SIZE = new Size(512, 384);
+ public static final Size FULL_SCREEN_SIZE = new Size(1024, 786);
+ public static final Size MICRO_SIZE = new Size(96, 96);
+
+ public static @NonNull Size getKindSize(int kind) {
+ if (kind == ThumbnailConstants.MICRO_KIND) {
+ return ThumbnailConstants.MICRO_SIZE;
+ } else if (kind == ThumbnailConstants.FULL_SCREEN_KIND) {
+ return ThumbnailConstants.FULL_SCREEN_SIZE;
+ } else if (kind == ThumbnailConstants.MINI_KIND) {
+ return ThumbnailConstants.MINI_SIZE;
+ } else {
+ throw new IllegalArgumentException("Unsupported kind: " + kind);
+ }
+ }
}
/**
@@ -1749,22 +1727,22 @@ public final class MediaStore {
}
}
- /** {@hide} */
+ /**
+ * @deprecated since this method doesn't have a {@link Context}, we can't
+ * find the actual {@link StorageVolume} for the given path, so
+ * only a vague guess is returned. Callers should use
+ * {@link StorageManager#getStorageVolume(File)} instead.
+ * @hide
+ */
+ @Deprecated
public static @NonNull String getVolumeName(@NonNull File path) {
- if (FileUtils.contains(Environment.getStorageDirectory(), path)) {
- final StorageManager sm = AppGlobals.getInitialApplication()
- .getSystemService(StorageManager.class);
- final StorageVolume sv = sm.getStorageVolume(path);
- if (sv != null) {
- if (sv.isPrimary()) {
- return VOLUME_EXTERNAL_PRIMARY;
- } else {
- return checkArgumentVolumeName(sv.getNormalizedUuid());
- }
- }
- throw new IllegalStateException("Unknown volume at " + path);
+ // Ideally we'd find the relevant StorageVolume, but we don't have a
+ // Context to obtain it from, so the best we can do is assume
+ if (path.getAbsolutePath()
+ .startsWith(Environment.getStorageDirectory().getAbsolutePath())) {
+ return MediaStore.VOLUME_EXTERNAL;
} else {
- return VOLUME_INTERNAL;
+ return MediaStore.VOLUME_INTERNAL;
}
}
@@ -1777,7 +1755,7 @@ public final class MediaStore {
/**
* Currently outstanding thumbnail requests that can be cancelled.
*/
- @GuardedBy("sPending")
+ // @GuardedBy("sPending")
private static ArrayMap<Uri, CancellationSignal> sPending = new ArrayMap<>();
/**
@@ -1789,16 +1767,7 @@ public final class MediaStore {
@Deprecated
static @Nullable Bitmap getThumbnail(@NonNull ContentResolver cr, @NonNull Uri uri,
int kind, @Nullable BitmapFactory.Options opts) {
- final Point size;
- if (kind == ThumbnailConstants.MICRO_KIND) {
- size = ThumbnailConstants.MICRO_SIZE;
- } else if (kind == ThumbnailConstants.FULL_SCREEN_KIND) {
- size = ThumbnailConstants.FULL_SCREEN_SIZE;
- } else if (kind == ThumbnailConstants.MINI_KIND) {
- size = ThumbnailConstants.MINI_SIZE;
- } else {
- throw new IllegalArgumentException("Unsupported kind: " + kind);
- }
+ final Size size = ThumbnailConstants.getKindSize(kind);
CancellationSignal signal = null;
synchronized (sPending) {
@@ -1810,7 +1779,7 @@ public final class MediaStore {
}
try {
- return cr.loadThumbnail(uri, Point.convert(size), signal);
+ return cr.loadThumbnail(uri, size, signal);
} catch (IOException e) {
Log.w(TAG, "Failed to obtain thumbnail for " + uri, e);
return null;
@@ -2007,26 +1976,14 @@ public final class MediaStore {
@Deprecated
public static final String insertImage(ContentResolver cr, String imagePath,
String name, String description) throws FileNotFoundException {
- final File file = new File(imagePath);
- final String mimeType = MediaFile.getMimeTypeForFile(imagePath);
-
- if (TextUtils.isEmpty(name)) name = "Image";
- final PendingParams params = new PendingParams(
- MediaStore.Images.Media.EXTERNAL_CONTENT_URI, name, mimeType);
-
- final Context context = AppGlobals.getInitialApplication();
- final Uri pendingUri = createPending(context, params);
- try (PendingSession session = openPending(context, pendingUri)) {
- try (InputStream in = new FileInputStream(file);
- OutputStream out = session.openOutputStream()) {
- FileUtils.copy(in, out);
- }
- return session.publish().toString();
- } catch (Exception e) {
- Log.w(TAG, "Failed to insert image", e);
- context.getContentResolver().delete(pendingUri, null, null);
- return null;
+ final Bitmap source;
+ try {
+ source = ImageDecoder
+ .decodeBitmap(ImageDecoder.createSource(new File(imagePath)));
+ } catch (IOException e) {
+ throw new FileNotFoundException(e.getMessage());
}
+ return insertImage(cr, source, name, description);
}
/**
@@ -2043,22 +2000,34 @@ public final class MediaStore {
* control over lifecycle.
*/
@Deprecated
- public static final String insertImage(ContentResolver cr, Bitmap source,
- String title, String description) {
+ public static final String insertImage(ContentResolver cr, Bitmap source, String title,
+ String description) {
if (TextUtils.isEmpty(title)) title = "Image";
- final PendingParams params = new PendingParams(
- MediaStore.Images.Media.EXTERNAL_CONTENT_URI, title, "image/jpeg");
- final Context context = AppGlobals.getInitialApplication();
- final Uri pendingUri = createPending(context, params);
- try (PendingSession session = openPending(context, pendingUri)) {
- try (OutputStream out = session.openOutputStream()) {
+ final long now = System.currentTimeMillis();
+ final ContentValues values = new ContentValues();
+ values.put(MediaColumns.DISPLAY_NAME, title);
+ values.put(MediaColumns.MIME_TYPE, "image/jpeg");
+ values.put(MediaColumns.DATE_ADDED, now / 1000);
+ values.put(MediaColumns.DATE_MODIFIED, now / 1000);
+ values.put(MediaColumns.DATE_EXPIRES, (now + DateUtils.DAY_IN_MILLIS) / 1000);
+ values.put(MediaColumns.IS_PENDING, 1);
+
+ final Uri uri = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
+ try {
+ try (OutputStream out = cr.openOutputStream(uri)) {
source.compress(Bitmap.CompressFormat.JPEG, 90, out);
}
- return session.publish().toString();
+
+ // Everything went well above, publish it!
+ values.clear();
+ values.put(MediaColumns.IS_PENDING, 0);
+ values.putNull(MediaColumns.DATE_EXPIRES);
+ cr.update(uri, values, null, null);
+ return uri.toString();
} catch (Exception e) {
Log.w(TAG, "Failed to insert image", e);
- context.getContentResolver().delete(pendingUri, null, null);
+ cr.delete(uri, null, null);
return null;
}
}
@@ -2318,6 +2287,14 @@ public final class MediaStore {
public static final int MICRO_KIND = ThumbnailConstants.MICRO_KIND;
/**
+ * Return the typical {@link Size} (in pixels) used internally when
+ * the given thumbnail kind is requested.
+ */
+ public static @NonNull Size getKindSize(int kind) {
+ return ThumbnailConstants.getKindSize(kind);
+ }
+
+ /**
* The blob raw data of thumbnail
*
* @deprecated this column never existed internally, and could never
@@ -3572,6 +3549,14 @@ public final class MediaStore {
public static final int MICRO_KIND = ThumbnailConstants.MICRO_KIND;
/**
+ * Return the typical {@link Size} (in pixels) used internally when
+ * the given thumbnail kind is requested.
+ */
+ public static @NonNull Size getKindSize(int kind) {
+ return ThumbnailConstants.getKindSize(kind);
+ }
+
+ /**
* The width of the thumbnal
*/
@Column(value = Cursor.FIELD_TYPE_INTEGER, readOnly = true)
@@ -3603,54 +3588,44 @@ public final class MediaStore {
*/
public static @NonNull Set<String> getExternalVolumeNames(@NonNull Context context) {
final StorageManager sm = context.getSystemService(StorageManager.class);
- final Set<String> volumeNames = new ArraySet<>();
- for (VolumeInfo vi : sm.getVolumes()) {
- if (vi.isVisibleForUser(UserHandle.myUserId()) && vi.isMountedReadable()) {
- if (vi.isPrimary()) {
- volumeNames.add(VOLUME_EXTERNAL_PRIMARY);
- } else {
- volumeNames.add(vi.getNormalizedFsUuid());
+ final Set<String> res = new ArraySet<>();
+ for (StorageVolume sv : sm.getStorageVolumes()) {
+ switch (sv.getState()) {
+ case Environment.MEDIA_MOUNTED:
+ case Environment.MEDIA_MOUNTED_READ_ONLY: {
+ final String volumeName = sv.getMediaStoreVolumeName();
+ if (volumeName != null) {
+ res.add(volumeName);
+ }
+ break;
}
}
}
- return volumeNames;
+ return res;
}
/**
- * Return list of all specific volume names that have recently been part of
+ * Return list of all recent volume names that have been part of
* {@link #VOLUME_EXTERNAL}.
* <p>
- * This includes both currently mounted volumes <em>and</em> recently
- * mounted (but currently unmounted) volumes. Any indexed metadata for these
- * volumes is preserved to optimize the speed of remounting at a later time.
- *
- * @hide
+ * These volume names are not currently mounted, but they're likely to
+ * reappear in the future, so apps are encouraged to preserve any indexed
+ * metadata related to these volumes to optimize user experiences.
+ * <p>
+ * Each specific volume name can be passed to APIs like
+ * {@link MediaStore.Images.Media#getContentUri(String)} to interact with
+ * media on that storage device.
*/
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WRITE_MEDIA_STORAGE)
public static @NonNull Set<String> getRecentExternalVolumeNames(@NonNull Context context) {
final StorageManager sm = context.getSystemService(StorageManager.class);
-
- // We always have primary storage
- final Set<String> volumeNames = new ArraySet<>();
- volumeNames.add(VOLUME_EXTERNAL_PRIMARY);
-
- final long lastWeek = System.currentTimeMillis() - DateUtils.WEEK_IN_MILLIS;
- for (VolumeRecord rec : sm.getVolumeRecords()) {
- // Skip volumes without valid UUIDs
- if (TextUtils.isEmpty(rec.fsUuid)) continue;
-
- final VolumeInfo vi = sm.findVolumeByUuid(rec.fsUuid);
- if (vi != null && vi.isVisibleForUser(UserHandle.myUserId())
- && vi.isMountedReadable()) {
- // We're mounted right now
- volumeNames.add(rec.getNormalizedFsUuid());
- } else if (rec.lastSeenMillis > 0 && rec.lastSeenMillis < lastWeek) {
- // We're not mounted right now, but we've been seen recently
- volumeNames.add(rec.getNormalizedFsUuid());
+ final Set<String> res = new ArraySet<>();
+ for (StorageVolume sv : sm.getRecentStorageVolumes()) {
+ final String volumeName = sv.getMediaStoreVolumeName();
+ if (volumeName != null) {
+ res.add(volumeName);
}
}
- return volumeNames;
+ return res;
}
/**
@@ -3703,97 +3678,6 @@ public final class MediaStore {
}
/**
- * Return path where the given specific volume is mounted. Not valid for
- * {@link #VOLUME_INTERNAL} or {@link #VOLUME_EXTERNAL}, since those are
- * broad collections that cover many paths.
- *
- * @hide
- */
- @TestApi
- public static @NonNull File getVolumePath(@NonNull String volumeName)
- throws FileNotFoundException {
- final StorageManager sm = AppGlobals.getInitialApplication()
- .getSystemService(StorageManager.class);
- return getVolumePath(sm.getVolumes(), volumeName);
- }
-
- /** {@hide} */
- public static @NonNull File getVolumePath(@NonNull List<VolumeInfo> volumes,
- @NonNull String volumeName) throws FileNotFoundException {
- if (TextUtils.isEmpty(volumeName)) {
- throw new IllegalArgumentException();
- }
-
- switch (volumeName) {
- case VOLUME_INTERNAL:
- case VOLUME_EXTERNAL:
- throw new FileNotFoundException(volumeName + " has no associated path");
- }
-
- final boolean wantPrimary = VOLUME_EXTERNAL_PRIMARY.equals(volumeName);
- for (VolumeInfo volume : volumes) {
- final boolean matchPrimary = wantPrimary
- && volume.isPrimary();
- final boolean matchSecondary = !wantPrimary
- && Objects.equals(volume.getNormalizedFsUuid(), volumeName);
- if (matchPrimary || matchSecondary) {
- final File path = volume.getPathForUser(UserHandle.myUserId());
- if (path != null) {
- return path;
- }
- }
- }
- throw new FileNotFoundException("Failed to find path for " + volumeName);
- }
-
- /**
- * Return paths that should be scanned for the given volume.
- *
- * @hide
- */
- @TestApi
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WRITE_MEDIA_STORAGE)
- public static @NonNull Collection<File> getVolumeScanPaths(@NonNull String volumeName)
- throws FileNotFoundException {
- if (TextUtils.isEmpty(volumeName)) {
- throw new IllegalArgumentException();
- }
-
- final Context context = AppGlobals.getInitialApplication();
- final UserManager um = context.getSystemService(UserManager.class);
-
- final ArrayList<File> res = new ArrayList<>();
- if (VOLUME_INTERNAL.equals(volumeName)) {
- addCanonicalFile(res, new File(Environment.getRootDirectory(), "media"));
- addCanonicalFile(res, new File(Environment.getOemDirectory(), "media"));
- addCanonicalFile(res, new File(Environment.getProductDirectory(), "media"));
- } else if (VOLUME_EXTERNAL.equals(volumeName)) {
- for (String exactVolume : getExternalVolumeNames(context)) {
- addCanonicalFile(res, getVolumePath(exactVolume));
- }
- if (um.isDemoUser()) {
- addCanonicalFile(res, Environment.getDataPreloadsMediaDirectory());
- }
- } else {
- addCanonicalFile(res, getVolumePath(volumeName));
- if (VOLUME_EXTERNAL_PRIMARY.equals(volumeName) && um.isDemoUser()) {
- addCanonicalFile(res, Environment.getDataPreloadsMediaDirectory());
- }
- }
- return res;
- }
-
- private static void addCanonicalFile(List<File> list, File file) {
- try {
- list.add(file.getCanonicalFile());
- } catch (IOException e) {
- Log.w(TAG, "Failed to resolve " + file + ": " + e);
- list.add(file);
- }
- }
-
- /**
* Uri for querying the state of the media scanner.
*/
public static Uri getMediaScannerUri() {
@@ -3876,10 +3760,10 @@ public final class MediaStore {
try (ContentProviderClient client = resolver.acquireContentProviderClient(AUTHORITY)) {
final Bundle in = new Bundle();
- in.putParcelable(DocumentsContract.EXTRA_URI, mediaUri);
- in.putParcelableList(DocumentsContract.EXTRA_URI_PERMISSIONS, uriPermissions);
+ in.putParcelable(EXTRA_URI, mediaUri);
+ in.putParcelableArrayList(EXTRA_URI_PERMISSIONS, new ArrayList<>(uriPermissions));
final Bundle out = client.call(GET_DOCUMENT_URI_CALL, null, in);
- return out.getParcelable(DocumentsContract.EXTRA_URI);
+ return out.getParcelable(EXTRA_URI);
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
@@ -3906,134 +3790,43 @@ public final class MediaStore {
try (ContentProviderClient client = resolver.acquireContentProviderClient(AUTHORITY)) {
final Bundle in = new Bundle();
- in.putParcelable(DocumentsContract.EXTRA_URI, documentUri);
- in.putParcelableList(DocumentsContract.EXTRA_URI_PERMISSIONS, uriPermissions);
+ in.putParcelable(EXTRA_URI, documentUri);
+ in.putParcelableArrayList(EXTRA_URI_PERMISSIONS, new ArrayList<>(uriPermissions));
final Bundle out = client.call(GET_MEDIA_URI_CALL, null, in);
- return out.getParcelable(DocumentsContract.EXTRA_URI);
+ return out.getParcelable(EXTRA_URI);
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
}
+ /** @hide */
+ @TestApi
+ public static void waitForIdle(@NonNull ContentResolver resolver) {
+ resolver.call(AUTHORITY, WAIT_FOR_IDLE_CALL, null, null);
+ }
+
/**
- * Calculate size of media contributed by given package under the calling
- * user. The meaning of "contributed" means it won't automatically be
- * deleted when the app is uninstalled.
+ * Perform a blocking scan of the given {@link File}, returning the
+ * {@link Uri} of the scanned file.
*
* @hide
*/
+ @SystemApi
@TestApi
- @RequiresPermission(android.Manifest.permission.CLEAR_APP_USER_DATA)
- public static @BytesLong long getContributedMediaSize(Context context, String packageName,
- UserHandle user) throws IOException {
- final UserManager um = context.getSystemService(UserManager.class);
- if (um.isUserUnlocked(user) && um.isUserRunning(user)) {
- try {
- final ContentResolver resolver = context
- .createPackageContextAsUser(packageName, 0, user).getContentResolver();
- final Bundle in = new Bundle();
- in.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
- final Bundle out = resolver.call(AUTHORITY, GET_CONTRIBUTED_MEDIA_CALL, null, in);
- return out.getLong(Intent.EXTRA_INDEX);
- } catch (Exception e) {
- throw new IOException(e);
- }
- } else {
- throw new IOException("User " + user + " must be unlocked and running");
- }
+ @SuppressLint("StreamFiles")
+ public static @NonNull Uri scanFile(@NonNull ContentResolver resolver, @NonNull File file) {
+ final Bundle out = resolver.call(AUTHORITY, SCAN_FILE_CALL, file.getAbsolutePath(), null);
+ return out.getParcelable(Intent.EXTRA_STREAM);
}
/**
- * Delete all media contributed by given package under the calling user. The
- * meaning of "contributed" means it won't automatically be deleted when the
- * app is uninstalled.
+ * Perform a blocking scan of the given storage volume.
*
* @hide
*/
+ @SystemApi
@TestApi
- @RequiresPermission(android.Manifest.permission.CLEAR_APP_USER_DATA)
- public static void deleteContributedMedia(Context context, String packageName,
- UserHandle user) throws IOException {
- final UserManager um = context.getSystemService(UserManager.class);
- if (um.isUserUnlocked(user) && um.isUserRunning(user)) {
- try {
- final ContentResolver resolver = context
- .createPackageContextAsUser(packageName, 0, user).getContentResolver();
- final Bundle in = new Bundle();
- in.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
- resolver.call(AUTHORITY, DELETE_CONTRIBUTED_MEDIA_CALL, null, in);
- } catch (Exception e) {
- throw new IOException(e);
- }
- } else {
- throw new IOException("User " + user + " must be unlocked and running");
- }
- }
-
- /** @hide */
- @TestApi
- public static void waitForIdle(Context context) {
- final ContentResolver resolver = context.getContentResolver();
- try (ContentProviderClient client = resolver.acquireContentProviderClient(AUTHORITY)) {
- client.call(WAIT_FOR_IDLE_CALL, null, null);
- } catch (RemoteException e) {
- throw e.rethrowAsRuntimeException();
- }
- }
-
- /** @hide */
- public static void suicide(Context context) {
- final ContentResolver resolver = context.getContentResolver();
- try (ContentProviderClient client = resolver
- .acquireUnstableContentProviderClient(AUTHORITY)) {
- client.call(SUICIDE_CALL, null, null);
- } catch (Exception ignored) {
- }
- }
-
- /** @hide */
- @TestApi
- public static Uri scanFile(Context context, File file) {
- return scan(context, SCAN_FILE_CALL, file, false);
- }
-
- /** @hide */
- @TestApi
- public static Uri scanFileFromShell(Context context, File file) {
- return scan(context, SCAN_FILE_CALL, file, true);
- }
-
- /** @hide */
- @TestApi
- public static void scanVolume(Context context, File file) {
- scan(context, SCAN_VOLUME_CALL, file, false);
- }
-
- /** @hide */
- public static Uri scanFile(ContentProviderClient client, File file) {
- return scan(client, SCAN_FILE_CALL, file, false);
- }
-
- /** @hide */
- private static Uri scan(Context context, String method, File file,
- boolean originatedFromShell) {
- final ContentResolver resolver = context.getContentResolver();
- try (ContentProviderClient client = resolver.acquireContentProviderClient(AUTHORITY)) {
- return scan(client, method, file, originatedFromShell);
- }
- }
-
- /** @hide */
- private static Uri scan(ContentProviderClient client, String method, File file,
- boolean originatedFromShell) {
- try {
- final Bundle in = new Bundle();
- in.putParcelable(Intent.EXTRA_STREAM, Uri.fromFile(file));
- in.putBoolean(EXTRA_ORIGINATED_FROM_SHELL, originatedFromShell);
- final Bundle out = client.call(method, null, in);
- return out.getParcelable(Intent.EXTRA_STREAM);
- } catch (RemoteException e) {
- throw e.rethrowAsRuntimeException();
- }
+ public static void scanVolume(@NonNull ContentResolver resolver, @NonNull String volumeName) {
+ resolver.call(AUTHORITY, SCAN_VOLUME_CALL, volumeName, null);
}
}
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index ad8d55313795..503d6db9df9c 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -568,16 +568,47 @@ public final class Settings {
/**
* Activity Action: Show settings to enroll fingerprints, and setup PIN/Pattern/Pass if
* necessary.
+ * @deprecated See {@link #ACTION_BIOMETRIC_ENROLL}.
* <p>
* Input: Nothing.
* <p>
* Output: Nothing.
*/
+ @Deprecated
@SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
public static final String ACTION_FINGERPRINT_ENROLL =
"android.settings.FINGERPRINT_ENROLL";
/**
+ * Activity Action: Show settings to enroll biometrics, and setup PIN/Pattern/Pass if
+ * necessary. By default, this prompts the user to enroll biometrics with strength
+ * Weak or above, as defined by the CDD. Only biometrics that meet or exceed Strong, as defined
+ * in the CDD are allowed to participate in Keystore operations.
+ * <p>
+ * Input: extras {@link #EXTRA_BIOMETRIC_MINIMUM_STRENGTH_REQUIRED} as an integer, with
+ * constants defined in {@link android.hardware.biometrics.BiometricManager.Authenticators},
+ * e.g. {@link android.hardware.biometrics.BiometricManager.Authenticators#BIOMETRIC_STRONG}.
+ * If not specified, the default behavior is
+ * {@link android.hardware.biometrics.BiometricManager.Authenticators#BIOMETRIC_WEAK}.
+ * <p>
+ * Output: Nothing.
+ */
+ @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
+ public static final String ACTION_BIOMETRIC_ENROLL =
+ "android.settings.BIOMETRIC_ENROLL";
+
+ /**
+ * Activity Extra: The minimum strength to request enrollment for.
+ * <p>
+ * This can be passed as an extra field to the {@link #ACTION_BIOMETRIC_ENROLL} intent to
+ * indicate that only enrollment for sensors that meet this strength should be shown. The
+ * value should be one of the biometric strength constants defined in
+ * {@link android.hardware.biometrics.BiometricManager.Authenticators}.
+ */
+ public static final String EXTRA_BIOMETRIC_MINIMUM_STRENGTH_REQUIRED =
+ "android.provider.extra.BIOMETRIC_MINIMUM_STRENGTH_REQUIRED";
+
+ /**
* Activity Action: Show settings to allow configuration of cast endpoints.
* <p>
* In some cases, a matching Activity may not exist, so ensure you
@@ -648,6 +679,22 @@ public final class Settings {
"android.settings.NIGHT_DISPLAY_SETTINGS";
/**
+ * Activity Action: Show settings to allow configuration of Dark theme.
+ * <p>
+ * In some cases, a matching Activity may not exist, so ensure you
+ * safeguard against this.
+ * <p>
+ * Input: Nothing.
+ * <p>
+ * Output: Nothing.
+ *
+ * @hide
+ */
+ @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
+ public static final String ACTION_DARK_THEME_SETTINGS =
+ "android.settings.DARK_THEME_SETTINGS";
+
+ /**
* Activity Action: Show settings to allow configuration of locale.
* <p>
* In some cases, a matching Activity may not exist, so ensure you
@@ -8376,6 +8423,20 @@ public final class Settings {
"navigation_mode";
/**
+ * Scale factor for the back gesture inset size on the left side of the screen.
+ * @hide
+ */
+ public static final String BACK_GESTURE_INSET_SCALE_LEFT =
+ "back_gesture_inset_scale_left";
+
+ /**
+ * Scale factor for the back gesture inset size on the right side of the screen.
+ * @hide
+ */
+ public static final String BACK_GESTURE_INSET_SCALE_RIGHT =
+ "back_gesture_inset_scale_right";
+
+ /**
* Controls whether aware is enabled.
* @hide
*/
@@ -8394,6 +8455,18 @@ public final class Settings {
public static final String TAP_GESTURE = "tap_gesture";
/**
+ * Controls whether the people strip is enabled.
+ * @hide
+ */
+ public static final String PEOPLE_STRIP = "people_strip";
+
+ /**
+ * Controls if window magnification is enabled.
+ * @hide
+ */
+ public static final String WINDOW_MAGNIFICATION = "window_magnification";
+
+ /**
* Keys we no longer back up under the current schema, but want to continue to
* process when restoring historical backup datasets.
*
@@ -10296,6 +10369,19 @@ public final class Settings {
public static final String ERROR_LOGCAT_PREFIX = "logcat_for_";
/**
+ * Maximum number of bytes of a system crash/ANR/etc. report that
+ * ActivityManagerService should send to DropBox, as a prefix of the
+ * dropbox tag of the report type. For example,
+ * "max_error_bytes_for_system_server_anr" controls the maximum
+ * number of bytes captured with system server ANR reports.
+ * <p>
+ * Type: int (max size in bytes)
+ *
+ * @hide
+ */
+ public static final String MAX_ERROR_BYTES_PREFIX = "max_error_bytes_for_";
+
+ /**
* The interval in minutes after which the amount of free storage left
* on the device is logged to the event log
*
@@ -13598,13 +13684,6 @@ public final class Settings {
public static final String KERNEL_CPU_THREAD_READER = "kernel_cpu_thread_reader";
/**
- * Default user id to boot into. They map to user ids, for example, 10, 11, 12.
- *
- * @hide
- */
- public static final String DEFAULT_USER_ID_TO_BOOT_INTO = "default_boot_into_user_id";
-
- /**
* Persistent user id that is last logged in to.
*
* They map to user ids, for example, 10, 11, 12.
@@ -14194,6 +14273,20 @@ public final class Settings {
*/
public static final int ADD_WIFI_RESULT_ALREADY_EXISTS = 2;
+ /**
+ * Activity Action: Allows user to select current bug report handler.
+ * <p>
+ * Input: Nothing.
+ * <p>
+ * Output: Nothing.
+ *
+ * @hide
+ */
+ @SystemApi
+ @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
+ public static final String ACTION_BUGREPORT_HANDLER_SETTINGS =
+ "android.settings.BUGREPORT_HANDLER_SETTINGS";
+
private static final String[] PM_WRITE_SETTINGS = {
android.Manifest.permission.WRITE_SETTINGS
};
diff --git a/core/java/android/provider/Telephony.java b/core/java/android/provider/Telephony.java
index 70c8e5d311bd..c287ae381261 100644
--- a/core/java/android/provider/Telephony.java
+++ b/core/java/android/provider/Telephony.java
@@ -25,6 +25,7 @@ import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.ChangeId;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
@@ -1307,8 +1308,7 @@ public final class Telephony {
* Broadcast action: When SMS-MMS db is being created. If file-based encryption is
* supported, this broadcast indicates creation of the db in credential-encrypted
* storage. A boolean is specified in {@link #EXTRA_IS_INITIAL_CREATE} to indicate if
- * this is the initial create of the db. Requires
- * {@link android.Manifest.permission#READ_SMS} to receive.
+ * this is the initial create of the db.
*
* @see #EXTRA_IS_INITIAL_CREATE
*
@@ -4032,6 +4032,16 @@ public final class Telephony {
@Retention(RetentionPolicy.SOURCE)
public @interface Skip464XlatStatus {}
+ /**
+ * Compat framework change ID for the APN db read permission change.
+ *
+ * In API level 30 and beyond, accessing the APN database will require the
+ * {@link android.Manifest.permission#WRITE_APN_SETTINGS} permission. This change ID tracks
+ * apps that are affected because they don't hold this permission.
+ * @hide
+ */
+ @ChangeId
+ public static final long APN_READING_PERMISSION_CHANGE_ID = 124107808L;
}
/**
diff --git a/core/java/android/se/omapi/SEService.java b/core/java/android/se/omapi/SEService.java
index 00060ab8ef4a..d646e23d230a 100644
--- a/core/java/android/se/omapi/SEService.java
+++ b/core/java/android/se/omapi/SEService.java
@@ -22,11 +22,14 @@
package android.se.omapi;
+import android.app.ActivityThread;
import android.annotation.NonNull;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
+import android.content.pm.IPackageManager;
+import android.content.pm.PackageManager;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
@@ -140,6 +143,10 @@ public final class SEService {
throw new NullPointerException("Arguments must not be null");
}
+ if (!hasOMAPIReaders()) {
+ throw new UnsupportedOperationException("Device does not support any OMAPI reader");
+ }
+
mContext = context;
mSEListener.mListener = listener;
mSEListener.mExecutor = executor;
@@ -270,4 +277,23 @@ public final class SEService {
throw new IllegalStateException(e.getMessage());
}
}
+
+ /**
+ * Helper to check if this device support any OMAPI readers
+ */
+ private static boolean hasOMAPIReaders() {
+ IPackageManager pm = ActivityThread.getPackageManager();
+ if (pm == null) {
+ Log.e(TAG, "Cannot get package manager, assuming OMAPI readers supported");
+ return true;
+ }
+ try {
+ return pm.hasSystemFeature(PackageManager.FEATURE_SE_OMAPI_UICC, 0)
+ || pm.hasSystemFeature(PackageManager.FEATURE_SE_OMAPI_ESE, 0)
+ || pm.hasSystemFeature(PackageManager.FEATURE_SE_OMAPI_SD, 0);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Package manager query failed, assuming OMAPI readers supported", e);
+ return true;
+ }
+ }
}
diff --git a/core/java/android/security/keymaster/KeymasterDefs.java b/core/java/android/security/keymaster/KeymasterDefs.java
index 15ded8d1b7b1..e4ba87c14626 100644
--- a/core/java/android/security/keymaster/KeymasterDefs.java
+++ b/core/java/android/security/keymaster/KeymasterDefs.java
@@ -94,6 +94,7 @@ public final class KeymasterDefs {
public static final int KM_TAG_ATTESTATION_ID_MEID = KM_BYTES | 715;
public static final int KM_TAG_ATTESTATION_ID_MANUFACTURER = KM_BYTES | 716;
public static final int KM_TAG_ATTESTATION_ID_MODEL = KM_BYTES | 717;
+ public static final int KM_TAG_DEVICE_UNIQUE_ATTESTATION = KM_BOOL | 720;
public static final int KM_TAG_ASSOCIATED_DATA = KM_BYTES | 1000;
public static final int KM_TAG_NONCE = KM_BYTES | 1001;
diff --git a/core/java/android/service/autofill/FillRequest.java b/core/java/android/service/autofill/FillRequest.java
index e53ebada55fb..72e9ad047ed7 100644
--- a/core/java/android/service/autofill/FillRequest.java
+++ b/core/java/android/service/autofill/FillRequest.java
@@ -23,6 +23,7 @@ import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.view.View;
+import android.view.inputmethod.InlineSuggestionsRequest;
import com.android.internal.util.DataClass;
import com.android.internal.util.Preconditions;
@@ -116,20 +117,34 @@ public final class FillRequest implements Parcelable {
*/
private final @RequestFlags int mFlags;
+ /**
+ * Gets the {@link android.view.inputmethod.InlineSuggestionsRequest} associated
+ * with this request.
+ *
+ * TODO(b/137800469): Add more doc describing how to handle the inline suggestions request.
+ *
+ * @return the suggestionspec
+ */
+ private final @Nullable InlineSuggestionsRequest mInlineSuggestionsRequest;
+
private void onConstructed() {
Preconditions.checkCollectionElementsNotNull(mFillContexts, "contexts");
}
- // Code below generated by codegen v1.0.0.
+ // Code below generated by codegen v1.0.14.
//
// DO NOT MODIFY!
+ // CHECKSTYLE:OFF Generated code
//
// To regenerate run:
// $ codegen $ANDROID_BUILD_TOP/frameworks/base/core/java/android/service/autofill/FillRequest.java
//
- // CHECKSTYLE:OFF Generated code
+ // To exclude the generated code from IntelliJ auto-formatting enable (one-time):
+ // Settings > Editor > Code Style > Formatter Control
+ //@formatter:off
+
/** @hide */
@IntDef(flag = true, prefix = "FLAG_", value = {
@@ -184,6 +199,11 @@ public final class FillRequest implements Parcelable {
*
* @return any combination of {@link #FLAG_MANUAL_REQUEST} and
* {@link #FLAG_COMPATIBILITY_MODE_REQUEST}.
+ * @param inlineSuggestionsRequest
+ * Gets the {@link android.view.inputmethod.InlineSuggestionsRequest} associated
+ * with this request.
+ *
+ * TODO(b/137800469): Add more doc describing how to handle the inline suggestions request.
* @hide
*/
@DataClass.Generated.Member
@@ -191,7 +211,8 @@ public final class FillRequest implements Parcelable {
int id,
@NonNull List<FillContext> fillContexts,
@Nullable Bundle clientState,
- @RequestFlags int flags) {
+ @RequestFlags int flags,
+ @Nullable InlineSuggestionsRequest inlineSuggestionsRequest) {
this.mId = id;
this.mFillContexts = fillContexts;
com.android.internal.util.AnnotationValidations.validate(
@@ -203,6 +224,7 @@ public final class FillRequest implements Parcelable {
mFlags,
FLAG_MANUAL_REQUEST
| FLAG_COMPATIBILITY_MODE_REQUEST);
+ this.mInlineSuggestionsRequest = inlineSuggestionsRequest;
onConstructed();
}
@@ -256,6 +278,19 @@ public final class FillRequest implements Parcelable {
return mFlags;
}
+ /**
+ * Gets the {@link android.view.inputmethod.InlineSuggestionsRequest} associated
+ * with this request.
+ *
+ * TODO(b/137800469): Add more doc describing how to handle the inline suggestions request.
+ *
+ * @return the suggestionspec
+ */
+ @DataClass.Generated.Member
+ public @Nullable InlineSuggestionsRequest getInlineSuggestionsRequest() {
+ return mInlineSuggestionsRequest;
+ }
+
@Override
@DataClass.Generated.Member
public String toString() {
@@ -266,29 +301,63 @@ public final class FillRequest implements Parcelable {
"id = " + mId + ", " +
"fillContexts = " + mFillContexts + ", " +
"clientState = " + mClientState + ", " +
- "flags = " + requestFlagsToString(mFlags) +
+ "flags = " + requestFlagsToString(mFlags) + ", " +
+ "inlineSuggestionsRequest = " + mInlineSuggestionsRequest +
" }";
}
@Override
@DataClass.Generated.Member
- public void writeToParcel(Parcel dest, int flags) {
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
// You can override field parcelling by defining methods like:
// void parcelFieldName(Parcel dest, int flags) { ... }
byte flg = 0;
if (mClientState != null) flg |= 0x4;
+ if (mInlineSuggestionsRequest != null) flg |= 0x10;
dest.writeByte(flg);
dest.writeInt(mId);
dest.writeParcelableList(mFillContexts, flags);
if (mClientState != null) dest.writeBundle(mClientState);
dest.writeInt(mFlags);
+ if (mInlineSuggestionsRequest != null) dest.writeTypedObject(mInlineSuggestionsRequest, flags);
}
@Override
@DataClass.Generated.Member
public int describeContents() { return 0; }
+ /** @hide */
+ @SuppressWarnings({"unchecked", "RedundantCast"})
+ @DataClass.Generated.Member
+ /* package-private */ FillRequest(@NonNull Parcel in) {
+ // You can override field unparcelling by defining methods like:
+ // static FieldType unparcelFieldName(Parcel in) { ... }
+
+ byte flg = in.readByte();
+ int id = in.readInt();
+ List<FillContext> fillContexts = new ArrayList<>();
+ in.readParcelableList(fillContexts, FillContext.class.getClassLoader());
+ Bundle clientState = (flg & 0x4) == 0 ? null : in.readBundle();
+ int flags = in.readInt();
+ InlineSuggestionsRequest inlineSuggestionsRequest = (flg & 0x10) == 0 ? null : (InlineSuggestionsRequest) in.readTypedObject(InlineSuggestionsRequest.CREATOR);
+
+ this.mId = id;
+ this.mFillContexts = fillContexts;
+ com.android.internal.util.AnnotationValidations.validate(
+ NonNull.class, null, mFillContexts);
+ this.mClientState = clientState;
+ this.mFlags = flags;
+
+ Preconditions.checkFlagsArgument(
+ mFlags,
+ FLAG_MANUAL_REQUEST
+ | FLAG_COMPATIBILITY_MODE_REQUEST);
+ this.mInlineSuggestionsRequest = inlineSuggestionsRequest;
+
+ onConstructed();
+ }
+
@DataClass.Generated.Member
public static final @NonNull Parcelable.Creator<FillRequest> CREATOR
= new Parcelable.Creator<FillRequest>() {
@@ -298,31 +367,21 @@ public final class FillRequest implements Parcelable {
}
@Override
- @SuppressWarnings({"unchecked", "RedundantCast"})
- public FillRequest createFromParcel(Parcel in) {
- // You can override field unparcelling by defining methods like:
- // static FieldType unparcelFieldName(Parcel in) { ... }
-
- byte flg = in.readByte();
- int id = in.readInt();
- List<FillContext> fillContexts = new ArrayList<>();
- in.readParcelableList(fillContexts, FillContext.class.getClassLoader());
- Bundle clientState = (flg & 0x4) == 0 ? null : in.readBundle();
- int flags = in.readInt();
- return new FillRequest(
- id,
- fillContexts,
- clientState,
- flags);
+ public FillRequest createFromParcel(@NonNull Parcel in) {
+ return new FillRequest(in);
}
};
@DataClass.Generated(
- time = 1565152134349L,
- codegenVersion = "1.0.0",
+ time = 1575928271155L,
+ codegenVersion = "1.0.14",
sourceFile = "frameworks/base/core/java/android/service/autofill/FillRequest.java",
- inputSignatures = "public static final @android.service.autofill.FillRequest.RequestFlags int FLAG_MANUAL_REQUEST\npublic static final @android.service.autofill.FillRequest.RequestFlags int FLAG_COMPATIBILITY_MODE_REQUEST\npublic static final int INVALID_REQUEST_ID\nprivate final int mId\nprivate final @android.annotation.NonNull java.util.List<android.service.autofill.FillContext> mFillContexts\nprivate final @android.annotation.Nullable android.os.Bundle mClientState\nprivate final @android.service.autofill.FillRequest.RequestFlags int mFlags\nprivate void onConstructed()\nclass FillRequest extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genToString=true, genHiddenConstructor=true, genHiddenConstDefs=true)")
+ inputSignatures = "public static final @android.service.autofill.FillRequest.RequestFlags int FLAG_MANUAL_REQUEST\npublic static final @android.service.autofill.FillRequest.RequestFlags int FLAG_COMPATIBILITY_MODE_REQUEST\npublic static final int INVALID_REQUEST_ID\nprivate final int mId\nprivate final @android.annotation.NonNull java.util.List<android.service.autofill.FillContext> mFillContexts\nprivate final @android.annotation.Nullable android.os.Bundle mClientState\nprivate final @android.service.autofill.FillRequest.RequestFlags int mFlags\nprivate final @android.annotation.Nullable android.view.inputmethod.InlineSuggestionsRequest mInlineSuggestionsRequest\nprivate void onConstructed()\nclass FillRequest extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genToString=true, genHiddenConstructor=true, genHiddenConstDefs=true)")
@Deprecated
private void __metadata() {}
+
+ //@formatter:on
+ // End of generated code
+
}
diff --git a/core/java/android/service/autofill/FillResponse.java b/core/java/android/service/autofill/FillResponse.java
index c99fe6149aab..02a6390a08bb 100644
--- a/core/java/android/service/autofill/FillResponse.java
+++ b/core/java/android/service/autofill/FillResponse.java
@@ -25,6 +25,7 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
import android.app.Activity;
+import android.app.slice.Slice;
import android.content.IntentSender;
import android.content.pm.ParceledListSlice;
import android.os.Bundle;
@@ -86,6 +87,7 @@ public final class FillResponse implements Parcelable {
private int mRequestId;
private final @Nullable UserData mUserData;
private final @Nullable int[] mCancelIds;
+ private final @Nullable ParceledListSlice<Slice> mInlineSuggestionSlices;
private FillResponse(@NonNull Builder builder) {
mDatasets = (builder.mDatasets != null) ? new ParceledListSlice<>(builder.mDatasets) : null;
@@ -103,6 +105,8 @@ public final class FillResponse implements Parcelable {
mRequestId = INVALID_REQUEST_ID;
mUserData = builder.mUserData;
mCancelIds = builder.mCancelIds;
+ mInlineSuggestionSlices = (builder.mInlineSuggestionSlices != null)
+ ? new ParceledListSlice<>(builder.mInlineSuggestionSlices) : null;
}
/** @hide */
@@ -195,6 +199,11 @@ public final class FillResponse implements Parcelable {
return mCancelIds;
}
+ /** @hide */
+ public List<Slice> getInlineSuggestionSlices() {
+ return (mInlineSuggestionSlices != null) ? mInlineSuggestionSlices.getList() : null;
+ }
+
/**
* Builder for {@link FillResponse} objects. You must to provide at least
* one dataset or set an authentication intent with a presentation view.
@@ -215,6 +224,7 @@ public final class FillResponse implements Parcelable {
private boolean mDestroyed;
private UserData mUserData;
private int[] mCancelIds;
+ private ArrayList<Slice> mInlineSuggestionSlices;
/**
* Triggers a custom UI before before autofilling the screen with any data set in this
@@ -570,6 +580,20 @@ public final class FillResponse implements Parcelable {
}
/**
+ * TODO(b/137800469): add javadoc
+ */
+ @NonNull
+ public Builder addInlineSuggestionSlice(@NonNull Slice inlineSuggestionSlice) {
+ throwIfDestroyed();
+ throwIfAuthenticationCalled();
+ if (mInlineSuggestionSlices == null) {
+ mInlineSuggestionSlices = new ArrayList<>();
+ }
+ mInlineSuggestionSlices.add(inlineSuggestionSlice);
+ return this;
+ }
+
+ /**
* Builds a new {@link FillResponse} instance.
*
* @throws IllegalStateException if any of the following conditions occur:
@@ -670,7 +694,9 @@ public final class FillResponse implements Parcelable {
if (mCancelIds != null) {
builder.append(", mCancelIds=").append(mCancelIds.length);
}
-
+ if (mInlineSuggestionSlices != null) {
+ builder.append(", inlinedSuggestions=").append(mInlineSuggestionSlices.getList());
+ }
return builder.append("]").toString();
}
@@ -699,7 +725,7 @@ public final class FillResponse implements Parcelable {
parcel.writeParcelableArray(mFieldClassificationIds, flags);
parcel.writeInt(mFlags);
parcel.writeIntArray(mCancelIds);
-
+ parcel.writeParcelable(mInlineSuggestionSlices, flags);
parcel.writeInt(mRequestId);
}
@@ -755,6 +781,16 @@ public final class FillResponse implements Parcelable {
final int[] cancelIds = parcel.createIntArray();
builder.setCancelTargetIds(cancelIds);
+ final ParceledListSlice<Slice> parceledInlineSuggestionSlices =
+ parcel.readParcelable(null);
+ if (parceledInlineSuggestionSlices != null) {
+ final List<Slice> inlineSuggestionSlices = parceledInlineSuggestionSlices.getList();
+ final int size = inlineSuggestionSlices.size();
+ for (int i = 0; i < size; i++) {
+ builder.addInlineSuggestionSlice(inlineSuggestionSlices.get(i));
+ }
+ }
+
final FillResponse response = builder.build();
response.setRequestId(parcel.readInt());
diff --git a/core/java/android/service/controls/BooleanAction.java b/core/java/android/service/controls/BooleanAction.java
index 8508c635142f..877f82e96174 100644
--- a/core/java/android/service/controls/BooleanAction.java
+++ b/core/java/android/service/controls/BooleanAction.java
@@ -18,6 +18,7 @@ package android.service.controls;
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.os.Bundle;
import android.os.Parcel;
/**
@@ -26,6 +27,8 @@ import android.os.Parcel;
*/
public final class BooleanAction extends ControlAction {
+ private static final String KEY_NEW_STATE = "key_new_state";
+
private final boolean mNewState;
/**
@@ -49,9 +52,9 @@ public final class BooleanAction extends ControlAction {
mNewState = newValue;
}
- BooleanAction(Parcel in) {
- super(in);
- mNewState = in.readByte() == 1;
+ BooleanAction(Bundle b) {
+ super(b);
+ mNewState = b.getBoolean(KEY_NEW_STATE);
}
/**
@@ -72,17 +75,17 @@ public final class BooleanAction extends ControlAction {
return ControlAction.TYPE_BOOLEAN;
}
-
@Override
- public void writeToParcel(Parcel dest, int flags) {
- super.writeToParcel(dest, flags);
- dest.writeByte(mNewState ? (byte) 1 : (byte) 0);
+ protected Bundle getDataBundle() {
+ Bundle b = super.getDataBundle();
+ b.putBoolean(KEY_NEW_STATE, mNewState);
+ return b;
}
public static final @NonNull Creator<BooleanAction> CREATOR = new Creator<BooleanAction>() {
@Override
public BooleanAction createFromParcel(Parcel source) {
- return new BooleanAction(source);
+ return new BooleanAction(source.readBundle());
}
@Override
diff --git a/core/java/android/service/controls/Control.java b/core/java/android/service/controls/Control.java
index a69408c43df3..2c17e89d02cc 100644
--- a/core/java/android/service/controls/Control.java
+++ b/core/java/android/service/controls/Control.java
@@ -18,6 +18,7 @@ package android.service.controls;
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.app.PendingIntent;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.drawable.Icon;
@@ -55,7 +56,7 @@ public class Control implements Parcelable {
private final @NonNull Icon mIcon;
private final @NonNull CharSequence mTitle;
private final @Nullable ColorStateList mTintColor;
- private final @NonNull Intent mAppIntent;
+ private final @NonNull PendingIntent mAppIntent;
private final @ControlTemplate.TemplateType int mPrimaryType;
/**
@@ -64,14 +65,15 @@ public class Control implements Parcelable {
* @param title the user facing name of this control (e.g. "Bedroom thermostat").
* @param tintColor the color to tint parts of the element UI. If {@code null} is passed, the
* system accent color will be used.
- * @param appIntent an intent linking to a page to interact with the corresponding device.
+ * @param appIntent a {@link PendingIntent} linking to a page to interact with the
+ * corresponding device.
* @param primaryType the primary template for this type.
*/
public Control(@NonNull String controlId,
@NonNull Icon icon,
@NonNull CharSequence title,
@Nullable ColorStateList tintColor,
- @NonNull Intent appIntent,
+ @NonNull PendingIntent appIntent,
int primaryType) {
Preconditions.checkNotNull(controlId);
Preconditions.checkNotNull(icon);
@@ -94,7 +96,7 @@ public class Control implements Parcelable {
} else {
mTintColor = null;
}
- mAppIntent = Intent.CREATOR.createFromParcel(in);
+ mAppIntent = PendingIntent.CREATOR.createFromParcel(in);
mPrimaryType = in.readInt();
}
@@ -119,7 +121,7 @@ public class Control implements Parcelable {
}
@NonNull
- public Intent getAppIntent() {
+ public PendingIntent getAppIntent() {
return mAppIntent;
}
@@ -175,17 +177,17 @@ public class Control implements Parcelable {
private Icon mIcon;
private CharSequence mTitle = "";
private ColorStateList mTintColor;
- private @Nullable Intent mAppIntent;
+ private @Nullable PendingIntent mAppIntent;
private @ControlTemplate.TemplateType int mPrimaryType = ControlTemplate.TYPE_NONE;
/**
* @param controlId the identifier for the {@link Control}.
* @param icon the icon for the {@link Control}.
- * @param appIntent the intent linking to the device Activity.
+ * @param appIntent the pending intent linking to the device Activity.
*/
public Builder(@NonNull String controlId,
@NonNull Icon icon,
- @NonNull Intent appIntent) {
+ @NonNull PendingIntent appIntent) {
Preconditions.checkNotNull(controlId);
Preconditions.checkNotNull(icon);
Preconditions.checkNotNull(appIntent);
@@ -256,7 +258,7 @@ public class Control implements Parcelable {
* @return {@code this}
*/
@NonNull
- public Builder setAppIntent(@NonNull Intent appIntent) {
+ public Builder setAppIntent(@NonNull PendingIntent appIntent) {
Preconditions.checkNotNull(appIntent);
mAppIntent = appIntent;
return this;
diff --git a/core/java/android/service/controls/ControlAction.java b/core/java/android/service/controls/ControlAction.java
index 8b759556b597..0a7c97c1bbc9 100644
--- a/core/java/android/service/controls/ControlAction.java
+++ b/core/java/android/service/controls/ControlAction.java
@@ -16,9 +16,11 @@
package android.service.controls;
+import android.annotation.CallSuper;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
@@ -36,25 +38,38 @@ import java.lang.annotation.RetentionPolicy;
*/
public abstract class ControlAction implements Parcelable {
+ private static final String KEY_TEMPLATE_ID = "key_template_id";
+ private static final String KEY_CHALLENGE_VALUE = "key_challenge_value";
+
+ public static final ControlAction UNKNOWN_ACTION = new ControlAction() {
+
+ @Override
+ public int getActionType() {
+ return TYPE_UNKNOWN;
+ }
+ };
+
/**
* @hide
*/
@Retention(RetentionPolicy.SOURCE)
@IntDef({
+ TYPE_UNKNOWN,
TYPE_BOOLEAN,
TYPE_FLOAT
})
public @interface ActionType {};
+ public static final @ActionType int TYPE_UNKNOWN = 0;
/**
* The identifier of {@link BooleanAction}.
*/
- public static final @ActionType int TYPE_BOOLEAN = 0;
+ public static final @ActionType int TYPE_BOOLEAN = 1;
/**
* The identifier of {@link FloatAction}.
*/
- public static final @ActionType int TYPE_FLOAT = 1;
+ public static final @ActionType int TYPE_FLOAT = 2;
/**
* @hide
@@ -120,13 +135,9 @@ public abstract class ControlAction implements Parcelable {
/**
* @hide
*/
- ControlAction(Parcel in) {
- mTemplateId = in.readString();
- if (in.readByte() == 1) {
- mChallengeValue = in.readString();
- } else {
- mChallengeValue = null;
- }
+ ControlAction(Bundle b) {
+ mTemplateId = b.getString(KEY_TEMPLATE_ID);
+ mChallengeValue = b.getString(KEY_CHALLENGE_VALUE);
}
/**
@@ -151,15 +162,24 @@ public abstract class ControlAction implements Parcelable {
}
@Override
- public void writeToParcel(Parcel dest, int flags) {
+ public final void writeToParcel(Parcel dest, int flags) {
dest.writeInt(getActionType());
- dest.writeString(mTemplateId);
- if (mChallengeValue != null) {
- dest.writeByte((byte) 1);
- dest.writeString(mChallengeValue);
- } else {
- dest.writeByte((byte) 0);
- }
+ dest.writeBundle(getDataBundle());
+ }
+
+ /**
+ * Obtain a {@link Bundle} describing this object populated with data.
+ *
+ * Implementations in subclasses should populate the {@link Bundle} returned by
+ * {@link ControlAction}.
+ * @return a {@link Bundle} containing the data that represents this object.
+ */
+ @CallSuper
+ protected Bundle getDataBundle() {
+ Bundle b = new Bundle();
+ b.putString(KEY_TEMPLATE_ID, mTemplateId);
+ b.putString(KEY_CHALLENGE_VALUE, mChallengeValue);
+ return b;
}
public static final @NonNull Creator<ControlAction> CREATOR = new Creator<ControlAction>() {
@@ -175,6 +195,7 @@ public abstract class ControlAction implements Parcelable {
}
};
+
private static ControlAction createActionFromType(@ActionType int type, Parcel source) {
switch(type) {
case TYPE_BOOLEAN:
@@ -182,7 +203,8 @@ public abstract class ControlAction implements Parcelable {
case TYPE_FLOAT:
return FloatAction.CREATOR.createFromParcel(source);
default:
- return null;
+ source.readBundle();
+ return UNKNOWN_ACTION;
}
}
diff --git a/core/java/android/service/controls/ControlButton.java b/core/java/android/service/controls/ControlButton.java
index fed31158be35..969c0a75f4ed 100644
--- a/core/java/android/service/controls/ControlButton.java
+++ b/core/java/android/service/controls/ControlButton.java
@@ -29,29 +29,29 @@ import com.android.internal.util.Preconditions;
*/
public class ControlButton implements Parcelable {
- private final boolean mActive;
+ private final boolean mChecked;
private final @NonNull Icon mIcon;
private final @NonNull CharSequence mContentDescription;
/**
- * @param active true if the button should be rendered as active.
+ * @param checked true if the button should be rendered as active.
* @param icon icon to display in the button.
* @param contentDescription content description for the button.
*/
- public ControlButton(boolean active, @NonNull Icon icon,
+ public ControlButton(boolean checked, @NonNull Icon icon,
@NonNull CharSequence contentDescription) {
Preconditions.checkNotNull(icon);
Preconditions.checkNotNull(contentDescription);
- mActive = active;
+ mChecked = checked;
mIcon = icon;
mContentDescription = contentDescription;
}
/**
- * Whether the button should be rendered in its active state.
+ * Whether the button should be rendered in a checked state.
*/
- public boolean isActive() {
- return mActive;
+ public boolean isChecked() {
+ return mChecked;
}
/**
@@ -78,13 +78,13 @@ public class ControlButton implements Parcelable {
@Override
public void writeToParcel(Parcel dest, int flags) {
- dest.writeByte(mActive ? (byte) 1 : (byte) 0);
+ dest.writeByte(mChecked ? (byte) 1 : (byte) 0);
mIcon.writeToParcel(dest, flags);
dest.writeCharSequence(mContentDescription);
}
ControlButton(Parcel in) {
- mActive = in.readByte() != 0;
+ mChecked = in.readByte() != 0;
mIcon = Icon.CREATOR.createFromParcel(in);
mContentDescription = in.readCharSequence();
}
diff --git a/core/java/android/service/controls/ControlState.java b/core/java/android/service/controls/ControlState.java
index 804aef798eb5..1477f9f4e708 100644
--- a/core/java/android/service/controls/ControlState.java
+++ b/core/java/android/service/controls/ControlState.java
@@ -19,6 +19,7 @@ package android.service.controls;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.app.PendingIntent;
import android.content.res.ColorStateList;
import android.graphics.drawable.Icon;
import android.os.Parcel;
@@ -33,11 +34,11 @@ import java.lang.annotation.RetentionPolicy;
* Current state for a {@link Control}.
*
* Collects information to render the current state of a {@link Control} as well as possible action
- * that can be performed on it. Some of the information may temporarily override the defaults
- * provided by the corresponding {@link Control}, while this state is being displayed.
- *
- * Additionally, this can be used to modify information related to the corresponding
- * {@link Control}.
+ * that can be performed on it.
+ * <p>
+ * Additionally, this object is used to modify elements from the {@link Control} such as icons,
+ * colors, names and intents. This information will last until it is again modified by a
+ * {@link ControlState}.
* @hide
*/
public final class ControlState implements Parcelable {
@@ -74,58 +75,81 @@ public final class ControlState implements Parcelable {
*/
public static final int STATUS_DISABLED = 3;
- private final @NonNull Control mControl;
+ private final @NonNull String mControlId;
private final @Status int mStatus;
private final @NonNull ControlTemplate mControlTemplate;
private final @NonNull CharSequence mStatusText;
- private final @Nullable Icon mOverrideIcon;
- private final @Nullable ColorStateList mOverrideTint;
+ private final @Nullable CharSequence mTitle;
+ private final @Nullable PendingIntent mAppIntent;
+ private final @Nullable Icon mIcon;
+ private final @Nullable ColorStateList mTint;
/**
- * @param control the {@link Control} this state should be applied to. Can be used to
- * update information about the {@link Control}
+ * @param controlId the identifier of the {@link Control} this object refers to.
* @param status the current status of the {@link Control}.
- * @param controlTemplate the template to be used to render the {@link Control}.
- * @param statusText the text describing the current status.
- * @param overrideIcon the icon to temporarily override the one provided in
- * {@link Control#getIcon()}. Pass {@code null} to use the icon in
- * {@link Control#getIcon()}.
- * @param overrideTint the colors to temporarily override those provided in
- * {@link Control#getTint()}. Pass {@code null} to use the colors in
- * {@link Control#getTint()}.
+ * @param controlTemplate the template to be used to render the {@link Control}. This can be
+ * of a different
+ * {@link android.service.controls.ControlTemplate.TemplateType} than the
+ * one defined in {@link Control#getPrimaryType}
+ * @param statusText the user facing text describing the current status.
+ * @param title the title to replace the one set in the {@link Control} or set in the
+ * last {@link ControlState}. Pass {@code null} to use the last value set for this
+ * {@link Control}
+ * @param appIntent the {@link PendingIntent} to replace the one set in the {@link Control} or
+ * set in the last {@link ControlState}. Pass {@code null} to use the last
+ * value set for this {@link Control}.
+ * @param icon the icon to replace the one set in the {@link Control} or set in the last
+ * {@link ControlState}. Pass {@code null} to use the last value set for this
+ * {@link Control}.
+ * @param tint the colors to replace those set in the {@link Control} or set in the last
+ * {@link ControlState}. Pass {@code null} to use the last value set for this
+ * {@link Control}.
*/
- public ControlState(@NonNull Control control,
+ public ControlState(@NonNull String controlId,
int status,
@NonNull ControlTemplate controlTemplate,
@NonNull CharSequence statusText,
- @Nullable Icon overrideIcon,
- @Nullable ColorStateList overrideTint) {
- Preconditions.checkNotNull(control);
+ @Nullable CharSequence title,
+ @Nullable PendingIntent appIntent,
+ @Nullable Icon icon,
+ @Nullable ColorStateList tint) {
+ Preconditions.checkNotNull(controlId);
Preconditions.checkNotNull(controlTemplate);
Preconditions.checkNotNull(statusText);
-
- mControl = control;
+ mControlId = controlId;
mStatus = status;
mControlTemplate = controlTemplate;
- mOverrideIcon = overrideIcon;
mStatusText = statusText;
- mOverrideTint = overrideTint;
+ mTitle = title;
+ mAppIntent = appIntent;
+ mIcon = icon;
+ mTint = tint;
}
ControlState(Parcel in) {
- mControl = Control.CREATOR.createFromParcel(in);
+ mControlId = in.readString();
mStatus = in.readInt();
mControlTemplate = ControlTemplate.CREATOR.createFromParcel(in);
mStatusText = in.readCharSequence();
if (in.readByte() == 1) {
- mOverrideIcon = Icon.CREATOR.createFromParcel(in);
+ mTitle = in.readCharSequence();
+ } else {
+ mTitle = null;
+ }
+ if (in.readByte() == 1) {
+ mAppIntent = PendingIntent.CREATOR.createFromParcel(in);
+ } else {
+ mAppIntent = null;
+ }
+ if (in.readByte() == 1) {
+ mIcon = Icon.CREATOR.createFromParcel(in);
} else {
- mOverrideIcon = null;
+ mIcon = null;
}
if (in.readByte() == 1) {
- mOverrideTint = ColorStateList.CREATOR.createFromParcel(in);
+ mTint = ColorStateList.CREATOR.createFromParcel(in);
} else {
- mOverrideTint = null;
+ mTint = null;
}
}
@@ -134,6 +158,21 @@ public final class ControlState implements Parcelable {
return 0;
}
+ @NonNull
+ public String getControlId() {
+ return mControlId;
+ }
+
+ @Nullable
+ public CharSequence getTitle() {
+ return mTitle;
+ }
+
+ @Nullable
+ public PendingIntent getAppIntent() {
+ return mAppIntent;
+ }
+
@Status
public int getStatus() {
return mStatus;
@@ -145,8 +184,8 @@ public final class ControlState implements Parcelable {
}
@Nullable
- public Icon getOverrideIcon() {
- return mOverrideIcon;
+ public Icon getIcon() {
+ return mIcon;
}
@NonNull
@@ -155,35 +194,37 @@ public final class ControlState implements Parcelable {
}
@Nullable
- public ColorStateList getOverrideTint() {
- return mOverrideTint;
- }
-
- @NonNull
- public Control getControl() {
- return mControl;
- }
-
- @NonNull
- public String getControlId() {
- return mControl.getControlId();
+ public ColorStateList getTint() {
+ return mTint;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
- mControl.writeToParcel(dest, flags);
+ dest.writeString(mControlId);
dest.writeInt(mStatus);
mControlTemplate.writeToParcel(dest, flags);
dest.writeCharSequence(mStatusText);
- if (mOverrideIcon != null) {
+ if (mTitle != null) {
+ dest.writeByte((byte) 1);
+ dest.writeCharSequence(mTitle);
+ } else {
+ dest.writeByte((byte) 0);
+ }
+ if (mAppIntent != null) {
+ dest.writeByte((byte) 1);
+ mAppIntent.writeToParcel(dest, flags);
+ } else {
+ dest.writeByte((byte) 0);
+ }
+ if (mIcon != null) {
dest.writeByte((byte) 1);
- mOverrideIcon.writeToParcel(dest, flags);
+ mIcon.writeToParcel(dest, flags);
} else {
dest.writeByte((byte) 0);
}
- if (mOverrideTint != null) {
+ if (mTint != null) {
dest.writeByte((byte) 1);
- mOverrideTint.writeToParcel(dest, flags);
+ mTint.writeToParcel(dest, flags);
} else {
dest.writeByte((byte) 0);
}
@@ -213,19 +254,22 @@ public final class ControlState implements Parcelable {
* </ul>
*/
public static class Builder {
- private @NonNull Control mControl;
+ private @NonNull String mControlId;
private @Status int mStatus = STATUS_OK;
private @NonNull ControlTemplate mControlTemplate = ControlTemplate.NO_TEMPLATE;
private @NonNull CharSequence mStatusText = "";
- private @Nullable Icon mOverrideIcon;
- private @Nullable ColorStateList mOverrideTint;
+ private @Nullable CharSequence mTitle;
+ private @Nullable PendingIntent mAppIntent;
+ private @Nullable Icon mIcon;
+ private @Nullable ColorStateList mTint;
/**
- * @param control the {@link Control} that the resulting {@link ControlState} refers to.
+ * @param controlId the identifier of the {@link Control} that the resulting
+ * {@link ControlState} refers to.
*/
- public Builder(@NonNull Control control) {
- Preconditions.checkNotNull(control);
- mControl = control;
+ public Builder(@NonNull String controlId) {
+ Preconditions.checkNotNull(controlId);
+ mControlId = controlId;
}
/**
@@ -234,21 +278,24 @@ public final class ControlState implements Parcelable {
*/
public Builder(@NonNull ControlState controlState) {
Preconditions.checkNotNull(controlState);
- mControl = controlState.mControl;
+ mControlId = controlState.mControlId;
+ mStatus = controlState.mStatus;
mControlTemplate = controlState.mControlTemplate;
- mOverrideIcon = controlState.mOverrideIcon;
mStatusText = controlState.mStatusText;
- mOverrideTint = controlState.mOverrideTint;
+ mTitle = controlState.mTitle;
+ mAppIntent = controlState.mAppIntent;
+ mIcon = controlState.mIcon;
+ mTint = controlState.mTint;
}
/**
- * @param control the updated {@link Control} information.
+ * @param controlId the identifier of the {@link Control} for the resulting object.
* @return {@code this}
*/
@NonNull
- public Builder setControl(@NonNull Control control) {
- mControl = control;
+ public Builder setControlId(@NonNull String controlId) {
+ mControlId = controlId;
return this;
}
@@ -285,24 +332,50 @@ public final class ControlState implements Parcelable {
}
/**
- * @param overrideIcon the icon to override the one defined in the corresponding
- * {@code Control}. Pass {@code null} to remove the override.
+ * @param title the title to replace the one defined in the corresponding {@link Control} or
+ * set by the last {@link ControlState}. Pass {@code null} to keep the last
+ * value.
+ * @return {@code this}
+ */
+ @NonNull
+ public Builder setTitle(@Nullable CharSequence title) {
+ mTitle = title;
+ return this;
+ }
+
+ /**
+ * @param appIntent the Pending Intent to replace the one defined in the corresponding
+ * {@link Control} or set by the last {@link ControlState}. Pass
+ * {@code null} to keep the last value.
+ * @return {@code this}
+ */
+ @NonNull
+ public Builder setAppIntent(@Nullable PendingIntent appIntent) {
+ mAppIntent = appIntent;
+ return this;
+ }
+
+ /**
+ * @param icon the title to replace the one defined in the corresponding {@link Control} or
+ * set by the last {@link ControlState}. Pass {@code null} to keep the last
+ * value.
* @return {@code this}
*/
@NonNull
- public Builder setOverrideIcon(@Nullable Icon overrideIcon) {
- mOverrideIcon = overrideIcon;
+ public Builder setIcon(@Nullable Icon icon) {
+ mIcon = icon;
return this;
}
/**
- * @param overrideTint the colors to override the ones defined in the corresponding
- * {@code Control}. Pass {@code null} to remove the override.
+ * @param tint the title to replace the one defined in the corresponding {@link Control} or
+ * set by the last {@link ControlState}. Pass {@code null} to keep the last
+ * value.
* @return {@code this}
*/
@NonNull
- public Builder setOverrideTint(@Nullable ColorStateList overrideTint) {
- mOverrideTint = overrideTint;
+ public Builder setTint(@Nullable ColorStateList tint) {
+ mTint = tint;
return this;
}
@@ -310,8 +383,8 @@ public final class ControlState implements Parcelable {
* @return a new {@link ControlState}
*/
public ControlState build() {
- return new ControlState(mControl, mStatus, mControlTemplate, mStatusText,
- mOverrideIcon, mOverrideTint);
+ return new ControlState(mControlId, mStatus, mControlTemplate, mStatusText,
+ mTitle, mAppIntent, mIcon, mTint);
}
}
}
diff --git a/core/java/android/service/controls/ControlTemplate.java b/core/java/android/service/controls/ControlTemplate.java
index e559862e86d6..8bcabd6972a5 100644
--- a/core/java/android/service/controls/ControlTemplate.java
+++ b/core/java/android/service/controls/ControlTemplate.java
@@ -16,8 +16,10 @@
package android.service.controls;
+import android.annotation.CallSuper;
import android.annotation.IntDef;
import android.annotation.NonNull;
+import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
@@ -40,6 +42,8 @@ import java.lang.annotation.RetentionPolicy;
*/
public abstract class ControlTemplate implements Parcelable {
+ private static final String KEY_TEMPLATE_ID = "key_template_id";
+
/**
* Singleton representing a {@link Control} with no input.
*/
@@ -114,17 +118,28 @@ public abstract class ControlTemplate implements Parcelable {
}
@Override
- public void writeToParcel(Parcel dest, int flags) {
+ public final void writeToParcel(Parcel dest, int flags) {
dest.writeInt(getTemplateType());
- dest.writeString(mTemplateId);
+ dest.writeBundle(getDataBundle());
+ }
+
+ /**
+ * Obtain a {@link Bundle} describing this object populated with data.
+ * @return a {@link Bundle} containing the data that represents this object.
+ */
+ @CallSuper
+ protected Bundle getDataBundle() {
+ Bundle b = new Bundle();
+ b.putString(KEY_TEMPLATE_ID, mTemplateId);
+ return b;
}
private ControlTemplate() {
mTemplateId = "";
}
- ControlTemplate(Parcel in) {
- mTemplateId = in.readString();
+ ControlTemplate(@NonNull Bundle b) {
+ mTemplateId = b.getString(KEY_TEMPLATE_ID);
}
/**
@@ -148,6 +163,7 @@ public abstract class ControlTemplate implements Parcelable {
}
};
+
private static ControlTemplate createTemplateFromType(@TemplateType int type, Parcel source) {
switch(type) {
case TYPE_TOGGLE:
@@ -159,9 +175,9 @@ public abstract class ControlTemplate implements Parcelable {
case TYPE_DISCRETE_TOGGLE:
return DiscreteToggleTemplate.CREATOR.createFromParcel(source);
case TYPE_NONE:
- return NO_TEMPLATE;
default:
- return null;
+ source.readBundle();
+ return NO_TEMPLATE;
}
}
}
diff --git a/core/java/android/service/controls/ControlsProviderService.java b/core/java/android/service/controls/ControlsProviderService.java
new file mode 100644
index 000000000000..193b2bcfd869
--- /dev/null
+++ b/core/java/android/service/controls/ControlsProviderService.java
@@ -0,0 +1,147 @@
+/*
+ * Copyright (C) 2019 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.controls;
+
+import android.annotation.NonNull;
+import android.annotation.SdkConstant;
+import android.annotation.SdkConstant.SdkConstantType;
+import android.app.Service;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.Looper;
+import android.os.Message;
+
+import java.util.List;
+
+/**
+ * Service implementation allowing applications to contribute controls to the
+ * System UI.
+ * @hide
+ */
+public abstract class ControlsProviderService extends Service {
+
+ @SdkConstant(SdkConstantType.SERVICE_ACTION)
+ public static final String CONTROLS_ACTION = "android.service.controls.ControlsProviderService";
+
+ private IControlsProviderCallback mCallback;
+ private RequestHandler mHandler;
+
+ /**
+ * Signal to retrieve all Controls. When complete, call
+ * {@link IControlsProviderCallback#onLoad} to inform the caller.
+ */
+ public abstract void load();
+
+ /**
+ * Informs the service that the caller is listening for updates to the given controlIds.
+ * {@link IControlsProviderCallback#onRefreshState} should be called any time
+ * there are Control updates to render.
+ */
+ public abstract void subscribe(@NonNull List<String> controlIds);
+
+ /**
+ * Informs the service that the caller is done listening for updates,
+ * and any calls to {@link IControlsProviderCallback#onRefreshState} will be ignored.
+ */
+ public abstract void unsubscribe();
+
+ /**
+ * The user has interacted with a Control. The action is dictated by the type of
+ * {@link ControlAction} that was sent.
+ */
+ public abstract void onAction(@NonNull String controlId, @NonNull ControlAction action);
+
+ protected IControlsProviderCallback getControlsProviderCallback() {
+ return mCallback;
+ }
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ mHandler = new RequestHandler(Looper.getMainLooper());
+
+ Bundle bundle = intent.getBundleExtra("CALLBACK_BUNDLE");
+ IBinder callbackBinder = bundle.getBinder("CALLBACK_BINDER");
+ mCallback = IControlsProviderCallback.Stub.asInterface(callbackBinder);
+
+ return new IControlsProvider.Stub() {
+ public void load() {
+ mHandler.sendEmptyMessage(RequestHandler.MSG_LOAD);
+ }
+
+ public void subscribe(List<String> ids) {
+ mHandler.obtainMessage(RequestHandler.MSG_SUBSCRIBE, ids).sendToTarget();
+ }
+
+ public void unsubscribe() {
+ mHandler.sendEmptyMessage(RequestHandler.MSG_UNSUBSCRIBE);
+ }
+
+ public void onAction(String id, ControlAction action) {
+ ActionMessage msg = new ActionMessage(id, action);
+ mHandler.obtainMessage(RequestHandler.MSG_SUBSCRIBE, msg).sendToTarget();
+ }
+ };
+ }
+
+ @Override
+ public boolean onUnbind(Intent intent) {
+ mCallback = null;
+ mHandler = null;
+ return true;
+ }
+
+ private class RequestHandler extends Handler {
+ private static final int MSG_LOAD = 1;
+ private static final int MSG_SUBSCRIBE = 2;
+ private static final int MSG_UNSUBSCRIBE = 3;
+ private static final int MSG_ON_ACTION = 4;
+
+ RequestHandler(Looper looper) {
+ super(looper);
+ }
+
+ public void handleMessage(Message msg) {
+ switch(msg.what) {
+ case MSG_LOAD:
+ ControlsProviderService.this.load();
+ break;
+ case MSG_SUBSCRIBE:
+ List<String> ids = (List<String>) msg.obj;
+ ControlsProviderService.this.subscribe(ids);
+ break;
+ case MSG_UNSUBSCRIBE:
+ ControlsProviderService.this.unsubscribe();
+ break;
+ case MSG_ON_ACTION:
+ ActionMessage aMsg = (ActionMessage) msg.obj;
+ ControlsProviderService.this.onAction(aMsg.mId, aMsg.mAction);
+ break;
+ }
+ }
+ }
+
+ private class ActionMessage {
+ final String mId;
+ final ControlAction mAction;
+
+ ActionMessage(String id, ControlAction action) {
+ this.mId = id;
+ this.mAction = action;
+ }
+ }
+}
diff --git a/core/java/android/service/controls/DiscreteToggleTemplate.java b/core/java/android/service/controls/DiscreteToggleTemplate.java
index 5167af41c2f0..571825299c77 100644
--- a/core/java/android/service/controls/DiscreteToggleTemplate.java
+++ b/core/java/android/service/controls/DiscreteToggleTemplate.java
@@ -17,6 +17,7 @@
package android.service.controls;
import android.annotation.NonNull;
+import android.os.Bundle;
import android.os.Parcel;
import com.android.internal.util.Preconditions;
@@ -34,6 +35,9 @@ import com.android.internal.util.Preconditions;
*/
public class DiscreteToggleTemplate extends ControlTemplate {
+ private static final String KEY_NEGATIVE_BUTTON = "key_negative_button";
+ private static final String KEY_POSITIVE_BUTTON = "key_positive_button";
+
private final @NonNull ControlButton mNegativeButton;
private final @NonNull ControlButton mPositiveButton;
@@ -52,10 +56,10 @@ public class DiscreteToggleTemplate extends ControlTemplate {
mPositiveButton = positiveButton;
}
- DiscreteToggleTemplate(Parcel in) {
- super(in);
- this.mNegativeButton = ControlButton.CREATOR.createFromParcel(in);
- this.mPositiveButton = ControlButton.CREATOR.createFromParcel(in);
+ DiscreteToggleTemplate(Bundle b) {
+ super(b);
+ mNegativeButton = b.getParcelable(KEY_NEGATIVE_BUTTON);
+ mPositiveButton = b.getParcelable(KEY_POSITIVE_BUTTON);
}
/**
@@ -89,17 +93,18 @@ public class DiscreteToggleTemplate extends ControlTemplate {
}
@Override
- public void writeToParcel(Parcel dest, int flags) {
- super.writeToParcel(dest, flags);
- mNegativeButton.writeToParcel(dest, flags);
- mPositiveButton.writeToParcel(dest, flags);
+ protected Bundle getDataBundle() {
+ Bundle b = super.getDataBundle();
+ b.putObject(KEY_NEGATIVE_BUTTON, mNegativeButton);
+ b.putObject(KEY_POSITIVE_BUTTON, mPositiveButton);
+ return b;
}
public static final Creator<DiscreteToggleTemplate> CREATOR =
new Creator<DiscreteToggleTemplate>() {
@Override
public DiscreteToggleTemplate createFromParcel(Parcel source) {
- return new DiscreteToggleTemplate(source);
+ return new DiscreteToggleTemplate(source.readBundle());
}
@Override
diff --git a/core/java/android/service/controls/FloatAction.java b/core/java/android/service/controls/FloatAction.java
index fe6db10a98cd..229435f647a2 100644
--- a/core/java/android/service/controls/FloatAction.java
+++ b/core/java/android/service/controls/FloatAction.java
@@ -18,6 +18,7 @@ package android.service.controls;
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.os.Bundle;
import android.os.Parcel;
/**
@@ -26,6 +27,8 @@ import android.os.Parcel;
*/
public final class FloatAction extends ControlAction {
+ private static final String KEY_NEW_VALUE = "key_new_value";
+
private final float mNewValue;
/**
@@ -50,9 +53,9 @@ public final class FloatAction extends ControlAction {
mNewValue = newValue;
}
- public FloatAction(Parcel in) {
- super(in);
- mNewValue = in.readFloat();
+ public FloatAction(Bundle b) {
+ super(b);
+ mNewValue = b.getFloat(KEY_NEW_VALUE);
}
/**
@@ -71,15 +74,16 @@ public final class FloatAction extends ControlAction {
}
@Override
- public void writeToParcel(Parcel dest, int flags) {
- super.writeToParcel(dest, flags);
- dest.writeFloat(mNewValue);
+ protected Bundle getDataBundle() {
+ Bundle b = super.getDataBundle();
+ b.putFloat(KEY_NEW_VALUE, mNewValue);
+ return b;
}
public static final @NonNull Creator<FloatAction> CREATOR = new Creator<FloatAction>() {
@Override
public FloatAction createFromParcel(Parcel source) {
- return new FloatAction(source);
+ return new FloatAction(source.readBundle());
}
@Override
diff --git a/core/java/android/service/controls/RangeTemplate.java b/core/java/android/service/controls/RangeTemplate.java
index 70bf2dd4aad4..f0bce30081b8 100644
--- a/core/java/android/service/controls/RangeTemplate.java
+++ b/core/java/android/service/controls/RangeTemplate.java
@@ -18,10 +18,9 @@ package android.service.controls;
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.os.Bundle;
import android.os.Parcel;
-import com.android.internal.util.Preconditions;
-
import java.security.InvalidParameterException;
/**
@@ -32,6 +31,12 @@ import java.security.InvalidParameterException;
*/
public final class RangeTemplate extends ControlTemplate {
+ private static final String KEY_MIN_VALUE = "key_min_value";
+ private static final String KEY_MAX_VALUE = "key_max_value";
+ private static final String KEY_CURRENT_VALUE = "key_current_value";
+ private static final String KEY_STEP_VALUE = "key_step_value";
+ private static final String KEY_FORMAT_STRING = "key_format_string";
+
private final float mMinValue;
private final float mMaxValue;
private final float mCurrentValue;
@@ -67,7 +72,6 @@ public final class RangeTemplate extends ControlTemplate {
float stepValue,
@Nullable CharSequence formatString) {
super(templateId);
- Preconditions.checkNotNull(formatString);
mMinValue = minValue;
mMaxValue = maxValue;
mCurrentValue = currentValue;
@@ -87,13 +91,13 @@ public final class RangeTemplate extends ControlTemplate {
* @see RangeTemplate#RangeTemplate(String, float, float, float, float, CharSequence)
* @hide
*/
- RangeTemplate(Parcel in) {
- super(in);
- mMinValue = in.readFloat();
- mMaxValue = in.readFloat();
- mCurrentValue = in.readFloat();
- mStepValue = in.readFloat();
- mFormatString = in.readCharSequence();
+ RangeTemplate(Bundle b) {
+ super(b);
+ mMinValue = b.getFloat(KEY_MIN_VALUE);
+ mMaxValue = b.getFloat(KEY_MAX_VALUE);
+ mCurrentValue = b.getFloat(KEY_CURRENT_VALUE);
+ mStepValue = b.getFloat(KEY_STEP_VALUE);
+ mFormatString = b.getCharSequence(KEY_FORMAT_STRING, "%.1f");
validate();
}
@@ -144,13 +148,14 @@ public final class RangeTemplate extends ControlTemplate {
}
@Override
- public void writeToParcel(Parcel dest, int flags) {
- super.writeToParcel(dest, flags);
- dest.writeFloat(mMinValue);
- dest.writeFloat(mMaxValue);
- dest.writeFloat(mCurrentValue);
- dest.writeFloat(mStepValue);
- dest.writeCharSequence(mFormatString);
+ protected Bundle getDataBundle() {
+ Bundle b = super.getDataBundle();
+ b.putFloat(KEY_MIN_VALUE, mMinValue);
+ b.putFloat(KEY_MAX_VALUE, mMaxValue);
+ b.putFloat(KEY_CURRENT_VALUE, mCurrentValue);
+ b.putFloat(KEY_STEP_VALUE, mStepValue);
+ b.putCharSequence(KEY_FORMAT_STRING, mFormatString);
+ return b;
}
/**
@@ -179,7 +184,7 @@ public final class RangeTemplate extends ControlTemplate {
public static final Creator<RangeTemplate> CREATOR = new Creator<RangeTemplate>() {
@Override
public RangeTemplate createFromParcel(Parcel source) {
- return new RangeTemplate(source);
+ return new RangeTemplate(source.readBundle());
}
@Override
diff --git a/core/java/android/service/controls/ThumbnailTemplate.java b/core/java/android/service/controls/ThumbnailTemplate.java
index 796d2de89576..6e729c011196 100644
--- a/core/java/android/service/controls/ThumbnailTemplate.java
+++ b/core/java/android/service/controls/ThumbnailTemplate.java
@@ -18,6 +18,7 @@ package android.service.controls;
import android.annotation.NonNull;
import android.graphics.drawable.Icon;
+import android.os.Bundle;
import android.os.Parcel;
import com.android.internal.util.Preconditions;
@@ -28,6 +29,9 @@ import com.android.internal.util.Preconditions;
*/
public final class ThumbnailTemplate extends ControlTemplate {
+ private static final String KEY_ICON = "key_icon";
+ private static final String KEY_CONTENT_DESCRIPTION = "key_content_description";
+
private final @NonNull Icon mThumbnail;
private final @NonNull CharSequence mContentDescription;
@@ -45,10 +49,10 @@ public final class ThumbnailTemplate extends ControlTemplate {
mContentDescription = contentDescription;
}
- ThumbnailTemplate(Parcel in) {
- super(in);
- mThumbnail = Icon.CREATOR.createFromParcel(in);
- mContentDescription = in.readCharSequence();
+ ThumbnailTemplate(Bundle b) {
+ super(b);
+ mThumbnail = b.getParcelable(KEY_ICON);
+ mContentDescription = b.getCharSequence(KEY_CONTENT_DESCRIPTION, "");
}
/**
@@ -74,17 +78,19 @@ public final class ThumbnailTemplate extends ControlTemplate {
public int getTemplateType() {
return TYPE_THUMBNAIL;
}
+
@Override
- public void writeToParcel(Parcel dest, int flags) {
- super.writeToParcel(dest, flags);
- mThumbnail.writeToParcel(dest, flags);
- dest.writeCharSequence(mContentDescription);
+ protected Bundle getDataBundle() {
+ Bundle b = super.getDataBundle();
+ b.putObject(KEY_ICON, mThumbnail);
+ b.putObject(KEY_CONTENT_DESCRIPTION, mContentDescription);
+ return b;
}
public static final Creator<ThumbnailTemplate> CREATOR = new Creator<ThumbnailTemplate>() {
@Override
public ThumbnailTemplate createFromParcel(Parcel source) {
- return new ThumbnailTemplate(source);
+ return new ThumbnailTemplate(source.readBundle());
}
@Override
diff --git a/core/java/android/service/controls/ToggleTemplate.java b/core/java/android/service/controls/ToggleTemplate.java
index 3766bd168477..4c4fd5e33cde 100644
--- a/core/java/android/service/controls/ToggleTemplate.java
+++ b/core/java/android/service/controls/ToggleTemplate.java
@@ -17,6 +17,7 @@
package android.service.controls;
import android.annotation.NonNull;
+import android.os.Bundle;
import android.os.Parcel;
import com.android.internal.util.Preconditions;
@@ -24,7 +25,7 @@ import com.android.internal.util.Preconditions;
/**
* A template for a {@link Control} with a single button that can be toggled between two states.
*
- * The states for the toggle correspond to the states in {@link ControlButton#isActive()}.
+ * The states for the toggle correspond to the states in {@link ControlButton#isChecked()}.
* An action on this template will originate a {@link BooleanAction} to change that state.
*
* @see BooleanAction
@@ -32,6 +33,7 @@ import com.android.internal.util.Preconditions;
*/
public final class ToggleTemplate extends ControlTemplate {
+ private static final String KEY_BUTTON = "key_button";
private final @NonNull ControlButton mButton;
/**
@@ -44,9 +46,9 @@ public final class ToggleTemplate extends ControlTemplate {
mButton = button;
}
- ToggleTemplate(Parcel in) {
- super(in);
- mButton = ControlButton.CREATOR.createFromParcel(in);
+ ToggleTemplate(Bundle b) {
+ super(b);
+ mButton = b.getParcelable(KEY_BUTTON);
}
/**
@@ -66,15 +68,16 @@ public final class ToggleTemplate extends ControlTemplate {
}
@Override
- public void writeToParcel(Parcel dest, int flags) {
- super.writeToParcel(dest, flags);
- mButton.writeToParcel(dest, flags);
+ protected Bundle getDataBundle() {
+ Bundle b = super.getDataBundle();
+ b.putObject(KEY_BUTTON, mButton);
+ return b;
}
public static final Creator<ToggleTemplate> CREATOR = new Creator<ToggleTemplate>() {
@Override
public ToggleTemplate createFromParcel(Parcel source) {
- return new ToggleTemplate(source);
+ return new ToggleTemplate(source.readBundle());
}
@Override
diff --git a/core/java/android/service/dataloader/DataLoaderService.java b/core/java/android/service/dataloader/DataLoaderService.java
new file mode 100644
index 000000000000..373e1e5f979f
--- /dev/null
+++ b/core/java/android/service/dataloader/DataLoaderService.java
@@ -0,0 +1,307 @@
+/*
+ * Copyright (C) 2019 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.dataloader;
+
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.app.Service;
+import android.content.Intent;
+import android.content.pm.DataLoaderParams;
+import android.content.pm.DataLoaderParamsParcel;
+import android.content.pm.FileSystemControlParcel;
+import android.content.pm.IDataLoader;
+import android.content.pm.IDataLoaderStatusListener;
+import android.content.pm.IPackageInstallerSessionFileSystemConnector;
+import android.content.pm.InstallationFile;
+import android.content.pm.NamedParcelFileDescriptor;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.ParcelFileDescriptor;
+import android.os.RemoteException;
+import android.util.ExceptionUtils;
+import android.util.Slog;
+
+import java.io.IOException;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.util.List;
+
+/**
+ * The base class for implementing data loader service to control data loaders. Expecting
+ * Incremental Service to bind to a children class of this.
+ *
+ * @hide
+ *
+ * Hide for now, should be @SystemApi
+ * TODO(b/136132412): update with latest API design
+ */
+public abstract class DataLoaderService extends Service {
+ private static final String TAG = "IncrementalDataLoaderService";
+ private final DataLoaderBinderService mBinder = new DataLoaderBinderService();
+
+ public static final int DATA_LOADER_READY =
+ IDataLoaderStatusListener.DATA_LOADER_READY;
+ public static final int DATA_LOADER_NOT_READY =
+ IDataLoaderStatusListener.DATA_LOADER_NOT_READY;
+ public static final int DATA_LOADER_RUNNING =
+ IDataLoaderStatusListener.DATA_LOADER_RUNNING;
+ public static final int DATA_LOADER_STOPPED =
+ IDataLoaderStatusListener.DATA_LOADER_STOPPED;
+ public static final int DATA_LOADER_SLOW_CONNECTION =
+ IDataLoaderStatusListener.DATA_LOADER_SLOW_CONNECTION;
+ public static final int DATA_LOADER_NO_CONNECTION =
+ IDataLoaderStatusListener.DATA_LOADER_NO_CONNECTION;
+ public static final int DATA_LOADER_CONNECTION_OK =
+ IDataLoaderStatusListener.DATA_LOADER_CONNECTION_OK;
+
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(prefix = {"DATA_LOADER_"}, value = {
+ DATA_LOADER_READY,
+ DATA_LOADER_NOT_READY,
+ DATA_LOADER_RUNNING,
+ DATA_LOADER_STOPPED,
+ DATA_LOADER_SLOW_CONNECTION,
+ DATA_LOADER_NO_CONNECTION,
+ DATA_LOADER_CONNECTION_OK
+ })
+ public @interface DataLoaderStatus {
+ }
+
+ /**
+ * Managed DataLoader interface. Each instance corresponds to a single Incremental File System
+ * instance.
+ */
+ public abstract static class DataLoader {
+ /**
+ * A virtual constructor used to do simple initialization. Not ready to serve any data yet.
+ * All heavy-lifting has to be done in onStart.
+ *
+ * @param params Data loader configuration parameters.
+ * @param connector IncFS API wrapper.
+ * @param listener Used for reporting internal state to IncrementalService.
+ * @return True if initialization of a Data Loader was successful. False will be reported to
+ * IncrementalService and can cause an unmount of an IFS instance.
+ */
+ public abstract boolean onCreate(@NonNull DataLoaderParams params,
+ @NonNull FileSystemConnector connector,
+ @NonNull StatusListener listener);
+
+ /**
+ * Start the data loader. After this method returns data loader is considered to be ready to
+ * receive callbacks from IFS, supply data via connector and send status updates via
+ * callbacks.
+ *
+ * @return True if Data Loader was able to start. False will be reported to
+ * IncrementalService and can cause an unmount of an IFS instance.
+ */
+ public abstract boolean onStart();
+
+ /**
+ * Stop the data loader. Use to stop any additional threads and free up resources. Data
+ * loader is not longer responsible for supplying data. Start/Stop pair can be called
+ * multiple times e.g. if IFS detects corruption and data needs to be re-loaded.
+ */
+ public abstract void onStop();
+
+ /**
+ * Virtual destructor. Use to cleanup all internal state. After this method returns, the
+ * data loader can no longer use connector or callbacks. For any additional operations with
+ * this instance of IFS a new DataLoader will be created using createDataLoader method.
+ */
+ public abstract void onDestroy();
+ }
+
+ /**
+ * DataLoader factory method.
+ *
+ * @return An instance of a DataLoader.
+ */
+ public abstract @Nullable DataLoader onCreateDataLoader();
+
+ /**
+ * @hide
+ */
+ public final @NonNull IBinder onBind(@NonNull Intent intent) {
+ return (IBinder) mBinder;
+ }
+
+ private class DataLoaderBinderService extends IDataLoader.Stub {
+ private int mId;
+
+ @Override
+ public void create(int id, @NonNull Bundle options,
+ @NonNull IDataLoaderStatusListener listener)
+ throws IllegalArgumentException, RuntimeException {
+ mId = id;
+ final DataLoaderParamsParcel params = options.getParcelable("params");
+ if (params == null) {
+ throw new IllegalArgumentException("Must specify Incremental data loader params");
+ }
+ final FileSystemControlParcel control =
+ options.getParcelable("control");
+ if (control == null) {
+ throw new IllegalArgumentException("Must specify Incremental control parcel");
+ }
+ mStatusListener = listener;
+ try {
+ if (!nativeCreateDataLoader(id, control, params, listener)) {
+ Slog.e(TAG, "Failed to create native loader for " + mId);
+ }
+ } catch (Exception ex) {
+ destroy();
+ throw new RuntimeException(ex);
+ } finally {
+ // Closing FDs.
+ if (control.incremental.cmd != null) {
+ try {
+ control.incremental.cmd.close();
+ } catch (IOException e) {
+ Slog.e(TAG, "Failed to close IncFs CMD file descriptor " + e);
+ }
+ }
+ if (control.incremental.log != null) {
+ try {
+ control.incremental.log.close();
+ } catch (IOException e) {
+ Slog.e(TAG, "Failed to close IncFs LOG file descriptor " + e);
+ }
+ }
+ NamedParcelFileDescriptor[] fds = params.dynamicArgs;
+ for (NamedParcelFileDescriptor nfd : fds) {
+ try {
+ nfd.fd.close();
+ } catch (IOException e) {
+ Slog.e(TAG,
+ "Failed to close DynamicArgs parcel file descriptor " + e);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void start(List<InstallationFile> fileInfos) {
+ if (!nativeStartDataLoader(mId)) {
+ Slog.e(TAG, "Failed to start loader: loader not found for " + mId);
+ }
+ }
+
+ @Override
+ public void stop() {
+ if (!nativeStopDataLoader(mId)) {
+ Slog.w(TAG, "Failed to stop loader: loader not found for " + mId);
+ }
+ }
+
+ @Override
+ public void destroy() {
+ if (!nativeDestroyDataLoader(mId)) {
+ Slog.w(TAG, "Failed to destroy loader: loader not found for " + mId);
+ }
+ }
+ }
+
+ /**
+ *
+ * Used by the DataLoaderService implementations.
+ *
+ * @hide
+ *
+ * TODO(b/136132412) Should be @SystemApi
+ */
+ public static final class FileSystemConnector {
+ /**
+ * Creates a wrapper for an installation session connector.
+ * @hide
+ */
+ FileSystemConnector(IPackageInstallerSessionFileSystemConnector connector) {
+ mConnector = connector;
+ }
+
+ /**
+ * Write data to an installation file from an arbitrary FD.
+ *
+ * @param name name of file previously added to the installation session.
+ * @param offsetBytes offset into the file to begin writing at, or 0 to
+ * start at the beginning of the file.
+ * @param lengthBytes total size of the file being written, used to
+ * preallocate the underlying disk space, or -1 if unknown.
+ * The system may clear various caches as needed to allocate
+ * this space.
+ * @param incomingFd FD to read bytes from.
+ * @throws IOException if trouble opening the file for writing, such as
+ * lack of disk space or unavailable media.
+ */
+ public void writeData(String name, long offsetBytes, long lengthBytes,
+ ParcelFileDescriptor incomingFd) throws IOException {
+ try {
+ mConnector.writeData(name, offsetBytes, lengthBytes, incomingFd);
+ } catch (RuntimeException e) {
+ ExceptionUtils.maybeUnwrapIOException(e);
+ throw e;
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ private final IPackageInstallerSessionFileSystemConnector mConnector;
+ }
+
+ /**
+ * Wrapper for native reporting DataLoader statuses.
+ * @hide
+ * TODO(b/136132412) Should be @SystemApi
+ */
+ public static final class StatusListener {
+ /**
+ * Creates a wrapper for a native instance.
+ * @hide
+ */
+ StatusListener(long nativeInstance) {
+ mNativeInstance = nativeInstance;
+ }
+
+ /**
+ * Report the status of DataLoader. Used for system-wide notifications e.g., disabling
+ * applications which rely on this data loader to function properly.
+ *
+ * @param status status to report.
+ * @return True if status was reported successfully.
+ */
+ public boolean onStatusChanged(@DataLoaderStatus int status) {
+ return nativeReportStatus(mNativeInstance, status);
+ }
+
+ private final long mNativeInstance;
+ }
+
+ private IDataLoaderStatusListener mStatusListener = null;
+
+ /* Native methods */
+ private native boolean nativeCreateDataLoader(int storageId,
+ @NonNull FileSystemControlParcel control,
+ @NonNull DataLoaderParamsParcel params,
+ IDataLoaderStatusListener listener);
+
+ private native boolean nativeStartDataLoader(int storageId);
+
+ private native boolean nativeStopDataLoader(int storageId);
+
+ private native boolean nativeDestroyDataLoader(int storageId);
+
+ private static native boolean nativeReportStatus(long nativeInstance, int status);
+}
diff --git a/core/java/android/service/dreams/Sandman.java b/core/java/android/service/dreams/Sandman.java
index efb8923a459f..f2cedbc7aa92 100644
--- a/core/java/android/service/dreams/Sandman.java
+++ b/core/java/android/service/dreams/Sandman.java
@@ -36,12 +36,6 @@ import android.util.Slog;
public final class Sandman {
private static final String TAG = "Sandman";
- // The component name of a special dock app that merely launches a dream.
- // We don't want to launch this app when docked because it causes an unnecessary
- // activity transition. We just want to start the dream.
- private static final ComponentName SOMNAMBULATOR_COMPONENT =
- new ComponentName("com.android.systemui", "com.android.systemui.Somnambulator");
-
// The sandman is eternal. No one instantiates him.
private Sandman() {
@@ -52,8 +46,11 @@ public final class Sandman {
* False if we should dream instead, if appropriate.
*/
public static boolean shouldStartDockApp(Context context, Intent intent) {
+ final ComponentName somnambulatorComponent = ComponentName.unflattenFromString(
+ context.getResources().getString(
+ com.android.internal.R.string.config_somnambulatorComponent));
ComponentName name = intent.resolveActivity(context.getPackageManager());
- return name != null && !name.equals(SOMNAMBULATOR_COMPONENT);
+ return name != null && !name.equals(somnambulatorComponent);
}
/**
diff --git a/core/java/android/service/notification/Adjustment.java b/core/java/android/service/notification/Adjustment.java
index 8ab687f0d001..c84fbc7287bb 100644
--- a/core/java/android/service/notification/Adjustment.java
+++ b/core/java/android/service/notification/Adjustment.java
@@ -124,6 +124,13 @@ public final class Adjustment implements Parcelable {
public static final String KEY_IMPORTANCE = "key_importance";
/**
+ * Data type: float, a ranking score from 0 (lowest) to 1 (highest).
+ * Used to rank notifications inside that fall under the same classification (i.e. alerting,
+ * silenced).
+ */
+ public static final String KEY_RANKING_SCORE = "key_ranking_score";
+
+ /**
* Create a notification adjustment.
*
* @param pkg The package of the notification.
diff --git a/core/java/android/service/notification/NotificationListenerService.java b/core/java/android/service/notification/NotificationListenerService.java
index 85f13d552fcf..c04ac5929e1f 100644
--- a/core/java/android/service/notification/NotificationListenerService.java
+++ b/core/java/android/service/notification/NotificationListenerService.java
@@ -1895,7 +1895,8 @@ public abstract class NotificationListenerService extends Service {
&& ((mSmartActions == null ? 0 : mSmartActions.size())
== (other.mSmartActions == null ? 0 : other.mSmartActions.size()))
&& Objects.equals(mSmartReplies, other.mSmartReplies)
- && Objects.equals(mCanBubble, other.mCanBubble);
+ && Objects.equals(mCanBubble, other.mCanBubble)
+ && Objects.equals(mVisuallyInterruptive, other.mVisuallyInterruptive);
}
}
diff --git a/core/java/android/service/quicksettings/TileService.java b/core/java/android/service/quicksettings/TileService.java
index dd2586cd58ad..d0675ed4b99a 100644
--- a/core/java/android/service/quicksettings/TileService.java
+++ b/core/java/android/service/quicksettings/TileService.java
@@ -481,9 +481,12 @@ public class TileService extends Service {
* as true on their TileService Manifest declaration, and will do nothing otherwise.
*/
public static final void requestListeningState(Context context, ComponentName component) {
+ final ComponentName sysuiComponent = ComponentName.unflattenFromString(
+ context.getResources().getString(
+ com.android.internal.R.string.config_systemUIServiceComponent));
Intent intent = new Intent(ACTION_REQUEST_LISTENING);
intent.putExtra(Intent.EXTRA_COMPONENT_NAME, component);
- intent.setPackage("com.android.systemui");
+ intent.setPackage(sysuiComponent.getPackageName());
context.sendBroadcast(intent, Manifest.permission.BIND_QUICK_SETTINGS_TILE);
}
}
diff --git a/core/java/android/service/sms/FinancialSmsService.java b/core/java/android/service/sms/FinancialSmsService.java
deleted file mode 100644
index 5fb7249b6ecb..000000000000
--- a/core/java/android/service/sms/FinancialSmsService.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2018 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.sms;
-
-import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.app.Service;
-import android.content.Intent;
-import android.database.CursorWindow;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.IBinder;
-import android.os.Looper;
-import android.os.RemoteCallback;
-import android.os.RemoteException;
-
-/**
- * A service to support sms messages read for financial apps.
- *
- * {@hide}
- */
-@SystemApi
-public abstract class FinancialSmsService extends Service {
-
- private static final String TAG = "FinancialSmsService";
-
- /**
- * The {@link Intent} action that must be declared as handled by a service
- * in its manifest for the system to recognize it as a quota providing
- * service.
- */
- public static final String ACTION_FINANCIAL_SERVICE_INTENT =
- "android.service.sms.action.FINANCIAL_SERVICE_INTENT";
-
- /** {@hide} **/
- public static final String EXTRA_SMS_MSGS = "sms_messages";
-
- private FinancialSmsServiceWrapper mWrapper;
-
- private void getSmsMessages(RemoteCallback callback, Bundle params) {
- final Bundle data = new Bundle();
- CursorWindow smsMessages = onGetSmsMessages(params);
- if (smsMessages != null) {
- data.putParcelable(EXTRA_SMS_MSGS, smsMessages);
- }
- callback.sendResult(data);
- }
-
- private final Handler mHandler = new Handler(Looper.getMainLooper(), null, true);
-
- /** @hide */
- public FinancialSmsService() {
- }
-
- @Override
- public void onCreate() {
- super.onCreate();
- mWrapper = new FinancialSmsServiceWrapper();
- }
-
- @Override
- public IBinder onBind(Intent intent) {
- return mWrapper;
- }
-
- /**
- * Get sms messages for financial apps.
- *
- * @param params parameters passed in by the calling app.
- * @return the {@code CursorWindow} with all sms messages for the app to read.
- *
- * {@hide}
- */
- @Nullable
- @SystemApi
- public abstract CursorWindow onGetSmsMessages(@NonNull Bundle params);
-
- private final class FinancialSmsServiceWrapper extends IFinancialSmsService.Stub {
- @Override
- public void getSmsMessages(RemoteCallback callback, Bundle params) throws RemoteException {
- mHandler.sendMessage(obtainMessage(
- FinancialSmsService::getSmsMessages,
- FinancialSmsService.this,
- callback, params));
- }
- }
-
-}
diff --git a/core/java/android/service/textclassifier/TextClassifierService.java b/core/java/android/service/textclassifier/TextClassifierService.java
index 20dc2beeaa48..8dca69f856e5 100644
--- a/core/java/android/service/textclassifier/TextClassifierService.java
+++ b/core/java/android/service/textclassifier/TextClassifierService.java
@@ -37,7 +37,6 @@ import android.os.IBinder;
import android.os.Looper;
import android.os.Parcelable;
import android.os.RemoteException;
-import android.provider.Settings;
import android.text.TextUtils;
import android.util.Slog;
import android.view.textclassifier.ConversationActions;
@@ -437,28 +436,16 @@ public abstract class TextClassifierService extends Service {
/**
* Returns the component name of the system default textclassifier service if it can be found
* on the system. Otherwise, returns null.
- * @hide
- */
- public static ComponentName getServiceComponentName(@NonNull Context context) {
- return getServiceComponentName(context, new TextClassificationConstants(
- () -> Settings.Global.getString(
- context.getContentResolver(),
- Settings.Global.TEXT_CLASSIFIER_CONSTANTS)));
- }
-
- /**
- * Returns the component name of the system default textclassifier service if it can be found
- * on the system. Otherwise, returns null.
- * @param context the text classification context
- * @param settings TextClassifier specific settings.
*
+ * @param context the text classification context
* @hide
*/
@Nullable
- public static ComponentName getServiceComponentName(@NonNull Context context,
- @NonNull TextClassificationConstants settings) {
+ public static ComponentName getServiceComponentName(@NonNull Context context) {
+ final TextClassificationConstants settings = TextClassificationManager.getSettings(context);
// get override TextClassifierService package name
- String packageName = settings.getTextClassifierServiceName();
+ String packageName = settings.getTextClassifierServicePackageOverride();
+
ComponentName serviceComponent = null;
final boolean isOverrideService = !TextUtils.isEmpty(packageName);
if (isOverrideService) {
@@ -468,7 +455,7 @@ public abstract class TextClassifierService extends Service {
if (serviceComponent != null) {
return serviceComponent;
}
- // If no TextClassifierService overrode or invalid override package name, read the first
+ // If no TextClassifierService override or invalid override package name, read the first
// package defined in the config
final String[] packages = context.getPackageManager().getSystemTextClassifierPackages();
if (packages.length == 0 || TextUtils.isEmpty(packages[0])) {
diff --git a/core/java/android/service/voice/VoiceInteractionSession.java b/core/java/android/service/voice/VoiceInteractionSession.java
index c9d37bf86a27..52b72949ee04 100644
--- a/core/java/android/service/voice/VoiceInteractionSession.java
+++ b/core/java/android/service/voice/VoiceInteractionSession.java
@@ -1137,6 +1137,7 @@ public class VoiceInteractionSession implements KeyEvent.Callback, ComponentCall
mWindow = new SoftInputWindow(mContext, "VoiceInteractionSession", mTheme,
mCallbacks, this, mDispatcherState,
WindowManager.LayoutParams.TYPE_VOICE_INTERACTION, Gravity.BOTTOM, true);
+ mWindow.getWindow().setFitWindowInsetsTypes(0 /* types */);
mWindow.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED |
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
diff --git a/core/java/android/service/wallpaper/WallpaperService.java b/core/java/android/service/wallpaper/WallpaperService.java
index d5c67668b88e..e50d6c206a11 100644
--- a/core/java/android/service/wallpaper/WallpaperService.java
+++ b/core/java/android/service/wallpaper/WallpaperService.java
@@ -811,6 +811,7 @@ public abstract class WallpaperService extends Service {
// Add window
mLayout.type = mIWallpaperEngine.mWindowType;
mLayout.gravity = Gravity.START|Gravity.TOP;
+ mLayout.setFitWindowInsetsTypes(0 /* types */);
mLayout.setTitle(WallpaperService.this.getClass().getName());
mLayout.windowAnimations =
com.android.internal.R.style.Animation_Wallpaper;
diff --git a/core/java/android/telephony/CellBroadcastIntents.java b/core/java/android/telephony/CellBroadcastIntents.java
index 4474f3ecc620..8446253c6302 100644
--- a/core/java/android/telephony/CellBroadcastIntents.java
+++ b/core/java/android/telephony/CellBroadcastIntents.java
@@ -26,7 +26,6 @@ import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.UserHandle;
-import android.util.Log;
/**
* A static helper class used to send Intents with prepopulated flags.
@@ -75,20 +74,20 @@ public class CellBroadcastIntents {
@Nullable String receiverAppOp, @Nullable BroadcastReceiver resultReceiver,
@Nullable Handler scheduler, int initialCode, @Nullable String initialData,
@Nullable Bundle initialExtras) {
- Log.d(LOG_TAG, "sendOrderedBroadcastForBackgroundReceivers intent=" + intent.getAction());
int status = context.checkCallingOrSelfPermission(
"android.permission.GRANT_RUNTIME_PERMISSIONS_TO_TELEPHONY_DEFAULTS");
if (status == PackageManager.PERMISSION_DENIED) {
throw new SecurityException(
"Caller does not have permission to send broadcast for background receivers");
}
- intent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
+ Intent backgroundIntent = new Intent(intent);
+ backgroundIntent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
if (user != null) {
- context.createContextAsUser(user, 0).sendOrderedBroadcast(intent, receiverPermission,
- receiverAppOp, resultReceiver, scheduler, initialCode, initialData,
- initialExtras);
+ context.createContextAsUser(user, 0).sendOrderedBroadcast(backgroundIntent,
+ receiverPermission, receiverAppOp, resultReceiver, scheduler, initialCode,
+ initialData, initialExtras);
} else {
- context.sendOrderedBroadcast(intent, receiverPermission,
+ context.sendOrderedBroadcast(backgroundIntent, receiverPermission,
receiverAppOp, resultReceiver, scheduler, initialCode, initialData,
initialExtras);
}
diff --git a/core/java/android/telephony/PhoneStateListener.java b/core/java/android/telephony/PhoneStateListener.java
index 716a5225ea91..51a9c864ee29 100644
--- a/core/java/android/telephony/PhoneStateListener.java
+++ b/core/java/android/telephony/PhoneStateListener.java
@@ -35,8 +35,8 @@ import android.telephony.Annotation.SrvccState;
import android.telephony.emergency.EmergencyNumber;
import android.telephony.ims.ImsReasonInfo;
-import com.android.internal.telephony.IPhoneStateListener;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.telephony.IPhoneStateListener;
import dalvik.system.VMRuntime;
@@ -169,14 +169,6 @@ public class PhoneStateListener {
public static final int LISTEN_SIGNAL_STRENGTHS = 0x00000100;
/**
- * Listen for changes to OTASP mode.
- *
- * @see #onOtaspChanged
- * @hide
- */
- public static final int LISTEN_OTASP_CHANGED = 0x00000200;
-
- /**
* Listen for changes to observed cell info.
*
* @see #onCellInfoChanged
@@ -196,12 +188,13 @@ public class PhoneStateListener {
/**
* Listen for {@link PreciseDataConnectionState} on the data connection (cellular).
*
- * @see #onPreciseDataConnectionStateChanged
+ * <p>Requires permission {@link android.Manifest.permission#MODIFY_PHONE_STATE}
+ * or the calling app has carrier privileges
+ * (see {@link TelephonyManager#hasCarrierPrivileges}).
*
- * @hide
+ * @see #onPreciseDataConnectionStateChanged
*/
- @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
- @SystemApi
+ @RequiresPermission((android.Manifest.permission.MODIFY_PHONE_STATE))
public static final int LISTEN_PRECISE_DATA_CONNECTION_STATE = 0x00001000;
/**
@@ -624,29 +617,6 @@ public class PhoneStateListener {
// default implementation empty
}
-
- /**
- * The Over The Air Service Provisioning (OTASP) has changed on the registered subscription.
- * Note, the registration subId comes from {@link TelephonyManager} object which registers
- * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
- * If this TelephonyManager object was created with
- * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
- * subId. Otherwise, this callback applies to
- * {@link SubscriptionManager#getDefaultSubscriptionId()}.
- *
- * Requires the READ_PHONE_STATE permission.
- * @param otaspMode is integer <code>OTASP_UNKNOWN=1<code>
- * means the value is currently unknown and the system should wait until
- * <code>OTASP_NEEDED=2<code> or <code>OTASP_NOT_NEEDED=3<code> is received before
- * making the decision to perform OTASP or not.
- *
- * @hide
- */
- @UnsupportedAppUsage
- public void onOtaspChanged(int otaspMode) {
- // default implementation empty
- }
-
/**
* Callback invoked when a observed cell info has changed or new cells have been added
* or removed on the registered subscription.
@@ -719,8 +689,9 @@ public class PhoneStateListener {
}
/**
- * Callback invoked when data connection state changes with precise information
- * on the registered subscription.
+ * Callback providing update about the default/internet data connection on the registered
+ * subscription.
+ *
* Note, the registration subId comes from {@link TelephonyManager} object which registers
* PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
* If this TelephonyManager object was created with
@@ -728,12 +699,13 @@ public class PhoneStateListener {
* subId. Otherwise, this callback applies to
* {@link SubscriptionManager#getDefaultSubscriptionId()}.
*
- * @param dataConnectionState {@link PreciseDataConnectionState}
+ * <p>Requires permission {@link android.Manifest.permission#MODIFY_PHONE_STATE}
+ * or the calling app has carrier privileges
+ * (see {@link TelephonyManager#hasCarrierPrivileges}).
*
- * @hide
+ * @param dataConnectionState {@link PreciseDataConnectionState}
*/
- @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
- @SystemApi
+ @RequiresPermission((android.Manifest.permission.MODIFY_PHONE_STATE))
public void onPreciseDataConnectionStateChanged(
@NonNull PreciseDataConnectionState dataConnectionState) {
// default implementation empty
@@ -1042,11 +1014,21 @@ public class PhoneStateListener {
PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
if (psl == null) return;
- Binder.withCleanCallingIdentity(() -> mExecutor.execute(
- () -> {
- psl.onDataConnectionStateChanged(state, networkType);
- psl.onDataConnectionStateChanged(state);
- }));
+ if (state == TelephonyManager.DATA_DISCONNECTING
+ && VMRuntime.getRuntime().getTargetSdkVersion() < Build.VERSION_CODES.R) {
+ Binder.withCleanCallingIdentity(() -> mExecutor.execute(
+ () -> {
+ psl.onDataConnectionStateChanged(
+ TelephonyManager.DATA_CONNECTED, networkType);
+ psl.onDataConnectionStateChanged(TelephonyManager.DATA_CONNECTED);
+ }));
+ } else {
+ Binder.withCleanCallingIdentity(() -> mExecutor.execute(
+ () -> {
+ psl.onDataConnectionStateChanged(state, networkType);
+ psl.onDataConnectionStateChanged(state);
+ }));
+ }
}
public void onDataActivity(int direction) {
@@ -1065,14 +1047,6 @@ public class PhoneStateListener {
() -> mExecutor.execute(() -> psl.onSignalStrengthsChanged(signalStrength)));
}
- public void onOtaspChanged(int otaspMode) {
- PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
- if (psl == null) return;
-
- Binder.withCleanCallingIdentity(
- () -> mExecutor.execute(() -> psl.onOtaspChanged(otaspMode)));
- }
-
public void onCellInfoChanged(List<CellInfo> cellInfo) {
PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
if (psl == null) return;
diff --git a/core/java/android/telephony/TelephonyRegistryManager.java b/core/java/android/telephony/TelephonyRegistryManager.java
index 9d7b57ba250d..f574160e5303 100644
--- a/core/java/android/telephony/TelephonyRegistryManager.java
+++ b/core/java/android/telephony/TelephonyRegistryManager.java
@@ -21,17 +21,13 @@ import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.content.Context;
-import android.net.LinkProperties;
-import android.net.NetworkCapabilities;
import android.os.Binder;
import android.os.Bundle;
import android.os.RemoteException;
import android.os.ServiceManager;
-import android.telephony.Annotation.ApnType;
import android.telephony.Annotation.CallState;
import android.telephony.Annotation.DataActivityType;
import android.telephony.Annotation.DataFailureCause;
-import android.telephony.Annotation.DataState;
import android.telephony.Annotation.NetworkType;
import android.telephony.Annotation.PreciseCallStates;
import android.telephony.Annotation.RadioPowerState;
@@ -357,27 +353,18 @@ public class TelephonyRegistryManager {
* @param subId for which data connection state changed.
* @param slotIndex for which data connections state changed. Can be derived from subId except
* when subId is invalid.
- * @param state latest data connection state, e.g,
- * @param isDataConnectivityPossible indicates if data is allowed
- * @param apn the APN {@link ApnSetting#getApnName()} of this data connection.
- * @param apnType the apnType, "ims" for IMS APN, "emergency" for EMERGENCY APN.
- * @param linkProperties {@link LinkProperties} associated with this data connection.
- * @param networkCapabilities {@link NetworkCapabilities} associated with this data connection.
- * @param networkType associated with this data connection.
- * @param roaming {@code true} indicates in roaming, {@false} otherwise.
- * @see TelephonyManager#DATA_DISCONNECTED
- * @see TelephonyManager#isDataConnectivityPossible()
+ * @param apnType the APN type that triggered this update
+ * @param preciseState the PreciseDataConnectionState
*
+ * @see android.telephony.PreciseDataConnection
+ * @see TelephonyManager#DATA_DISCONNECTED
* @hide
*/
- public void notifyDataConnectionForSubscriber(int slotIndex, int subId, @DataState int state,
- boolean isDataConnectivityPossible,
- @ApnType String apn, String apnType, LinkProperties linkProperties,
- NetworkCapabilities networkCapabilities, int networkType, boolean roaming) {
+ public void notifyDataConnectionForSubscriber(int slotIndex, int subId,
+ String apnType, PreciseDataConnectionState preciseState) {
try {
- sRegistry.notifyDataConnectionForSubscriber(slotIndex, subId, state,
- isDataConnectivityPossible,
- apn, apnType, linkProperties, networkCapabilities, networkType, roaming);
+ sRegistry.notifyDataConnectionForSubscriber(
+ slotIndex, subId, apnType, preciseState);
} catch (RemoteException ex) {
// system process is dead
}
@@ -600,22 +587,6 @@ public class TelephonyRegistryManager {
}
/**
- * Notify over the air sim provisioning(OTASP) mode changed on certain subscription.
- *
- * @param subId for which otasp mode changed.
- * @param otaspMode latest mode for OTASP e.g, OTASP needed.
- *
- * @hide
- */
- public void notifyOtaspChanged(int subId, int otaspMode) {
- try {
- sRegistry.notifyOtaspChanged(subId, otaspMode);
- } catch (RemoteException ex) {
- // system process is dead
- }
- }
-
- /**
* Notify precise call state changed on certain subscription, including foreground, background
* and ringcall states.
*
@@ -662,25 +633,6 @@ public class TelephonyRegistryManager {
}
/**
- * Notify data connection failed on certain subscription.
- *
- * @param subId for which data connection failed.
- * @param slotIndex for which data conenction faled. Can be derived from subId except when subId
- * is invalid.
- * @param apnType the apnType, "ims" for IMS APN, "emergency" for EMERGENCY APN. Note each data
- * connection can support multiple anyTypes.
- *
- * @hide
- */
- public void notifyDataConnectionFailed(int subId, int slotIndex, String apnType) {
- try {
- sRegistry.notifyDataConnectionFailedForSubscriber(slotIndex, subId, apnType);
- } catch (RemoteException ex) {
- // system process is dead
- }
- }
-
- /**
* TODO change from bundle to CellLocation?
* @hide
*/
diff --git a/core/java/android/text/AlteredCharSequence.java b/core/java/android/text/AlteredCharSequence.java
index 4cc71fd28e4b..971a47dba6e8 100644
--- a/core/java/android/text/AlteredCharSequence.java
+++ b/core/java/android/text/AlteredCharSequence.java
@@ -16,12 +16,14 @@
package android.text;
-// XXX should this really be in the public API at all?
/**
* An AlteredCharSequence is a CharSequence that is largely mirrored from
* another CharSequence, except that a specified range of characters are
* mirrored from a different char array instead.
+ *
+ * @deprecated The functionality this class offers is easily implemented outside the framework.
*/
+@Deprecated
public class AlteredCharSequence
implements CharSequence, GetChars
{
diff --git a/core/java/android/text/format/DateUtils.java b/core/java/android/text/format/DateUtils.java
index b00a9385eec8..0c279230fab0 100644
--- a/core/java/android/text/format/DateUtils.java
+++ b/core/java/android/text/format/DateUtils.java
@@ -59,8 +59,12 @@ public class DateUtils
public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;
public static final long WEEK_IN_MILLIS = DAY_IN_MILLIS * 7;
/**
- * This constant is actually the length of 364 days, not of a year!
+ * @deprecated Not all years have the same number of days, and this constant is actually the
+ * length of 364 days. Please use other date/time constructs such as
+ * {@link java.util.concurrent.TimeUnit}, {@link java.util.Calendar} or
+ * {@link java.time.Duration} instead.
*/
+ @Deprecated
public static final long YEAR_IN_MILLIS = WEEK_IN_MILLIS * 52;
// The following FORMAT_* symbols are used for specifying the format of
diff --git a/core/java/android/util/CloseGuard.java b/core/java/android/util/CloseGuard.java
new file mode 100644
index 000000000000..6ac769623bff
--- /dev/null
+++ b/core/java/android/util/CloseGuard.java
@@ -0,0 +1,145 @@
+/*
+ * Copyright (C) 2019 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.util;
+
+import android.annotation.NonNull;
+
+/**
+ * CloseGuard is a mechanism for flagging implicit finalizer cleanup of
+ * resources that should have been cleaned up by explicit close
+ * methods (aka "explicit termination methods" in Effective Java).
+ * <p>
+ * A simple example: <pre> {@code
+ * class Foo {
+ *
+ * private final CloseGuard guard = CloseGuard.get();
+ *
+ * ...
+ *
+ * public Foo() {
+ * ...;
+ * guard.open("cleanup");
+ * }
+ *
+ * public void cleanup() {
+ * guard.close();
+ * ...;
+ * if (Build.VERSION.SDK_INT >= 28) {
+ * Reference.reachabilityFence(this);
+ * }
+ * // For full correctness in the absence of a close() call, other methods may also need
+ * // reachabilityFence() calls.
+ * }
+ *
+ * protected void finalize() throws Throwable {
+ * try {
+ * // Note that guard could be null if the constructor threw.
+ * if (guard != null) {
+ * guard.warnIfOpen();
+ * }
+ * cleanup();
+ * } finally {
+ * super.finalize();
+ * }
+ * }
+ * }
+ * }</pre>
+ *
+ * In usage where the resource to be explicitly cleaned up is
+ * allocated after object construction, CloseGuard protection can
+ * be deferred. For example: <pre> {@code
+ * class Bar {
+ *
+ * private final CloseGuard guard = CloseGuard.get();
+ *
+ * ...
+ *
+ * public Bar() {
+ * ...;
+ * }
+ *
+ * public void connect() {
+ * ...;
+ * guard.open("cleanup");
+ * }
+ *
+ * public void cleanup() {
+ * guard.close();
+ * ...;
+ * if (Build.VERSION.SDK_INT >= 28) {
+ * Reference.reachabilityFence(this);
+ * }
+ * // For full correctness in the absence of a close() call, other methods may also need
+ * // reachabilityFence() calls.
+ * }
+ *
+ * protected void finalize() throws Throwable {
+ * try {
+ * // Note that guard could be null if the constructor threw.
+ * if (guard != null) {
+ * guard.warnIfOpen();
+ * }
+ * cleanup();
+ * } finally {
+ * super.finalize();
+ * }
+ * }
+ * }
+ * }</pre>
+ *
+ * When used in a constructor, calls to {@code open} should occur at
+ * the end of the constructor since an exception that would cause
+ * abrupt termination of the constructor will mean that the user will
+ * not have a reference to the object to cleanup explicitly. When used
+ * in a method, the call to {@code open} should occur just after
+ * resource acquisition.
+ */
+public final class CloseGuard {
+ private final dalvik.system.CloseGuard mImpl;
+
+ /**
+ * Constructs a new CloseGuard instance.
+ * {@link #open(String)} can be used to set up the instance to warn on failure to close.
+ */
+ public CloseGuard() {
+ mImpl = dalvik.system.CloseGuard.get();
+ }
+
+ /**
+ * Initializes the instance with a warning that the caller should have explicitly called the
+ * {@code closeMethodName} method instead of relying on finalization.
+ *
+ * @param closeMethodName non-null name of explicit termination method. Printed by warnIfOpen.
+ * @throws NullPointerException if closeMethodName is null.
+ */
+ public void open(@NonNull String closeMethodName) {
+ mImpl.open(closeMethodName);
+ }
+
+ /** Marks this CloseGuard instance as closed to avoid warnings on finalization. */
+ public void close() {
+ mImpl.close();
+ }
+
+ /**
+ * Logs a warning if the caller did not properly cleanup by calling an explicit close method
+ * before finalization.
+ */
+ public void warnIfOpen() {
+ mImpl.warnIfOpen();
+ }
+}
diff --git a/core/java/android/util/FeatureFlagUtils.java b/core/java/android/util/FeatureFlagUtils.java
index 236e5ae6f952..1b2db36c1335 100644
--- a/core/java/android/util/FeatureFlagUtils.java
+++ b/core/java/android/util/FeatureFlagUtils.java
@@ -59,6 +59,7 @@ public class FeatureFlagUtils {
DEFAULT_FLAGS.put(SETTINGS_WIFITRACKER2, "false");
DEFAULT_FLAGS.put("settings_work_profile", "true");
DEFAULT_FLAGS.put("settings_controller_loading_enhancement", "false");
+ DEFAULT_FLAGS.put("settings_conditionals", "false");
}
/**
diff --git a/core/java/android/util/LongArrayQueue.java b/core/java/android/util/LongArrayQueue.java
index d5f048434b32..5c701dbebdfb 100644
--- a/core/java/android/util/LongArrayQueue.java
+++ b/core/java/android/util/LongArrayQueue.java
@@ -162,4 +162,24 @@ public class LongArrayQueue {
final int index = (mTail == 0) ? mValues.length - 1 : mTail - 1;
return mValues[index];
}
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String toString() {
+ if (mSize <= 0) {
+ return "{}";
+ }
+
+ final StringBuilder buffer = new StringBuilder(mSize * 64);
+ buffer.append('{');
+ buffer.append(get(0));
+ for (int i = 1; i < mSize; i++) {
+ buffer.append(", ");
+ buffer.append(get(i));
+ }
+ buffer.append('}');
+ return buffer.toString();
+ }
}
diff --git a/core/java/android/util/SparseSetArray.java b/core/java/android/util/SparseSetArray.java
index c1873d76f46f..9f0f24617f5d 100644
--- a/core/java/android/util/SparseSetArray.java
+++ b/core/java/android/util/SparseSetArray.java
@@ -27,8 +27,8 @@ public class SparseSetArray<T> {
}
/**
- * Add a value at index n.
- * @return FALSE when the value already existed at the given index, TRUE otherwise.
+ * Add a value for key n.
+ * @return FALSE when the value already existed for the given key, TRUE otherwise.
*/
public boolean add(int n, T value) {
ArraySet<T> set = mData.get(n);
@@ -51,7 +51,7 @@ public class SparseSetArray<T> {
}
/**
- * @return whether a value exists at index n.
+ * @return whether the value exists for the key n.
*/
public boolean contains(int n, T value) {
final ArraySet<T> set = mData.get(n);
@@ -62,15 +62,15 @@ public class SparseSetArray<T> {
}
/**
- * @return the set of items at index n
+ * @return the set of items of key n
*/
public ArraySet<T> get(int n) {
return mData.get(n);
}
/**
- * Remove a value from index n.
- * @return TRUE when the value existed at the given index and removed, FALSE otherwise.
+ * Remove a value for key n.
+ * @return TRUE when the value existed for the given key and removed, FALSE otherwise.
*/
public boolean remove(int n, T value) {
final ArraySet<T> set = mData.get(n);
@@ -85,7 +85,7 @@ public class SparseSetArray<T> {
}
/**
- * Remove all values from index n.
+ * Remove all values for key n.
*/
public void remove(int n) {
mData.remove(n);
diff --git a/core/java/android/util/StatsLog.java b/core/java/android/util/StatsLog.java
index 8cb5b05df685..952d7cbcd119 100644
--- a/core/java/android/util/StatsLog.java
+++ b/core/java/android/util/StatsLog.java
@@ -24,7 +24,7 @@ import android.annotation.NonNull;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.content.Context;
-import android.os.IStatsManager;
+import android.os.IStatsd;
import android.os.RemoteException;
import android.os.ServiceManager;
@@ -36,7 +36,7 @@ public final class StatsLog extends StatsLogInternal {
private static final String TAG = "StatsLog";
private static final boolean DEBUG = false;
- private static IStatsManager sService;
+ private static IStatsd sService;
private static Object sLogLock = new Object();
@@ -52,7 +52,7 @@ public final class StatsLog extends StatsLogInternal {
public static boolean logStart(int label) {
synchronized (sLogLock) {
try {
- IStatsManager service = getIStatsManagerLocked();
+ IStatsd service = getIStatsdLocked();
if (service == null) {
if (DEBUG) {
Slog.d(TAG, "Failed to find statsd when logging start");
@@ -81,7 +81,7 @@ public final class StatsLog extends StatsLogInternal {
public static boolean logStop(int label) {
synchronized (sLogLock) {
try {
- IStatsManager service = getIStatsManagerLocked();
+ IStatsd service = getIStatsdLocked();
if (service == null) {
if (DEBUG) {
Slog.d(TAG, "Failed to find statsd when logging stop");
@@ -109,7 +109,7 @@ public final class StatsLog extends StatsLogInternal {
public static boolean logEvent(int label) {
synchronized (sLogLock) {
try {
- IStatsManager service = getIStatsManagerLocked();
+ IStatsd service = getIStatsdLocked();
if (service == null) {
if (DEBUG) {
Slog.d(TAG, "Failed to find statsd when logging event");
@@ -151,7 +151,7 @@ public final class StatsLog extends StatsLogInternal {
@NonNull long[] experimentIds) {
synchronized (sLogLock) {
try {
- IStatsManager service = getIStatsManagerLocked();
+ IStatsd service = getIStatsdLocked();
if (service == null) {
if (DEBUG) {
Slog.d(TAG, "Failed to find statsd when logging event");
@@ -191,7 +191,7 @@ public final class StatsLog extends StatsLogInternal {
long packageVersionCode, int rollbackReason, String failingPackageName) {
synchronized (sLogLock) {
try {
- IStatsManager service = getIStatsManagerLocked();
+ IStatsd service = getIStatsdLocked();
if (service == null) {
if (DEBUG) {
Slog.d(TAG, "Failed to find statsd when logging event");
@@ -215,11 +215,11 @@ public final class StatsLog extends StatsLogInternal {
}
- private static IStatsManager getIStatsManagerLocked() throws RemoteException {
+ private static IStatsd getIStatsdLocked() throws RemoteException {
if (sService != null) {
return sService;
}
- sService = IStatsManager.Stub.asInterface(ServiceManager.getService("stats"));
+ sService = IStatsd.Stub.asInterface(ServiceManager.getService("stats"));
return sService;
}
@@ -248,12 +248,15 @@ public final class StatsLog extends StatsLogInternal {
/**
* Write an event to stats log using the raw format encapsulated in StatsEvent.
+ * After writing to stats log, release() is called on the StatsEvent object.
+ * No further action should be taken on the StatsEvent object following this call.
*
* @param statsEvent The StatsEvent object containing the encoded buffer of data to write.
* @hide
*/
public static void write(@NonNull final StatsEvent statsEvent) {
writeImpl(statsEvent.getBytes(), statsEvent.getNumBytes(), statsEvent.getAtomId());
+ statsEvent.release();
}
private static void enforceDumpCallingPermission(Context context) {
diff --git a/core/java/android/util/apk/VerityBuilder.java b/core/java/android/util/apk/VerityBuilder.java
index 443bbd8597af..e81e3f7b38d6 100644
--- a/core/java/android/util/apk/VerityBuilder.java
+++ b/core/java/android/util/apk/VerityBuilder.java
@@ -70,22 +70,6 @@ public abstract class VerityBuilder {
/**
* Generates the 4k, SHA-256 based Merkle tree for the given APK and stores in the {@link
- * ByteBuffer} created by the {@link ByteBufferFactory}. The output is suitable to be used as
- * the on-disk format for fs-verity to use.
- *
- * @return VerityResult containing a buffer with the generated Merkle tree stored at the
- * front, the tree size, and the calculated root hash.
- */
- @NonNull
- public static VerityResult generateFsVerityTree(@NonNull RandomAccessFile apk,
- @NonNull ByteBufferFactory bufferFactory)
- throws IOException, SecurityException, NoSuchAlgorithmException, DigestException {
- return generateVerityTreeInternal(apk, bufferFactory, null /* signatureInfo */,
- false /* skipSigningBlock */);
- }
-
- /**
- * Generates the 4k, SHA-256 based Merkle tree for the given APK and stores in the {@link
* ByteBuffer} created by the {@link ByteBufferFactory}. The Merkle tree does not cover Signing
* Block specificed in {@code signatureInfo}. The output is suitable to be used as the on-disk
* format for fs-verity to use (with elide and patch extensions).
@@ -97,21 +81,16 @@ public abstract class VerityBuilder {
public static VerityResult generateApkVerityTree(@NonNull RandomAccessFile apk,
@Nullable SignatureInfo signatureInfo, @NonNull ByteBufferFactory bufferFactory)
throws IOException, SecurityException, NoSuchAlgorithmException, DigestException {
- return generateVerityTreeInternal(apk, bufferFactory, signatureInfo,
- true /* skipSigningBlock */);
+ return generateVerityTreeInternal(apk, bufferFactory, signatureInfo);
}
@NonNull
private static VerityResult generateVerityTreeInternal(@NonNull RandomAccessFile apk,
- @NonNull ByteBufferFactory bufferFactory, @Nullable SignatureInfo signatureInfo,
- boolean skipSigningBlock)
+ @NonNull ByteBufferFactory bufferFactory, @Nullable SignatureInfo signatureInfo)
throws IOException, SecurityException, NoSuchAlgorithmException, DigestException {
- long dataSize = apk.length();
- if (skipSigningBlock) {
- long signingBlockSize =
- signatureInfo.centralDirOffset - signatureInfo.apkSigningBlockOffset;
- dataSize -= signingBlockSize;
- }
+ long signingBlockSize =
+ signatureInfo.centralDirOffset - signatureInfo.apkSigningBlockOffset;
+ long dataSize = apk.length() - signingBlockSize;
int[] levelOffset = calculateVerityLevelOffset(dataSize);
int merkleTreeSize = levelOffset[levelOffset.length - 1];
@@ -120,10 +99,8 @@ public abstract class VerityBuilder {
+ CHUNK_SIZE_BYTES); // maximum size of apk-verity metadata
output.order(ByteOrder.LITTLE_ENDIAN);
ByteBuffer tree = slice(output, 0, merkleTreeSize);
- // Only use default salt in legacy case.
- byte[] salt = skipSigningBlock ? DEFAULT_SALT : null;
- byte[] apkRootHash = generateVerityTreeInternal(apk, signatureInfo, salt, levelOffset,
- tree, skipSigningBlock);
+ byte[] apkRootHash = generateVerityTreeInternal(apk, signatureInfo, DEFAULT_SALT,
+ levelOffset, tree);
return new VerityResult(output, merkleTreeSize, apkRootHash);
}
@@ -173,8 +150,7 @@ public abstract class VerityBuilder {
throws IOException, SignatureNotFoundException, SecurityException, DigestException,
NoSuchAlgorithmException {
try (RandomAccessFile apk = new RandomAccessFile(apkPath, "r")) {
- VerityResult result = generateVerityTreeInternal(apk, bufferFactory, signatureInfo,
- true /* skipSigningBlock */);
+ VerityResult result = generateVerityTreeInternal(apk, bufferFactory, signatureInfo);
ByteBuffer footer = slice(result.verityData, result.merkleTreeSize,
result.verityData.limit());
generateApkVerityFooter(apk, signatureInfo, footer);
@@ -351,17 +327,12 @@ public abstract class VerityBuilder {
@NonNull
private static byte[] generateVerityTreeInternal(@NonNull RandomAccessFile apk,
@Nullable SignatureInfo signatureInfo, @Nullable byte[] salt,
- @NonNull int[] levelOffset, @NonNull ByteBuffer output, boolean skipSigningBlock)
+ @NonNull int[] levelOffset, @NonNull ByteBuffer output)
throws IOException, NoSuchAlgorithmException, DigestException {
// 1. Digest the apk to generate the leaf level hashes.
- if (skipSigningBlock) {
- assertSigningBlockAlignedAndHasFullPages(signatureInfo);
- generateApkVerityDigestAtLeafLevel(apk, signatureInfo, salt, slice(output,
- levelOffset[levelOffset.length - 2], levelOffset[levelOffset.length - 1]));
- } else {
- generateFsVerityDigestAtLeafLevel(apk, slice(output,
- levelOffset[levelOffset.length - 2], levelOffset[levelOffset.length - 1]));
- }
+ assertSigningBlockAlignedAndHasFullPages(signatureInfo);
+ generateApkVerityDigestAtLeafLevel(apk, signatureInfo, salt, slice(output,
+ levelOffset[levelOffset.length - 2], levelOffset[levelOffset.length - 1]));
// 2. Digest the lower level hashes bottom up.
for (int level = levelOffset.length - 3; level >= 0; level--) {
diff --git a/core/java/android/view/Choreographer.java b/core/java/android/view/Choreographer.java
index 28eb79ae1f2a..987edf7761d2 100644
--- a/core/java/android/view/Choreographer.java
+++ b/core/java/android/view/Choreographer.java
@@ -16,13 +16,13 @@
package android.view;
-import static android.view.DisplayEventReceiver.CONFIG_CHANGED_EVENT_SUPPRESS;
import static android.view.DisplayEventReceiver.VSYNC_SOURCE_APP;
import static android.view.DisplayEventReceiver.VSYNC_SOURCE_SURFACE_FLINGER;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.FrameInfo;
+import android.graphics.Insets;
import android.hardware.display.DisplayManagerGlobal;
import android.os.Build;
import android.os.Handler;
@@ -219,9 +219,10 @@ public final class Choreographer {
/**
* Callback type: Animation callback to handle inset updates. This is separate from
* {@link #CALLBACK_ANIMATION} as we need to "gather" all inset animation updates via
- * {@link WindowInsetsAnimationController#changeInsets} for multiple ongoing animations but then
- * update the whole view system with a single callback to {@link View#dispatchWindowInsetsAnimationProgress}
- * that contains all the combined updated insets.
+ * {@link WindowInsetsAnimationController#setInsetsAndAlpha(Insets, float, float)} for multiple
+ * ongoing animations but then update the whole view system with a single callback to
+ * {@link View#dispatchWindowInsetsAnimationProgress} that contains all the combined updated
+ * insets.
* <p>
* Both input and animation may change insets, so we need to run this after these callbacks, but
* before traversals.
diff --git a/core/java/android/view/ContextThemeWrapper.java b/core/java/android/view/ContextThemeWrapper.java
index 696e048ffed8..876331b5c57f 100644
--- a/core/java/android/view/ContextThemeWrapper.java
+++ b/core/java/android/view/ContextThemeWrapper.java
@@ -18,7 +18,7 @@ package android.view;
import android.annotation.Nullable;
import android.annotation.StyleRes;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.AssetManager;
diff --git a/core/java/android/view/Display.java b/core/java/android/view/Display.java
index 03e68b0058b2..1a6ec4e1d3ed 100644
--- a/core/java/android/view/Display.java
+++ b/core/java/android/view/Display.java
@@ -22,8 +22,8 @@ import android.annotation.IntDef;
import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.KeyguardManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.res.CompatibilityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
@@ -1525,5 +1525,14 @@ public final class Display {
public int describeContents() {
return 0;
}
+
+ @Override
+ public String toString() {
+ return "HdrCapabilities{"
+ + "mSupportedHdrTypes=" + Arrays.toString(mSupportedHdrTypes)
+ + ", mMaxLuminance=" + mMaxLuminance
+ + ", mMaxAverageLuminance=" + mMaxAverageLuminance
+ + ", mMinLuminance=" + mMinLuminance + '}';
+ }
}
}
diff --git a/core/java/android/view/DisplayAdjustments.java b/core/java/android/view/DisplayAdjustments.java
index da4d92fa0c94..834dd7b6e7d8 100644
--- a/core/java/android/view/DisplayAdjustments.java
+++ b/core/java/android/view/DisplayAdjustments.java
@@ -16,7 +16,7 @@
package android.view;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.res.CompatibilityInfo;
import android.content.res.Configuration;
diff --git a/core/java/android/view/DisplayCutout.java b/core/java/android/view/DisplayCutout.java
index 411508faa84b..615dab0f04e4 100644
--- a/core/java/android/view/DisplayCutout.java
+++ b/core/java/android/view/DisplayCutout.java
@@ -66,6 +66,7 @@ public final class DisplayCutout {
private static final String BOTTOM_MARKER = "@bottom";
private static final String DP_MARKER = "@dp";
private static final String RIGHT_MARKER = "@right";
+ private static final String LEFT_MARKER = "@left";
/**
* Category for overlays that allow emulating a display cutout on devices that don't have
@@ -647,6 +648,9 @@ public final class DisplayCutout {
if (spec.endsWith(RIGHT_MARKER)) {
offsetX = displayWidth;
spec = spec.substring(0, spec.length() - RIGHT_MARKER.length()).trim();
+ } else if (spec.endsWith(LEFT_MARKER)) {
+ offsetX = 0;
+ spec = spec.substring(0, spec.length() - LEFT_MARKER.length()).trim();
} else {
offsetX = displayWidth / 2f;
}
diff --git a/core/java/android/view/DisplayEventReceiver.java b/core/java/android/view/DisplayEventReceiver.java
index 91acc4638c26..eaf297cc05d8 100644
--- a/core/java/android/view/DisplayEventReceiver.java
+++ b/core/java/android/view/DisplayEventReceiver.java
@@ -16,7 +16,7 @@
package android.view;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Looper;
import android.os.MessageQueue;
import android.util.Log;
diff --git a/core/java/android/view/DisplayInfo.java b/core/java/android/view/DisplayInfo.java
index 04e82c72da89..8a5385d6e2b2 100644
--- a/core/java/android/view/DisplayInfo.java
+++ b/core/java/android/view/DisplayInfo.java
@@ -24,7 +24,7 @@ import static android.view.DisplayInfoProto.LOGICAL_WIDTH;
import static android.view.DisplayInfoProto.NAME;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.res.CompatibilityInfo;
import android.content.res.Configuration;
import android.graphics.Rect;
diff --git a/core/java/android/view/DisplayListCanvas.java b/core/java/android/view/DisplayListCanvas.java
index 8e6e99a6d949..6035cbebb032 100644
--- a/core/java/android/view/DisplayListCanvas.java
+++ b/core/java/android/view/DisplayListCanvas.java
@@ -16,7 +16,7 @@
package android.view;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.BaseRecordingCanvas;
import android.graphics.CanvasProperty;
import android.graphics.Paint;
diff --git a/core/java/android/view/DragEvent.java b/core/java/android/view/DragEvent.java
index 2a43bcc00daf..35af0f252d2d 100644
--- a/core/java/android/view/DragEvent.java
+++ b/core/java/android/view/DragEvent.java
@@ -16,7 +16,7 @@
package android.view;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ClipData;
import android.content.ClipDescription;
import android.os.Parcel;
diff --git a/core/java/android/view/FrameMetrics.java b/core/java/android/view/FrameMetrics.java
index ea66656bfc45..054dff726ca1 100644
--- a/core/java/android/view/FrameMetrics.java
+++ b/core/java/android/view/FrameMetrics.java
@@ -17,7 +17,7 @@
package android.view;
import android.annotation.IntDef;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
diff --git a/core/java/android/view/FrameMetricsObserver.java b/core/java/android/view/FrameMetricsObserver.java
index 0f38e847f4bd..41bc9a742752 100644
--- a/core/java/android/view/FrameMetricsObserver.java
+++ b/core/java/android/view/FrameMetricsObserver.java
@@ -17,11 +17,8 @@
package android.view;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
-import android.os.Looper;
-import android.os.MessageQueue;
-
-import com.android.internal.util.VirtualRefBasePtr;
+import android.graphics.HardwareRendererObserver;
+import android.os.Handler;
import java.lang.ref.WeakReference;
@@ -31,47 +28,39 @@ import java.lang.ref.WeakReference;
*
* @hide
*/
-public class FrameMetricsObserver {
- @UnsupportedAppUsage
- private MessageQueue mMessageQueue;
-
- private WeakReference<Window> mWindow;
-
- @UnsupportedAppUsage
- private FrameMetrics mFrameMetrics;
-
- /* pacage */ Window.OnFrameMetricsAvailableListener mListener;
- /** @hide */
- public VirtualRefBasePtr mNative;
+public class FrameMetricsObserver
+ implements HardwareRendererObserver.OnFrameMetricsAvailableListener {
+ private final WeakReference<Window> mWindow;
+ private final FrameMetrics mFrameMetrics;
+ private final HardwareRendererObserver mObserver;
+ /*package*/ final Window.OnFrameMetricsAvailableListener mListener;
/**
* Creates a FrameMetricsObserver
*
- * @param looper the looper to use when invoking callbacks
+ * @param handler the Handler to use when invoking callbacks
*/
- FrameMetricsObserver(@NonNull Window window, @NonNull Looper looper,
+ FrameMetricsObserver(@NonNull Window window, @NonNull Handler handler,
@NonNull Window.OnFrameMetricsAvailableListener listener) {
- if (looper == null) {
- throw new NullPointerException("looper cannot be null");
- }
-
- mMessageQueue = looper.getQueue();
- if (mMessageQueue == null) {
- throw new IllegalStateException("invalid looper, null message queue\n");
- }
-
- mFrameMetrics = new FrameMetrics();
mWindow = new WeakReference<>(window);
mListener = listener;
+ mFrameMetrics = new FrameMetrics();
+ mObserver = new HardwareRendererObserver(this, mFrameMetrics.mTimingData, handler);
}
- // Called by native on the provided Handler
- @SuppressWarnings("unused")
- @UnsupportedAppUsage
- private void notifyDataAvailable(int dropCount) {
- final Window window = mWindow.get();
- if (window != null) {
- mListener.onFrameMetricsAvailable(window, mFrameMetrics, dropCount);
+ /**
+ * Implementation of OnFrameMetricsAvailableListener
+ * @param dropCountSinceLastInvocation the number of reports dropped since the last time
+ * @Override
+ */
+ public void onFrameMetricsAvailable(int dropCountSinceLastInvocation) {
+ if (mWindow.get() != null) {
+ mListener.onFrameMetricsAvailable(mWindow.get(), mFrameMetrics,
+ dropCountSinceLastInvocation);
}
}
+
+ /*package*/ HardwareRendererObserver getRendererObserver() {
+ return mObserver;
+ }
}
diff --git a/core/java/android/view/GestureDetector.java b/core/java/android/view/GestureDetector.java
index d59ee92dba7e..4d71136d0af1 100644
--- a/core/java/android/view/GestureDetector.java
+++ b/core/java/android/view/GestureDetector.java
@@ -23,7 +23,7 @@ import static android.util.StatsLog.TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__SC
import static android.util.StatsLog.TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__SINGLE_TAP;
import static android.util.StatsLog.TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__UNKNOWN_CLASSIFICATION;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
diff --git a/core/java/android/view/GhostView.java b/core/java/android/view/GhostView.java
index 3286bd623694..a72832760f96 100644
--- a/core/java/android/view/GhostView.java
+++ b/core/java/android/view/GhostView.java
@@ -15,7 +15,7 @@
*/
package android.view;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.RecordingCanvas;
diff --git a/core/java/android/view/IWindowManager.aidl b/core/java/android/view/IWindowManager.aidl
index b829c9f36f84..9496827b1a84 100644
--- a/core/java/android/view/IWindowManager.aidl
+++ b/core/java/android/view/IWindowManager.aidl
@@ -44,6 +44,7 @@ import android.view.RemoteAnimationAdapter;
import android.view.IRotationWatcher;
import android.view.ISystemGestureExclusionListener;
import android.view.IWallpaperVisibilityListener;
+import android.view.IWindow;
import android.view.IWindowSession;
import android.view.IWindowSessionCallback;
import android.view.KeyEvent;
@@ -120,6 +121,17 @@ interface IWindowManager
void setDisplayWindowRotationController(IDisplayWindowRotationController controller);
/**
+ * Adds a root container that a client shell can populate with its own windows (usually via
+ * WindowlessWindowManager).
+ *
+ * @param client an IWindow used for window-level communication (ime, finish draw, etc.).
+ * @param windowType used by WM to determine the z-order. This is the same as the window type
+ * used in {@link WindowManager.LayoutParams}.
+ * @return a SurfaceControl to add things to.
+ */
+ SurfaceControl addShellRoot(int displayId, IWindow client, int windowType);
+
+ /**
* Like overridePendingAppTransitionMultiThumb, but uses a future to supply the specs. This is
* used for recents, where generating the thumbnails of the specs takes a non-trivial amount of
* time, so we want to move that off the critical path for starting the new activity.
diff --git a/core/java/android/view/InputChannel.java b/core/java/android/view/InputChannel.java
index 5d0d5bd79857..5a64b131faea 100644
--- a/core/java/android/view/InputChannel.java
+++ b/core/java/android/view/InputChannel.java
@@ -16,7 +16,7 @@
package android.view;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.IBinder;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/view/InputDevice.java b/core/java/android/view/InputDevice.java
index e723f91887c1..360deddf544d 100644
--- a/core/java/android/view/InputDevice.java
+++ b/core/java/android/view/InputDevice.java
@@ -18,7 +18,7 @@ package android.view;
import android.annotation.RequiresPermission;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.hardware.input.InputDeviceIdentifier;
import android.hardware.input.InputManager;
diff --git a/core/java/android/view/InputEvent.java b/core/java/android/view/InputEvent.java
index 4b88a6a54efe..5f9c4801ee66 100644
--- a/core/java/android/view/InputEvent.java
+++ b/core/java/android/view/InputEvent.java
@@ -16,7 +16,7 @@
package android.view;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/view/InputEventConsistencyVerifier.java b/core/java/android/view/InputEventConsistencyVerifier.java
index e4b1a8d855ec..c0a3cec4547a 100644
--- a/core/java/android/view/InputEventConsistencyVerifier.java
+++ b/core/java/android/view/InputEventConsistencyVerifier.java
@@ -16,7 +16,7 @@
package android.view;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.util.Log;
diff --git a/core/java/android/view/InputEventReceiver.java b/core/java/android/view/InputEventReceiver.java
index 3080b42e81ce..5674de8c1925 100644
--- a/core/java/android/view/InputEventReceiver.java
+++ b/core/java/android/view/InputEventReceiver.java
@@ -16,7 +16,7 @@
package android.view;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.IBinder;
import android.os.Looper;
import android.os.MessageQueue;
diff --git a/core/java/android/view/InputEventSender.java b/core/java/android/view/InputEventSender.java
index c5f4c23b7b15..86a309e3ed79 100644
--- a/core/java/android/view/InputEventSender.java
+++ b/core/java/android/view/InputEventSender.java
@@ -16,7 +16,7 @@
package android.view;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Looper;
import android.os.MessageQueue;
import android.util.Log;
diff --git a/core/java/android/view/InputFilter.java b/core/java/android/view/InputFilter.java
index 3aaf31ef406f..36d558630da9 100644
--- a/core/java/android/view/InputFilter.java
+++ b/core/java/android/view/InputFilter.java
@@ -16,7 +16,7 @@
package android.view;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
diff --git a/core/java/android/view/InputQueue.java b/core/java/android/view/InputQueue.java
index 69ebc46cb456..74ce6ac02db3 100644
--- a/core/java/android/view/InputQueue.java
+++ b/core/java/android/view/InputQueue.java
@@ -16,7 +16,7 @@
package android.view;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Looper;
import android.os.MessageQueue;
import android.util.LongSparseArray;
diff --git a/core/java/android/view/InsetsAnimationControlImpl.java b/core/java/android/view/InsetsAnimationControlImpl.java
index 3d139cd73518..cdfd397a732a 100644
--- a/core/java/android/view/InsetsAnimationControlImpl.java
+++ b/core/java/android/view/InsetsAnimationControlImpl.java
@@ -21,7 +21,6 @@ import static android.view.InsetsState.ISIDE_FLOATING;
import static android.view.InsetsState.ISIDE_LEFT;
import static android.view.InsetsState.ISIDE_RIGHT;
import static android.view.InsetsState.ISIDE_TOP;
-import static android.view.InsetsState.toPublicType;
import android.annotation.Nullable;
import android.graphics.Insets;
@@ -34,7 +33,8 @@ import android.util.SparseSetArray;
import android.view.InsetsState.InternalInsetsSide;
import android.view.SyncRtSurfaceTransactionApplier.SurfaceParams;
import android.view.WindowInsets.Type.InsetsType;
-import android.view.WindowInsetsAnimationListener.InsetsAnimation;
+import android.view.WindowInsetsAnimationCallback.AnimationBounds;
+import android.view.WindowInsetsAnimationCallback.InsetsAnimation;
import android.view.WindowManager.LayoutParams;
import com.android.internal.annotations.VisibleForTesting;
@@ -66,23 +66,28 @@ public class InsetsAnimationControlImpl implements WindowInsetsAnimationControll
private final @InsetsType int mTypes;
private final Supplier<SyncRtSurfaceTransactionApplier> mTransactionApplierSupplier;
private final InsetsController mController;
- private final WindowInsetsAnimationListener.InsetsAnimation mAnimation;
+ private final WindowInsetsAnimationCallback.InsetsAnimation mAnimation;
private final Rect mFrame;
+ private final boolean mFade;
private Insets mCurrentInsets;
private Insets mPendingInsets;
+ private float mPendingFraction;
private boolean mFinished;
private boolean mCancelled;
- private int mFinishedShownTypes;
+ private boolean mShownOnFinish;
+ private float mCurrentAlpha;
+ private float mPendingAlpha;
@VisibleForTesting
public InsetsAnimationControlImpl(SparseArray<InsetsSourceConsumer> consumers, Rect frame,
InsetsState state, WindowInsetsAnimationControlListener listener,
@InsetsType int types,
Supplier<SyncRtSurfaceTransactionApplier> transactionApplierSupplier,
- InsetsController controller) {
+ InsetsController controller, long durationMs, boolean fade) {
mConsumers = consumers;
mListener = listener;
mTypes = types;
+ mFade = fade;
mTransactionApplierSupplier = transactionApplierSupplier;
mController = controller;
mInitialInsetsState = new InsetsState(state, true /* copySources */);
@@ -97,9 +102,11 @@ public class InsetsAnimationControlImpl implements WindowInsetsAnimationControll
// TODO: Check for controllability first and wait for IME if needed.
listener.onReady(this, types);
- mAnimation = new WindowInsetsAnimationListener.InsetsAnimation(mTypes, mHiddenInsets,
- mShownInsets);
- mController.dispatchAnimationStarted(mAnimation);
+ mAnimation = new WindowInsetsAnimationCallback.InsetsAnimation(mTypes,
+ InsetsController.INTERPOLATOR, durationMs);
+ mAnimation.setAlpha(getCurrentAlpha());
+ mController.dispatchAnimationStarted(mAnimation,
+ new AnimationBounds(mHiddenInsets, mShownInsets));
}
@Override
@@ -118,12 +125,17 @@ public class InsetsAnimationControlImpl implements WindowInsetsAnimationControll
}
@Override
+ public float getCurrentAlpha() {
+ return mCurrentAlpha;
+ }
+
+ @Override
@InsetsType public int getTypes() {
return mTypes;
}
@Override
- public void changeInsets(Insets insets) {
+ public void setInsetsAndAlpha(Insets insets, float alpha, float fraction) {
if (mFinished) {
throw new IllegalStateException(
"Can't change insets on an animation that is finished.");
@@ -132,7 +144,9 @@ public class InsetsAnimationControlImpl implements WindowInsetsAnimationControll
throw new IllegalStateException(
"Can't change insets on an animation that is cancelled.");
}
+ mPendingFraction = sanitize(fraction);
mPendingInsets = sanitize(insets);
+ mPendingAlpha = 1 - sanitize(alpha);
mController.scheduleApplyChangeInsets();
}
@@ -145,40 +159,52 @@ public class InsetsAnimationControlImpl implements WindowInsetsAnimationControll
return false;
}
final Insets offset = Insets.subtract(mShownInsets, mPendingInsets);
+ final Float alphaOffset = 1 - mPendingAlpha;
ArrayList<SurfaceParams> params = new ArrayList<>();
- updateLeashesForSide(ISIDE_LEFT, offset.left, mPendingInsets.left, params, state);
- updateLeashesForSide(ISIDE_TOP, offset.top, mPendingInsets.top, params, state);
- updateLeashesForSide(ISIDE_RIGHT, offset.right, mPendingInsets.right, params, state);
- updateLeashesForSide(ISIDE_BOTTOM, offset.bottom, mPendingInsets.bottom, params, state);
- updateLeashesForSide(ISIDE_FLOATING, 0 /* offset */, 0 /* inset */, params, state);
+ updateLeashesForSide(ISIDE_LEFT, offset.left, mShownInsets.left, mPendingInsets.left,
+ params, state, alphaOffset);
+ updateLeashesForSide(ISIDE_TOP, offset.top, mShownInsets.top, mPendingInsets.top, params,
+ state, alphaOffset);
+ updateLeashesForSide(ISIDE_RIGHT, offset.right, mShownInsets.right, mPendingInsets.right,
+ params, state, alphaOffset);
+ updateLeashesForSide(ISIDE_BOTTOM, offset.bottom, mShownInsets.bottom,
+ mPendingInsets.bottom, params, state, alphaOffset);
+ updateLeashesForSide(ISIDE_FLOATING, 0 /* offset */, 0 /* inset */, 0 /* maxInset */,
+ params, state, alphaOffset);
SyncRtSurfaceTransactionApplier applier = mTransactionApplierSupplier.get();
applier.scheduleApply(params.toArray(new SurfaceParams[params.size()]));
mCurrentInsets = mPendingInsets;
+ mAnimation.setFraction(mPendingFraction);
+ mCurrentAlpha = 1 - alphaOffset;
if (mFinished) {
- mController.notifyFinished(this, mFinishedShownTypes);
+ mController.notifyFinished(this, mShownOnFinish);
}
return mFinished;
}
@Override
- public void finish(int shownTypes) {
+ public void finish(boolean shown) {
if (mCancelled) {
return;
}
InsetsState state = new InsetsState(mController.getState());
for (int i = mConsumers.size() - 1; i >= 0; i--) {
InsetsSourceConsumer consumer = mConsumers.valueAt(i);
- boolean visible = (shownTypes & toPublicType(consumer.getType())) != 0;
- state.getSource(consumer.getType()).setVisible(visible);
+ state.getSource(consumer.getType()).setVisible(shown);
}
Insets insets = getInsetsFromState(state, mFrame, null /* typeSideMap */);
- changeInsets(insets);
+ setInsetsAndAlpha(insets, 1f /* alpha */, shown ? 1f : 0f /* fraction */);
mFinished = true;
- mFinishedShownTypes = shownTypes;
+ mShownOnFinish = shown;
}
+ @Override
@VisibleForTesting
+ public float getCurrentFraction() {
+ return mAnimation.getFraction();
+ }
+
public void onCancelled() {
if (mFinished) {
return;
@@ -191,6 +217,10 @@ public class InsetsAnimationControlImpl implements WindowInsetsAnimationControll
return mAnimation;
}
+ WindowInsetsAnimationControlListener getListener() {
+ return mListener;
+ }
+
private Insets calculateInsets(InsetsState state, Rect frame,
SparseArray<InsetsSourceConsumer> consumers, boolean shown,
@Nullable @InternalInsetsSide SparseIntArray typeSideMap) {
@@ -210,11 +240,18 @@ public class InsetsAnimationControlImpl implements WindowInsetsAnimationControll
}
private Insets sanitize(Insets insets) {
+ if (insets == null) {
+ insets = getCurrentInsets();
+ }
return Insets.max(Insets.min(insets, mShownInsets), mHiddenInsets);
}
+ private static float sanitize(float alpha) {
+ return alpha >= 1 ? 1 : (alpha <= 0 ? 0 : alpha);
+ }
+
private void updateLeashesForSide(@InternalInsetsSide int side, int offset, int inset,
- ArrayList<SurfaceParams> surfaceParams, InsetsState state) {
+ int maxInset, ArrayList<SurfaceParams> surfaceParams, InsetsState state, Float alpha) {
ArraySet<InsetsSourceConsumer> items = mSideSourceMap.get(side);
if (items == null) {
return;
@@ -238,7 +275,9 @@ public class InsetsAnimationControlImpl implements WindowInsetsAnimationControll
// If the system is controlling the insets source, the leash can be null.
if (leash != null) {
- surfaceParams.add(new SurfaceParams(leash, 1f /* alpha */, mTmpMatrix,
+ // TODO: use a better interpolation for fade.
+ alpha = mFade ? ((float) maxInset / inset * 0.3f + 0.7f) : alpha;
+ surfaceParams.add(new SurfaceParams(leash, alpha, mTmpMatrix,
null /* windowCrop */, 0 /* layer */, 0f /* cornerRadius*/,
side == ISIDE_FLOATING ? consumer.isVisible() : inset != 0 /* visible */));
}
diff --git a/core/java/android/view/InsetsController.java b/core/java/android/view/InsetsController.java
index bc70d634b4ec..5563d629f25e 100644
--- a/core/java/android/view/InsetsController.java
+++ b/core/java/android/view/InsetsController.java
@@ -39,6 +39,8 @@ import android.view.InsetsState.InternalInsetsType;
import android.view.SurfaceControl.Transaction;
import android.view.WindowInsets.Type;
import android.view.WindowInsets.Type.InsetsType;
+import android.view.WindowInsetsAnimationCallback.AnimationBounds;
+import android.view.WindowInsetsAnimationCallback.InsetsAnimation;
import android.view.animation.Interpolator;
import android.view.animation.PathInterpolator;
@@ -55,11 +57,12 @@ public class InsetsController implements WindowInsetsController {
private static final int ANIMATION_DURATION_SHOW_MS = 275;
private static final int ANIMATION_DURATION_HIDE_MS = 340;
- private static final Interpolator INTERPOLATOR = new PathInterpolator(0.4f, 0f, 0.2f, 1f);
private static final int DIRECTION_NONE = 0;
private static final int DIRECTION_SHOW = 1;
private static final int DIRECTION_HIDE = 2;
+ static final Interpolator INTERPOLATOR = new PathInterpolator(0.4f, 0f, 0.2f, 1f);
+
@IntDef ({DIRECTION_NONE, DIRECTION_SHOW, DIRECTION_HIDE})
private @interface AnimationDirection{}
@@ -85,8 +88,75 @@ public class InsetsController implements WindowInsetsController {
return object.getCurrentInsets();
}
@Override
- public void set(WindowInsetsAnimationController object, Insets value) {
- object.changeInsets(value);
+ public void set(WindowInsetsAnimationController controller, Insets value) {
+ controller.setInsetsAndAlpha(
+ value, 1f /* alpha */, (((DefaultAnimationControlListener)
+ ((InsetsAnimationControlImpl) controller).getListener())
+ .getRawProgress()));
+ }
+ }
+
+ private class DefaultAnimationControlListener implements WindowInsetsAnimationControlListener {
+
+ private WindowInsetsAnimationController mController;
+ private ObjectAnimator mAnimator;
+ private boolean mShow;
+
+ DefaultAnimationControlListener(boolean show) {
+ mShow = show;
+ }
+
+ @Override
+ public void onReady(WindowInsetsAnimationController controller, int types) {
+ mController = controller;
+ if (mShow) {
+ showDirectly(types);
+ } else {
+ hideDirectly(types);
+ }
+ mAnimationDirection = mShow ? DIRECTION_SHOW : DIRECTION_HIDE;
+ mAnimator = ObjectAnimator.ofObject(
+ controller,
+ new InsetsProperty(),
+ sEvaluator,
+ mShow ? controller.getHiddenStateInsets() : controller.getShownStateInsets(),
+ mShow ? controller.getShownStateInsets() : controller.getHiddenStateInsets()
+ );
+ mAnimator.setDuration(getDurationMs());
+ mAnimator.setInterpolator(INTERPOLATOR);
+ mAnimator.addListener(new AnimatorListenerAdapter() {
+
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ onAnimationFinish();
+ }
+ });
+ mAnimator.start();
+ }
+
+ @Override
+ public void onCancelled() {
+ // Animator can be null when it is cancelled before onReady() completes.
+ if (mAnimator != null) {
+ mAnimator.cancel();
+ }
+ }
+
+ private void onAnimationFinish() {
+ mAnimationDirection = DIRECTION_NONE;
+ mController.finish(mShow);
+ }
+
+ private float getRawProgress() {
+ float fraction = (float) mAnimator.getCurrentPlayTime() / mAnimator.getDuration();
+ return mShow ? fraction : 1 - fraction;
+ }
+
+ private long getDurationMs() {
+ if (mAnimator != null) {
+ return mAnimator.getDuration();
+ }
+ return mShow ? ANIMATION_DURATION_SHOW_MS : ANIMATION_DURATION_HIDE_MS;
}
}
@@ -123,6 +193,10 @@ public class InsetsController implements WindowInsetsController {
if (mAnimationControls.isEmpty()) {
return;
}
+ if (mViewRoot.mView == null) {
+ // The view has already detached from window.
+ return;
+ }
mTmpFinishedControls.clear();
InsetsState state = new InsetsState(mState, true /* copySources */);
@@ -154,6 +228,7 @@ public class InsetsController implements WindowInsetsController {
mFrame.set(frame);
}
+ @Override
public InsetsState getState() {
return mState;
}
@@ -273,24 +348,25 @@ public class InsetsController implements WindowInsetsController {
}
@Override
- public void controlWindowInsetsAnimation(@InsetsType int types,
+ public void controlWindowInsetsAnimation(@InsetsType int types, long durationMs,
WindowInsetsAnimationControlListener listener) {
- controlWindowInsetsAnimation(types, listener, false /* fromIme */);
+ controlWindowInsetsAnimation(types, listener, false /* fromIme */, durationMs);
}
private void controlWindowInsetsAnimation(@InsetsType int types,
- WindowInsetsAnimationControlListener listener, boolean fromIme) {
+ WindowInsetsAnimationControlListener listener, boolean fromIme, long durationMs) {
// If the frame of our window doesn't span the entire display, the control API makes very
// little sense, as we don't deal with negative insets. So just cancel immediately.
if (!mState.getDisplayFrame().equals(mFrame)) {
listener.onCancelled();
return;
}
- controlAnimationUnchecked(types, listener, mFrame, fromIme);
+ controlAnimationUnchecked(types, listener, mFrame, fromIme, durationMs, false /* fade */);
}
private void controlAnimationUnchecked(@InsetsType int types,
- WindowInsetsAnimationControlListener listener, Rect frame, boolean fromIme) {
+ WindowInsetsAnimationControlListener listener, Rect frame, boolean fromIme,
+ long durationMs, boolean fade) {
if (types == 0) {
// nothing to animate.
return;
@@ -321,7 +397,7 @@ public class InsetsController implements WindowInsetsController {
final InsetsAnimationControlImpl controller = new InsetsAnimationControlImpl(consumers,
frame, mState, listener, typesReady,
- () -> new SyncRtSurfaceTransactionApplier(mViewRoot.mView), this);
+ () -> new SyncRtSurfaceTransactionApplier(mViewRoot.mView), this, durationMs, fade);
mAnimationControls.add(controller);
}
@@ -392,10 +468,13 @@ public class InsetsController implements WindowInsetsController {
}
@VisibleForTesting
- public void notifyFinished(InsetsAnimationControlImpl controller, int shownTypes) {
+ public void notifyFinished(InsetsAnimationControlImpl controller, boolean shown) {
mAnimationControls.remove(controller);
- hideDirectly(controller.getTypes() & ~shownTypes);
- showDirectly(controller.getTypes() & shownTypes);
+ if (shown) {
+ showDirectly(controller.getTypes());
+ } else {
+ hideDirectly(controller.getTypes());
+ }
}
void notifyControlRevoked(InsetsSourceConsumer consumer) {
@@ -505,58 +584,12 @@ public class InsetsController implements WindowInsetsController {
return;
}
- WindowInsetsAnimationControlListener listener = new WindowInsetsAnimationControlListener() {
-
- private WindowInsetsAnimationController mController;
- private ObjectAnimator mAnimator;
-
- @Override
- public void onReady(WindowInsetsAnimationController controller, int types) {
- mController = controller;
- if (show) {
- showDirectly(types);
- } else {
- hideDirectly(types);
- }
- mAnimationDirection = show ? DIRECTION_SHOW : DIRECTION_HIDE;
- mAnimator = ObjectAnimator.ofObject(
- controller,
- new InsetsProperty(),
- sEvaluator,
- show ? controller.getHiddenStateInsets() : controller.getShownStateInsets(),
- show ? controller.getShownStateInsets() : controller.getHiddenStateInsets()
- );
- mAnimator.setDuration(show
- ? ANIMATION_DURATION_SHOW_MS
- : ANIMATION_DURATION_HIDE_MS);
- mAnimator.setInterpolator(INTERPOLATOR);
- mAnimator.addListener(new AnimatorListenerAdapter() {
-
- @Override
- public void onAnimationEnd(Animator animation) {
- onAnimationFinish();
- }
- });
- mAnimator.start();
- }
-
- @Override
- public void onCancelled() {
- // Animator can be null when it is cancelled before onReady() completes.
- if (mAnimator != null) {
- mAnimator.cancel();
- }
- }
-
- private void onAnimationFinish() {
- mAnimationDirection = DIRECTION_NONE;
- mController.finish(show ? types : 0);
- }
- };
-
+ final DefaultAnimationControlListener listener = new DefaultAnimationControlListener(show);
// Show/hide animations always need to be relative to the display frame, in order that shown
// and hidden state insets are correct.
- controlAnimationUnchecked(types, listener, mState.getDisplayFrame(), fromIme);
+ controlAnimationUnchecked(
+ types, listener, mState.getDisplayFrame(), fromIme, listener.getDurationMs(),
+ true /* fade */);
}
private void hideDirectly(@InsetsType int types) {
@@ -587,12 +620,12 @@ public class InsetsController implements WindowInsetsController {
}
@VisibleForTesting
- public void dispatchAnimationStarted(WindowInsetsAnimationListener.InsetsAnimation animation) {
- mViewRoot.mView.dispatchWindowInsetsAnimationStarted(animation);
+ public void dispatchAnimationStarted(InsetsAnimation animation, AnimationBounds bounds) {
+ mViewRoot.mView.dispatchWindowInsetsAnimationStarted(animation, bounds);
}
@VisibleForTesting
- public void dispatchAnimationFinished(WindowInsetsAnimationListener.InsetsAnimation animation) {
+ public void dispatchAnimationFinished(InsetsAnimation animation) {
mViewRoot.mView.dispatchWindowInsetsAnimationFinished(animation);
}
diff --git a/core/java/android/view/KeyCharacterMap.java b/core/java/android/view/KeyCharacterMap.java
index bd033480ea87..90e0f3f89a0f 100644
--- a/core/java/android/view/KeyCharacterMap.java
+++ b/core/java/android/view/KeyCharacterMap.java
@@ -16,7 +16,7 @@
package android.view;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.hardware.input.InputManager;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/view/KeyEvent.java b/core/java/android/view/KeyEvent.java
index 60db6a57d187..c638717b13c0 100644
--- a/core/java/android/view/KeyEvent.java
+++ b/core/java/android/view/KeyEvent.java
@@ -20,7 +20,7 @@ import static android.view.Display.INVALID_DISPLAY;
import android.annotation.NonNull;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/view/LayoutInflater.java b/core/java/android/view/LayoutInflater.java
index 75862e01d41c..1afe11ea1acf 100644
--- a/core/java/android/view/LayoutInflater.java
+++ b/core/java/android/view/LayoutInflater.java
@@ -21,7 +21,7 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.res.Resources;
@@ -31,10 +31,7 @@ import android.graphics.Canvas;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
-import android.os.SystemProperties;
import android.os.Trace;
-import android.provider.DeviceConfig;
-import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
diff --git a/core/java/android/view/MotionEvent.java b/core/java/android/view/MotionEvent.java
index 1c94e02462d0..c3c7b950838b 100644
--- a/core/java/android/view/MotionEvent.java
+++ b/core/java/android/view/MotionEvent.java
@@ -22,7 +22,7 @@ import static java.lang.annotation.RetentionPolicy.SOURCE;
import android.annotation.IntDef;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.Matrix;
import android.os.Build;
import android.os.Parcel;
diff --git a/core/java/android/view/NotificationHeaderView.java b/core/java/android/view/NotificationHeaderView.java
index d54e9d58356b..8ec5df85dc7b 100644
--- a/core/java/android/view/NotificationHeaderView.java
+++ b/core/java/android/view/NotificationHeaderView.java
@@ -17,9 +17,9 @@
package android.view;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
import android.app.AppOpsManager;
import android.app.Notification;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
diff --git a/core/java/android/view/PointerIcon.java b/core/java/android/view/PointerIcon.java
index dfe34c80bb8f..18d0d7b98a42 100644
--- a/core/java/android/view/PointerIcon.java
+++ b/core/java/android/view/PointerIcon.java
@@ -17,8 +17,8 @@
package android.view;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.XmlRes;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
diff --git a/core/java/android/view/RemoteAnimationAdapter.java b/core/java/android/view/RemoteAnimationAdapter.java
index c686440171a2..166d3baa2fdf 100644
--- a/core/java/android/view/RemoteAnimationAdapter.java
+++ b/core/java/android/view/RemoteAnimationAdapter.java
@@ -16,8 +16,8 @@
package android.view;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityOptions;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/view/RemoteAnimationDefinition.java b/core/java/android/view/RemoteAnimationDefinition.java
index da599efb6eee..c9bd92ae84ba 100644
--- a/core/java/android/view/RemoteAnimationDefinition.java
+++ b/core/java/android/view/RemoteAnimationDefinition.java
@@ -19,9 +19,9 @@ package android.view;
import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
import android.app.WindowConfiguration;
import android.app.WindowConfiguration.ActivityType;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.ArraySet;
diff --git a/core/java/android/view/RemoteAnimationTarget.java b/core/java/android/view/RemoteAnimationTarget.java
index b87348257e0e..b04372a1ce19 100644
--- a/core/java/android/view/RemoteAnimationTarget.java
+++ b/core/java/android/view/RemoteAnimationTarget.java
@@ -30,8 +30,8 @@ import static android.view.RemoteAnimationTargetProto.TASK_ID;
import static android.view.RemoteAnimationTargetProto.WINDOW_CONFIGURATION;
import android.annotation.IntDef;
-import android.annotation.UnsupportedAppUsage;
import android.app.WindowConfiguration;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Parcel;
diff --git a/core/java/android/view/RenderNodeAnimator.java b/core/java/android/view/RenderNodeAnimator.java
index 93f52a04d626..06cb51927ba8 100644
--- a/core/java/android/view/RenderNodeAnimator.java
+++ b/core/java/android/view/RenderNodeAnimator.java
@@ -19,7 +19,7 @@ package android.view;
import android.animation.Animator;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.CanvasProperty;
import android.graphics.Paint;
import android.graphics.RecordingCanvas;
diff --git a/core/java/android/view/ScaleGestureDetector.java b/core/java/android/view/ScaleGestureDetector.java
index 1d721516a979..346f76cace7d 100644
--- a/core/java/android/view/ScaleGestureDetector.java
+++ b/core/java/android/view/ScaleGestureDetector.java
@@ -16,7 +16,7 @@
package android.view;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
diff --git a/core/java/android/view/Surface.java b/core/java/android/view/Surface.java
index dac62821fe90..7707ad163b85 100644
--- a/core/java/android/view/Surface.java
+++ b/core/java/android/view/Surface.java
@@ -18,7 +18,7 @@ package android.view;
import android.annotation.IntDef;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.res.CompatibilityInfo.Translator;
import android.graphics.Canvas;
import android.graphics.ColorSpace;
diff --git a/core/java/android/view/SurfaceControl.java b/core/java/android/view/SurfaceControl.java
index 87628da42599..93cc626b51a7 100644
--- a/core/java/android/view/SurfaceControl.java
+++ b/core/java/android/view/SurfaceControl.java
@@ -32,7 +32,7 @@ import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.Size;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.Bitmap;
import android.graphics.ColorSpace;
import android.graphics.GraphicBuffer;
@@ -2092,6 +2092,13 @@ public final class SurfaceControl implements Parcelable {
Runnable mFreeNativeResources;
/**
+ * @hide
+ */
+ protected void checkPreconditions(SurfaceControl sc) {
+ sc.checkNotReleased();
+ }
+
+ /**
* Open a new transaction object. The transaction may be filed with commands to
* manipulate {@link SurfaceControl} instances, and then applied atomically with
* {@link #apply}. Eventually the user should invoke {@link #close}, when the object
@@ -2155,7 +2162,7 @@ public final class SurfaceControl implements Parcelable {
*/
@NonNull
public Transaction setVisibility(@NonNull SurfaceControl sc, boolean visible) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
if (visible) {
return show(sc);
} else {
@@ -2172,7 +2179,7 @@ public final class SurfaceControl implements Parcelable {
*/
@UnsupportedAppUsage
public Transaction show(SurfaceControl sc) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSetFlags(mNativeObject, sc.mNativeObject, 0, SURFACE_HIDDEN);
return this;
}
@@ -2186,7 +2193,7 @@ public final class SurfaceControl implements Parcelable {
*/
@UnsupportedAppUsage
public Transaction hide(SurfaceControl sc) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSetFlags(mNativeObject, sc.mNativeObject, SURFACE_HIDDEN, SURFACE_HIDDEN);
return this;
}
@@ -2196,7 +2203,7 @@ public final class SurfaceControl implements Parcelable {
*/
@UnsupportedAppUsage
public Transaction setPosition(SurfaceControl sc, float x, float y) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSetPosition(mNativeObject, sc.mNativeObject, x, y);
return this;
}
@@ -2213,7 +2220,7 @@ public final class SurfaceControl implements Parcelable {
@NonNull
public Transaction setBufferSize(@NonNull SurfaceControl sc,
@IntRange(from = 0) int w, @IntRange(from = 0) int h) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
mResizedSurfaces.put(sc, new Point(w, h));
nativeSetSize(mNativeObject, sc.mNativeObject, w, h);
return this;
@@ -2231,7 +2238,7 @@ public final class SurfaceControl implements Parcelable {
@NonNull
public Transaction setLayer(@NonNull SurfaceControl sc,
@IntRange(from = Integer.MIN_VALUE, to = Integer.MAX_VALUE) int z) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSetLayer(mNativeObject, sc.mNativeObject, z);
return this;
}
@@ -2240,7 +2247,7 @@ public final class SurfaceControl implements Parcelable {
* @hide
*/
public Transaction setRelativeLayer(SurfaceControl sc, SurfaceControl relativeTo, int z) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSetRelativeLayer(mNativeObject, sc.mNativeObject, relativeTo.mNativeObject, z);
return this;
}
@@ -2249,7 +2256,7 @@ public final class SurfaceControl implements Parcelable {
* @hide
*/
public Transaction setTransparentRegionHint(SurfaceControl sc, Region transparentRegion) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSetTransparentRegionHint(mNativeObject,
sc.mNativeObject, transparentRegion);
return this;
@@ -2265,7 +2272,7 @@ public final class SurfaceControl implements Parcelable {
@NonNull
public Transaction setAlpha(@NonNull SurfaceControl sc,
@FloatRange(from = 0.0, to = 1.0) float alpha) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSetAlpha(mNativeObject, sc.mNativeObject, alpha);
return this;
}
@@ -2274,7 +2281,7 @@ public final class SurfaceControl implements Parcelable {
* @hide
*/
public Transaction setInputWindowInfo(SurfaceControl sc, InputWindowHandle handle) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSetInputWindowInfo(mNativeObject, sc.mNativeObject, handle);
return this;
}
@@ -2304,7 +2311,7 @@ public final class SurfaceControl implements Parcelable {
@NonNull
public Transaction setGeometry(@NonNull SurfaceControl sc, @Nullable Rect sourceCrop,
@Nullable Rect destFrame, @Surface.Rotation int orientation) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSetGeometry(mNativeObject, sc.mNativeObject, sourceCrop, destFrame, orientation);
return this;
}
@@ -2315,7 +2322,7 @@ public final class SurfaceControl implements Parcelable {
@UnsupportedAppUsage
public Transaction setMatrix(SurfaceControl sc,
float dsdx, float dtdx, float dtdy, float dsdy) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSetMatrix(mNativeObject, sc.mNativeObject,
dsdx, dtdx, dtdy, dsdy);
return this;
@@ -2349,7 +2356,7 @@ public final class SurfaceControl implements Parcelable {
*/
public Transaction setColorTransform(SurfaceControl sc, @Size(9) float[] matrix,
@Size(3) float[] translation) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSetColorTransform(mNativeObject, sc.mNativeObject, matrix, translation);
return this;
}
@@ -2361,7 +2368,7 @@ public final class SurfaceControl implements Parcelable {
* @hide
*/
public Transaction setColorSpaceAgnostic(SurfaceControl sc, boolean agnostic) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSetColorSpaceAgnostic(mNativeObject, sc.mNativeObject, agnostic);
return this;
}
@@ -2378,7 +2385,7 @@ public final class SurfaceControl implements Parcelable {
*/
@UnsupportedAppUsage
public Transaction setWindowCrop(SurfaceControl sc, Rect crop) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
if (crop != null) {
nativeSetWindowCrop(mNativeObject, sc.mNativeObject,
crop.left, crop.top, crop.right, crop.bottom);
@@ -2399,7 +2406,7 @@ public final class SurfaceControl implements Parcelable {
* @hide
*/
public Transaction setWindowCrop(SurfaceControl sc, int width, int height) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSetWindowCrop(mNativeObject, sc.mNativeObject, 0, 0, width, height);
return this;
}
@@ -2413,7 +2420,7 @@ public final class SurfaceControl implements Parcelable {
*/
@UnsupportedAppUsage
public Transaction setCornerRadius(SurfaceControl sc, float cornerRadius) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSetCornerRadius(mNativeObject, sc.mNativeObject, cornerRadius);
return this;
@@ -2424,7 +2431,7 @@ public final class SurfaceControl implements Parcelable {
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.O)
public Transaction setLayerStack(SurfaceControl sc, int layerStack) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSetLayerStack(mNativeObject, sc.mNativeObject, layerStack);
return this;
}
@@ -2438,7 +2445,7 @@ public final class SurfaceControl implements Parcelable {
if (frameNumber < 0) {
return this;
}
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeDeferTransactionUntil(mNativeObject, sc.mNativeObject, barrier.mNativeObject,
frameNumber);
return this;
@@ -2453,7 +2460,7 @@ public final class SurfaceControl implements Parcelable {
if (frameNumber < 0) {
return this;
}
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeDeferTransactionUntilSurface(mNativeObject, sc.mNativeObject,
barrierSurface.mNativeObject, frameNumber);
return this;
@@ -2463,7 +2470,7 @@ public final class SurfaceControl implements Parcelable {
* @hide
*/
public Transaction reparentChildren(SurfaceControl sc, SurfaceControl newParent) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeReparentChildren(mNativeObject, sc.mNativeObject, newParent.mNativeObject);
return this;
}
@@ -2480,7 +2487,7 @@ public final class SurfaceControl implements Parcelable {
@NonNull
public Transaction reparent(@NonNull SurfaceControl sc,
@Nullable SurfaceControl newParent) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
long otherObject = 0;
if (newParent != null) {
newParent.checkNotReleased();
@@ -2494,7 +2501,7 @@ public final class SurfaceControl implements Parcelable {
* @hide
*/
public Transaction detachChildren(SurfaceControl sc) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSeverChildren(mNativeObject, sc.mNativeObject);
return this;
}
@@ -2503,7 +2510,7 @@ public final class SurfaceControl implements Parcelable {
* @hide
*/
public Transaction setOverrideScalingMode(SurfaceControl sc, int overrideScalingMode) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSetOverrideScalingMode(mNativeObject, sc.mNativeObject,
overrideScalingMode);
return this;
@@ -2516,7 +2523,7 @@ public final class SurfaceControl implements Parcelable {
*/
@UnsupportedAppUsage
public Transaction setColor(SurfaceControl sc, @Size(3) float[] color) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSetColor(mNativeObject, sc.mNativeObject, color);
return this;
}
@@ -2527,7 +2534,7 @@ public final class SurfaceControl implements Parcelable {
* @hide
*/
public Transaction setSecure(SurfaceControl sc, boolean isSecure) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
if (isSecure) {
nativeSetFlags(mNativeObject, sc.mNativeObject, SECURE, SECURE);
} else {
@@ -2542,7 +2549,7 @@ public final class SurfaceControl implements Parcelable {
* @hide
*/
public Transaction setOpaque(SurfaceControl sc, boolean isOpaque) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
if (isOpaque) {
nativeSetFlags(mNativeObject, sc.mNativeObject, SURFACE_OPAQUE, SURFACE_OPAQUE);
} else {
@@ -2657,7 +2664,7 @@ public final class SurfaceControl implements Parcelable {
* @hide
*/
public Transaction setMetadata(SurfaceControl sc, int key, Parcel data) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSetMetadata(mNativeObject, sc.mNativeObject, key, data);
return this;
}
@@ -2680,7 +2687,7 @@ public final class SurfaceControl implements Parcelable {
* @hide
*/
public Transaction setShadowRadius(SurfaceControl sc, float shadowRadius) {
- sc.checkNotReleased();
+ checkPreconditions(sc);
nativeSetShadowRadius(mNativeObject, sc.mNativeObject, shadowRadius);
return this;
}
@@ -2763,4 +2770,27 @@ public final class SurfaceControl implements Parcelable {
}
};
}
+
+ /**
+ * A debugging utility subclass of SurfaceControl.Transaction. At construction
+ * you can pass in a monitor object, and all the other methods will throw an exception
+ * if the monitor is not held when they are called.
+ * @hide
+ */
+ public static class LockDebuggingTransaction extends SurfaceControl.Transaction {
+ Object mMonitor;
+
+ public LockDebuggingTransaction(Object o) {
+ mMonitor = o;
+ }
+
+ @Override
+ protected void checkPreconditions(SurfaceControl sc) {
+ super.checkPreconditions(sc);
+ if (!Thread.holdsLock(mMonitor)) {
+ throw new RuntimeException(
+ "Unlocked access to synchronized SurfaceControl.Transaction");
+ }
+ }
+ }
}
diff --git a/core/java/android/view/SurfaceSession.java b/core/java/android/view/SurfaceSession.java
index 361ac932758e..0f851c1881f5 100644
--- a/core/java/android/view/SurfaceSession.java
+++ b/core/java/android/view/SurfaceSession.java
@@ -16,7 +16,7 @@
package android.view;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/**
* An instance of this class represents a connection to the surface
diff --git a/core/java/android/view/SurfaceView.java b/core/java/android/view/SurfaceView.java
index 0b5af2d01349..95a75eb0bba5 100644
--- a/core/java/android/view/SurfaceView.java
+++ b/core/java/android/view/SurfaceView.java
@@ -22,7 +22,7 @@ import static android.view.WindowManagerPolicyConstants.APPLICATION_PANEL_SUBLAY
import android.annotation.Nullable;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.CompatibilityInfo.Translator;
import android.graphics.BlendMode;
diff --git a/core/java/android/view/TextureView.java b/core/java/android/view/TextureView.java
index 5876b03476ce..277b872a8cd0 100644
--- a/core/java/android/view/TextureView.java
+++ b/core/java/android/view/TextureView.java
@@ -18,7 +18,7 @@ package android.view;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
diff --git a/core/java/android/view/TouchDelegate.java b/core/java/android/view/TouchDelegate.java
index 2ea95e90a8bf..de0f9e5c5cf6 100644
--- a/core/java/android/view/TouchDelegate.java
+++ b/core/java/android/view/TouchDelegate.java
@@ -17,7 +17,7 @@
package android.view;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.Rect;
import android.graphics.Region;
import android.util.ArrayMap;
diff --git a/core/java/android/view/VelocityTracker.java b/core/java/android/view/VelocityTracker.java
index 7154f2bdee42..a56633e3c5fa 100644
--- a/core/java/android/view/VelocityTracker.java
+++ b/core/java/android/view/VelocityTracker.java
@@ -16,7 +16,7 @@
package android.view;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.util.Pools.SynchronizedPool;
/**
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 9d4f387895bb..1a5b3e58f576 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -43,7 +43,7 @@ import android.annotation.Size;
import android.annotation.StyleRes;
import android.annotation.TestApi;
import android.annotation.UiThread;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.AutofillOptions;
import android.content.ClipData;
import android.content.Context;
@@ -109,7 +109,8 @@ import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
import android.view.AccessibilityIterators.TextSegmentIterator;
import android.view.AccessibilityIterators.WordTextSegmentIterator;
import android.view.ContextMenu.ContextMenuInfo;
-import android.view.WindowInsetsAnimationListener.InsetsAnimation;
+import android.view.WindowInsetsAnimationCallback.AnimationBounds;
+import android.view.WindowInsetsAnimationCallback.InsetsAnimation;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityEventSource;
import android.view.accessibility.AccessibilityManager;
@@ -4626,7 +4627,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
private ArrayList<OnUnhandledKeyEventListener> mUnhandledKeyListeners;
- private WindowInsetsAnimationListener mWindowInsetsAnimationListener;
+ private WindowInsetsAnimationCallback mWindowInsetsAnimationCallback;
/**
* This lives here since it's only valid for interactive views.
@@ -7146,10 +7147,9 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
mFrameMetricsObservers = new ArrayList<>();
}
- FrameMetricsObserver fmo = new FrameMetricsObserver(window,
- handler.getLooper(), listener);
+ FrameMetricsObserver fmo = new FrameMetricsObserver(window, handler, listener);
mFrameMetricsObservers.add(fmo);
- mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo);
+ mAttachInfo.mThreadedRenderer.addObserver(fmo.getRendererObserver());
} else {
Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
}
@@ -7158,8 +7158,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
mFrameMetricsObservers = new ArrayList<>();
}
- FrameMetricsObserver fmo = new FrameMetricsObserver(window,
- handler.getLooper(), listener);
+ FrameMetricsObserver fmo = new FrameMetricsObserver(window, handler, listener);
mFrameMetricsObservers.add(fmo);
}
}
@@ -7181,7 +7180,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
if (mFrameMetricsObservers != null) {
mFrameMetricsObservers.remove(fmo);
if (renderer != null) {
- renderer.removeFrameMetricsObserver(fmo);
+ renderer.removeObserver(fmo.getRendererObserver());
}
}
}
@@ -7191,7 +7190,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
ThreadedRenderer renderer = getThreadedRenderer();
if (renderer != null) {
for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
- renderer.addFrameMetricsObserver(fmo);
+ renderer.addObserver(fmo.getRendererObserver());
}
} else {
Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
@@ -11091,33 +11090,55 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
}
/**
- * Sets a {@link WindowInsetsAnimationListener} to be notified about animations of windows that
+ * Sets a {@link WindowInsetsAnimationCallback} to be notified about animations of windows that
* cause insets.
*
* @param listener The listener to set.
- * @hide pending unhide
*/
- public void setWindowInsetsAnimationListener(WindowInsetsAnimationListener listener) {
- getListenerInfo().mWindowInsetsAnimationListener = listener;
+ public void setWindowInsetsAnimationCallback(@Nullable WindowInsetsAnimationCallback listener) {
+ getListenerInfo().mWindowInsetsAnimationCallback = listener;
}
- void dispatchWindowInsetsAnimationStarted(InsetsAnimation animation) {
- if (mListenerInfo != null && mListenerInfo.mWindowInsetsAnimationListener != null) {
- mListenerInfo.mWindowInsetsAnimationListener.onStarted(animation);
+ /**
+ * Dispatches {@link WindowInsetsAnimationCallback#onStarted(InsetsAnimation, AnimationBounds)}
+ * when Window Insets animation is started.
+ * @param animation current animation
+ * @param bounds the upper and lower {@link AnimationBounds} that provides range of
+ * {@link InsetsAnimation}.
+ * @return the upper and lower {@link AnimationBounds}.
+ */
+ @NonNull
+ public AnimationBounds dispatchWindowInsetsAnimationStarted(
+ @NonNull InsetsAnimation animation, @NonNull AnimationBounds bounds) {
+ if (mListenerInfo != null && mListenerInfo.mWindowInsetsAnimationCallback != null) {
+ return mListenerInfo.mWindowInsetsAnimationCallback.onStarted(animation, bounds);
}
+ return bounds;
}
- WindowInsets dispatchWindowInsetsAnimationProgress(WindowInsets insets) {
- if (mListenerInfo != null && mListenerInfo.mWindowInsetsAnimationListener != null) {
- return mListenerInfo.mWindowInsetsAnimationListener.onProgress(insets);
+ /**
+ * Dispatches {@link WindowInsetsAnimationCallback#onProgress(WindowInsets)}
+ * when Window Insets animation makes progress.
+ * @param insets The current {@link WindowInsets}.
+ * @return current {@link WindowInsets}.
+ */
+ @NonNull
+ public WindowInsets dispatchWindowInsetsAnimationProgress(@NonNull WindowInsets insets) {
+ if (mListenerInfo != null && mListenerInfo.mWindowInsetsAnimationCallback != null) {
+ return mListenerInfo.mWindowInsetsAnimationCallback.onProgress(insets);
} else {
return insets;
}
}
- void dispatchWindowInsetsAnimationFinished(InsetsAnimation animation) {
- if (mListenerInfo != null && mListenerInfo.mWindowInsetsAnimationListener != null) {
- mListenerInfo.mWindowInsetsAnimationListener.onFinished(animation);
+ /**
+ * Dispatches {@link WindowInsetsAnimationCallback#onFinished(InsetsAnimation)}
+ * when Window Insets animation finishes.
+ * @param animation The current ongoing {@link InsetsAnimation}.
+ */
+ public void dispatchWindowInsetsAnimationFinished(@NonNull InsetsAnimation animation) {
+ if (mListenerInfo != null && mListenerInfo.mWindowInsetsAnimationCallback != null) {
+ mListenerInfo.mWindowInsetsAnimationCallback.onFinished(animation);
}
}
@@ -11253,7 +11274,6 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
* @return The {@link WindowInsetsController} or {@code null} if the view isn't attached to a
* a window.
* @see Window#getInsetsController()
- * @hide pending unhide
*/
public @Nullable WindowInsetsController getWindowInsetsController() {
if (mAttachInfo != null) {
@@ -16163,7 +16183,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
* by the most recent call to {@link #measure(int, int)}. This result is a bit mask
* as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
* This should be used during measurement and layout calculations only. Use
- * {@link #getHeight()} to see how wide a view is after layout.
+ * {@link #getHeight()} to see how high a view is after layout.
*
* @return The measured height of this view as a bit mask.
*/
diff --git a/core/java/android/view/ViewConfiguration.java b/core/java/android/view/ViewConfiguration.java
index 9e914d4e7d41..774a2dea6311 100644
--- a/core/java/android/view/ViewConfiguration.java
+++ b/core/java/android/view/ViewConfiguration.java
@@ -18,8 +18,8 @@ package android.view;
import android.annotation.FloatRange;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.AppGlobals;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
diff --git a/core/java/android/view/ViewDebug.java b/core/java/android/view/ViewDebug.java
index a62ba63b64e4..2f44fe039cf5 100644
--- a/core/java/android/view/ViewDebug.java
+++ b/core/java/android/view/ViewDebug.java
@@ -19,7 +19,7 @@ package android.view;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java
index 853a30226982..21e9e3185066 100644
--- a/core/java/android/view/ViewGroup.java
+++ b/core/java/android/view/ViewGroup.java
@@ -24,7 +24,7 @@ import android.annotation.IdRes;
import android.annotation.NonNull;
import android.annotation.TestApi;
import android.annotation.UiThread;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
@@ -51,7 +51,8 @@ import android.util.Pools;
import android.util.Pools.SynchronizedPool;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
-import android.view.WindowInsetsAnimationListener.InsetsAnimation;
+import android.view.WindowInsetsAnimationCallback.AnimationBounds;
+import android.view.WindowInsetsAnimationCallback.InsetsAnimation;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.AccessibilityNodeInfo;
@@ -7198,16 +7199,20 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager
}
@Override
- void dispatchWindowInsetsAnimationStarted(InsetsAnimation animation) {
- super.dispatchWindowInsetsAnimationStarted(animation);
+ @NonNull
+ public AnimationBounds dispatchWindowInsetsAnimationStarted(
+ @NonNull InsetsAnimation animation, @NonNull AnimationBounds bounds) {
+ super.dispatchWindowInsetsAnimationStarted(animation, bounds);
final int count = getChildCount();
for (int i = 0; i < count; i++) {
- getChildAt(i).dispatchWindowInsetsAnimationStarted(animation);
+ getChildAt(i).dispatchWindowInsetsAnimationStarted(animation, bounds);
}
+ return bounds;
}
@Override
- WindowInsets dispatchWindowInsetsAnimationProgress(WindowInsets insets) {
+ @NonNull
+ public WindowInsets dispatchWindowInsetsAnimationProgress(@NonNull WindowInsets insets) {
insets = super.dispatchWindowInsetsAnimationProgress(insets);
final int count = getChildCount();
for (int i = 0; i < count; i++) {
@@ -7217,7 +7222,7 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager
}
@Override
- void dispatchWindowInsetsAnimationFinished(InsetsAnimation animation) {
+ public void dispatchWindowInsetsAnimationFinished(@NonNull InsetsAnimation animation) {
super.dispatchWindowInsetsAnimationFinished(animation);
final int count = getChildCount();
for (int i = 0; i < count; i++) {
diff --git a/core/java/android/view/ViewHierarchyEncoder.java b/core/java/android/view/ViewHierarchyEncoder.java
index d5716bfaaf00..b0e0524a0d85 100644
--- a/core/java/android/view/ViewHierarchyEncoder.java
+++ b/core/java/android/view/ViewHierarchyEncoder.java
@@ -2,7 +2,7 @@ package android.view;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
diff --git a/core/java/android/view/ViewOverlay.java b/core/java/android/view/ViewOverlay.java
index e23c687af49b..7830c57e53ec 100644
--- a/core/java/android/view/ViewOverlay.java
+++ b/core/java/android/view/ViewOverlay.java
@@ -17,7 +17,7 @@ package android.view;
import android.animation.LayoutTransition;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index 3171306fc568..3bab9eb63961 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -19,12 +19,29 @@ package android.view;
import static android.view.Display.DEFAULT_DISPLAY;
import static android.view.Display.INVALID_DISPLAY;
import static android.view.View.PFLAG_DRAW_ANIMATION;
+import static android.view.View.SYSTEM_UI_FLAG_FULLSCREEN;
+import static android.view.View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
+import static android.view.View.SYSTEM_UI_FLAG_IMMERSIVE;
+import static android.view.View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
+import static android.view.View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
+import static android.view.View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
import static android.view.WindowCallbacks.RESIZE_MODE_DOCKED_DIVIDER;
import static android.view.WindowCallbacks.RESIZE_MODE_FREEFORM;
+import static android.view.WindowInsetsController.BEHAVIOR_SHOW_BARS_BY_SWIPE;
+import static android.view.WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE;
+import static android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN;
+import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
+import static android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
+import static android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
import static android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
+import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_FIT_INSETS_CONTROLLED;
import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_DECOR_VIEW_VISIBILITY;
+import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
+import static android.view.WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL;
+import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
+import static android.view.WindowManager.LayoutParams.TYPE_TOAST;
import static android.view.WindowManager.LayoutParams.TYPE_VOLUME_OVERLAY;
import android.Manifest;
@@ -32,10 +49,10 @@ import android.animation.LayoutTransition;
import android.annotation.AnyThread;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityManager;
import android.app.ActivityThread;
import android.app.ResourcesManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.Context;
@@ -93,6 +110,7 @@ import android.view.SurfaceControl.Transaction;
import android.view.View.AttachInfo;
import android.view.View.FocusDirection;
import android.view.View.MeasureSpec;
+import android.view.WindowInsets.Type;
import android.view.WindowInsets.Type.InsetsType;
import android.view.WindowManager.LayoutParams.SoftInputModeFlags;
import android.view.accessibility.AccessibilityEvent;
@@ -118,6 +136,7 @@ import android.widget.Scroller;
import com.android.internal.R;
import com.android.internal.annotations.GuardedBy;
+import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.os.IResultReceiver;
import com.android.internal.os.SomeArgs;
import com.android.internal.policy.PhoneFallbackEventHandler;
@@ -519,6 +538,9 @@ public final class ViewRootImpl implements ViewParent,
private WindowInsets mLastWindowInsets;
+ // Insets types hidden by legacy window flags or system UI flags.
+ private @InsetsType int mTypesHiddenByFlags = 0;
+
/** Last applied configuration obtained from resources. */
private final Configuration mLastConfigurationFromResources = new Configuration();
/** Last configuration reported from WM or via {@link #MSG_UPDATE_CONFIGURATION}. */
@@ -890,6 +912,7 @@ public final class ViewRootImpl implements ViewParent,
mOrigWindowType = mWindowAttributes.type;
mAttachInfo.mRecomputeGlobalAttributes = true;
collectViewAttributes();
+ adjustLayoutParamsForCompatibility(mWindowAttributes);
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(), mTmpFrame,
mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
@@ -1841,15 +1864,96 @@ public final class ViewRootImpl implements ViewParent,
private int getImpliedSystemUiVisibility(WindowManager.LayoutParams params) {
int vis = 0;
// Translucent decor window flags imply stable system ui visibility.
- if ((params.flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0) {
+ if ((params.flags & FLAG_TRANSLUCENT_STATUS) != 0) {
vis |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
}
- if ((params.flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) != 0) {
+ if ((params.flags & FLAG_TRANSLUCENT_NAVIGATION) != 0) {
vis |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
}
return vis;
}
+ @VisibleForTesting
+ public static void adjustLayoutParamsForCompatibility(WindowManager.LayoutParams inOutParams) {
+ if (sNewInsetsMode != NEW_INSETS_MODE_FULL) {
+ return;
+ }
+ final int sysUiVis = inOutParams.systemUiVisibility | inOutParams.subtreeSystemUiVisibility;
+ final int flags = inOutParams.flags;
+ final int type = inOutParams.type;
+ final int adjust = inOutParams.softInputMode & SOFT_INPUT_MASK_ADJUST;
+
+ if ((sysUiVis & SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0) {
+ inOutParams.insetsFlags.behavior = BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE;
+ } else if ((sysUiVis & SYSTEM_UI_FLAG_IMMERSIVE) != 0) {
+ inOutParams.insetsFlags.behavior = BEHAVIOR_SHOW_BARS_BY_SWIPE;
+ }
+
+ if ((inOutParams.privateFlags & PRIVATE_FLAG_FIT_INSETS_CONTROLLED) != 0) {
+ return;
+ }
+
+ int types = inOutParams.getFitWindowInsetsTypes();
+ int sides = inOutParams.getFitWindowInsetsSides();
+ boolean ignoreVis = inOutParams.getFitIgnoreVisibility();
+
+ if (((sysUiVis & SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) != 0
+ || (flags & FLAG_LAYOUT_IN_SCREEN) != 0)
+ || (flags & FLAG_TRANSLUCENT_STATUS) != 0) {
+ types &= ~Type.statusBars();
+ }
+ if ((sysUiVis & SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
+ || (flags & FLAG_TRANSLUCENT_NAVIGATION) != 0) {
+ types &= ~Type.systemBars();
+ }
+ if (type == TYPE_TOAST || type == TYPE_SYSTEM_ALERT) {
+ ignoreVis = true;
+ } else if ((types & Type.systemBars()) == Type.systemBars()
+ && adjust == SOFT_INPUT_ADJUST_RESIZE) {
+ types |= Type.ime();
+ }
+ inOutParams.setFitWindowInsetsTypes(types);
+ inOutParams.setFitWindowInsetsSides(sides);
+ inOutParams.setFitIgnoreVisibility(ignoreVis);
+
+ // The fitting of insets are not really controlled by the clients, so we remove the flag.
+ inOutParams.privateFlags &= ~PRIVATE_FLAG_FIT_INSETS_CONTROLLED;
+ }
+
+ private void controlInsetsForCompatibility(WindowManager.LayoutParams params) {
+ if (sNewInsetsMode != NEW_INSETS_MODE_FULL) {
+ return;
+ }
+ final int sysUiVis = params.systemUiVisibility | params.subtreeSystemUiVisibility;
+ final int flags = params.flags;
+ final boolean statusWasHiddenByFlags = (mTypesHiddenByFlags & Type.statusBars()) != 0;
+ final boolean statusIsHiddenByFlags = (sysUiVis & SYSTEM_UI_FLAG_FULLSCREEN) != 0
+ || (flags & FLAG_FULLSCREEN) != 0;
+ final boolean navWasHiddenByFlags = (mTypesHiddenByFlags & Type.navigationBars()) != 0;
+ final boolean navIsHiddenByFlags = (sysUiVis & SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0;
+
+ @InsetsType int typesToHide = 0;
+ @InsetsType int typesToShow = 0;
+ if (statusIsHiddenByFlags && !statusWasHiddenByFlags) {
+ typesToHide |= Type.statusBars();
+ } else if (!statusIsHiddenByFlags && statusWasHiddenByFlags) {
+ typesToShow |= Type.statusBars();
+ }
+ if (navIsHiddenByFlags && !navWasHiddenByFlags) {
+ typesToHide |= Type.navigationBars();
+ } else if (!navIsHiddenByFlags && navWasHiddenByFlags) {
+ typesToShow |= Type.navigationBars();
+ }
+ if (typesToHide != 0) {
+ getInsetsController().hide(typesToHide);
+ }
+ if (typesToShow != 0) {
+ getInsetsController().show(typesToShow);
+ }
+ mTypesHiddenByFlags |= typesToHide;
+ mTypesHiddenByFlags &= ~typesToShow;
+ }
+
private boolean measureHierarchy(final View host, final WindowManager.LayoutParams lp,
final Resources res, final int desiredWindowWidth, final int desiredWindowHeight) {
int childWidthMeasureSpec;
@@ -2271,6 +2375,8 @@ public final class ViewRootImpl implements ViewParent,
&& !PixelFormat.formatHasAlpha(params.format)) {
params.format = PixelFormat.TRANSLUCENT;
}
+ adjustLayoutParamsForCompatibility(params);
+ controlInsetsForCompatibility(params);
}
if (mFirst || windowShouldResize || insetsChanged ||
@@ -2757,7 +2863,7 @@ public final class ViewRootImpl implements ViewParent,
if (changedVisibility || regainedFocus) {
// Toasts are presented as notifications - don't present them as windows as well
boolean isToast = (mWindowAttributes == null) ? false
- : (mWindowAttributes.type == WindowManager.LayoutParams.TYPE_TOAST);
+ : (mWindowAttributes.type == TYPE_TOAST);
if (!isToast) {
host.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
}
@@ -4051,7 +4157,7 @@ public final class ViewRootImpl implements ViewParent,
}
boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
- final Rect ci = mAttachInfo.mContentInsets;
+ final Rect ci = getWindowInsets(false).getSystemWindowInsetsAsRect();
final Rect vi = mAttachInfo.mVisibleInsets;
int scrollY = 0;
boolean handled = false;
diff --git a/core/java/android/view/ViewTreeObserver.java b/core/java/android/view/ViewTreeObserver.java
index c72baca0b93b..d7b0afc89eaa 100644
--- a/core/java/android/view/ViewTreeObserver.java
+++ b/core/java/android/view/ViewTreeObserver.java
@@ -18,7 +18,7 @@ package android.view;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.Region;
diff --git a/core/java/android/view/Window.java b/core/java/android/view/Window.java
index c699cdca4d00..07764694a40b 100644
--- a/core/java/android/view/Window.java
+++ b/core/java/android/view/Window.java
@@ -26,8 +26,8 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.StyleRes;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.WindowConfiguration;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
@@ -46,6 +46,8 @@ import android.os.RemoteException;
import android.transition.Scene;
import android.transition.Transition;
import android.transition.TransitionManager;
+import android.view.WindowInsets.Side.InsetsSide;
+import android.view.WindowInsets.Type.InsetsType;
import android.view.accessibility.AccessibilityEvent;
import java.util.Collections;
@@ -1170,16 +1172,6 @@ public abstract class Window {
/**
* {@hide}
*/
- @UnsupportedAppUsage
- protected void setNeedsMenuKey(int value) {
- final WindowManager.LayoutParams attrs = getAttributes();
- attrs.needsMenuKey = value;
- dispatchWindowAttributesChanged(attrs);
- }
-
- /**
- * {@hide}
- */
protected void dispatchWindowAttributesChanged(WindowManager.LayoutParams attrs) {
if (mCallback != null) {
mCallback.onWindowAttributesChanged(attrs);
@@ -1251,6 +1243,60 @@ public abstract class Window {
}
/**
+ * A shortcut for {@link WindowManager.LayoutParams#setFitWindowInsetsTypes(int)}
+ * @hide pending unhide
+ */
+ public void setFitWindowInsetsTypes(@InsetsType int types) {
+ final WindowManager.LayoutParams attrs = getAttributes();
+ attrs.setFitWindowInsetsTypes(types);
+ dispatchWindowAttributesChanged(attrs);
+ }
+
+ /**
+ * A shortcut for {@link WindowManager.LayoutParams#setFitWindowInsetsSides(int)}
+ * @hide pending unhide
+ */
+ public void setFitWindowInsetsSides(@InsetsSide int sides) {
+ final WindowManager.LayoutParams attrs = getAttributes();
+ attrs.setFitWindowInsetsSides(sides);
+ dispatchWindowAttributesChanged(attrs);
+ }
+
+ /**
+ * A shortcut for {@link WindowManager.LayoutParams#setFitIgnoreVisibility(boolean)}
+ * @hide pending unhide
+ */
+ public void setFitIgnoreVisibility(boolean ignore) {
+ final WindowManager.LayoutParams attrs = getAttributes();
+ attrs.setFitIgnoreVisibility(ignore);
+ dispatchWindowAttributesChanged(attrs);
+ }
+
+ /**
+ * A shortcut for {@link WindowManager.LayoutParams#getFitWindowInsetsTypes}
+ * @hide pending unhide
+ */
+ public @InsetsType int getFitWindowInsetsTypes() {
+ return getAttributes().getFitWindowInsetsTypes();
+ }
+
+ /**
+ * A shortcut for {@link WindowManager.LayoutParams#getFitWindowInsetsSides()}
+ * @hide pending unhide
+ */
+ public @InsetsSide int getFitWindowInsetsSides() {
+ return getAttributes().getFitWindowInsetsSides();
+ }
+
+ /**
+ * A shortcut for {@link WindowManager.LayoutParams#getFitIgnoreVisibility()}
+ * @hide pending unhide
+ */
+ public boolean getFitIgnoreVisibility() {
+ return getAttributes().getFitIgnoreVisibility();
+ }
+
+ /**
* Specify custom window attributes. <strong>PLEASE NOTE:</strong> the
* layout params you give here should generally be from values previously
* retrieved with {@link #getAttributes()}; you probably do not want to
@@ -2527,7 +2573,8 @@ public abstract class Window {
/**
* @return The {@link WindowInsetsController} associated with this window
* @see View#getWindowInsetsController()
- * @hide pending unhide
*/
- public abstract @NonNull WindowInsetsController getInsetsController();
+ public @Nullable WindowInsetsController getInsetsController() {
+ return null;
+ }
}
diff --git a/core/java/android/view/WindowAnimationFrameStats.java b/core/java/android/view/WindowAnimationFrameStats.java
index 399dfba64461..dfc4f0cd4dc6 100644
--- a/core/java/android/view/WindowAnimationFrameStats.java
+++ b/core/java/android/view/WindowAnimationFrameStats.java
@@ -16,7 +16,7 @@
package android.view;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/view/WindowContentFrameStats.java b/core/java/android/view/WindowContentFrameStats.java
index 9fa5a005055d..217197c96793 100644
--- a/core/java/android/view/WindowContentFrameStats.java
+++ b/core/java/android/view/WindowContentFrameStats.java
@@ -16,7 +16,7 @@
package android.view;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/view/WindowInsets.java b/core/java/android/view/WindowInsets.java
index 57bd5bb8cae8..a9cc50f9e65e 100644
--- a/core/java/android/view/WindowInsets.java
+++ b/core/java/android/view/WindowInsets.java
@@ -34,7 +34,7 @@ import android.annotation.IntDef;
import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Intent;
import android.graphics.Insets;
import android.graphics.Rect;
@@ -177,7 +177,7 @@ public final class WindowInsets {
* @return The insets that include system bars indicated by {@code typeMask}, taken from
* {@code typeInsetsMap}.
*/
- private static Insets getInsets(Insets[] typeInsetsMap, @InsetsType int typeMask) {
+ static Insets getInsets(Insets[] typeInsetsMap, @InsetsType int typeMask) {
Insets result = null;
for (int i = FIRST; i <= LAST; i = i << 1) {
if ((typeMask & i) == 0) {
@@ -289,9 +289,8 @@ public final class WindowInsets {
*
* @param typeMask Bit mask of {@link InsetsType}s to query the insets for.
* @return The insets.
- *
- * @hide pending unhide
*/
+ @NonNull
public Insets getInsets(@InsetsType int typeMask) {
return getInsets(mTypeInsetsMap, typeMask);
}
@@ -313,8 +312,8 @@ public final class WindowInsets {
* insets are not available for this type as the height of the
* IME is dynamic depending on the {@link EditorInfo} of the
* currently focused view, as well as the UI state of the IME.
- * @hide pending unhide
*/
+ @NonNull
public Insets getMaxInsets(@InsetsType int typeMask) throws IllegalArgumentException {
if ((typeMask & IME) != 0) {
throw new IllegalArgumentException("Unable to query the maximum insets for IME");
@@ -329,7 +328,6 @@ public final class WindowInsets {
* @param typeMask Bit mask of {@link Type.InsetsType}s to query visibility status.
* @return {@code true} if and only if all windows included in {@code typeMask} are currently
* visible on screen.
- * @hide pending unhide
*/
public boolean isVisible(@InsetsType int typeMask) {
for (int i = FIRST; i <= LAST; i = i << 1) {
@@ -874,7 +872,7 @@ public final class WindowInsets {
return typeInsetsMap;
}
- private static Insets insetInsets(Insets insets, int left, int top, int right, int bottom) {
+ static Insets insetInsets(Insets insets, int left, int top, int right, int bottom) {
int newLeft = Math.max(0, insets.left - left);
int newTop = Math.max(0, insets.top - top);
int newRight = Math.max(0, insets.right - right);
@@ -1015,7 +1013,6 @@ public final class WindowInsets {
* @param insets The insets to set.
*
* @return itself
- * @hide pending unhide
*/
@NonNull
public Builder setInsets(@InsetsType int typeMask, @NonNull Insets insets) {
@@ -1046,7 +1043,6 @@ public final class WindowInsets {
* the IME is dynamic depending on the {@link EditorInfo}
* of the currently focused view, as well as the UI
* state of the IME.
- * @hide pending unhide
*/
@NonNull
public Builder setMaxInsets(@InsetsType int typeMask, @NonNull Insets insets)
@@ -1070,7 +1066,6 @@ public final class WindowInsets {
* @param visible Whether to mark the windows as visible or not.
*
* @return itself
- * @hide pending unhide
*/
@NonNull
public Builder setVisible(@InsetsType int typeMask, boolean visible) {
@@ -1145,7 +1140,6 @@ public final class WindowInsets {
/**
* Class that defines different types of sources causing window insets.
- * @hide pending unhide
*/
public static final class Type {
@@ -1295,4 +1289,31 @@ public final class WindowInsets {
return 0xFFFFFFFF;
}
}
+
+ /**
+ * Class that defines different sides for insets.
+ * @hide pending unhide
+ */
+ public static final class Side {
+
+ public static final int LEFT = 1 << 0;
+ public static final int TOP = 1 << 1;
+ public static final int RIGHT = 1 << 2;
+ public static final int BOTTOM = 1 << 3;
+
+ private Side() {
+ }
+
+ /** @hide */
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(flag = true, value = {LEFT, TOP, RIGHT, BOTTOM})
+ public @interface InsetsSide {}
+
+ /**
+ * @return all four sides.
+ */
+ public static @InsetsSide int all() {
+ return LEFT | TOP | RIGHT | BOTTOM;
+ }
+ }
}
diff --git a/core/java/android/view/WindowInsetsAnimationCallback.java b/core/java/android/view/WindowInsetsAnimationCallback.java
new file mode 100644
index 000000000000..5e71f271f1d4
--- /dev/null
+++ b/core/java/android/view/WindowInsetsAnimationCallback.java
@@ -0,0 +1,276 @@
+/*
+ * Copyright (C) 2019 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.view;
+
+import android.annotation.FloatRange;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.graphics.Insets;
+import android.view.WindowInsets.Type.InsetsType;
+import android.view.animation.Interpolator;
+
+/**
+ * Interface that allows the application to listen to animation events for windows that cause
+ * insets.
+ */
+public interface WindowInsetsAnimationCallback {
+
+ /**
+ * Called when an inset animation gets started.
+ * <p>
+ * Note that, like {@link #onProgress}, dispatch of the animation start event is hierarchical:
+ * It will starts at the root of the view hierarchy and then traverse it and invoke the callback
+ * of the specific {@link View} that is being traversed. The method my return a modified
+ * instance of the bounds by calling {@link AnimationBounds#inset} to indicate that a part of
+ * the insets have been used to offset or clip its children, and the children shouldn't worry
+ * about that part anymore.
+ *
+ * @param animation The animation that is about to start.
+ * @param bounds The bounds in which animation happens.
+ * @return The animation representing the part of the insets that should be dispatched to the
+ * subtree of the hierarchy.
+ */
+ @NonNull
+ default AnimationBounds onStarted(
+ @NonNull InsetsAnimation animation, @NonNull AnimationBounds bounds) {
+ return bounds;
+ }
+
+ /**
+ * Called when the insets change as part of running an animation. Note that even if multiple
+ * animations for different types are running, there will only be one progress callback per
+ * frame. The {@code insets} passed as an argument represents the overall state and will include
+ * all types, regardless of whether they are animating or not.
+ * <p>
+ * Note that insets dispatch is hierarchical: It will start at the root of the view hierarchy,
+ * and then traverse it and invoke the callback of the specific {@link View} being traversed.
+ * The method may return a modified instance by calling
+ * {@link WindowInsets#inset(int, int, int, int)} to indicate that a part of the insets have
+ * been used to offset or clip its children, and the children shouldn't worry about that part
+ * anymore.
+ * TODO: Introduce a way to map (type -> InsetAnimation) so app developer can query animation
+ * for a given type e.g. callback.getAnimation(type) OR controller.getAnimation(type).
+ * Or on the controller directly?
+ * @param insets The current insets.
+ * @return The insets to dispatch to the subtree of the hierarchy.
+ */
+ @NonNull
+ WindowInsets onProgress(@NonNull WindowInsets insets);
+
+ /**
+ * Called when an inset animation has finished.
+ *
+ * @param animation The animation that has finished running. This will be the same instance as
+ * passed into {@link #onStarted}
+ */
+ default void onFinished(@NonNull InsetsAnimation animation) {
+ }
+
+ /**
+ * Class representing an animation of a set of windows that cause insets.
+ */
+ final class InsetsAnimation {
+
+ private final @InsetsType int mTypeMask;
+ private float mFraction;
+ @Nullable private final Interpolator mInterpolator;
+ private long mDurationMs;
+ private float mAlpha;
+
+ public InsetsAnimation(
+ @InsetsType int typeMask, @Nullable Interpolator interpolator, long durationMs) {
+ mTypeMask = typeMask;
+ mInterpolator = interpolator;
+ mDurationMs = durationMs;
+ }
+
+ /**
+ * @return The bitmask of {@link WindowInsets.Type.InsetsType}s that are animating.
+ */
+ public @InsetsType int getTypeMask() {
+ return mTypeMask;
+ }
+
+ /**
+ * Returns the raw fractional progress of this animation between
+ * {@link AnimationBounds#getLowerBound()} and {@link AnimationBounds#getUpperBound()}. Note
+ * that this progress is the global progress of the animation, whereas
+ * {@link WindowInsetsAnimationCallback#onProgress} will only dispatch the insets that may
+ * be inset with {@link WindowInsets#inset} by parents of views in the hierarchy.
+ * Progress per insets animation is global for the entire animation. One animation animates
+ * all things together (in, out, ...). If they don't animate together, we'd have
+ * multiple animations.
+ *
+ * @return The current progress of this animation.
+ */
+ @FloatRange(from = 0f, to = 1f)
+ public float getFraction() {
+ return mFraction;
+ }
+
+ /**
+ * Returns the interpolated fractional progress of this animation between
+ * {@link AnimationBounds#getLowerBound()} and {@link AnimationBounds#getUpperBound()}. Note
+ * that this progress is the global progress of the animation, whereas
+ * {@link WindowInsetsAnimationCallback#onProgress} will only dispatch the insets that may
+ * be inset with {@link WindowInsets#inset} by parents of views in the hierarchy.
+ * Progress per insets animation is global for the entire animation. One animation animates
+ * all things together (in, out, ...). If they don't animate together, we'd have
+ * multiple animations.
+ * @see #getFraction() for raw fraction.
+ * @return The current interpolated progress of this animation. -1 if interpolator isn't
+ * specified.
+ */
+ public float getInterpolatedFraction() {
+ if (mInterpolator != null) {
+ return mInterpolator.getInterpolation(mFraction);
+ }
+ return -1;
+ }
+
+ @Nullable
+ public Interpolator getInterpolator() {
+ return mInterpolator;
+ }
+
+ /**
+ * @return duration of animation in {@link java.util.concurrent.TimeUnit#MILLISECONDS}.
+ */
+ public long getDurationMillis() {
+ return mDurationMs;
+ }
+
+ /**
+ * Set fraction of the progress if {@link WindowInsets.Type.InsetsType} animation is
+ * controlled by the app {@see #getCurrentFraction}.
+ * <p>Note: If app didn't create {@link InsetsAnimation}, it shouldn't set progress either.
+ * Progress would be set by system with the system-default animation.
+ * </p>
+ * @param fraction fractional progress between 0 and 1 where 0 represents hidden and
+ * zero progress and 1 represent fully shown final state.
+ */
+ public void setFraction(@FloatRange(from = 0f, to = 1f) float fraction) {
+ mFraction = fraction;
+ }
+
+ /**
+ * Set duration of the animation if {@link WindowInsets.Type.InsetsType} animation is
+ * controlled by the app.
+ * <p>Note: If app didn't create {@link InsetsAnimation}, it shouldn't set duration either.
+ * Duration would be set by system with the system-default animation.
+ * </p>
+ * @param durationMs in {@link java.util.concurrent.TimeUnit#MILLISECONDS}
+ */
+ public void setDuration(long durationMs) {
+ mDurationMs = durationMs;
+ }
+
+ /**
+ * @return alpha of {@link WindowInsets.Type.InsetsType}.
+ */
+ @FloatRange(from = 0f, to = 1f)
+ public float getAlpha() {
+ return mAlpha;
+ }
+
+ void setAlpha(@FloatRange(from = 0f, to = 1f) float alpha) {
+ mAlpha = alpha;
+ }
+ }
+
+ /**
+ * Class representing the range of an {@link InsetsAnimation}
+ */
+ final class AnimationBounds {
+ private final Insets mLowerBound;
+ private final Insets mUpperBound;
+
+ public AnimationBounds(@NonNull Insets lowerBound, @NonNull Insets upperBound) {
+ mLowerBound = lowerBound;
+ mUpperBound = upperBound;
+ }
+
+ /**
+ * Queries the lower inset bound of the animation. If the animation is about showing or
+ * hiding a window that cause insets, the lower bound is {@link Insets#NONE} and the upper
+ * bound is the same as {@link WindowInsets#getInsets(int)} for the fully shown state. This
+ * is the same as {@link WindowInsetsAnimationController#getHiddenStateInsets} and
+ * {@link WindowInsetsAnimationController#getShownStateInsets} in case the listener gets
+ * invoked because of an animation that originates from
+ * {@link WindowInsetsAnimationController}.
+ * <p>
+ * However, if the size of a window that causes insets is changing, these are the
+ * lower/upper bounds of that size animation.
+ * </p>
+ * There are no overlapping animations for a specific type, but there may be multiple
+ * animations running at the same time for different inset types.
+ *
+ * @see #getUpperBound()
+ * @see WindowInsetsAnimationController#getHiddenStateInsets
+ */
+ @NonNull
+ public Insets getLowerBound() {
+ return mLowerBound;
+ }
+
+ /**
+ * Queries the upper inset bound of the animation. If the animation is about showing or
+ * hiding a window that cause insets, the lower bound is {@link Insets#NONE}
+ * nd the upper bound is the same as {@link WindowInsets#getInsets(int)} for the fully
+ * shown state. This is the same as
+ * {@link WindowInsetsAnimationController#getHiddenStateInsets} and
+ * {@link WindowInsetsAnimationController#getShownStateInsets} in case the listener gets
+ * invoked because of an animation that originates from
+ * {@link WindowInsetsAnimationController}.
+ * <p>
+ * However, if the size of a window that causes insets is changing, these are the
+ * lower/upper bounds of that size animation.
+ * <p>
+ * There are no overlapping animations for a specific type, but there may be multiple
+ * animations running at the same time for different inset types.
+ *
+ * @see #getLowerBound()
+ * @see WindowInsetsAnimationController#getShownStateInsets
+ */
+ @NonNull
+ public Insets getUpperBound() {
+ return mUpperBound;
+ }
+
+ /**
+ * Insets both the lower and upper bound by the specified insets. This is to be used in
+ * {@link WindowInsetsAnimationCallback#onStarted} to indicate that a part of the insets has
+ * been used to offset or clip its children, and the children shouldn't worry about that
+ * part anymore.
+ *
+ * @param insets The amount to inset.
+ * @return A copy of this instance inset in the given directions.
+ * @see WindowInsets#inset
+ * @see WindowInsetsAnimationCallback#onStarted
+ */
+ @NonNull
+ public AnimationBounds inset(@NonNull Insets insets) {
+ return new AnimationBounds(
+ // TODO: refactor so that WindowInsets.insetInsets() is in a more appropriate
+ // place eventually.
+ WindowInsets.insetInsets(
+ mLowerBound, insets.left, insets.top, insets.right, insets.bottom),
+ WindowInsets.insetInsets(
+ mUpperBound, insets.left, insets.top, insets.right, insets.bottom));
+ }
+ }
+}
diff --git a/core/java/android/view/WindowInsetsAnimationControlListener.java b/core/java/android/view/WindowInsetsAnimationControlListener.java
index 33fb327121c0..8a226c1bbe23 100644
--- a/core/java/android/view/WindowInsetsAnimationControlListener.java
+++ b/core/java/android/view/WindowInsetsAnimationControlListener.java
@@ -22,19 +22,17 @@ import android.view.inputmethod.EditorInfo;
/**
* Interface that informs the client about {@link WindowInsetsAnimationController} state changes.
- * @hide pending unhide
*/
public interface WindowInsetsAnimationControlListener {
/**
- * Gets called as soon as the animation is ready to be controlled. This may be
- * delayed when the IME needs to redraw because of an {@link EditorInfo} change, or when the
- * window is starting up.
+ * Called when the animation is ready to be controlled. This may be delayed when the IME needs
+ * to redraw because of an {@link EditorInfo} change, or when the window is starting up.
*
* @param controller The controller to control the inset animation.
* @param types The {@link InsetsType}s it was able to gain control over. Note that this may be
* different than the types passed into
- * {@link WindowInsetsController#controlWindowInsetsAnimation} in case the window
+ * {@link WindowInsetsController#controlInputMethodAnimation} in case the window
* wasn't able to gain the controls because it wasn't the IME target or not
* currently the window that's controlling the system bars.
*/
diff --git a/core/java/android/view/WindowInsetsAnimationController.java b/core/java/android/view/WindowInsetsAnimationController.java
index 5cbf3b852018..2bf0d277268d 100644
--- a/core/java/android/view/WindowInsetsAnimationController.java
+++ b/core/java/android/view/WindowInsetsAnimationController.java
@@ -16,83 +16,133 @@
package android.view;
+import android.annotation.FloatRange;
import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.SuppressLint;
import android.graphics.Insets;
import android.view.WindowInsets.Type.InsetsType;
-import android.view.WindowInsetsAnimationListener.InsetsAnimation;
+import android.view.WindowInsetsAnimationCallback.AnimationBounds;
/**
- * Interface to control a window inset animation frame-by-frame.
- * @hide pending unhide
+ * Controller for app-driven animation of system windows.
+ * <p>
+ * {@code WindowInsetsAnimationController} lets apps animate system windows such as
+ * the {@link android.inputmethodservice.InputMethodService IME}. The animation is
+ * synchronized, such that changes the system windows and the app's current frame
+ * are rendered at the same time.
+ * <p>
+ * Control is obtained through {@link WindowInsetsController#controlInputMethodAnimation}.
*/
+@SuppressLint("NotClosable")
public interface WindowInsetsAnimationController {
/**
* Retrieves the {@link Insets} when the windows this animation is controlling are fully hidden.
* <p>
+ * Note that these insets are always relative to the window, which is the same as being relative
+ * to {@link View#getRootView}
+ * <p>
* If there are any animation listeners registered, this value is the same as
- * {@link InsetsAnimation#getLowerBound()} that will be passed into the callbacks.
+ * {@link AnimationBounds#getLowerBound()} that is being be passed into the root view of the
+ * hierarchy.
*
* @return Insets when the windows this animation is controlling are fully hidden.
*
- * @see InsetsAnimation#getLowerBound()
+ * @see AnimationBounds#getLowerBound()
*/
@NonNull Insets getHiddenStateInsets();
/**
* Retrieves the {@link Insets} when the windows this animation is controlling are fully shown.
* <p>
- * In case the size of a window causing insets is changing in the middle of the animation, we
- * execute that height change after this animation has finished.
+ * Note that these insets are always relative to the window, which is the same as being relative
+ * to {@link View#getRootView}
* <p>
* If there are any animation listeners registered, this value is the same as
- * {@link InsetsAnimation#getUpperBound()} that will be passed into the callbacks.
+ * {@link AnimationBounds#getUpperBound()} that is being passed into the root view of hierarchy.
*
* @return Insets when the windows this animation is controlling are fully shown.
*
- * @see InsetsAnimation#getUpperBound()
+ * @see AnimationBounds#getUpperBound()
*/
@NonNull Insets getShownStateInsets();
/**
- * @return The current insets on the window. These will follow any animation changes.
+ * Retrieves the current insets.
+ * <p>
+ * Note that these insets are always relative to the window, which is the same as
+ * being relative
+ * to {@link View#getRootView}
+ * @return The current insets on the currently showing frame. These insets will change as the
+ * animation progresses to reflect the current insets provided by the controlled window.
*/
@NonNull Insets getCurrentInsets();
/**
+ * Returns the progress as previously set by {@code fraction} in {@link #setInsetsAndAlpha}
+ *
+ * @return the progress of the animation, where {@code 0} is fully hidden and {@code 1} is
+ * fully shown.
+ * <p>
+ * Note: this value represents raw overall progress of the animation
+ * i.e. the combined progress of insets and alpha.
+ * <p>
+ */
+ @FloatRange(from = 0f, to = 1f)
+ float getCurrentFraction();
+
+ /**
+ * Current alpha value of the window.
+ * @return float value between 0 and 1.
+ */
+ float getCurrentAlpha();
+
+ /**
* @return The {@link InsetsType}s this object is currently controlling.
*/
@InsetsType int getTypes();
/**
- * Modifies the insets by indirectly moving the windows around in the system that are causing
- * window insets.
+ * Modifies the insets for the frame being drawn by indirectly moving the windows around in the
+ * system that are causing window insets.
+ * <p>
+ * Note that these insets are always relative to the window, which is the same as being relative
+ * to {@link View#getRootView}
* <p>
- * Note that this will <b>not</b> inform the view system of a full inset change via
+ * Also note that this will <b>not</b> inform the view system of a full inset change via
* {@link View#dispatchApplyWindowInsets} in order to avoid a full layout pass during the
* animation. If you'd like to animate views during a window inset animation, register a
- * {@link WindowInsetsAnimationListener} by calling
- * {@link View#setWindowInsetsAnimationListener(WindowInsetsAnimationListener)} that will be
- * notified about any insets change via {@link WindowInsetsAnimationListener#onProgress} during
+ * {@link WindowInsetsAnimationCallback} by calling
+ * {@link View#setWindowInsetsAnimationCallback(WindowInsetsAnimationCallback)} that will be
+ * notified about any insets change via {@link WindowInsetsAnimationCallback#onProgress} during
* the animation.
* <p>
* {@link View#dispatchApplyWindowInsets} will instead be called once the animation has
* finished, i.e. once {@link #finish} has been called.
+ * Note: If there are no insets, alpha animation is still applied.
*
* @param insets The new insets to apply. Based on the requested insets, the system will
* calculate the positions of the windows in the system causing insets such that
* the resulting insets of that configuration will match the passed in parameter.
* Note that these insets are being clamped to the range from
- * {@link #getHiddenStateInsets} to {@link #getShownStateInsets}
+ * {@link #getHiddenStateInsets} to {@link #getShownStateInsets}.
+ * If you intend on changing alpha only, pass null or {@link #getCurrentInsets()}.
+ * @param alpha The new alpha to apply to the inset side.
+ * @param fraction instantaneous animation progress. This value is dispatched to
+ * {@link WindowInsetsAnimationCallback}.
*
- * @see WindowInsetsAnimationListener
- * @see View#setWindowInsetsAnimationListener(WindowInsetsAnimationListener)
+ * @see WindowInsetsAnimationCallback
+ * @see View#setWindowInsetsAnimationCallback(WindowInsetsAnimationCallback)
*/
- void changeInsets(@NonNull Insets insets);
+ void setInsetsAndAlpha(@Nullable Insets insets, @FloatRange(from = 0f, to = 1f) float alpha,
+ @FloatRange(from = 0f, to = 1f) float fraction);
/**
- * @param shownTypes The list of windows causing insets that should remain shown after finishing
- * the animation.
+ * Finishes the animation, and leaves the windows shown or hidden. After invoking
+ * {@link #finish(boolean)}, this instance is no longer valid.
+ * @param shown if {@code true}, the windows will be shown after finishing the
+ * animation. Otherwise they will be hidden.
*/
- void finish(@InsetsType int shownTypes);
+ void finish(boolean shown);
}
diff --git a/core/java/android/view/WindowInsetsAnimationListener.java b/core/java/android/view/WindowInsetsAnimationListener.java
deleted file mode 100644
index f734b4b7cb0f..000000000000
--- a/core/java/android/view/WindowInsetsAnimationListener.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Copyright (C) 2018 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.view;
-
-import android.graphics.Insets;
-
-/**
- * Interface that allows the application to listen to animation events for windows that cause
- * insets.
- * @hide pending unhide
- */
-public interface WindowInsetsAnimationListener {
-
- /**
- * Called when an inset animation gets started.
- *
- * @param animation The animation that is about to start.
- */
- void onStarted(InsetsAnimation animation);
-
- /**
- * Called when the insets change as part of running an animation. Note that even if multiple
- * animations for different types are running, there will only be one progress callback per
- * frame. The {@code insets} passed as an argument represents the overall state and will include
- * all types, regardless of whether they are animating or not.
- * <p>
- * Note that insets dispatch is hierarchical: It will start at the root of the view hierarchy,
- * and then traverse it and invoke the callback of the specific {@link View} being traversed.
- * The callback may return a modified instance by calling {@link WindowInsets#inset(int, int, int, int)}
- * to indicate that a part of the insets have been used to offset or clip its children, and the
- * children shouldn't worry about that part anymore.
- *
- * @param insets The current insets.
- * @return The insets to dispatch to the subtree of the hierarchy.
- */
- WindowInsets onProgress(WindowInsets insets);
-
- /**
- * Called when an inset animation has finished.
- *
- * @param animation The animation that has finished running.
- */
- void onFinished(InsetsAnimation animation);
-
- /**
- * Class representing an animation of a set of windows that cause insets.
- */
- class InsetsAnimation {
-
- private final @WindowInsets.Type.InsetsType int mTypeMask;
- private final Insets mLowerBound;
- private final Insets mUpperBound;
-
- /**
- * @hide
- */
- InsetsAnimation(int typeMask, Insets lowerBound, Insets upperBound) {
- mTypeMask = typeMask;
- mLowerBound = lowerBound;
- mUpperBound = upperBound;
- }
-
- /**
- * @return The bitmask of {@link WindowInsets.Type.InsetsType}s that are animating.
- */
- public @WindowInsets.Type.InsetsType int getTypeMask() {
- return mTypeMask;
- }
-
- /**
- * Queries the lower inset bound of the animation. If the animation is about showing or
- * hiding a window that cause insets, the lower bound is {@link Insets#NONE} and the upper
- * bound is the same as {@link WindowInsets#getInsets(int)} for the fully shown state. This
- * is the same as {@link WindowInsetsAnimationController#getHiddenStateInsets} and
- * {@link WindowInsetsAnimationController#getShownStateInsets} in case the listener gets
- * invoked because of an animation that originates from
- * {@link WindowInsetsAnimationController}.
- * <p>
- * However, if the size of a window that causes insets is changing, these are the
- * lower/upper bounds of that size animation.
- * <p>
- * There are no overlapping animations for a specific type, but there may be two animations
- * running at the same time for different inset types.
- *
- * @see #getUpperBound()
- * @see WindowInsetsAnimationController#getHiddenStateInsets
- * TODO: It's a bit weird that these are global per window but onProgress is hierarchical.
- * TODO: If multiple types are animating, querying the bound per type isn't possible. Should
- * we:
- * 1. Offer bounds by type here?
- * 2. Restrict one animation to one single type only?
- * Returning WindowInsets here isn't feasible in case of overlapping animations: We can't
- * fill in the insets for the types from the other animation into the WindowInsets object
- * as it's changing as well.
- */
- public Insets getLowerBound() {
- return mLowerBound;
- }
-
- /**
- * @see #getLowerBound()
- * @see WindowInsetsAnimationController#getShownStateInsets
- */
- public Insets getUpperBound() {
- return mUpperBound;
- }
- }
-}
diff --git a/core/java/android/view/WindowInsetsController.java b/core/java/android/view/WindowInsetsController.java
index 39e2e73f6fa8..6de56be2f3c5 100644
--- a/core/java/android/view/WindowInsetsController.java
+++ b/core/java/android/view/WindowInsetsController.java
@@ -30,7 +30,6 @@ import java.lang.annotation.RetentionPolicy;
* Interface to control windows that generate insets.
*
* TODO Needs more information and examples once the API is more baked.
- * @hide pending unhide
*/
public interface WindowInsetsController {
@@ -64,7 +63,10 @@ public interface WindowInsetsController {
*/
int APPEARANCE_LIGHT_NAVIGATION_BARS = 1 << 4;
- /** Determines the appearance of system bars. */
+ /**
+ * Determines the appearance of system bars.
+ * @hide
+ */
@Retention(RetentionPolicy.SOURCE)
@IntDef(flag = true, value = {APPEARANCE_OPAQUE_STATUS_BARS, APPEARANCE_OPAQUE_NAVIGATION_BARS,
APPEARANCE_LOW_PROFILE_BARS, APPEARANCE_LIGHT_STATUS_BARS,
@@ -75,33 +77,40 @@ public interface WindowInsetsController {
/**
* The default option for {@link #setSystemBarsBehavior(int)}. System bars will be forcibly
* shown on any user interaction on the corresponding display if navigation bars are hidden by
- * {@link #hide(int)} or {@link WindowInsetsAnimationController#changeInsets(Insets)}.
+ * {@link #hide(int)} or
+ * {@link WindowInsetsAnimationController#setInsetsAndAlpha(Insets, float, float)}.
+ * @hide
*/
int BEHAVIOR_SHOW_BARS_BY_TOUCH = 0;
/**
* Option for {@link #setSystemBarsBehavior(int)}: Window would like to remain interactive when
* hiding navigation bars by calling {@link #hide(int)} or
- * {@link WindowInsetsAnimationController#changeInsets(Insets)}.
+ * {@link WindowInsetsAnimationController#setInsetsAndAlpha(Insets, float, float)}.
*
* <p>When system bars are hidden in this mode, they can be revealed with system gestures, such
* as swiping from the edge of the screen where the bar is hidden from.</p>
+ * @hide
*/
int BEHAVIOR_SHOW_BARS_BY_SWIPE = 1;
/**
* Option for {@link #setSystemBarsBehavior(int)}: Window would like to remain interactive when
* hiding navigation bars by calling {@link #hide(int)} or
- * {@link WindowInsetsAnimationController#changeInsets(Insets)}.
+ * {@link WindowInsetsAnimationController#setInsetsAndAlpha(Insets, float, float)}.
*
* <p>When system bars are hidden in this mode, they can be revealed temporarily with system
* gestures, such as swiping from the edge of the screen where the bar is hidden from. These
* transient system bars will overlay app’s content, may have some degree of transparency, and
* will automatically hide after a short timeout.</p>
+ * @hide
*/
int BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE = 2;
- /** Determines the behavior of system bars when hiding them by calling {@link #hide}. */
+ /**
+ * Determines the behavior of system bars when hiding them by calling {@link #hide}.
+ * @hide
+ */
@Retention(RetentionPolicy.SOURCE)
@IntDef(value = {BEHAVIOR_SHOW_BARS_BY_TOUCH, BEHAVIOR_SHOW_BARS_BY_SWIPE,
BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE})
@@ -139,23 +148,27 @@ public interface WindowInsetsController {
* the position of the windows in the system causing insets directly.
*
* @param types The {@link InsetsType}s the application has requested to control.
+ * @param durationMillis duration of animation in
+ * {@link java.util.concurrent.TimeUnit#MILLISECONDS}
* @param listener The {@link WindowInsetsAnimationControlListener} that gets called when the
* windows are ready to be controlled, among other callbacks.
* @hide
*/
- void controlWindowInsetsAnimation(@InsetsType int types,
+ void controlWindowInsetsAnimation(@InsetsType int types, long durationMillis,
@NonNull WindowInsetsAnimationControlListener listener);
/**
* Lets the application control the animation for showing the IME in a frame-by-frame manner by
* modifying the position of the IME when it's causing insets.
*
+ * @param durationMillis duration of the animation in
+ * {@link java.util.concurrent.TimeUnit#MILLISECONDS}
* @param listener The {@link WindowInsetsAnimationControlListener} that gets called when the
* IME are ready to be controlled, among other callbacks.
*/
- default void controlInputMethodAnimation(
+ default void controlInputMethodAnimation(long durationMillis,
@NonNull WindowInsetsAnimationControlListener listener) {
- controlWindowInsetsAnimation(ime(), listener);
+ controlWindowInsetsAnimation(ime(), durationMillis, listener);
}
/**
@@ -166,7 +179,7 @@ public interface WindowInsetsController {
* the event by observing {@link View#onApplyWindowInsets} and checking visibility with
* {@link WindowInsets#isVisible}.
*
- * @see #controlInputMethodAnimation(WindowInsetsAnimationControlListener)
+ * @see #controlInputMethodAnimation(long, WindowInsetsAnimationControlListener)
* @see #hideInputMethod()
*/
default void showInputMethod() {
@@ -181,7 +194,7 @@ public interface WindowInsetsController {
* the event by observing {@link View#onApplyWindowInsets} and checking visibility with
* {@link WindowInsets#isVisible}.
*
- * @see #controlInputMethodAnimation(WindowInsetsAnimationControlListener)
+ * @see #controlInputMethodAnimation(long, WindowInsetsAnimationControlListener)
* @see #showInputMethod()
*/
default void hideInputMethod() {
@@ -203,4 +216,9 @@ public interface WindowInsetsController {
* @see Behavior
*/
void setSystemBarsBehavior(@Behavior int behavior);
+
+ /**
+ * @hide
+ */
+ InsetsState getState();
}
diff --git a/core/java/android/view/WindowManager.java b/core/java/android/view/WindowManager.java
index d40f8325c320..fc126396edc6 100644
--- a/core/java/android/view/WindowManager.java
+++ b/core/java/android/view/WindowManager.java
@@ -17,11 +17,26 @@
package android.view;
import static android.content.pm.ActivityInfo.COLOR_MODE_DEFAULT;
+import static android.view.WindowInsets.Side.BOTTOM;
+import static android.view.WindowInsets.Side.LEFT;
+import static android.view.WindowInsets.Side.RIGHT;
+import static android.view.WindowInsets.Side.TOP;
+import static android.view.WindowInsets.Type.CAPTION_BAR;
+import static android.view.WindowInsets.Type.IME;
+import static android.view.WindowInsets.Type.MANDATORY_SYSTEM_GESTURES;
+import static android.view.WindowInsets.Type.NAVIGATION_BARS;
+import static android.view.WindowInsets.Type.STATUS_BARS;
+import static android.view.WindowInsets.Type.SYSTEM_GESTURES;
+import static android.view.WindowInsets.Type.TAPPABLE_ELEMENT;
+import static android.view.WindowInsets.Type.WINDOW_DECOR;
import static android.view.WindowLayoutParamsProto.ALPHA;
import static android.view.WindowLayoutParamsProto.APPEARANCE;
import static android.view.WindowLayoutParamsProto.BEHAVIOR;
import static android.view.WindowLayoutParamsProto.BUTTON_BRIGHTNESS;
import static android.view.WindowLayoutParamsProto.COLOR_MODE;
+import static android.view.WindowLayoutParamsProto.FIT_IGNORE_VISIBILITY;
+import static android.view.WindowLayoutParamsProto.FIT_INSETS_SIDES;
+import static android.view.WindowLayoutParamsProto.FIT_INSETS_TYPES;
import static android.view.WindowLayoutParamsProto.FLAGS;
import static android.view.WindowLayoutParamsProto.FORMAT;
import static android.view.WindowLayoutParamsProto.GRAVITY;
@@ -29,7 +44,6 @@ import static android.view.WindowLayoutParamsProto.HAS_SYSTEM_UI_LISTENERS;
import static android.view.WindowLayoutParamsProto.HEIGHT;
import static android.view.WindowLayoutParamsProto.HORIZONTAL_MARGIN;
import static android.view.WindowLayoutParamsProto.INPUT_FEATURE_FLAGS;
-import static android.view.WindowLayoutParamsProto.NEEDS_MENU_KEY;
import static android.view.WindowLayoutParamsProto.PREFERRED_REFRESH_RATE;
import static android.view.WindowLayoutParamsProto.PRIVATE_FLAGS;
import static android.view.WindowLayoutParamsProto.ROTATION_ANIMATION;
@@ -52,9 +66,9 @@ import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.KeyguardManager;
import android.app.Presentation;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
@@ -66,6 +80,10 @@ import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Log;
import android.util.proto.ProtoOutputStream;
+import android.view.WindowInsets.Side;
+import android.view.WindowInsets.Side.InsetsSide;
+import android.view.WindowInsets.Type;
+import android.view.WindowInsets.Type.InsetsType;
import android.view.accessibility.AccessibilityNodeInfo;
import java.lang.annotation.Retention;
@@ -1106,6 +1124,13 @@ public interface WindowManager extends ViewManager {
public static final int TYPE_APPLICATION_OVERLAY = FIRST_SYSTEM_WINDOW + 38;
/**
+ * Window type: Window for adding accessibility window magnification above other windows.
+ * This will place the window in the overlay windows.
+ * @hide
+ */
+ public static final int TYPE_ACCESSIBILITY_MAGNIFICATION_OVERLAY = FIRST_SYSTEM_WINDOW + 39;
+
+ /**
* End of types of system windows.
*/
public static final int LAST_SYSTEM_WINDOW = 2999;
@@ -1288,14 +1313,11 @@ public interface WindowManager extends ViewManager {
* set for you by Window as described in {@link Window#setFlags}.*/
public static final int FLAG_LAYOUT_INSET_DECOR = 0x00010000;
- /** Window flag: invert the state of {@link #FLAG_NOT_FOCUSABLE} with
- * respect to how this window interacts with the current method. That
- * is, if FLAG_NOT_FOCUSABLE is set and this flag is set, then the
- * window will behave as if it needs to interact with the input method
- * and thus be placed behind/away from it; if FLAG_NOT_FOCUSABLE is
- * not set and this flag is set, then the window will behave as if it
- * doesn't need to interact with the input method and can be placed
- * to use more space and cover the input method.
+ /** Window flag: When set, input method can't interact with the focusable window
+ * and can be placed to use more space and cover the input method.
+ * Note: When combined with {@link #FLAG_NOT_FOCUSABLE}, this flag has no
+ * effect since input method cannot interact with windows having {@link #FLAG_NOT_FOCUSABLE}
+ * flag set.
*/
public static final int FLAG_ALT_FOCUSABLE_IM = 0x00020000;
@@ -1834,6 +1856,20 @@ public interface WindowManager extends ViewManager {
public static final int PRIVATE_FLAG_USE_BLAST = 0x02000000;
/**
+ * Flag to indicate that the window is controlling how it fits window insets on its own.
+ * So we don't need to adjust its attributes for fitting window insets.
+ * @hide
+ */
+ public static final int PRIVATE_FLAG_FIT_INSETS_CONTROLLED = 0x04000000;
+
+ /**
+ * Flag to indicate that the window only draws the bottom bar background so that we don't
+ * extend it to system bar areas at other sides.
+ * @hide
+ */
+ public static final int PRIVATE_FLAG_ONLY_DRAW_BOTTOM_BAR_BACKGROUND = 0x08000000;
+
+ /**
* An internal annotation for flags that can be specified to {@link #softInputMode}.
*
* @hide
@@ -1935,54 +1971,20 @@ public interface WindowManager extends ViewManager {
@ViewDebug.FlagToString(
mask = PRIVATE_FLAG_COLOR_SPACE_AGNOSTIC,
equals = PRIVATE_FLAG_COLOR_SPACE_AGNOSTIC,
- name = "COLOR_SPACE_AGNOSTIC")
+ name = "COLOR_SPACE_AGNOSTIC"),
+ @ViewDebug.FlagToString(
+ mask = PRIVATE_FLAG_FIT_INSETS_CONTROLLED,
+ equals = PRIVATE_FLAG_FIT_INSETS_CONTROLLED,
+ name = "FIT_INSETS_CONTROLLED"),
+ @ViewDebug.FlagToString(
+ mask = PRIVATE_FLAG_ONLY_DRAW_BOTTOM_BAR_BACKGROUND,
+ equals = PRIVATE_FLAG_ONLY_DRAW_BOTTOM_BAR_BACKGROUND,
+ name = "ONLY_DRAW_BOTTOM_BAR_BACKGROUND")
})
@TestApi
public int privateFlags;
/**
- * Value for {@link #needsMenuKey} for a window that has not explicitly specified if it
- * needs {@link #NEEDS_MENU_SET_TRUE} or doesn't need {@link #NEEDS_MENU_SET_FALSE} a menu
- * key. For this case, we should look at windows behind it to determine the appropriate
- * value.
- *
- * @hide
- */
- public static final int NEEDS_MENU_UNSET = 0;
-
- /**
- * Value for {@link #needsMenuKey} for a window that has explicitly specified it needs a
- * menu key.
- *
- * @hide
- */
- @UnsupportedAppUsage
- public static final int NEEDS_MENU_SET_TRUE = 1;
-
- /**
- * Value for {@link #needsMenuKey} for a window that has explicitly specified it doesn't
- * needs a menu key.
- *
- * @hide
- */
- @UnsupportedAppUsage
- public static final int NEEDS_MENU_SET_FALSE = 2;
-
- /**
- * State variable for a window belonging to an activity that responds to
- * {@link KeyEvent#KEYCODE_MENU} and therefore needs a Menu key. For devices where Menu is a
- * physical button this variable is ignored, but on devices where the Menu key is drawn in
- * software it may be hidden unless this variable is set to {@link #NEEDS_MENU_SET_TRUE}.
- *
- * (Note that Action Bars, when available, are the preferred way to offer additional
- * functions otherwise accessed via an options menu.)
- *
- * {@hide}
- */
- @UnsupportedAppUsage
- public int needsMenuKey = NEEDS_MENU_UNSET;
-
- /**
* Given a particular set of window manager flags, determine whether
* such a window may be a target for an input method when it has
* focus. In particular, this checks the
@@ -1993,16 +1995,12 @@ public interface WindowManager extends ViewManager {
*
* @param flags The current window manager flags.
*
- * @return Returns true if such a window should be behind/interact
- * with an input method, false if not.
+ * @return Returns {@code true} if such a window should be behind/interact
+ * with an input method, {@code false} if not.
*/
public static boolean mayUseInputMethod(int flags) {
- switch (flags&(FLAG_NOT_FOCUSABLE|FLAG_ALT_FOCUSABLE_IM)) {
- case 0:
- case FLAG_NOT_FOCUSABLE|FLAG_ALT_FOCUSABLE_IM:
- return true;
- }
- return false;
+ return (flags & FLAG_NOT_FOCUSABLE) != FLAG_NOT_FOCUSABLE
+ && (flags & FLAG_ALT_FOCUSABLE_IM) != FLAG_ALT_FOCUSABLE_IM;
}
/**
@@ -2627,6 +2625,124 @@ public interface WindowManager extends ViewManager {
*/
public final InsetsFlags insetsFlags = new InsetsFlags();
+ @ViewDebug.ExportedProperty(flagMapping = {
+ @ViewDebug.FlagToString(
+ mask = STATUS_BARS,
+ equals = STATUS_BARS,
+ name = "STATUS_BARS"),
+ @ViewDebug.FlagToString(
+ mask = NAVIGATION_BARS,
+ equals = NAVIGATION_BARS,
+ name = "NAVIGATION_BARS"),
+ @ViewDebug.FlagToString(
+ mask = CAPTION_BAR,
+ equals = CAPTION_BAR,
+ name = "CAPTION_BAR"),
+ @ViewDebug.FlagToString(
+ mask = IME,
+ equals = IME,
+ name = "IME"),
+ @ViewDebug.FlagToString(
+ mask = SYSTEM_GESTURES,
+ equals = SYSTEM_GESTURES,
+ name = "SYSTEM_GESTURES"),
+ @ViewDebug.FlagToString(
+ mask = MANDATORY_SYSTEM_GESTURES,
+ equals = MANDATORY_SYSTEM_GESTURES,
+ name = "MANDATORY_SYSTEM_GESTURES"),
+ @ViewDebug.FlagToString(
+ mask = TAPPABLE_ELEMENT,
+ equals = TAPPABLE_ELEMENT,
+ name = "TAPPABLE_ELEMENT"),
+ @ViewDebug.FlagToString(
+ mask = WINDOW_DECOR,
+ equals = WINDOW_DECOR,
+ name = "WINDOW_DECOR")
+ })
+ private @InsetsType int mFitWindowInsetsTypes = Type.systemBars();
+
+ @ViewDebug.ExportedProperty(flagMapping = {
+ @ViewDebug.FlagToString(
+ mask = LEFT,
+ equals = LEFT,
+ name = "LEFT"),
+ @ViewDebug.FlagToString(
+ mask = TOP,
+ equals = TOP,
+ name = "TOP"),
+ @ViewDebug.FlagToString(
+ mask = RIGHT,
+ equals = RIGHT,
+ name = "RIGHT"),
+ @ViewDebug.FlagToString(
+ mask = BOTTOM,
+ equals = BOTTOM,
+ name = "BOTTOM")
+ })
+ private @InsetsSide int mFitWindowInsetsSides = Side.all();
+
+ private boolean mFitIgnoreVisibility = false;
+
+ /**
+ * Specifies types of insets that this window should avoid overlapping during layout.
+ *
+ * @param types which types of insets that this window should avoid. The initial value of
+ * this object includes all system bars.
+ * @hide pending unhide
+ */
+ public void setFitWindowInsetsTypes(@InsetsType int types) {
+ mFitWindowInsetsTypes = types;
+ privateFlags |= PRIVATE_FLAG_FIT_INSETS_CONTROLLED;
+ }
+
+ /**
+ * Specifies sides of insets that this window should avoid overlapping during layout.
+ *
+ * @param sides which sides that this window should avoid overlapping with the types
+ * specified. The initial value of this object includes all sides.
+ * @hide pending unhide
+ */
+ public void setFitWindowInsetsSides(@InsetsSide int sides) {
+ mFitWindowInsetsSides = sides;
+ privateFlags |= PRIVATE_FLAG_FIT_INSETS_CONTROLLED;
+ }
+
+ /**
+ * Specifies if this window should fit the window insets no matter they are visible or not.
+ *
+ * @param ignore if true, this window will fit the given types even if they are not visible.
+ * @hide pending unhide
+ */
+ public void setFitIgnoreVisibility(boolean ignore) {
+ mFitIgnoreVisibility = ignore;
+ privateFlags |= PRIVATE_FLAG_FIT_INSETS_CONTROLLED;
+ }
+
+ /**
+ * @return the insets types that this window is avoiding overlapping.
+ * @hide pending unhide
+ */
+ public @InsetsType int getFitWindowInsetsTypes() {
+ return mFitWindowInsetsTypes;
+ }
+
+ /**
+ * @return the sides that this window is avoiding overlapping.
+ * @hide pending unhide
+ */
+ public @InsetsSide int getFitWindowInsetsSides() {
+ return mFitWindowInsetsSides;
+ }
+
+ /**
+ * @return {@code true} if this window fits the window insets no matter they are visible or
+ * not.
+ * @hide pending unhide
+ */
+ public boolean getFitIgnoreVisibility() {
+ return mFitIgnoreVisibility;
+ }
+
public LayoutParams() {
super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
type = TYPE_APPLICATION;
@@ -2784,13 +2900,15 @@ public interface WindowManager extends ViewManager {
out.writeInt(surfaceInsets.bottom);
out.writeInt(hasManualSurfaceInsets ? 1 : 0);
out.writeInt(preservePreviousSurfaceInsets ? 1 : 0);
- out.writeInt(needsMenuKey);
out.writeLong(accessibilityIdOfAnchor);
TextUtils.writeToParcel(accessibilityTitle, out, parcelableFlags);
out.writeInt(mColorMode);
out.writeLong(hideTimeoutMilliseconds);
out.writeInt(insetsFlags.appearance);
out.writeInt(insetsFlags.behavior);
+ out.writeInt(mFitWindowInsetsTypes);
+ out.writeInt(mFitWindowInsetsSides);
+ out.writeBoolean(mFitIgnoreVisibility);
}
public static final @android.annotation.NonNull Parcelable.Creator<LayoutParams> CREATOR
@@ -2842,13 +2960,15 @@ public interface WindowManager extends ViewManager {
surfaceInsets.bottom = in.readInt();
hasManualSurfaceInsets = in.readInt() != 0;
preservePreviousSurfaceInsets = in.readInt() != 0;
- needsMenuKey = in.readInt();
accessibilityIdOfAnchor = in.readLong();
accessibilityTitle = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
mColorMode = in.readInt();
hideTimeoutMilliseconds = in.readLong();
insetsFlags.appearance = in.readInt();
insetsFlags.behavior = in.readInt();
+ mFitWindowInsetsTypes = in.readInt();
+ mFitWindowInsetsSides = in.readInt();
+ mFitIgnoreVisibility = in.readBoolean();
}
@SuppressWarnings({"PointlessBitwiseExpression"})
@@ -2884,8 +3004,6 @@ public interface WindowManager extends ViewManager {
/** {@hide} */
public static final int PREFERRED_REFRESH_RATE_CHANGED = 1 << 21;
/** {@hide} */
- public static final int NEEDS_MENU_KEY_CHANGED = 1 << 22;
- /** {@hide} */
public static final int PREFERRED_DISPLAY_MODE_ID = 1 << 23;
/** {@hide} */
public static final int ACCESSIBILITY_ANCHOR_CHANGED = 1 << 24;
@@ -3059,11 +3177,6 @@ public interface WindowManager extends ViewManager {
changes |= SURFACE_INSETS_CHANGED;
}
- if (needsMenuKey != o.needsMenuKey) {
- needsMenuKey = o.needsMenuKey;
- changes |= NEEDS_MENU_KEY_CHANGED;
- }
-
if (accessibilityIdOfAnchor != o.accessibilityIdOfAnchor) {
accessibilityIdOfAnchor = o.accessibilityIdOfAnchor;
changes |= ACCESSIBILITY_ANCHOR_CHANGED;
@@ -3094,6 +3207,21 @@ public interface WindowManager extends ViewManager {
changes |= INSET_FLAGS_CHANGED;
}
+ if (mFitWindowInsetsTypes != o.mFitWindowInsetsTypes) {
+ mFitWindowInsetsTypes = o.mFitWindowInsetsTypes;
+ changes |= LAYOUT_CHANGED;
+ }
+
+ if (mFitWindowInsetsSides != o.mFitWindowInsetsSides) {
+ mFitWindowInsetsSides = o.mFitWindowInsetsSides;
+ changes |= LAYOUT_CHANGED;
+ }
+
+ if (mFitIgnoreVisibility != o.mFitIgnoreVisibility) {
+ mFitIgnoreVisibility = o.mFitIgnoreVisibility;
+ changes |= LAYOUT_CHANGED;
+ }
+
return changes;
}
@@ -3217,9 +3345,6 @@ public interface WindowManager extends ViewManager {
sb.append(" (!preservePreviousSurfaceInsets)");
}
}
- if (needsMenuKey == NEEDS_MENU_SET_TRUE) {
- sb.append(" needsMenuKey");
- }
if (mColorMode != COLOR_MODE_DEFAULT) {
sb.append(" colorMode=").append(ActivityInfo.colorModeToString(mColorMode));
}
@@ -3251,6 +3376,20 @@ public interface WindowManager extends ViewManager {
sb.append(prefix).append(" bhv=").append(ViewDebug.flagsToString(
InsetsFlags.class, "behavior", insetsFlags.behavior));
}
+ if (mFitWindowInsetsTypes != 0) {
+ sb.append(System.lineSeparator());
+ sb.append(prefix).append(" fitTypes=").append(ViewDebug.flagsToString(
+ LayoutParams.class, "mFitWindowInsetsTypes", mFitWindowInsetsTypes));
+ }
+ if (mFitWindowInsetsSides != Side.all()) {
+ sb.append(System.lineSeparator());
+ sb.append(prefix).append(" fitSides=").append(ViewDebug.flagsToString(
+ LayoutParams.class, "mFitWindowInsetsSides", mFitWindowInsetsSides));
+ }
+ if (mFitIgnoreVisibility) {
+ sb.append(System.lineSeparator());
+ sb.append(prefix).append(" fitIgnoreVis");
+ }
sb.append('}');
return sb.toString();
@@ -3281,7 +3420,6 @@ public interface WindowManager extends ViewManager {
proto.write(HAS_SYSTEM_UI_LISTENERS, hasSystemUiListeners);
proto.write(INPUT_FEATURE_FLAGS, inputFeatures);
proto.write(USER_ACTIVITY_TIMEOUT, userActivityTimeout);
- proto.write(NEEDS_MENU_KEY, needsMenuKey);
proto.write(COLOR_MODE, mColorMode);
proto.write(FLAGS, flags);
proto.write(PRIVATE_FLAGS, privateFlags);
@@ -3289,6 +3427,9 @@ public interface WindowManager extends ViewManager {
proto.write(SUBTREE_SYSTEM_UI_VISIBILITY_FLAGS, subtreeSystemUiVisibility);
proto.write(APPEARANCE, insetsFlags.appearance);
proto.write(BEHAVIOR, insetsFlags.behavior);
+ proto.write(FIT_INSETS_TYPES, mFitWindowInsetsTypes);
+ proto.write(FIT_INSETS_SIDES, mFitWindowInsetsSides);
+ proto.write(FIT_IGNORE_VISIBILITY, mFitIgnoreVisibility);
proto.end(token);
}
diff --git a/core/java/android/view/WindowManagerGlobal.java b/core/java/android/view/WindowManagerGlobal.java
index 55b2a2a4033a..95780023563d 100644
--- a/core/java/android/view/WindowManagerGlobal.java
+++ b/core/java/android/view/WindowManagerGlobal.java
@@ -18,8 +18,8 @@ package android.view;
import android.animation.ValueAnimator;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentCallbacks2;
import android.content.Context;
import android.content.pm.ApplicationInfo;
diff --git a/core/java/android/view/WindowManagerImpl.java b/core/java/android/view/WindowManagerImpl.java
index c3494432ebcb..cdeeaa438acb 100644
--- a/core/java/android/view/WindowManagerImpl.java
+++ b/core/java/android/view/WindowManagerImpl.java
@@ -17,7 +17,7 @@
package android.view;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.graphics.Region;
import android.os.Bundle;
diff --git a/core/java/android/view/accessibility/AccessibilityCache.java b/core/java/android/view/accessibility/AccessibilityCache.java
index dc8bf9b5fbae..9ab2c2b8bcb1 100644
--- a/core/java/android/view/accessibility/AccessibilityCache.java
+++ b/core/java/android/view/accessibility/AccessibilityCache.java
@@ -69,6 +69,8 @@ public class AccessibilityCache {
private long mAccessibilityFocus = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
private long mInputFocus = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
+ private int mAccessibilityFocusedWindow = AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
+
private boolean mIsAllWindowsCached;
// The SparseArray of all {@link AccessibilityWindowInfo}s on all displays.
@@ -164,16 +166,19 @@ public class AccessibilityCache {
switch (eventType) {
case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
if (mAccessibilityFocus != AccessibilityNodeInfo.UNDEFINED_ITEM_ID) {
- refreshCachedNodeLocked(event.getWindowId(), mAccessibilityFocus);
+ refreshCachedNodeLocked(mAccessibilityFocusedWindow, mAccessibilityFocus);
}
mAccessibilityFocus = event.getSourceNodeId();
- refreshCachedNodeLocked(event.getWindowId(), mAccessibilityFocus);
+ mAccessibilityFocusedWindow = event.getWindowId();
+ refreshCachedNodeLocked(mAccessibilityFocusedWindow, mAccessibilityFocus);
} break;
case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
- if (mAccessibilityFocus == event.getSourceNodeId()) {
- refreshCachedNodeLocked(event.getWindowId(), mAccessibilityFocus);
+ if (mAccessibilityFocus == event.getSourceNodeId()
+ && mAccessibilityFocusedWindow == event.getWindowId()) {
+ refreshCachedNodeLocked(mAccessibilityFocusedWindow, mAccessibilityFocus);
mAccessibilityFocus = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
+ mAccessibilityFocusedWindow = AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
}
} break;
@@ -210,6 +215,13 @@ public class AccessibilityCache {
} break;
case AccessibilityEvent.TYPE_WINDOWS_CHANGED:
+ if (event.getWindowChanges()
+ == AccessibilityEvent.WINDOWS_CHANGE_ACCESSIBILITY_FOCUSED) {
+ // Don't need to clear all cache. Unless the changes are related to
+ // content, we won't clear all cache here.
+ refreshCachedWindowLocked(event.getWindowId());
+ break;
+ }
case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED: {
clear();
} break;
@@ -243,6 +255,34 @@ public class AccessibilityCache {
clearSubTreeLocked(windowId, sourceId);
}
+ private void refreshCachedWindowLocked(int windowId) {
+ if (DEBUG) {
+ Log.i(LOG_TAG, "Refreshing cached window.");
+ }
+
+ if (windowId == AccessibilityWindowInfo.UNDEFINED_WINDOW_ID) {
+ return;
+ }
+
+ final int displayCounts = mWindowCacheByDisplay.size();
+ for (int i = 0; i < displayCounts; i++) {
+ final SparseArray<AccessibilityWindowInfo> windowsOfDisplay =
+ mWindowCacheByDisplay.valueAt(i);
+ if (windowsOfDisplay == null) {
+ continue;
+ }
+ final AccessibilityWindowInfo window = windowsOfDisplay.get(windowId);
+ if (window == null) {
+ continue;
+ }
+ if (!mAccessibilityNodeRefresher.refreshWindow(window)) {
+ // If we fail to refresh the window, clear all windows.
+ clearWindowCacheLocked();
+ }
+ return;
+ }
+ }
+
/**
* Gets a cached {@link AccessibilityNodeInfo} given the id of the hosting
* window and the accessibility id of the node.
@@ -413,8 +453,10 @@ public class AccessibilityCache {
refreshCachedNodeLocked(windowId, mAccessibilityFocus);
}
mAccessibilityFocus = sourceId;
+ mAccessibilityFocusedWindow = windowId;
} else if (mAccessibilityFocus == sourceId) {
mAccessibilityFocus = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
+ mAccessibilityFocusedWindow = AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
}
if (clone.isFocused()) {
mInputFocus = sourceId;
@@ -439,6 +481,8 @@ public class AccessibilityCache {
mAccessibilityFocus = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
mInputFocus = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
+
+ mAccessibilityFocusedWindow = AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
}
}
@@ -653,8 +697,14 @@ public class AccessibilityCache {
// Layer of indirection included to break dependency chain for testing
public static class AccessibilityNodeRefresher {
+ /** Refresh the given AccessibilityNodeInfo object. */
public boolean refreshNode(AccessibilityNodeInfo info, boolean bypassCache) {
return info.refresh(null, bypassCache);
}
+
+ /** Refresh the given AccessibilityWindowInfo object. */
+ public boolean refreshWindow(AccessibilityWindowInfo info) {
+ return info.refresh();
+ }
}
}
diff --git a/core/java/android/view/accessibility/AccessibilityEvent.java b/core/java/android/view/accessibility/AccessibilityEvent.java
index 34654edd00e8..3b8368380dda 100644
--- a/core/java/android/view/accessibility/AccessibilityEvent.java
+++ b/core/java/android/view/accessibility/AccessibilityEvent.java
@@ -18,7 +18,7 @@ package android.view.accessibility;
import android.annotation.IntDef;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/view/accessibility/AccessibilityInteractionClient.java b/core/java/android/view/accessibility/AccessibilityInteractionClient.java
index bb10ef10d79e..914ff1871d69 100644
--- a/core/java/android/view/accessibility/AccessibilityInteractionClient.java
+++ b/core/java/android/view/accessibility/AccessibilityInteractionClient.java
@@ -17,7 +17,7 @@
package android.view.accessibility;
import android.accessibilityservice.IAccessibilityServiceConnection;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
@@ -223,19 +223,36 @@ public final class AccessibilityInteractionClient
* @return The {@link AccessibilityWindowInfo}.
*/
public AccessibilityWindowInfo getWindow(int connectionId, int accessibilityWindowId) {
+ return getWindow(connectionId, accessibilityWindowId, /* bypassCache */ false);
+ }
+
+ /**
+ * Gets the info for a window.
+ *
+ * @param connectionId The id of a connection for interacting with the system.
+ * @param accessibilityWindowId A unique window id. Use
+ * {@link android.view.accessibility.AccessibilityWindowInfo#ACTIVE_WINDOW_ID}
+ * to query the currently active window.
+ * @param bypassCache Whether to bypass the cache.
+ * @return The {@link AccessibilityWindowInfo}.
+ */
+ public AccessibilityWindowInfo getWindow(int connectionId, int accessibilityWindowId,
+ boolean bypassCache) {
try {
IAccessibilityServiceConnection connection = getConnection(connectionId);
if (connection != null) {
- AccessibilityWindowInfo window = sAccessibilityCache.getWindow(
- accessibilityWindowId);
- if (window != null) {
+ AccessibilityWindowInfo window;
+ if (!bypassCache) {
+ window = sAccessibilityCache.getWindow(accessibilityWindowId);
+ if (window != null) {
+ if (DEBUG) {
+ Log.i(LOG_TAG, "Window cache hit");
+ }
+ return window;
+ }
if (DEBUG) {
- Log.i(LOG_TAG, "Window cache hit");
+ Log.i(LOG_TAG, "Window cache miss");
}
- return window;
- }
- if (DEBUG) {
- Log.i(LOG_TAG, "Window cache miss");
}
final long identityToken = Binder.clearCallingIdentity();
try {
@@ -244,7 +261,9 @@ public final class AccessibilityInteractionClient
Binder.restoreCallingIdentity(identityToken);
}
if (window != null) {
- sAccessibilityCache.addWindow(window);
+ if (!bypassCache) {
+ sAccessibilityCache.addWindow(window);
+ }
return window;
}
} else {
diff --git a/core/java/android/view/accessibility/AccessibilityManager.java b/core/java/android/view/accessibility/AccessibilityManager.java
index cc2884075c39..ff31bccfa648 100644
--- a/core/java/android/view/accessibility/AccessibilityManager.java
+++ b/core/java/android/view/accessibility/AccessibilityManager.java
@@ -30,8 +30,8 @@ import android.annotation.SdkConstant;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.UserIdInt;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
@@ -117,7 +117,7 @@ public final class AccessibilityManager {
* Activity action: Launch UI to manage which accessibility service or feature is assigned
* to the navigation bar Accessibility button.
* <p>
- * Input: Nothing.
+ * Input: {@link #EXTRA_SHORTCUT_TYPE} is the shortcut type.
* </p>
* <p>
* Output: Nothing.
@@ -130,6 +130,42 @@ public final class AccessibilityManager {
"com.android.internal.intent.action.CHOOSE_ACCESSIBILITY_BUTTON";
/**
+ * Used as an int extra field in {@link #ACTION_CHOOSE_ACCESSIBILITY_BUTTON} intent to specify
+ * the shortcut type.
+ *
+ * @hide
+ */
+ public static final String EXTRA_SHORTCUT_TYPE =
+ "com.android.internal.intent.extra.SHORTCUT_TYPE";
+
+ /**
+ * Used as an int value for {@link #EXTRA_SHORTCUT_TYPE} to represent the accessibility button
+ * shortcut type.
+ *
+ * @hide
+ */
+ public static final int ACCESSIBILITY_BUTTON = 0;
+
+ /**
+ * Used as an int value for {@link #EXTRA_SHORTCUT_TYPE} to represent hardware key shortcut,
+ * such as volume key button.
+ *
+ * @hide
+ */
+ public static final int ACCESSIBILITY_SHORTCUT_KEY = 1;
+
+ /**
+ * Annotations for the shortcut type.
+ * @hide
+ */
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(value = {
+ ACCESSIBILITY_BUTTON,
+ ACCESSIBILITY_SHORTCUT_KEY
+ })
+ public @interface ShortcutType {}
+
+ /**
* Annotations for content flag of UI.
* @hide
*/
@@ -1242,27 +1278,28 @@ public final class AccessibilityManager {
}
/**
- * Get the component name of the service currently assigned to the accessibility shortcut.
+ * Returns the list of shortcut target names currently assigned to the given shortcut.
*
- * @return The flattened component name
+ * @param shortcutType The shortcut type.
+ * @return The list of shortcut target names.
* @hide
*/
@TestApi
@RequiresPermission(Manifest.permission.MANAGE_ACCESSIBILITY)
- @Nullable
- public String getAccessibilityShortcutService() {
+ @NonNull
+ public List<String> getAccessibilityShortcutTargets(@ShortcutType int shortcutType) {
final IAccessibilityManager service;
synchronized (mLock) {
service = getServiceLocked();
}
if (service != null) {
try {
- return service.getAccessibilityShortcutService();
+ return service.getAccessibilityShortcutTargets(shortcutType);
} catch (RemoteException re) {
re.rethrowFromSystemServer();
}
}
- return null;
+ return Collections.emptyList();
}
/**
diff --git a/core/java/android/view/accessibility/AccessibilityNodeInfo.java b/core/java/android/view/accessibility/AccessibilityNodeInfo.java
index f2f84cdc631c..92aa7d523da0 100644
--- a/core/java/android/view/accessibility/AccessibilityNodeInfo.java
+++ b/core/java/android/view/accessibility/AccessibilityNodeInfo.java
@@ -26,7 +26,7 @@ import android.accessibilityservice.AccessibilityServiceInfo;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.Rect;
import android.graphics.Region;
import android.os.Build;
diff --git a/core/java/android/view/accessibility/AccessibilityRecord.java b/core/java/android/view/accessibility/AccessibilityRecord.java
index 4f6c9ef55220..c3a4d3206462 100644
--- a/core/java/android/view/accessibility/AccessibilityRecord.java
+++ b/core/java/android/view/accessibility/AccessibilityRecord.java
@@ -20,7 +20,7 @@ import static com.android.internal.util.CollectionUtils.isEmpty;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcelable;
import android.view.View;
diff --git a/core/java/android/view/accessibility/AccessibilityWindowInfo.java b/core/java/android/view/accessibility/AccessibilityWindowInfo.java
index 2cc6e9aebd74..ca5c417bdc6d 100644
--- a/core/java/android/view/accessibility/AccessibilityWindowInfo.java
+++ b/core/java/android/view/accessibility/AccessibilityWindowInfo.java
@@ -87,6 +87,8 @@ public final class AccessibilityWindowInfo implements Parcelable {
/** @hide */
public static final int ACTIVE_WINDOW_ID = Integer.MAX_VALUE;
/** @hide */
+ public static final int UNDEFINED_CONNECTION_ID = -1;
+ /** @hide */
public static final int UNDEFINED_WINDOW_ID = -1;
/** @hide */
public static final int ANY_WINDOW_ID = -2;
@@ -117,7 +119,7 @@ public final class AccessibilityWindowInfo implements Parcelable {
private CharSequence mTitle;
private long mAnchorId = AccessibilityNodeInfo.UNDEFINED_NODE_ID;
- private int mConnectionId = UNDEFINED_WINDOW_ID;
+ private int mConnectionId = UNDEFINED_CONNECTION_ID;
/**
* Creates a new {@link AccessibilityWindowInfo}.
@@ -539,6 +541,30 @@ public final class AccessibilityWindowInfo implements Parcelable {
}
}
+ /**
+ * Refreshes this window with the latest state of the window it represents.
+ * <p>
+ * <strong>Note:</strong> If this method returns false this info is obsolete
+ * since it represents a window that is no longer exist.
+ * </p>
+ *
+ * @hide
+ */
+ public boolean refresh() {
+ if (mConnectionId == UNDEFINED_CONNECTION_ID || mId == UNDEFINED_WINDOW_ID) {
+ return false;
+ }
+ final AccessibilityInteractionClient client = AccessibilityInteractionClient.getInstance();
+ final AccessibilityWindowInfo refreshedInfo = client.getWindow(mConnectionId,
+ mId, /* bypassCache */true);
+ if (refreshedInfo == null) {
+ return false;
+ }
+ init(refreshedInfo);
+ refreshedInfo.recycle();
+ return true;
+ }
+
@Override
public int describeContents() {
return 0;
@@ -586,6 +612,7 @@ public final class AccessibilityWindowInfo implements Parcelable {
mTitle = other.mTitle;
mAnchorId = other.mAnchorId;
+ if (mChildIds != null) mChildIds.clear();
if (other.mChildIds != null && other.mChildIds.size() > 0) {
if (mChildIds == null) {
mChildIds = other.mChildIds.clone();
diff --git a/core/java/android/view/accessibility/CaptioningManager.java b/core/java/android/view/accessibility/CaptioningManager.java
index c42e9fec91bf..3d68692a3b5c 100644
--- a/core/java/android/view/accessibility/CaptioningManager.java
+++ b/core/java/android/view/accessibility/CaptioningManager.java
@@ -19,7 +19,7 @@ package android.view.accessibility;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
diff --git a/core/java/android/view/accessibility/IAccessibilityManager.aidl b/core/java/android/view/accessibility/IAccessibilityManager.aidl
index 023fda52a1b1..36515b3ba094 100644
--- a/core/java/android/view/accessibility/IAccessibilityManager.aidl
+++ b/core/java/android/view/accessibility/IAccessibilityManager.aidl
@@ -73,7 +73,7 @@ interface IAccessibilityManager {
void performAccessibilityShortcut();
// Requires Manifest.permission.MANAGE_ACCESSIBILITY
- String getAccessibilityShortcutService();
+ List<String> getAccessibilityShortcutTargets(int shortcutType);
// System process only
boolean sendFingerprintGesture(int gestureKeyCode);
diff --git a/core/java/android/view/animation/Animation.java b/core/java/android/view/animation/Animation.java
index b03732a2a7f0..b1d618eff40a 100644
--- a/core/java/android/view/animation/Animation.java
+++ b/core/java/android/view/animation/Animation.java
@@ -19,7 +19,7 @@ package android.view.animation;
import android.annotation.AnimRes;
import android.annotation.ColorInt;
import android.annotation.InterpolatorRes;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.RectF;
diff --git a/core/java/android/view/animation/AnimationUtils.java b/core/java/android/view/animation/AnimationUtils.java
index f5b074674454..7ce0f4571f76 100644
--- a/core/java/android/view/animation/AnimationUtils.java
+++ b/core/java/android/view/animation/AnimationUtils.java
@@ -19,7 +19,7 @@ package android.view.animation;
import android.annotation.AnimRes;
import android.annotation.InterpolatorRes;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.Resources.NotFoundException;
diff --git a/core/java/android/view/animation/Transformation.java b/core/java/android/view/animation/Transformation.java
index 58da04d8d38f..cfc6e39da876 100644
--- a/core/java/android/view/animation/Transformation.java
+++ b/core/java/android/view/animation/Transformation.java
@@ -17,7 +17,7 @@
package android.view.animation;
import android.annotation.FloatRange;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.Matrix;
import android.graphics.Rect;
diff --git a/core/java/android/view/animation/TranslateAnimation.java b/core/java/android/view/animation/TranslateAnimation.java
index 6c040d4c61aa..ec55a0273999 100644
--- a/core/java/android/view/animation/TranslateAnimation.java
+++ b/core/java/android/view/animation/TranslateAnimation.java
@@ -16,7 +16,7 @@
package android.view.animation;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
diff --git a/core/java/android/view/animation/TranslateYAnimation.java b/core/java/android/view/animation/TranslateYAnimation.java
index a6e0ccb18805..1a1dfbfd6f05 100644
--- a/core/java/android/view/animation/TranslateYAnimation.java
+++ b/core/java/android/view/animation/TranslateYAnimation.java
@@ -16,7 +16,7 @@
package android.view.animation;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.Matrix;
/**
diff --git a/core/java/android/view/inline/InlineContentView.java b/core/java/android/view/inline/InlineContentView.java
index 4bc2176e8279..b143fad778ec 100644
--- a/core/java/android/view/inline/InlineContentView.java
+++ b/core/java/android/view/inline/InlineContentView.java
@@ -50,7 +50,10 @@ public class InlineContentView extends SurfaceView {
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
- // TODO(b/137800469): implement this.
+ new SurfaceControl.Transaction()
+ .setVisibility(surfaceControl, false)
+ .reparent(surfaceControl, null)
+ .apply();
}
});
}
diff --git a/core/java/android/view/inputmethod/InlineSuggestion.java b/core/java/android/view/inputmethod/InlineSuggestion.java
index 25e34d36aa9a..c10144e6ee25 100644
--- a/core/java/android/view/inputmethod/InlineSuggestion.java
+++ b/core/java/android/view/inputmethod/InlineSuggestion.java
@@ -271,7 +271,7 @@ public final class InlineSuggestion implements Parcelable {
};
@DataClass.Generated(
- time = 1574446220398L,
+ time = 1575933636929L,
codegenVersion = "1.0.14",
sourceFile = "frameworks/base/core/java/android/view/inputmethod/InlineSuggestion.java",
inputSignatures = "private static final java.lang.String TAG\nprivate final @android.annotation.NonNull android.view.inputmethod.InlineSuggestionInfo mInfo\nprivate final @android.annotation.Nullable com.android.internal.view.inline.IInlineContentProvider mContentProvider\npublic void inflate(android.content.Context,android.util.Size,java.util.concurrent.Executor,java.util.function.Consumer<android.view.View>)\nclass InlineSuggestion extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genEqualsHashCode=true, genToString=true, genHiddenConstDefs=true, genHiddenConstructor=true)")
diff --git a/core/java/android/view/inputmethod/InputMethod.java b/core/java/android/view/inputmethod/InputMethod.java
index 112653aa34e3..1e5a3b027609 100644
--- a/core/java/android/view/inputmethod/InputMethod.java
+++ b/core/java/android/view/inputmethod/InputMethod.java
@@ -21,11 +21,16 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
+import android.content.ComponentName;
import android.inputmethodservice.InputMethodService;
import android.os.IBinder;
+import android.os.RemoteException;
import android.os.ResultReceiver;
+import android.util.Log;
+import android.view.autofill.AutofillId;
import com.android.internal.inputmethod.IInputMethodPrivilegedOperations;
+import com.android.internal.view.IInlineSuggestionsRequestCallback;
/**
* The InputMethod interface represents an input method which can generate key
@@ -104,6 +109,20 @@ public interface InputMethod {
}
/**
+ * Called to notify the IME that Autofill Frameworks requested an inline suggestions request.
+ *
+ * @hide
+ */
+ default void onCreateInlineSuggestionsRequest(ComponentName componentName,
+ AutofillId autofillId, IInlineSuggestionsRequestCallback cb) {
+ try {
+ cb.onInlineSuggestionsUnsupported();
+ } catch (RemoteException e) {
+ Log.w("InputMethod", "RemoteException calling onInlineSuggestionsUnsupported: " + e);
+ }
+ }
+
+ /**
* Called first thing after an input method is created, this supplies a
* unique token for the session it has with the system service. It is
* needed to identify itself with the service to validate its operations.
diff --git a/core/java/android/view/inputmethod/InputMethodInfo.java b/core/java/android/view/inputmethod/InputMethodInfo.java
index fe07feef3bfa..34005ac02735 100644
--- a/core/java/android/view/inputmethod/InputMethodInfo.java
+++ b/core/java/android/view/inputmethod/InputMethodInfo.java
@@ -17,7 +17,7 @@
package android.view.inputmethod;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
diff --git a/core/java/android/view/inputmethod/InputMethodManager.java b/core/java/android/view/inputmethod/InputMethodManager.java
index 2650a67652a5..67ce8d2e49b5 100644
--- a/core/java/android/view/inputmethod/InputMethodManager.java
+++ b/core/java/android/view/inputmethod/InputMethodManager.java
@@ -26,9 +26,9 @@ import android.annotation.RequiresFeature;
import android.annotation.RequiresPermission;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.UserIdInt;
import android.app.ActivityThread;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
@@ -2863,7 +2863,7 @@ public final class InputMethodManager {
}
/**
- * This is kept due to {@link android.annotation.UnsupportedAppUsage}.
+ * This is kept due to {@link android.compat.annotation.UnsupportedAppUsage}.
*
* <p>TODO(Bug 113914148): Check if we can remove this. We have accidentally exposed
* WindowManagerInternal#getInputMethodWindowVisibleHeight to app developers and some of them
diff --git a/core/java/android/view/inputmethod/InputMethodSubtypeArray.java b/core/java/android/view/inputmethod/InputMethodSubtypeArray.java
index 8dd0dcd45a1c..50e95c80cfed 100644
--- a/core/java/android/view/inputmethod/InputMethodSubtypeArray.java
+++ b/core/java/android/view/inputmethod/InputMethodSubtypeArray.java
@@ -16,7 +16,7 @@
package android.view.inputmethod;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.util.Slog;
diff --git a/core/java/android/view/textclassifier/ConfigParser.java b/core/java/android/view/textclassifier/ConfigParser.java
deleted file mode 100644
index 9b51458d27d9..000000000000
--- a/core/java/android/view/textclassifier/ConfigParser.java
+++ /dev/null
@@ -1,264 +0,0 @@
-/*
- * Copyright (C) 2019 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.view.textclassifier;
-
-import android.annotation.Nullable;
-import android.provider.DeviceConfig;
-import android.util.ArrayMap;
-import android.util.KeyValueListParser;
-
-import com.android.internal.annotations.GuardedBy;
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.annotations.VisibleForTesting.Visibility;
-import com.android.internal.util.Preconditions;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Supplier;
-
-/**
- * Retrieves settings from {@link DeviceConfig} and {@link android.provider.Settings}.
- * It will try DeviceConfig first and then Settings.
- *
- * @hide
- */
-@VisibleForTesting(visibility = Visibility.PACKAGE)
-public final class ConfigParser {
- private static final String TAG = "ConfigParser";
-
- public static final boolean ENABLE_DEVICE_CONFIG = true;
-
- private static final String STRING_LIST_DELIMITER = ":";
-
- private final Supplier<String> mLegacySettingsSupplier;
- private final Object mLock = new Object();
- @GuardedBy("mLock")
- private final Map<String, Object> mCache = new ArrayMap<>();
- @GuardedBy("mLock")
- private @Nullable KeyValueListParser mSettingsParser; // Call getLegacySettings() instead.
-
- public ConfigParser(Supplier<String> legacySettingsSupplier) {
- mLegacySettingsSupplier = Preconditions.checkNotNull(legacySettingsSupplier);
- }
-
- private KeyValueListParser getLegacySettings() {
- synchronized (mLock) {
- if (mSettingsParser == null) {
- final String legacySettings = mLegacySettingsSupplier.get();
- try {
- mSettingsParser = new KeyValueListParser(',');
- mSettingsParser.setString(legacySettings);
- } catch (IllegalArgumentException e) {
- // Failed to parse the settings string, log this and move on with defaults.
- Log.w(TAG, "Bad text_classifier_constants: " + legacySettings);
- }
- }
- return mSettingsParser;
- }
- }
-
- /**
- * Reads a boolean setting through the cache.
- */
- public boolean getBoolean(String key, boolean defaultValue) {
- synchronized (mLock) {
- final Object cached = mCache.get(key);
- if (cached instanceof Boolean) {
- return (boolean) cached;
- }
- final boolean value;
- if (ENABLE_DEVICE_CONFIG) {
- value = DeviceConfig.getBoolean(
- DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- key,
- getLegacySettings().getBoolean(key, defaultValue));
- } else {
- value = getLegacySettings().getBoolean(key, defaultValue);
- }
- mCache.put(key, value);
- return value;
- }
- }
-
- /**
- * Reads an integer setting through the cache.
- */
- public int getInt(String key, int defaultValue) {
- synchronized (mLock) {
- final Object cached = mCache.get(key);
- if (cached instanceof Integer) {
- return (int) cached;
- }
- final int value;
- if (ENABLE_DEVICE_CONFIG) {
- value = DeviceConfig.getInt(
- DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- key,
- getLegacySettings().getInt(key, defaultValue));
- } else {
- value = getLegacySettings().getInt(key, defaultValue);
- }
- mCache.put(key, value);
- return value;
- }
- }
-
- /**
- * Reads a float setting through the cache.
- */
- public float getFloat(String key, float defaultValue) {
- synchronized (mLock) {
- final Object cached = mCache.get(key);
- if (cached instanceof Float) {
- return (float) cached;
- }
- final float value;
- if (ENABLE_DEVICE_CONFIG) {
- value = DeviceConfig.getFloat(
- DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- key,
- getLegacySettings().getFloat(key, defaultValue));
- } else {
- value = getLegacySettings().getFloat(key, defaultValue);
- }
- mCache.put(key, value);
- return value;
- }
- }
-
- /**
- * Reads a string setting through the cache.
- */
- public String getString(String key, String defaultValue) {
- synchronized (mLock) {
- final Object cached = mCache.get(key);
- if (cached instanceof String) {
- return (String) cached;
- }
- final String value;
- if (ENABLE_DEVICE_CONFIG) {
- value = DeviceConfig.getString(
- DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- key,
- getLegacySettings().getString(key, defaultValue));
- } else {
- value = getLegacySettings().getString(key, defaultValue);
- }
- mCache.put(key, value);
- return value;
- }
- }
-
- /**
- * Reads a string list setting through the cache.
- */
- public List<String> getStringList(String key, List<String> defaultValue) {
- synchronized (mLock) {
- final Object cached = mCache.get(key);
- if (cached instanceof List) {
- final List asList = (List) cached;
- if (asList.isEmpty()) {
- return Collections.emptyList();
- } else if (asList.get(0) instanceof String) {
- return (List<String>) cached;
- }
- }
- final List<String> value;
- if (ENABLE_DEVICE_CONFIG) {
- value = getDeviceConfigStringList(
- key,
- getSettingsStringList(key, defaultValue));
- } else {
- value = getSettingsStringList(key, defaultValue);
- }
- mCache.put(key, value);
- return value;
- }
- }
-
- /**
- * Reads a float array through the cache. The returned array should be expected to be of the
- * same length as that of the defaultValue.
- */
- public float[] getFloatArray(String key, float[] defaultValue) {
- synchronized (mLock) {
- final Object cached = mCache.get(key);
- if (cached instanceof float[]) {
- return (float[]) cached;
- }
- final float[] value;
- if (ENABLE_DEVICE_CONFIG) {
- value = getDeviceConfigFloatArray(
- key,
- getSettingsFloatArray(key, defaultValue));
- } else {
- value = getSettingsFloatArray(key, defaultValue);
- }
- mCache.put(key, value);
- return value;
- }
- }
-
- private List<String> getSettingsStringList(String key, List<String> defaultValue) {
- return parse(mSettingsParser.getString(key, null), defaultValue);
- }
-
- private static List<String> getDeviceConfigStringList(String key, List<String> defaultValue) {
- return parse(
- DeviceConfig.getString(DeviceConfig.NAMESPACE_TEXTCLASSIFIER, key, null),
- defaultValue);
- }
-
- private static float[] getDeviceConfigFloatArray(String key, float[] defaultValue) {
- return parse(
- DeviceConfig.getString(DeviceConfig.NAMESPACE_TEXTCLASSIFIER, key, null),
- defaultValue);
- }
-
- private float[] getSettingsFloatArray(String key, float[] defaultValue) {
- return parse(mSettingsParser.getString(key, null), defaultValue);
- }
-
- private static List<String> parse(@Nullable String listStr, List<String> defaultValue) {
- if (listStr != null) {
- return Collections.unmodifiableList(
- Arrays.asList(listStr.split(STRING_LIST_DELIMITER)));
- }
- return defaultValue;
- }
-
- private static float[] parse(@Nullable String arrayStr, float[] defaultValue) {
- if (arrayStr != null) {
- final String[] split = arrayStr.split(STRING_LIST_DELIMITER);
- if (split.length != defaultValue.length) {
- return defaultValue;
- }
- final float[] result = new float[split.length];
- for (int i = 0; i < split.length; i++) {
- try {
- result[i] = Float.parseFloat(split[i]);
- } catch (NumberFormatException e) {
- return defaultValue;
- }
- }
- return result;
- } else {
- return defaultValue;
- }
- }
-}
diff --git a/core/java/android/view/textclassifier/ConversationAction.java b/core/java/android/view/textclassifier/ConversationAction.java
index 6070b5341cf9..e633404fd7d8 100644
--- a/core/java/android/view/textclassifier/ConversationAction.java
+++ b/core/java/android/view/textclassifier/ConversationAction.java
@@ -26,9 +26,8 @@ import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
-import com.android.internal.util.Preconditions;
-
import java.lang.annotation.Retention;
+import java.util.Objects;
/** Represents the action suggested by a {@link TextClassifier} on a given conversation. */
public final class ConversationAction implements Parcelable {
@@ -133,11 +132,11 @@ public final class ConversationAction implements Parcelable {
@Nullable CharSequence textReply,
float score,
@NonNull Bundle extras) {
- mType = Preconditions.checkNotNull(type);
+ mType = Objects.requireNonNull(type);
mAction = action;
mTextReply = textReply;
mScore = score;
- mExtras = Preconditions.checkNotNull(extras);
+ mExtras = Objects.requireNonNull(extras);
}
private ConversationAction(Parcel in) {
@@ -221,7 +220,7 @@ public final class ConversationAction implements Parcelable {
private Bundle mExtras;
public Builder(@NonNull @ActionType String actionType) {
- mType = Preconditions.checkNotNull(actionType);
+ mType = Objects.requireNonNull(actionType);
}
/**
diff --git a/core/java/android/view/textclassifier/ConversationActions.java b/core/java/android/view/textclassifier/ConversationActions.java
index f7f503ab60ec..80027b1ed75d 100644
--- a/core/java/android/view/textclassifier/ConversationActions.java
+++ b/core/java/android/view/textclassifier/ConversationActions.java
@@ -38,6 +38,7 @@ import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import java.util.Objects;
/**
* Represents a list of actions suggested by a {@link TextClassifier} on a given conversation.
@@ -66,7 +67,7 @@ public final class ConversationActions implements Parcelable {
public ConversationActions(
@NonNull List<ConversationAction> conversationActions, @Nullable String id) {
mConversationActions =
- Collections.unmodifiableList(Preconditions.checkNotNull(conversationActions));
+ Collections.unmodifiableList(Objects.requireNonNull(conversationActions));
mId = id;
}
@@ -149,7 +150,7 @@ public final class ConversationActions implements Parcelable {
mAuthor = author;
mReferenceTime = referenceTime;
mText = text;
- mExtras = Preconditions.checkNotNull(bundle);
+ mExtras = Objects.requireNonNull(bundle);
}
private Message(Parcel in) {
@@ -243,7 +244,7 @@ public final class ConversationActions implements Parcelable {
* {@link #PERSON_USER_OTHERS} to represent a remote user.
*/
public Builder(@NonNull Person author) {
- mAuthor = Preconditions.checkNotNull(author);
+ mAuthor = Objects.requireNonNull(author);
}
/** Sets the text of this message. */
@@ -329,8 +330,8 @@ public final class ConversationActions implements Parcelable {
int maxSuggestions,
@Nullable @Hint List<String> hints,
@NonNull Bundle extras) {
- mConversation = Preconditions.checkNotNull(conversation);
- mTypeConfig = Preconditions.checkNotNull(typeConfig);
+ mConversation = Objects.requireNonNull(conversation);
+ mTypeConfig = Objects.requireNonNull(typeConfig);
mMaxSuggestions = maxSuggestions;
mHints = hints;
mExtras = extras;
@@ -483,7 +484,7 @@ public final class ConversationActions implements Parcelable {
* actions for.
*/
public Builder(@NonNull List<Message> conversation) {
- mConversation = Preconditions.checkNotNull(conversation);
+ mConversation = Objects.requireNonNull(conversation);
}
/**
diff --git a/core/java/android/view/textclassifier/EntityConfidence.java b/core/java/android/view/textclassifier/EntityConfidence.java
index 3c51c38952f0..4c12dda0109a 100644
--- a/core/java/android/view/textclassifier/EntityConfidence.java
+++ b/core/java/android/view/textclassifier/EntityConfidence.java
@@ -22,12 +22,11 @@ import android.os.Parcel;
import android.os.Parcelable;
import android.util.ArrayMap;
-import com.android.internal.util.Preconditions;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
/**
* Helper object for setting and getting entity scores for classified text.
@@ -42,7 +41,7 @@ final class EntityConfidence implements Parcelable {
EntityConfidence() {}
EntityConfidence(@NonNull EntityConfidence source) {
- Preconditions.checkNotNull(source);
+ Objects.requireNonNull(source);
mEntityConfidence.putAll(source.mEntityConfidence);
mSortedEntities.addAll(source.mSortedEntities);
}
@@ -56,7 +55,7 @@ final class EntityConfidence implements Parcelable {
* 1 (high confidence).
*/
EntityConfidence(@NonNull Map<String, Float> source) {
- Preconditions.checkNotNull(source);
+ Objects.requireNonNull(source);
// Prune non-existent entities and clamp to 1.
mEntityConfidence.ensureCapacity(source.size());
diff --git a/core/java/android/view/textclassifier/GenerateLinksLogger.java b/core/java/android/view/textclassifier/GenerateLinksLogger.java
index 3996b277aa1c..17ec73ad395f 100644
--- a/core/java/android/view/textclassifier/GenerateLinksLogger.java
+++ b/core/java/android/view/textclassifier/GenerateLinksLogger.java
@@ -23,7 +23,6 @@ import android.util.ArrayMap;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.logging.MetricsLogger;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.internal.util.Preconditions;
import java.util.Locale;
import java.util.Map;
@@ -66,9 +65,9 @@ public final class GenerateLinksLogger {
/** Logs statistics about a call to generateLinks. */
public void logGenerateLinks(CharSequence text, TextLinks links, String callingPackageName,
long latencyMs) {
- Preconditions.checkNotNull(text);
- Preconditions.checkNotNull(links);
- Preconditions.checkNotNull(callingPackageName);
+ Objects.requireNonNull(text);
+ Objects.requireNonNull(links);
+ Objects.requireNonNull(callingPackageName);
if (!shouldLog()) {
return;
}
diff --git a/core/java/android/view/textclassifier/ModelFileManager.java b/core/java/android/view/textclassifier/ModelFileManager.java
index e04285db75be..0a4ff5d559ab 100644
--- a/core/java/android/view/textclassifier/ModelFileManager.java
+++ b/core/java/android/view/textclassifier/ModelFileManager.java
@@ -23,7 +23,6 @@ import android.os.ParcelFileDescriptor;
import android.text.TextUtils;
import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.util.Preconditions;
import java.io.File;
import java.io.FileNotFoundException;
@@ -51,7 +50,7 @@ public final class ModelFileManager {
private List<ModelFile> mModelFiles;
public ModelFileManager(Supplier<List<ModelFile>> modelFileSupplier) {
- mModelFileSupplier = Preconditions.checkNotNull(modelFileSupplier);
+ mModelFileSupplier = Objects.requireNonNull(modelFileSupplier);
}
/**
@@ -106,12 +105,12 @@ public final class ModelFileManager {
File updatedModelFile,
Function<Integer, Integer> versionSupplier,
Function<Integer, String> supportedLocalesSupplier) {
- mUpdatedModelFile = Preconditions.checkNotNull(updatedModelFile);
- mFactoryModelDir = Preconditions.checkNotNull(factoryModelDir);
+ mUpdatedModelFile = Objects.requireNonNull(updatedModelFile);
+ mFactoryModelDir = Objects.requireNonNull(factoryModelDir);
mModelFilenamePattern = Pattern.compile(
- Preconditions.checkNotNull(factoryModelFileNameRegex));
- mVersionSupplier = Preconditions.checkNotNull(versionSupplier);
- mSupportedLocalesSupplier = Preconditions.checkNotNull(supportedLocalesSupplier);
+ Objects.requireNonNull(factoryModelFileNameRegex));
+ mVersionSupplier = Objects.requireNonNull(versionSupplier);
+ mSupportedLocalesSupplier = Objects.requireNonNull(supportedLocalesSupplier);
}
@Override
@@ -208,10 +207,10 @@ public final class ModelFileManager {
public ModelFile(File file, int version, List<Locale> supportedLocales,
String supportedLocalesStr,
boolean languageIndependent) {
- mFile = Preconditions.checkNotNull(file);
+ mFile = Objects.requireNonNull(file);
mVersion = version;
- mSupportedLocales = Preconditions.checkNotNull(supportedLocales);
- mSupportedLocalesStr = Preconditions.checkNotNull(supportedLocalesStr);
+ mSupportedLocales = Objects.requireNonNull(supportedLocales);
+ mSupportedLocalesStr = Objects.requireNonNull(supportedLocalesStr);
mLanguageIndependent = languageIndependent;
}
@@ -232,7 +231,7 @@ public final class ModelFileManager {
/** Returns whether the language supports any language in the given ranges. */
public boolean isAnyLanguageSupported(List<Locale.LanguageRange> languageRanges) {
- Preconditions.checkNotNull(languageRanges);
+ Objects.requireNonNull(languageRanges);
return mLanguageIndependent || Locale.lookup(languageRanges, mSupportedLocales) != null;
}
diff --git a/core/java/android/view/textclassifier/SelectionEvent.java b/core/java/android/view/textclassifier/SelectionEvent.java
index 12ed4b971e83..09cb7a07faa8 100644
--- a/core/java/android/view/textclassifier/SelectionEvent.java
+++ b/core/java/android/view/textclassifier/SelectionEvent.java
@@ -149,7 +149,7 @@ public final class SelectionEvent implements Parcelable {
mAbsoluteStart = start;
mAbsoluteEnd = end;
mEventType = eventType;
- mEntityType = Preconditions.checkNotNull(entityType);
+ mEntityType = Objects.requireNonNull(entityType);
mResultId = resultId;
mInvocationMethod = invocationMethod;
}
@@ -161,7 +161,6 @@ public final class SelectionEvent implements Parcelable {
mEntityType = in.readString();
mWidgetVersion = in.readInt() > 0 ? in.readString() : null;
mPackageName = in.readString();
- mUserId = in.readInt();
mWidgetType = in.readString();
mInvocationMethod = in.readInt();
mResultId = in.readString();
@@ -175,6 +174,7 @@ public final class SelectionEvent implements Parcelable {
mEnd = in.readInt();
mSmartStart = in.readInt();
mSmartEnd = in.readInt();
+ mUserId = in.readInt();
}
@Override
@@ -188,7 +188,6 @@ public final class SelectionEvent implements Parcelable {
dest.writeString(mWidgetVersion);
}
dest.writeString(mPackageName);
- dest.writeInt(mUserId);
dest.writeString(mWidgetType);
dest.writeInt(mInvocationMethod);
dest.writeString(mResultId);
@@ -204,6 +203,7 @@ public final class SelectionEvent implements Parcelable {
dest.writeInt(mEnd);
dest.writeInt(mSmartStart);
dest.writeInt(mSmartEnd);
+ dest.writeInt(mUserId);
}
@Override
@@ -257,7 +257,7 @@ public final class SelectionEvent implements Parcelable {
public static SelectionEvent createSelectionModifiedEvent(
int start, int end, @NonNull TextClassification classification) {
Preconditions.checkArgument(end >= start, "end cannot be less than start");
- Preconditions.checkNotNull(classification);
+ Objects.requireNonNull(classification);
final String entityType = classification.getEntityCount() > 0
? classification.getEntity(0)
: TextClassifier.TYPE_UNKNOWN;
@@ -281,7 +281,7 @@ public final class SelectionEvent implements Parcelable {
public static SelectionEvent createSelectionModifiedEvent(
int start, int end, @NonNull TextSelection selection) {
Preconditions.checkArgument(end >= start, "end cannot be less than start");
- Preconditions.checkNotNull(selection);
+ Objects.requireNonNull(selection);
final String entityType = selection.getEntityCount() > 0
? selection.getEntity(0)
: TextClassifier.TYPE_UNKNOWN;
@@ -329,7 +329,7 @@ public final class SelectionEvent implements Parcelable {
int start, int end, @SelectionEvent.ActionType int actionType,
@NonNull TextClassification classification) {
Preconditions.checkArgument(end >= start, "end cannot be less than start");
- Preconditions.checkNotNull(classification);
+ Objects.requireNonNull(classification);
checkActionType(actionType);
final String entityType = classification.getEntityCount() > 0
? classification.getEntity(0)
@@ -398,7 +398,7 @@ public final class SelectionEvent implements Parcelable {
}
void setEntityType(@EntityType String entityType) {
- mEntityType = Preconditions.checkNotNull(entityType);
+ mEntityType = Objects.requireNonNull(entityType);
}
/**
diff --git a/core/java/android/view/textclassifier/SelectionSessionLogger.java b/core/java/android/view/textclassifier/SelectionSessionLogger.java
index 20cc94433872..9c9b2d0f1ce2 100644
--- a/core/java/android/view/textclassifier/SelectionSessionLogger.java
+++ b/core/java/android/view/textclassifier/SelectionSessionLogger.java
@@ -24,7 +24,6 @@ import android.metrics.LogMaker;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.logging.MetricsLogger;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.internal.util.Preconditions;
import java.text.BreakIterator;
import java.util.List;
@@ -65,12 +64,12 @@ public final class SelectionSessionLogger {
@VisibleForTesting
public SelectionSessionLogger(@NonNull MetricsLogger metricsLogger) {
- mMetricsLogger = Preconditions.checkNotNull(metricsLogger);
+ mMetricsLogger = Objects.requireNonNull(metricsLogger);
}
/** Emits a selection event to the logs. */
public void writeEvent(@NonNull SelectionEvent event) {
- Preconditions.checkNotNull(event);
+ Objects.requireNonNull(event);
final LogMaker log = new LogMaker(MetricsEvent.TEXT_SELECTION_SESSION)
.setType(getLogType(event))
.setSubtype(getLogSubType(event))
@@ -240,7 +239,7 @@ public final class SelectionSessionLogger {
* Returns a token iterator for tokenizing text for logging purposes.
*/
public static BreakIterator getTokenIterator(@NonNull Locale locale) {
- return BreakIterator.getWordInstance(Preconditions.checkNotNull(locale));
+ return BreakIterator.getWordInstance(Objects.requireNonNull(locale));
}
/**
@@ -249,9 +248,9 @@ public final class SelectionSessionLogger {
public static String createId(
String text, int start, int end, Context context, int modelVersion,
List<Locale> locales) {
- Preconditions.checkNotNull(text);
- Preconditions.checkNotNull(context);
- Preconditions.checkNotNull(locales);
+ Objects.requireNonNull(text);
+ Objects.requireNonNull(context);
+ Objects.requireNonNull(locales);
final StringJoiner localesJoiner = new StringJoiner(",");
for (Locale locale : locales) {
localesJoiner.add(locale.toLanguageTag());
diff --git a/core/java/android/view/textclassifier/SystemTextClassifier.java b/core/java/android/view/textclassifier/SystemTextClassifier.java
index 66f75043a9c8..138d25dd7c83 100644
--- a/core/java/android/view/textclassifier/SystemTextClassifier.java
+++ b/core/java/android/view/textclassifier/SystemTextClassifier.java
@@ -33,8 +33,8 @@ import android.service.textclassifier.TextClassifierService;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.annotations.VisibleForTesting.Visibility;
import com.android.internal.util.IndentingPrintWriter;
-import com.android.internal.util.Preconditions;
+import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -61,10 +61,10 @@ public final class SystemTextClassifier implements TextClassifier {
throws ServiceManager.ServiceNotFoundException {
mManagerService = ITextClassifierService.Stub.asInterface(
ServiceManager.getServiceOrThrow(Context.TEXT_CLASSIFICATION_SERVICE));
- mSettings = Preconditions.checkNotNull(settings);
+ mSettings = Objects.requireNonNull(settings);
mFallback = context.getSystemService(TextClassificationManager.class)
.getTextClassifier(TextClassifier.LOCAL);
- mPackageName = Preconditions.checkNotNull(context.getOpPackageName());
+ mPackageName = Objects.requireNonNull(context.getOpPackageName());
mUserId = context.getUserId();
}
@@ -74,7 +74,7 @@ public final class SystemTextClassifier implements TextClassifier {
@Override
@WorkerThread
public TextSelection suggestSelection(TextSelection.Request request) {
- Preconditions.checkNotNull(request);
+ Objects.requireNonNull(request);
Utils.checkMainThread();
try {
request.setCallingPackageName(mPackageName);
@@ -98,7 +98,7 @@ public final class SystemTextClassifier implements TextClassifier {
@Override
@WorkerThread
public TextClassification classifyText(TextClassification.Request request) {
- Preconditions.checkNotNull(request);
+ Objects.requireNonNull(request);
Utils.checkMainThread();
try {
request.setCallingPackageName(mPackageName);
@@ -122,7 +122,7 @@ public final class SystemTextClassifier implements TextClassifier {
@Override
@WorkerThread
public TextLinks generateLinks(@NonNull TextLinks.Request request) {
- Preconditions.checkNotNull(request);
+ Objects.requireNonNull(request);
Utils.checkMainThread();
if (!mSettings.isSmartLinkifyEnabled() && request.isLegacyFallback()) {
@@ -147,7 +147,7 @@ public final class SystemTextClassifier implements TextClassifier {
@Override
public void onSelectionEvent(SelectionEvent event) {
- Preconditions.checkNotNull(event);
+ Objects.requireNonNull(event);
Utils.checkMainThread();
try {
@@ -160,7 +160,7 @@ public final class SystemTextClassifier implements TextClassifier {
@Override
public void onTextClassifierEvent(@NonNull TextClassifierEvent event) {
- Preconditions.checkNotNull(event);
+ Objects.requireNonNull(event);
Utils.checkMainThread();
try {
@@ -178,7 +178,7 @@ public final class SystemTextClassifier implements TextClassifier {
@Override
public TextLanguage detectLanguage(TextLanguage.Request request) {
- Preconditions.checkNotNull(request);
+ Objects.requireNonNull(request);
Utils.checkMainThread();
try {
@@ -199,7 +199,7 @@ public final class SystemTextClassifier implements TextClassifier {
@Override
public ConversationActions suggestConversationActions(ConversationActions.Request request) {
- Preconditions.checkNotNull(request);
+ Objects.requireNonNull(request);
Utils.checkMainThread();
try {
@@ -260,7 +260,7 @@ public final class SystemTextClassifier implements TextClassifier {
void initializeRemoteSession(
@NonNull TextClassificationContext classificationContext,
@NonNull TextClassificationSessionId sessionId) {
- mSessionId = Preconditions.checkNotNull(sessionId);
+ mSessionId = Objects.requireNonNull(sessionId);
try {
classificationContext.setUserId(mUserId);
mManagerService.onCreateTextClassificationSession(classificationContext, mSessionId);
diff --git a/core/java/android/view/textclassifier/TextClassification.java b/core/java/android/view/textclassifier/TextClassification.java
index 93f7103c3d8d..3628d2d40c1e 100644
--- a/core/java/android/view/textclassifier/TextClassification.java
+++ b/core/java/android/view/textclassifier/TextClassification.java
@@ -150,7 +150,7 @@ public final class TextClassification implements Parcelable {
mLegacyIntent = legacyIntent;
mLegacyOnClickListener = legacyOnClickListener;
mActions = Collections.unmodifiableList(actions);
- mEntityConfidence = Preconditions.checkNotNull(entityConfidence);
+ mEntityConfidence = Objects.requireNonNull(entityConfidence);
mId = id;
mExtras = extras;
}
@@ -287,7 +287,7 @@ public final class TextClassification implements Parcelable {
* @hide
*/
public static OnClickListener createIntentOnClickListener(@NonNull final PendingIntent intent) {
- Preconditions.checkNotNull(intent);
+ Objects.requireNonNull(intent);
return v -> {
try {
intent.send();
diff --git a/core/java/android/view/textclassifier/TextClassificationConstants.java b/core/java/android/view/textclassifier/TextClassificationConstants.java
index 9f8671aad313..ed69513b7f69 100644
--- a/core/java/android/view/textclassifier/TextClassificationConstants.java
+++ b/core/java/android/view/textclassifier/TextClassificationConstants.java
@@ -16,38 +16,31 @@
package android.view.textclassifier;
+import android.annotation.Nullable;
+import android.provider.DeviceConfig;
+
+import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.IndentingPrintWriter;
import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
-import java.util.function.Supplier;
/**
* TextClassifier specific settings.
- * This is encoded as a key=value list, separated by commas.
- * <p>
- * Example of setting the values for testing.
- * <p>
- * <pre>
- * adb shell settings put global text_classifier_constants \
- * model_dark_launch_enabled=true,smart_selection_enabled=true, \
- * entity_list_default=phone:address, \
- * lang_id_context_settings=20:1.0:0.4
- * </pre>
- * <p>
- * Settings are also available in device config. These take precedence over those in settings
- * global.
- * <p>
+ *
+ * <p>Currently, this class does not guarantee co-diverted flags are updated atomically.
+ *
* <pre>
* adb shell cmd device_config put textclassifier system_textclassifier_enabled true
* </pre>
*
- * @see android.provider.Settings.Global.TEXT_CLASSIFIER_CONSTANTS
- * @see android.provider.DeviceConfig.NAMESPACE_TEXTCLASSIFIER
+ * @see android.provider.DeviceConfig#NAMESPACE_TEXTCLASSIFIER
* @hide
*/
// TODO: Rename to TextClassifierSettings.
public final class TextClassificationConstants {
+ private static final String DELIMITER = ":";
/**
* Whether the smart linkify feature is enabled.
@@ -56,11 +49,12 @@ public final class TextClassificationConstants {
/**
* Whether SystemTextClassifier is enabled.
*/
- private static final String SYSTEM_TEXT_CLASSIFIER_ENABLED = "system_textclassifier_enabled";
+ static final String SYSTEM_TEXT_CLASSIFIER_ENABLED = "system_textclassifier_enabled";
/**
* Whether TextClassifierImpl is enabled.
*/
- private static final String LOCAL_TEXT_CLASSIFIER_ENABLED = "local_textclassifier_enabled";
+ @VisibleForTesting
+ static final String LOCAL_TEXT_CLASSIFIER_ENABLED = "local_textclassifier_enabled";
/**
* Enable smart selection without a visible UI changes.
*/
@@ -82,7 +76,8 @@ public final class TextClassificationConstants {
/**
* Max length of text that suggestSelection can accept.
*/
- private static final String SUGGEST_SELECTION_MAX_RANGE_LENGTH =
+ @VisibleForTesting
+ static final String SUGGEST_SELECTION_MAX_RANGE_LENGTH =
"suggest_selection_max_range_length";
/**
* Max length of text that classifyText can accept.
@@ -101,7 +96,8 @@ public final class TextClassificationConstants {
* A colon(:) separated string that specifies the default entities types for
* generateLinks when hint is not given.
*/
- private static final String ENTITY_LIST_DEFAULT = "entity_list_default";
+ @VisibleForTesting
+ static final String ENTITY_LIST_DEFAULT = "entity_list_default";
/**
* A colon(:) separated string that specifies the default entities types for
* generateLinks when the text is in a not editable UI widget.
@@ -127,7 +123,8 @@ public final class TextClassificationConstants {
/**
* Threshold to accept a suggested language from LangID model.
*/
- private static final String LANG_ID_THRESHOLD_OVERRIDE = "lang_id_threshold_override";
+ @VisibleForTesting
+ static final String LANG_ID_THRESHOLD_OVERRIDE = "lang_id_threshold_override";
/**
* Whether to enable {@link android.view.textclassifier.TemplateIntentFactory}.
*/
@@ -156,7 +153,8 @@ public final class TextClassificationConstants {
* Reject all text less than minimumTextSize with penalizeRatio=0
* @see {@code TextClassifierImpl#detectLanguages(String, int, int)} for reference.
*/
- private static final String LANG_ID_CONTEXT_SETTINGS = "lang_id_context_settings";
+ @VisibleForTesting
+ static final String LANG_ID_CONTEXT_SETTINGS = "lang_id_context_settings";
/**
* The TextClassifierService which would like to use. Example of setting the package:
@@ -164,9 +162,9 @@ public final class TextClassificationConstants {
* adb shell cmd device_config put textclassifier textclassifier_service_package_override \
* com.android.textclassifier
* </pre>
- *
*/
- private static final String TEXT_CLASSIFIER_SERVICE_PACKAGE_OVERRIDE =
+ @VisibleForTesting
+ static final String TEXT_CLASSIFIER_SERVICE_PACKAGE_OVERRIDE =
"textclassifier_service_package_override";
private static final String DEFAULT_TEXT_CLASSIFIER_SERVICE_PACKAGE_OVERRIDE = null;
@@ -213,142 +211,124 @@ public final class TextClassificationConstants {
private static final boolean DETECT_LANGUAGES_FROM_TEXT_ENABLED_DEFAULT = true;
private static final float[] LANG_ID_CONTEXT_SETTINGS_DEFAULT = new float[] {20f, 1.0f, 0.4f};
- private final ConfigParser mConfigParser;
-
- public TextClassificationConstants(Supplier<String> legacySettingsSupplier) {
- mConfigParser = new ConfigParser(legacySettingsSupplier);
- }
-
- public String getTextClassifierServiceName() {
- return mConfigParser.getString(
+ @Nullable
+ public String getTextClassifierServicePackageOverride() {
+ return DeviceConfig.getString(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
TEXT_CLASSIFIER_SERVICE_PACKAGE_OVERRIDE,
DEFAULT_TEXT_CLASSIFIER_SERVICE_PACKAGE_OVERRIDE);
}
public boolean isLocalTextClassifierEnabled() {
- return mConfigParser.getBoolean(
- LOCAL_TEXT_CLASSIFIER_ENABLED,
- LOCAL_TEXT_CLASSIFIER_ENABLED_DEFAULT);
+ return DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
+ LOCAL_TEXT_CLASSIFIER_ENABLED, LOCAL_TEXT_CLASSIFIER_ENABLED_DEFAULT);
}
public boolean isSystemTextClassifierEnabled() {
- return mConfigParser.getBoolean(
+ return DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
SYSTEM_TEXT_CLASSIFIER_ENABLED,
SYSTEM_TEXT_CLASSIFIER_ENABLED_DEFAULT);
}
public boolean isModelDarkLaunchEnabled() {
- return mConfigParser.getBoolean(
- MODEL_DARK_LAUNCH_ENABLED,
- MODEL_DARK_LAUNCH_ENABLED_DEFAULT);
+ return DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
+ MODEL_DARK_LAUNCH_ENABLED, MODEL_DARK_LAUNCH_ENABLED_DEFAULT);
}
public boolean isSmartSelectionEnabled() {
- return mConfigParser.getBoolean(
- SMART_SELECTION_ENABLED,
- SMART_SELECTION_ENABLED_DEFAULT);
+ return DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
+ SMART_SELECTION_ENABLED, SMART_SELECTION_ENABLED_DEFAULT);
}
public boolean isSmartTextShareEnabled() {
- return mConfigParser.getBoolean(
- SMART_TEXT_SHARE_ENABLED,
- SMART_TEXT_SHARE_ENABLED_DEFAULT);
+ return DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
+ SMART_TEXT_SHARE_ENABLED, SMART_TEXT_SHARE_ENABLED_DEFAULT);
}
public boolean isSmartLinkifyEnabled() {
- return mConfigParser.getBoolean(
- SMART_LINKIFY_ENABLED,
+ return DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_TEXTCLASSIFIER, SMART_LINKIFY_ENABLED,
SMART_LINKIFY_ENABLED_DEFAULT);
}
public boolean isSmartSelectionAnimationEnabled() {
- return mConfigParser.getBoolean(
- SMART_SELECT_ANIMATION_ENABLED,
- SMART_SELECT_ANIMATION_ENABLED_DEFAULT);
+ return DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
+ SMART_SELECT_ANIMATION_ENABLED, SMART_SELECT_ANIMATION_ENABLED_DEFAULT);
}
public int getSuggestSelectionMaxRangeLength() {
- return mConfigParser.getInt(
- SUGGEST_SELECTION_MAX_RANGE_LENGTH,
- SUGGEST_SELECTION_MAX_RANGE_LENGTH_DEFAULT);
+ return DeviceConfig.getInt(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
+ SUGGEST_SELECTION_MAX_RANGE_LENGTH, SUGGEST_SELECTION_MAX_RANGE_LENGTH_DEFAULT);
}
public int getClassifyTextMaxRangeLength() {
- return mConfigParser.getInt(
- CLASSIFY_TEXT_MAX_RANGE_LENGTH,
- CLASSIFY_TEXT_MAX_RANGE_LENGTH_DEFAULT);
+ return DeviceConfig.getInt(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
+ CLASSIFY_TEXT_MAX_RANGE_LENGTH, CLASSIFY_TEXT_MAX_RANGE_LENGTH_DEFAULT);
}
public int getGenerateLinksMaxTextLength() {
- return mConfigParser.getInt(
- GENERATE_LINKS_MAX_TEXT_LENGTH,
- GENERATE_LINKS_MAX_TEXT_LENGTH_DEFAULT);
+ return DeviceConfig.getInt(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
+ GENERATE_LINKS_MAX_TEXT_LENGTH, GENERATE_LINKS_MAX_TEXT_LENGTH_DEFAULT);
}
public int getGenerateLinksLogSampleRate() {
- return mConfigParser.getInt(
- GENERATE_LINKS_LOG_SAMPLE_RATE,
- GENERATE_LINKS_LOG_SAMPLE_RATE_DEFAULT);
+ return DeviceConfig.getInt(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
+ GENERATE_LINKS_LOG_SAMPLE_RATE, GENERATE_LINKS_LOG_SAMPLE_RATE_DEFAULT);
}
public List<String> getEntityListDefault() {
- return mConfigParser.getStringList(
- ENTITY_LIST_DEFAULT,
- ENTITY_LIST_DEFAULT_VALUE);
+ return getDeviceConfigStringList(ENTITY_LIST_DEFAULT, ENTITY_LIST_DEFAULT_VALUE);
}
public List<String> getEntityListNotEditable() {
- return mConfigParser.getStringList(
- ENTITY_LIST_NOT_EDITABLE,
- ENTITY_LIST_DEFAULT_VALUE);
+ return getDeviceConfigStringList(ENTITY_LIST_NOT_EDITABLE, ENTITY_LIST_DEFAULT_VALUE);
}
public List<String> getEntityListEditable() {
- return mConfigParser.getStringList(
- ENTITY_LIST_EDITABLE,
- ENTITY_LIST_DEFAULT_VALUE);
+ return getDeviceConfigStringList(ENTITY_LIST_EDITABLE, ENTITY_LIST_DEFAULT_VALUE);
}
public List<String> getInAppConversationActionTypes() {
- return mConfigParser.getStringList(
+ return getDeviceConfigStringList(
IN_APP_CONVERSATION_ACTION_TYPES_DEFAULT,
CONVERSATION_ACTIONS_TYPES_DEFAULT_VALUES);
}
public List<String> getNotificationConversationActionTypes() {
- return mConfigParser.getStringList(
+ return getDeviceConfigStringList(
NOTIFICATION_CONVERSATION_ACTION_TYPES_DEFAULT,
CONVERSATION_ACTIONS_TYPES_DEFAULT_VALUES);
}
public float getLangIdThresholdOverride() {
- return mConfigParser.getFloat(
+ return DeviceConfig.getFloat(
+ DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
LANG_ID_THRESHOLD_OVERRIDE,
LANG_ID_THRESHOLD_OVERRIDE_DEFAULT);
}
public boolean isTemplateIntentFactoryEnabled() {
- return mConfigParser.getBoolean(
+ return DeviceConfig.getBoolean(
+ DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
TEMPLATE_INTENT_FACTORY_ENABLED,
TEMPLATE_INTENT_FACTORY_ENABLED_DEFAULT);
}
public boolean isTranslateInClassificationEnabled() {
- return mConfigParser.getBoolean(
+ return DeviceConfig.getBoolean(
+ DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
TRANSLATE_IN_CLASSIFICATION_ENABLED,
TRANSLATE_IN_CLASSIFICATION_ENABLED_DEFAULT);
}
public boolean isDetectLanguagesFromTextEnabled() {
- return mConfigParser.getBoolean(
+ return DeviceConfig.getBoolean(
+ DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
DETECT_LANGUAGES_FROM_TEXT_ENABLED,
DETECT_LANGUAGES_FROM_TEXT_ENABLED_DEFAULT);
}
public float[] getLangIdContextSettings() {
- return mConfigParser.getFloatArray(
- LANG_ID_CONTEXT_SETTINGS,
- LANG_ID_CONTEXT_SETTINGS_DEFAULT);
+ return getDeviceConfigFloatArray(
+ LANG_ID_CONTEXT_SETTINGS, LANG_ID_CONTEXT_SETTINGS_DEFAULT);
}
void dump(IndentingPrintWriter pw) {
@@ -356,7 +336,7 @@ public final class TextClassificationConstants {
pw.increaseIndent();
pw.printPair("classify_text_max_range_length", getClassifyTextMaxRangeLength())
.println();
- pw.printPair("detect_language_from_text_enabled", isDetectLanguagesFromTextEnabled())
+ pw.printPair("detect_languages_from_text_enabled", isDetectLanguagesFromTextEnabled())
.println();
pw.printPair("entity_list_default", getEntityListDefault())
.println();
@@ -396,8 +376,47 @@ public final class TextClassificationConstants {
.println();
pw.printPair("translate_in_classification_enabled", isTranslateInClassificationEnabled())
.println();
- pw.printPair("textclassifier_service_package_override", getTextClassifierServiceName())
- .println();
+ pw.printPair("textclassifier_service_package_override",
+ getTextClassifierServicePackageOverride()).println();
pw.decreaseIndent();
}
+
+ private static List<String> getDeviceConfigStringList(String key, List<String> defaultValue) {
+ return parse(
+ DeviceConfig.getString(DeviceConfig.NAMESPACE_TEXTCLASSIFIER, key, null),
+ defaultValue);
+ }
+
+ private static float[] getDeviceConfigFloatArray(String key, float[] defaultValue) {
+ return parse(
+ DeviceConfig.getString(DeviceConfig.NAMESPACE_TEXTCLASSIFIER, key, null),
+ defaultValue);
+ }
+
+ private static List<String> parse(@Nullable String listStr, List<String> defaultValue) {
+ if (listStr != null) {
+ return Collections.unmodifiableList(Arrays.asList(listStr.split(DELIMITER)));
+ }
+ return defaultValue;
+ }
+
+ private static float[] parse(@Nullable String arrayStr, float[] defaultValue) {
+ if (arrayStr != null) {
+ final String[] split = arrayStr.split(DELIMITER);
+ if (split.length != defaultValue.length) {
+ return defaultValue;
+ }
+ final float[] result = new float[split.length];
+ for (int i = 0; i < split.length; i++) {
+ try {
+ result[i] = Float.parseFloat(split[i]);
+ } catch (NumberFormatException e) {
+ return defaultValue;
+ }
+ }
+ return result;
+ } else {
+ return defaultValue;
+ }
+ }
} \ No newline at end of file
diff --git a/core/java/android/view/textclassifier/TextClassificationContext.java b/core/java/android/view/textclassifier/TextClassificationContext.java
index e4baaac9a300..930765b29197 100644
--- a/core/java/android/view/textclassifier/TextClassificationContext.java
+++ b/core/java/android/view/textclassifier/TextClassificationContext.java
@@ -24,9 +24,8 @@ import android.os.Parcelable;
import android.os.UserHandle;
import android.view.textclassifier.TextClassifier.WidgetType;
-import com.android.internal.util.Preconditions;
-
import java.util.Locale;
+import java.util.Objects;
/**
* A representation of the context in which text classification would be performed.
@@ -44,8 +43,8 @@ public final class TextClassificationContext implements Parcelable {
String packageName,
String widgetType,
String widgetVersion) {
- mPackageName = Preconditions.checkNotNull(packageName);
- mWidgetType = Preconditions.checkNotNull(widgetType);
+ mPackageName = Objects.requireNonNull(packageName);
+ mWidgetType = Objects.requireNonNull(widgetType);
mWidgetVersion = widgetVersion;
}
@@ -121,8 +120,8 @@ public final class TextClassificationContext implements Parcelable {
* @return this builder
*/
public Builder(@NonNull String packageName, @NonNull @WidgetType String widgetType) {
- mPackageName = Preconditions.checkNotNull(packageName);
- mWidgetType = Preconditions.checkNotNull(widgetType);
+ mPackageName = Objects.requireNonNull(packageName);
+ mWidgetType = Objects.requireNonNull(widgetType);
}
/**
diff --git a/core/java/android/view/textclassifier/TextClassificationManager.java b/core/java/android/view/textclassifier/TextClassificationManager.java
index 3e0f7eef33a7..bb96d5543b0b 100644
--- a/core/java/android/view/textclassifier/TextClassificationManager.java
+++ b/core/java/android/view/textclassifier/TextClassificationManager.java
@@ -19,23 +19,22 @@ package android.view.textclassifier;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityThread;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
-import android.database.ContentObserver;
import android.os.ServiceManager;
import android.provider.DeviceConfig;
import android.provider.DeviceConfig.Properties;
-import android.provider.Settings;
import android.service.textclassifier.TextClassifierService;
import android.view.textclassifier.TextClassifier.TextClassifierType;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.IndentingPrintWriter;
-import com.android.internal.util.Preconditions;
import java.lang.ref.WeakReference;
+import java.util.Objects;
+import java.util.Set;
/**
* Interface to the text classification service.
@@ -46,7 +45,7 @@ public final class TextClassificationManager {
private static final String LOG_TAG = "TextClassificationManager";
private static final TextClassificationConstants sDefaultSettings =
- new TextClassificationConstants(() -> null);
+ new TextClassificationConstants();
private final Object mLock = new Object();
private final TextClassificationSessionFactory mDefaultSessionFactory =
@@ -72,7 +71,7 @@ public final class TextClassificationManager {
/** @hide */
public TextClassificationManager(Context context) {
- mContext = Preconditions.checkNotNull(context);
+ mContext = Objects.requireNonNull(context);
mSessionFactory = mDefaultSessionFactory;
mSettingsObserver = new SettingsObserver(this);
}
@@ -132,10 +131,7 @@ public final class TextClassificationManager {
private TextClassificationConstants getSettings() {
synchronized (mLock) {
if (mSettings == null) {
- mSettings = new TextClassificationConstants(
- () -> Settings.Global.getString(
- getApplicationContext().getContentResolver(),
- Settings.Global.TEXT_CLASSIFIER_CONSTANTS));
+ mSettings = new TextClassificationConstants();
}
return mSettings;
}
@@ -161,10 +157,10 @@ public final class TextClassificationManager {
@NonNull
public TextClassifier createTextClassificationSession(
@NonNull TextClassificationContext classificationContext) {
- Preconditions.checkNotNull(classificationContext);
+ Objects.requireNonNull(classificationContext);
final TextClassifier textClassifier =
mSessionFactory.createTextClassificationSession(classificationContext);
- Preconditions.checkNotNull(textClassifier, "Session Factory should never return null");
+ Objects.requireNonNull(textClassifier, "Session Factory should never return null");
return textClassifier;
}
@@ -174,8 +170,8 @@ public final class TextClassificationManager {
*/
public TextClassifier createTextClassificationSession(
TextClassificationContext classificationContext, TextClassifier textClassifier) {
- Preconditions.checkNotNull(classificationContext);
- Preconditions.checkNotNull(textClassifier);
+ Objects.requireNonNull(classificationContext);
+ Objects.requireNonNull(textClassifier);
return new TextClassificationSession(classificationContext, textClassifier);
}
@@ -201,11 +197,7 @@ public final class TextClassificationManager {
try {
// Note that fields could be null if the constructor threw.
if (mSettingsObserver != null) {
- getApplicationContext().getContentResolver()
- .unregisterContentObserver(mSettingsObserver);
- if (ConfigParser.ENABLE_DEVICE_CONFIG) {
- DeviceConfig.removeOnPropertiesChangedListener(mSettingsObserver);
- }
+ DeviceConfig.removeOnPropertiesChangedListener(mSettingsObserver);
}
} finally {
super.finalize();
@@ -250,7 +242,7 @@ public final class TextClassificationManager {
private boolean isSystemTextClassifierEnabled() {
return getSettings().isSystemTextClassifierEnabled()
- && TextClassifierService.getServiceComponentName(mContext, getSettings()) != null;
+ && TextClassifierService.getServiceComponentName(mContext) != null;
}
/** @hide */
@@ -262,6 +254,12 @@ public final class TextClassificationManager {
private void invalidate() {
synchronized (mLock) {
mSettings = null;
+ invalidateTextClassifiers();
+ }
+ }
+
+ private void invalidateTextClassifiers() {
+ synchronized (mLock) {
mLocalTextClassifier = null;
mSystemTextClassifier = null;
}
@@ -282,7 +280,7 @@ public final class TextClassificationManager {
/** @hide */
public static TextClassificationConstants getSettings(Context context) {
- Preconditions.checkNotNull(context);
+ Objects.requireNonNull(context);
final TextClassificationManager tcm =
context.getSystemService(TextClassificationManager.class);
if (tcm != null) {
@@ -293,40 +291,29 @@ public final class TextClassificationManager {
}
}
- private static final class SettingsObserver extends ContentObserver
- implements DeviceConfig.OnPropertiesChangedListener {
+ private static final class SettingsObserver implements
+ DeviceConfig.OnPropertiesChangedListener {
private final WeakReference<TextClassificationManager> mTcm;
SettingsObserver(TextClassificationManager tcm) {
- super(null);
mTcm = new WeakReference<>(tcm);
- tcm.getApplicationContext().getContentResolver().registerContentObserver(
- Settings.Global.getUriFor(Settings.Global.TEXT_CLASSIFIER_CONSTANTS),
- false /* notifyForDescendants */,
+ DeviceConfig.addOnPropertiesChangedListener(
+ DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
+ ActivityThread.currentApplication().getMainExecutor(),
this);
- if (ConfigParser.ENABLE_DEVICE_CONFIG) {
- DeviceConfig.addOnPropertiesChangedListener(
- DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- ActivityThread.currentApplication().getMainExecutor(),
- this);
- }
- }
-
- @Override
- public void onChange(boolean selfChange) {
- invalidateSettings();
}
@Override
public void onPropertiesChanged(Properties properties) {
- invalidateSettings();
- }
-
- private void invalidateSettings() {
final TextClassificationManager tcm = mTcm.get();
if (tcm != null) {
- tcm.invalidate();
+ final Set<String> keys = properties.getKeyset();
+ if (keys.contains(TextClassificationConstants.SYSTEM_TEXT_CLASSIFIER_ENABLED)
+ || keys.contains(
+ TextClassificationConstants.LOCAL_TEXT_CLASSIFIER_ENABLED)) {
+ tcm.invalidateTextClassifiers();
+ }
}
}
}
diff --git a/core/java/android/view/textclassifier/TextClassificationSession.java b/core/java/android/view/textclassifier/TextClassificationSession.java
index 6a706f5183ce..abfbc6c4f4ae 100644
--- a/core/java/android/view/textclassifier/TextClassificationSession.java
+++ b/core/java/android/view/textclassifier/TextClassificationSession.java
@@ -20,6 +20,7 @@ import android.annotation.WorkerThread;
import android.view.textclassifier.SelectionEvent.InvocationMethod;
import com.android.internal.util.Preconditions;
+import java.util.Objects;
/**
* Session-aware TextClassifier.
@@ -37,8 +38,8 @@ final class TextClassificationSession implements TextClassifier {
private boolean mDestroyed;
TextClassificationSession(TextClassificationContext context, TextClassifier delegate) {
- mClassificationContext = Preconditions.checkNotNull(context);
- mDelegate = Preconditions.checkNotNull(delegate);
+ mClassificationContext = Objects.requireNonNull(context);
+ mDelegate = Objects.requireNonNull(delegate);
mSessionId = new TextClassificationSessionId();
mEventHelper = new SelectionEventHelper(mSessionId, mClassificationContext);
initializeRemoteSession();
@@ -149,8 +150,8 @@ final class TextClassificationSession implements TextClassifier {
SelectionEventHelper(
TextClassificationSessionId sessionId, TextClassificationContext context) {
- mSessionId = Preconditions.checkNotNull(sessionId);
- mContext = Preconditions.checkNotNull(context);
+ mSessionId = Objects.requireNonNull(sessionId);
+ mContext = Objects.requireNonNull(context);
}
/**
diff --git a/core/java/android/view/textclassifier/TextClassificationSessionId.java b/core/java/android/view/textclassifier/TextClassificationSessionId.java
index 8b68e17aa681..f90e6b2e407c 100644
--- a/core/java/android/view/textclassifier/TextClassificationSessionId.java
+++ b/core/java/android/view/textclassifier/TextClassificationSessionId.java
@@ -20,9 +20,8 @@ import android.annotation.NonNull;
import android.os.Parcel;
import android.os.Parcelable;
-import com.android.internal.util.Preconditions;
-
import java.util.Locale;
+import java.util.Objects;
import java.util.UUID;
/**
@@ -118,7 +117,7 @@ public final class TextClassificationSessionId implements Parcelable {
@Override
public TextClassificationSessionId createFromParcel(Parcel parcel) {
return new TextClassificationSessionId(
- Preconditions.checkNotNull(parcel.readString()));
+ Objects.requireNonNull(parcel.readString()));
}
@Override
diff --git a/core/java/android/view/textclassifier/TextClassifier.java b/core/java/android/view/textclassifier/TextClassifier.java
index ac8a429a0fd6..9b3369390b6a 100644
--- a/core/java/android/view/textclassifier/TextClassifier.java
+++ b/core/java/android/view/textclassifier/TextClassifier.java
@@ -46,6 +46,7 @@ import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
/**
@@ -193,7 +194,7 @@ public interface TextClassifier {
@WorkerThread
@NonNull
default TextSelection suggestSelection(@NonNull TextSelection.Request request) {
- Preconditions.checkNotNull(request);
+ Objects.requireNonNull(request);
Utils.checkMainThread();
return new TextSelection.Builder(request.getStartIndex(), request.getEndIndex()).build();
}
@@ -252,7 +253,7 @@ public interface TextClassifier {
@WorkerThread
@NonNull
default TextClassification classifyText(@NonNull TextClassification.Request request) {
- Preconditions.checkNotNull(request);
+ Objects.requireNonNull(request);
Utils.checkMainThread();
return TextClassification.EMPTY;
}
@@ -313,7 +314,7 @@ public interface TextClassifier {
@WorkerThread
@NonNull
default TextLinks generateLinks(@NonNull TextLinks.Request request) {
- Preconditions.checkNotNull(request);
+ Objects.requireNonNull(request);
Utils.checkMainThread();
return new TextLinks.Builder(request.getText().toString()).build();
}
@@ -346,7 +347,7 @@ public interface TextClassifier {
@WorkerThread
@NonNull
default TextLanguage detectLanguage(@NonNull TextLanguage.Request request) {
- Preconditions.checkNotNull(request);
+ Objects.requireNonNull(request);
Utils.checkMainThread();
return TextLanguage.EMPTY;
}
@@ -358,7 +359,7 @@ public interface TextClassifier {
@NonNull
default ConversationActions suggestConversationActions(
@NonNull ConversationActions.Request request) {
- Preconditions.checkNotNull(request);
+ Objects.requireNonNull(request);
Utils.checkMainThread();
return new ConversationActions(Collections.emptyList(), null);
}
@@ -427,9 +428,9 @@ public interface TextClassifier {
List<String> excludedEntityTypes,
List<String> hints,
boolean includeTypesFromTextClassifier) {
- mIncludedTypes = Preconditions.checkNotNull(includedEntityTypes);
- mExcludedTypes = Preconditions.checkNotNull(excludedEntityTypes);
- mHints = Preconditions.checkNotNull(hints);
+ mIncludedTypes = Objects.requireNonNull(includedEntityTypes);
+ mExcludedTypes = Objects.requireNonNull(excludedEntityTypes);
+ mHints = Objects.requireNonNull(hints);
mIncludeTypesFromTextClassifier = includeTypesFromTextClassifier;
}
diff --git a/core/java/android/view/textclassifier/TextClassifierEvent.java b/core/java/android/view/textclassifier/TextClassifierEvent.java
index eb6aec07aad9..db8801150f0d 100644
--- a/core/java/android/view/textclassifier/TextClassifierEvent.java
+++ b/core/java/android/view/textclassifier/TextClassifierEvent.java
@@ -25,11 +25,11 @@ import android.os.Parcel;
import android.os.Parcelable;
import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.util.Preconditions;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
+import java.util.Objects;
/**
* This class represents events that are sent by components to the {@link TextClassifier} to report
@@ -549,7 +549,7 @@ public abstract class TextClassifierEvent implements Parcelable {
*/
@NonNull
public T setEntityTypes(@NonNull String... entityTypes) {
- Preconditions.checkNotNull(entityTypes);
+ Objects.requireNonNull(entityTypes);
mEntityTypes = new String[entityTypes.length];
System.arraycopy(entityTypes, 0, mEntityTypes, 0, entityTypes.length);
return self();
@@ -587,7 +587,7 @@ public abstract class TextClassifierEvent implements Parcelable {
*/
@NonNull
public T setScores(@NonNull float... scores) {
- Preconditions.checkNotNull(scores);
+ Objects.requireNonNull(scores);
mScores = new float[scores.length];
System.arraycopy(scores, 0, mScores, 0, scores.length);
return self();
@@ -652,7 +652,7 @@ public abstract class TextClassifierEvent implements Parcelable {
*/
@NonNull
public T setExtras(@NonNull Bundle extras) {
- mExtras = Preconditions.checkNotNull(extras);
+ mExtras = Objects.requireNonNull(extras);
return self();
}
diff --git a/core/java/android/view/textclassifier/TextClassifierEventTronLogger.java b/core/java/android/view/textclassifier/TextClassifierEventTronLogger.java
index 3e088b8565f2..8162699a74c6 100644
--- a/core/java/android/view/textclassifier/TextClassifierEventTronLogger.java
+++ b/core/java/android/view/textclassifier/TextClassifierEventTronLogger.java
@@ -29,7 +29,7 @@ import android.metrics.LogMaker;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.logging.MetricsLogger;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.internal.util.Preconditions;
+import java.util.Objects;
/**
@@ -50,12 +50,12 @@ public final class TextClassifierEventTronLogger {
@VisibleForTesting
public TextClassifierEventTronLogger(MetricsLogger metricsLogger) {
- mMetricsLogger = Preconditions.checkNotNull(metricsLogger);
+ mMetricsLogger = Objects.requireNonNull(metricsLogger);
}
/** Emits a text classifier event to the logs. */
public void writeEvent(TextClassifierEvent event) {
- Preconditions.checkNotNull(event);
+ Objects.requireNonNull(event);
int category = getCategory(event);
if (category == -1) {
diff --git a/core/java/android/view/textclassifier/TextClassifierImpl.java b/core/java/android/view/textclassifier/TextClassifierImpl.java
index 024c379e0165..61bd7c72b80b 100644
--- a/core/java/android/view/textclassifier/TextClassifierImpl.java
+++ b/core/java/android/view/textclassifier/TextClassifierImpl.java
@@ -130,9 +130,9 @@ public final class TextClassifierImpl implements TextClassifier {
public TextClassifierImpl(
Context context, TextClassificationConstants settings, TextClassifier fallback) {
- mContext = Preconditions.checkNotNull(context);
- mFallback = Preconditions.checkNotNull(fallback);
- mSettings = Preconditions.checkNotNull(settings);
+ mContext = Objects.requireNonNull(context);
+ mFallback = Objects.requireNonNull(fallback);
+ mSettings = Objects.requireNonNull(settings);
mGenerateLinksLogger = new GenerateLinksLogger(mSettings.getGenerateLinksLogSampleRate());
mAnnotatorModelFileManager = new ModelFileManager(
new ModelFileManager.ModelFileSupplierImpl(
@@ -180,7 +180,7 @@ public final class TextClassifierImpl implements TextClassifier {
@Override
@WorkerThread
public TextSelection suggestSelection(TextSelection.Request request) {
- Preconditions.checkNotNull(request);
+ Objects.requireNonNull(request);
Utils.checkMainThread();
try {
final int rangeLength = request.getEndIndex() - request.getStartIndex();
@@ -245,7 +245,7 @@ public final class TextClassifierImpl implements TextClassifier {
@Override
@WorkerThread
public TextClassification classifyText(TextClassification.Request request) {
- Preconditions.checkNotNull(request);
+ Objects.requireNonNull(request);
Utils.checkMainThread();
try {
final int rangeLength = request.getEndIndex() - request.getStartIndex();
@@ -285,7 +285,7 @@ public final class TextClassifierImpl implements TextClassifier {
@Override
@WorkerThread
public TextLinks generateLinks(@NonNull TextLinks.Request request) {
- Preconditions.checkNotNull(request);
+ Objects.requireNonNull(request);
Utils.checkTextLength(request.getText(), getMaxGenerateLinksTextLength());
Utils.checkMainThread();
@@ -399,7 +399,7 @@ public final class TextClassifierImpl implements TextClassifier {
/** @inheritDoc */
@Override
public TextLanguage detectLanguage(@NonNull TextLanguage.Request request) {
- Preconditions.checkNotNull(request);
+ Objects.requireNonNull(request);
Utils.checkMainThread();
try {
final TextLanguage.Builder builder = new TextLanguage.Builder();
@@ -420,7 +420,7 @@ public final class TextClassifierImpl implements TextClassifier {
@Override
public ConversationActions suggestConversationActions(ConversationActions.Request request) {
- Preconditions.checkNotNull(request);
+ Objects.requireNonNull(request);
Utils.checkMainThread();
try {
ActionsSuggestionsModel actionsImpl = getActionsImpl();
diff --git a/core/java/android/view/textclassifier/TextLinks.java b/core/java/android/view/textclassifier/TextLinks.java
index bbb7f07e0fdc..237d1a9e7838 100644
--- a/core/java/android/view/textclassifier/TextLinks.java
+++ b/core/java/android/view/textclassifier/TextLinks.java
@@ -48,6 +48,7 @@ import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
+import java.util.Objects;
import java.util.function.Function;
/**
@@ -155,7 +156,7 @@ public final class TextLinks implements Parcelable {
@NonNull Spannable text,
@ApplyStrategy int applyStrategy,
@Nullable Function<TextLink, TextLinkSpan> spanFactory) {
- Preconditions.checkNotNull(text);
+ Objects.requireNonNull(text);
return new TextLinksParams.Builder()
.setApplyStrategy(applyStrategy)
.setSpanFactory(spanFactory)
@@ -223,10 +224,10 @@ public final class TextLinks implements Parcelable {
*/
private TextLink(int start, int end, @NonNull EntityConfidence entityConfidence,
@NonNull Bundle extras, @Nullable URLSpan urlSpan) {
- Preconditions.checkNotNull(entityConfidence);
+ Objects.requireNonNull(entityConfidence);
Preconditions.checkArgument(!entityConfidence.getEntities().isEmpty());
Preconditions.checkArgument(start <= end);
- Preconditions.checkNotNull(extras);
+ Objects.requireNonNull(extras);
mStart = start;
mEnd = end;
mEntityScores = entityConfidence;
@@ -455,7 +456,7 @@ public final class TextLinks implements Parcelable {
@Nullable private Bundle mExtras;
public Builder(@NonNull CharSequence text) {
- mText = Preconditions.checkNotNull(text);
+ mText = Objects.requireNonNull(text);
}
/**
@@ -654,7 +655,7 @@ public final class TextLinks implements Parcelable {
* @param fullText The full text to annotate with links
*/
public Builder(@NonNull String fullText) {
- mFullText = Preconditions.checkNotNull(fullText);
+ mFullText = Objects.requireNonNull(fullText);
mLinks = new ArrayList<>();
}
diff --git a/core/java/android/view/textclassifier/TextLinksParams.java b/core/java/android/view/textclassifier/TextLinksParams.java
index 8af423300406..b7d63bfabd6d 100644
--- a/core/java/android/view/textclassifier/TextLinksParams.java
+++ b/core/java/android/view/textclassifier/TextLinksParams.java
@@ -25,10 +25,9 @@ import android.text.util.Linkify.LinkifyMask;
import android.view.textclassifier.TextLinks.TextLink;
import android.view.textclassifier.TextLinks.TextLinkSpan;
-import com.android.internal.util.Preconditions;
-
import java.util.ArrayList;
import java.util.List;
+import java.util.Objects;
import java.util.function.Function;
/**
@@ -103,8 +102,8 @@ public final class TextLinksParams {
*/
@TextLinks.Status
public int apply(@NonNull Spannable text, @NonNull TextLinks textLinks) {
- Preconditions.checkNotNull(text);
- Preconditions.checkNotNull(textLinks);
+ Objects.requireNonNull(text);
+ Objects.requireNonNull(textLinks);
final String textString = text.toString();
diff --git a/core/java/android/view/textclassifier/TextSelection.java b/core/java/android/view/textclassifier/TextSelection.java
index 0c8974956a7a..4a36cbfc35e5 100644
--- a/core/java/android/view/textclassifier/TextSelection.java
+++ b/core/java/android/view/textclassifier/TextSelection.java
@@ -36,6 +36,7 @@ import com.android.internal.util.Preconditions;
import java.util.Locale;
import java.util.Map;
+import java.util.Objects;
/**
* Information about where text selection should be.
@@ -165,7 +166,7 @@ public final class TextSelection implements Parcelable {
public Builder setEntityType(
@NonNull @EntityType String type,
@FloatRange(from = 0.0, to = 1.0) float confidenceScore) {
- Preconditions.checkNotNull(type);
+ Objects.requireNonNull(type);
mEntityConfidence.put(type, confidenceScore);
return this;
}
diff --git a/core/java/android/view/textclassifier/intent/LabeledIntent.java b/core/java/android/view/textclassifier/intent/LabeledIntent.java
index 30fc20ea86a1..cbd9d1a522f6 100644
--- a/core/java/android/view/textclassifier/intent/LabeledIntent.java
+++ b/core/java/android/view/textclassifier/intent/LabeledIntent.java
@@ -32,7 +32,8 @@ import android.view.textclassifier.TextClassification;
import android.view.textclassifier.TextClassifier;
import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.util.Preconditions;
+
+import java.util.Objects;
/**
* Helper class to store the information from which RemoteActions are built.
@@ -86,9 +87,9 @@ public final class LabeledIntent {
}
this.titleWithoutEntity = titleWithoutEntity;
this.titleWithEntity = titleWithEntity;
- this.description = Preconditions.checkNotNull(description);
+ this.description = Objects.requireNonNull(description);
this.descriptionWithAppName = descriptionWithAppName;
- this.intent = Preconditions.checkNotNull(intent);
+ this.intent = Objects.requireNonNull(intent);
this.requestCode = requestCode;
}
@@ -198,8 +199,8 @@ public final class LabeledIntent {
public final RemoteAction remoteAction;
public Result(Intent resolvedIntent, RemoteAction remoteAction) {
- this.resolvedIntent = Preconditions.checkNotNull(resolvedIntent);
- this.remoteAction = Preconditions.checkNotNull(remoteAction);
+ this.resolvedIntent = Objects.requireNonNull(resolvedIntent);
+ this.remoteAction = Objects.requireNonNull(remoteAction);
}
}
diff --git a/core/java/android/view/textclassifier/intent/TemplateClassificationIntentFactory.java b/core/java/android/view/textclassifier/intent/TemplateClassificationIntentFactory.java
index 111fc6ab5f9f..aef4bd6c7351 100644
--- a/core/java/android/view/textclassifier/intent/TemplateClassificationIntentFactory.java
+++ b/core/java/android/view/textclassifier/intent/TemplateClassificationIntentFactory.java
@@ -30,6 +30,7 @@ import com.google.android.textclassifier.RemoteActionTemplate;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
+import java.util.Objects;
/**
* Creates intents based on {@link RemoteActionTemplate} objects for a ClassificationResult.
@@ -44,8 +45,8 @@ public final class TemplateClassificationIntentFactory implements Classification
public TemplateClassificationIntentFactory(TemplateIntentFactory templateIntentFactory,
ClassificationIntentFactory fallback) {
- mTemplateIntentFactory = Preconditions.checkNotNull(templateIntentFactory);
- mFallback = Preconditions.checkNotNull(fallback);
+ mTemplateIntentFactory = Objects.requireNonNull(templateIntentFactory);
+ mFallback = Objects.requireNonNull(fallback);
}
/**
diff --git a/core/java/android/view/textclassifier/logging/SmartSelectionEventTracker.java b/core/java/android/view/textclassifier/logging/SmartSelectionEventTracker.java
index 157c43597a44..7dbcbf971bed 100644
--- a/core/java/android/view/textclassifier/logging/SmartSelectionEventTracker.java
+++ b/core/java/android/view/textclassifier/logging/SmartSelectionEventTracker.java
@@ -19,7 +19,7 @@ package android.view.textclassifier.logging;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.metrics.LogMaker;
import android.util.Log;
@@ -105,14 +105,14 @@ public final class SmartSelectionEventTracker {
public SmartSelectionEventTracker(@NonNull Context context, @WidgetType int widgetType) {
mWidgetType = widgetType;
mWidgetVersion = null;
- mContext = Preconditions.checkNotNull(context);
+ mContext = Objects.requireNonNull(context);
}
public SmartSelectionEventTracker(
@NonNull Context context, @WidgetType int widgetType, @Nullable String widgetVersion) {
mWidgetType = widgetType;
mWidgetVersion = widgetVersion;
- mContext = Preconditions.checkNotNull(context);
+ mContext = Objects.requireNonNull(context);
}
/**
@@ -122,7 +122,7 @@ public final class SmartSelectionEventTracker {
*/
@UnsupportedAppUsage(trackingBug = 136637107)
public void logEvent(@NonNull SelectionEvent event) {
- Preconditions.checkNotNull(event);
+ Objects.requireNonNull(event);
if (event.mEventType != SelectionEvent.EventType.SELECTION_STARTED && mSessionId == null
&& DEBUG_LOG_ENABLED) {
@@ -435,8 +435,8 @@ public final class SmartSelectionEventTracker {
mStart = start;
mEnd = end;
mEventType = eventType;
- mEntityType = Preconditions.checkNotNull(entityType);
- mVersionTag = Preconditions.checkNotNull(versionTag);
+ mEntityType = Objects.requireNonNull(entityType);
+ mVersionTag = Objects.requireNonNull(versionTag);
}
/**
diff --git a/core/java/android/view/textservice/SpellCheckerSession.java b/core/java/android/view/textservice/SpellCheckerSession.java
index f553ca512881..afddaa2ff58a 100644
--- a/core/java/android/view/textservice/SpellCheckerSession.java
+++ b/core/java/android/view/textservice/SpellCheckerSession.java
@@ -16,7 +16,7 @@
package android.view.textservice;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Binder;
import android.os.Handler;
import android.os.HandlerThread;
diff --git a/core/java/android/view/textservice/TextServicesManager.java b/core/java/android/view/textservice/TextServicesManager.java
index 9ff64d9b268a..acb35d63df9d 100644
--- a/core/java/android/view/textservice/TextServicesManager.java
+++ b/core/java/android/view/textservice/TextServicesManager.java
@@ -18,8 +18,8 @@ package android.view.textservice;
import android.annotation.NonNull;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.UserIdInt;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.Bundle;
import android.os.RemoteException;
diff --git a/core/java/android/webkit/CacheManager.java b/core/java/android/webkit/CacheManager.java
index 7e067197ced8..fafe81393888 100644
--- a/core/java/android/webkit/CacheManager.java
+++ b/core/java/android/webkit/CacheManager.java
@@ -17,7 +17,7 @@
package android.webkit;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import java.io.File;
import java.io.IOException;
diff --git a/core/java/android/webkit/ConsoleMessage.java b/core/java/android/webkit/ConsoleMessage.java
index e54849772f9a..5474557c9998 100644
--- a/core/java/android/webkit/ConsoleMessage.java
+++ b/core/java/android/webkit/ConsoleMessage.java
@@ -16,7 +16,7 @@
package android.webkit;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
/**
diff --git a/core/java/android/webkit/JsResult.java b/core/java/android/webkit/JsResult.java
index 5bf6aab3225d..448db58e2658 100644
--- a/core/java/android/webkit/JsResult.java
+++ b/core/java/android/webkit/JsResult.java
@@ -17,7 +17,7 @@
package android.webkit;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/**
* An instance of this class is passed as a parameter in various {@link WebChromeClient} action
diff --git a/core/java/android/webkit/PluginData.java b/core/java/android/webkit/PluginData.java
index 8aeeb1c53241..c9a196017a75 100644
--- a/core/java/android/webkit/PluginData.java
+++ b/core/java/android/webkit/PluginData.java
@@ -16,7 +16,8 @@
package android.webkit;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
+
import java.io.InputStream;
import java.util.Map;
diff --git a/core/java/android/webkit/URLUtil.java b/core/java/android/webkit/URLUtil.java
index 5d704cb09dcb..844b156b84d3 100644
--- a/core/java/android/webkit/URLUtil.java
+++ b/core/java/android/webkit/URLUtil.java
@@ -17,7 +17,7 @@
package android.webkit;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.net.ParseException;
import android.net.Uri;
import android.net.WebAddress;
diff --git a/core/java/android/webkit/UrlInterceptHandler.java b/core/java/android/webkit/UrlInterceptHandler.java
index f23aae6be8c2..a48e10799be7 100644
--- a/core/java/android/webkit/UrlInterceptHandler.java
+++ b/core/java/android/webkit/UrlInterceptHandler.java
@@ -17,9 +17,8 @@
package android.webkit;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.webkit.CacheManager.CacheResult;
-import android.webkit.PluginData;
import java.util.Map;
diff --git a/core/java/android/webkit/UrlInterceptRegistry.java b/core/java/android/webkit/UrlInterceptRegistry.java
index eeb28d73be85..c9dee00942c3 100644
--- a/core/java/android/webkit/UrlInterceptRegistry.java
+++ b/core/java/android/webkit/UrlInterceptRegistry.java
@@ -17,10 +17,8 @@
package android.webkit;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.webkit.CacheManager.CacheResult;
-import android.webkit.PluginData;
-import android.webkit.UrlInterceptHandler;
import java.util.Iterator;
import java.util.LinkedList;
diff --git a/core/java/android/webkit/WebResourceResponse.java b/core/java/android/webkit/WebResourceResponse.java
index 7c8f33e181d6..219523b15ab0 100644
--- a/core/java/android/webkit/WebResourceResponse.java
+++ b/core/java/android/webkit/WebResourceResponse.java
@@ -18,7 +18,7 @@ package android.webkit;
import android.annotation.NonNull;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import java.io.InputStream;
import java.io.StringBufferInputStream;
diff --git a/core/java/android/webkit/WebSettings.java b/core/java/android/webkit/WebSettings.java
index 2895621f962a..2d27a789ebcb 100644
--- a/core/java/android/webkit/WebSettings.java
+++ b/core/java/android/webkit/WebSettings.java
@@ -19,7 +19,7 @@ package android.webkit;
import android.annotation.IntDef;
import android.annotation.Nullable;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import java.lang.annotation.ElementType;
diff --git a/core/java/android/webkit/WebSyncManager.java b/core/java/android/webkit/WebSyncManager.java
index e44d6ebf37d1..7046c5108783 100644
--- a/core/java/android/webkit/WebSyncManager.java
+++ b/core/java/android/webkit/WebSyncManager.java
@@ -16,7 +16,7 @@
package android.webkit;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
/**
diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java
index 4b479270d9eb..f9a713ac7fcc 100644
--- a/core/java/android/webkit/WebView.java
+++ b/core/java/android/webkit/WebView.java
@@ -21,8 +21,8 @@ import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.Widget;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
diff --git a/core/java/android/webkit/WebViewDelegate.java b/core/java/android/webkit/WebViewDelegate.java
index f5657dff538f..df86926a95dc 100644
--- a/core/java/android/webkit/WebViewDelegate.java
+++ b/core/java/android/webkit/WebViewDelegate.java
@@ -19,10 +19,10 @@ package android.webkit;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityThread;
import android.app.Application;
import android.app.ResourcesManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.res.Resources;
diff --git a/core/java/android/webkit/WebViewFactory.java b/core/java/android/webkit/WebViewFactory.java
index 678a25223ef5..941af6ef1d7a 100644
--- a/core/java/android/webkit/WebViewFactory.java
+++ b/core/java/android/webkit/WebViewFactory.java
@@ -17,10 +17,10 @@
package android.webkit;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityManager;
import android.app.AppGlobals;
import android.app.Application;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
diff --git a/core/java/android/webkit/WebViewProviderInfo.java b/core/java/android/webkit/WebViewProviderInfo.java
index 7e00cded2c5a..6629fdc4cdee 100644
--- a/core/java/android/webkit/WebViewProviderInfo.java
+++ b/core/java/android/webkit/WebViewProviderInfo.java
@@ -17,7 +17,7 @@
package android.webkit;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.Signature;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/webkit/WebViewProviderResponse.java b/core/java/android/webkit/WebViewProviderResponse.java
index 5622abe0e99f..b58cc4bb1577 100644
--- a/core/java/android/webkit/WebViewProviderResponse.java
+++ b/core/java/android/webkit/WebViewProviderResponse.java
@@ -16,7 +16,7 @@
package android.webkit;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.PackageInfo;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/core/java/android/webkit/WebViewUpdateService.java b/core/java/android/webkit/WebViewUpdateService.java
index 12d3221fb7b5..9152b438618f 100644
--- a/core/java/android/webkit/WebViewUpdateService.java
+++ b/core/java/android/webkit/WebViewUpdateService.java
@@ -17,7 +17,7 @@
package android.webkit;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.RemoteException;
/**
diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java
index 6d60366dc72d..4752eadfe385 100644
--- a/core/java/android/widget/AbsListView.java
+++ b/core/java/android/widget/AbsListView.java
@@ -20,7 +20,7 @@ import android.annotation.ColorInt;
import android.annotation.DrawableRes;
import android.annotation.NonNull;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
diff --git a/core/java/android/widget/AbsSeekBar.java b/core/java/android/widget/AbsSeekBar.java
index bbcba2e12a2c..11a6acf5b934 100644
--- a/core/java/android/widget/AbsSeekBar.java
+++ b/core/java/android/widget/AbsSeekBar.java
@@ -18,7 +18,7 @@ package android.widget;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
diff --git a/core/java/android/widget/ActionMenuPresenter.java b/core/java/android/widget/ActionMenuPresenter.java
index cfb93ec2321f..aa3590aaff0a 100644
--- a/core/java/android/widget/ActionMenuPresenter.java
+++ b/core/java/android/widget/ActionMenuPresenter.java
@@ -22,7 +22,7 @@ import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
diff --git a/core/java/android/widget/ActionMenuView.java b/core/java/android/widget/ActionMenuView.java
index 7e58622db3b8..3a743562110f 100644
--- a/core/java/android/widget/ActionMenuView.java
+++ b/core/java/android/widget/ActionMenuView.java
@@ -18,7 +18,7 @@ package android.widget;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.StyleRes;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
diff --git a/core/java/android/widget/ActivityChooserModel.java b/core/java/android/widget/ActivityChooserModel.java
index f5bf7598aa5a..d87bdf482e43 100644
--- a/core/java/android/widget/ActivityChooserModel.java
+++ b/core/java/android/widget/ActivityChooserModel.java
@@ -16,8 +16,8 @@
package android.widget;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
diff --git a/core/java/android/widget/ActivityChooserView.java b/core/java/android/widget/ActivityChooserView.java
index 89ea0747b532..aa18d576c8f4 100644
--- a/core/java/android/widget/ActivityChooserView.java
+++ b/core/java/android/widget/ActivityChooserView.java
@@ -17,7 +17,7 @@
package android.widget;
import android.annotation.StringRes;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
diff --git a/core/java/android/widget/AdapterView.java b/core/java/android/widget/AdapterView.java
index c55f7d654548..52658404548c 100644
--- a/core/java/android/widget/AdapterView.java
+++ b/core/java/android/widget/AdapterView.java
@@ -18,7 +18,7 @@ package android.widget;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.database.DataSetObserver;
import android.os.Build;
diff --git a/core/java/android/widget/AnalogClock.java b/core/java/android/widget/AnalogClock.java
index 67a70b48b534..d165bd0f0fa7 100644
--- a/core/java/android/widget/AnalogClock.java
+++ b/core/java/android/widget/AnalogClock.java
@@ -16,7 +16,7 @@
package android.widget;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
diff --git a/core/java/android/widget/ArrayAdapter.java b/core/java/android/widget/ArrayAdapter.java
index f7225d036e15..de9f76d6eea1 100644
--- a/core/java/android/widget/ArrayAdapter.java
+++ b/core/java/android/widget/ArrayAdapter.java
@@ -21,7 +21,7 @@ import android.annotation.IdRes;
import android.annotation.LayoutRes;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
diff --git a/core/java/android/widget/AutoCompleteTextView.java b/core/java/android/widget/AutoCompleteTextView.java
index 8785251b0a64..8d9ae58be290 100644
--- a/core/java/android/widget/AutoCompleteTextView.java
+++ b/core/java/android/widget/AutoCompleteTextView.java
@@ -18,7 +18,7 @@ package android.widget;
import android.annotation.DrawableRes;
import android.annotation.IntDef;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.Resources.Theme;
import android.content.res.TypedArray;
diff --git a/core/java/android/widget/BaseAdapter.java b/core/java/android/widget/BaseAdapter.java
index 7b9365b08a41..27cf9a64a8d5 100644
--- a/core/java/android/widget/BaseAdapter.java
+++ b/core/java/android/widget/BaseAdapter.java
@@ -17,7 +17,7 @@
package android.widget;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.database.DataSetObservable;
import android.database.DataSetObserver;
import android.view.View;
diff --git a/core/java/android/widget/CalendarView.java b/core/java/android/widget/CalendarView.java
index b552aa6c85c4..4b2f738ef7ab 100644
--- a/core/java/android/widget/CalendarView.java
+++ b/core/java/android/widget/CalendarView.java
@@ -23,8 +23,8 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.StyleRes;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.Widget;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
diff --git a/core/java/android/widget/CheckedTextView.java b/core/java/android/widget/CheckedTextView.java
index 8b70f41f050c..422d2d37321c 100644
--- a/core/java/android/widget/CheckedTextView.java
+++ b/core/java/android/widget/CheckedTextView.java
@@ -19,7 +19,7 @@ package android.widget;
import android.annotation.DrawableRes;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
diff --git a/core/java/android/widget/RadioButton.java b/core/java/android/widget/RadioButton.java
index d44fbd7c6f8e..3e26f6369747 100644
--- a/core/java/android/widget/RadioButton.java
+++ b/core/java/android/widget/RadioButton.java
@@ -18,6 +18,7 @@ package android.widget;
import android.content.Context;
import android.util.AttributeSet;
+import android.view.accessibility.AccessibilityNodeInfo;
/**
@@ -38,19 +39,19 @@ import android.util.AttributeSet;
* guide.</p>
*
* <p><strong>XML attributes</strong></p>
- * <p>
- * See {@link android.R.styleable#CompoundButton CompoundButton Attributes},
- * {@link android.R.styleable#Button Button Attributes},
- * {@link android.R.styleable#TextView TextView Attributes},
+ * <p>
+ * See {@link android.R.styleable#CompoundButton CompoundButton Attributes},
+ * {@link android.R.styleable#Button Button Attributes},
+ * {@link android.R.styleable#TextView TextView Attributes},
* {@link android.R.styleable#View View Attributes}
* </p>
*/
public class RadioButton extends CompoundButton {
-
+
public RadioButton(Context context) {
this(context, null);
}
-
+
public RadioButton(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.radioButtonStyle);
}
@@ -81,4 +82,20 @@ public class RadioButton extends CompoundButton {
public CharSequence getAccessibilityClassName() {
return RadioButton.class.getName();
}
+
+ @Override
+ public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
+ super.onInitializeAccessibilityNodeInfo(info);
+ if (getParent() instanceof RadioGroup) {
+ RadioGroup radioGroup = (RadioGroup) getParent();
+ if (radioGroup.getOrientation() == LinearLayout.HORIZONTAL) {
+ info.setCollectionItemInfo(AccessibilityNodeInfo.CollectionItemInfo.obtain(0, 1,
+ radioGroup.getIndexWithinVisibleButtons(this), 1, false, isChecked()));
+ } else {
+ info.setCollectionItemInfo(AccessibilityNodeInfo.CollectionItemInfo.obtain(
+ radioGroup.getIndexWithinVisibleButtons(this), 1, 0, 1,
+ false, isChecked()));
+ }
+ }
+ }
}
diff --git a/core/java/android/widget/RadioGroup.java b/core/java/android/widget/RadioGroup.java
index c62c16c7e719..90bc0a3ee7b2 100644
--- a/core/java/android/widget/RadioGroup.java
+++ b/core/java/android/widget/RadioGroup.java
@@ -18,6 +18,7 @@ package android.widget;
import android.annotation.IdRes;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.TypedArray;
@@ -26,6 +27,7 @@ import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStructure;
+import android.view.accessibility.AccessibilityNodeInfo;
import android.view.autofill.AutofillManager;
import android.view.autofill.AutofillValue;
@@ -93,6 +95,7 @@ public class RadioGroup extends LinearLayout {
if (getImportantForAutofill() == IMPORTANT_FOR_AUTOFILL_AUTO) {
setImportantForAutofill(IMPORTANT_FOR_AUTOFILL_YES);
}
+ setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
// retrieve selected radio button as requested by the user in the
// XML layout file
@@ -475,4 +478,50 @@ public class RadioGroup extends LinearLayout {
}
return null;
}
-}
+
+ @Override
+ public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
+ super.onInitializeAccessibilityNodeInfo(info);
+ if (this.getOrientation() == HORIZONTAL) {
+ info.setCollectionInfo(AccessibilityNodeInfo.CollectionInfo.obtain(1,
+ getVisibleChildCount(), false,
+ AccessibilityNodeInfo.CollectionInfo.SELECTION_MODE_SINGLE));
+ } else {
+ info.setCollectionInfo(
+ AccessibilityNodeInfo.CollectionInfo.obtain(getVisibleChildCount(),
+ 1, false,
+ AccessibilityNodeInfo.CollectionInfo.SELECTION_MODE_SINGLE));
+ }
+ }
+
+ private int getVisibleChildCount() {
+ int count = 0;
+ for (int i = 0; i < getChildCount(); i++) {
+ if (this.getChildAt(i) instanceof RadioButton) {
+ if (((RadioButton) this.getChildAt(i)).getVisibility() == VISIBLE) {
+ count++;
+ }
+ }
+ }
+ return count;
+ }
+
+ int getIndexWithinVisibleButtons(@Nullable View child) {
+ if (!(child instanceof RadioButton)) {
+ return -1;
+ }
+ int index = 0;
+ for (int i = 0; i < getChildCount(); i++) {
+ if (this.getChildAt(i) instanceof RadioButton) {
+ RadioButton radioButton = (RadioButton) this.getChildAt(i);
+ if (radioButton == child) {
+ return index;
+ }
+ if (radioButton.getVisibility() == VISIBLE) {
+ index++;
+ }
+ }
+ }
+ return -1;
+ }
+} \ No newline at end of file
diff --git a/core/java/android/widget/RemoteViews.java b/core/java/android/widget/RemoteViews.java
index 7cec440dd80b..a6304b1a4f87 100644
--- a/core/java/android/widget/RemoteViews.java
+++ b/core/java/android/widget/RemoteViews.java
@@ -3575,7 +3575,6 @@ public class RemoteViews implements Parcelable, Filter {
@Override
public void onCancel() {
cancel(true);
- mCancelSignal.setOnCancelListener(null);
}
private CancellationSignal startTaskOnExecutor(Executor executor) {
diff --git a/core/java/android/widget/Switch.java b/core/java/android/widget/Switch.java
index ac2336c4a10f..fbd29ba2f592 100644
--- a/core/java/android/widget/Switch.java
+++ b/core/java/android/widget/Switch.java
@@ -309,6 +309,9 @@ public class Switch extends CompoundButton {
// Refresh display with current params
refreshDrawableState();
+ // Default state is derived from on/off-text, so state has to be updated when on/off-text
+ // are updated.
+ setDefaultStateDescritption();
setChecked(isChecked());
}
diff --git a/core/java/android/widget/Toast.java b/core/java/android/widget/Toast.java
index bdc2f9af2775..8f2133f85ba4 100644
--- a/core/java/android/widget/Toast.java
+++ b/core/java/android/widget/Toast.java
@@ -401,6 +401,7 @@ public class Toast {
params.format = PixelFormat.TRANSLUCENT;
params.windowAnimations = com.android.internal.R.style.Animation_Toast;
params.type = WindowManager.LayoutParams.TYPE_TOAST;
+ params.setFitIgnoreVisibility(true);
params.setTitle("Toast");
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
diff --git a/core/java/android/widget/ToggleButton.java b/core/java/android/widget/ToggleButton.java
index d47405b3b11e..59e0c16cde37 100644
--- a/core/java/android/widget/ToggleButton.java
+++ b/core/java/android/widget/ToggleButton.java
@@ -58,6 +58,9 @@ public class ToggleButton extends CompoundButton {
mTextOff = a.getText(com.android.internal.R.styleable.ToggleButton_textOff);
mDisabledAlpha = a.getFloat(com.android.internal.R.styleable.ToggleButton_disabledAlpha, 0.5f);
syncTextState();
+ // Default state is derived from on/off-text, so state has to be updated when on/off-text
+ // are updated.
+ setDefaultStateDescritption();
a.recycle();
}
diff --git a/telephony/java/com/android/ims/internal/uce/common/CapInfo.aidl b/core/java/com/android/ims/internal/uce/common/CapInfo.aidl
index 5b0ac1f4da99..5b0ac1f4da99 100644
--- a/telephony/java/com/android/ims/internal/uce/common/CapInfo.aidl
+++ b/core/java/com/android/ims/internal/uce/common/CapInfo.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/common/CapInfo.java b/core/java/com/android/ims/internal/uce/common/CapInfo.java
index a9847ba61cf6..a9847ba61cf6 100644
--- a/telephony/java/com/android/ims/internal/uce/common/CapInfo.java
+++ b/core/java/com/android/ims/internal/uce/common/CapInfo.java
diff --git a/telephony/java/com/android/ims/internal/uce/common/StatusCode.aidl b/core/java/com/android/ims/internal/uce/common/StatusCode.aidl
index e1e5798b4333..e1e5798b4333 100644
--- a/telephony/java/com/android/ims/internal/uce/common/StatusCode.aidl
+++ b/core/java/com/android/ims/internal/uce/common/StatusCode.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/common/StatusCode.java b/core/java/com/android/ims/internal/uce/common/StatusCode.java
index 7250eee70ecb..7250eee70ecb 100644
--- a/telephony/java/com/android/ims/internal/uce/common/StatusCode.java
+++ b/core/java/com/android/ims/internal/uce/common/StatusCode.java
diff --git a/telephony/java/com/android/ims/internal/uce/common/UceLong.aidl b/core/java/com/android/ims/internal/uce/common/UceLong.aidl
index 2a15f4214544..2a15f4214544 100644
--- a/telephony/java/com/android/ims/internal/uce/common/UceLong.aidl
+++ b/core/java/com/android/ims/internal/uce/common/UceLong.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/common/UceLong.java b/core/java/com/android/ims/internal/uce/common/UceLong.java
index 720789918e45..720789918e45 100644
--- a/telephony/java/com/android/ims/internal/uce/common/UceLong.java
+++ b/core/java/com/android/ims/internal/uce/common/UceLong.java
diff --git a/telephony/java/com/android/ims/internal/uce/options/IOptionsListener.aidl b/core/java/com/android/ims/internal/uce/options/IOptionsListener.aidl
index c69d5a94f760..c69d5a94f760 100644
--- a/telephony/java/com/android/ims/internal/uce/options/IOptionsListener.aidl
+++ b/core/java/com/android/ims/internal/uce/options/IOptionsListener.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/options/IOptionsService.aidl b/core/java/com/android/ims/internal/uce/options/IOptionsService.aidl
index 2e49082988c3..2e49082988c3 100644
--- a/telephony/java/com/android/ims/internal/uce/options/IOptionsService.aidl
+++ b/core/java/com/android/ims/internal/uce/options/IOptionsService.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/options/OptionsCapInfo.aidl b/core/java/com/android/ims/internal/uce/options/OptionsCapInfo.aidl
index 711c51679547..711c51679547 100644
--- a/telephony/java/com/android/ims/internal/uce/options/OptionsCapInfo.aidl
+++ b/core/java/com/android/ims/internal/uce/options/OptionsCapInfo.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/options/OptionsCapInfo.java b/core/java/com/android/ims/internal/uce/options/OptionsCapInfo.java
index bcb9f2d6284d..bcb9f2d6284d 100644
--- a/telephony/java/com/android/ims/internal/uce/options/OptionsCapInfo.java
+++ b/core/java/com/android/ims/internal/uce/options/OptionsCapInfo.java
diff --git a/telephony/java/com/android/ims/internal/uce/options/OptionsCmdId.aidl b/core/java/com/android/ims/internal/uce/options/OptionsCmdId.aidl
index e83e13e8fe44..e83e13e8fe44 100644
--- a/telephony/java/com/android/ims/internal/uce/options/OptionsCmdId.aidl
+++ b/core/java/com/android/ims/internal/uce/options/OptionsCmdId.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/options/OptionsCmdId.java b/core/java/com/android/ims/internal/uce/options/OptionsCmdId.java
index 14c64ac105bb..14c64ac105bb 100644
--- a/telephony/java/com/android/ims/internal/uce/options/OptionsCmdId.java
+++ b/core/java/com/android/ims/internal/uce/options/OptionsCmdId.java
diff --git a/telephony/java/com/android/ims/internal/uce/options/OptionsCmdStatus.aidl b/core/java/com/android/ims/internal/uce/options/OptionsCmdStatus.aidl
index 1d30a9b2547e..1d30a9b2547e 100644
--- a/telephony/java/com/android/ims/internal/uce/options/OptionsCmdStatus.aidl
+++ b/core/java/com/android/ims/internal/uce/options/OptionsCmdStatus.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/options/OptionsCmdStatus.java b/core/java/com/android/ims/internal/uce/options/OptionsCmdStatus.java
index 4af3e6e3cea4..4af3e6e3cea4 100644
--- a/telephony/java/com/android/ims/internal/uce/options/OptionsCmdStatus.java
+++ b/core/java/com/android/ims/internal/uce/options/OptionsCmdStatus.java
diff --git a/telephony/java/com/android/ims/internal/uce/options/OptionsSipResponse.aidl b/core/java/com/android/ims/internal/uce/options/OptionsSipResponse.aidl
index 6e9583d9c0b8..6e9583d9c0b8 100644
--- a/telephony/java/com/android/ims/internal/uce/options/OptionsSipResponse.aidl
+++ b/core/java/com/android/ims/internal/uce/options/OptionsSipResponse.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/options/OptionsSipResponse.java b/core/java/com/android/ims/internal/uce/options/OptionsSipResponse.java
index c5f333d35ba5..c5f333d35ba5 100644
--- a/telephony/java/com/android/ims/internal/uce/options/OptionsSipResponse.java
+++ b/core/java/com/android/ims/internal/uce/options/OptionsSipResponse.java
diff --git a/telephony/java/com/android/ims/internal/uce/presence/IPresenceListener.aidl b/core/java/com/android/ims/internal/uce/presence/IPresenceListener.aidl
index 65e7fc9756bb..65e7fc9756bb 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/IPresenceListener.aidl
+++ b/core/java/com/android/ims/internal/uce/presence/IPresenceListener.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/presence/IPresenceService.aidl b/core/java/com/android/ims/internal/uce/presence/IPresenceService.aidl
index 26a3e83efcfa..26a3e83efcfa 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/IPresenceService.aidl
+++ b/core/java/com/android/ims/internal/uce/presence/IPresenceService.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresCapInfo.aidl b/core/java/com/android/ims/internal/uce/presence/PresCapInfo.aidl
index df9d75a4b7e9..df9d75a4b7e9 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresCapInfo.aidl
+++ b/core/java/com/android/ims/internal/uce/presence/PresCapInfo.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresCapInfo.java b/core/java/com/android/ims/internal/uce/presence/PresCapInfo.java
index 745df5b71aa7..745df5b71aa7 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresCapInfo.java
+++ b/core/java/com/android/ims/internal/uce/presence/PresCapInfo.java
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresCmdId.aidl b/core/java/com/android/ims/internal/uce/presence/PresCmdId.aidl
index 6ece045ffcf7..6ece045ffcf7 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresCmdId.aidl
+++ b/core/java/com/android/ims/internal/uce/presence/PresCmdId.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresCmdId.java b/core/java/com/android/ims/internal/uce/presence/PresCmdId.java
index 41020ec5b49b..41020ec5b49b 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresCmdId.java
+++ b/core/java/com/android/ims/internal/uce/presence/PresCmdId.java
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresCmdStatus.aidl b/core/java/com/android/ims/internal/uce/presence/PresCmdStatus.aidl
index 69bca2f9af0d..69bca2f9af0d 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresCmdStatus.aidl
+++ b/core/java/com/android/ims/internal/uce/presence/PresCmdStatus.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresCmdStatus.java b/core/java/com/android/ims/internal/uce/presence/PresCmdStatus.java
index ff8069c569ff..ff8069c569ff 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresCmdStatus.java
+++ b/core/java/com/android/ims/internal/uce/presence/PresCmdStatus.java
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresPublishTriggerType.aidl b/core/java/com/android/ims/internal/uce/presence/PresPublishTriggerType.aidl
index 0fc0f1b5b375..0fc0f1b5b375 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresPublishTriggerType.aidl
+++ b/core/java/com/android/ims/internal/uce/presence/PresPublishTriggerType.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresPublishTriggerType.java b/core/java/com/android/ims/internal/uce/presence/PresPublishTriggerType.java
index 87193e36ce90..87193e36ce90 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresPublishTriggerType.java
+++ b/core/java/com/android/ims/internal/uce/presence/PresPublishTriggerType.java
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresResInfo.aidl b/core/java/com/android/ims/internal/uce/presence/PresResInfo.aidl
index 2b7b3bbd8733..2b7b3bbd8733 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresResInfo.aidl
+++ b/core/java/com/android/ims/internal/uce/presence/PresResInfo.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresResInfo.java b/core/java/com/android/ims/internal/uce/presence/PresResInfo.java
index 237c9994451a..237c9994451a 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresResInfo.java
+++ b/core/java/com/android/ims/internal/uce/presence/PresResInfo.java
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresResInstanceInfo.aidl b/core/java/com/android/ims/internal/uce/presence/PresResInstanceInfo.aidl
index 3a0cfc44aa98..3a0cfc44aa98 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresResInstanceInfo.aidl
+++ b/core/java/com/android/ims/internal/uce/presence/PresResInstanceInfo.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresResInstanceInfo.java b/core/java/com/android/ims/internal/uce/presence/PresResInstanceInfo.java
index 29699ea6c802..29699ea6c802 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresResInstanceInfo.java
+++ b/core/java/com/android/ims/internal/uce/presence/PresResInstanceInfo.java
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresRlmiInfo.aidl b/core/java/com/android/ims/internal/uce/presence/PresRlmiInfo.aidl
index 2689c2dce1ac..2689c2dce1ac 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresRlmiInfo.aidl
+++ b/core/java/com/android/ims/internal/uce/presence/PresRlmiInfo.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresRlmiInfo.java b/core/java/com/android/ims/internal/uce/presence/PresRlmiInfo.java
index ab46e4b6295e..ab46e4b6295e 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresRlmiInfo.java
+++ b/core/java/com/android/ims/internal/uce/presence/PresRlmiInfo.java
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresServiceInfo.aidl b/core/java/com/android/ims/internal/uce/presence/PresServiceInfo.aidl
index 91ddf866734d..91ddf866734d 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresServiceInfo.aidl
+++ b/core/java/com/android/ims/internal/uce/presence/PresServiceInfo.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresServiceInfo.java b/core/java/com/android/ims/internal/uce/presence/PresServiceInfo.java
index 83ba722fe2f1..83ba722fe2f1 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresServiceInfo.java
+++ b/core/java/com/android/ims/internal/uce/presence/PresServiceInfo.java
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresSipResponse.aidl b/core/java/com/android/ims/internal/uce/presence/PresSipResponse.aidl
index 7dfff3db9a1d..7dfff3db9a1d 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresSipResponse.aidl
+++ b/core/java/com/android/ims/internal/uce/presence/PresSipResponse.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresSipResponse.java b/core/java/com/android/ims/internal/uce/presence/PresSipResponse.java
index 5e4259297d74..5e4259297d74 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresSipResponse.java
+++ b/core/java/com/android/ims/internal/uce/presence/PresSipResponse.java
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresSubscriptionState.aidl b/core/java/com/android/ims/internal/uce/presence/PresSubscriptionState.aidl
index 7bff24ab6974..7bff24ab6974 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresSubscriptionState.aidl
+++ b/core/java/com/android/ims/internal/uce/presence/PresSubscriptionState.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresSubscriptionState.java b/core/java/com/android/ims/internal/uce/presence/PresSubscriptionState.java
index bee928c3280a..bee928c3280a 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresSubscriptionState.java
+++ b/core/java/com/android/ims/internal/uce/presence/PresSubscriptionState.java
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresTupleInfo.aidl b/core/java/com/android/ims/internal/uce/presence/PresTupleInfo.aidl
index 6571ebe8b74c..6571ebe8b74c 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresTupleInfo.aidl
+++ b/core/java/com/android/ims/internal/uce/presence/PresTupleInfo.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/presence/PresTupleInfo.java b/core/java/com/android/ims/internal/uce/presence/PresTupleInfo.java
index 7a47786b5af6..7a47786b5af6 100644
--- a/telephony/java/com/android/ims/internal/uce/presence/PresTupleInfo.java
+++ b/core/java/com/android/ims/internal/uce/presence/PresTupleInfo.java
diff --git a/telephony/java/com/android/ims/internal/uce/uceservice/IUceListener.aidl b/core/java/com/android/ims/internal/uce/uceservice/IUceListener.aidl
index 41abf7d1a1f0..41abf7d1a1f0 100644
--- a/telephony/java/com/android/ims/internal/uce/uceservice/IUceListener.aidl
+++ b/core/java/com/android/ims/internal/uce/uceservice/IUceListener.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/uceservice/IUceService.aidl b/core/java/com/android/ims/internal/uce/uceservice/IUceService.aidl
index ec45371689cf..ec45371689cf 100644
--- a/telephony/java/com/android/ims/internal/uce/uceservice/IUceService.aidl
+++ b/core/java/com/android/ims/internal/uce/uceservice/IUceService.aidl
diff --git a/telephony/java/com/android/ims/internal/uce/uceservice/ImsUceManager.java b/core/java/com/android/ims/internal/uce/uceservice/ImsUceManager.java
index 4b0b098d4e5b..4b0b098d4e5b 100644
--- a/telephony/java/com/android/ims/internal/uce/uceservice/ImsUceManager.java
+++ b/core/java/com/android/ims/internal/uce/uceservice/ImsUceManager.java
diff --git a/telephony/java/com/android/ims/internal/uce/uceservice/UceServiceBase.java b/core/java/com/android/ims/internal/uce/uceservice/UceServiceBase.java
index ceb191910427..ceb191910427 100644
--- a/telephony/java/com/android/ims/internal/uce/uceservice/UceServiceBase.java
+++ b/core/java/com/android/ims/internal/uce/uceservice/UceServiceBase.java
diff --git a/core/java/com/android/internal/accessibility/AccessibilityShortcutController.java b/core/java/com/android/internal/accessibility/AccessibilityShortcutController.java
index 0b15cd06a7ea..3fdedc88fe53 100644
--- a/core/java/com/android/internal/accessibility/AccessibilityShortcutController.java
+++ b/core/java/com/android/internal/accessibility/AccessibilityShortcutController.java
@@ -17,6 +17,7 @@
package com.android.internal.accessibility;
import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG;
+import static android.view.accessibility.AccessibilityManager.ACCESSIBILITY_SHORTCUT_KEY;
import static com.android.internal.util.ArrayUtils.convertToLongArray;
@@ -34,6 +35,7 @@ import android.media.AudioAttributes;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
+import android.os.Build;
import android.os.Handler;
import android.os.UserHandle;
import android.os.Vibrator;
@@ -52,11 +54,12 @@ import com.android.internal.R;
import com.android.internal.util.function.pooled.PooledLambda;
import java.util.Collections;
+import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
- * Class to help manage the accessibility shortcut
+ * Class to help manage the accessibility shortcut key
*/
public class AccessibilityShortcutController {
private static final String TAG = "AccessibilityShortcutController";
@@ -66,6 +69,8 @@ public class AccessibilityShortcutController {
new ComponentName("com.android.server.accessibility", "ColorInversion");
public static final ComponentName DALTONIZER_COMPONENT_NAME =
new ComponentName("com.android.server.accessibility", "Daltonizer");
+ public static final String MAGNIFICATION_CONTROLLER_NAME =
+ "com.android.server.accessibility.MagnificationController";
private static final AudioAttributes VIBRATION_ATTRIBUTES = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
@@ -84,26 +89,6 @@ public class AccessibilityShortcutController {
public FrameworkObjectProvider mFrameworkObjectProvider = new FrameworkObjectProvider();
/**
- * Get the component name string for the service or feature currently assigned to the
- * accessiblity shortcut
- *
- * @param context A valid context
- * @param userId The user ID of interest
- * @return The flattened component name string of the service selected by the user, or the
- * string for the default service if the user has not made a selection
- */
- public static String getTargetServiceComponentNameString(
- Context context, int userId) {
- final String currentShortcutServiceId = Settings.Secure.getStringForUser(
- context.getContentResolver(), Settings.Secure.ACCESSIBILITY_SHORTCUT_TARGET_SERVICE,
- userId);
- if (currentShortcutServiceId != null) {
- return currentShortcutServiceId;
- }
- return context.getString(R.string.config_defaultAccessibilityService);
- }
-
- /**
* @return An immutable map from dummy component names to feature info for toggling a framework
* feature
*/
@@ -163,7 +148,7 @@ public class AccessibilityShortcutController {
/**
* Check if the shortcut is available.
*
- * @param onLockScreen Whether or not the phone is currently locked.
+ * @param phoneLocked Whether or not the phone is currently locked.
*
* @return {@code true} if the shortcut is available
*/
@@ -172,8 +157,7 @@ public class AccessibilityShortcutController {
}
public void onSettingsChanged() {
- final boolean haveValidService =
- !TextUtils.isEmpty(getTargetServiceComponentNameString(mContext, mUserId));
+ final boolean hasShortcutTarget = hasShortcutTarget();
final ContentResolver cr = mContext.getContentResolver();
final boolean enabled = Settings.Secure.getIntForUser(
cr, Settings.Secure.ACCESSIBILITY_SHORTCUT_ENABLED, 1, mUserId) == 1;
@@ -183,7 +167,7 @@ public class AccessibilityShortcutController {
mEnabledOnLockScreen = Settings.Secure.getIntForUser(
cr, Settings.Secure.ACCESSIBILITY_SHORTCUT_ON_LOCK_SCREEN,
dialogAlreadyShown, mUserId) == 1;
- mIsShortcutEnabled = enabled && haveValidService;
+ mIsShortcutEnabled = enabled && hasShortcutTarget;
}
/**
@@ -205,7 +189,6 @@ public class AccessibilityShortcutController {
vibrator.vibrate(vibePattern, -1, VIBRATION_ATTRIBUTES);
}
-
if (dialogAlreadyShown == 0) {
// The first time, we show a warning rather than toggle the service to give the user a
// chance to turn off this feature before stuff gets enabled.
@@ -229,32 +212,44 @@ public class AccessibilityShortcutController {
mAlertDialog.dismiss();
mAlertDialog = null;
}
-
- // Show a toast alerting the user to what's happening
- final String serviceName = getShortcutFeatureDescription(false /* no summary */);
- if (serviceName == null) {
- Slog.e(TAG, "Accessibility shortcut set to invalid service");
- return;
- }
- // For accessibility services, show a toast explaining what we're doing.
- final AccessibilityServiceInfo serviceInfo = getInfoForTargetService();
- if (serviceInfo != null) {
- String toastMessageFormatString = mContext.getString(isServiceEnabled(serviceInfo)
- ? R.string.accessibility_shortcut_disabling_service
- : R.string.accessibility_shortcut_enabling_service);
- String toastMessage = String.format(toastMessageFormatString, serviceName);
- Toast warningToast = mFrameworkObjectProvider.makeToastFromText(
- mContext, toastMessage, Toast.LENGTH_LONG);
- warningToast.getWindowParams().privateFlags |=
- WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS;
- warningToast.show();
- }
-
+ showToast();
mFrameworkObjectProvider.getAccessibilityManagerInstance(mContext)
.performAccessibilityShortcut();
}
}
+ /**
+ * Show toast if current assigned shortcut target is an accessibility service and its target
+ * sdk version is less than or equal to Q, or greater than Q and does not request
+ * accessibility button.
+ */
+ private void showToast() {
+ final AccessibilityServiceInfo serviceInfo = getInfoForTargetService();
+ if (serviceInfo == null) {
+ return;
+ }
+ final String serviceName = getShortcutFeatureDescription(/* no summary */ false);
+ if (serviceName == null) {
+ return;
+ }
+ final boolean requestA11yButton = (serviceInfo.flags
+ & AccessibilityServiceInfo.FLAG_REQUEST_ACCESSIBILITY_BUTTON) != 0;
+ if (serviceInfo.getResolveInfo().serviceInfo.applicationInfo
+ .targetSdkVersion > Build.VERSION_CODES.Q && requestA11yButton) {
+ return;
+ }
+ // For accessibility services, show a toast explaining what we're doing.
+ String toastMessageFormatString = mContext.getString(isServiceEnabled(serviceInfo)
+ ? R.string.accessibility_shortcut_disabling_service
+ : R.string.accessibility_shortcut_enabling_service);
+ String toastMessage = String.format(toastMessageFormatString, serviceName);
+ Toast warningToast = mFrameworkObjectProvider.makeToastFromText(
+ mContext, toastMessage, Toast.LENGTH_LONG);
+ warningToast.getWindowParams().privateFlags |=
+ WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS;
+ warningToast.show();
+ }
+
private AlertDialog createShortcutWarningDialog(int userId) {
final String serviceDescription = getShortcutFeatureDescription(true /* Include summary */);
@@ -288,25 +283,21 @@ public class AccessibilityShortcutController {
}
private AccessibilityServiceInfo getInfoForTargetService() {
- final String currentShortcutServiceString = getTargetServiceComponentNameString(
- mContext, UserHandle.USER_CURRENT);
- if (currentShortcutServiceString == null) {
+ final ComponentName targetComponentName = getShortcutTargetComponentName();
+ if (targetComponentName == null) {
return null;
}
AccessibilityManager accessibilityManager =
mFrameworkObjectProvider.getAccessibilityManagerInstance(mContext);
return accessibilityManager.getInstalledServiceInfoWithComponentName(
- ComponentName.unflattenFromString(currentShortcutServiceString));
+ targetComponentName);
}
private String getShortcutFeatureDescription(boolean includeSummary) {
- final String currentShortcutServiceString = getTargetServiceComponentNameString(
- mContext, UserHandle.USER_CURRENT);
- if (currentShortcutServiceString == null) {
+ final ComponentName targetComponentName = getShortcutTargetComponentName();
+ if (targetComponentName == null) {
return null;
}
- final ComponentName targetComponentName =
- ComponentName.unflattenFromString(currentShortcutServiceString);
final ToggleableFrameworkFeatureInfo frameworkFeatureInfo =
getFrameworkShortcutFeaturesMap().get(targetComponentName);
if (frameworkFeatureInfo != null) {
@@ -372,6 +363,36 @@ public class AccessibilityShortcutController {
}
/**
+ * Returns {@code true} if any shortcut targets were assigned to accessibility shortcut key.
+ */
+ private boolean hasShortcutTarget() {
+ // AccessibilityShortcutController is initialized earlier than AccessibilityManagerService.
+ // AccessibilityManager#getAccessibilityShortcutTargets may not return correct shortcut
+ // targets during boot. Needs to read settings directly here.
+ String shortcutTargets = Settings.Secure.getStringForUser(mContext.getContentResolver(),
+ Settings.Secure.ACCESSIBILITY_SHORTCUT_TARGET_SERVICE, mUserId);
+ if (TextUtils.isEmpty(shortcutTargets)) {
+ shortcutTargets = mContext.getString(R.string.config_defaultAccessibilityService);
+ }
+ return !TextUtils.isEmpty(shortcutTargets);
+ }
+
+ /**
+ * Gets the component name of the shortcut target.
+ *
+ * @return The component name, or null if it's assigned by multiple targets.
+ */
+ private ComponentName getShortcutTargetComponentName() {
+ final List<String> shortcutTargets = mFrameworkObjectProvider
+ .getAccessibilityManagerInstance(mContext)
+ .getAccessibilityShortcutTargets(ACCESSIBILITY_SHORTCUT_KEY);
+ if (shortcutTargets.size() != 1) {
+ return null;
+ }
+ return ComponentName.unflattenFromString(shortcutTargets.get(0));
+ }
+
+ /**
* Class to wrap TextToSpeech for shortcut dialog spoken feedback.
*/
private class TtsPrompt implements TextToSpeech.OnInitListener {
diff --git a/core/java/com/android/internal/app/AbstractMultiProfilePagerAdapter.java b/core/java/com/android/internal/app/AbstractMultiProfilePagerAdapter.java
new file mode 100644
index 000000000000..08022e983892
--- /dev/null
+++ b/core/java/com/android/internal/app/AbstractMultiProfilePagerAdapter.java
@@ -0,0 +1,163 @@
+/*
+ * Copyright (C) 2019 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 com.android.internal.app;
+
+import android.annotation.IntDef;
+import android.annotation.Nullable;
+import android.content.Context;
+import android.os.UserHandle;
+import android.view.View;
+import android.view.ViewGroup;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.widget.PagerAdapter;
+import com.android.internal.widget.ViewPager;
+
+import java.util.Objects;
+
+/**
+ * Skeletal {@link PagerAdapter} implementation of a work or personal profile page for
+ * intent resolution (including share sheet).
+ */
+public abstract class AbstractMultiProfilePagerAdapter extends PagerAdapter {
+
+ static final int PROFILE_PERSONAL = 0;
+ static final int PROFILE_WORK = 1;
+ @IntDef({PROFILE_PERSONAL, PROFILE_WORK})
+ @interface Profile {}
+
+ private final Context mContext;
+ private int mCurrentPage;
+
+ AbstractMultiProfilePagerAdapter(Context context, int currentPage) {
+ mContext = Objects.requireNonNull(context);
+ mCurrentPage = currentPage;
+ }
+
+ Context getContext() {
+ return mContext;
+ }
+
+ /**
+ * Sets this instance of this class as {@link ViewPager}'s {@link PagerAdapter} and sets
+ * an {@link ViewPager.OnPageChangeListener} where it keeps track of the currently displayed
+ * page and rebuilds the list.
+ */
+ void setupViewPager(ViewPager viewPager) {
+ viewPager.setCurrentItem(mCurrentPage);
+ viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
+ @Override
+ public void onPageSelected(int position) {
+ mCurrentPage = position;
+ getActiveListAdapter().rebuildList();
+ }
+ });
+ viewPager.setAdapter(this);
+ }
+
+ @Override
+ public ViewGroup instantiateItem(ViewGroup container, int position) {
+ final ProfileDescriptor profileDescriptor = getItem(position);
+ setupListAdapter(position);
+ container.addView(profileDescriptor.rootView);
+ return profileDescriptor.rootView;
+ }
+
+ @Override
+ public void destroyItem(ViewGroup container, int position, Object view) {
+ container.removeView((View) view);
+ }
+
+ @Override
+ public int getCount() {
+ return getItemCount();
+ }
+
+ protected int getCurrentPage() {
+ return mCurrentPage;
+ }
+
+ UserHandle getCurrentUserHandle() {
+ return getActiveListAdapter().mResolverListController.getUserHandle();
+ }
+
+ @Override
+ public boolean isViewFromObject(View view, Object object) {
+ return view == object;
+ }
+
+ @Override
+ public CharSequence getPageTitle(int position) {
+ return null;
+ }
+
+ /**
+ * Returns the {@link ProfileDescriptor} relevant to the given <code>pageIndex</code>.
+ * <ul>
+ * <li>For a device with only one user, <code>pageIndex</code> value of
+ * <code>0</code> would return the personal profile {@link ProfileDescriptor}.</li>
+ * <li>For a device with a work profile, <code>pageIndex</code> value of <code>0</code> would
+ * return the personal profile {@link ProfileDescriptor}, and <code>pageIndex</code> value of
+ * <code>1</code> would return the work profile {@link ProfileDescriptor}.</li>
+ * </ul>
+ */
+ abstract ProfileDescriptor getItem(int pageIndex);
+
+ /**
+ * Returns the number of {@link ProfileDescriptor} objects.
+ * <p>For a normal consumer device with only one user returns <code>1</code>.
+ * <p>For a device with a work profile returns <code>2</code>.
+ */
+ abstract int getItemCount();
+
+ /**
+ * Responsible for assigning an adapter to the list view for the relevant page, specified by
+ * <code>pageIndex</code>, and other list view-related initialization procedures.
+ */
+ abstract void setupListAdapter(int pageIndex);
+
+ /**
+ * Returns the adapter of the list view for the relevant page specified by
+ * <code>pageIndex</code>.
+ * <p>This method is meant to be implemented with an implementation-specific return type
+ * depending on the adapter type.
+ */
+ abstract Object getAdapterForIndex(int pageIndex);
+
+ @VisibleForTesting
+ public abstract ResolverListAdapter getActiveListAdapter();
+
+ /**
+ * If this is a device with a work profile, returns the {@link ResolverListAdapter} instance
+ * of the profile that is not the active one. Otherwise returns {@code null}. For example,
+ * if the share sheet is launched in the work profile, this method returns the personal
+ * profile {@link ResolverListAdapter}.
+ * @see #getActiveListAdapter()
+ */
+ @VisibleForTesting
+ public abstract @Nullable ResolverListAdapter getInactiveListAdapter();
+
+ abstract Object getCurrentRootAdapter();
+
+ abstract ViewGroup getCurrentAdapterView();
+
+ protected class ProfileDescriptor {
+ final ViewGroup rootView;
+ ProfileDescriptor(ViewGroup rootView) {
+ this.rootView = rootView;
+ }
+ }
+} \ No newline at end of file
diff --git a/core/java/com/android/internal/app/AbstractResolverComparator.java b/core/java/com/android/internal/app/AbstractResolverComparator.java
index bb7e4d5114ba..eb746127a351 100644
--- a/core/java/com/android/internal/app/AbstractResolverComparator.java
+++ b/core/java/com/android/internal/app/AbstractResolverComparator.java
@@ -263,6 +263,7 @@ public abstract class AbstractResolverComparator implements Comparator<ResolvedC
mHandler.removeMessages(RANKER_SERVICE_RESULT);
mHandler.removeMessages(RANKER_RESULT_TIMEOUT);
afterCompute();
+ mAfterCompute = null;
}
private boolean isDefaultBrowser(ResolveInfo ri) {
diff --git a/core/java/com/android/internal/app/ChooserActivity.java b/core/java/com/android/internal/app/ChooserActivity.java
index 183e9a6faf09..48853bfe116a 100644
--- a/core/java/com/android/internal/app/ChooserActivity.java
+++ b/core/java/com/android/internal/app/ChooserActivity.java
@@ -98,6 +98,7 @@ import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
+import android.view.WindowInsets;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
@@ -110,6 +111,7 @@ import com.android.internal.app.ResolverListAdapter.ActivityInfoPresentationGett
import com.android.internal.app.ResolverListAdapter.ViewHolder;
import com.android.internal.app.chooser.ChooserTargetInfo;
import com.android.internal.app.chooser.DisplayResolveInfo;
+import com.android.internal.app.chooser.MultiDisplayResolveInfo;
import com.android.internal.app.chooser.NotSelectableTargetInfo;
import com.android.internal.app.chooser.SelectableTargetInfo;
import com.android.internal.app.chooser.SelectableTargetInfo.SelectableTargetInfoCommunicator;
@@ -173,7 +175,6 @@ public class ChooserActivity extends ResolverActivity implements
@VisibleForTesting
public static final int LIST_VIEW_UPDATE_INTERVAL_IN_MILLIS = 250;
- private static final int SINGLE_CELL_SPAN_SIZE = 1;
private boolean mIsAppPredictorComponentAvailable;
private AppPredictor mAppPredictor;
@@ -229,9 +230,6 @@ public class ChooserActivity extends ResolverActivity implements
private long mQueriedTargetServicesTimeMs;
private long mQueriedSharingShortcutsTimeMs;
- private RecyclerView mRecyclerView;
- private ChooserListAdapter mChooserListAdapter;
- private ChooserGridAdapter mChooserGridAdapter;
private int mChooserRowServiceSpacing;
private int mCurrAvailableWidth = 0;
@@ -265,6 +263,9 @@ public class ChooserActivity extends ResolverActivity implements
private ContentPreviewCoordinator mPreviewCoord;
+ @VisibleForTesting
+ protected ChooserMultiProfilePagerAdapter mChooserMultiProfilePagerAdapter;
+
private class ContentPreviewCoordinator {
private static final int IMAGE_FADE_IN_MILLIS = 150;
private static final int IMAGE_LOAD_TIMEOUT = 1;
@@ -362,9 +363,7 @@ public class ChooserActivity extends ResolverActivity implements
Log.i(TAG, "Hiding image preview area. Timed out waiting for preview to load"
+ " within " + mImageLoadTimeoutMillis + "ms.");
collapseParentView();
- if (mChooserGridAdapter != null) {
- mChooserGridAdapter.hideContentPreview();
- }
+ hideContentPreview();
mHideParentOnFail = false;
}
}
@@ -431,13 +430,14 @@ public class ChooserActivity extends ResolverActivity implements
logDirectShareTargetReceived(
MetricsEvent.ACTION_DIRECT_SHARE_TARGETS_LOADED_CHOOSER_SERVICE);
sendVoiceChoicesIfNeeded();
- mChooserListAdapter.completeServiceTargetLoading();
+ mChooserMultiProfilePagerAdapter.getActiveListAdapter()
+ .completeServiceTargetLoading();
}
}
@Override
public void handleMessage(Message msg) {
- if (mChooserListAdapter == null || isDestroyed()) {
+ if (mChooserMultiProfilePagerAdapter.getActiveListAdapter() == null || isDestroyed()) {
return;
}
@@ -452,8 +452,10 @@ public class ChooserActivity extends ResolverActivity implements
break;
}
if (sri.resultTargets != null) {
- mChooserListAdapter.addServiceResults(sri.originalTarget,
- sri.resultTargets, TARGET_TYPE_CHOOSER_TARGET);
+ // TODO(arangelov): Instead of using getCurrentListAdapter(), pass the
+ // profileId as part of the message.
+ mChooserMultiProfilePagerAdapter.getActiveListAdapter().addServiceResults(
+ sri.originalTarget, sri.resultTargets, TARGET_TYPE_CHOOSER_TARGET);
}
unbindService(sri.connection);
sri.connection.destroy();
@@ -476,15 +478,15 @@ public class ChooserActivity extends ResolverActivity implements
Log.d(TAG, "LIST_VIEW_UPDATE_MESSAGE; ");
}
- mChooserListAdapter.refreshListView();
+ mChooserMultiProfilePagerAdapter.getActiveListAdapter().refreshListView();
break;
case SHORTCUT_MANAGER_SHARE_TARGET_RESULT:
if (DEBUG) Log.d(TAG, "SHORTCUT_MANAGER_SHARE_TARGET_RESULT");
final ServiceResultInfo resultInfo = (ServiceResultInfo) msg.obj;
if (resultInfo.resultTargets != null) {
- mChooserListAdapter.addServiceResults(resultInfo.originalTarget,
- resultInfo.resultTargets, msg.arg1);
+ mChooserMultiProfilePagerAdapter.getActiveListAdapter().addServiceResults(
+ resultInfo.originalTarget, resultInfo.resultTargets, msg.arg1);
}
break;
@@ -504,6 +506,7 @@ public class ChooserActivity extends ResolverActivity implements
protected void onCreate(Bundle savedInstanceState) {
final long intentReceivedTime = System.currentTimeMillis();
// This is the only place this value is being set. Effectively final.
+ //TODO(arangelov) - should there be a mIsAppPredictorComponentAvailable flag for work tab?
mIsAppPredictorComponentAvailable = isAppPredictionServiceAvailable();
mIsSuccessfullySelected = false;
@@ -638,19 +641,24 @@ public class ChooserActivity extends ResolverActivity implements
if (appPredictor != null) {
mDirectShareAppTargetCache = new HashMap<>();
mAppPredictorCallback = resultList -> {
+ //TODO(arangelov) Take care of edge case when callback called after swiping tabs
if (isFinishing() || isDestroyed()) {
return;
}
- if (mChooserListAdapter.getCount() == 0) {
+ if (mChooserMultiProfilePagerAdapter.getActiveListAdapter().getCount() == 0) {
return;
}
if (resultList.isEmpty()) {
// APS may be disabled, so try querying targets ourselves.
- queryDirectShareTargets(mChooserListAdapter, true);
+ //TODO(arangelov) queryDirectShareTargets indirectly uses mIntents.
+ // Investigate implications for work tab.
+ queryDirectShareTargets(
+ mChooserMultiProfilePagerAdapter.getActiveListAdapter(), true);
return;
}
final List<DisplayResolveInfo> driList =
- getDisplayResolveInfos(mChooserListAdapter);
+ getDisplayResolveInfos(
+ mChooserMultiProfilePagerAdapter.getActiveListAdapter());
final List<ShortcutManager.ShareShortcutInfo> shareShortcutInfos =
new ArrayList<>();
for (AppTarget appTarget : resultList) {
@@ -684,21 +692,22 @@ public class ChooserActivity extends ResolverActivity implements
final float chooserHeaderScrollElevation =
getResources().getDimensionPixelSize(R.dimen.chooser_header_scroll_elevation);
- mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
- public void onScrollStateChanged(RecyclerView view, int scrollState) {
- }
-
- public void onScrolled(RecyclerView view, int dx, int dy) {
- if (view.getChildCount() > 0) {
- View child = view.getLayoutManager().findViewByPosition(0);
- if (child == null || child.getTop() < 0) {
- chooserHeader.setElevation(chooserHeaderScrollElevation);
- return;
+ mChooserMultiProfilePagerAdapter.getCurrentAdapterView().addOnScrollListener(
+ new RecyclerView.OnScrollListener() {
+ public void onScrollStateChanged(RecyclerView view, int scrollState) {
}
- }
- chooserHeader.setElevation(defaultElevation);
- }
+ public void onScrolled(RecyclerView view, int dx, int dy) {
+ if (view.getChildCount() > 0) {
+ View child = view.getLayoutManager().findViewByPosition(0);
+ if (child == null || child.getTop() < 0) {
+ chooserHeader.setElevation(chooserHeaderScrollElevation);
+ return;
+ }
+ }
+
+ chooserHeader.setElevation(defaultElevation);
+ }
});
mResolverDrawerLayout.setOnCollapsedChangedListener(
@@ -738,6 +747,71 @@ public class ChooserActivity extends ResolverActivity implements
return context.getSharedPreferences(prefsFile, MODE_PRIVATE);
}
+ @Override
+ protected AbstractMultiProfilePagerAdapter createMultiProfilePagerAdapter(
+ Intent[] initialIntents,
+ List<ResolveInfo> rList,
+ boolean filterLastUsed) {
+ if (hasWorkProfile() && ENABLE_TABBED_VIEW) {
+ mChooserMultiProfilePagerAdapter = createChooserMultiProfilePagerAdapterForTwoProfiles(
+ initialIntents, rList, filterLastUsed);
+ } else {
+ mChooserMultiProfilePagerAdapter = createChooserMultiProfilePagerAdapterForOneProfile(
+ initialIntents, rList, filterLastUsed);
+ }
+ return mChooserMultiProfilePagerAdapter;
+ }
+
+ private ChooserMultiProfilePagerAdapter createChooserMultiProfilePagerAdapterForOneProfile(
+ Intent[] initialIntents,
+ List<ResolveInfo> rList,
+ boolean filterLastUsed) {
+ ChooserGridAdapter adapter = createChooserGridAdapter(
+ /* context */ this,
+ /* payloadIntents */ mIntents,
+ initialIntents,
+ rList,
+ filterLastUsed,
+ mUseLayoutForBrowsables,
+ /* userHandle */ UserHandle.of(UserHandle.myUserId()));
+ return new ChooserMultiProfilePagerAdapter(
+ /* context */ this,
+ adapter);
+ }
+
+ private ChooserMultiProfilePagerAdapter createChooserMultiProfilePagerAdapterForTwoProfiles(
+ Intent[] initialIntents,
+ List<ResolveInfo> rList,
+ boolean filterLastUsed) {
+ ChooserGridAdapter personalAdapter = createChooserGridAdapter(
+ /* context */ this,
+ /* payloadIntents */ mIntents,
+ initialIntents,
+ rList,
+ filterLastUsed,
+ mUseLayoutForBrowsables,
+ /* userHandle */ getPersonalProfileUserHandle());
+ ChooserGridAdapter workAdapter = createChooserGridAdapter(
+ /* context */ this,
+ /* payloadIntents */ mIntents,
+ initialIntents,
+ rList,
+ filterLastUsed,
+ mUseLayoutForBrowsables,
+ /* userHandle */ getWorkProfileUserHandle());
+ return new ChooserMultiProfilePagerAdapter(
+ /* context */ this,
+ personalAdapter,
+ workAdapter,
+ /* defaultProfile */ getCurrentProfile());
+ }
+
+ @Override
+ protected boolean postRebuildList(boolean rebuildCompleted) {
+ updateContentPreview();
+ return postRebuildListInternal(rebuildCompleted);
+ }
+
/**
* Returns true if app prediction service is defined and the component exists on device.
*/
@@ -776,7 +850,7 @@ public class ChooserActivity extends ResolverActivity implements
* set up)
*/
protected boolean isWorkProfile() {
- return ((UserManager) getSystemService(Context.USER_SERVICE))
+ return getSystemService(UserManager.class)
.getUserInfo(UserHandle.myUserId()).isManagedProfile();
}
@@ -785,12 +859,21 @@ public class ChooserActivity extends ResolverActivity implements
return new PackageMonitor() {
@Override
public void onSomePackagesChanged() {
- mAdapter.handlePackagesChanged();
- updateProfileViewButton();
+ handlePackagesChanged();
}
};
}
+ /**
+ * Update UI to reflect changes in data.
+ */
+ public void handlePackagesChanged() {
+ // TODO(arangelov): Dispatch this to all adapters when we have the helper methods
+ // in a follow-up CL
+ mChooserMultiProfilePagerAdapter.getActiveListAdapter().handlePackagesChanged();
+ updateProfileViewButton();
+ }
+
private void onCopyButtonClicked(View v) {
Intent targetIntent = getTargetIntent();
if (targetIntent == null) {
@@ -875,6 +958,12 @@ public class ChooserActivity extends ResolverActivity implements
}
}
+ private ViewGroup createContentPreviewView(ViewGroup parent) {
+ Intent targetIntent = getTargetIntent();
+ int previewType = findPreferredContentPreview(targetIntent, getContentResolver());
+ return displayContentPreview(previewType, targetIntent, getLayoutInflater(), parent);
+ }
+
private ViewGroup displayContentPreview(@ContentPreviewType int previewType,
Intent targetIntent, LayoutInflater layoutInflater, ViewGroup parent) {
ViewGroup layout = null;
@@ -1239,36 +1328,14 @@ public class ChooserActivity extends ResolverActivity implements
}
@Override
- public void onPrepareAdapterView(ResolverListAdapter adapter, boolean isVisible) {
- mRecyclerView = findViewById(R.id.resolver_list);
- if (!isVisible) {
- mRecyclerView.setVisibility(View.GONE);
- return;
- }
- mRecyclerView.setVisibility(View.VISIBLE);
+ public void onPrepareAdapterView(ResolverListAdapter adapter) {
+ mChooserMultiProfilePagerAdapter.getCurrentAdapterView().setVisibility(View.VISIBLE);
if (mCallerChooserTargets != null && mCallerChooserTargets.length > 0) {
- mChooserListAdapter.addServiceResults(null, Lists.newArrayList(mCallerChooserTargets),
+ mChooserMultiProfilePagerAdapter.getActiveListAdapter().addServiceResults(
+ /* origTarget */ null,
+ Lists.newArrayList(mCallerChooserTargets),
TARGET_TYPE_DEFAULT);
}
- mChooserGridAdapter = new ChooserGridAdapter(mChooserListAdapter);
- GridLayoutManager glm = (GridLayoutManager) mRecyclerView.getLayoutManager();
- glm.setSpanCount(mChooserGridAdapter.getMaxTargetsPerRow());
- glm.setSpanSizeLookup(
- new GridLayoutManager.SpanSizeLookup() {
- @Override
- public int getSpanSize(int position) {
- return mChooserGridAdapter.getItemViewType(position)
- == ChooserGridAdapter.VIEW_TYPE_NORMAL
- ? SINGLE_CELL_SPAN_SIZE
- : glm.getSpanCount();
- }
- });
- }
-
- @Override
- protected boolean postRebuildList(boolean rebuildCompleted) {
- mChooserListAdapter = (ChooserListAdapter) mAdapter;
- return postRebuildListInternal(rebuildCompleted);
}
@Override
@@ -1293,17 +1360,31 @@ public class ChooserActivity extends ResolverActivity implements
return getIntent().getBooleanExtra(Intent.EXTRA_AUTO_LAUNCH_SINGLE_CHOICE, true);
}
- @Override
- public void showTargetDetails(ResolveInfo ri) {
- if (ri == null) {
+ void showTargetDetails(TargetInfo ti) {
+ if (ti == null) {
return;
}
-
- ComponentName name = ri.activityInfo.getComponentName();
+ ComponentName name = ti.getResolveInfo().activityInfo.getComponentName();
boolean pinned = mPinnedSharedPrefs.getBoolean(name.flattenToString(), false);
- ResolverTargetActionsDialogFragment f =
- new ResolverTargetActionsDialogFragment(ri.loadLabel(getPackageManager()),
- name, pinned);
+
+ ResolverTargetActionsDialogFragment f;
+
+ // For multiple targets, include info on all targets
+ if (ti instanceof MultiDisplayResolveInfo) {
+ MultiDisplayResolveInfo mti = (MultiDisplayResolveInfo) ti;
+ List<CharSequence> labels = new ArrayList<>();
+
+ for (TargetInfo innerInfo : mti.getTargets()) {
+ labels.add(innerInfo.getResolveInfo().loadLabel(getPackageManager()));
+ }
+ f = new ResolverTargetActionsDialogFragment(
+ mti.getResolveInfo().loadLabel(getPackageManager()), name, mti.getTargets(),
+ labels);
+ } else {
+ f = new ResolverTargetActionsDialogFragment(
+ ti.getResolveInfo().loadLabel(getPackageManager()), name, pinned);
+ }
+
f.show(getFragmentManager(), TARGET_DETAILS_FRAGMENT_TAG);
}
@@ -1348,15 +1429,36 @@ public class ChooserActivity extends ResolverActivity implements
@Override
public void startSelected(int which, boolean always, boolean filtered) {
- TargetInfo targetInfo = mChooserListAdapter.targetInfoForPosition(which, filtered);
+ ChooserListAdapter currentListAdapter =
+ mChooserMultiProfilePagerAdapter.getActiveListAdapter();
+ TargetInfo targetInfo = currentListAdapter
+ .targetInfoForPosition(which, filtered);
if (targetInfo != null && targetInfo instanceof NotSelectableTargetInfo) {
return;
}
final long selectionCost = System.currentTimeMillis() - mChooserShownTime;
+
+ // Stacked apps get a disambiguation first
+ if (targetInfo instanceof MultiDisplayResolveInfo) {
+ MultiDisplayResolveInfo mti = (MultiDisplayResolveInfo) targetInfo;
+ CharSequence[] labels = new CharSequence[mti.getTargets().size()];
+ int i = 0;
+ for (TargetInfo ti : mti.getTargets()) {
+ labels[i++] = ti.getResolveInfo().loadLabel(getPackageManager());
+ }
+ ChooserStackedAppDialogFragment f = new ChooserStackedAppDialogFragment(
+ targetInfo.getDisplayLabel(),
+ ((MultiDisplayResolveInfo) targetInfo).getTargets(), labels);
+
+ f.show(getFragmentManager(), TARGET_DETAILS_FRAGMENT_TAG);
+ return;
+ }
+
super.startSelected(which, always, filtered);
- if (mChooserListAdapter.getCount() > 0) {
+
+ if (currentListAdapter.getCount() > 0) {
// Log the index of which type of target the user picked.
// Lower values mean the ranking was better.
int cat = 0;
@@ -1364,13 +1466,12 @@ public class ChooserActivity extends ResolverActivity implements
int directTargetAlsoRanked = -1;
int numCallerProvided = 0;
HashedStringCache.HashResult directTargetHashed = null;
- switch (mChooserListAdapter.getPositionTargetType(which)) {
+ switch (currentListAdapter.getPositionTargetType(which)) {
case ChooserListAdapter.TARGET_SERVICE:
cat = MetricsEvent.ACTION_ACTIVITY_CHOOSER_PICKED_SERVICE_TARGET;
// Log the package name + target name to answer the question if most users
// share to mostly the same person or to a bunch of different people.
- ChooserTarget target =
- mChooserListAdapter.getChooserTargetForValue(value);
+ ChooserTarget target = currentListAdapter.getChooserTargetForValue(value);
directTargetHashed = HashedStringCache.getInstance().hashString(
this,
TAG,
@@ -1386,8 +1487,8 @@ public class ChooserActivity extends ResolverActivity implements
case ChooserListAdapter.TARGET_CALLER:
case ChooserListAdapter.TARGET_STANDARD:
cat = MetricsEvent.ACTION_ACTIVITY_CHOOSER_PICKED_APP_TARGET;
- value -= mChooserListAdapter.getSelectableServiceTargetCount();
- numCallerProvided = mChooserListAdapter.getCallerTargetCount();
+ value -= currentListAdapter.getSelectableServiceTargetCount();
+ numCallerProvided = currentListAdapter.getCallerTargetCount();
break;
case ChooserListAdapter.TARGET_STANDARD_AZ:
// A-Z targets are unranked standard targets; we use -1 to mark that they
@@ -1429,11 +1530,13 @@ public class ChooserActivity extends ResolverActivity implements
private int getRankedPosition(SelectableTargetInfo targetInfo) {
String targetPackageName =
targetInfo.getChooserTarget().getComponentName().getPackageName();
- int maxRankedResults = Math.min(mChooserListAdapter.mDisplayList.size(),
- MAX_LOG_RANK_POSITION);
+ ChooserListAdapter currentListAdapter =
+ mChooserMultiProfilePagerAdapter.getActiveListAdapter();
+ int maxRankedResults = Math.min(currentListAdapter.mDisplayList.size(),
+ MAX_LOG_RANK_POSITION);
for (int i = 0; i < maxRankedResults; i++) {
- if (mChooserListAdapter.mDisplayList.get(i)
+ if (currentListAdapter.mDisplayList.get(i)
.getResolveInfo().activityInfo.packageName.equals(targetPackageName)) {
return i;
}
@@ -1577,6 +1680,7 @@ public class ChooserActivity extends ResolverActivity implements
}
}
// Default to just querying ShortcutManager if AppPredictor not present.
+ //TODO(arangelov) we're using mIntents here, investicate possible implications on work tab
final IntentFilter filter = getTargetIntentFilter();
if (filter == null) {
return;
@@ -1584,6 +1688,7 @@ public class ChooserActivity extends ResolverActivity implements
final List<DisplayResolveInfo> driList = getDisplayResolveInfos(adapter);
AsyncTask.execute(() -> {
+ //TODO(arangelov) use the selected probile tab's ShortcutManager
ShortcutManager sm = (ShortcutManager) getSystemService(Context.SHORTCUT_SERVICE);
List<ShortcutManager.ShareShortcutInfo> resultList = sm.getShareTargets(filter);
sendShareShortcutInfoList(resultList, driList, null);
@@ -1779,9 +1884,11 @@ public class ChooserActivity extends ResolverActivity implements
final ResolveInfo ri = info.getResolveInfo();
Intent targetIntent = getTargetIntent();
if (ri != null && ri.activityInfo != null && targetIntent != null) {
- if (mAdapter != null) {
- mAdapter.updateModel(info.getResolvedComponentName());
- mAdapter.updateChooserCounts(ri.activityInfo.packageName, getUserId(),
+ ChooserListAdapter currentListAdapter =
+ mChooserMultiProfilePagerAdapter.getActiveListAdapter();
+ if (currentListAdapter != null) {
+ currentListAdapter.updateModel(info.getResolvedComponentName());
+ currentListAdapter.updateChooserCounts(ri.activityInfo.packageName, getUserId(),
targetIntent.getAction());
}
if (DEBUG) {
@@ -1956,8 +2063,9 @@ public class ChooserActivity extends ResolverActivity implements
Intent targetIntent,
String referrerPackageName,
int launchedFromUid,
+ UserHandle userId,
AbstractResolverComparator resolverComparator) {
- super(context, pm, targetIntent, referrerPackageName, launchedFromUid,
+ super(context, pm, targetIntent, referrerPackageName, launchedFromUid, userId,
resolverComparator);
}
@@ -1980,17 +2088,18 @@ public class ChooserActivity extends ResolverActivity implements
}
}
- @Override
- public ResolverListAdapter createAdapter(Context context, List<Intent> payloadIntents,
- Intent[] initialIntents, List<ResolveInfo> rList,
- boolean filterLastUsed, boolean useLayoutForBrowsables) {
- return new ChooserListAdapter(context, payloadIntents,
- initialIntents, rList, filterLastUsed, createListController(),
- useLayoutForBrowsables, this, this);
+ @VisibleForTesting
+ public ChooserGridAdapter createChooserGridAdapter(Context context,
+ List<Intent> payloadIntents, Intent[] initialIntents, List<ResolveInfo> rList,
+ boolean filterLastUsed, boolean useLayoutForBrowsables, UserHandle userHandle) {
+ return new ChooserGridAdapter(
+ new ChooserListAdapter(context, payloadIntents, initialIntents, rList,
+ filterLastUsed, createListController(userHandle), useLayoutForBrowsables,
+ this, this));
}
@VisibleForTesting
- protected ResolverListController createListController() {
+ protected ResolverListController createListController(UserHandle userHandle) {
AppPredictor appPredictor = getAppPredictorForShareActivitesIfEnabled();
AbstractResolverComparator resolverComparator;
if (appPredictor != null) {
@@ -2008,6 +2117,7 @@ public class ChooserActivity extends ResolverActivity implements
getTargetIntent(),
getReferrerPackageName(),
mLaunchedFromUid,
+ userHandle,
resolverComparator);
}
@@ -2041,8 +2151,8 @@ public class ChooserActivity extends ResolverActivity implements
}
private void handleScroll(View view, int x, int y, int oldx, int oldy) {
- if (mChooserGridAdapter != null) {
- mChooserGridAdapter.handleScroll(view, y, oldy);
+ if (mChooserMultiProfilePagerAdapter.getCurrentRootAdapter() != null) {
+ mChooserMultiProfilePagerAdapter.getCurrentRootAdapter().handleScroll(view, y, oldy);
}
}
@@ -2053,53 +2163,61 @@ public class ChooserActivity extends ResolverActivity implements
*/
private void handleLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft,
int oldTop, int oldRight, int oldBottom) {
- if (mChooserGridAdapter == null || mRecyclerView == null) {
+ if (mChooserMultiProfilePagerAdapter == null) {
+ return;
+ }
+ RecyclerView recyclerView = mChooserMultiProfilePagerAdapter.getCurrentAdapterView();
+ ChooserGridAdapter gridAdapter = mChooserMultiProfilePagerAdapter.getCurrentRootAdapter();
+ if (gridAdapter == null || recyclerView == null) {
return;
}
final int availableWidth = right - left - v.getPaddingLeft() - v.getPaddingRight();
- if (mChooserGridAdapter.consumeLayoutRequest()
- || mChooserGridAdapter.calculateChooserTargetWidth(availableWidth)
- || mRecyclerView.getAdapter() == null
+ if (gridAdapter.consumeLayoutRequest()
+ || gridAdapter.calculateChooserTargetWidth(availableWidth)
+ || recyclerView.getAdapter() == null
|| availableWidth != mCurrAvailableWidth) {
mCurrAvailableWidth = availableWidth;
- mRecyclerView.setAdapter(mChooserGridAdapter);
- ((GridLayoutManager) mRecyclerView.getLayoutManager())
- .setSpanCount(mChooserGridAdapter.getMaxTargetsPerRow());
+ recyclerView.setAdapter(gridAdapter);
+ ((GridLayoutManager) recyclerView.getLayoutManager())
+ .setSpanCount(gridAdapter.getMaxTargetsPerRow());
getMainThreadHandler().post(() -> {
- if (mResolverDrawerLayout == null || mChooserGridAdapter == null) {
+ if (mResolverDrawerLayout == null || gridAdapter == null) {
return;
}
final int bottomInset = mSystemWindowInsets != null
? mSystemWindowInsets.bottom : 0;
int offset = bottomInset;
- int rowsToShow = mChooserGridAdapter.getContentPreviewRowCount()
- + mChooserGridAdapter.getProfileRowCount()
- + mChooserGridAdapter.getServiceTargetRowCount()
- + mChooserGridAdapter.getCallerAndRankedTargetRowCount();
+ int rowsToShow = gridAdapter.getProfileRowCount()
+ + gridAdapter.getServiceTargetRowCount()
+ + gridAdapter.getCallerAndRankedTargetRowCount();
// then this is most likely not a SEND_* action, so check
// the app target count
if (rowsToShow == 0) {
- rowsToShow = mChooserGridAdapter.getRowCount();
+ rowsToShow = gridAdapter.getRowCount();
}
// still zero? then use a default height and leave, which
// can happen when there are no targets to show
- if (rowsToShow == 0) {
+ if (rowsToShow == 0 && !shouldShowContentPreview()) {
offset += getResources().getDimensionPixelSize(
R.dimen.chooser_max_collapsed_height);
mResolverDrawerLayout.setCollapsibleHeightReserved(offset);
return;
}
+ if (shouldShowContentPreview()) {
+ offset += findViewById(R.id.content_preview_container).getHeight();
+ }
+
int directShareHeight = 0;
rowsToShow = Math.min(4, rowsToShow);
- for (int i = 0, childCount = mRecyclerView.getChildCount();
+ for (int i = 0, childCount = recyclerView.getChildCount();
i < childCount && rowsToShow > 0; i++) {
- View child = mRecyclerView.getChildAt(i);
+ View child = recyclerView.getChildAt(i);
if (((GridLayoutManager.LayoutParams)
child.getLayoutParams()).getSpanIndex() != 0) {
continue;
@@ -2107,9 +2225,9 @@ public class ChooserActivity extends ResolverActivity implements
int height = child.getHeight();
offset += height;
- if (mChooserGridAdapter.getTargetType(
- mRecyclerView.getChildAdapterPosition(child))
- == mChooserListAdapter.TARGET_SERVICE) {
+ if (gridAdapter.getTargetType(
+ recyclerView.getChildAdapterPosition(child))
+ == ChooserListAdapter.TARGET_SERVICE) {
directShareHeight = height;
}
rowsToShow--;
@@ -2145,13 +2263,13 @@ public class ChooserActivity extends ResolverActivity implements
@Override // ResolverListCommunicator
public void onHandlePackagesChanged() {
mServicesRequested.clear();
- mAdapter.notifyDataSetChanged();
+ mChooserMultiProfilePagerAdapter.getActiveListAdapter().notifyDataSetChanged();
super.onHandlePackagesChanged();
}
@Override // SelectableTargetInfoCommunicator
public ActivityInfoPresentationGetter makePresentationGetter(ActivityInfo info) {
- return mChooserListAdapter.makePresentationGetter(info);
+ return mChooserMultiProfilePagerAdapter.getActiveListAdapter().makePresentationGetter(info);
}
@Override // SelectableTargetInfoCommunicator
@@ -2161,9 +2279,9 @@ public class ChooserActivity extends ResolverActivity implements
@Override // ChooserListCommunicator
public int getMaxRankedTargets() {
- return mChooserGridAdapter == null
+ return mChooserMultiProfilePagerAdapter.getCurrentRootAdapter() == null
? ChooserGridAdapter.MAX_TARGETS_PER_ROW_PORTRAIT
- : mChooserGridAdapter.getMaxTargetsPerRow();
+ : mChooserMultiProfilePagerAdapter.getCurrentRootAdapter().getMaxTargetsPerRow();
}
@Override // ChooserListCommunicator
@@ -2173,20 +2291,21 @@ public class ChooserActivity extends ResolverActivity implements
}
@Override
- public void onListRebuilt() {
- if (mChooserListAdapter.mDisplayList == null
- || mChooserListAdapter.mDisplayList.isEmpty()) {
- mChooserListAdapter.notifyDataSetChanged();
+ public void onListRebuilt(ResolverListAdapter listAdapter) {
+ ChooserListAdapter chooserListAdapter = (ChooserListAdapter) listAdapter;
+ if (chooserListAdapter.mDisplayList == null
+ || chooserListAdapter.mDisplayList.isEmpty()) {
+ chooserListAdapter.notifyDataSetChanged();
} else {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
- mChooserListAdapter.updateAlphabeticalList();
+ chooserListAdapter.updateAlphabeticalList();
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
- mChooserListAdapter.notifyDataSetChanged();
+ chooserListAdapter.notifyDataSetChanged();
}
}.execute();
}
@@ -2202,14 +2321,14 @@ public class ChooserActivity extends ResolverActivity implements
Log.d(TAG, "querying direct share targets from ShortcutManager");
}
- queryDirectShareTargets(mChooserListAdapter, false);
+ queryDirectShareTargets(chooserListAdapter, false);
}
if (USE_CHOOSER_TARGET_SERVICE_FOR_DIRECT_TARGETS) {
if (DEBUG) {
Log.d(TAG, "List built querying services");
}
- queryTargetServices(mChooserListAdapter);
+ queryTargetServices(chooserListAdapter);
}
}
@@ -2231,10 +2350,43 @@ public class ChooserActivity extends ResolverActivity implements
return false;
}
+ private boolean shouldShowContentPreview() {
+ return mMultiProfilePagerAdapter.getActiveListAdapter().getCount() > 0
+ && isSendAction(getTargetIntent());
+ }
+
+ private void updateContentPreview() {
+ if (shouldShowContentPreview()) {
+ showContentPreview();
+ } else {
+ hideContentPreview();
+ }
+ }
+
+ private void showContentPreview() {
+ ViewGroup contentPreviewContainer = findViewById(R.id.content_preview_container);
+ contentPreviewContainer.setVisibility(View.VISIBLE);
+ ViewGroup contentPreviewView = createContentPreviewView(contentPreviewContainer);
+ contentPreviewContainer.addView(contentPreviewView);
+ logActionShareWithPreview();
+ }
+
+ private void hideContentPreview() {
+ ViewGroup contentPreviewContainer = findViewById(R.id.content_preview_container);
+ contentPreviewContainer.removeAllViews();
+ contentPreviewContainer.setVisibility(View.GONE);
+ }
+
+ private void logActionShareWithPreview() {
+ Intent targetIntent = getTargetIntent();
+ int previewType = findPreferredContentPreview(targetIntent, getContentResolver());
+ getMetricsLogger().write(new LogMaker(MetricsEvent.ACTION_SHARE_WITH_PREVIEW)
+ .setSubtype(previewType));
+ }
+
/**
* Used to bind types of individual item including
* {@link ChooserGridAdapter#VIEW_TYPE_NORMAL},
- * {@link ChooserGridAdapter#VIEW_TYPE_CONTENT_PREVIEW},
* {@link ChooserGridAdapter#VIEW_TYPE_PROFILE},
* and {@link ChooserGridAdapter#VIEW_TYPE_AZ_LABEL}.
*/
@@ -2250,8 +2402,8 @@ public class ChooserActivity extends ResolverActivity implements
false/* always */, true/* filterd */));
itemView.setOnLongClickListener(v -> {
showTargetDetails(
- mChooserListAdapter.resolveInfoForPosition(
- mListPosition, true/* filtered */));
+ mChooserMultiProfilePagerAdapter.getActiveListAdapter()
+ .targetInfoForPosition(mListPosition, /* filtered */ true));
return true;
});
}
@@ -2259,6 +2411,29 @@ public class ChooserActivity extends ResolverActivity implements
}
/**
+ * Intentionally override the {@link ResolverActivity} implementation as we only need that
+ * implementation for the intent resolver case.
+ */
+ @Override
+ protected WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
+ return insets.consumeSystemWindowInsets();
+ }
+
+ /**
+ * Intentionally override the {@link ResolverActivity} implementation as we only need that
+ * implementation for the intent resolver case.
+ */
+ @Override
+ public void onButtonClick(View v) {}
+
+ /**
+ * Intentionally override the {@link ResolverActivity} implementation as we only need that
+ * implementation for the intent resolver case.
+ */
+ @Override
+ protected void resetButtonBar() {}
+
+ /**
* Adapter for all types of items and targets in ShareSheet.
* Note that ranked sections like Direct Share - while appearing grid-like - are handled on the
* row level by this adapter but not on the item level. Individual targets within the row are
@@ -2272,15 +2447,13 @@ public class ChooserActivity extends ResolverActivity implements
private int mChooserTargetWidth = 0;
private boolean mShowAzLabelIfPoss;
- private boolean mHideContentPreview = false;
private boolean mLayoutRequested = false;
private static final int VIEW_TYPE_DIRECT_SHARE = 0;
private static final int VIEW_TYPE_NORMAL = 1;
- private static final int VIEW_TYPE_CONTENT_PREVIEW = 2;
- private static final int VIEW_TYPE_PROFILE = 3;
- private static final int VIEW_TYPE_AZ_LABEL = 4;
- private static final int VIEW_TYPE_CALLER_AND_RANK = 5;
+ private static final int VIEW_TYPE_PROFILE = 2;
+ private static final int VIEW_TYPE_AZ_LABEL = 3;
+ private static final int VIEW_TYPE_CALLER_AND_RANK = 4;
private static final int MAX_TARGETS_PER_ROW_PORTRAIT = 4;
private static final int MAX_TARGETS_PER_ROW_LANDSCAPE = 8;
@@ -2329,21 +2502,14 @@ public class ChooserActivity extends ResolverActivity implements
return false;
}
- private int getMaxTargetsPerRow() {
+ int getMaxTargetsPerRow() {
int maxTargets = MAX_TARGETS_PER_ROW_PORTRAIT;
if (shouldDisplayLandscape(getResources().getConfiguration().orientation)) {
maxTargets = MAX_TARGETS_PER_ROW_LANDSCAPE;
}
-
return maxTargets;
}
- public void hideContentPreview() {
- mHideContentPreview = true;
- mLayoutRequested = true;
- notifyDataSetChanged();
- }
-
public boolean consumeLayoutRequest() {
boolean oldValue = mLayoutRequested;
mLayoutRequested = false;
@@ -2352,8 +2518,7 @@ public class ChooserActivity extends ResolverActivity implements
public int getRowCount() {
return (int) (
- getContentPreviewRowCount()
- + getProfileRowCount()
+ getProfileRowCount()
+ getServiceTargetRowCount()
+ getCallerAndRankedTargetRowCount()
+ getAzLabelRowCount()
@@ -2363,19 +2528,6 @@ public class ChooserActivity extends ResolverActivity implements
);
}
- public int getContentPreviewRowCount() {
- if (!isSendAction(getTargetIntent())) {
- return 0;
- }
-
- if (mHideContentPreview || mChooserListAdapter == null
- || mChooserListAdapter.getCount() == 0) {
- return 0;
- }
-
- return 1;
- }
-
public int getProfileRowCount() {
return mChooserListAdapter.getOtherProfile() == null ? 0 : 1;
}
@@ -2404,8 +2556,7 @@ public class ChooserActivity extends ResolverActivity implements
@Override
public int getItemCount() {
return (int) (
- getContentPreviewRowCount()
- + getProfileRowCount()
+ getProfileRowCount()
+ getServiceTargetRowCount()
+ getCallerAndRankedTargetRowCount()
+ getAzLabelRowCount()
@@ -2416,8 +2567,6 @@ public class ChooserActivity extends ResolverActivity implements
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
- case VIEW_TYPE_CONTENT_PREVIEW:
- return new ItemViewHolder(createContentPreviewView(parent), false);
case VIEW_TYPE_PROFILE:
return new ItemViewHolder(createProfileView(parent), false);
case VIEW_TYPE_AZ_LABEL:
@@ -2452,10 +2601,7 @@ public class ChooserActivity extends ResolverActivity implements
public int getItemViewType(int position) {
int count;
- int countSum = (count = getContentPreviewRowCount());
- if (count > 0 && position < countSum) return VIEW_TYPE_CONTENT_PREVIEW;
-
- countSum += (count = getProfileRowCount());
+ int countSum = (count = getProfileRowCount());
if (count > 0 && position < countSum) return VIEW_TYPE_PROFILE;
countSum += (count = getServiceTargetRowCount());
@@ -2474,16 +2620,6 @@ public class ChooserActivity extends ResolverActivity implements
return mChooserListAdapter.getPositionTargetType(getListPosition(position));
}
- private ViewGroup createContentPreviewView(ViewGroup parent) {
- Intent targetIntent = getTargetIntent();
- int previewType = findPreferredContentPreview(targetIntent, getContentResolver());
-
- getMetricsLogger().write(new LogMaker(MetricsEvent.ACTION_SHARE_WITH_PREVIEW)
- .setSubtype(previewType));
-
- return displayContentPreview(previewType, targetIntent, mLayoutInflater, parent);
- }
-
private View createProfileView(ViewGroup parent) {
View profileRow = mLayoutInflater.inflate(R.layout.chooser_profile_row, parent, false);
profileRow.setBackground(
@@ -2519,7 +2655,7 @@ public class ChooserActivity extends ResolverActivity implements
@Override
public boolean onLongClick(View v) {
showTargetDetails(
- mChooserListAdapter.resolveInfoForPosition(
+ mChooserListAdapter.targetInfoForPosition(
holder.getItemIndex(column), true));
return true;
}
@@ -2667,6 +2803,7 @@ public class ChooserActivity extends ResolverActivity implements
for (int i = 0; i < columnCount; i++) {
final View v = holder.getView(i);
+
if (start + i <= end) {
holder.setViewVisibility(i, View.VISIBLE);
holder.setItemIndex(i, start + i);
@@ -2678,7 +2815,7 @@ public class ChooserActivity extends ResolverActivity implements
}
int getListPosition(int position) {
- position -= getContentPreviewRowCount() + getProfileRowCount();
+ position -= getProfileRowCount();
final int serviceCount = mChooserListAdapter.getServiceTargetCount();
final int serviceRows = (int) Math.ceil((float) serviceCount
@@ -2712,9 +2849,19 @@ public class ChooserActivity extends ResolverActivity implements
&& !isInMultiWindowMode();
if (mDirectShareViewHolder != null && canExpandDirectShare) {
- mDirectShareViewHolder.handleScroll(mRecyclerView, y, oldy, getMaxTargetsPerRow());
+ mDirectShareViewHolder.handleScroll(
+ mChooserMultiProfilePagerAdapter.getCurrentAdapterView(), y, oldy,
+ getMaxTargetsPerRow());
}
}
+
+ public ChooserListAdapter getListAdapter() {
+ return mChooserListAdapter;
+ }
+
+ boolean shouldCellSpan(int position) {
+ return getItemViewType(position) == VIEW_TYPE_NORMAL;
+ }
}
/**
@@ -2898,7 +3045,8 @@ public class ChooserActivity extends ResolverActivity implements
// only expand if we have more than maxTargetsPerRow, and delay that decision
// until they start to scroll
- if (mChooserListAdapter.getSelectableServiceTargetCount() <= maxTargetsPerRow) {
+ if (mChooserMultiProfilePagerAdapter.getActiveListAdapter()
+ .getSelectableServiceTargetCount() <= maxTargetsPerRow) {
mHideDirectShareExpansion = true;
return;
}
diff --git a/core/java/com/android/internal/app/ChooserListAdapter.java b/core/java/com/android/internal/app/ChooserListAdapter.java
index 4eccf21677d5..a8a676d03971 100644
--- a/core/java/com/android/internal/app/ChooserListAdapter.java
+++ b/core/java/com/android/internal/app/ChooserListAdapter.java
@@ -38,17 +38,22 @@ import com.android.internal.R;
import com.android.internal.app.ResolverActivity.ResolvedComponentInfo;
import com.android.internal.app.chooser.ChooserTargetInfo;
import com.android.internal.app.chooser.DisplayResolveInfo;
+import com.android.internal.app.chooser.MultiDisplayResolveInfo;
import com.android.internal.app.chooser.SelectableTargetInfo;
import com.android.internal.app.chooser.TargetInfo;
import java.util.ArrayList;
import java.util.Collections;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
public class ChooserListAdapter extends ResolverListAdapter {
private static final String TAG = "ChooserListAdapter";
private static final boolean DEBUG = false;
+ private boolean mEnableStackedApps = true;
+
public static final int NO_POSITION = -1;
public static final int TARGET_BAD = -1;
public static final int TARGET_CALLER = 0;
@@ -218,7 +223,25 @@ public class ChooserListAdapter extends ResolverListAdapter {
void updateAlphabeticalList() {
mSortedList.clear();
- mSortedList.addAll(mDisplayList);
+ if (mEnableStackedApps) {
+ // Consolidate multiple targets from same app.
+ Map<String, DisplayResolveInfo> consolidated = new HashMap<>();
+ for (DisplayResolveInfo info : mDisplayList) {
+ String packageName = info.getResolvedComponentName().getPackageName();
+ if (consolidated.get(packageName) != null) {
+ // create consolidated target
+ MultiDisplayResolveInfo multiDisplayResolveInfo =
+ new MultiDisplayResolveInfo(packageName, info);
+ multiDisplayResolveInfo.addTarget(consolidated.get(packageName));
+ consolidated.put(packageName, multiDisplayResolveInfo);
+ } else {
+ consolidated.put(packageName, info);
+ }
+ }
+ mSortedList.addAll(consolidated.values());
+ } else {
+ mSortedList.addAll(mDisplayList);
+ }
Collections.sort(mSortedList, new ChooserActivity.AzInfoComparator(mContext));
}
@@ -270,7 +293,7 @@ public class ChooserListAdapter extends ResolverListAdapter {
}
int getAlphaTargetCount() {
- int standardCount = super.getCount();
+ int standardCount = mSortedList.size();
return standardCount > mChooserListCommunicator.getMaxRankedTargets() ? standardCount : 0;
}
diff --git a/core/java/com/android/internal/app/ChooserMultiProfilePagerAdapter.java b/core/java/com/android/internal/app/ChooserMultiProfilePagerAdapter.java
new file mode 100644
index 000000000000..7d856e1b945d
--- /dev/null
+++ b/core/java/com/android/internal/app/ChooserMultiProfilePagerAdapter.java
@@ -0,0 +1,137 @@
+/*
+ * Copyright (C) 2019 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 com.android.internal.app;
+
+import android.content.Context;
+import android.view.LayoutInflater;
+import android.view.ViewGroup;
+
+import com.android.internal.R;
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.widget.GridLayoutManager;
+import com.android.internal.widget.PagerAdapter;
+import com.android.internal.widget.RecyclerView;
+
+/**
+ * A {@link PagerAdapter} which describes the work and personal profile share sheet screens.
+ */
+@VisibleForTesting
+public class ChooserMultiProfilePagerAdapter extends AbstractMultiProfilePagerAdapter {
+ private static final int SINGLE_CELL_SPAN_SIZE = 1;
+
+ private final ChooserProfileDescriptor[] mItems;
+
+ ChooserMultiProfilePagerAdapter(Context context,
+ ChooserActivity.ChooserGridAdapter adapter) {
+ super(context, /* currentPage */ 0);
+ mItems = new ChooserProfileDescriptor[] {
+ createProfileDescriptor(adapter)
+ };
+ }
+
+ ChooserMultiProfilePagerAdapter(Context context,
+ ChooserActivity.ChooserGridAdapter personalAdapter,
+ ChooserActivity.ChooserGridAdapter workAdapter,
+ @Profile int defaultProfile) {
+ super(context, /* currentPage */ defaultProfile);
+ mItems = new ChooserProfileDescriptor[] {
+ createProfileDescriptor(personalAdapter),
+ createProfileDescriptor(workAdapter)
+ };
+ }
+
+ private ChooserProfileDescriptor createProfileDescriptor(
+ ChooserActivity.ChooserGridAdapter adapter) {
+ final LayoutInflater inflater = LayoutInflater.from(getContext());
+ final ViewGroup rootView =
+ (ViewGroup) inflater.inflate(R.layout.chooser_list_per_profile, null, false);
+ return new ChooserProfileDescriptor(rootView, adapter);
+ }
+
+ RecyclerView getListViewForIndex(int index) {
+ return getItem(index).recyclerView;
+ }
+
+ @Override
+ ChooserProfileDescriptor getItem(int pageIndex) {
+ return mItems[pageIndex];
+ }
+
+ @Override
+ int getItemCount() {
+ return mItems.length;
+ }
+
+ @Override
+ ChooserActivity.ChooserGridAdapter getAdapterForIndex(int pageIndex) {
+ return mItems[pageIndex].chooserGridAdapter;
+ }
+
+ @Override
+ void setupListAdapter(int pageIndex) {
+ final RecyclerView recyclerView = getItem(pageIndex).recyclerView;
+ ChooserActivity.ChooserGridAdapter chooserGridAdapter =
+ getItem(pageIndex).chooserGridAdapter;
+ recyclerView.setAdapter(chooserGridAdapter);
+ GridLayoutManager glm = (GridLayoutManager) recyclerView.getLayoutManager();
+ glm.setSpanCount(chooserGridAdapter.getMaxTargetsPerRow());
+ glm.setSpanSizeLookup(
+ new GridLayoutManager.SpanSizeLookup() {
+ @Override
+ public int getSpanSize(int position) {
+ return chooserGridAdapter.shouldCellSpan(position)
+ ? SINGLE_CELL_SPAN_SIZE
+ : glm.getSpanCount();
+ }
+ });
+ }
+
+ @Override
+ @VisibleForTesting
+ public ChooserListAdapter getActiveListAdapter() {
+ return getAdapterForIndex(getCurrentPage()).getListAdapter();
+ }
+
+ @Override
+ @VisibleForTesting
+ public ChooserListAdapter getInactiveListAdapter() {
+ if (getCount() == 1) {
+ return null;
+ }
+ return getAdapterForIndex(1 - getCurrentPage()).getListAdapter();
+ }
+
+ @Override
+ ChooserActivity.ChooserGridAdapter getCurrentRootAdapter() {
+ return getAdapterForIndex(getCurrentPage());
+ }
+
+ @Override
+ RecyclerView getCurrentAdapterView() {
+ return getListViewForIndex(getCurrentPage());
+ }
+
+ class ChooserProfileDescriptor extends ProfileDescriptor {
+ private ChooserActivity.ChooserGridAdapter chooserGridAdapter;
+ private RecyclerView recyclerView;
+ ChooserProfileDescriptor(ViewGroup rootView, ChooserActivity.ChooserGridAdapter adapter) {
+ super(rootView);
+ chooserGridAdapter = adapter;
+ recyclerView = rootView.findViewById(R.id.resolver_list);
+ }
+ }
+}
diff --git a/core/java/com/android/internal/app/ChooserStackedAppDialogFragment.java b/core/java/com/android/internal/app/ChooserStackedAppDialogFragment.java
new file mode 100644
index 000000000000..ff6582d10535
--- /dev/null
+++ b/core/java/com/android/internal/app/ChooserStackedAppDialogFragment.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2019 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 com.android.internal.app;
+
+import android.app.AlertDialog.Builder;
+import android.app.Dialog;
+import android.app.DialogFragment;
+import android.content.DialogInterface;
+import android.content.res.Configuration;
+import android.os.Bundle;
+
+import com.android.internal.app.chooser.DisplayResolveInfo;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Shows individual actions for a "stacked" app target - such as an app with multiple posting
+ * streams represented in the Sharesheet.
+ */
+public class ChooserStackedAppDialogFragment extends DialogFragment
+ implements DialogInterface.OnClickListener {
+ private static final String TITLE_KEY = "title";
+ private static final String PINNED_KEY = "pinned";
+
+ private List<DisplayResolveInfo> mTargetInfos = new ArrayList<>();
+ private CharSequence[] mLabels;
+
+ public ChooserStackedAppDialogFragment() {
+ }
+
+ public ChooserStackedAppDialogFragment(CharSequence title) {
+ Bundle args = new Bundle();
+ args.putCharSequence(TITLE_KEY, title);
+ setArguments(args);
+ }
+
+ public ChooserStackedAppDialogFragment(CharSequence title,
+ List<DisplayResolveInfo> targets, CharSequence[] labels) {
+ Bundle args = new Bundle();
+ args.putCharSequence(TITLE_KEY, title);
+ mTargetInfos = targets;
+ mLabels = labels;
+ setArguments(args);
+ }
+
+ @Override
+ public Dialog onCreateDialog(Bundle savedInstanceState) {
+ final Bundle args = getArguments();
+ return new Builder(getContext())
+ .setCancelable(true)
+ .setItems(mLabels, this)
+ .setTitle(args.getCharSequence(TITLE_KEY))
+ .create();
+ }
+
+ @Override
+ public void onClick(DialogInterface dialog, int which) {
+ final Bundle args = getArguments();
+ mTargetInfos.get(which).start(getActivity(), null);
+ dismiss();
+ }
+
+ @Override
+ public void onConfigurationChanged(Configuration newConfig) {
+ // Dismiss on config changed (eg: rotation)
+ // TODO: Maintain state on config change
+ super.onConfigurationChanged(newConfig);
+ dismiss();
+ }
+}
diff --git a/core/java/com/android/internal/app/ISoundTriggerService.aidl b/core/java/com/android/internal/app/ISoundTriggerService.aidl
index ea24d5fbb2f7..d94294f0aa22 100644
--- a/core/java/com/android/internal/app/ISoundTriggerService.aidl
+++ b/core/java/com/android/internal/app/ISoundTriggerService.aidl
@@ -20,6 +20,7 @@ import android.app.PendingIntent;
import android.content.ComponentName;
import android.hardware.soundtrigger.IRecognitionStatusCallback;
import android.hardware.soundtrigger.SoundTrigger;
+import android.hardware.soundtrigger.ModelParams;
import android.os.Bundle;
import android.os.ParcelUuid;
@@ -56,4 +57,16 @@ interface ISoundTriggerService {
int getModelState(in ParcelUuid soundModelId);
@nullable SoundTrigger.ModuleProperties getModuleProperties();
+
+ int setParameter(in ParcelUuid soundModelId, in ModelParams modelParam,
+ int value);
+
+ /**
+ * @throws UnsupportedOperationException if hal or model do not support this API.
+ * @throws IllegalArgumentException if invalid model handle or parameter is passed.
+ */
+ int getParameter(in ParcelUuid soundModelId, in ModelParams modelParam);
+
+ @nullable SoundTrigger.ModelParamRange queryParameter(in ParcelUuid soundModelId,
+ in ModelParams modelParam);
}
diff --git a/core/java/com/android/internal/app/ResolverActivity.java b/core/java/com/android/internal/app/ResolverActivity.java
index 9e38f3847f65..8dc3a072b47e 100644
--- a/core/java/com/android/internal/app/ResolverActivity.java
+++ b/core/java/com/android/internal/app/ResolverActivity.java
@@ -18,11 +18,15 @@ package com.android.internal.app;
import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
+import static com.android.internal.app.AbstractMultiProfilePagerAdapter.PROFILE_PERSONAL;
+import static com.android.internal.app.AbstractMultiProfilePagerAdapter.PROFILE_WORK;
+
import android.annotation.Nullable;
import android.annotation.StringRes;
import android.annotation.UiThread;
import android.annotation.UnsupportedAppUsage;
import android.app.Activity;
+import android.app.ActivityManager;
import android.app.ActivityTaskManager;
import android.app.ActivityThread;
import android.app.VoiceInteractor.PickOptionRequest;
@@ -71,6 +75,7 @@ import android.widget.Toast;
import com.android.internal.R;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.app.AbstractMultiProfilePagerAdapter.Profile;
import com.android.internal.app.chooser.DisplayResolveInfo;
import com.android.internal.app.chooser.TargetInfo;
import com.android.internal.content.PackageMonitor;
@@ -98,10 +103,7 @@ public class ResolverActivity extends Activity implements
public ResolverActivity() {
}
- @UnsupportedAppUsage
- protected ResolverListAdapter mAdapter;
private boolean mSafeForwardingMode;
- private AbsListView mAdapterView;
private Button mAlwaysButton;
private Button mOnceButton;
protected View mProfileView;
@@ -142,8 +144,16 @@ public class ResolverActivity extends Activity implements
private static final String EXTRA_FRAGMENT_ARG_KEY = ":settings:fragment_args_key";
private static final String OPEN_LINKS_COMPONENT_KEY = "app_link_state";
+ /**
+ * TODO(arangelov): Remove a couple of weeks after work/personal tabs are finalized.
+ */
+ static final boolean ENABLE_TABBED_VIEW = false;
+
private final PackageMonitor mPackageMonitor = createPackageMonitor();
+ @VisibleForTesting
+ protected AbstractMultiProfilePagerAdapter mMultiProfilePagerAdapter;
+
// Intent extra for connected audio devices
public static final String EXTRA_IS_AUDIO_CAPTURE_DEVICE = "is_audio_capture_device";
@@ -229,7 +239,7 @@ public class ResolverActivity extends Activity implements
return new PackageMonitor() {
@Override
public void onSomePackagesChanged() {
- mAdapter.handlePackagesChanged();
+ mMultiProfilePagerAdapter.getActiveListAdapter().handlePackagesChanged();
updateProfileViewButton();
}
@@ -324,15 +334,13 @@ public class ResolverActivity extends Activity implements
mSupportsAlwaysUseOption = supportsAlwaysUseOption;
- // The last argument of createAdapter is whether to do special handling
+ // The last argument of createResolverListAdapter is whether to do special handling
// of the last used choice to highlight it in the list. We need to always
// turn this off when running under voice interaction, since it results in
// a more complicated UI that the current voice interaction flow is not able
// to handle.
boolean filterLastUsed = mSupportsAlwaysUseOption && !isVoiceInteraction();
- mAdapter = createAdapter(this, mIntents, initialIntents, rList,
- filterLastUsed, mUseLayoutForBrowsables);
-
+ mMultiProfilePagerAdapter = createMultiProfilePagerAdapter(initialIntents, rList, filterLastUsed);
if (configureContentView()) {
return;
}
@@ -363,15 +371,96 @@ public class ResolverActivity extends Activity implements
}
final Set<String> categories = intent.getCategories();
- MetricsLogger.action(this, mAdapter.hasFilteredItem()
+ MetricsLogger.action(this, mMultiProfilePagerAdapter.getActiveListAdapter().hasFilteredItem()
? MetricsProto.MetricsEvent.ACTION_SHOW_APP_DISAMBIG_APP_FEATURED
: MetricsProto.MetricsEvent.ACTION_SHOW_APP_DISAMBIG_NONE_FEATURED,
intent.getAction() + ":" + intent.getType() + ":"
+ (categories != null ? Arrays.toString(categories.toArray()) : ""));
}
+ protected AbstractMultiProfilePagerAdapter createMultiProfilePagerAdapter(
+ Intent[] initialIntents,
+ List<ResolveInfo> rList,
+ boolean filterLastUsed) {
+ AbstractMultiProfilePagerAdapter resolverMultiProfilePagerAdapter = null;
+ if (hasWorkProfile() && ENABLE_TABBED_VIEW) {
+ resolverMultiProfilePagerAdapter =
+ createResolverMultiProfilePagerAdapterForTwoProfiles(
+ initialIntents, rList, filterLastUsed);
+ } else {
+ resolverMultiProfilePagerAdapter = createResolverMultiProfilePagerAdapterForOneProfile(
+ initialIntents, rList, filterLastUsed);
+ }
+ return resolverMultiProfilePagerAdapter;
+ }
+
+ private ResolverMultiProfilePagerAdapter createResolverMultiProfilePagerAdapterForOneProfile(
+ Intent[] initialIntents,
+ List<ResolveInfo> rList, boolean filterLastUsed) {
+ ResolverListAdapter adapter = createResolverListAdapter(
+ /* context */ this,
+ /* payloadIntents */ mIntents,
+ initialIntents,
+ rList,
+ filterLastUsed,
+ mUseLayoutForBrowsables,
+ /* userHandle */ UserHandle.of(UserHandle.myUserId()));
+ return new ResolverMultiProfilePagerAdapter(
+ /* context */ this,
+ adapter);
+ }
+
+ private ResolverMultiProfilePagerAdapter createResolverMultiProfilePagerAdapterForTwoProfiles(
+ Intent[] initialIntents,
+ List<ResolveInfo> rList,
+ boolean filterLastUsed) {
+ ResolverListAdapter personalAdapter = createResolverListAdapter(
+ /* context */ this,
+ /* payloadIntents */ mIntents,
+ initialIntents,
+ rList,
+ filterLastUsed,
+ mUseLayoutForBrowsables,
+ /* userHandle */ getPersonalProfileUserHandle());
+ ResolverListAdapter workAdapter = createResolverListAdapter(
+ /* context */ this,
+ /* payloadIntents */ mIntents,
+ initialIntents,
+ rList,
+ filterLastUsed,
+ mUseLayoutForBrowsables,
+ /* userHandle */ getWorkProfileUserHandle());
+ return new ResolverMultiProfilePagerAdapter(
+ /* context */ this,
+ personalAdapter,
+ workAdapter,
+ /* defaultProfile */ getCurrentProfile());
+ }
+
+ protected @Profile int getCurrentProfile() {
+ return (UserHandle.myUserId() == UserHandle.USER_SYSTEM ? PROFILE_PERSONAL : PROFILE_WORK);
+ }
+
+ protected UserHandle getPersonalProfileUserHandle() {
+ return UserHandle.of(ActivityManager.getCurrentUser());
+ }
+ protected @Nullable UserHandle getWorkProfileUserHandle() {
+ UserManager userManager = getSystemService(UserManager.class);
+ for (final UserInfo userInfo : userManager.getProfiles(ActivityManager.getCurrentUser())) {
+ if (userInfo.isManagedProfile()) {
+ return userInfo.getUserHandle();
+ }
+ }
+ return null;
+ }
+
+ protected boolean hasWorkProfile() {
+ return getWorkProfileUserHandle() != null;
+ }
+
protected void onProfileClick(View v) {
- final DisplayResolveInfo dri = mAdapter.getOtherProfile();
+ final DisplayResolveInfo dri =
+ mMultiProfilePagerAdapter.getActiveListAdapter().getOtherProfile();
if (dri == null) {
return;
}
@@ -394,11 +483,13 @@ public class ResolverActivity extends Activity implements
if (mFooterSpacer == null) {
mFooterSpacer = new Space(getApplicationContext());
} else {
- ((ListView) mAdapterView).removeFooterView(mFooterSpacer);
+ ((ResolverMultiProfilePagerAdapter) mMultiProfilePagerAdapter)
+ .getCurrentAdapterView().removeFooterView(mFooterSpacer);
}
mFooterSpacer.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.MATCH_PARENT,
mSystemWindowInsets.bottom));
- ((ListView) mAdapterView).addFooterView(mFooterSpacer);
+ ((ResolverMultiProfilePagerAdapter) mMultiProfilePagerAdapter)
+ .getCurrentAdapterView().addFooterView(mFooterSpacer);
} else {
View emptyView = findViewById(R.id.empty);
if (emptyView != null) {
@@ -416,7 +507,7 @@ public class ResolverActivity extends Activity implements
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
- mAdapter.handlePackagesChanged();
+ mMultiProfilePagerAdapter.getActiveListAdapter().handlePackagesChanged();
if (mSystemWindowInsets != null) {
mResolverDrawerLayout.setPadding(mSystemWindowInsets.left, mSystemWindowInsets.top,
@@ -431,9 +522,10 @@ public class ResolverActivity extends Activity implements
return;
}
- final Option[] options = new Option[mAdapter.getCount()];
+ int count = mMultiProfilePagerAdapter.getActiveListAdapter().getCount();
+ final Option[] options = new Option[count];
for (int i = 0, N = options.length; i < N; i++) {
- TargetInfo target = mAdapter.getItem(i);
+ TargetInfo target = mMultiProfilePagerAdapter.getActiveListAdapter().getItem(i);
if (target == null) {
// If this occurs, a new set of targets is being loaded. Let that complete,
// and have the next call to send voice choices proceed instead.
@@ -482,8 +574,9 @@ public class ResolverActivity extends Activity implements
return;
}
- final DisplayResolveInfo dri = mAdapter.getOtherProfile();
- if (dri != null) {
+ final DisplayResolveInfo dri =
+ mMultiProfilePagerAdapter.getActiveListAdapter().getOtherProfile();
+ if (dri != null && !ENABLE_TABBED_VIEW) {
mProfileView.setVisibility(View.VISIBLE);
View text = mProfileView.findViewById(R.id.profile_button);
if (!(text instanceof TextView)) {
@@ -534,7 +627,8 @@ public class ResolverActivity extends Activity implements
// While there may already be a filtered item, we can only use it in the title if the list
// is already sorted and all information relevant to it is already in the list.
- final boolean named = mAdapter.getFilteredPosition() >= 0;
+ final boolean named =
+ mMultiProfilePagerAdapter.getActiveListAdapter().getFilteredPosition() >= 0;
if (title == ActionTitle.DEFAULT && defaultTitleRes != 0) {
return getString(defaultTitleRes);
} else if (isHttpSchemeAndViewAction(intent)) {
@@ -543,12 +637,14 @@ public class ResolverActivity extends Activity implements
String dialogTitle = null;
if (named && !mUseLayoutForBrowsables) {
dialogTitle = getString(ActionTitle.BROWSABLE_APP_TITLE_RES,
- mAdapter.getFilteredItem().getDisplayLabel());
+ mMultiProfilePagerAdapter.getActiveListAdapter().getFilteredItem()
+ .getDisplayLabel());
} else if (named && mUseLayoutForBrowsables) {
dialogTitle = getString(ActionTitle.BROWSABLE_HOST_APP_TITLE_RES,
intent.getData().getHost(),
- mAdapter.getFilteredItem().getDisplayLabel());
- } else if (mAdapter.areAllTargetsBrowsers()) {
+ mMultiProfilePagerAdapter.getActiveListAdapter().getFilteredItem()
+ .getDisplayLabel());
+ } else if (mMultiProfilePagerAdapter.getActiveListAdapter().areAllTargetsBrowsers()) {
dialogTitle = getString(ActionTitle.BROWSABLE_TITLE_RES);
} else {
dialogTitle = getString(ActionTitle.BROWSABLE_HOST_TITLE_RES,
@@ -557,7 +653,8 @@ public class ResolverActivity extends Activity implements
return dialogTitle;
} else {
return named
- ? getString(title.namedTitleRes, mAdapter.getFilteredItem().getDisplayLabel())
+ ? getString(title.namedTitleRes, mMultiProfilePagerAdapter
+ .getActiveListAdapter().getFilteredItem().getDisplayLabel())
: getString(title.titleRes);
}
}
@@ -575,7 +672,7 @@ public class ResolverActivity extends Activity implements
mPackageMonitor.register(this, getMainLooper(), false);
mRegistered = true;
}
- mAdapter.handlePackagesChanged();
+ mMultiProfilePagerAdapter.getActiveListAdapter().handlePackagesChanged();
updateProfileViewButton();
}
@@ -608,8 +705,8 @@ public class ResolverActivity extends Activity implements
if (!isChangingConfigurations() && mPickOptionRequest != null) {
mPickOptionRequest.cancel();
}
- if (mAdapter != null) {
- mAdapter.onDestroy();
+ if (mMultiProfilePagerAdapter.getActiveListAdapter() != null) {
+ mMultiProfilePagerAdapter.getActiveListAdapter().onDestroy();
}
}
@@ -657,8 +754,10 @@ public class ResolverActivity extends Activity implements
private void setAlwaysButtonEnabled(boolean hasValidSelection, int checkedPos,
boolean filtered) {
boolean enabled = false;
+ ResolveInfo ri = null;
if (hasValidSelection) {
- ResolveInfo ri = mAdapter.resolveInfoForPosition(checkedPos, filtered);
+ ri = mMultiProfilePagerAdapter.getActiveListAdapter()
+ .resolveInfoForPosition(checkedPos, filtered);
if (ri == null) {
Log.e(TAG, "Invalid position supplied to setAlwaysButtonEnabled");
return;
@@ -676,16 +775,33 @@ public class ResolverActivity extends Activity implements
.getString(R.string.activity_resolver_use_always));
}
}
+
+ ActivityInfo activityInfo = ri.activityInfo;
+
+ boolean hasRecordPermission =
+ mPm.checkPermission(android.Manifest.permission.RECORD_AUDIO,
+ activityInfo.packageName)
+ == android.content.pm.PackageManager.PERMISSION_GRANTED;
+
+ if (!hasRecordPermission) {
+ // OK, we know the record permission, is this a capture device
+ boolean hasAudioCapture =
+ getIntent().getBooleanExtra(
+ ResolverActivity.EXTRA_IS_AUDIO_CAPTURE_DEVICE, false);
+ enabled = !hasAudioCapture;
+ }
mAlwaysButton.setEnabled(enabled);
}
public void onButtonClick(View v) {
final int id = v.getId();
- int which = mAdapter.hasFilteredItem()
- ? mAdapter.getFilteredPosition()
- : mAdapterView.getCheckedItemPosition();
- boolean hasIndexBeenFiltered = !mAdapter.hasFilteredItem();
- ResolveInfo ri = mAdapter.resolveInfoForPosition(which, hasIndexBeenFiltered);
+ ListView listView = (ListView) mMultiProfilePagerAdapter.getCurrentAdapterView();
+ ResolverListAdapter currentListAdapter = mMultiProfilePagerAdapter.getActiveListAdapter();
+ int which = currentListAdapter.hasFilteredItem()
+ ? currentListAdapter.getFilteredPosition()
+ : listView.getCheckedItemPosition();
+ boolean hasIndexBeenFiltered = !currentListAdapter.hasFilteredItem();
+ ResolveInfo ri = currentListAdapter.resolveInfoForPosition(which, hasIndexBeenFiltered);
if (mUseLayoutForBrowsables
&& !ri.handleAllWebDataURI && id == R.id.button_always) {
showSettingsForSelected(ri);
@@ -716,7 +832,8 @@ public class ResolverActivity extends Activity implements
if (isFinishing()) {
return;
}
- ResolveInfo ri = mAdapter.resolveInfoForPosition(which, hasIndexBeenFiltered);
+ ResolveInfo ri = mMultiProfilePagerAdapter.getActiveListAdapter()
+ .resolveInfoForPosition(which, hasIndexBeenFiltered);
if (mResolvingHome && hasManagedProfile() && !supportsManagedProfiles(ri)) {
Toast.makeText(this, String.format(getResources().getString(
com.android.internal.R.string.activity_resolver_work_profiles_support),
@@ -725,7 +842,8 @@ public class ResolverActivity extends Activity implements
return;
}
- TargetInfo target = mAdapter.targetInfoForPosition(which, hasIndexBeenFiltered);
+ TargetInfo target = mMultiProfilePagerAdapter.getActiveListAdapter()
+ .targetInfoForPosition(which, hasIndexBeenFiltered);
if (target == null) {
return;
}
@@ -740,7 +858,8 @@ public class ResolverActivity extends Activity implements
MetricsLogger.action(
this, MetricsProto.MetricsEvent.ACTION_APP_DISAMBIG_TAP);
}
- MetricsLogger.action(this, mAdapter.hasFilteredItem()
+ MetricsLogger.action(this,
+ mMultiProfilePagerAdapter.getActiveListAdapter().hasFilteredItem()
? MetricsProto.MetricsEvent.ACTION_HIDE_APP_DISAMBIG_APP_FEATURED
: MetricsProto.MetricsEvent.ACTION_HIDE_APP_DISAMBIG_NONE_FEATURED);
finish();
@@ -756,17 +875,17 @@ public class ResolverActivity extends Activity implements
}
@Override // ResolverListCommunicator
- public void onPostListReady() {
+ public void onPostListReady(ResolverListAdapter listAdapter) {
setHeader();
resetButtonBar();
- onListRebuilt();
+ onListRebuilt(listAdapter);
}
- protected void onListRebuilt() {
- int count = mAdapter.getUnfilteredCount();
- if (count == 1 && mAdapter.getOtherProfile() == null) {
+ protected void onListRebuilt(ResolverListAdapter listAdapter) {
+ int count = listAdapter.getUnfilteredCount();
+ if (count == 1 && listAdapter.getOtherProfile() == null) {
// Only one target, so we're a candidate to auto-launch!
- final TargetInfo target = mAdapter.targetInfoForPosition(0, false);
+ final TargetInfo target = listAdapter.targetInfoForPosition(0, false);
if (shouldAutoLaunchSingleChoice(target)) {
safelyStartActivity(target);
finish();
@@ -778,8 +897,9 @@ public class ResolverActivity extends Activity implements
final ResolveInfo ri = target.getResolveInfo();
final Intent intent = target != null ? target.getResolvedIntent() : null;
- if (intent != null && (mSupportsAlwaysUseOption || mAdapter.hasFilteredItem())
- && mAdapter.mUnfilteredResolveList != null) {
+ if (intent != null && (mSupportsAlwaysUseOption
+ || mMultiProfilePagerAdapter.getActiveListAdapter().hasFilteredItem())
+ && mMultiProfilePagerAdapter.getActiveListAdapter().getUnfilteredResolveList() != null) {
// Build a reasonable intent filter, based on what matched.
IntentFilter filter = new IntentFilter();
Intent filterIntent;
@@ -864,13 +984,14 @@ public class ResolverActivity extends Activity implements
}
if (filter != null) {
- final int N = mAdapter.mUnfilteredResolveList.size();
+ final int N = mMultiProfilePagerAdapter.getActiveListAdapter()
+ .getUnfilteredResolveList().size();
ComponentName[] set;
// If we don't add back in the component for forwarding the intent to a managed
// profile, the preferred activity may not be updated correctly (as the set of
// components we tell it we knew about will have changed).
final boolean needToAddBackProfileForwardingComponent =
- mAdapter.getOtherProfile() != null;
+ mMultiProfilePagerAdapter.getActiveListAdapter().getOtherProfile() != null;
if (!needToAddBackProfileForwardingComponent) {
set = new ComponentName[N];
} else {
@@ -879,15 +1000,18 @@ public class ResolverActivity extends Activity implements
int bestMatch = 0;
for (int i=0; i<N; i++) {
- ResolveInfo r = mAdapter.mUnfilteredResolveList.get(i).getResolveInfoAt(0);
+ ResolveInfo r = mMultiProfilePagerAdapter.getActiveListAdapter()
+ .getUnfilteredResolveList().get(i).getResolveInfoAt(0);
set[i] = new ComponentName(r.activityInfo.packageName,
r.activityInfo.name);
if (r.match > bestMatch) bestMatch = r.match;
}
if (needToAddBackProfileForwardingComponent) {
- set[N] = mAdapter.getOtherProfile().getResolvedComponentName();
- final int otherProfileMatch = mAdapter.getOtherProfile().getResolveInfo().match;
+ set[N] = mMultiProfilePagerAdapter.getActiveListAdapter()
+ .getOtherProfile().getResolvedComponentName();
+ final int otherProfileMatch = mMultiProfilePagerAdapter.getActiveListAdapter()
+ .getOtherProfile().getResolveInfo().match;
if (otherProfileMatch > bestMatch) bestMatch = otherProfileMatch;
}
@@ -926,7 +1050,8 @@ public class ResolverActivity extends Activity implements
}
} else {
try {
- mAdapter.mResolverListController.setLastChosen(intent, filter, bestMatch);
+ mMultiProfilePagerAdapter.getActiveListAdapter()
+ .mResolverListController.setLastChosen(intent, filter, bestMatch);
} catch (RemoteException re) {
Log.d(TAG, "Error calling setLastChosenActivity\n" + re);
}
@@ -964,14 +1089,15 @@ public class ResolverActivity extends Activity implements
if (mProfileSwitchMessageId != -1) {
Toast.makeText(this, getString(mProfileSwitchMessageId), Toast.LENGTH_LONG).show();
}
+ UserHandle currentUserHandle = mMultiProfilePagerAdapter.getCurrentUserHandle();
if (!mSafeForwardingMode) {
- if (cti.start(this, null)) {
+ if (cti.startAsUser(this, null, currentUserHandle)) {
onActivityStarted(cti);
}
return;
}
try {
- if (cti.startAsCaller(this, null, UserHandle.USER_NULL)) {
+ if (cti.startAsCaller(this, null, currentUserHandle.getIdentifier())) {
onActivityStarted(cti);
}
} catch (RuntimeException e) {
@@ -1034,34 +1160,34 @@ public class ResolverActivity extends Activity implements
return !target.isSuspended();
}
- public void showTargetDetails(ResolveInfo ri) {
+ void showTargetDetails(ResolveInfo ri) {
Intent in = new Intent().setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
.setData(Uri.fromParts("package", ri.activityInfo.packageName, null))
.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
startActivity(in);
}
- public ResolverListAdapter createAdapter(Context context, List<Intent> payloadIntents,
- Intent[] initialIntents, List<ResolveInfo> rList,
- boolean filterLastUsed, boolean useLayoutForBrowsables) {
-
+ @VisibleForTesting
+ protected ResolverListAdapter createResolverListAdapter(Context context,
+ List<Intent> payloadIntents, Intent[] initialIntents, List<ResolveInfo> rList,
+ boolean filterLastUsed, boolean useLayoutForBrowsables, UserHandle userHandle) {
Intent startIntent = getIntent();
boolean isAudioCaptureDevice =
startIntent.getBooleanExtra(EXTRA_IS_AUDIO_CAPTURE_DEVICE, false);
-
return new ResolverListAdapter(context, payloadIntents, initialIntents, rList,
- filterLastUsed, createListController(), useLayoutForBrowsables, this,
+ filterLastUsed, createListController(userHandle), useLayoutForBrowsables, this,
isAudioCaptureDevice);
}
@VisibleForTesting
- protected ResolverListController createListController() {
+ protected ResolverListController createListController(UserHandle userHandle) {
return new ResolverListController(
this,
mPm,
getTargetIntent(),
getReferrerPackageName(),
- mLaunchedFromUid);
+ mLaunchedFromUid,
+ userHandle);
}
/**
@@ -1069,16 +1195,21 @@ public class ResolverActivity extends Activity implements
* @return <code>true</code> if the activity is finishing and creation should halt.
*/
private boolean configureContentView() {
- if (mAdapter == null) {
- throw new IllegalStateException("mAdapter cannot be null.");
+ if (mMultiProfilePagerAdapter.getActiveListAdapter() == null) {
+ throw new IllegalStateException("mMultiProfilePagerAdapter.getCurrentListAdapter() "
+ + "cannot be null.");
+ }
+ boolean rebuildCompleted = mMultiProfilePagerAdapter.getActiveListAdapter().rebuildList();
+ if (mMultiProfilePagerAdapter.getInactiveListAdapter() != null) {
+ mMultiProfilePagerAdapter.getInactiveListAdapter().rebuildList();
}
- boolean rebuildCompleted = mAdapter.rebuildList();
if (useLayoutWithDefault()) {
mLayoutId = R.layout.resolver_list_with_default;
} else {
mLayoutId = getLayoutResource();
}
setContentView(mLayoutId);
+ mMultiProfilePagerAdapter.setupViewPager(findViewById(R.id.profile_pager));
return postRebuildList(rebuildCompleted);
}
@@ -1099,14 +1230,16 @@ public class ResolverActivity extends Activity implements
*/
final boolean postRebuildListInternal(boolean rebuildCompleted) {
- int count = mAdapter.getUnfilteredCount();
+ int count = mMultiProfilePagerAdapter.getActiveListAdapter().getUnfilteredCount();
// We only rebuild asynchronously when we have multiple elements to sort. In the case where
// we're already done, we can check if we should auto-launch immediately.
if (rebuildCompleted) {
- if (count == 1 && mAdapter.getOtherProfile() == null) {
+ if (count == 1
+ && mMultiProfilePagerAdapter.getActiveListAdapter().getOtherProfile() == null) {
// Only one target, so we're a candidate to auto-launch!
- final TargetInfo target = mAdapter.targetInfoForPosition(0, false);
+ final TargetInfo target = mMultiProfilePagerAdapter.getActiveListAdapter()
+ .targetInfoForPosition(0, false);
if (shouldAutoLaunchSingleChoice(target)) {
safelyStartActivity(target);
mPackageMonitor.unregister();
@@ -1117,37 +1250,32 @@ public class ResolverActivity extends Activity implements
}
}
- boolean isAdapterViewVisible = true;
- if (count == 0 && mAdapter.getPlaceholderCount() == 0) {
+ setupViewVisibilities(count);
+ return false;
+ }
+
+ private void setupViewVisibilities(int count) {
+ if (count == 0
+ && mMultiProfilePagerAdapter.getActiveListAdapter().getPlaceholderCount() == 0) {
final TextView emptyView = findViewById(R.id.empty);
emptyView.setVisibility(View.VISIBLE);
- isAdapterViewVisible = false;
+ findViewById(R.id.profile_pager).setVisibility(View.GONE);
+ } else {
+ onPrepareAdapterView(mMultiProfilePagerAdapter.getActiveListAdapter());
}
-
- onPrepareAdapterView(mAdapter, isAdapterViewVisible);
- return false;
}
/**
* Prepare the scrollable view which consumes data in the list adapter.
* @param adapter The adapter used to provide data to item views.
- * @param isVisible True if the scrollable view should be visible; false, otherwise.
*/
- public void onPrepareAdapterView(ResolverListAdapter adapter, boolean isVisible) {
- mAdapterView = findViewById(R.id.resolver_list);
- if (!isVisible) {
- mAdapterView.setVisibility(View.GONE);
- return;
- }
- mAdapterView.setVisibility(View.VISIBLE);
+ public void onPrepareAdapterView(ResolverListAdapter adapter) {
+ mMultiProfilePagerAdapter.getCurrentAdapterView().setVisibility(View.VISIBLE);
final boolean useHeader = adapter.hasFilteredItem();
- final ListView listView = mAdapterView instanceof ListView ? (ListView) mAdapterView : null;
-
- mAdapterView.setAdapter(mAdapter);
-
+ final ListView listView = (ListView) mMultiProfilePagerAdapter.getCurrentAdapterView();
final ItemClickListener listener = new ItemClickListener();
- mAdapterView.setOnItemClickListener(listener);
- mAdapterView.setOnItemLongClickListener(listener);
+ listView.setOnItemClickListener(listener);
+ listView.setOnItemLongClickListener(listener);
if (mSupportsAlwaysUseOption || mUseLayoutForBrowsables) {
listView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
@@ -1166,7 +1294,8 @@ public class ResolverActivity extends Activity implements
* Configure the area above the app selection list (title, content preview, etc).
*/
public void setHeader() {
- if (mAdapter.getCount() == 0 && mAdapter.getPlaceholderCount() == 0) {
+ if (mMultiProfilePagerAdapter.getActiveListAdapter().getCount() == 0
+ && mMultiProfilePagerAdapter.getActiveListAdapter().getPlaceholderCount() == 0) {
final TextView titleView = findViewById(R.id.title);
if (titleView != null) {
titleView.setVisibility(View.GONE);
@@ -1187,11 +1316,11 @@ public class ResolverActivity extends Activity implements
final ImageView iconView = findViewById(R.id.icon);
if (iconView != null) {
- mAdapter.loadFilteredItemIconTaskAsync(iconView);
+ mMultiProfilePagerAdapter.getActiveListAdapter().loadFilteredItemIconTaskAsync(iconView);
}
}
- private void resetButtonBar() {
+ protected void resetButtonBar() {
if (!mSupportsAlwaysUseOption && !mUseLayoutForBrowsables) {
return;
}
@@ -1215,24 +1344,27 @@ public class ResolverActivity extends Activity implements
}
private void resetAlwaysOrOnceButtonBar() {
- if (useLayoutWithDefault()
- && mAdapter.getFilteredPosition() != ListView.INVALID_POSITION) {
- setAlwaysButtonEnabled(true, mAdapter.getFilteredPosition(), false);
+ int filteredPosition = mMultiProfilePagerAdapter.getActiveListAdapter()
+ .getFilteredPosition();
+ if (useLayoutWithDefault() && filteredPosition != ListView.INVALID_POSITION) {
+ setAlwaysButtonEnabled(true, filteredPosition, false);
mOnceButton.setEnabled(true);
return;
}
// When the items load in, if an item was already selected, enable the buttons
- if (mAdapterView != null
- && mAdapterView.getCheckedItemPosition() != ListView.INVALID_POSITION) {
- setAlwaysButtonEnabled(true, mAdapterView.getCheckedItemPosition(), true);
+ ListView currentAdapterView = (ListView) mMultiProfilePagerAdapter.getCurrentAdapterView();
+ if (currentAdapterView != null
+ && currentAdapterView.getCheckedItemPosition() != ListView.INVALID_POSITION) {
+ setAlwaysButtonEnabled(true, currentAdapterView.getCheckedItemPosition(), true);
mOnceButton.setEnabled(true);
}
}
@Override // ResolverListCommunicator
public boolean useLayoutWithDefault() {
- return mSupportsAlwaysUseOption && mAdapter.hasFilteredItem();
+ return mSupportsAlwaysUseOption
+ && mMultiProfilePagerAdapter.getActiveListAdapter().hasFilteredItem();
}
/**
@@ -1256,7 +1388,9 @@ public class ResolverActivity extends Activity implements
@Override // ResolverListCommunicator
public void onHandlePackagesChanged() {
- if (mAdapter.getCount() == 0) {
+ ResolverListAdapter activeListAdapter = mMultiProfilePagerAdapter.getActiveListAdapter();
+ activeListAdapter.rebuildList();
+ if (activeListAdapter.getCount() == 0) {
// We no longer have any items... just finish the activity.
finish();
}
@@ -1331,11 +1465,14 @@ public class ResolverActivity extends Activity implements
return;
}
// If we're still loading, we can't yet enable the buttons.
- if (mAdapter.resolveInfoForPosition(position, true) == null) {
+ if (mMultiProfilePagerAdapter.getActiveListAdapter()
+ .resolveInfoForPosition(position, true) == null) {
return;
}
- final int checkedPos = mAdapterView.getCheckedItemPosition();
+ ListView currentAdapterView =
+ (ListView) mMultiProfilePagerAdapter.getCurrentAdapterView();
+ final int checkedPos = currentAdapterView.getCheckedItemPosition();
final boolean hasValidSelection = checkedPos != ListView.INVALID_POSITION;
if (!useLayoutWithDefault()
&& (!hasValidSelection || mLastSelected != checkedPos)
@@ -1343,7 +1480,7 @@ public class ResolverActivity extends Activity implements
setAlwaysButtonEnabled(hasValidSelection, checkedPos, true);
mOnceButton.setEnabled(hasValidSelection);
if (hasValidSelection) {
- mAdapterView.smoothScrollToPosition(checkedPos);
+ currentAdapterView.smoothScrollToPosition(checkedPos);
}
mLastSelected = checkedPos;
} else {
@@ -1361,7 +1498,8 @@ public class ResolverActivity extends Activity implements
// Header views don't count.
return false;
}
- ResolveInfo ri = mAdapter.resolveInfoForPosition(position, true);
+ ResolveInfo ri = mMultiProfilePagerAdapter.getActiveListAdapter()
+ .resolveInfoForPosition(position, true);
showTargetDetails(ri);
return true;
}
@@ -1401,7 +1539,8 @@ public class ResolverActivity extends Activity implements
final ResolverActivity ra = (ResolverActivity) getActivity();
if (ra != null) {
- final TargetInfo ti = ra.mAdapter.getItem(selections[0].getIndex());
+ final TargetInfo ti = ra.mMultiProfilePagerAdapter.getActiveListAdapter()
+ .getItem(selections[0].getIndex());
if (ra.onTargetSelected(ti, false)) {
ra.mPickOptionRequest = null;
ra.finish();
diff --git a/core/java/com/android/internal/app/ResolverListAdapter.java b/core/java/com/android/internal/app/ResolverListAdapter.java
index bb7ca358f815..ef7a347cf7be 100644
--- a/core/java/com/android/internal/app/ResolverListAdapter.java
+++ b/core/java/com/android/internal/app/ResolverListAdapter.java
@@ -37,7 +37,6 @@ import android.graphics.ColorMatrixColorFilter;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
-import android.os.Process;
import android.os.RemoteException;
import android.os.UserHandle;
import android.os.UserManager;
@@ -81,7 +80,7 @@ public class ResolverListAdapter extends BaseAdapter {
// This one is the list that the Adapter will actually present.
List<DisplayResolveInfo> mDisplayList;
- List<ResolvedComponentInfo> mUnfilteredResolveList;
+ private List<ResolvedComponentInfo> mUnfilteredResolveList;
private int mLastChosenPosition = -1;
private boolean mFilterLastUsed;
@@ -114,7 +113,6 @@ public class ResolverListAdapter extends BaseAdapter {
}
public void handlePackagesChanged() {
- rebuildList();
mResolverListCommunicator.onHandlePackagesChanged();
}
@@ -162,6 +160,10 @@ public class ResolverListAdapter extends BaseAdapter {
mResolverListController.updateChooserCounts(packageName, userId, action);
}
+ List<ResolvedComponentInfo> getUnfilteredResolveList() {
+ return mUnfilteredResolveList;
+ }
+
/**
* @return true if all items in the display list are defined as browsers by
* ResolveInfo.handleAllWebDataURI
@@ -348,12 +350,12 @@ public class ResolverListAdapter extends BaseAdapter {
* determine the layout known. We therefore can't update the UI inline and post to the
* handler thread to update after the current task is finished.
*/
- private void postListReadyRunnable() {
+ void postListReadyRunnable() {
if (mPostListReadyRunnable == null) {
mPostListReadyRunnable = new Runnable() {
@Override
public void run() {
- mResolverListCommunicator.onPostListReady();
+ mResolverListCommunicator.onPostListReady(ResolverListAdapter.this);
mPostListReadyRunnable = null;
}
};
@@ -576,7 +578,7 @@ public class ResolverListAdapter extends BaseAdapter {
Drawable loadIconForResolveInfo(ResolveInfo ri) {
// Load icons based on the current process. If in work profile icons should be badged.
- return makePresentationGetter(ri).getIcon(Process.myUserHandle());
+ return makePresentationGetter(ri).getIcon(mResolverListController.getUserHandle());
}
void loadFilteredItemIconTaskAsync(@NonNull ImageView iconView) {
@@ -596,7 +598,7 @@ public class ResolverListAdapter extends BaseAdapter {
Intent getReplacementIntent(ActivityInfo activityInfo, Intent defIntent);
- void onPostListReady();
+ void onPostListReady(ResolverListAdapter listAdapter);
void sendVoiceChoicesIfNeeded();
diff --git a/core/java/com/android/internal/app/ResolverListController.java b/core/java/com/android/internal/app/ResolverListController.java
index b456ca00fe2b..abd3eb2453df 100644
--- a/core/java/com/android/internal/app/ResolverListController.java
+++ b/core/java/com/android/internal/app/ResolverListController.java
@@ -28,6 +28,7 @@ import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.RemoteException;
+import android.os.UserHandle;
import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
@@ -55,6 +56,7 @@ public class ResolverListController {
private static final String TAG = "ResolverListController";
private static final boolean DEBUG = false;
+ private final UserHandle mUserHandle;
private AbstractResolverComparator mResolverComparator;
private boolean isComputed = false;
@@ -64,8 +66,9 @@ public class ResolverListController {
PackageManager pm,
Intent targetIntent,
String referrerPackage,
- int launchedFromUid) {
- this(context, pm, targetIntent, referrerPackage, launchedFromUid,
+ int launchedFromUid,
+ UserHandle userHandle) {
+ this(context, pm, targetIntent, referrerPackage, launchedFromUid, userHandle,
new ResolverRankerServiceResolverComparator(
context, targetIntent, referrerPackage, null));
}
@@ -76,12 +79,14 @@ public class ResolverListController {
Intent targetIntent,
String referrerPackage,
int launchedFromUid,
+ UserHandle userHandle,
AbstractResolverComparator resolverComparator) {
mContext = context;
mpm = pm;
mLaunchedFromUid = launchedFromUid;
mTargetIntent = targetIntent;
mReferrerPackage = referrerPackage;
+ mUserHandle = userHandle;
mResolverComparator = resolverComparator;
}
@@ -116,7 +121,8 @@ public class ResolverListController {
|| (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) != 0) {
flags |= PackageManager.MATCH_INSTANT;
}
- final List<ResolveInfo> infos = mpm.queryIntentActivities(intent, flags);
+ final List<ResolveInfo> infos = mpm.queryIntentActivitiesAsUser(intent, flags,
+ mUserHandle);
if (infos != null) {
if (resolvedComponents == null) {
resolvedComponents = new ArrayList<>();
@@ -127,6 +133,10 @@ public class ResolverListController {
return resolvedComponents;
}
+ UserHandle getUserHandle() {
+ return mUserHandle;
+ }
+
@VisibleForTesting
public void addResolveListDedupe(List<ResolverActivity.ResolvedComponentInfo> into,
Intent intent,
diff --git a/core/java/com/android/internal/app/ResolverMultiProfilePagerAdapter.java b/core/java/com/android/internal/app/ResolverMultiProfilePagerAdapter.java
new file mode 100644
index 000000000000..d72c52bfe6b6
--- /dev/null
+++ b/core/java/com/android/internal/app/ResolverMultiProfilePagerAdapter.java
@@ -0,0 +1,122 @@
+/*
+ * Copyright (C) 2019 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 com.android.internal.app;
+
+import android.content.Context;
+import android.view.LayoutInflater;
+import android.view.ViewGroup;
+import android.widget.ListView;
+
+import com.android.internal.R;
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.widget.PagerAdapter;
+
+/**
+ * A {@link PagerAdapter} which describes the work and personal profile intent resolver screens.
+ */
+@VisibleForTesting
+public class ResolverMultiProfilePagerAdapter extends AbstractMultiProfilePagerAdapter {
+
+ private final ResolverProfileDescriptor[] mItems;
+
+ ResolverMultiProfilePagerAdapter(Context context,
+ ResolverListAdapter adapter) {
+ super(context, /* currentPage */ 0);
+ mItems = new ResolverProfileDescriptor[] {
+ createProfileDescriptor(adapter)
+ };
+ }
+
+ ResolverMultiProfilePagerAdapter(Context context,
+ ResolverListAdapter personalAdapter,
+ ResolverListAdapter workAdapter,
+ @Profile int defaultProfile) {
+ super(context, /* currentPage */ defaultProfile);
+ mItems = new ResolverProfileDescriptor[] {
+ createProfileDescriptor(personalAdapter),
+ createProfileDescriptor(workAdapter)
+ };
+ }
+
+ private ResolverProfileDescriptor createProfileDescriptor(
+ ResolverListAdapter adapter) {
+ final LayoutInflater inflater = LayoutInflater.from(getContext());
+ final ViewGroup rootView =
+ (ViewGroup) inflater.inflate(R.layout.resolver_list_per_profile, null, false);
+ return new ResolverProfileDescriptor(rootView, adapter);
+ }
+
+ ListView getListViewForIndex(int index) {
+ return getItem(index).listView;
+ }
+
+ @Override
+ ResolverProfileDescriptor getItem(int pageIndex) {
+ return mItems[pageIndex];
+ }
+
+ @Override
+ int getItemCount() {
+ return mItems.length;
+ }
+
+ @Override
+ void setupListAdapter(int pageIndex) {
+ final ListView listView = getItem(pageIndex).listView;
+ listView.setAdapter(getItem(pageIndex).resolverListAdapter);
+ }
+
+ @Override
+ ResolverListAdapter getAdapterForIndex(int pageIndex) {
+ return mItems[pageIndex].resolverListAdapter;
+ }
+
+ @Override
+ @VisibleForTesting
+ public ResolverListAdapter getActiveListAdapter() {
+ return getAdapterForIndex(getCurrentPage());
+ }
+
+ @Override
+ @VisibleForTesting
+ public ResolverListAdapter getInactiveListAdapter() {
+ if (getCount() == 1) {
+ return null;
+ }
+ return getAdapterForIndex(1 - getCurrentPage());
+ }
+
+ @Override
+ ResolverListAdapter getCurrentRootAdapter() {
+ return getActiveListAdapter();
+ }
+
+ @Override
+ ListView getCurrentAdapterView() {
+ return getListViewForIndex(getCurrentPage());
+ }
+
+ class ResolverProfileDescriptor extends ProfileDescriptor {
+ private ResolverListAdapter resolverListAdapter;
+ final ListView listView;
+ ResolverProfileDescriptor(ViewGroup rootView, ResolverListAdapter adapter) {
+ super(rootView);
+ resolverListAdapter = adapter;
+ listView = rootView.findViewById(R.id.resolver_list);
+ }
+ }
+}
diff --git a/core/java/com/android/internal/app/ResolverTargetActionsDialogFragment.java b/core/java/com/android/internal/app/ResolverTargetActionsDialogFragment.java
index df91c4a1f88d..21efc78bddf8 100644
--- a/core/java/com/android/internal/app/ResolverTargetActionsDialogFragment.java
+++ b/core/java/com/android/internal/app/ResolverTargetActionsDialogFragment.java
@@ -24,14 +24,19 @@ import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
+import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import com.android.internal.R;
+import com.android.internal.app.chooser.DisplayResolveInfo;
+
+import java.util.ArrayList;
+import java.util.List;
/**
- * Shows a dialog with actions to take on a chooser target
+ * Shows a dialog with actions to take on a chooser target.
*/
public class ResolverTargetActionsDialogFragment extends DialogFragment
implements DialogInterface.OnClickListener {
@@ -43,6 +48,10 @@ public class ResolverTargetActionsDialogFragment extends DialogFragment
private static final int TOGGLE_PIN_INDEX = 0;
private static final int APP_INFO_INDEX = 1;
+ private List<DisplayResolveInfo> mTargetInfos = new ArrayList<>();
+ private List<CharSequence> mLabels = new ArrayList<>();
+ private boolean[] mPinned;
+
public ResolverTargetActionsDialogFragment() {
}
@@ -55,15 +64,43 @@ public class ResolverTargetActionsDialogFragment extends DialogFragment
setArguments(args);
}
+ public ResolverTargetActionsDialogFragment(CharSequence title, ComponentName name,
+ List<DisplayResolveInfo> targets, List<CharSequence> labels) {
+ Bundle args = new Bundle();
+ args.putCharSequence(TITLE_KEY, title);
+ args.putParcelable(NAME_KEY, name);
+ mTargetInfos = targets;
+ mLabels = labels;
+ setArguments(args);
+ }
+
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Bundle args = getArguments();
final int itemRes = args.getBoolean(PINNED_KEY, false)
? R.array.resolver_target_actions_unpin
: R.array.resolver_target_actions_pin;
+ String[] defaultActions = getResources().getStringArray(itemRes);
+ CharSequence[] items;
+
+ if (mTargetInfos == null || mTargetInfos.size() < 2) {
+ items = defaultActions;
+ } else {
+ // Pin item for each sub-item
+ items = new CharSequence[mTargetInfos.size() + 1];
+ for (int i = 0; i < mTargetInfos.size(); i++) {
+ items[i] = mTargetInfos.get(i).isPinned()
+ ? getResources().getString(R.string.unpin_specific_target, mLabels.get(i))
+ : getResources().getString(R.string.pin_specific_target, mLabels.get(i));
+ }
+ // "App info"
+ items[mTargetInfos.size()] = defaultActions[1];
+ }
+
+
return new Builder(getContext())
.setCancelable(true)
- .setItems(itemRes, this)
+ .setItems(items, this)
.setTitle(args.getCharSequence(TITLE_KEY))
.create();
}
@@ -72,27 +109,41 @@ public class ResolverTargetActionsDialogFragment extends DialogFragment
public void onClick(DialogInterface dialog, int which) {
final Bundle args = getArguments();
ComponentName name = args.getParcelable(NAME_KEY);
- switch (which) {
- case TOGGLE_PIN_INDEX:
- SharedPreferences sp = ChooserActivity.getPinnedSharedPrefs(getContext());
- final String key = name.flattenToString();
- boolean currentVal = sp.getBoolean(name.flattenToString(), false);
- if (currentVal) {
- sp.edit().remove(key).apply();
- } else {
- sp.edit().putBoolean(key, true).apply();
- }
-
- // Force the chooser to requery and resort things
- getActivity().recreate();
- break;
- case APP_INFO_INDEX:
- Intent in = new Intent().setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
- .setData(Uri.fromParts("package", name.getPackageName(), null))
- .addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
- startActivity(in);
- break;
+ if (which == 0 || (mTargetInfos.size() > 0 && which < mTargetInfos.size())) {
+ if (mTargetInfos == null || mTargetInfos.size() == 0) {
+ pinComponent(name);
+ } else {
+ pinComponent(mTargetInfos.get(which).getResolvedComponentName());
+ }
+ // Force the chooser to requery and resort things
+ ((ChooserActivity) getActivity()).handlePackagesChanged();
+ } else {
+ // Last item in dialog is App Info
+ Intent in = new Intent().setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
+ .setData(Uri.fromParts("package", name.getPackageName(), null))
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
+ startActivity(in);
+ }
+ dismiss();
+ }
+
+ private void pinComponent(ComponentName name) {
+ SharedPreferences sp = ChooserActivity.getPinnedSharedPrefs(getContext());
+ final String key = name.flattenToString();
+ boolean currentVal = sp.getBoolean(name.flattenToString(), false);
+ if (currentVal) {
+ sp.edit().remove(key).apply();
+ } else {
+ sp.edit().putBoolean(key, true).apply();
}
+ }
+
+ @Override
+ public void onConfigurationChanged(Configuration newConfig) {
+ // Dismiss on config changed (eg: rotation)
+ // TODO: Maintain state on config change
+ super.onConfigurationChanged(newConfig);
dismiss();
}
+
}
diff --git a/core/java/com/android/internal/app/WrapHeightViewPager.java b/core/java/com/android/internal/app/WrapHeightViewPager.java
new file mode 100644
index 000000000000..b017bb44d751
--- /dev/null
+++ b/core/java/com/android/internal/app/WrapHeightViewPager.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2019 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 com.android.internal.app;
+
+import android.content.Context;
+import android.util.AttributeSet;
+import android.view.View;
+
+import com.android.internal.widget.ViewPager;
+
+/**
+ * A {@link ViewPager} which wraps around its first child's height.
+ * <p>Normally {@link ViewPager} instances expand their height to cover all remaining space in
+ * the layout.
+ * <p>This class is used for the intent resolver picker's tabbed view to maintain
+ * consistency with the previous behavior.
+ */
+public class WrapHeightViewPager extends ViewPager {
+
+ public WrapHeightViewPager(Context context) {
+ super(context);
+ }
+
+ public WrapHeightViewPager(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ }
+
+ public WrapHeightViewPager(Context context, AttributeSet attrs, int defStyleAttr) {
+ super(context, attrs, defStyleAttr);
+ }
+
+ public WrapHeightViewPager(Context context, AttributeSet attrs,
+ int defStyleAttr, int defStyleRes) {
+ super(context, attrs, defStyleAttr, defStyleRes);
+ }
+
+ // TODO(arangelov): When we have multiple pages, the height should wrap to the currently
+ // displayed page. Investigate whether onMeasure is called when changing a page, and instead
+ // of getChildAt(0), use the currently displayed one.
+ @Override
+ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
+ super.onMeasure(widthMeasureSpec, heightMeasureSpec);
+ if (MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.AT_MOST) {
+ return;
+ }
+ widthMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY);
+ int height = getMeasuredHeight();
+ if (getChildCount() > 0) {
+ View firstChild = getChildAt(0);
+ firstChild.measure(widthMeasureSpec,
+ MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST));
+ height = firstChild.getMeasuredHeight();
+ }
+ heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
+ super.onMeasure(widthMeasureSpec, heightMeasureSpec);
+ }
+}
diff --git a/core/java/com/android/internal/app/chooser/DisplayResolveInfo.java b/core/java/com/android/internal/app/chooser/DisplayResolveInfo.java
index f92637c1bf01..86a9af3db196 100644
--- a/core/java/com/android/internal/app/chooser/DisplayResolveInfo.java
+++ b/core/java/com/android/internal/app/chooser/DisplayResolveInfo.java
@@ -91,6 +91,16 @@ public class DisplayResolveInfo implements TargetInfo {
mResolveInfoPresentationGetter = resolveInfoPresentationGetter;
}
+ DisplayResolveInfo(DisplayResolveInfo other) {
+ mSourceIntents.addAll(other.getAllSourceIntents());
+ mResolveInfo = other.mResolveInfo;
+ mDisplayLabel = other.mDisplayLabel;
+ mDisplayIcon = other.mDisplayIcon;
+ mExtendedInfo = other.mExtendedInfo;
+ mResolvedIntent = other.mResolvedIntent;
+ mResolveInfoPresentationGetter = other.mResolveInfoPresentationGetter;
+ }
+
public ResolveInfo getResolveInfo() {
return mResolveInfo;
}
@@ -189,4 +199,5 @@ public class DisplayResolveInfo implements TargetInfo {
public void setPinned(boolean pinned) {
mPinned = pinned;
}
+
}
diff --git a/core/java/com/android/internal/app/chooser/MultiDisplayResolveInfo.java b/core/java/com/android/internal/app/chooser/MultiDisplayResolveInfo.java
new file mode 100644
index 000000000000..4c52411d6376
--- /dev/null
+++ b/core/java/com/android/internal/app/chooser/MultiDisplayResolveInfo.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2019 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 com.android.internal.app.chooser;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Represents a "stack" of chooser targets for various activities within the same component.
+ */
+public class MultiDisplayResolveInfo extends DisplayResolveInfo {
+
+ List<DisplayResolveInfo> mTargetInfos = new ArrayList<>();
+ String mPackageName;
+ // We'll use this DRI for basic presentation info - eg icon, name.
+ final DisplayResolveInfo mBaseInfo;
+
+ /**
+ * @param firstInfo A representative DRI to use for the main icon, title, etc for this Info.
+ */
+ public MultiDisplayResolveInfo(String packageName, DisplayResolveInfo firstInfo) {
+ super(firstInfo);
+ mBaseInfo = firstInfo;
+ mTargetInfos.add(firstInfo);
+ }
+
+ /**
+ * Add another DisplayResolveInfo to the list included for this target.
+ */
+ public void addTarget(DisplayResolveInfo target) {
+ mTargetInfos.add(target);
+ }
+
+ /**
+ * List of all DisplayResolveInfos included in this target.
+ */
+ public List<DisplayResolveInfo> getTargets() {
+ return mTargetInfos;
+ }
+
+}
diff --git a/core/java/com/android/internal/content/FileSystemProvider.java b/core/java/com/android/internal/content/FileSystemProvider.java
index f5708a5c89af..dec9ae701fb2 100644
--- a/core/java/com/android/internal/content/FileSystemProvider.java
+++ b/core/java/com/android/internal/content/FileSystemProvider.java
@@ -259,7 +259,7 @@ public abstract class FileSystemProvider extends DocumentsProvider {
throw new IllegalStateException("Failed to touch " + file + ": " + e);
}
}
- MediaStore.scanFile(getContext(), file);
+ MediaStore.scanFile(getContext().getContentResolver(), file);
return childId;
}
@@ -316,10 +316,10 @@ public abstract class FileSystemProvider extends DocumentsProvider {
private void moveInMediaStore(@Nullable File oldVisibleFile, @Nullable File newVisibleFile) {
if (oldVisibleFile != null) {
- MediaStore.scanFile(getContext(), oldVisibleFile);
+ MediaStore.scanFile(getContext().getContentResolver(), oldVisibleFile);
}
if (newVisibleFile != null) {
- MediaStore.scanFile(getContext(), newVisibleFile);
+ MediaStore.scanFile(getContext().getContentResolver(), newVisibleFile);
}
}
diff --git a/core/java/com/android/internal/content/NativeLibraryHelper.java b/core/java/com/android/internal/content/NativeLibraryHelper.java
index f5fae1932cc4..22fe31eeda38 100644
--- a/core/java/com/android/internal/content/NativeLibraryHelper.java
+++ b/core/java/com/android/internal/content/NativeLibraryHelper.java
@@ -444,7 +444,7 @@ public class NativeLibraryHelper {
return sum;
}
- /**
+ /**
* Configure the native library files managed by Incremental Service. Makes sure Incremental
* Service will create native library directories and set up native library binary files in the
* same structure as they are in non-incremental installations.
@@ -458,8 +458,20 @@ public class NativeLibraryHelper {
*/
public static int configureNativeBinariesForSupportedAbi(AndroidPackage pkg, Handle handle,
File libraryRoot, String[] abiList, boolean useIsaSubdir) {
- // TODO(b/136132412): Implement this.
- return -1;
+ int abi = findSupportedAbi(handle, abiList);
+ if (abi < 0) {
+ Slog.e(TAG, "Failed to find find matching ABI.");
+ return abi;
+ }
+
+ // Currently only support installations that have pre-configured native library files
+ // TODO(b/136132412): implement this after incfs supports file mapping
+ if (!libraryRoot.exists()) {
+ Slog.e(TAG, "Incremental installation currently does not configure native libs");
+ return INSTALL_FAILED_NO_MATCHING_ABIS;
+ }
+
+ return abi;
}
// We don't care about the other return values for now.
diff --git a/core/java/com/android/internal/content/PackageMonitor.java b/core/java/com/android/internal/content/PackageMonitor.java
index 6e9c4c36d40b..6b76a0f4127d 100644
--- a/core/java/com/android/internal/content/PackageMonitor.java
+++ b/core/java/com/android/internal/content/PackageMonitor.java
@@ -28,9 +28,9 @@ import android.os.UserHandle;
import android.util.Slog;
import com.android.internal.os.BackgroundThread;
-import com.android.internal.util.Preconditions;
import java.util.HashSet;
+import java.util.Objects;
/**
* Helper class for monitoring the state of packages: adding, removing,
@@ -93,7 +93,7 @@ public abstract class PackageMonitor extends android.content.BroadcastReceiver {
throw new IllegalStateException("Already registered");
}
mRegisteredContext = context;
- mRegisteredHandler = Preconditions.checkNotNull(handler);
+ mRegisteredHandler = Objects.requireNonNull(handler);
if (user != null) {
context.registerReceiverAsUser(this, user, sPackageFilt, null, mRegisteredHandler);
context.registerReceiverAsUser(this, user, sNonDataFilt, null, mRegisteredHandler);
diff --git a/core/java/com/android/internal/infra/AndroidFuture.java b/core/java/com/android/internal/infra/AndroidFuture.java
index c8929e93f030..b250578c8454 100644
--- a/core/java/com/android/internal/infra/AndroidFuture.java
+++ b/core/java/com/android/internal/infra/AndroidFuture.java
@@ -513,6 +513,11 @@ public class AndroidFuture<T> extends CompletableFuture<T> implements Parcelable
try {
result = get();
} catch (Exception t) {
+ // Exceptions coming out of get() are wrapped in ExecutionException, which is not
+ // handled by Parcel.
+ if (t instanceof ExecutionException && t.getCause() instanceof Exception) {
+ t = (Exception) t.getCause();
+ }
dest.writeBoolean(true);
dest.writeException(t);
return;
@@ -526,6 +531,12 @@ public class AndroidFuture<T> extends CompletableFuture<T> implements Parcelable
try {
AndroidFuture.this.complete((T) resultContainer.get());
} catch (Throwable t) {
+ // If resultContainer was completed exceptionally, get() wraps the
+ // underlying exception in an ExecutionException. Unwrap it now to avoid
+ // double-layering ExecutionExceptions.
+ if (t instanceof ExecutionException && t.getCause() != null) {
+ t = t.getCause();
+ }
completeExceptionally(t);
}
}
diff --git a/core/java/com/android/internal/infra/ServiceConnector.java b/core/java/com/android/internal/infra/ServiceConnector.java
index 98d679eb776b..857377afd3e8 100644
--- a/core/java/com/android/internal/infra/ServiceConnector.java
+++ b/core/java/com/android/internal/infra/ServiceConnector.java
@@ -32,7 +32,6 @@ import android.text.TextUtils;
import android.util.DebugUtils;
import android.util.Log;
-import com.android.internal.util.Preconditions;
import com.android.internal.util.function.pooled.PooledLambda;
import java.io.PrintWriter;
@@ -40,6 +39,7 @@ import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
@@ -352,7 +352,7 @@ public interface ServiceConnector<I extends IInterface> {
@Override
public <R> CompletionAwareJob<I, R> postForResult(@NonNull Job<I, R> job) {
CompletionAwareJob<I, R> task = new CompletionAwareJob<>();
- task.mDelegate = Preconditions.checkNotNull(job);
+ task.mDelegate = Objects.requireNonNull(job);
enqueue(task);
return task;
}
@@ -360,7 +360,7 @@ public interface ServiceConnector<I extends IInterface> {
@Override
public <R> AndroidFuture<R> postAsync(@NonNull Job<I, CompletableFuture<R>> job) {
CompletionAwareJob<I, R> task = new CompletionAwareJob<>();
- task.mDelegate = Preconditions.checkNotNull((Job) job);
+ task.mDelegate = Objects.requireNonNull((Job) job);
task.mAsync = true;
enqueue(task);
return task;
diff --git a/core/java/com/android/internal/infra/TEST_MAPPING b/core/java/com/android/internal/infra/TEST_MAPPING
index 3781d637f68c..3de107e892b6 100644
--- a/core/java/com/android/internal/infra/TEST_MAPPING
+++ b/core/java/com/android/internal/infra/TEST_MAPPING
@@ -6,10 +6,18 @@
{
"name": "CtsPermissionTestCases",
"options": [
- {
- "include-filter": "android.permission.cts.PermissionControllerTest"
- }
+ {
+ "include-filter": "android.permission.cts.PermissionControllerTest"
+ }
+ ]
+ },
+ {
+ "name": "FrameworksCoreTests",
+ "options": [
+ {
+ "include-filter": "com.android.internal.infra."
+ }
]
}
]
-} \ No newline at end of file
+}
diff --git a/core/java/com/android/internal/infra/WhitelistHelper.java b/core/java/com/android/internal/infra/WhitelistHelper.java
index 9d653bad4d00..b1d85f78984c 100644
--- a/core/java/com/android/internal/infra/WhitelistHelper.java
+++ b/core/java/com/android/internal/infra/WhitelistHelper.java
@@ -23,10 +23,9 @@ import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.Log;
-import com.android.internal.util.Preconditions;
-
import java.io.PrintWriter;
import java.util.List;
+import java.util.Objects;
/**
* Helper class for keeping track of whitelisted packages/activities.
@@ -107,7 +106,7 @@ public final class WhitelistHelper {
* Returns {@code true} if the entire package is whitelisted.
*/
public boolean isWhitelisted(@NonNull String packageName) {
- Preconditions.checkNotNull(packageName);
+ Objects.requireNonNull(packageName);
if (mWhitelistedPackages == null) return false;
@@ -119,7 +118,7 @@ public final class WhitelistHelper {
* Returns {@code true} if the specified activity is whitelisted.
*/
public boolean isWhitelisted(@NonNull ComponentName componentName) {
- Preconditions.checkNotNull(componentName);
+ Objects.requireNonNull(componentName);
final String packageName = componentName.getPackageName();
final ArraySet<ComponentName> whitelistedComponents = getWhitelistedComponents(packageName);
@@ -136,7 +135,7 @@ public final class WhitelistHelper {
*/
@Nullable
public ArraySet<ComponentName> getWhitelistedComponents(@NonNull String packageName) {
- Preconditions.checkNotNull(packageName);
+ Objects.requireNonNull(packageName);
return mWhitelistedPackages == null ? null : mWhitelistedPackages.get(packageName);
}
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index bc44fcf3691d..d0a83c4369a6 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -16,6 +16,9 @@
package com.android.internal.os;
+import static android.os.BatteryStatsManager.NUM_WIFI_STATES;
+import static android.os.BatteryStatsManager.NUM_WIFI_SUPPL_STATES;
+
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.UnsupportedAppUsage;
@@ -5267,7 +5270,7 @@ public class BatteryStatsImpl extends BatteryStats {
// Unknown is included in DATA_CONNECTION_OTHER.
int bin = DATA_CONNECTION_OUT_OF_SERVICE;
if (hasData) {
- if (dataType > 0 && dataType <= TelephonyManager.MAX_NETWORK_TYPE) {
+ if (dataType > 0 && dataType <= TelephonyManager.getAllNetworkTypes().length) {
bin = dataType;
} else {
switch (serviceType) {
diff --git a/core/java/com/android/internal/os/FuseAppLoop.java b/core/java/com/android/internal/os/FuseAppLoop.java
index d08930b007ff..a22615ba19ef 100644
--- a/core/java/com/android/internal/os/FuseAppLoop.java
+++ b/core/java/com/android/internal/os/FuseAppLoop.java
@@ -32,6 +32,7 @@ import com.android.internal.util.Preconditions;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
+import java.util.Objects;
import java.util.concurrent.ThreadFactory;
public class FuseAppLoop implements Handler.Callback {
@@ -92,8 +93,8 @@ public class FuseAppLoop implements Handler.Callback {
public int registerCallback(@NonNull ProxyFileDescriptorCallback callback,
@NonNull Handler handler) throws FuseUnavailableMountException {
synchronized (mLock) {
- Preconditions.checkNotNull(callback);
- Preconditions.checkNotNull(handler);
+ Objects.requireNonNull(callback);
+ Objects.requireNonNull(handler);
Preconditions.checkState(
mCallbackMap.size() < Integer.MAX_VALUE - MIN_INODE, "Too many opened files.");
Preconditions.checkArgument(
@@ -333,8 +334,8 @@ public class FuseAppLoop implements Handler.Callback {
boolean opened;
CallbackEntry(ProxyFileDescriptorCallback callback, Handler handler) {
- this.callback = Preconditions.checkNotNull(callback);
- this.handler = Preconditions.checkNotNull(handler);
+ this.callback = Objects.requireNonNull(callback);
+ this.handler = Objects.requireNonNull(handler);
}
long getThreadId() {
@@ -368,7 +369,7 @@ public class FuseAppLoop implements Handler.Callback {
void stopUsing(long threadId) {
final BytesMapEntry entry = mEntries.get(threadId);
- Preconditions.checkNotNull(entry);
+ Objects.requireNonNull(entry);
entry.counter--;
if (entry.counter <= 0) {
mEntries.remove(threadId);
diff --git a/core/java/com/android/internal/os/RuntimeInit.java b/core/java/com/android/internal/os/RuntimeInit.java
index a21187165c65..fa823c4bf2f6 100644
--- a/core/java/com/android/internal/os/RuntimeInit.java
+++ b/core/java/com/android/internal/os/RuntimeInit.java
@@ -367,8 +367,8 @@ public class RuntimeInit {
if (DEBUG) Slog.d(TAG, "Leaving RuntimeInit!");
}
- protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
- ClassLoader classLoader) {
+ protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,
+ String[] argv, ClassLoader classLoader) {
// If the application calls System.exit(), terminate the process
// immediately without running any shutdown hooks. It is not possible to
// shutdown an Android application gracefully. Among other things, the
@@ -377,6 +377,7 @@ public class RuntimeInit {
nativeSetExitWithoutCleanup(true);
VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
+ VMRuntime.getRuntime().setDisabledCompatChanges(disabledCompatChanges);
final Arguments args = new Arguments(argv);
diff --git a/core/java/com/android/internal/os/WrapperInit.java b/core/java/com/android/internal/os/WrapperInit.java
index f0e779694c90..790d7f7ab694 100644
--- a/core/java/com/android/internal/os/WrapperInit.java
+++ b/core/java/com/android/internal/os/WrapperInit.java
@@ -23,16 +23,18 @@ import android.system.Os;
import android.system.OsConstants;
import android.system.StructCapUserData;
import android.system.StructCapUserHeader;
-import android.util.TimingsTraceLog;
import android.util.Slog;
+import android.util.TimingsTraceLog;
+
import dalvik.system.VMRuntime;
+
+import libcore.io.IoUtils;
+
import java.io.DataOutputStream;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
-import libcore.io.IoUtils;
-
/**
* Startup class for the wrapper process.
* @hide
@@ -166,10 +168,10 @@ public class WrapperInit {
System.arraycopy(argv, 2, removedArgs, 0, argv.length - 2);
argv = removedArgs;
}
-
// Perform the same initialization that would happen after the Zygote forks.
Zygote.nativePreApplicationInit();
- return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
+ return RuntimeInit.applicationInit(targetSdkVersion, /*disabledCompatChanges*/ null,
+ argv, classLoader);
}
/**
diff --git a/core/java/com/android/internal/os/Zygote.java b/core/java/com/android/internal/os/Zygote.java
index fbacdd73dabb..c390a518bb22 100644
--- a/core/java/com/android/internal/os/Zygote.java
+++ b/core/java/com/android/internal/os/Zygote.java
@@ -151,6 +151,9 @@ public final class Zygote {
/** Make the new process have top application priority. */
public static final String START_AS_TOP_APP_ARG = "--is-top-app";
+ /** List of packages with the same uid, and its app data info: volume uuid and inode. */
+ public static final String PKG_DATA_INFO_MAP = "--pkg-data-info-map";
+
/**
* An extraArg passed when a zygote process is forking a child-zygote, specifying a name
* in the abstract socket namespace. This socket name is what the new child zygote
@@ -254,6 +257,8 @@ public final class Zygote {
* @param instructionSet null-ok the instruction set to use.
* @param appDataDir null-ok the data directory of the app.
* @param isTopApp true if the process is for top (high priority) application.
+ * @param pkgDataInfoList A list that stores related packages and its app data
+ * info: volume uuid and inode.
*
* @return 0 if this is the child, pid of the child
* if this is the parent, or -1 on error.
@@ -261,12 +266,13 @@ public final class Zygote {
static int forkAndSpecialize(int uid, int gid, int[] gids, int runtimeFlags,
int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
int[] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir,
- int targetSdkVersion, boolean isTopApp) {
+ int targetSdkVersion, boolean isTopApp, String[] pkgDataInfoList) {
ZygoteHooks.preFork();
int pid = nativeForkAndSpecialize(
uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
- fdsToIgnore, startChildZygote, instructionSet, appDataDir, isTopApp);
+ fdsToIgnore, startChildZygote, instructionSet, appDataDir, isTopApp,
+ pkgDataInfoList);
// Enable tracing as soon as possible for the child process.
if (pid == 0) {
Zygote.disableExecuteOnly(targetSdkVersion);
@@ -286,7 +292,7 @@ public final class Zygote {
private static native int nativeForkAndSpecialize(int uid, int gid, int[] gids,
int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
int[] fdsToClose, int[] fdsToIgnore, boolean startChildZygote, String instructionSet,
- String appDataDir, boolean isTopApp);
+ String appDataDir, boolean isTopApp, String[] pkgDataInfoList);
/**
* Specialize an unspecialized app process. The current VM must have been started
@@ -309,12 +315,16 @@ public final class Zygote {
* @param instructionSet null-ok The instruction set to use.
* @param appDataDir null-ok The data directory of the app.
* @param isTopApp True if the process is for top (high priority) application.
+ * @param pkgDataInfoList A list that stores related packages and its app data
+ * info: volume uuid and inode.
*/
private static void specializeAppProcess(int uid, int gid, int[] gids, int runtimeFlags,
int[][] rlimits, int mountExternal, String seInfo, String niceName,
- boolean startChildZygote, String instructionSet, String appDataDir, boolean isTopApp) {
+ boolean startChildZygote, String instructionSet, String appDataDir, boolean isTopApp,
+ String[] pkgDataInfoList) {
nativeSpecializeAppProcess(uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo,
- niceName, startChildZygote, instructionSet, appDataDir, isTopApp);
+ niceName, startChildZygote, instructionSet, appDataDir, isTopApp,
+ pkgDataInfoList);
// Enable tracing as soon as possible for the child process.
Trace.setTracingEnabled(true, runtimeFlags);
@@ -336,7 +346,8 @@ public final class Zygote {
private static native void nativeSpecializeAppProcess(int uid, int gid, int[] gids,
int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
- boolean startChildZygote, String instructionSet, String appDataDir, boolean isTopApp);
+ boolean startChildZygote, String instructionSet, String appDataDir, boolean isTopApp,
+ String[] pkgDataInfoList);
/**
* Called to do any initialization before starting an application.
@@ -665,13 +676,15 @@ public final class Zygote {
specializeAppProcess(args.mUid, args.mGid, args.mGids,
args.mRuntimeFlags, rlimits, args.mMountExternal,
args.mSeInfo, args.mNiceName, args.mStartChildZygote,
- args.mInstructionSet, args.mAppDataDir, args.mIsTopApp);
+ args.mInstructionSet, args.mAppDataDir, args.mIsTopApp,
+ args.mPkgDataInfoList);
disableExecuteOnly(args.mTargetSdkVersion);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
return ZygoteInit.zygoteInit(args.mTargetSdkVersion,
+ args.mDisabledCompatChanges,
args.mRemainingArgs,
null /* classLoader */);
} finally {
diff --git a/core/java/com/android/internal/os/ZygoteArguments.java b/core/java/com/android/internal/os/ZygoteArguments.java
index a23e659db49a..d3499541a3a3 100644
--- a/core/java/com/android/internal/os/ZygoteArguments.java
+++ b/core/java/com/android/internal/os/ZygoteArguments.java
@@ -215,6 +215,18 @@ class ZygoteArguments {
boolean mIsTopApp;
/**
+ * A set of disabled app compatibility changes for the running app. From
+ * --disabled-compat-changes.
+ */
+ long[] mDisabledCompatChanges = null;
+
+ /**
+ * A list that stores all related packages and its data info: volume uuid and inode.
+ * Null if it does need to do app data isolation.
+ */
+ String[] mPkgDataInfoList;
+
+ /**
* Constructs instance and parses args
*
* @param args zygote command-line args
@@ -421,6 +433,18 @@ class ZygoteArguments {
expectRuntimeArgs = false;
} else if (arg.startsWith(Zygote.START_AS_TOP_APP_ARG)) {
mIsTopApp = true;
+ } else if (arg.startsWith("--disabled-compat-changes=")) {
+ if (mDisabledCompatChanges != null) {
+ throw new IllegalArgumentException("Duplicate arg specified");
+ }
+ final String[] params = getAssignmentList(arg);
+ final int length = params.length;
+ mDisabledCompatChanges = new long[length];
+ for (int i = 0; i < length; i++) {
+ mDisabledCompatChanges[i] = Long.parseLong(params[i]);
+ }
+ } else if (arg.startsWith(Zygote.PKG_DATA_INFO_MAP)) {
+ mPkgDataInfoList = getAssignmentList(arg);
} else {
break;
}
diff --git a/core/java/com/android/internal/os/ZygoteConnection.java b/core/java/com/android/internal/os/ZygoteConnection.java
index a14b09343a01..9c6a288372c6 100644
--- a/core/java/com/android/internal/os/ZygoteConnection.java
+++ b/core/java/com/android/internal/os/ZygoteConnection.java
@@ -258,7 +258,7 @@ class ZygoteConnection {
parsedArgs.mRuntimeFlags, rlimits, parsedArgs.mMountExternal, parsedArgs.mSeInfo,
parsedArgs.mNiceName, fdsToClose, fdsToIgnore, parsedArgs.mStartChildZygote,
parsedArgs.mInstructionSet, parsedArgs.mAppDataDir, parsedArgs.mTargetSdkVersion,
- parsedArgs.mIsTopApp);
+ parsedArgs.mIsTopApp, parsedArgs.mPkgDataInfoList);
try {
if (pid == 0) {
@@ -501,6 +501,7 @@ class ZygoteConnection {
} else {
if (!isZygote) {
return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
+ parsedArgs.mDisabledCompatChanges,
parsedArgs.mRemainingArgs, null /* classLoader */);
} else {
return ZygoteInit.childZygoteInit(parsedArgs.mTargetSdkVersion,
diff --git a/core/java/com/android/internal/os/ZygoteInit.java b/core/java/com/android/internal/os/ZygoteInit.java
index 9ee79eada626..49b4cf828db6 100644
--- a/core/java/com/android/internal/os/ZygoteInit.java
+++ b/core/java/com/android/internal/os/ZygoteInit.java
@@ -553,6 +553,7 @@ public class ZygoteInit {
* Pass the remaining arguments to SystemServer.
*/
return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
+ parsedArgs.mDisabledCompatChanges,
parsedArgs.mRemainingArgs, cl);
}
@@ -988,14 +989,16 @@ public class ZygoteInit {
*
* Current recognized args:
* <ul>
- * <li> <code> [--] &lt;start class name&gt; &lt;args&gt;
+ * <li> <code> [--] &lt;start class name&gt; &lt;args&gt;
* </ul>
*
* @param targetSdkVersion target SDK version
- * @param argv arg strings
+ * @param disabledCompatChanges set of disabled compat changes for the process (all others
+ * are enabled)
+ * @param argv arg strings
*/
- public static final Runnable zygoteInit(int targetSdkVersion, String[] argv,
- ClassLoader classLoader) {
+ public static final Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
+ String[] argv, ClassLoader classLoader) {
if (RuntimeInit.DEBUG) {
Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
}
@@ -1005,7 +1008,8 @@ public class ZygoteInit {
RuntimeInit.commonInit();
ZygoteInit.nativeZygoteInit();
- return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
+ return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
+ classLoader);
}
/**
diff --git a/core/java/com/android/internal/policy/DecorView.java b/core/java/com/android/internal/policy/DecorView.java
index c33b6dc0bba2..29b148c5afee 100644
--- a/core/java/com/android/internal/policy/DecorView.java
+++ b/core/java/com/android/internal/policy/DecorView.java
@@ -22,6 +22,8 @@ import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
import static android.os.Build.VERSION_CODES.M;
import static android.os.Build.VERSION_CODES.N;
+import static android.view.InsetsState.ITYPE_NAVIGATION_BAR;
+import static android.view.InsetsState.ITYPE_STATUS_BAR;
import static android.view.View.MeasureSpec.AT_MOST;
import static android.view.View.MeasureSpec.EXACTLY;
import static android.view.View.MeasureSpec.getMode;
@@ -74,6 +76,8 @@ import android.view.ActionMode;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.InputQueue;
+import android.view.InsetsState;
+import android.view.InsetsState.InternalInsetsType;
import android.view.KeyEvent;
import android.view.KeyboardShortcutGroup;
import android.view.LayoutInflater;
@@ -90,6 +94,9 @@ import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowCallbacks;
import android.view.WindowInsets;
+import android.view.WindowInsets.Side;
+import android.view.WindowInsets.Type;
+import android.view.WindowInsetsController;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
@@ -134,7 +141,7 @@ public class DecorView extends FrameLayout implements RootViewSurfaceTaker, Wind
Gravity.TOP, Gravity.LEFT, Gravity.RIGHT,
Window.STATUS_BAR_BACKGROUND_TRANSITION_NAME,
com.android.internal.R.id.statusBarBackground,
- FLAG_FULLSCREEN);
+ FLAG_FULLSCREEN, ITYPE_STATUS_BAR);
public static final ColorViewAttributes NAVIGATION_BAR_COLOR_VIEW_ATTRIBUTES =
new ColorViewAttributes(
@@ -142,7 +149,7 @@ public class DecorView extends FrameLayout implements RootViewSurfaceTaker, Wind
Gravity.BOTTOM, Gravity.RIGHT, Gravity.LEFT,
Window.NAVIGATION_BAR_BACKGROUND_TRANSITION_NAME,
com.android.internal.R.id.navigationBarBackground,
- 0 /* hideWindowFlag */);
+ 0 /* hideWindowFlag */, ITYPE_NAVIGATION_BAR);
// This is used to workaround an issue where the PiP shadow can be transparent if the window
// background is transparent
@@ -1085,6 +1092,9 @@ public class DecorView extends FrameLayout implements RootViewSurfaceTaker, Wind
WindowManager.LayoutParams attrs = mWindow.getAttributes();
int sysUiVisibility = attrs.systemUiVisibility | getWindowSystemUiVisibility();
+ final WindowInsetsController controller = getWindowInsetsController();
+ final InsetsState state = controller != null ? controller.getState() : null;
+
// IME is an exceptional floating window that requires color view.
final boolean isImeWindow =
mWindow.getAttributes().type == WindowManager.LayoutParams.TYPE_INPUT_METHOD;
@@ -1133,7 +1143,7 @@ public class DecorView extends FrameLayout implements RootViewSurfaceTaker, Wind
calculateNavigationBarColor(), mWindow.mNavigationBarDividerColor, navBarSize,
navBarToRightEdge || navBarToLeftEdge, navBarToLeftEdge,
0 /* sideInset */, animate && !disallowAnimate,
- mForceWindowDrawsBarBackgrounds);
+ mForceWindowDrawsBarBackgrounds, state);
boolean oldDrawLegacy = mDrawLegacyNavigationBarBackground;
mDrawLegacyNavigationBarBackground = mNavigationColorViewState.visible
&& (mWindow.getAttributes().flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0;
@@ -1154,7 +1164,7 @@ public class DecorView extends FrameLayout implements RootViewSurfaceTaker, Wind
calculateStatusBarColor(), 0, mLastTopInset,
false /* matchVertical */, statusBarNeedsLeftInset, statusBarSideInset,
animate && !disallowAnimate,
- mForceWindowDrawsBarBackgrounds);
+ mForceWindowDrawsBarBackgrounds, state);
}
// When we expand the window with FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS or
@@ -1164,16 +1174,19 @@ public class DecorView extends FrameLayout implements RootViewSurfaceTaker, Wind
// Note: We don't need to check for IN_SCREEN or INSET_DECOR because unlike the status bar,
// these flags wouldn't make the window draw behind the navigation bar, unless
// LAYOUT_HIDE_NAVIGATION was set.
- boolean hideNavigation = (sysUiVisibility & SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0;
+ boolean hideNavigation = (sysUiVisibility & SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0
+ || !(state == null || state.getSource(ITYPE_NAVIGATION_BAR).isVisible());
boolean forceConsumingNavBar = (mForceWindowDrawsBarBackgrounds
&& (attrs.flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0
&& (sysUiVisibility & SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) == 0
+ && (attrs.getFitWindowInsetsTypes() & Type.navigationBars()) != 0
&& !hideNavigation)
|| (mLastShouldAlwaysConsumeSystemBars && hideNavigation);
boolean consumingNavBar =
((attrs.flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0
&& (sysUiVisibility & SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) == 0
+ && (attrs.getFitWindowInsetsTypes() & Type.navigationBars()) != 0
&& !hideNavigation)
|| forceConsumingNavBar;
@@ -1182,18 +1195,21 @@ public class DecorView extends FrameLayout implements RootViewSurfaceTaker, Wind
// If we should always consume system bars, only consume that if the app wanted to go to
// fullscreen, as othrewise we can expect the app to handle it.
boolean fullscreen = (sysUiVisibility & SYSTEM_UI_FLAG_FULLSCREEN) != 0
- || (attrs.flags & FLAG_FULLSCREEN) != 0;
+ || (attrs.flags & FLAG_FULLSCREEN) != 0
+ || !(state == null || state.getSource(ITYPE_STATUS_BAR).isVisible());
boolean consumingStatusBar = (sysUiVisibility & SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) == 0
&& (attrs.flags & FLAG_LAYOUT_IN_SCREEN) == 0
&& (attrs.flags & FLAG_LAYOUT_INSET_DECOR) == 0
+ && (attrs.getFitWindowInsetsTypes() & Type.statusBars()) != 0
&& mForceWindowDrawsBarBackgrounds
&& mLastTopInset != 0
|| (mLastShouldAlwaysConsumeSystemBars && fullscreen);
- int consumedTop = consumingStatusBar ? mLastTopInset : 0;
- int consumedRight = consumingNavBar ? mLastRightInset : 0;
- int consumedBottom = consumingNavBar ? mLastBottomInset : 0;
- int consumedLeft = consumingNavBar ? mLastLeftInset : 0;
+ int sides = attrs.getFitWindowInsetsSides();
+ int consumedTop = consumingStatusBar && (sides & Side.TOP) != 0 ? mLastTopInset : 0;
+ int consumedRight = consumingNavBar && (sides & Side.RIGHT) != 0 ? mLastRightInset : 0;
+ int consumedBottom = consumingNavBar && (sides & Side.BOTTOM) != 0 ? mLastBottomInset : 0;
+ int consumedLeft = consumingNavBar && (sides & Side.LEFT) != 0 ? mLastLeftInset : 0;
if (mContentRoot != null
&& mContentRoot.getLayoutParams() instanceof MarginLayoutParams) {
@@ -1325,8 +1341,10 @@ public class DecorView extends FrameLayout implements RootViewSurfaceTaker, Wind
*/
private void updateColorViewInt(final ColorViewState state, int sysUiVis, int color,
int dividerColor, int size, boolean verticalBar, boolean seascape, int sideMargin,
- boolean animate, boolean force) {
- state.present = state.attributes.isPresent(sysUiVis, mWindow.getAttributes().flags, force);
+ boolean animate, boolean force, InsetsState insetsState) {
+ state.present = ViewRootImpl.sNewInsetsMode != ViewRootImpl.NEW_INSETS_MODE_FULL
+ ? state.attributes.isPresent(sysUiVis, mWindow.getAttributes().flags, force)
+ : state.attributes.isPresent(insetsState, mWindow.getAttributes().flags, force);
boolean show = state.attributes.isVisible(state.present, color,
mWindow.getAttributes().flags, force);
boolean showView = show && !isResizing() && size > 0;
@@ -2536,10 +2554,11 @@ public class DecorView extends FrameLayout implements RootViewSurfaceTaker, Wind
final int seascapeGravity;
final String transitionName;
final int hideWindowFlag;
+ final @InternalInsetsType int insetsType;
private ColorViewAttributes(int systemUiHideFlag, int translucentFlag, int verticalGravity,
int horizontalGravity, int seascapeGravity, String transitionName, int id,
- int hideWindowFlag) {
+ int hideWindowFlag, @InternalInsetsType int insetsType) {
this.id = id;
this.systemUiHideFlag = systemUiHideFlag;
this.translucentFlag = translucentFlag;
@@ -2548,8 +2567,10 @@ public class DecorView extends FrameLayout implements RootViewSurfaceTaker, Wind
this.seascapeGravity = seascapeGravity;
this.transitionName = transitionName;
this.hideWindowFlag = hideWindowFlag;
+ this.insetsType = insetsType;
}
+ // TODO(b/118118435): remove after migration
public boolean isPresent(int sysUiVis, int windowFlags, boolean force) {
return (sysUiVis & systemUiHideFlag) == 0
&& (windowFlags & hideWindowFlag) == 0
@@ -2557,16 +2578,27 @@ public class DecorView extends FrameLayout implements RootViewSurfaceTaker, Wind
|| force);
}
+ public boolean isPresent(InsetsState state, int windowFlags, boolean force) {
+ return (state == null || state.getSource(insetsType).isVisible())
+ && ((windowFlags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0 || force);
+ }
+
public boolean isVisible(boolean present, int color, int windowFlags, boolean force) {
return present
&& (color & Color.BLACK) != 0
&& ((windowFlags & translucentFlag) == 0 || force);
}
+ // TODO(b/118118435): remove after migration
public boolean isVisible(int sysUiVis, int color, int windowFlags, boolean force) {
final boolean present = isPresent(sysUiVis, windowFlags, force);
return isVisible(present, color, windowFlags, force);
}
+
+ public boolean isVisible(InsetsState state, int color, int windowFlags, boolean force) {
+ final boolean present = isPresent(state, windowFlags, force);
+ return isVisible(present, color, windowFlags, force);
+ }
}
/**
diff --git a/core/java/com/android/internal/policy/PhoneWindow.java b/core/java/com/android/internal/policy/PhoneWindow.java
index 764d4a598bd5..9aa56f03275f 100644
--- a/core/java/com/android/internal/policy/PhoneWindow.java
+++ b/core/java/com/android/internal/policy/PhoneWindow.java
@@ -22,7 +22,6 @@ import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static android.view.WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
import static android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
-import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
import static android.view.WindowManager.LayoutParams.FLAG_SPLIT_TOUCH;
@@ -2423,19 +2422,8 @@ public class PhoneWindow extends Window implements MenuBuilder.Callback {
final Context context = getContext();
final int targetSdk = context.getApplicationInfo().targetSdkVersion;
- final boolean targetPreHoneycomb = targetSdk < android.os.Build.VERSION_CODES.HONEYCOMB;
- final boolean targetPreIcs = targetSdk < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
final boolean targetPreL = targetSdk < android.os.Build.VERSION_CODES.LOLLIPOP;
final boolean targetPreQ = targetSdk < Build.VERSION_CODES.Q;
- final boolean targetHcNeedsOptions = context.getResources().getBoolean(
- R.bool.target_honeycomb_needs_options_menu);
- final boolean noActionBar = !hasFeature(FEATURE_ACTION_BAR) || hasFeature(FEATURE_NO_TITLE);
-
- if (targetPreHoneycomb || (targetPreIcs && targetHcNeedsOptions && noActionBar)) {
- setNeedsMenuKey(WindowManager.LayoutParams.NEEDS_MENU_SET_TRUE);
- } else {
- setNeedsMenuKey(WindowManager.LayoutParams.NEEDS_MENU_SET_FALSE);
- }
if (!mForcedStatusBarColor) {
mStatusBarColor = a.getColor(R.styleable.Window_statusBarColor, 0xFF000000);
diff --git a/core/java/com/android/internal/telephony/IPhoneStateListener.aidl b/core/java/com/android/internal/telephony/IPhoneStateListener.aidl
index 01f57438a02c..cb67309ce74f 100644
--- a/core/java/com/android/internal/telephony/IPhoneStateListener.aidl
+++ b/core/java/com/android/internal/telephony/IPhoneStateListener.aidl
@@ -43,7 +43,6 @@ oneway interface IPhoneStateListener {
void onDataConnectionStateChanged(int state, int networkType);
void onDataActivity(int direction);
void onSignalStrengthsChanged(in SignalStrength signalStrength);
- void onOtaspChanged(in int otaspMode);
void onCellInfoChanged(in List<CellInfo> cellInfo);
void onPreciseCallStateChanged(in PreciseCallState callState);
void onPreciseDataConnectionStateChanged(in PreciseDataConnectionState dataConnectionState);
diff --git a/core/java/com/android/internal/telephony/ITelephonyRegistry.aidl b/core/java/com/android/internal/telephony/ITelephonyRegistry.aidl
index 2f34aa087b30..f954679ebf4d 100644
--- a/core/java/com/android/internal/telephony/ITelephonyRegistry.aidl
+++ b/core/java/com/android/internal/telephony/ITelephonyRegistry.aidl
@@ -24,6 +24,8 @@ import android.telephony.CallQuality;
import android.telephony.CellInfo;
import android.telephony.ims.ImsReasonInfo;
import android.telephony.PhoneCapability;
+import android.telephony.PhysicalChannelConfig;
+import android.telephony.PreciseDataConnectionState;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.telephony.emergency.EmergencyNumber;
@@ -60,21 +62,13 @@ interface ITelephonyRegistry {
@UnsupportedAppUsage(maxTargetSdk = 28)
void notifyDataActivity(int state);
void notifyDataActivityForSubscriber(in int subId, int state);
- void notifyDataConnection(int state, boolean isDataConnectivityPossible,
- String apn, String apnType, in LinkProperties linkProperties,
- in NetworkCapabilities networkCapabilities, int networkType, boolean roaming);
- void notifyDataConnectionForSubscriber(int phoneId, int subId, int state,
- boolean isDataConnectivityPossible,
- String apn, String apnType, in LinkProperties linkProperties,
- in NetworkCapabilities networkCapabilities, int networkType, boolean roaming);
+ void notifyDataConnectionForSubscriber(
+ int phoneId, int subId, String apnType, in PreciseDataConnectionState preciseState);
@UnsupportedAppUsage
void notifyDataConnectionFailed(String apnType);
- void notifyDataConnectionFailedForSubscriber(int phoneId, int subId, String apnType);
@UnsupportedAppUsage(maxTargetSdk = 28)
void notifyCellLocation(in Bundle cellLocation);
void notifyCellLocationForSubscriber(in int subId, in Bundle cellLocation);
- @UnsupportedAppUsage(maxTargetSdk = 28)
- void notifyOtaspChanged(in int subId, in int otaspMode);
@UnsupportedAppUsage
void notifyCellInfo(in List<CellInfo> cellInfo);
void notifyPreciseCallState(int phoneId, int subId, int ringingCallState,
diff --git a/core/java/com/android/internal/util/FileRotator.java b/core/java/com/android/internal/util/FileRotator.java
index f8885a20970d..3ca33203f554 100644
--- a/core/java/com/android/internal/util/FileRotator.java
+++ b/core/java/com/android/internal/util/FileRotator.java
@@ -27,6 +27,7 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -96,8 +97,8 @@ public class FileRotator {
* may be deleted.
*/
public FileRotator(File basePath, String prefix, long rotateAgeMillis, long deleteAgeMillis) {
- mBasePath = Preconditions.checkNotNull(basePath);
- mPrefix = Preconditions.checkNotNull(prefix);
+ mBasePath = Objects.requireNonNull(basePath);
+ mPrefix = Objects.requireNonNull(prefix);
mRotateAgeMillis = rotateAgeMillis;
mDeleteAgeMillis = deleteAgeMillis;
@@ -406,7 +407,7 @@ public class FileRotator {
public long endMillis;
public FileInfo(String prefix) {
- this.prefix = Preconditions.checkNotNull(prefix);
+ this.prefix = Objects.requireNonNull(prefix);
}
/**
diff --git a/core/java/com/android/internal/util/ObjectUtils.java b/core/java/com/android/internal/util/ObjectUtils.java
index a47768870dfe..5568d91011dc 100644
--- a/core/java/com/android/internal/util/ObjectUtils.java
+++ b/core/java/com/android/internal/util/ObjectUtils.java
@@ -19,6 +19,7 @@ package com.android.internal.util;
import android.annotation.NonNull;
import android.annotation.Nullable;
+import java.util.Objects;
/** @hide */
public class ObjectUtils {
@@ -32,7 +33,7 @@ public class ObjectUtils {
*/
@NonNull
public static <T> T firstNotNull(@Nullable T a, @NonNull T b) {
- return a != null ? a : Preconditions.checkNotNull(b);
+ return a != null ? a : Objects.requireNonNull(b);
}
/**
diff --git a/core/java/com/android/internal/util/ScreenRecordHelper.java b/core/java/com/android/internal/util/ScreenRecordHelper.java
index 64d089848b7d..ec7ed4e0008a 100644
--- a/core/java/com/android/internal/util/ScreenRecordHelper.java
+++ b/core/java/com/android/internal/util/ScreenRecordHelper.java
@@ -24,10 +24,6 @@ import android.content.Intent;
* Helper class to initiate a screen recording
*/
public class ScreenRecordHelper {
- private static final String SYSUI_PACKAGE = "com.android.systemui";
- private static final String SYSUI_SCREENRECORD_LAUNCHER =
- "com.android.systemui.screenrecord.ScreenRecordDialog";
-
private final Context mContext;
/**
@@ -42,8 +38,9 @@ public class ScreenRecordHelper {
* Show dialog of screen recording options to user.
*/
public void launchRecordPrompt() {
- final ComponentName launcherComponent = new ComponentName(SYSUI_PACKAGE,
- SYSUI_SCREENRECORD_LAUNCHER);
+ final ComponentName launcherComponent = ComponentName.unflattenFromString(
+ mContext.getResources().getString(
+ com.android.internal.R.string.config_screenRecorderComponent));
final Intent intent = new Intent();
intent.setComponent(launcherComponent);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
diff --git a/core/java/com/android/internal/util/ScreenshotHelper.java b/core/java/com/android/internal/util/ScreenshotHelper.java
index f6f187fd27c5..8cad5a0d1d09 100644
--- a/core/java/com/android/internal/util/ScreenshotHelper.java
+++ b/core/java/com/android/internal/util/ScreenshotHelper.java
@@ -20,12 +20,6 @@ import java.util.function.Consumer;
public class ScreenshotHelper {
private static final String TAG = "ScreenshotHelper";
- private static final String SYSUI_PACKAGE = "com.android.systemui";
- private static final String SYSUI_SCREENSHOT_SERVICE =
- "com.android.systemui.screenshot.TakeScreenshotService";
- private static final String SYSUI_SCREENSHOT_ERROR_RECEIVER =
- "com.android.systemui.screenshot.ScreenshotServiceErrorReceiver";
-
// Time until we give up on the screenshot & show an error instead.
private final int SCREENSHOT_TIMEOUT_MS = 10000;
@@ -94,8 +88,9 @@ public class ScreenshotHelper {
if (mScreenshotConnection != null) {
return;
}
- final ComponentName serviceComponent = new ComponentName(SYSUI_PACKAGE,
- SYSUI_SCREENSHOT_SERVICE);
+ final ComponentName serviceComponent = ComponentName.unflattenFromString(
+ mContext.getResources().getString(
+ com.android.internal.R.string.config_screenshotServiceComponent));
final Intent serviceIntent = new Intent();
final Runnable mScreenshotTimeout = new Runnable() {
@@ -181,8 +176,9 @@ public class ScreenshotHelper {
*/
private void notifyScreenshotError() {
// If the service process is killed, then ask it to clean up after itself
- final ComponentName errorComponent = new ComponentName(SYSUI_PACKAGE,
- SYSUI_SCREENSHOT_ERROR_RECEIVER);
+ final ComponentName errorComponent = ComponentName.unflattenFromString(
+ mContext.getResources().getString(
+ com.android.internal.R.string.config_screenshotErrorReceiverComponent));
// Broadcast needs to have a valid action. We'll just pick
// a generic one, since the receiver here doesn't care.
Intent errorIntent = new Intent(Intent.ACTION_USER_PRESENT);
diff --git a/core/java/com/android/internal/util/function/pooled/PooledLambdaImpl.java b/core/java/com/android/internal/util/function/pooled/PooledLambdaImpl.java
index c7502ef04f1b..8446bbd09df7 100755
--- a/core/java/com/android/internal/util/function/pooled/PooledLambdaImpl.java
+++ b/core/java/com/android/internal/util/function/pooled/PooledLambdaImpl.java
@@ -25,7 +25,6 @@ import android.util.Pools;
import com.android.internal.util.ArrayUtils;
import com.android.internal.util.BitUtils;
-import com.android.internal.util.Preconditions;
import com.android.internal.util.function.DecConsumer;
import com.android.internal.util.function.DecFunction;
import com.android.internal.util.function.DecPredicate;
@@ -545,7 +544,7 @@ final class PooledLambdaImpl<R> extends OmniFunction<Object,
+ ", k = " + k
+ ")");
}
- r.mFunc = Preconditions.checkNotNull(func);
+ r.mFunc = Objects.requireNonNull(func);
r.setFlags(MASK_FUNC_TYPE, LambdaType.encode(fNumArgs, fReturnType));
r.setFlags(MASK_EXPOSED_AS, LambdaType.encode(numPlaceholders, fReturnType));
if (ArrayUtils.size(r.mArgs) < fNumArgs) r.mArgs = new Object[fNumArgs];
diff --git a/core/java/com/android/internal/view/FloatingActionMode.java b/core/java/com/android/internal/view/FloatingActionMode.java
index 54dede6753e4..f9e98e7eb473 100644
--- a/core/java/com/android/internal/view/FloatingActionMode.java
+++ b/core/java/com/android/internal/view/FloatingActionMode.java
@@ -33,11 +33,11 @@ import android.view.WindowManager;
import android.widget.PopupWindow;
import com.android.internal.R;
-import com.android.internal.util.Preconditions;
import com.android.internal.view.menu.MenuBuilder;
import com.android.internal.widget.FloatingToolbar;
import java.util.Arrays;
+import java.util.Objects;
public final class FloatingActionMode extends ActionMode {
@@ -84,8 +84,8 @@ public final class FloatingActionMode extends ActionMode {
public FloatingActionMode(
Context context, ActionMode.Callback2 callback,
View originatingView, FloatingToolbar floatingToolbar) {
- mContext = Preconditions.checkNotNull(context);
- mCallback = Preconditions.checkNotNull(callback);
+ mContext = Objects.requireNonNull(context);
+ mCallback = Objects.requireNonNull(callback);
mMenu = new MenuBuilder(context).setDefaultShowAsAction(
MenuItem.SHOW_AS_ACTION_IF_ROOM);
setType(ActionMode.TYPE_FLOATING);
@@ -107,14 +107,14 @@ public final class FloatingActionMode extends ActionMode {
mViewRectOnScreen = new Rect();
mPreviousViewRectOnScreen = new Rect();
mScreenRect = new Rect();
- mOriginatingView = Preconditions.checkNotNull(originatingView);
+ mOriginatingView = Objects.requireNonNull(originatingView);
mOriginatingView.getLocationOnScreen(mViewPositionOnScreen);
// Allow the content rect to overshoot a little bit beyond the
// bottom view bound if necessary.
mBottomAllowance = context.getResources()
.getDimensionPixelSize(R.dimen.content_rect_bottom_clip_allowance);
mDisplaySize = new Point();
- setFloatingToolbar(Preconditions.checkNotNull(floatingToolbar));
+ setFloatingToolbar(Objects.requireNonNull(floatingToolbar));
}
private void setFloatingToolbar(FloatingToolbar floatingToolbar) {
@@ -328,7 +328,7 @@ public final class FloatingActionMode extends ActionMode {
private long mLastShowTime;
public FloatingToolbarVisibilityHelper(FloatingToolbar toolbar) {
- mToolbar = Preconditions.checkNotNull(toolbar);
+ mToolbar = Objects.requireNonNull(toolbar);
}
public void activate() {
diff --git a/core/java/com/android/internal/view/IInputMethod.aidl b/core/java/com/android/internal/view/IInputMethod.aidl
index 2ee902ab6468..58aaa80b51be 100644
--- a/core/java/com/android/internal/view/IInputMethod.aidl
+++ b/core/java/com/android/internal/view/IInputMethod.aidl
@@ -16,13 +16,16 @@
package com.android.internal.view;
+import android.content.ComponentName;
import android.os.IBinder;
import android.os.ResultReceiver;
+import android.view.autofill.AutofillId;
import android.view.InputChannel;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputBinding;
import android.view.inputmethod.InputMethodSubtype;
import com.android.internal.inputmethod.IInputMethodPrivilegedOperations;
+import com.android.internal.view.IInlineSuggestionsRequestCallback;
import com.android.internal.view.IInputContext;
import com.android.internal.view.IInputMethodSession;
import com.android.internal.view.IInputSessionCallback;
@@ -35,6 +38,9 @@ import com.android.internal.view.IInputSessionCallback;
oneway interface IInputMethod {
void initializeInternal(IBinder token, int displayId, IInputMethodPrivilegedOperations privOps);
+ void onCreateInlineSuggestionsRequest(in ComponentName componentName, in AutofillId autofillId,
+ in IInlineSuggestionsRequestCallback cb);
+
void bindInput(in InputBinding binding);
void unbindInput();
diff --git a/core/java/com/android/internal/view/menu/StandardMenuPopup.java b/core/java/com/android/internal/view/menu/StandardMenuPopup.java
index d618f6758faa..1979e4fe7a90 100644
--- a/core/java/com/android/internal/view/menu/StandardMenuPopup.java
+++ b/core/java/com/android/internal/view/menu/StandardMenuPopup.java
@@ -35,7 +35,7 @@ import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.PopupWindow.OnDismissListener;
-import com.android.internal.util.Preconditions;
+import java.util.Objects;
/**
* A standard menu popup in which when a submenu is opened, it replaces its parent menu in the
@@ -113,7 +113,7 @@ final class StandardMenuPopup extends MenuPopup implements OnDismissListener, On
public StandardMenuPopup(Context context, MenuBuilder menu, View anchorView, int popupStyleAttr,
int popupStyleRes, boolean overflowOnly) {
- mContext = Preconditions.checkNotNull(context);
+ mContext = Objects.requireNonNull(context);
mMenu = menu;
mOverflowOnly = overflowOnly;
final LayoutInflater inflater = LayoutInflater.from(context);
diff --git a/core/java/com/android/internal/widget/FloatingToolbar.java b/core/java/com/android/internal/widget/FloatingToolbar.java
index bb7423a67754..d7611dcd0aa0 100644
--- a/core/java/com/android/internal/widget/FloatingToolbar.java
+++ b/core/java/com/android/internal/widget/FloatingToolbar.java
@@ -155,7 +155,7 @@ public final class FloatingToolbar {
// TODO(b/65172902): Pass context in constructor when DecorView (and other callers)
// supports multi-display.
mContext = applyDefaultTheme(window.getContext());
- mWindow = Preconditions.checkNotNull(window);
+ mWindow = Objects.requireNonNull(window);
mPopup = new FloatingToolbarPopup(mContext, window.getDecorView());
}
@@ -165,7 +165,7 @@ public final class FloatingToolbar {
* toolbar.
*/
public FloatingToolbar setMenu(Menu menu) {
- mMenu = Preconditions.checkNotNull(menu);
+ mMenu = Objects.requireNonNull(menu);
return this;
}
@@ -189,7 +189,7 @@ public final class FloatingToolbar {
* toolbar.
*/
public FloatingToolbar setContentRect(Rect rect) {
- mContentRect.set(Preconditions.checkNotNull(rect));
+ mContentRect.set(Objects.requireNonNull(rect));
return this;
}
@@ -457,8 +457,8 @@ public final class FloatingToolbar {
* from.
*/
public FloatingToolbarPopup(Context context, View parent) {
- mParent = Preconditions.checkNotNull(parent);
- mContext = Preconditions.checkNotNull(context);
+ mParent = Objects.requireNonNull(parent);
+ mContext = Objects.requireNonNull(context);
mContentContainer = createContentContainer(context);
mPopupWindow = createPopupWindow(mContentContainer);
mMarginHorizontal = parent.getResources()
@@ -578,7 +578,7 @@ public final class FloatingToolbar {
* The specified coordinates may be adjusted to make sure the popup is entirely on-screen.
*/
public void show(Rect contentRectOnScreen) {
- Preconditions.checkNotNull(contentRectOnScreen);
+ Objects.requireNonNull(contentRectOnScreen);
if (isShowing()) {
return;
@@ -650,7 +650,7 @@ public final class FloatingToolbar {
* This is a no-op if this popup is not showing.
*/
public void updateCoordinates(Rect contentRectOnScreen) {
- Preconditions.checkNotNull(contentRectOnScreen);
+ Objects.requireNonNull(contentRectOnScreen);
if (!isShowing() || !mPopupWindow.isShowing()) {
return;
@@ -1134,11 +1134,11 @@ public final class FloatingToolbar {
* Sets the touchable region of this popup to be the area occupied by its content.
*/
private void setContentAreaAsTouchableSurface() {
- Preconditions.checkNotNull(mMainPanelSize);
+ Objects.requireNonNull(mMainPanelSize);
final int width;
final int height;
if (mIsOverflowOpen) {
- Preconditions.checkNotNull(mOverflowPanelSize);
+ Objects.requireNonNull(mOverflowPanelSize);
width = mOverflowPanelSize.getWidth();
height = mOverflowPanelSize.getHeight();
} else {
@@ -1183,7 +1183,7 @@ public final class FloatingToolbar {
*/
public List<MenuItem> layoutMainPanelItems(
List<MenuItem> menuItems, final int toolbarWidth) {
- Preconditions.checkNotNull(menuItems);
+ Objects.requireNonNull(menuItems);
int availableWidth = toolbarWidth;
@@ -1555,7 +1555,7 @@ public final class FloatingToolbar {
private final FloatingToolbarPopup mPopup;
OverflowPanel(FloatingToolbarPopup popup) {
- super(Preconditions.checkNotNull(popup).mContext);
+ super(Objects.requireNonNull(popup).mContext);
this.mPopup = popup;
setScrollBarDefaultDelayBeforeFade(ViewConfiguration.getScrollDefaultDelay() * 3);
setScrollIndicators(View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_BOTTOM);
@@ -1616,7 +1616,7 @@ public final class FloatingToolbar {
private final Context mContext;
public OverflowPanelViewHelper(Context context, int iconTextSpacing) {
- mContext = Preconditions.checkNotNull(context);
+ mContext = Objects.requireNonNull(context);
mIconTextSpacing = iconTextSpacing;
mSidePadding = context.getResources()
.getDimensionPixelSize(R.dimen.floating_toolbar_overflow_side_padding);
@@ -1624,7 +1624,7 @@ public final class FloatingToolbar {
}
public View getView(MenuItem menuItem, int minimumWidth, View convertView) {
- Preconditions.checkNotNull(menuItem);
+ Objects.requireNonNull(menuItem);
if (convertView != null) {
updateMenuItemButton(
convertView, menuItem, mIconTextSpacing, shouldShowIcon(menuItem));
diff --git a/core/java/com/android/internal/widget/LockscreenCredential.java b/core/java/com/android/internal/widget/LockscreenCredential.java
index f456349a8937..9b87dd2c5f8b 100644
--- a/core/java/com/android/internal/widget/LockscreenCredential.java
+++ b/core/java/com/android/internal/widget/LockscreenCredential.java
@@ -33,6 +33,7 @@ import com.android.internal.util.Preconditions;
import java.util.Arrays;
import java.util.List;
+import java.util.Objects;
/**
* A class representing a lockscreen credential. It can be either an empty password, a pattern
@@ -67,7 +68,7 @@ public class LockscreenCredential implements Parcelable, AutoCloseable {
* minimize the number of extra copies introduced.
*/
private LockscreenCredential(int type, byte[] credential) {
- Preconditions.checkNotNull(credential);
+ Objects.requireNonNull(credential);
if (type == CREDENTIAL_TYPE_NONE) {
Preconditions.checkArgument(credential.length == 0);
} else {
diff --git a/core/java/com/android/server/SystemConfig.java b/core/java/com/android/server/SystemConfig.java
index e6232e851253..8a59c998dacb 100644
--- a/core/java/com/android/server/SystemConfig.java
+++ b/core/java/com/android/server/SystemConfig.java
@@ -25,6 +25,7 @@ import android.content.pm.FeatureInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
+import android.os.FileUtils;
import android.os.Process;
import android.os.SystemProperties;
import android.os.Trace;
@@ -222,6 +223,8 @@ public class SystemConfig {
private ArrayMap<String, Set<String>> mPackageToUserTypeWhitelist = new ArrayMap<>();
private ArrayMap<String, Set<String>> mPackageToUserTypeBlacklist = new ArrayMap<>();
+ private final ArraySet<String> mRollbackWhitelistedPackages = new ArraySet<>();
+
/**
* Map of system pre-defined, uniquely named actors; keys are namespace,
* value maps actor name to package name.
@@ -382,6 +385,10 @@ public class SystemConfig {
return mBugreportWhitelistedPackages;
}
+ public Set<String> getRollbackWhitelistedPackages() {
+ return mRollbackWhitelistedPackages;
+ }
+
/**
* Gets map of packagesNames to userTypes, dictating on which user types each package should be
* initially installed, and then removes this map from SystemConfig.
@@ -492,6 +499,19 @@ public class SystemConfig {
Environment.getSystemExtDirectory(), "etc", "sysconfig"), ALLOW_ALL);
readPermissions(Environment.buildPath(
Environment.getSystemExtDirectory(), "etc", "permissions"), ALLOW_ALL);
+
+ // Skip loading configuration from apex if it is not a system process.
+ if (!isSystemProcess()) {
+ return;
+ }
+ // Read configuration of libs from apex module.
+ // TODO: Use a solid way to filter apex module folders?
+ for (File f: FileUtils.listFilesOrEmpty(Environment.getApexDirectory())) {
+ if (f.isFile() || f.getPath().contains("@")) {
+ continue;
+ }
+ readPermissions(Environment.buildPath(f, "etc", "permissions"), ALLOW_LIBS);
+ }
}
@VisibleForTesting
@@ -1078,6 +1098,16 @@ public class SystemConfig {
}
XmlUtils.skipCurrentTag(parser);
} break;
+ case "rollback-whitelisted-app": {
+ String pkgname = parser.getAttributeValue(null, "package");
+ if (pkgname == null) {
+ Slog.w(TAG, "<" + name + "> without package in " + permFile
+ + " at " + parser.getPositionDescription());
+ } else {
+ mRollbackWhitelistedPackages.add(pkgname);
+ }
+ XmlUtils.skipCurrentTag(parser);
+ } break;
default: {
Slog.w(TAG, "Tag " + name + " is unknown in "
+ permFile + " at " + parser.getPositionDescription());
diff --git a/core/jni/Android.bp b/core/jni/Android.bp
index 148b0a2799b4..7cd18a2be9df 100644
--- a/core/jni/Android.bp
+++ b/core/jni/Android.bp
@@ -110,7 +110,6 @@ cc_library_shared {
"android_view_InputEventReceiver.cpp",
"android_view_InputEventSender.cpp",
"android_view_InputQueue.cpp",
- "android_view_FrameMetricsObserver.cpp",
"android_view_KeyCharacterMap.cpp",
"android_view_KeyEvent.cpp",
"android_view_MotionEvent.cpp",
@@ -144,6 +143,7 @@ cc_library_shared {
"android_os_VintfRuntimeInfo.cpp",
"android_net_LocalSocketImpl.cpp",
"android_net_NetUtils.cpp",
+ "android_service_DataLoaderService.cpp",
"android_util_AssetManager.cpp",
"android_util_Binder.cpp",
"android_util_StatsLog.cpp",
@@ -152,6 +152,7 @@ cc_library_shared {
"android_util_StringBlock.cpp",
"android_util_XmlBlock.cpp",
"android_util_jar_StrictJarFile.cpp",
+ "android_media_AudioDeviceAddress.cpp",
"android_media_AudioEffectDescriptor.cpp",
"android_media_AudioRecord.cpp",
"android_media_AudioSystem.cpp",
@@ -175,7 +176,6 @@ cc_library_shared {
"android_hardware_HardwareBuffer.cpp",
"android_hardware_SensorManager.cpp",
"android_hardware_SerialPort.cpp",
- "android_hardware_SoundTrigger.cpp",
"android_hardware_UsbDevice.cpp",
"android_hardware_UsbDeviceConnection.cpp",
"android_hardware_UsbRequest.cpp",
@@ -207,6 +207,7 @@ cc_library_shared {
static_libs: [
"libasync_safe",
+ "libdmabufinfo",
"libgif",
"libseccomp_policy",
"libgrallocusage",
@@ -239,6 +240,8 @@ cc_library_shared {
"libGLESv1_CM",
"libGLESv2",
"libGLESv3",
+ "libincfs",
+ "libdataloader",
"libvulkan",
"libETC1",
"libhardware",
@@ -255,7 +258,6 @@ cc_library_shared {
"libpdfium",
"libimg_utils",
"libnetd_client",
- "libsoundtrigger",
"libprocessgroup",
"libnativebridge_lazy",
"libnativeloader_lazy",
@@ -349,6 +351,7 @@ cc_library_static {
"android_graphics_ColorSpace.cpp",
"android_graphics_drawable_AnimatedVectorDrawable.cpp",
"android_graphics_drawable_VectorDrawable.cpp",
+ "android_graphics_HardwareRendererObserver.cpp",
"android_graphics_Picture.cpp",
"android_nio_utils.cpp",
"android_view_DisplayListCanvas.cpp",
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index 97451a2c4cfd..3cde887ba465 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -80,12 +80,12 @@ extern int register_android_hardware_camera2_DngCreator(JNIEnv *env);
extern int register_android_hardware_HardwareBuffer(JNIEnv *env);
extern int register_android_hardware_SensorManager(JNIEnv *env);
extern int register_android_hardware_SerialPort(JNIEnv *env);
-extern int register_android_hardware_SoundTrigger(JNIEnv *env);
extern int register_android_hardware_UsbDevice(JNIEnv *env);
extern int register_android_hardware_UsbDeviceConnection(JNIEnv *env);
extern int register_android_hardware_UsbRequest(JNIEnv *env);
extern int register_android_hardware_location_ActivityRecognitionHardware(JNIEnv* env);
+extern int register_android_media_AudioDeviceAddress(JNIEnv *env);
extern int register_android_media_AudioEffectDescriptor(JNIEnv *env);
extern int register_android_media_AudioRecord(JNIEnv *env);
extern int register_android_media_AudioSystem(JNIEnv *env);
@@ -129,6 +129,7 @@ extern int register_android_database_CursorWindow(JNIEnv* env);
extern int register_android_database_SQLiteConnection(JNIEnv* env);
extern int register_android_database_SQLiteGlobal(JNIEnv* env);
extern int register_android_database_SQLiteDebug(JNIEnv* env);
+extern int register_android_media_MediaMetrics(JNIEnv *env);
extern int register_android_os_Debug(JNIEnv* env);
extern int register_android_os_GraphicsEnvironment(JNIEnv* env);
extern int register_android_os_HidlSupport(JNIEnv* env);
@@ -150,6 +151,7 @@ extern int register_android_os_UEventObserver(JNIEnv* env);
extern int register_android_os_HidlMemory(JNIEnv* env);
extern int register_android_os_MemoryFile(JNIEnv* env);
extern int register_android_os_SharedMemory(JNIEnv* env);
+extern int register_android_service_DataLoaderService(JNIEnv* env);
extern int register_android_net_LocalSocketImpl(JNIEnv* env);
extern int register_android_net_NetworkUtils(JNIEnv* env);
extern int register_android_text_AndroidCharacter(JNIEnv *env);
@@ -1451,6 +1453,7 @@ static const RegJNIRec gRegJNI[] = {
REG_JNI(register_android_os_NativeHandle),
REG_JNI(register_android_os_VintfObject),
REG_JNI(register_android_os_VintfRuntimeInfo),
+ REG_JNI(register_android_service_DataLoaderService),
REG_JNI(register_android_view_DisplayEventReceiver),
REG_JNI(register_android_view_RenderNodeAnimator),
REG_JNI(register_android_view_InputApplicationHandle),
@@ -1505,11 +1508,11 @@ static const RegJNIRec gRegJNI[] = {
REG_JNI(register_android_hardware_HardwareBuffer),
REG_JNI(register_android_hardware_SensorManager),
REG_JNI(register_android_hardware_SerialPort),
- REG_JNI(register_android_hardware_SoundTrigger),
REG_JNI(register_android_hardware_UsbDevice),
REG_JNI(register_android_hardware_UsbDeviceConnection),
REG_JNI(register_android_hardware_UsbRequest),
REG_JNI(register_android_hardware_location_ActivityRecognitionHardware),
+ REG_JNI(register_android_media_AudioDeviceAddress),
REG_JNI(register_android_media_AudioEffectDescriptor),
REG_JNI(register_android_media_AudioSystem),
REG_JNI(register_android_media_AudioRecord),
@@ -1518,6 +1521,7 @@ static const RegJNIRec gRegJNI[] = {
REG_JNI(register_android_media_AudioProductStrategies),
REG_JNI(register_android_media_AudioVolumeGroups),
REG_JNI(register_android_media_AudioVolumeGroupChangeHandler),
+ REG_JNI(register_android_media_MediaMetrics),
REG_JNI(register_android_media_MicrophoneInfo),
REG_JNI(register_android_media_RemoteDisplay),
REG_JNI(register_android_media_ToneGenerator),
diff --git a/core/jni/android/graphics/AnimatedImageDrawable.cpp b/core/jni/android/graphics/AnimatedImageDrawable.cpp
index 12900261bddd..6c2a5a3f3fcc 100644
--- a/core/jni/android/graphics/AnimatedImageDrawable.cpp
+++ b/core/jni/android/graphics/AnimatedImageDrawable.cpp
@@ -25,6 +25,7 @@
#include <SkPicture.h>
#include <SkPictureRecorder.h>
#include <hwui/AnimatedImageDrawable.h>
+#include <hwui/ImageDecoder.h>
#include <hwui/Canvas.h>
#include <utils/Looper.h>
diff --git a/core/jni/android/graphics/BitmapFactory.cpp b/core/jni/android/graphics/BitmapFactory.cpp
index 3f05c3b57c69..fa64fd10d6db 100644
--- a/core/jni/android/graphics/BitmapFactory.cpp
+++ b/core/jni/android/graphics/BitmapFactory.cpp
@@ -7,7 +7,6 @@
#include "SkAndroidCodec.h"
#include "SkBRDAllocator.h"
#include "SkFrontBufferedStream.h"
-#include "SkMakeUnique.h"
#include "SkMath.h"
#include "SkPixelRef.h"
#include "SkStream.h"
@@ -586,7 +585,7 @@ static jobject nativeDecodeAsset(JNIEnv* env, jobject clazz, jlong native_asset,
Asset* asset = reinterpret_cast<Asset*>(native_asset);
// since we know we'll be done with the asset when we return, we can
// just use a simple wrapper
- return doDecode(env, skstd::make_unique<AssetStreamAdaptor>(asset), padding, options,
+ return doDecode(env, std::make_unique<AssetStreamAdaptor>(asset), padding, options,
inBitmapHandle, colorSpaceHandle);
}
@@ -594,7 +593,7 @@ static jobject nativeDecodeByteArray(JNIEnv* env, jobject, jbyteArray byteArray,
jint offset, jint length, jobject options, jlong inBitmapHandle, jlong colorSpaceHandle) {
AutoJavaByteArray ar(env, byteArray);
- return doDecode(env, skstd::make_unique<SkMemoryStream>(ar.ptr() + offset, length, false),
+ return doDecode(env, std::make_unique<SkMemoryStream>(ar.ptr() + offset, length, false),
nullptr, options, inBitmapHandle, colorSpaceHandle);
}
diff --git a/core/jni/android/graphics/ImageDecoder.cpp b/core/jni/android/graphics/ImageDecoder.cpp
index 4d907f6d4942..627f8f5b3e49 100644
--- a/core/jni/android/graphics/ImageDecoder.cpp
+++ b/core/jni/android/graphics/ImageDecoder.cpp
@@ -20,10 +20,12 @@
#include "CreateJavaOutputStreamAdaptor.h"
#include "GraphicsJNI.h"
#include "ImageDecoder.h"
+#include "NinePatchPeeker.h"
#include "Utils.h"
#include "core_jni_helpers.h"
#include <hwui/Bitmap.h>
+#include <hwui/ImageDecoder.h>
#include <HardwareBitmapUploader.h>
#include <SkAndroidCodec.h>
@@ -49,6 +51,28 @@ static jmethodID gCallback_onPartialImageMethodID;
static jmethodID gCanvas_constructorMethodID;
static jmethodID gCanvas_releaseMethodID;
+// These need to stay in sync with ImageDecoder.java's Allocator constants.
+enum Allocator {
+ kDefault_Allocator = 0,
+ kSoftware_Allocator = 1,
+ kSharedMemory_Allocator = 2,
+ kHardware_Allocator = 3,
+};
+
+// These need to stay in sync with ImageDecoder.java's Error constants.
+enum Error {
+ kSourceException = 1,
+ kSourceIncomplete = 2,
+ kSourceMalformedData = 3,
+};
+
+// These need to stay in sync with PixelFormat.java's Format constants.
+enum PixelFormat {
+ kUnknown = 0,
+ kTranslucent = -3,
+ kOpaque = -1,
+};
+
// Clear and return any pending exception for handling other than throwing directly.
static jthrowable get_and_clear_exception(JNIEnv* env) {
jthrowable jexception = env->ExceptionOccurred();
@@ -59,7 +83,7 @@ static jthrowable get_and_clear_exception(JNIEnv* env) {
}
// Throw a new ImageDecoder.DecodeException. Returns null for convenience.
-static jobject throw_exception(JNIEnv* env, ImageDecoder::Error error, const char* msg,
+static jobject throw_exception(JNIEnv* env, Error error, const char* msg,
jthrowable cause, jobject source) {
jstring jstr = nullptr;
if (msg) {
@@ -81,27 +105,27 @@ static jobject throw_exception(JNIEnv* env, ImageDecoder::Error error, const cha
static jobject native_create(JNIEnv* env, std::unique_ptr<SkStream> stream,
jobject source, jboolean preferAnimation) {
if (!stream.get()) {
- return throw_exception(env, ImageDecoder::kSourceMalformedData, "Failed to create a stream",
+ return throw_exception(env, kSourceMalformedData, "Failed to create a stream",
nullptr, source);
}
- std::unique_ptr<ImageDecoder> decoder(new ImageDecoder);
+ sk_sp<NinePatchPeeker> peeker(new NinePatchPeeker);
SkCodec::Result result;
auto codec = SkCodec::MakeFromStream(
- std::move(stream), &result, decoder->mPeeker.get(),
+ std::move(stream), &result, peeker.get(),
preferAnimation ? SkCodec::SelectionPolicy::kPreferAnimation
: SkCodec::SelectionPolicy::kPreferStillImage);
if (jthrowable jexception = get_and_clear_exception(env)) {
- return throw_exception(env, ImageDecoder::kSourceException, "", jexception, source);
+ return throw_exception(env, kSourceException, "", jexception, source);
}
if (!codec) {
switch (result) {
case SkCodec::kIncompleteInput:
- return throw_exception(env, ImageDecoder::kSourceIncomplete, "", nullptr, source);
+ return throw_exception(env, kSourceIncomplete, "", nullptr, source);
default:
SkString msg;
msg.printf("Failed to create image decoder with message '%s'",
SkCodec::ResultToString(result));
- return throw_exception(env, ImageDecoder::kSourceMalformedData, msg.c_str(),
+ return throw_exception(env, kSourceMalformedData, msg.c_str(),
nullptr, source);
}
@@ -109,21 +133,22 @@ static jobject native_create(JNIEnv* env, std::unique_ptr<SkStream> stream,
const bool animated = codec->getFrameCount() > 1;
if (jthrowable jexception = get_and_clear_exception(env)) {
- return throw_exception(env, ImageDecoder::kSourceException, "", jexception, source);
+ return throw_exception(env, kSourceException, "", jexception, source);
}
- decoder->mCodec = SkAndroidCodec::MakeFromCodec(std::move(codec),
+ auto androidCodec = SkAndroidCodec::MakeFromCodec(std::move(codec),
SkAndroidCodec::ExifOrientationBehavior::kRespect);
- if (!decoder->mCodec.get()) {
- return throw_exception(env, ImageDecoder::kSourceMalformedData, "", nullptr, source);
+ if (!androidCodec.get()) {
+ return throw_exception(env, kSourceMalformedData, "", nullptr, source);
}
- const auto& info = decoder->mCodec->getInfo();
+ const auto& info = androidCodec->getInfo();
const int width = info.width();
const int height = info.height();
- const bool isNinePatch = decoder->mPeeker->mPatch != nullptr;
+ const bool isNinePatch = peeker->mPatch != nullptr;
+ ImageDecoder* decoder = new ImageDecoder(std::move(androidCodec), std::move(peeker));
return env->NewObject(gImageDecoder_class, gImageDecoder_constructorMethodID,
- reinterpret_cast<jlong>(decoder.release()), width, height,
+ reinterpret_cast<jlong>(decoder), width, height,
animated, isNinePatch);
}
@@ -133,7 +158,7 @@ static jobject ImageDecoder_nCreateFd(JNIEnv* env, jobject /*clazz*/,
struct stat fdStat;
if (fstat(descriptor, &fdStat) == -1) {
- return throw_exception(env, ImageDecoder::kSourceMalformedData,
+ return throw_exception(env, kSourceMalformedData,
"broken file descriptor; fstat returned -1", nullptr, source);
}
@@ -141,7 +166,7 @@ static jobject ImageDecoder_nCreateFd(JNIEnv* env, jobject /*clazz*/,
FILE* file = fdopen(dupDescriptor, "r");
if (file == NULL) {
close(dupDescriptor);
- return throw_exception(env, ImageDecoder::kSourceMalformedData, "Could not open file",
+ return throw_exception(env, kSourceMalformedData, "Could not open file",
nullptr, source);
}
@@ -154,7 +179,7 @@ static jobject ImageDecoder_nCreateInputStream(JNIEnv* env, jobject /*clazz*/,
std::unique_ptr<SkStream> stream(CreateJavaInputStreamAdaptor(env, is, storage, false));
if (!stream.get()) {
- return throw_exception(env, ImageDecoder::kSourceMalformedData, "Failed to create a stream",
+ return throw_exception(env, kSourceMalformedData, "Failed to create a stream",
nullptr, source);
}
@@ -177,7 +202,7 @@ static jobject ImageDecoder_nCreateByteBuffer(JNIEnv* env, jobject /*clazz*/,
std::unique_ptr<SkStream> stream = CreateByteBufferStreamAdaptor(env, jbyteBuffer,
initialPosition, limit);
if (!stream) {
- return throw_exception(env, ImageDecoder::kSourceMalformedData, "Failed to read ByteBuffer",
+ return throw_exception(env, kSourceMalformedData, "Failed to read ByteBuffer",
nullptr, source);
}
return native_create(env, std::move(stream), source, preferAnimation);
@@ -195,7 +220,7 @@ jint postProcessAndRelease(JNIEnv* env, jobject jimageDecoder, std::unique_ptr<C
reinterpret_cast<jlong>(canvas.get()));
if (!jcanvas) {
doThrowOOME(env, "Failed to create Java Canvas for PostProcess!");
- return ImageDecoder::kUnknown;
+ return kUnknown;
}
// jcanvas now owns canvas.
@@ -206,43 +231,23 @@ jint postProcessAndRelease(JNIEnv* env, jobject jimageDecoder, std::unique_ptr<C
static jobject ImageDecoder_nDecodeBitmap(JNIEnv* env, jobject /*clazz*/, jlong nativePtr,
jobject jdecoder, jboolean jpostProcess,
- jint desiredWidth, jint desiredHeight, jobject jsubset,
+ jint targetWidth, jint targetHeight, jobject jsubset,
jboolean requireMutable, jint allocator,
jboolean requireUnpremul, jboolean preferRamOverQuality,
jboolean asAlphaMask, jlong colorSpaceHandle,
jboolean extended) {
auto* decoder = reinterpret_cast<ImageDecoder*>(nativePtr);
- SkAndroidCodec* codec = decoder->mCodec.get();
- const SkISize desiredSize = SkISize::Make(desiredWidth, desiredHeight);
- SkISize decodeSize = desiredSize;
- const int sampleSize = codec->computeSampleSize(&decodeSize);
- const bool scale = desiredSize != decodeSize;
- SkImageInfo decodeInfo = codec->getInfo().makeWH(decodeSize.width(), decodeSize.height());
- if (scale && requireUnpremul && kOpaque_SkAlphaType != decodeInfo.alphaType()) {
- doThrowISE(env, "Cannot scale unpremultiplied pixels!");
+ if (!decoder->setTargetSize(targetWidth, targetHeight)) {
+ doThrowISE(env, "Could not scale to target size!");
return nullptr;
}
-
- switch (decodeInfo.alphaType()) {
- case kUnpremul_SkAlphaType:
- if (!requireUnpremul) {
- decodeInfo = decodeInfo.makeAlphaType(kPremul_SkAlphaType);
- }
- break;
- case kPremul_SkAlphaType:
- if (requireUnpremul) {
- decodeInfo = decodeInfo.makeAlphaType(kUnpremul_SkAlphaType);
- }
- break;
- case kOpaque_SkAlphaType:
- break;
- case kUnknown_SkAlphaType:
- doThrowIOE(env, "Unknown alpha type");
- return nullptr;
+ if (requireUnpremul && !decoder->setOutAlphaType(kUnpremul_SkAlphaType)) {
+ doThrowISE(env, "Cannot scale unpremultiplied pixels!");
+ return nullptr;
}
SkColorType colorType = kN32_SkColorType;
- if (asAlphaMask && decodeInfo.colorType() == kGray_8_SkColorType) {
+ if (asAlphaMask && decoder->gray()) {
// We have to trick Skia to decode this to a single channel.
colorType = kGray_8_SkColorType;
} else if (preferRamOverQuality) {
@@ -250,12 +255,12 @@ static jobject ImageDecoder_nDecodeBitmap(JNIEnv* env, jobject /*clazz*/, jlong
// result incorrect. If we call the postProcess before now and record
// to a picture, we can know whether alpha was added, and if not, we
// can still use 565.
- if (decodeInfo.alphaType() == kOpaque_SkAlphaType && !jpostProcess) {
+ if (decoder->opaque() && !jpostProcess) {
// If the final result will be hardware, decoding to 565 and then
// uploading to the gpu as 8888 will not save memory. This still
// may save us from using F16, but do not go down to 565.
- if (allocator != ImageDecoder::kHardware_Allocator &&
- (allocator != ImageDecoder::kDefault_Allocator || requireMutable)) {
+ if (allocator != kHardware_Allocator &&
+ (allocator != kDefault_Allocator || requireMutable)) {
colorType = kRGB_565_SkColorType;
}
}
@@ -263,12 +268,12 @@ static jobject ImageDecoder_nDecodeBitmap(JNIEnv* env, jobject /*clazz*/, jlong
} else if (extended) {
colorType = kRGBA_F16_SkColorType;
} else {
- colorType = codec->computeOutputColorType(colorType);
+ colorType = decoder->mCodec->computeOutputColorType(colorType);
}
const bool isHardware = !requireMutable
- && (allocator == ImageDecoder::kDefault_Allocator ||
- allocator == ImageDecoder::kHardware_Allocator)
+ && (allocator == kDefault_Allocator ||
+ allocator == kHardware_Allocator)
&& colorType != kGray_8_SkColorType;
if (colorType == kRGBA_F16_SkColorType && isHardware &&
@@ -276,12 +281,28 @@ static jobject ImageDecoder_nDecodeBitmap(JNIEnv* env, jobject /*clazz*/, jlong
colorType = kN32_SkColorType;
}
- sk_sp<SkColorSpace> colorSpace = GraphicsJNI::getNativeColorSpace(colorSpaceHandle);
- colorSpace = codec->computeOutputColorSpace(colorType, colorSpace);
- decodeInfo = decodeInfo.makeColorType(colorType).makeColorSpace(colorSpace);
+ if (!decoder->setOutColorType(colorType)) {
+ doThrowISE(env, "Failed to set out color type!");
+ return nullptr;
+ }
+
+ {
+ sk_sp<SkColorSpace> colorSpace = GraphicsJNI::getNativeColorSpace(colorSpaceHandle);
+ colorSpace = decoder->mCodec->computeOutputColorSpace(colorType, colorSpace);
+ decoder->setOutColorSpace(std::move(colorSpace));
+ }
+
+ if (jsubset) {
+ SkIRect subset;
+ GraphicsJNI::jrect_to_irect(env, jsubset, &subset);
+ if (!decoder->setCropRect(&subset)) {
+ doThrowISE(env, "Invalid crop rect!");
+ return nullptr;
+ }
+ }
SkBitmap bm;
- auto bitmapInfo = decodeInfo;
+ SkImageInfo bitmapInfo = decoder->getOutputInfo();
if (asAlphaMask && colorType == kGray_8_SkColorType) {
bitmapInfo = bitmapInfo.makeColorType(kAlpha_8_SkColorType);
}
@@ -291,10 +312,7 @@ static jobject ImageDecoder_nDecodeBitmap(JNIEnv* env, jobject /*clazz*/, jlong
}
sk_sp<Bitmap> nativeBitmap;
- // If we are going to scale or subset, we will create a new bitmap later on,
- // so use the heap for the temporary.
- // FIXME: Use scanline decoding on only a couple lines to save memory. b/70709380.
- if (allocator == ImageDecoder::kSharedMemory_Allocator && !scale && !jsubset) {
+ if (allocator == kSharedMemory_Allocator) {
nativeBitmap = Bitmap::allocateAshmemBitmap(&bm);
} else {
nativeBitmap = Bitmap::allocateHeapBitmap(&bm);
@@ -302,16 +320,14 @@ static jobject ImageDecoder_nDecodeBitmap(JNIEnv* env, jobject /*clazz*/, jlong
if (!nativeBitmap) {
SkString msg;
msg.printf("OOM allocating Bitmap with dimensions %i x %i",
- decodeInfo.width(), decodeInfo.height());
+ bitmapInfo.width(), bitmapInfo.height());
doThrowOOME(env, msg.c_str());
return nullptr;
}
- SkAndroidCodec::AndroidOptions options;
- options.fSampleSize = sampleSize;
- auto result = codec->getAndroidPixels(decodeInfo, bm.getPixels(), bm.rowBytes(), &options);
+ SkCodec::Result result = decoder->decode(bm.getPixels(), bm.rowBytes());
jthrowable jexception = get_and_clear_exception(env);
- int onPartialImageError = jexception ? ImageDecoder::kSourceException
+ int onPartialImageError = jexception ? kSourceException
: 0; // No error.
switch (result) {
case SkCodec::kSuccess:
@@ -321,12 +337,12 @@ static jobject ImageDecoder_nDecodeBitmap(JNIEnv* env, jobject /*clazz*/, jlong
break;
case SkCodec::kIncompleteInput:
if (!jexception) {
- onPartialImageError = ImageDecoder::kSourceIncomplete;
+ onPartialImageError = kSourceIncomplete;
}
break;
case SkCodec::kErrorInInput:
if (!jexception) {
- onPartialImageError = ImageDecoder::kSourceMalformedData;
+ onPartialImageError = kSourceMalformedData;
}
break;
default:
@@ -350,20 +366,21 @@ static jobject ImageDecoder_nDecodeBitmap(JNIEnv* env, jobject /*clazz*/, jlong
// Ignore ninepatch when post-processing.
if (!jpostProcess) {
// FIXME: Share more code with BitmapFactory.cpp.
- if (decoder->mPeeker->mPatch != nullptr) {
- size_t ninePatchArraySize = decoder->mPeeker->mPatch->serializedSize();
+ auto* peeker = reinterpret_cast<NinePatchPeeker*>(decoder->mPeeker.get());
+ if (peeker->mPatch != nullptr) {
+ size_t ninePatchArraySize = peeker->mPatch->serializedSize();
ninePatchChunk = env->NewByteArray(ninePatchArraySize);
if (ninePatchChunk == nullptr) {
doThrowOOME(env, "Failed to allocate nine patch chunk.");
return nullptr;
}
- env->SetByteArrayRegion(ninePatchChunk, 0, decoder->mPeeker->mPatchSize,
- reinterpret_cast<jbyte*>(decoder->mPeeker->mPatch));
+ env->SetByteArrayRegion(ninePatchChunk, 0, peeker->mPatchSize,
+ reinterpret_cast<jbyte*>(peeker->mPatch));
}
- if (decoder->mPeeker->mHasInsets) {
- ninePatchInsets = decoder->mPeeker->createNinePatchInsets(env, 1.0f);
+ if (peeker->mHasInsets) {
+ ninePatchInsets = peeker->createNinePatchInsets(env, 1.0f);
if (ninePatchInsets == nullptr) {
doThrowOOME(env, "Failed to allocate nine patch insets.");
return nullptr;
@@ -371,58 +388,6 @@ static jobject ImageDecoder_nDecodeBitmap(JNIEnv* env, jobject /*clazz*/, jlong
}
}
- if (scale || jsubset) {
- int translateX = 0;
- int translateY = 0;
- SkImageInfo scaledInfo;
- if (jsubset) {
- SkIRect subset;
- GraphicsJNI::jrect_to_irect(env, jsubset, &subset);
-
- translateX = -subset.fLeft;
- translateY = -subset.fTop;
- scaledInfo = bitmapInfo.makeWH(subset.width(), subset.height());
- } else {
- scaledInfo = bitmapInfo.makeWH(desiredWidth, desiredHeight);
- }
- SkBitmap scaledBm;
- if (!scaledBm.setInfo(scaledInfo)) {
- doThrowIOE(env, "Failed scaled setInfo");
- return nullptr;
- }
-
- sk_sp<Bitmap> scaledPixelRef;
- if (allocator == ImageDecoder::kSharedMemory_Allocator) {
- scaledPixelRef = Bitmap::allocateAshmemBitmap(&scaledBm);
- } else {
- scaledPixelRef = Bitmap::allocateHeapBitmap(&scaledBm);
- }
- if (!scaledPixelRef) {
- SkString msg;
- msg.printf("OOM allocating scaled Bitmap with dimensions %i x %i",
- desiredWidth, desiredHeight);
- doThrowOOME(env, msg.c_str());
- return nullptr;
- }
-
- SkPaint paint;
- paint.setBlendMode(SkBlendMode::kSrc);
- paint.setFilterQuality(kLow_SkFilterQuality); // bilinear filtering
-
- SkCanvas canvas(scaledBm, SkCanvas::ColorBehavior::kLegacy);
- canvas.translate(translateX, translateY);
- if (scale) {
- float scaleX = (float) desiredWidth / decodeInfo.width();
- float scaleY = (float) desiredHeight / decodeInfo.height();
- canvas.scale(scaleX, scaleY);
- }
-
- canvas.drawBitmap(bm, 0.0f, 0.0f, &paint);
-
- bm.swap(scaledBm);
- nativeBitmap = std::move(scaledPixelRef);
- }
-
if (jpostProcess) {
std::unique_ptr<Canvas> canvas(Canvas::create_canvas(bm));
@@ -433,12 +398,12 @@ static jobject ImageDecoder_nDecodeBitmap(JNIEnv* env, jobject /*clazz*/, jlong
SkAlphaType newAlphaType = bm.alphaType();
switch (pixelFormat) {
- case ImageDecoder::kUnknown:
+ case kUnknown:
break;
- case ImageDecoder::kTranslucent:
+ case kTranslucent:
newAlphaType = kPremul_SkAlphaType;
break;
- case ImageDecoder::kOpaque:
+ case kOpaque:
newAlphaType = kOpaque_SkAlphaType;
break;
default:
@@ -477,7 +442,7 @@ static jobject ImageDecoder_nDecodeBitmap(JNIEnv* env, jobject /*clazz*/, jlong
return bitmap::createBitmap(env, hwBitmap.release(), bitmapCreateFlags,
ninePatchChunk, ninePatchInsets);
}
- if (allocator == ImageDecoder::kHardware_Allocator) {
+ if (allocator == kHardware_Allocator) {
doThrowOOME(env, "failed to allocate hardware Bitmap!");
return nullptr;
}
@@ -501,7 +466,7 @@ static jobject ImageDecoder_nGetSampledSize(JNIEnv* env, jobject /*clazz*/, jlon
static void ImageDecoder_nGetPadding(JNIEnv* env, jobject /*clazz*/, jlong nativePtr,
jobject outPadding) {
auto* decoder = reinterpret_cast<ImageDecoder*>(nativePtr);
- decoder->mPeeker->getPadding(env, outPadding);
+ reinterpret_cast<NinePatchPeeker*>(decoder->mPeeker.get())->getPadding(env, outPadding);
}
static void ImageDecoder_nClose(JNIEnv* /*env*/, jobject /*clazz*/, jlong nativePtr) {
diff --git a/core/jni/android/graphics/ImageDecoder.h b/core/jni/android/graphics/ImageDecoder.h
index fd9827bd74ca..8a7fa79503ba 100644
--- a/core/jni/android/graphics/ImageDecoder.h
+++ b/core/jni/android/graphics/ImageDecoder.h
@@ -14,48 +14,12 @@
* limitations under the License.
*/
-#include "NinePatchPeeker.h"
-
#include <hwui/Canvas.h>
#include <jni.h>
-class SkAndroidCodec;
-
-using namespace android;
-
-struct ImageDecoder {
- // These need to stay in sync with ImageDecoder.java's Allocator constants.
- enum Allocator {
- kDefault_Allocator = 0,
- kSoftware_Allocator = 1,
- kSharedMemory_Allocator = 2,
- kHardware_Allocator = 3,
- };
-
- // These need to stay in sync with ImageDecoder.java's Error constants.
- enum Error {
- kSourceException = 1,
- kSourceIncomplete = 2,
- kSourceMalformedData = 3,
- };
-
- // These need to stay in sync with PixelFormat.java's Format constants.
- enum PixelFormat {
- kUnknown = 0,
- kTranslucent = -3,
- kOpaque = -1,
- };
-
- std::unique_ptr<SkAndroidCodec> mCodec;
- sk_sp<NinePatchPeeker> mPeeker;
-
- ImageDecoder()
- :mPeeker(new NinePatchPeeker)
- {}
-};
-
// Creates a Java Canvas object from canvas, calls jimageDecoder's PostProcess on it, and then
// releases the Canvas.
// Caller needs to check for exceptions.
-jint postProcessAndRelease(JNIEnv* env, jobject jimageDecoder, std::unique_ptr<Canvas> canvas);
+jint postProcessAndRelease(JNIEnv* env, jobject jimageDecoder,
+ std::unique_ptr<android::Canvas> canvas);
diff --git a/core/jni/android/graphics/apex/jni_runtime.cpp b/core/jni/android/graphics/apex/jni_runtime.cpp
index 7f9bac0df44a..1f661534ad81 100644
--- a/core/jni/android/graphics/apex/jni_runtime.cpp
+++ b/core/jni/android/graphics/apex/jni_runtime.cpp
@@ -52,6 +52,7 @@ extern int register_android_graphics_ColorFilter(JNIEnv* env);
extern int register_android_graphics_ColorSpace(JNIEnv* env);
extern int register_android_graphics_DrawFilter(JNIEnv* env);
extern int register_android_graphics_FontFamily(JNIEnv* env);
+extern int register_android_graphics_HardwareRendererObserver(JNIEnv* env);
extern int register_android_graphics_Matrix(JNIEnv* env);
extern int register_android_graphics_Paint(JNIEnv* env);
extern int register_android_graphics_Path(JNIEnv* env);
@@ -71,7 +72,6 @@ extern int register_android_graphics_text_LineBreaker(JNIEnv *env);
extern int register_android_util_PathParser(JNIEnv* env);
extern int register_android_view_DisplayListCanvas(JNIEnv* env);
-extern int register_android_view_FrameMetricsObserver(JNIEnv* env);
extern int register_android_view_RenderNode(JNIEnv* env);
extern int register_android_view_TextureLayer(JNIEnv* env);
extern int register_android_view_ThreadedRenderer(JNIEnv* env);
@@ -105,6 +105,7 @@ static const RegJNIRec gRegJNI[] = {
REG_JNI(register_android_graphics_ColorFilter),
REG_JNI(register_android_graphics_DrawFilter),
REG_JNI(register_android_graphics_FontFamily),
+ REG_JNI(register_android_graphics_HardwareRendererObserver),
REG_JNI(register_android_graphics_ImageDecoder),
REG_JNI(register_android_graphics_drawable_AnimatedImageDrawable),
REG_JNI(register_android_graphics_Interpolator),
@@ -135,7 +136,6 @@ static const RegJNIRec gRegJNI[] = {
REG_JNI(register_android_util_PathParser),
REG_JNI(register_android_view_RenderNode),
REG_JNI(register_android_view_DisplayListCanvas),
- REG_JNI(register_android_view_FrameMetricsObserver),
REG_JNI(register_android_view_TextureLayer),
REG_JNI(register_android_view_ThreadedRenderer),
};
diff --git a/core/jni/android_graphics_HardwareRendererObserver.cpp b/core/jni/android_graphics_HardwareRendererObserver.cpp
new file mode 100644
index 000000000000..89b77b0b069a
--- /dev/null
+++ b/core/jni/android_graphics_HardwareRendererObserver.cpp
@@ -0,0 +1,130 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#include "android_graphics_HardwareRendererObserver.h"
+
+#include "core_jni_helpers.h"
+#include "nativehelper/jni_macros.h"
+
+#include <array>
+
+namespace android {
+
+struct {
+ jmethodID callback;
+} gHardwareRendererObserverClassInfo;
+
+static JNIEnv* getenv(JavaVM* vm) {
+ JNIEnv* env;
+ if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
+ LOG_ALWAYS_FATAL("Failed to get JNIEnv for JavaVM: %p", vm);
+ }
+ return env;
+}
+
+HardwareRendererObserver::HardwareRendererObserver(JavaVM *vm, jobject observer) : mVm(vm) {
+ mObserverWeak = getenv(mVm)->NewWeakGlobalRef(observer);
+ LOG_ALWAYS_FATAL_IF(mObserverWeak == nullptr,
+ "unable to create frame stats observer reference");
+}
+
+HardwareRendererObserver::~HardwareRendererObserver() {
+ JNIEnv* env = getenv(mVm);
+ env->DeleteWeakGlobalRef(mObserverWeak);
+}
+
+bool HardwareRendererObserver::getNextBuffer(JNIEnv* env, jlongArray metrics, int* dropCount) {
+ jsize bufferSize = env->GetArrayLength(reinterpret_cast<jarray>(metrics));
+ LOG_ALWAYS_FATAL_IF(bufferSize != HardwareRendererObserver::kBufferSize,
+ "Mismatched Java/Native FrameMetrics data format.");
+
+ FrameMetricsNotification& elem = mRingBuffer[mNextInQueue];
+ if (elem.hasData.load()) {
+ env->SetLongArrayRegion(metrics, 0, kBufferSize, elem.buffer);
+ *dropCount = elem.dropCount;
+ mNextInQueue = (mNextInQueue + 1) % kRingSize;
+ elem.hasData = false;
+ return true;
+ }
+
+ return false;
+}
+
+void HardwareRendererObserver::notify(const int64_t* stats) {
+ FrameMetricsNotification& elem = mRingBuffer[mNextFree];
+
+ if (!elem.hasData.load()) {
+ memcpy(elem.buffer, stats, kBufferSize * sizeof(stats[0]));
+
+ elem.dropCount = mDroppedReports;
+ mDroppedReports = 0;
+ mNextFree = (mNextFree + 1) % kRingSize;
+ elem.hasData = true;
+
+ JNIEnv* env = getenv(mVm);
+ jobject target = env->NewLocalRef(mObserverWeak);
+ if (target != nullptr) {
+ env->CallVoidMethod(target, gHardwareRendererObserverClassInfo.callback);
+ env->DeleteLocalRef(target);
+ }
+ } else {
+ mDroppedReports++;
+ }
+}
+
+static jlong android_graphics_HardwareRendererObserver_createObserver(JNIEnv* env,
+ jobject observerObj) {
+ JavaVM* vm = nullptr;
+ if (env->GetJavaVM(&vm) != JNI_OK) {
+ LOG_ALWAYS_FATAL("Unable to get Java VM");
+ return 0;
+ }
+
+ HardwareRendererObserver* observer = new HardwareRendererObserver(vm, observerObj);
+ return reinterpret_cast<jlong>(observer);
+}
+
+static jint android_graphics_HardwareRendererObserver_getNextBuffer(JNIEnv* env, jobject,
+ jlong observerPtr,
+ jlongArray metrics) {
+ HardwareRendererObserver* observer = reinterpret_cast<HardwareRendererObserver*>(observerPtr);
+ int dropCount = 0;
+ if (observer->getNextBuffer(env, metrics, &dropCount)) {
+ return dropCount;
+ } else {
+ return -1;
+ }
+}
+
+static const std::array gMethods = {
+ MAKE_JNI_NATIVE_METHOD("nCreateObserver", "()J",
+ android_graphics_HardwareRendererObserver_createObserver),
+ MAKE_JNI_NATIVE_METHOD("nGetNextBuffer", "(J[J)I",
+ android_graphics_HardwareRendererObserver_getNextBuffer),
+};
+
+int register_android_graphics_HardwareRendererObserver(JNIEnv* env) {
+
+ jclass observerClass = FindClassOrDie(env, "android/graphics/HardwareRendererObserver");
+ gHardwareRendererObserverClassInfo.callback = GetMethodIDOrDie(env, observerClass,
+ "notifyDataAvailable", "()V");
+
+ return RegisterMethodsOrDie(env, "android/graphics/HardwareRendererObserver",
+ gMethods.data(), gMethods.size());
+
+}
+
+} // namespace android \ No newline at end of file
diff --git a/core/jni/android_graphics_HardwareRendererObserver.h b/core/jni/android_graphics_HardwareRendererObserver.h
new file mode 100644
index 000000000000..62111fd7d7a1
--- /dev/null
+++ b/core/jni/android_graphics_HardwareRendererObserver.h
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#include "jni.h"
+
+#include <FrameInfo.h>
+#include <FrameMetricsObserver.h>
+
+namespace android {
+
+/*
+ * Implements JNI layer for hwui frame metrics reporting.
+ */
+class HardwareRendererObserver : public uirenderer::FrameMetricsObserver {
+public:
+ HardwareRendererObserver(JavaVM *vm, jobject observer);
+ ~HardwareRendererObserver();
+
+ /**
+ * Retrieves frame metrics for the oldest frame that the renderer has retained. The renderer
+ * will retain a buffer until it has been retrieved, via this method, or its internal storage
+ * is exhausted at which point it informs the caller of how many frames it has failed to store
+ * since the last time this method was invoked.
+ * @param env java env required to populate the provided buffer array
+ * @param metrics output parameter that represents the buffer of metrics that is to be filled
+ * @param dropCount output parameter that is updated to reflect the number of buffers that were
+ discarded since the last successful invocation of this method.
+ * @return true if there was data to populate the array and false otherwise. If false then
+ * neither the metrics buffer or dropCount will be modified.
+ */
+ bool getNextBuffer(JNIEnv* env, jlongArray metrics, int* dropCount);
+
+ void notify(const int64_t* stats) override;
+
+private:
+ static constexpr int kBufferSize = static_cast<int>(uirenderer::FrameInfoIndex::NumIndexes);
+ static constexpr int kRingSize = 3;
+
+ class FrameMetricsNotification {
+ public:
+ FrameMetricsNotification() {}
+
+ std::atomic_bool hasData = false;
+ int64_t buffer[kBufferSize];
+ int dropCount = 0;
+ private:
+ // non-copyable
+ FrameMetricsNotification(const FrameMetricsNotification&) = delete;
+ FrameMetricsNotification& operator=(const FrameMetricsNotification& ) = delete;
+ };
+
+ JavaVM* const mVm;
+ jweak mObserverWeak;
+
+ int mNextFree = 0;
+ int mNextInQueue = 0;
+ FrameMetricsNotification mRingBuffer[kRingSize];
+
+ int mDroppedReports = 0;
+};
+
+} // namespace android
diff --git a/core/jni/android_hardware_SoundTrigger.cpp b/core/jni/android_hardware_SoundTrigger.cpp
deleted file mode 100644
index 0002f8b4048a..000000000000
--- a/core/jni/android_hardware_SoundTrigger.cpp
+++ /dev/null
@@ -1,967 +0,0 @@
-/*
-**
-** Copyright 2014, 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.
-*/
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "SoundTrigger-JNI"
-#include <utils/Log.h>
-
-#include "jni.h"
-#include <nativehelper/JNIHelp.h>
-#include <nativehelper/ScopedUtfChars.h>
-#include "core_jni_helpers.h"
-#include <system/sound_trigger.h>
-#include <soundtrigger/SoundTriggerCallback.h>
-#include <soundtrigger/SoundTrigger.h>
-#include <utils/RefBase.h>
-#include <utils/Vector.h>
-#include <binder/IMemory.h>
-#include <binder/MemoryDealer.h>
-#include "android_media_AudioFormat.h"
-
-using namespace android;
-
-static jclass gArrayListClass;
-static struct {
- jmethodID add;
-} gArrayListMethods;
-
-static jclass gUUIDClass;
-static struct {
- jmethodID toString;
-} gUUIDMethods;
-
-static const char* const kSoundTriggerClassPathName = "android/hardware/soundtrigger/SoundTrigger";
-static jclass gSoundTriggerClass;
-
-static const char* const kModuleClassPathName = "android/hardware/soundtrigger/SoundTriggerModule";
-static jclass gModuleClass;
-static struct {
- jfieldID mNativeContext;
- jfieldID mId;
-} gModuleFields;
-static jmethodID gPostEventFromNative;
-
-static const char* const kModulePropertiesClassPathName =
- "android/hardware/soundtrigger/SoundTrigger$ModuleProperties";
-static jclass gModulePropertiesClass;
-static jmethodID gModulePropertiesCstor;
-
-static const char* const kSoundModelClassPathName =
- "android/hardware/soundtrigger/SoundTrigger$SoundModel";
-static jclass gSoundModelClass;
-static struct {
- jfieldID uuid;
- jfieldID vendorUuid;
- jfieldID data;
-} gSoundModelFields;
-
-static const char* const kGenericSoundModelClassPathName =
- "android/hardware/soundtrigger/SoundTrigger$GenericSoundModel";
-static jclass gGenericSoundModelClass;
-
-static const char* const kKeyphraseClassPathName =
- "android/hardware/soundtrigger/SoundTrigger$Keyphrase";
-static jclass gKeyphraseClass;
-static struct {
- jfieldID id;
- jfieldID recognitionModes;
- jfieldID locale;
- jfieldID text;
- jfieldID users;
-} gKeyphraseFields;
-
-static const char* const kKeyphraseSoundModelClassPathName =
- "android/hardware/soundtrigger/SoundTrigger$KeyphraseSoundModel";
-static jclass gKeyphraseSoundModelClass;
-static struct {
- jfieldID keyphrases;
-} gKeyphraseSoundModelFields;
-
-static const char* const kRecognitionConfigClassPathName =
- "android/hardware/soundtrigger/SoundTrigger$RecognitionConfig";
-static jclass gRecognitionConfigClass;
-static struct {
- jfieldID captureRequested;
- jfieldID keyphrases;
- jfieldID data;
-} gRecognitionConfigFields;
-
-static const char* const kRecognitionEventClassPathName =
- "android/hardware/soundtrigger/SoundTrigger$RecognitionEvent";
-static jclass gRecognitionEventClass;
-static jmethodID gRecognitionEventCstor;
-
-static const char* const kKeyphraseRecognitionEventClassPathName =
- "android/hardware/soundtrigger/SoundTrigger$KeyphraseRecognitionEvent";
-static jclass gKeyphraseRecognitionEventClass;
-static jmethodID gKeyphraseRecognitionEventCstor;
-
-static const char* const kGenericRecognitionEventClassPathName =
- "android/hardware/soundtrigger/SoundTrigger$GenericRecognitionEvent";
-static jclass gGenericRecognitionEventClass;
-static jmethodID gGenericRecognitionEventCstor;
-
-static const char* const kKeyphraseRecognitionExtraClassPathName =
- "android/hardware/soundtrigger/SoundTrigger$KeyphraseRecognitionExtra";
-static jclass gKeyphraseRecognitionExtraClass;
-static jmethodID gKeyphraseRecognitionExtraCstor;
-static struct {
- jfieldID id;
- jfieldID recognitionModes;
- jfieldID coarseConfidenceLevel;
- jfieldID confidenceLevels;
-} gKeyphraseRecognitionExtraFields;
-
-static const char* const kConfidenceLevelClassPathName =
- "android/hardware/soundtrigger/SoundTrigger$ConfidenceLevel";
-static jclass gConfidenceLevelClass;
-static jmethodID gConfidenceLevelCstor;
-static struct {
- jfieldID userId;
- jfieldID confidenceLevel;
-} gConfidenceLevelFields;
-
-static const char* const kAudioFormatClassPathName =
- "android/media/AudioFormat";
-static jclass gAudioFormatClass;
-static jmethodID gAudioFormatCstor;
-
-static const char* const kSoundModelEventClassPathName =
- "android/hardware/soundtrigger/SoundTrigger$SoundModelEvent";
-static jclass gSoundModelEventClass;
-static jmethodID gSoundModelEventCstor;
-
-static Mutex gLock;
-
-enum {
- SOUNDTRIGGER_STATUS_OK = 0,
- SOUNDTRIGGER_STATUS_ERROR = INT_MIN,
- SOUNDTRIGGER_PERMISSION_DENIED = -1,
- SOUNDTRIGGER_STATUS_NO_INIT = -19,
- SOUNDTRIGGER_STATUS_BAD_VALUE = -22,
- SOUNDTRIGGER_STATUS_DEAD_OBJECT = -32,
- SOUNDTRIGGER_INVALID_OPERATION = -38,
-};
-
-enum {
- SOUNDTRIGGER_EVENT_RECOGNITION = 1,
- SOUNDTRIGGER_EVENT_SERVICE_DIED = 2,
- SOUNDTRIGGER_EVENT_SOUNDMODEL = 3,
- SOUNDTRIGGER_EVENT_SERVICE_STATE_CHANGE = 4,
-};
-
-// ----------------------------------------------------------------------------
-// ref-counted object for callbacks
-class JNISoundTriggerCallback: public SoundTriggerCallback
-{
-public:
- JNISoundTriggerCallback(JNIEnv* env, jobject thiz, jobject weak_thiz);
- ~JNISoundTriggerCallback();
-
- virtual void onRecognitionEvent(struct sound_trigger_recognition_event *event);
- virtual void onSoundModelEvent(struct sound_trigger_model_event *event);
- virtual void onServiceStateChange(sound_trigger_service_state_t state);
- virtual void onServiceDied();
-
-private:
- jclass mClass; // Reference to SoundTrigger class
- jobject mObject; // Weak ref to SoundTrigger Java object to call on
-};
-
-JNISoundTriggerCallback::JNISoundTriggerCallback(JNIEnv* env, jobject thiz, jobject weak_thiz)
-{
-
- // Hold onto the SoundTriggerModule class for use in calling the static method
- // that posts events to the application thread.
- jclass clazz = env->GetObjectClass(thiz);
- if (clazz == NULL) {
- ALOGE("Can't find class %s", kModuleClassPathName);
- return;
- }
- mClass = (jclass)env->NewGlobalRef(clazz);
-
- // We use a weak reference so the SoundTriggerModule object can be garbage collected.
- // The reference is only used as a proxy for callbacks.
- mObject = env->NewGlobalRef(weak_thiz);
-}
-
-JNISoundTriggerCallback::~JNISoundTriggerCallback()
-{
- // remove global references
- JNIEnv *env = AndroidRuntime::getJNIEnv();
- env->DeleteGlobalRef(mObject);
- env->DeleteGlobalRef(mClass);
-}
-
-void JNISoundTriggerCallback::onRecognitionEvent(struct sound_trigger_recognition_event *event)
-{
- JNIEnv *env = AndroidRuntime::getJNIEnv();
- jobject jEvent = NULL;
- jbyteArray jData = NULL;
-
- if (event->data_size) {
- jData = env->NewByteArray(event->data_size);
- jbyte *nData = env->GetByteArrayElements(jData, NULL);
- memcpy(nData, (char *)event + event->data_offset, event->data_size);
- env->ReleaseByteArrayElements(jData, nData, 0);
- }
-
- jobject jAudioFormat = NULL;
- if (event->trigger_in_data || event->capture_available) {
- jint channelMask = (jint)audio_channel_mask_get_bits(event->audio_config.channel_mask);
- jint channelIndexMask = (jint)AUDIO_CHANNEL_NONE;
-
- switch (audio_channel_mask_get_representation(event->audio_config.channel_mask)) {
- case AUDIO_CHANNEL_REPRESENTATION_INDEX:
- channelIndexMask = channelMask;
- channelMask = (jint)AUDIO_CHANNEL_NONE;
- break;
- default:
- break;
- }
- jAudioFormat = env->NewObject(gAudioFormatClass,
- gAudioFormatCstor,
- audioFormatFromNative(event->audio_config.format),
- event->audio_config.sample_rate,
- channelMask,
- channelIndexMask);
-
- }
- if (event->type == SOUND_MODEL_TYPE_KEYPHRASE) {
- struct sound_trigger_phrase_recognition_event *phraseEvent =
- (struct sound_trigger_phrase_recognition_event *)event;
-
- jobjectArray jExtras = env->NewObjectArray(phraseEvent->num_phrases,
- gKeyphraseRecognitionExtraClass, NULL);
- if (jExtras == NULL) {
- return;
- }
-
- for (size_t i = 0; i < phraseEvent->num_phrases; i++) {
- jobjectArray jConfidenceLevels = env->NewObjectArray(
- phraseEvent->phrase_extras[i].num_levels,
- gConfidenceLevelClass, NULL);
-
- if (jConfidenceLevels == NULL) {
- return;
- }
- for (size_t j = 0; j < phraseEvent->phrase_extras[i].num_levels; j++) {
- jobject jConfidenceLevel = env->NewObject(gConfidenceLevelClass,
- gConfidenceLevelCstor,
- phraseEvent->phrase_extras[i].levels[j].user_id,
- phraseEvent->phrase_extras[i].levels[j].level);
- env->SetObjectArrayElement(jConfidenceLevels, j, jConfidenceLevel);
- env->DeleteLocalRef(jConfidenceLevel);
- }
-
- jobject jNewExtra = env->NewObject(gKeyphraseRecognitionExtraClass,
- gKeyphraseRecognitionExtraCstor,
- phraseEvent->phrase_extras[i].id,
- phraseEvent->phrase_extras[i].recognition_modes,
- phraseEvent->phrase_extras[i].confidence_level,
- jConfidenceLevels);
-
- if (jNewExtra == NULL) {
- return;
- }
- env->SetObjectArrayElement(jExtras, i, jNewExtra);
- env->DeleteLocalRef(jNewExtra);
- env->DeleteLocalRef(jConfidenceLevels);
- }
- jEvent = env->NewObject(gKeyphraseRecognitionEventClass, gKeyphraseRecognitionEventCstor,
- event->status, event->model, event->capture_available,
- event->capture_session, event->capture_delay_ms,
- event->capture_preamble_ms, event->trigger_in_data,
- jAudioFormat, jData, jExtras);
- env->DeleteLocalRef(jExtras);
- } else if (event->type == SOUND_MODEL_TYPE_GENERIC) {
- jEvent = env->NewObject(gGenericRecognitionEventClass, gGenericRecognitionEventCstor,
- event->status, event->model, event->capture_available,
- event->capture_session, event->capture_delay_ms,
- event->capture_preamble_ms, event->trigger_in_data,
- jAudioFormat, jData);
- } else {
- jEvent = env->NewObject(gRecognitionEventClass, gRecognitionEventCstor,
- event->status, event->model, event->capture_available,
- event->capture_session, event->capture_delay_ms,
- event->capture_preamble_ms, event->trigger_in_data,
- jAudioFormat, jData);
- }
-
- if (jAudioFormat != NULL) {
- env->DeleteLocalRef(jAudioFormat);
- }
- if (jData != NULL) {
- env->DeleteLocalRef(jData);
- }
-
- env->CallStaticVoidMethod(mClass, gPostEventFromNative, mObject,
- SOUNDTRIGGER_EVENT_RECOGNITION, 0, 0, jEvent);
-
- env->DeleteLocalRef(jEvent);
- if (env->ExceptionCheck()) {
- ALOGW("An exception occurred while notifying an event.");
- env->ExceptionClear();
- }
-}
-
-void JNISoundTriggerCallback::onSoundModelEvent(struct sound_trigger_model_event *event)
-{
- JNIEnv *env = AndroidRuntime::getJNIEnv();
- jobject jEvent = NULL;
- jbyteArray jData = NULL;
-
- if (event->data_size) {
- jData = env->NewByteArray(event->data_size);
- jbyte *nData = env->GetByteArrayElements(jData, NULL);
- memcpy(nData, (char *)event + event->data_offset, event->data_size);
- env->ReleaseByteArrayElements(jData, nData, 0);
- }
-
- jEvent = env->NewObject(gSoundModelEventClass, gSoundModelEventCstor,
- event->status, event->model, jData);
-
- env->DeleteLocalRef(jData);
- env->CallStaticVoidMethod(mClass, gPostEventFromNative, mObject,
- SOUNDTRIGGER_EVENT_SOUNDMODEL, 0, 0, jEvent);
- env->DeleteLocalRef(jEvent);
- if (env->ExceptionCheck()) {
- ALOGW("An exception occurred while notifying an event.");
- env->ExceptionClear();
- }
-}
-
-void JNISoundTriggerCallback::onServiceStateChange(sound_trigger_service_state_t state)
-{
- JNIEnv *env = AndroidRuntime::getJNIEnv();
- env->CallStaticVoidMethod(mClass, gPostEventFromNative, mObject,
- SOUNDTRIGGER_EVENT_SERVICE_STATE_CHANGE, state, 0, NULL);
- if (env->ExceptionCheck()) {
- ALOGW("An exception occurred while notifying an event.");
- env->ExceptionClear();
- }
-}
-
-void JNISoundTriggerCallback::onServiceDied()
-{
- JNIEnv *env = AndroidRuntime::getJNIEnv();
-
- env->CallStaticVoidMethod(mClass, gPostEventFromNative, mObject,
- SOUNDTRIGGER_EVENT_SERVICE_DIED, 0, 0, NULL);
- if (env->ExceptionCheck()) {
- ALOGW("An exception occurred while notifying an event.");
- env->ExceptionClear();
- }
-}
-
-// ----------------------------------------------------------------------------
-
-static sp<SoundTrigger> getSoundTrigger(JNIEnv* env, jobject thiz)
-{
- Mutex::Autolock l(gLock);
- SoundTrigger* const st = (SoundTrigger*)env->GetLongField(thiz,
- gModuleFields.mNativeContext);
- return sp<SoundTrigger>(st);
-}
-
-static sp<SoundTrigger> setSoundTrigger(JNIEnv* env, jobject thiz, const sp<SoundTrigger>& module)
-{
- Mutex::Autolock l(gLock);
- sp<SoundTrigger> old = (SoundTrigger*)env->GetLongField(thiz,
- gModuleFields.mNativeContext);
- if (module.get()) {
- module->incStrong((void*)setSoundTrigger);
- }
- if (old != 0) {
- old->decStrong((void*)setSoundTrigger);
- }
- env->SetLongField(thiz, gModuleFields.mNativeContext, (jlong)module.get());
- return old;
-}
-
-
-static jint
-android_hardware_SoundTrigger_listModules(JNIEnv *env, jobject clazz,
- jstring opPackageName, jobject jModules)
-{
- ALOGV("listModules");
-
- if (jModules == NULL) {
- ALOGE("listModules NULL AudioPatch ArrayList");
- return SOUNDTRIGGER_STATUS_BAD_VALUE;
- }
- if (!env->IsInstanceOf(jModules, gArrayListClass)) {
- ALOGE("listModules not an arraylist");
- return SOUNDTRIGGER_STATUS_BAD_VALUE;
- }
-
- unsigned int numModules = 0;
- struct sound_trigger_module_descriptor *nModules = NULL;
-
- ScopedUtfChars opPackageNameStr(env, opPackageName);
- const String16 opPackageNameString16 = String16(opPackageNameStr.c_str());
-
- status_t status = SoundTrigger::listModules(opPackageNameString16, nModules, &numModules);
- if (status != NO_ERROR || numModules == 0) {
- return (jint)status;
- }
-
- nModules = (struct sound_trigger_module_descriptor *)
- calloc(numModules, sizeof(struct sound_trigger_module_descriptor));
-
- status = SoundTrigger::listModules(opPackageNameString16, nModules, &numModules);
- ALOGV("listModules SoundTrigger::listModules status %d numModules %d", status, numModules);
-
- if (status != NO_ERROR) {
- numModules = 0;
- }
-
- for (size_t i = 0; i < numModules; i++) {
- char str[SOUND_TRIGGER_MAX_STRING_LEN];
-
- jstring implementor = env->NewStringUTF(nModules[i].properties.implementor);
- jstring description = env->NewStringUTF(nModules[i].properties.description);
- SoundTrigger::guidToString(&nModules[i].properties.uuid,
- str,
- SOUND_TRIGGER_MAX_STRING_LEN);
- jstring uuid = env->NewStringUTF(str);
-
- ALOGV("listModules module %zu id %d description %s maxSoundModels %d",
- i, nModules[i].handle, nModules[i].properties.description,
- nModules[i].properties.max_sound_models);
-
- jobject newModuleDesc = env->NewObject(gModulePropertiesClass, gModulePropertiesCstor,
- nModules[i].handle,
- implementor, description, uuid,
- nModules[i].properties.version,
- nModules[i].properties.max_sound_models,
- nModules[i].properties.max_key_phrases,
- nModules[i].properties.max_users,
- nModules[i].properties.recognition_modes,
- nModules[i].properties.capture_transition,
- nModules[i].properties.max_buffer_ms,
- nModules[i].properties.concurrent_capture,
- nModules[i].properties.power_consumption_mw,
- nModules[i].properties.trigger_in_event);
-
- env->DeleteLocalRef(implementor);
- env->DeleteLocalRef(description);
- env->DeleteLocalRef(uuid);
- if (newModuleDesc == NULL) {
- status = SOUNDTRIGGER_STATUS_ERROR;
- goto exit;
- }
- env->CallBooleanMethod(jModules, gArrayListMethods.add, newModuleDesc);
- }
-
-exit:
- free(nModules);
- return (jint) status;
-}
-
-static void
-android_hardware_SoundTrigger_setup(JNIEnv *env, jobject thiz,
- jstring opPackageName, jobject weak_this)
-{
- ALOGV("setup");
-
- ScopedUtfChars opPackageNameStr(env, opPackageName);
- const String16 opPackageNameString16 = String16(opPackageNameStr.c_str());
-
- sp<JNISoundTriggerCallback> callback = new JNISoundTriggerCallback(env, thiz, weak_this);
-
- sound_trigger_module_handle_t handle =
- (sound_trigger_module_handle_t)env->GetIntField(thiz, gModuleFields.mId);
-
- sp<SoundTrigger> module = SoundTrigger::attach(opPackageNameString16, handle, callback);
- if (module == 0) {
- return;
- }
-
- setSoundTrigger(env, thiz, module);
-}
-
-static void
-android_hardware_SoundTrigger_detach(JNIEnv *env, jobject thiz)
-{
- ALOGV("detach");
- sp<SoundTrigger> module = setSoundTrigger(env, thiz, 0);
- ALOGV("detach module %p", module.get());
- if (module != 0) {
- ALOGV("detach module->detach()");
- module->detach();
- }
-}
-
-static void
-android_hardware_SoundTrigger_finalize(JNIEnv *env, jobject thiz)
-{
- ALOGV("finalize");
- sp<SoundTrigger> module = getSoundTrigger(env, thiz);
- if (module != 0) {
- ALOGW("SoundTrigger finalized without being detached");
- }
- android_hardware_SoundTrigger_detach(env, thiz);
-}
-
-static jint
-android_hardware_SoundTrigger_loadSoundModel(JNIEnv *env, jobject thiz,
- jobject jSoundModel, jintArray jHandle)
-{
- jint status = SOUNDTRIGGER_STATUS_OK;
- jbyte *nData = NULL;
- struct sound_trigger_sound_model *nSoundModel;
- jbyteArray jData;
- sp<MemoryDealer> memoryDealer;
- sp<IMemory> memory;
- size_t size;
- sound_model_handle_t handle = 0;
- jobject jUuid;
- jstring jUuidString;
- const char *nUuidString;
-
- ALOGV("loadSoundModel");
- sp<SoundTrigger> module = getSoundTrigger(env, thiz);
- if (module == NULL) {
- return SOUNDTRIGGER_STATUS_ERROR;
- }
- if (jHandle == NULL) {
- return SOUNDTRIGGER_STATUS_BAD_VALUE;
- }
- jsize jHandleLen = env->GetArrayLength(jHandle);
- if (jHandleLen == 0) {
- return SOUNDTRIGGER_STATUS_BAD_VALUE;
- }
- jint *nHandle = env->GetIntArrayElements(jHandle, NULL);
- if (nHandle == NULL) {
- return SOUNDTRIGGER_STATUS_ERROR;
- }
- if (!env->IsInstanceOf(jSoundModel, gSoundModelClass)) {
- status = SOUNDTRIGGER_STATUS_BAD_VALUE;
- goto exit;
- }
- size_t offset;
- sound_trigger_sound_model_type_t type;
- if (env->IsInstanceOf(jSoundModel, gKeyphraseSoundModelClass)) {
- offset = sizeof(struct sound_trigger_phrase_sound_model);
- type = SOUND_MODEL_TYPE_KEYPHRASE;
- } else if (env->IsInstanceOf(jSoundModel, gGenericSoundModelClass)) {
- offset = sizeof(struct sound_trigger_generic_sound_model);
- type = SOUND_MODEL_TYPE_GENERIC;
- } else {
- offset = sizeof(struct sound_trigger_sound_model);
- type = SOUND_MODEL_TYPE_UNKNOWN;
- }
-
- jUuid = env->GetObjectField(jSoundModel, gSoundModelFields.uuid);
- jUuidString = (jstring)env->CallObjectMethod(jUuid, gUUIDMethods.toString);
- nUuidString = env->GetStringUTFChars(jUuidString, NULL);
- sound_trigger_uuid_t nUuid;
- SoundTrigger::stringToGuid(nUuidString, &nUuid);
- env->ReleaseStringUTFChars(jUuidString, nUuidString);
- env->DeleteLocalRef(jUuidString);
-
- sound_trigger_uuid_t nVendorUuid;
- jUuid = env->GetObjectField(jSoundModel, gSoundModelFields.vendorUuid);
- if (jUuid != NULL) {
- jUuidString = (jstring)env->CallObjectMethod(jUuid, gUUIDMethods.toString);
- nUuidString = env->GetStringUTFChars(jUuidString, NULL);
- SoundTrigger::stringToGuid(nUuidString, &nVendorUuid);
- env->ReleaseStringUTFChars(jUuidString, nUuidString);
- env->DeleteLocalRef(jUuidString);
- } else {
- SoundTrigger::stringToGuid("00000000-0000-0000-0000-000000000000", &nVendorUuid);
- }
-
- jData = (jbyteArray)env->GetObjectField(jSoundModel, gSoundModelFields.data);
- if (jData == NULL) {
- status = SOUNDTRIGGER_STATUS_BAD_VALUE;
- goto exit;
- }
- size = env->GetArrayLength(jData);
-
- nData = env->GetByteArrayElements(jData, NULL);
- if (jData == NULL) {
- status = SOUNDTRIGGER_STATUS_ERROR;
- goto exit;
- }
-
- memoryDealer = new MemoryDealer(offset + size, "SoundTrigge-JNI::LoadModel");
- if (memoryDealer == 0) {
- status = SOUNDTRIGGER_STATUS_ERROR;
- goto exit;
- }
- memory = memoryDealer->allocate(offset + size);
- if (memory == 0 || memory->unsecurePointer() == NULL) {
- status = SOUNDTRIGGER_STATUS_ERROR;
- goto exit;
- }
-
- nSoundModel = (struct sound_trigger_sound_model *)memory->unsecurePointer();
-
- nSoundModel->type = type;
- nSoundModel->uuid = nUuid;
- nSoundModel->vendor_uuid = nVendorUuid;
- nSoundModel->data_size = size;
- nSoundModel->data_offset = offset;
- memcpy((char *)nSoundModel + offset, nData, size);
- if (type == SOUND_MODEL_TYPE_KEYPHRASE) {
- struct sound_trigger_phrase_sound_model *phraseModel =
- (struct sound_trigger_phrase_sound_model *)nSoundModel;
-
- jobjectArray jPhrases =
- (jobjectArray)env->GetObjectField(jSoundModel, gKeyphraseSoundModelFields.keyphrases);
- if (jPhrases == NULL) {
- status = SOUNDTRIGGER_STATUS_BAD_VALUE;
- goto exit;
- }
-
- size_t numPhrases = env->GetArrayLength(jPhrases);
- phraseModel->num_phrases = numPhrases;
- ALOGV("loadSoundModel numPhrases %zu", numPhrases);
- for (size_t i = 0; i < numPhrases; i++) {
- jobject jPhrase = env->GetObjectArrayElement(jPhrases, i);
- phraseModel->phrases[i].id =
- env->GetIntField(jPhrase,gKeyphraseFields.id);
- phraseModel->phrases[i].recognition_mode =
- env->GetIntField(jPhrase,gKeyphraseFields.recognitionModes);
-
- jintArray jUsers = (jintArray)env->GetObjectField(jPhrase, gKeyphraseFields.users);
- phraseModel->phrases[i].num_users = env->GetArrayLength(jUsers);
- jint *nUsers = env->GetIntArrayElements(jUsers, NULL);
- memcpy(phraseModel->phrases[i].users,
- nUsers,
- phraseModel->phrases[i].num_users * sizeof(int));
- env->ReleaseIntArrayElements(jUsers, nUsers, 0);
- env->DeleteLocalRef(jUsers);
-
- jstring jLocale = (jstring)env->GetObjectField(jPhrase, gKeyphraseFields.locale);
- const char *nLocale = env->GetStringUTFChars(jLocale, NULL);
- strncpy(phraseModel->phrases[i].locale,
- nLocale,
- SOUND_TRIGGER_MAX_LOCALE_LEN);
- jstring jText = (jstring)env->GetObjectField(jPhrase, gKeyphraseFields.text);
- const char *nText = env->GetStringUTFChars(jText, NULL);
- strncpy(phraseModel->phrases[i].text,
- nText,
- SOUND_TRIGGER_MAX_STRING_LEN);
-
- env->ReleaseStringUTFChars(jLocale, nLocale);
- env->DeleteLocalRef(jLocale);
- env->ReleaseStringUTFChars(jText, nText);
- env->DeleteLocalRef(jText);
- ALOGV("loadSoundModel phrases %zu text %s locale %s",
- i, phraseModel->phrases[i].text, phraseModel->phrases[i].locale);
- env->DeleteLocalRef(jPhrase);
- }
- env->DeleteLocalRef(jPhrases);
- } else if (type == SOUND_MODEL_TYPE_GENERIC) {
- /* No initialization needed */
- }
- status = module->loadSoundModel(memory, &handle);
- ALOGV("loadSoundModel status %d handle %d", status, handle);
-
-exit:
- if (nHandle != NULL) {
- nHandle[0] = (jint)handle;
- env->ReleaseIntArrayElements(jHandle, nHandle, NULL);
- }
- if (nData != NULL) {
- env->ReleaseByteArrayElements(jData, nData, NULL);
- }
- return status;
-}
-
-static jint
-android_hardware_SoundTrigger_unloadSoundModel(JNIEnv *env, jobject thiz,
- jint jHandle)
-{
- jint status = SOUNDTRIGGER_STATUS_OK;
- ALOGV("unloadSoundModel");
- sp<SoundTrigger> module = getSoundTrigger(env, thiz);
- if (module == NULL) {
- return SOUNDTRIGGER_STATUS_ERROR;
- }
- status = module->unloadSoundModel((sound_model_handle_t)jHandle);
-
- return status;
-}
-
-static jint
-android_hardware_SoundTrigger_startRecognition(JNIEnv *env, jobject thiz,
- jint jHandle, jobject jConfig)
-{
- jint status = SOUNDTRIGGER_STATUS_OK;
- ALOGV("startRecognition");
- sp<SoundTrigger> module = getSoundTrigger(env, thiz);
- if (module == NULL) {
- return SOUNDTRIGGER_STATUS_ERROR;
- }
-
- if (!env->IsInstanceOf(jConfig, gRecognitionConfigClass)) {
- return SOUNDTRIGGER_STATUS_BAD_VALUE;
- }
-
- jbyteArray jData = (jbyteArray)env->GetObjectField(jConfig, gRecognitionConfigFields.data);
- jsize dataSize = 0;
- jbyte *nData = NULL;
- if (jData != NULL) {
- dataSize = env->GetArrayLength(jData);
- if (dataSize == 0) {
- return SOUNDTRIGGER_STATUS_BAD_VALUE;
- }
- nData = env->GetByteArrayElements(jData, NULL);
- if (nData == NULL) {
- return SOUNDTRIGGER_STATUS_ERROR;
- }
- }
-
- size_t totalSize = sizeof(struct sound_trigger_recognition_config) + dataSize;
- sp<MemoryDealer> memoryDealer =
- new MemoryDealer(totalSize, "SoundTrigge-JNI::StartRecognition");
- if (memoryDealer == 0) {
- return SOUNDTRIGGER_STATUS_ERROR;
- }
- sp<IMemory> memory = memoryDealer->allocate(totalSize);
- if (memory == 0 || memory->unsecurePointer() == NULL) {
- return SOUNDTRIGGER_STATUS_ERROR;
- }
- if (dataSize != 0) {
- memcpy((char *)memory->unsecurePointer() + sizeof(struct sound_trigger_recognition_config),
- nData,
- dataSize);
- env->ReleaseByteArrayElements(jData, nData, 0);
- }
- env->DeleteLocalRef(jData);
- struct sound_trigger_recognition_config *config =
- (struct sound_trigger_recognition_config *)memory->unsecurePointer();
- config->data_size = dataSize;
- config->data_offset = sizeof(struct sound_trigger_recognition_config);
- config->capture_requested = env->GetBooleanField(jConfig,
- gRecognitionConfigFields.captureRequested);
-
- config->num_phrases = 0;
- jobjectArray jPhrases =
- (jobjectArray)env->GetObjectField(jConfig, gRecognitionConfigFields.keyphrases);
- if (jPhrases != NULL) {
- config->num_phrases = env->GetArrayLength(jPhrases);
- }
- ALOGV("startRecognition num phrases %d", config->num_phrases);
- for (size_t i = 0; i < config->num_phrases; i++) {
- jobject jPhrase = env->GetObjectArrayElement(jPhrases, i);
- config->phrases[i].id = env->GetIntField(jPhrase,
- gKeyphraseRecognitionExtraFields.id);
- config->phrases[i].recognition_modes = env->GetIntField(jPhrase,
- gKeyphraseRecognitionExtraFields.recognitionModes);
- config->phrases[i].confidence_level = env->GetIntField(jPhrase,
- gKeyphraseRecognitionExtraFields.coarseConfidenceLevel);
- config->phrases[i].num_levels = 0;
- jobjectArray jConfidenceLevels = (jobjectArray)env->GetObjectField(jPhrase,
- gKeyphraseRecognitionExtraFields.confidenceLevels);
- if (jConfidenceLevels != NULL) {
- config->phrases[i].num_levels = env->GetArrayLength(jConfidenceLevels);
- }
- ALOGV("startRecognition phrase %zu num_levels %d", i, config->phrases[i].num_levels);
- for (size_t j = 0; j < config->phrases[i].num_levels; j++) {
- jobject jConfidenceLevel = env->GetObjectArrayElement(jConfidenceLevels, j);
- config->phrases[i].levels[j].user_id = env->GetIntField(jConfidenceLevel,
- gConfidenceLevelFields.userId);
- config->phrases[i].levels[j].level = env->GetIntField(jConfidenceLevel,
- gConfidenceLevelFields.confidenceLevel);
- env->DeleteLocalRef(jConfidenceLevel);
- }
- ALOGV("startRecognition phrases %zu", i);
- env->DeleteLocalRef(jConfidenceLevels);
- env->DeleteLocalRef(jPhrase);
- }
- env->DeleteLocalRef(jPhrases);
-
- status = module->startRecognition(jHandle, memory);
- return status;
-}
-
-static jint
-android_hardware_SoundTrigger_stopRecognition(JNIEnv *env, jobject thiz,
- jint jHandle)
-{
- jint status = SOUNDTRIGGER_STATUS_OK;
- ALOGV("stopRecognition");
- sp<SoundTrigger> module = getSoundTrigger(env, thiz);
- if (module == NULL) {
- return SOUNDTRIGGER_STATUS_ERROR;
- }
- status = module->stopRecognition(jHandle);
- return status;
-}
-
-static jint
-android_hardware_SoundTrigger_getModelState(JNIEnv *env, jobject thiz,
- jint jHandle)
-{
- jint status = SOUNDTRIGGER_STATUS_OK;
- ALOGV("getModelState");
- sp<SoundTrigger> module = getSoundTrigger(env, thiz);
- if (module == NULL) {
- return SOUNDTRIGGER_STATUS_ERROR;
- }
- status = module->getModelState(jHandle);
- return status;
-}
-
-static const JNINativeMethod gMethods[] = {
- {"listModules",
- "(Ljava/lang/String;Ljava/util/ArrayList;)I",
- (void *)android_hardware_SoundTrigger_listModules},
-};
-
-
-static const JNINativeMethod gModuleMethods[] = {
- {"native_setup",
- "(Ljava/lang/String;Ljava/lang/Object;)V",
- (void *)android_hardware_SoundTrigger_setup},
- {"native_finalize",
- "()V",
- (void *)android_hardware_SoundTrigger_finalize},
- {"detach",
- "()V",
- (void *)android_hardware_SoundTrigger_detach},
- {"loadSoundModel",
- "(Landroid/hardware/soundtrigger/SoundTrigger$SoundModel;[I)I",
- (void *)android_hardware_SoundTrigger_loadSoundModel},
- {"unloadSoundModel",
- "(I)I",
- (void *)android_hardware_SoundTrigger_unloadSoundModel},
- {"startRecognition",
- "(ILandroid/hardware/soundtrigger/SoundTrigger$RecognitionConfig;)I",
- (void *)android_hardware_SoundTrigger_startRecognition},
- {"stopRecognition",
- "(I)I",
- (void *)android_hardware_SoundTrigger_stopRecognition},
- {"getModelState",
- "(I)I",
- (void *)android_hardware_SoundTrigger_getModelState},
-};
-
-int register_android_hardware_SoundTrigger(JNIEnv *env)
-{
- jclass arrayListClass = FindClassOrDie(env, "java/util/ArrayList");
- gArrayListClass = MakeGlobalRefOrDie(env, arrayListClass);
- gArrayListMethods.add = GetMethodIDOrDie(env, arrayListClass, "add", "(Ljava/lang/Object;)Z");
-
- jclass uuidClass = FindClassOrDie(env, "java/util/UUID");
- gUUIDClass = MakeGlobalRefOrDie(env, uuidClass);
- gUUIDMethods.toString = GetMethodIDOrDie(env, uuidClass, "toString", "()Ljava/lang/String;");
-
- jclass lClass = FindClassOrDie(env, kSoundTriggerClassPathName);
- gSoundTriggerClass = MakeGlobalRefOrDie(env, lClass);
-
- jclass moduleClass = FindClassOrDie(env, kModuleClassPathName);
- gModuleClass = MakeGlobalRefOrDie(env, moduleClass);
- gPostEventFromNative = GetStaticMethodIDOrDie(env, moduleClass, "postEventFromNative",
- "(Ljava/lang/Object;IIILjava/lang/Object;)V");
- gModuleFields.mNativeContext = GetFieldIDOrDie(env, moduleClass, "mNativeContext", "J");
- gModuleFields.mId = GetFieldIDOrDie(env, moduleClass, "mId", "I");
-
- jclass modulePropertiesClass = FindClassOrDie(env, kModulePropertiesClassPathName);
- gModulePropertiesClass = MakeGlobalRefOrDie(env, modulePropertiesClass);
- gModulePropertiesCstor = GetMethodIDOrDie(env, modulePropertiesClass, "<init>",
- "(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;IIIIIZIZIZ)V");
-
- jclass soundModelClass = FindClassOrDie(env, kSoundModelClassPathName);
- gSoundModelClass = MakeGlobalRefOrDie(env, soundModelClass);
- gSoundModelFields.uuid = GetFieldIDOrDie(env, soundModelClass, "uuid", "Ljava/util/UUID;");
- gSoundModelFields.vendorUuid = GetFieldIDOrDie(env, soundModelClass, "vendorUuid",
- "Ljava/util/UUID;");
- gSoundModelFields.data = GetFieldIDOrDie(env, soundModelClass, "data", "[B");
-
- jclass genericSoundModelClass = FindClassOrDie(env, kGenericSoundModelClassPathName);
- gGenericSoundModelClass = MakeGlobalRefOrDie(env, genericSoundModelClass);
-
- jclass keyphraseClass = FindClassOrDie(env, kKeyphraseClassPathName);
- gKeyphraseClass = MakeGlobalRefOrDie(env, keyphraseClass);
- gKeyphraseFields.id = GetFieldIDOrDie(env, keyphraseClass, "id", "I");
- gKeyphraseFields.recognitionModes = GetFieldIDOrDie(env, keyphraseClass, "recognitionModes",
- "I");
- gKeyphraseFields.locale = GetFieldIDOrDie(env, keyphraseClass, "locale", "Ljava/lang/String;");
- gKeyphraseFields.text = GetFieldIDOrDie(env, keyphraseClass, "text", "Ljava/lang/String;");
- gKeyphraseFields.users = GetFieldIDOrDie(env, keyphraseClass, "users", "[I");
-
- jclass keyphraseSoundModelClass = FindClassOrDie(env, kKeyphraseSoundModelClassPathName);
- gKeyphraseSoundModelClass = MakeGlobalRefOrDie(env, keyphraseSoundModelClass);
- gKeyphraseSoundModelFields.keyphrases = GetFieldIDOrDie(env, keyphraseSoundModelClass,
- "keyphrases",
- "[Landroid/hardware/soundtrigger/SoundTrigger$Keyphrase;");
-
- jclass recognitionEventClass = FindClassOrDie(env, kRecognitionEventClassPathName);
- gRecognitionEventClass = MakeGlobalRefOrDie(env, recognitionEventClass);
- gRecognitionEventCstor = GetMethodIDOrDie(env, recognitionEventClass, "<init>",
- "(IIZIIIZLandroid/media/AudioFormat;[B)V");
-
- jclass keyphraseRecognitionEventClass = FindClassOrDie(env,
- kKeyphraseRecognitionEventClassPathName);
- gKeyphraseRecognitionEventClass = MakeGlobalRefOrDie(env, keyphraseRecognitionEventClass);
- gKeyphraseRecognitionEventCstor = GetMethodIDOrDie(env, keyphraseRecognitionEventClass, "<init>",
- "(IIZIIIZLandroid/media/AudioFormat;[B[Landroid/hardware/soundtrigger/SoundTrigger$KeyphraseRecognitionExtra;)V");
-
- jclass genericRecognitionEventClass = FindClassOrDie(env,
- kGenericRecognitionEventClassPathName);
- gGenericRecognitionEventClass = MakeGlobalRefOrDie(env, genericRecognitionEventClass);
- gGenericRecognitionEventCstor = GetMethodIDOrDie(env, genericRecognitionEventClass, "<init>",
- "(IIZIIIZLandroid/media/AudioFormat;[B)V");
-
- jclass keyRecognitionConfigClass = FindClassOrDie(env, kRecognitionConfigClassPathName);
- gRecognitionConfigClass = MakeGlobalRefOrDie(env, keyRecognitionConfigClass);
- gRecognitionConfigFields.captureRequested = GetFieldIDOrDie(env, keyRecognitionConfigClass,
- "captureRequested", "Z");
- gRecognitionConfigFields.keyphrases = GetFieldIDOrDie(env, keyRecognitionConfigClass,
- "keyphrases", "[Landroid/hardware/soundtrigger/SoundTrigger$KeyphraseRecognitionExtra;");
- gRecognitionConfigFields.data = GetFieldIDOrDie(env, keyRecognitionConfigClass, "data", "[B");
-
- jclass keyphraseRecognitionExtraClass = FindClassOrDie(env,
- kKeyphraseRecognitionExtraClassPathName);
- gKeyphraseRecognitionExtraClass = MakeGlobalRefOrDie(env, keyphraseRecognitionExtraClass);
- gKeyphraseRecognitionExtraCstor = GetMethodIDOrDie(env, keyphraseRecognitionExtraClass,
- "<init>", "(III[Landroid/hardware/soundtrigger/SoundTrigger$ConfidenceLevel;)V");
- gKeyphraseRecognitionExtraFields.id = GetFieldIDOrDie(env, gKeyphraseRecognitionExtraClass,
- "id", "I");
- gKeyphraseRecognitionExtraFields.recognitionModes = GetFieldIDOrDie(env,
- gKeyphraseRecognitionExtraClass, "recognitionModes", "I");
- gKeyphraseRecognitionExtraFields.coarseConfidenceLevel = GetFieldIDOrDie(env,
- gKeyphraseRecognitionExtraClass, "coarseConfidenceLevel", "I");
- gKeyphraseRecognitionExtraFields.confidenceLevels = GetFieldIDOrDie(env,
- gKeyphraseRecognitionExtraClass, "confidenceLevels",
- "[Landroid/hardware/soundtrigger/SoundTrigger$ConfidenceLevel;");
-
- jclass confidenceLevelClass = FindClassOrDie(env, kConfidenceLevelClassPathName);
- gConfidenceLevelClass = MakeGlobalRefOrDie(env, confidenceLevelClass);
- gConfidenceLevelCstor = GetMethodIDOrDie(env, confidenceLevelClass, "<init>", "(II)V");
- gConfidenceLevelFields.userId = GetFieldIDOrDie(env, confidenceLevelClass, "userId", "I");
- gConfidenceLevelFields.confidenceLevel = GetFieldIDOrDie(env, confidenceLevelClass,
- "confidenceLevel", "I");
-
- jclass audioFormatClass = FindClassOrDie(env, kAudioFormatClassPathName);
- gAudioFormatClass = MakeGlobalRefOrDie(env, audioFormatClass);
- gAudioFormatCstor = GetMethodIDOrDie(env, audioFormatClass, "<init>", "(IIII)V");
-
- jclass soundModelEventClass = FindClassOrDie(env, kSoundModelEventClassPathName);
- gSoundModelEventClass = MakeGlobalRefOrDie(env, soundModelEventClass);
- gSoundModelEventCstor = GetMethodIDOrDie(env, soundModelEventClass, "<init>", "(II[B)V");
-
-
- RegisterMethodsOrDie(env, kSoundTriggerClassPathName, gMethods, NELEM(gMethods));
- return RegisterMethodsOrDie(env, kModuleClassPathName, gModuleMethods, NELEM(gModuleMethods));
-}
diff --git a/core/jni/android_media_AudioDeviceAddress.cpp b/core/jni/android_media_AudioDeviceAddress.cpp
new file mode 100644
index 000000000000..5f39f7efb6a2
--- /dev/null
+++ b/core/jni/android_media_AudioDeviceAddress.cpp
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#include "core_jni_helpers.h"
+#include "android_media_AudioDeviceAddress.h"
+#include "android_media_AudioErrors.h"
+
+#include <media/AudioDeviceTypeAddr.h>
+
+using namespace android;
+
+static jclass gAudioDeviceAddressClass;
+static jmethodID gAudioDeviceAddressCstor;
+
+namespace android {
+
+jint createAudioDeviceAddressFromNative(
+ JNIEnv *env, jobject *jAudioDeviceAddress,
+ const AudioDeviceTypeAddr *devTypeAddr) {
+ jint jStatus = (jint)AUDIO_JAVA_SUCCESS;
+ jint jNativeType = (jint)devTypeAddr->mType;
+ ScopedLocalRef<jstring> jAddress(env, env->NewStringUTF(devTypeAddr->mAddress.data()));
+
+ *jAudioDeviceAddress = env->NewObject(gAudioDeviceAddressClass, gAudioDeviceAddressCstor,
+ jNativeType, jAddress.get());
+
+ return jStatus;
+}
+
+}
+
+int register_android_media_AudioDeviceAddress(JNIEnv *env)
+{
+ jclass audioDeviceTypeAddressClass = FindClassOrDie(env, "android/media/AudioDeviceAddress");
+ gAudioDeviceAddressClass = MakeGlobalRefOrDie(env, audioDeviceTypeAddressClass);
+ gAudioDeviceAddressCstor = GetMethodIDOrDie(env, audioDeviceTypeAddressClass, "<init>",
+ "(ILjava/lang/String;)V");
+
+ return 0;
+}
diff --git a/libs/services/include/android/util/StatsEvent.h b/core/jni/android_media_AudioDeviceAddress.h
index 48631174f7dd..c66b17978776 100644
--- a/libs/services/include/android/util/StatsEvent.h
+++ b/core/jni/android_media_AudioDeviceAddress.h
@@ -13,31 +13,21 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-#ifndef STATS_EVENT_H
-#define STATS_EVENT_H
-#include <binder/Parcel.h>
-#include <binder/Parcelable.h>
-#include <binder/Status.h>
-#include <vector>
+#ifndef ANDROID_MEDIA_AUDIODEVICEADDRESS_H
+#define ANDROID_MEDIA_AUDIODEVICEADDRESS_H
-namespace android {
-namespace util {
-class StatsEvent : public android::Parcelable {
- public:
- StatsEvent();
+#include <system/audio.h>
+#include <media/AudioDeviceTypeAddr.h>
- StatsEvent(StatsEvent&& in) = default;
+#include "jni.h"
- android::status_t writeToParcel(android::Parcel* out) const;
+namespace android {
- android::status_t readFromParcel(const android::Parcel* in);
+// Create a Java AudioDeviceAddress instance from a C++ AudioDeviceTypeAddress
- private:
- int mAtomTag;
- std::vector<uint8_t> mBuffer;
-};
-} // Namespace util
-} // Namespace android
+extern jint createAudioDeviceAddressFromNative(JNIEnv *env, jobject *jAudioDeviceAddress,
+ const AudioDeviceTypeAddr *devTypeAddr);
+} // namespace android
-#endif // STATS_ EVENT_H \ No newline at end of file
+#endif \ No newline at end of file
diff --git a/core/jni/android_media_AudioRecord.cpp b/core/jni/android_media_AudioRecord.cpp
index 342aba024fc5..6cbc5878db61 100644
--- a/core/jni/android_media_AudioRecord.cpp
+++ b/core/jni/android_media_AudioRecord.cpp
@@ -763,7 +763,7 @@ android_media_AudioRecord_native_getMetrics(JNIEnv *env, jobject thiz)
}
// get what we have for the metrics from the record session
- MediaAnalyticsItem *item = NULL;
+ mediametrics::Item *item = NULL;
status_t err = lpRecord->getMetrics(item);
if (err != OK) {
diff --git a/core/jni/android_media_AudioSystem.cpp b/core/jni/android_media_AudioSystem.cpp
index 01f9d0b0cde5..79cf0191057d 100644
--- a/core/jni/android_media_AudioSystem.cpp
+++ b/core/jni/android_media_AudioSystem.cpp
@@ -26,19 +26,19 @@
#include <nativehelper/JNIHelp.h>
#include "core_jni_helpers.h"
+#include "android_media_AudioAttributes.h"
+#include "android_media_AudioDeviceAddress.h"
+#include "android_media_AudioEffectDescriptor.h"
+#include "android_media_AudioErrors.h"
+#include "android_media_AudioFormat.h"
+#include "android_media_MicrophoneInfo.h"
#include <audiomanager/AudioManager.h>
-#include <media/AudioDeviceTypeAddr.h>
-#include <media/AudioSystem.h>
#include <media/AudioPolicy.h>
+#include <media/AudioSystem.h>
#include <media/MicrophoneInfo.h>
#include <nativehelper/ScopedLocalRef.h>
#include <system/audio.h>
#include <system/audio_policy.h>
-#include "android_media_AudioEffectDescriptor.h"
-#include "android_media_AudioFormat.h"
-#include "android_media_AudioErrors.h"
-#include "android_media_MicrophoneInfo.h"
-#include "android_media_AudioAttributes.h"
// ----------------------------------------------------------------------------
@@ -2254,9 +2254,9 @@ static jint
android_media_AudioSystem_setAudioHalPids(JNIEnv *env, jobject clazz, jintArray jPids)
{
if (jPids == NULL) {
- return (jint)AUDIO_JAVA_BAD_VALUE;
+ return (jint) AUDIO_JAVA_BAD_VALUE;
}
- pid_t *nPidsArray = (pid_t *)env->GetIntArrayElements(jPids, NULL);
+ pid_t *nPidsArray = (pid_t *) env->GetIntArrayElements(jPids, NULL);
std::vector<pid_t> nPids(nPidsArray, nPidsArray + env->GetArrayLength(jPids));
status_t status = AudioSystem::setAudioHalPids(nPids);
env->ReleaseIntArrayElements(jPids, nPidsArray, 0);
@@ -2270,6 +2270,48 @@ android_media_AudioSystem_isCallScreeningModeSupported(JNIEnv *env, jobject thiz
return AudioSystem::isCallScreenModeSupported();
}
+static jint
+android_media_AudioSystem_setPreferredDeviceForStrategy(JNIEnv *env, jobject thiz,
+ jint strategy, jint deviceType, jstring deviceAddress) {
+
+ const char *c_address = env->GetStringUTFChars(deviceAddress, NULL);
+ int status = check_AudioSystem_Command(
+ AudioSystem::setPreferredDeviceForStrategy((product_strategy_t) strategy,
+ AudioDeviceTypeAddr(deviceType, c_address)));
+ env->ReleaseStringUTFChars(deviceAddress, c_address);
+ return (jint) status;
+}
+
+static jint
+android_media_AudioSystem_removePreferredDeviceForStrategy(JNIEnv *env, jobject thiz, jint strategy)
+{
+ return (jint) check_AudioSystem_Command(
+ AudioSystem::removePreferredDeviceForStrategy((product_strategy_t) strategy));
+}
+
+static jint
+android_media_AudioSystem_getPreferredDeviceForStrategy(JNIEnv *env, jobject thiz,
+ jint strategy, jobjectArray jDeviceArray)
+{
+ if (jDeviceArray == nullptr || env->GetArrayLength(jDeviceArray) != 1) {
+ ALOGE("%s invalid array to store AudioDeviceAddress", __FUNCTION__);
+ return (jint)AUDIO_JAVA_BAD_VALUE;
+ }
+
+ AudioDeviceTypeAddr elDevice;
+ status_t status = check_AudioSystem_Command(
+ AudioSystem::getPreferredDeviceForStrategy((product_strategy_t) strategy, elDevice));
+ if (status != NO_ERROR) {
+ return (jint) status;
+ }
+ jobject jAudioDeviceAddress = NULL;
+ jint jStatus = createAudioDeviceAddressFromNative(env, &jAudioDeviceAddress, &elDevice);
+ if (jStatus == AUDIO_JAVA_SUCCESS) {
+ env->SetObjectArrayElement(jDeviceArray, 0, jAudioDeviceAddress);
+ }
+ return jStatus;
+}
+
// ----------------------------------------------------------------------------
static const JNINativeMethod gMethods[] = {
@@ -2350,6 +2392,9 @@ static const JNINativeMethod gMethods[] = {
{"setRttEnabled", "(Z)I", (void *)android_media_AudioSystem_setRttEnabled},
{"setAudioHalPids", "([I)I", (void *)android_media_AudioSystem_setAudioHalPids},
{"isCallScreeningModeSupported", "()Z", (void *)android_media_AudioSystem_isCallScreeningModeSupported},
+ {"setPreferredDeviceForStrategy", "(IILjava/lang/String;)I", (void *)android_media_AudioSystem_setPreferredDeviceForStrategy},
+ {"removePreferredDeviceForStrategy", "(I)I", (void *)android_media_AudioSystem_removePreferredDeviceForStrategy},
+ {"getPreferredDeviceForStrategy", "(I[Landroid/media/AudioDeviceAddress;)I", (void *)android_media_AudioSystem_getPreferredDeviceForStrategy},
};
static const JNINativeMethod gEventHandlerMethods[] = {
diff --git a/core/jni/android_media_AudioTrack.cpp b/core/jni/android_media_AudioTrack.cpp
index c5049ecd3784..c979133d2493 100644
--- a/core/jni/android_media_AudioTrack.cpp
+++ b/core/jni/android_media_AudioTrack.cpp
@@ -1032,7 +1032,7 @@ android_media_AudioTrack_native_getMetrics(JNIEnv *env, jobject thiz)
}
// get what we have for the metrics from the track
- MediaAnalyticsItem *item = NULL;
+ mediametrics::Item *item = NULL;
status_t err = lpTrack->getMetrics(item);
if (err != OK) {
diff --git a/core/jni/android_os_Debug.cpp b/core/jni/android_os_Debug.cpp
index d62d2d967d85..e21eefb196c9 100644
--- a/core/jni/android_os_Debug.cpp
+++ b/core/jni/android_os_Debug.cpp
@@ -43,6 +43,7 @@
#include <nativehelper/JNIHelp.h>
#include <nativehelper/ScopedUtfChars.h>
#include "jni.h"
+#include <dmabufinfo/dmabufinfo.h>
#include <meminfo/procmeminfo.h>
#include <meminfo/sysmeminfo.h>
#include <memtrack/memtrack.h>
@@ -560,6 +561,7 @@ enum {
MEMINFO_VMALLOC_USED,
MEMINFO_PAGE_TABLES,
MEMINFO_KERNEL_STACK,
+ MEMINFO_KERNEL_RECLAIMABLE,
MEMINFO_COUNT
};
@@ -780,6 +782,59 @@ static jlong android_os_Debug_getFreeZramKb(JNIEnv* env, jobject clazz) {
return zramFreeKb;
}
+static jlong android_os_Debug_getIonHeapsSizeKb(JNIEnv* env, jobject clazz) {
+ jlong heapsSizeKb = 0;
+ uint64_t size;
+
+ if (meminfo::ReadIonHeapsSizeKb(&size)) {
+ heapsSizeKb = size;
+ }
+
+ return heapsSizeKb;
+}
+
+static jlong android_os_Debug_getIonPoolsSizeKb(JNIEnv* env, jobject clazz) {
+ jlong poolsSizeKb = 0;
+ uint64_t size;
+
+ if (meminfo::ReadIonPoolsSizeKb(&size)) {
+ poolsSizeKb = size;
+ }
+
+ return poolsSizeKb;
+}
+
+static jlong android_os_Debug_getIonMappedSizeKb(JNIEnv* env, jobject clazz) {
+ jlong ionPss = 0;
+ std::vector<dmabufinfo::DmaBuffer> dmabufs;
+
+ std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir("/proc"), closedir);
+ if (!dir) {
+ LOG(ERROR) << "Failed to open /proc directory";
+ return false;
+ }
+
+ struct dirent* dent;
+ while ((dent = readdir(dir.get()))) {
+ if (dent->d_type != DT_DIR) continue;
+
+ int pid = atoi(dent->d_name);
+ if (pid == 0) {
+ continue;
+ }
+
+ if (!AppendDmaBufInfo(pid, &dmabufs, false)) {
+ LOG(ERROR) << "Failed to read maps for pid " << pid;
+ }
+ }
+
+ for (dmabufinfo::DmaBuffer buf : dmabufs) {
+ ionPss += buf.size() / 1024;
+ }
+
+ return ionPss;
+}
+
/*
* JNI registration.
*/
@@ -823,6 +878,12 @@ static const JNINativeMethod gMethods[] = {
(void*)android_os_Debug_getUnreachableMemory },
{ "getZramFreeKb", "()J",
(void*)android_os_Debug_getFreeZramKb },
+ { "getIonHeapsSizeKb", "()J",
+ (void*)android_os_Debug_getIonHeapsSizeKb },
+ { "getIonPoolsSizeKb", "()J",
+ (void*)android_os_Debug_getIonPoolsSizeKb },
+ { "getIonMappedSizeKb", "()J",
+ (void*)android_os_Debug_getIonMappedSizeKb },
};
int register_android_os_Debug(JNIEnv *env)
diff --git a/core/jni/android_os_Trace.cpp b/core/jni/android_os_Trace.cpp
index bd82bd91c55d..0f7611a8ead1 100644
--- a/core/jni/android_os_Trace.cpp
+++ b/core/jni/android_os_Trace.cpp
@@ -50,10 +50,6 @@ inline static void withString(JNIEnv* env, jstring jstr, F callback) {
callback(buffer.data());
}
-static jlong android_os_Trace_nativeGetEnabledTags(JNIEnv*, jclass) {
- return atrace_get_enabled_tags();
-}
-
static void android_os_Trace_nativeTraceCounter(JNIEnv* env, jclass,
jlong tag, jstring nameStr, jlong value) {
withString(env, nameStr, [tag, value](char* str) {
@@ -96,9 +92,6 @@ static void android_os_Trace_nativeSetTracingEnabled(JNIEnv*, jclass, jboolean e
static const JNINativeMethod gTraceMethods[] = {
/* name, signature, funcPtr */
- { "nativeGetEnabledTags",
- "()J",
- (void*)android_os_Trace_nativeGetEnabledTags },
{ "nativeSetAppTracingAllowed",
"(Z)V",
(void*)android_os_Trace_nativeSetAppTracingAllowed },
@@ -123,6 +116,11 @@ static const JNINativeMethod gTraceMethods[] = {
{ "nativeAsyncTraceEnd",
"(JLjava/lang/String;I)V",
(void*)android_os_Trace_nativeAsyncTraceEnd },
+
+ // ----------- @CriticalNative ----------------
+ { "nativeGetEnabledTags",
+ "()J",
+ (void*)atrace_get_enabled_tags },
};
int register_android_os_Trace(JNIEnv* env) {
diff --git a/core/jni/android_service_DataLoaderService.cpp b/core/jni/android_service_DataLoaderService.cpp
new file mode 100644
index 000000000000..381b386d7f62
--- /dev/null
+++ b/core/jni/android_service_DataLoaderService.cpp
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#define LOG_TAG "dataloader-jni"
+
+#include "core_jni_helpers.h"
+#include "dataloader_ndk.h"
+
+namespace android {
+namespace {
+
+static jboolean nativeCreateDataLoader(JNIEnv* env,
+ jobject thiz,
+ jint storageId,
+ jobject control,
+ jobject params,
+ jobject callback) {
+ return DataLoaderService_OnCreate(env, thiz,
+ storageId, control, params, callback);
+}
+
+static jboolean nativeStartDataLoader(JNIEnv* env,
+ jobject thiz,
+ jint storageId) {
+ return DataLoaderService_OnStart(storageId);
+}
+
+static jboolean nativeStopDataLoader(JNIEnv* env,
+ jobject thiz,
+ jint storageId) {
+ return DataLoaderService_OnStop(storageId);
+}
+
+static jboolean nativeDestroyDataLoader(JNIEnv* env,
+ jobject thiz,
+ jint storageId) {
+ return DataLoaderService_OnDestroy(storageId);
+}
+
+
+static jboolean nativeReportStatus(JNIEnv* env,
+ jobject clazz,
+ jlong self,
+ jint status) {
+ auto listener = (DataLoaderStatusListenerPtr)self;
+ return DataLoader_StatusListener_reportStatus(listener,
+ (DataLoaderStatus)status);
+}
+
+static const JNINativeMethod dlc_method_table[] = {
+ {"nativeCreateDataLoader",
+ "(ILandroid/content/pm/FileSystemControlParcel;"
+ "Landroid/content/pm/DataLoaderParamsParcel;"
+ "Landroid/content/pm/IDataLoaderStatusListener;)Z",
+ (void*)nativeCreateDataLoader},
+ {"nativeStartDataLoader", "(I)Z", (void*)nativeStartDataLoader},
+ {"nativeStopDataLoader", "(I)Z", (void*)nativeStopDataLoader},
+ {"nativeDestroyDataLoader", "(I)Z", (void*)nativeDestroyDataLoader},
+ {"nativeReportStatus", "(JI)Z", (void*)nativeReportStatus},
+};
+
+} // namespace
+
+int register_android_service_DataLoaderService(JNIEnv* env) {
+ return jniRegisterNativeMethods(env,
+ "android/service/dataloader/DataLoaderService",
+ dlc_method_table, NELEM(dlc_method_table));
+}
+
+} // namespace android
diff --git a/core/jni/android_view_FrameMetricsObserver.cpp b/core/jni/android_view_FrameMetricsObserver.cpp
deleted file mode 100644
index febcb55bd0cd..000000000000
--- a/core/jni/android_view_FrameMetricsObserver.cpp
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Copyright (C) 2019 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.
- */
-
-#include "android_view_FrameMetricsObserver.h"
-
-namespace android {
-
-struct {
- jfieldID frameMetrics;
- jfieldID timingDataBuffer;
- jfieldID messageQueue;
- jmethodID callback;
-} gFrameMetricsObserverClassInfo;
-
-static JNIEnv* getenv(JavaVM* vm) {
- JNIEnv* env;
- if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
- LOG_ALWAYS_FATAL("Failed to get JNIEnv for JavaVM: %p", vm);
- }
- return env;
-}
-
-static jlongArray get_metrics_buffer(JNIEnv* env, jobject observer) {
- jobject frameMetrics = env->GetObjectField(
- observer, gFrameMetricsObserverClassInfo.frameMetrics);
- LOG_ALWAYS_FATAL_IF(frameMetrics == nullptr, "unable to retrieve data sink object");
- jobject buffer = env->GetObjectField(
- frameMetrics, gFrameMetricsObserverClassInfo.timingDataBuffer);
- LOG_ALWAYS_FATAL_IF(buffer == nullptr, "unable to retrieve data sink buffer");
- return reinterpret_cast<jlongArray>(buffer);
-}
-
-class NotifyHandler : public MessageHandler {
-public:
- NotifyHandler(JavaVM* vm, FrameMetricsObserverProxy* observer) : mVm(vm), mObserver(observer) {}
-
- virtual void handleMessage(const Message& message);
-
-private:
- JavaVM* const mVm;
- FrameMetricsObserverProxy* const mObserver;
-};
-
-void NotifyHandler::handleMessage(const Message& message) {
- JNIEnv* env = getenv(mVm);
-
- jobject target = env->NewLocalRef(mObserver->getObserverReference());
-
- if (target != nullptr) {
- jlongArray javaBuffer = get_metrics_buffer(env, target);
- int dropCount = 0;
- while (mObserver->getNextBuffer(env, javaBuffer, &dropCount)) {
- env->CallVoidMethod(target, gFrameMetricsObserverClassInfo.callback, dropCount);
- }
- env->DeleteLocalRef(target);
- }
-
- mObserver->decStrong(nullptr);
-}
-
-FrameMetricsObserverProxy::FrameMetricsObserverProxy(JavaVM *vm, jobject observer) : mVm(vm) {
- JNIEnv* env = getenv(mVm);
-
- mObserverWeak = env->NewWeakGlobalRef(observer);
- LOG_ALWAYS_FATAL_IF(mObserverWeak == nullptr,
- "unable to create frame stats observer reference");
-
- jlongArray buffer = get_metrics_buffer(env, observer);
- jsize bufferSize = env->GetArrayLength(reinterpret_cast<jarray>(buffer));
- LOG_ALWAYS_FATAL_IF(bufferSize != kBufferSize,
- "Mismatched Java/Native FrameMetrics data format.");
-
- jobject messageQueueLocal = env->GetObjectField(
- observer, gFrameMetricsObserverClassInfo.messageQueue);
- mMessageQueue = android_os_MessageQueue_getMessageQueue(env, messageQueueLocal);
- LOG_ALWAYS_FATAL_IF(mMessageQueue == nullptr, "message queue not available");
-
- mMessageHandler = new NotifyHandler(mVm, this);
- LOG_ALWAYS_FATAL_IF(mMessageHandler == nullptr,
- "OOM: unable to allocate NotifyHandler");
-}
-
-FrameMetricsObserverProxy::~FrameMetricsObserverProxy() {
- JNIEnv* env = getenv(mVm);
- env->DeleteWeakGlobalRef(mObserverWeak);
-}
-
-bool FrameMetricsObserverProxy::getNextBuffer(JNIEnv* env, jlongArray sink, int* dropCount) {
- FrameMetricsNotification& elem = mRingBuffer[mNextInQueue];
-
- if (elem.hasData.load()) {
- env->SetLongArrayRegion(sink, 0, kBufferSize, elem.buffer);
- *dropCount = elem.dropCount;
- mNextInQueue = (mNextInQueue + 1) % kRingSize;
- elem.hasData = false;
- return true;
- }
-
- return false;
-}
-
-void FrameMetricsObserverProxy::notify(const int64_t* stats) {
- FrameMetricsNotification& elem = mRingBuffer[mNextFree];
-
- if (!elem.hasData.load()) {
- memcpy(elem.buffer, stats, kBufferSize * sizeof(stats[0]));
-
- elem.dropCount = mDroppedReports;
- mDroppedReports = 0;
-
- incStrong(nullptr);
- mNextFree = (mNextFree + 1) % kRingSize;
- elem.hasData = true;
-
- mMessageQueue->getLooper()->sendMessage(mMessageHandler, mMessage);
- } else {
- mDroppedReports++;
- }
-}
-
-int register_android_view_FrameMetricsObserver(JNIEnv* env) {
- jclass observerClass = FindClassOrDie(env, "android/view/FrameMetricsObserver");
- gFrameMetricsObserverClassInfo.frameMetrics = GetFieldIDOrDie(
- env, observerClass, "mFrameMetrics", "Landroid/view/FrameMetrics;");
- gFrameMetricsObserverClassInfo.messageQueue = GetFieldIDOrDie(
- env, observerClass, "mMessageQueue", "Landroid/os/MessageQueue;");
- gFrameMetricsObserverClassInfo.callback = GetMethodIDOrDie(
- env, observerClass, "notifyDataAvailable", "(I)V");
-
- jclass metricsClass = FindClassOrDie(env, "android/view/FrameMetrics");
- gFrameMetricsObserverClassInfo.timingDataBuffer = GetFieldIDOrDie(
- env, metricsClass, "mTimingData", "[J");
- return JNI_OK;
-}
-
-} // namespace android \ No newline at end of file
diff --git a/core/jni/android_view_FrameMetricsObserver.h b/core/jni/android_view_FrameMetricsObserver.h
deleted file mode 100644
index 647f51c4492d..000000000000
--- a/core/jni/android_view_FrameMetricsObserver.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2019 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.
- */
-
-#include "jni.h"
-#include "core_jni_helpers.h"
-
-#include "android_os_MessageQueue.h"
-
-#include <FrameInfo.h>
-#include <FrameMetricsObserver.h>
-
-namespace android {
-
-/*
- * Implements JNI layer for hwui frame metrics reporting.
- */
-class FrameMetricsObserverProxy : public uirenderer::FrameMetricsObserver {
-public:
- FrameMetricsObserverProxy(JavaVM *vm, jobject observer);
-
- ~FrameMetricsObserverProxy();
-
- jweak getObserverReference() {
- return mObserverWeak;
- }
-
- bool getNextBuffer(JNIEnv* env, jlongArray sink, int* dropCount);
-
- virtual void notify(const int64_t* stats);
-
-private:
- static const int kBufferSize = static_cast<int>(uirenderer::FrameInfoIndex::NumIndexes);
- static constexpr int kRingSize = 3;
-
- class FrameMetricsNotification {
- public:
- FrameMetricsNotification() : hasData(false) {}
-
- std::atomic_bool hasData;
- int64_t buffer[kBufferSize];
- int dropCount = 0;
- };
-
- JavaVM* const mVm;
- jweak mObserverWeak;
-
- sp<MessageQueue> mMessageQueue;
- sp<MessageHandler> mMessageHandler;
- Message mMessage;
-
- int mNextFree = 0;
- int mNextInQueue = 0;
- FrameMetricsNotification mRingBuffer[kRingSize];
-
- int mDroppedReports = 0;
-};
-
-} // namespace android
diff --git a/core/jni/android_view_ThreadedRenderer.cpp b/core/jni/android_view_ThreadedRenderer.cpp
index 170e467a72cd..69ca17c08257 100644
--- a/core/jni/android_view_ThreadedRenderer.cpp
+++ b/core/jni/android_view_ThreadedRenderer.cpp
@@ -30,7 +30,7 @@
#include <gui/BufferQueue.h>
#include <gui/Surface.h>
-#include "android_view_FrameMetricsObserver.h"
+#include "android_graphics_HardwareRendererObserver.h"
#include <private/EGL/cache.h>
@@ -580,28 +580,21 @@ static void android_view_ThreadedRenderer_preload(JNIEnv*, jclass) {
}
// ----------------------------------------------------------------------------
-// FrameMetricsObserver
+// HardwareRendererObserver
// ----------------------------------------------------------------------------
-static jlong android_view_ThreadedRenderer_addFrameMetricsObserver(JNIEnv* env,
- jclass clazz, jlong proxyPtr, jobject fso) {
- JavaVM* vm = nullptr;
- if (env->GetJavaVM(&vm) != JNI_OK) {
- LOG_ALWAYS_FATAL("Unable to get Java VM");
- return 0;
- }
-
+static void android_view_ThreadedRenderer_addObserver(JNIEnv* env, jclass clazz,
+ jlong proxyPtr, jlong observerPtr) {
+ HardwareRendererObserver* observer = reinterpret_cast<HardwareRendererObserver*>(observerPtr);
renderthread::RenderProxy* renderProxy =
reinterpret_cast<renderthread::RenderProxy*>(proxyPtr);
- FrameMetricsObserver* observer = new FrameMetricsObserverProxy(vm, fso);
renderProxy->addFrameMetricsObserver(observer);
- return reinterpret_cast<jlong>(observer);
}
-static void android_view_ThreadedRenderer_removeFrameMetricsObserver(JNIEnv* env, jclass clazz,
+static void android_view_ThreadedRenderer_removeObserver(JNIEnv* env, jclass clazz,
jlong proxyPtr, jlong observerPtr) {
- FrameMetricsObserver* observer = reinterpret_cast<FrameMetricsObserver*>(observerPtr);
+ HardwareRendererObserver* observer = reinterpret_cast<HardwareRendererObserver*>(observerPtr);
renderthread::RenderProxy* renderProxy =
reinterpret_cast<renderthread::RenderProxy*>(proxyPtr);
@@ -675,12 +668,8 @@ static const JNINativeMethod gMethods[] = {
(void*)android_view_ThreadedRenderer_setFrameCallback},
{ "nSetFrameCompleteCallback", "(JLandroid/graphics/HardwareRenderer$FrameCompleteCallback;)V",
(void*)android_view_ThreadedRenderer_setFrameCompleteCallback },
- { "nAddFrameMetricsObserver",
- "(JLandroid/view/FrameMetricsObserver;)J",
- (void*)android_view_ThreadedRenderer_addFrameMetricsObserver },
- { "nRemoveFrameMetricsObserver",
- "(JJ)V",
- (void*)android_view_ThreadedRenderer_removeFrameMetricsObserver },
+ { "nAddObserver", "(JJ)V", (void*)android_view_ThreadedRenderer_addObserver },
+ { "nRemoveObserver", "(JJ)V", (void*)android_view_ThreadedRenderer_removeObserver },
{ "nCopySurfaceInto", "(Landroid/view/Surface;IIIIJ)I",
(void*)android_view_ThreadedRenderer_copySurfaceInto },
{ "nCreateHardwareBitmap", "(JII)Landroid/graphics/Bitmap;",
diff --git a/core/jni/com_android_internal_os_Zygote.cpp b/core/jni/com_android_internal_os_Zygote.cpp
index f28c4221c637..df5b02c22a2d 100644
--- a/core/jni/com_android_internal_os_Zygote.cpp
+++ b/core/jni/com_android_internal_os_Zygote.cpp
@@ -31,6 +31,8 @@
// sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc
#include <sys/mount.h>
#include <linux/fs.h>
+#include <sys/types.h>
+#include <dirent.h>
#include <array>
#include <atomic>
@@ -40,6 +42,7 @@
#include <sstream>
#include <string>
#include <string_view>
+#include <unordered_set>
#include <android/fdsan.h>
#include <arpa/inet.h>
@@ -51,6 +54,7 @@
#include <mntent.h>
#include <paths.h>
#include <signal.h>
+#include <stdio.h>
#include <stdlib.h>
#include <sys/capability.h>
#include <sys/cdefs.h>
@@ -74,6 +78,7 @@
#include <android-base/strings.h>
#include <android-base/unique_fd.h>
#include <bionic/malloc.h>
+#include <bionic/page.h>
#include <cutils/fs.h>
#include <cutils/multiuser.h>
#include <cutils/sockets.h>
@@ -158,6 +163,17 @@ static std::atomic_uint32_t gUsapPoolCount = 0;
*/
static int gUsapPoolEventFD = -1;
+static constexpr int DEFAULT_DATA_DIR_PERMISSION = 0751;
+
+/**
+ * Property to control if app data isolation is enabled.
+ */
+static const std::string ANDROID_APP_DATA_ISOLATION_ENABLED_PROPERTY =
+ "persist.zygote.app_data_isolation";
+
+static constexpr const uint64_t UPPER_HALF_WORD_MASK = 0xFFFF'FFFF'0000'0000;
+static constexpr const uint64_t LOWER_HALF_WORD_MASK = 0x0000'0000'FFFF'FFFF;
+
/**
* The maximum value that the gUSAPPoolSizeMax variable may take. This value
* is a mirror of ZygoteServer.USAP_POOL_SIZE_MAX_LIMIT
@@ -662,7 +678,7 @@ static int UnmountTree(const char* path) {
return 0;
}
-static void CreateDir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid,
+static void PrepareDir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid,
fail_fn_t fail_fn) {
if (fs_prepare_dir(dir.c_str(), mode, uid, gid) != 0) {
fail_fn(CREATE_ERROR("fs_prepare_dir failed on %s: %s",
@@ -670,6 +686,16 @@ static void CreateDir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid,
}
}
+static void PrepareDirIfNotPresent(const std::string& dir, mode_t mode, uid_t uid, gid_t gid,
+ fail_fn_t fail_fn) {
+ struct stat sb;
+ if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) != -1) {
+ // Directory exists already
+ return;
+ }
+ PrepareDir(dir, mode, uid, gid, fail_fn);
+}
+
static void BindMount(const std::string& source_dir, const std::string& target_dir,
fail_fn_t fail_fn) {
if (TEMP_FAILURE_RETRY(mount(source_dir.c_str(), target_dir.c_str(), nullptr,
@@ -679,6 +705,15 @@ static void BindMount(const std::string& source_dir, const std::string& target_d
}
}
+static void MountAppDataTmpFs(const std::string& target_dir,
+ fail_fn_t fail_fn) {
+ if (TEMP_FAILURE_RETRY(mount("tmpfs", target_dir.c_str(), "tmpfs",
+ MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
+ fail_fn(CREATE_ERROR("Failed to mount tmpfs to %s: %s",
+ target_dir.c_str(), strerror(errno)));
+ }
+}
+
// Create a private mount namespace and bind mount appropriate emulated
// storage for the given user.
static void MountEmulatedStorage(uid_t uid, jint mount_mode,
@@ -711,11 +746,19 @@ static void MountEmulatedStorage(uid_t uid, jint mount_mode,
const std::string pass_through_source = StringPrintf("/mnt/pass_through/%d", user_id);
bool isFuse = GetBoolProperty(kPropFuse, false);
- CreateDir(user_source, 0751, AID_ROOT, AID_ROOT, fail_fn);
+ PrepareDir(user_source, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT, fail_fn);
if (isFuse) {
- BindMount(mount_mode == MOUNT_EXTERNAL_PASS_THROUGH ? pass_through_source : user_source,
- "/storage", fail_fn);
+ if (mount_mode == MOUNT_EXTERNAL_PASS_THROUGH || mount_mode ==
+ MOUNT_EXTERNAL_INSTALLER || mount_mode == MOUNT_EXTERNAL_FULL) {
+ // For now, MediaProvider, installers and "full" get the pass_through mount
+ // view, which is currently identical to the sdcardfs write view.
+ //
+ // TODO(b/146189163): scope down MOUNT_EXTERNAL_INSTALLER
+ BindMount(pass_through_source, "/storage", fail_fn);
+ } else {
+ BindMount(user_source, "/storage", fail_fn);
+ }
} else {
const std::string& storage_source = ExternalStorageViews[mount_mode];
BindMount(storage_source, "/storage", fail_fn);
@@ -1007,6 +1050,231 @@ static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
return pid;
}
+// Create an app data directory over tmpfs overlayed CE / DE storage, and bind mount it
+// from the actual app data directory in data mirror.
+static void createAndMountAppData(std::string_view package_name,
+ std::string_view mirror_pkg_dir_name, std::string_view mirror_data_path,
+ std::string_view actual_data_path, fail_fn_t fail_fn) {
+
+ char mirrorAppDataPath[PATH_MAX];
+ char actualAppDataPath[PATH_MAX];
+ snprintf(mirrorAppDataPath, PATH_MAX, "%s/%s", mirror_data_path.data(),
+ mirror_pkg_dir_name.data());
+ snprintf(actualAppDataPath, PATH_MAX, "%s/%s", actual_data_path.data(), package_name.data());
+
+ PrepareDir(actualAppDataPath, 0700, AID_ROOT, AID_ROOT, fail_fn);
+
+ // Bind mount from original app data directory in mirror.
+ BindMount(mirrorAppDataPath, actualAppDataPath, fail_fn);
+}
+
+// Get the directory name stored in /data/data. If device is unlocked it should be the same as
+// package name, otherwise it will be an encrypted name but with same inode number.
+static std::string getAppDataDirName(std::string_view parent_path, std::string_view package_name,
+ long long ce_data_inode, fail_fn_t fail_fn) {
+ // Check if directory exists
+ char tmpPath[PATH_MAX];
+ snprintf(tmpPath, PATH_MAX, "%s/%s", parent_path.data(), package_name.data());
+ struct stat s;
+ int err = stat(tmpPath, &s);
+ if (err == 0) {
+ // Directory exists, so return the directory name
+ return package_name.data();
+ } else {
+ if (errno != ENOENT) {
+ fail_fn(CREATE_ERROR("Unexpected error in getAppDataDirName: %s", strerror(errno)));
+ return nullptr;
+ }
+ // Directory doesn't exist, try to search the name from inode
+ DIR* dir = opendir(parent_path.data());
+ if (dir == nullptr) {
+ fail_fn(CREATE_ERROR("Failed to opendir %s", parent_path.data()));
+ }
+ struct dirent* ent;
+ while ((ent = readdir(dir))) {
+ if (ent->d_ino == ce_data_inode) {
+ closedir(dir);
+ return ent->d_name;
+ }
+ }
+ closedir(dir);
+
+ // Fallback due to b/145989852, ce_data_inode stored in package manager may be corrupted
+ // if ino_t is 32 bits.
+ ino_t fixed_ce_data_inode = 0;
+ if ((ce_data_inode & UPPER_HALF_WORD_MASK) == UPPER_HALF_WORD_MASK) {
+ fixed_ce_data_inode = ce_data_inode & LOWER_HALF_WORD_MASK;
+ } else if ((ce_data_inode & LOWER_HALF_WORD_MASK) == LOWER_HALF_WORD_MASK) {
+ fixed_ce_data_inode = ((ce_data_inode >> 32) & LOWER_HALF_WORD_MASK);
+ }
+ if (fixed_ce_data_inode != 0) {
+ dir = opendir(parent_path.data());
+ if (dir == nullptr) {
+ fail_fn(CREATE_ERROR("Failed to opendir %s", parent_path.data()));
+ }
+ while ((ent = readdir(dir))) {
+ if (ent->d_ino == fixed_ce_data_inode) {
+ long long d_ino = ent->d_ino;
+ ALOGW("Fallback success inode %lld -> %lld", ce_data_inode, d_ino);
+ closedir(dir);
+ return ent->d_name;
+ }
+ }
+ closedir(dir);
+ }
+ // Fallback done
+
+ fail_fn(CREATE_ERROR("Unable to find %s:%lld in %s", package_name.data(),
+ ce_data_inode, parent_path.data()));
+ return nullptr;
+ }
+}
+
+// Isolate app's data directory, by mounting a tmpfs on CE DE storage,
+// and create and bind mount app data in related_packages.
+static void isolateAppDataPerPackage(int userId, std::string_view package_name,
+ std::string_view volume_uuid, long long ce_data_inode, std::string_view actualCePath,
+ std::string_view actualDePath, fail_fn_t fail_fn) {
+
+ char mirrorCePath[PATH_MAX];
+ char mirrorDePath[PATH_MAX];
+ char mirrorCeParent[PATH_MAX];
+ snprintf(mirrorCeParent, PATH_MAX, "/data_mirror/data_ce/%s", volume_uuid.data());
+ snprintf(mirrorCePath, PATH_MAX, "%s/%d", mirrorCeParent, userId);
+ snprintf(mirrorDePath, PATH_MAX, "/data_mirror/data_de/%s/%d", volume_uuid.data(), userId);
+
+ createAndMountAppData(package_name, package_name, mirrorDePath, actualDePath, fail_fn);
+
+ std::string ce_data_path = getAppDataDirName(mirrorCePath, package_name, ce_data_inode, fail_fn);
+ createAndMountAppData(package_name, ce_data_path, mirrorCePath, actualCePath, fail_fn);
+}
+
+/**
+ * Make other apps data directory not visible in CE, DE storage.
+ *
+ * Apps without app data isolation can detect if another app is installed on system,
+ * by "touching" other apps data directory like /data/data/com.whatsapp, if it returns
+ * "Permission denied" it means apps installed, otherwise it returns "File not found".
+ * Traditional file permissions or SELinux can only block accessing those directories but
+ * can't fix fingerprinting like this.
+ * We fix it by "overlaying" data directory, and only relevant app data packages exists
+ * in data directories.
+ *
+ * Steps:
+ * 1). Collect a list of all related apps (apps with same uid and whitelisted apps) data info
+ * (package name, data stored volume uuid, and inode number of its CE data directory)
+ * 2). Mount tmpfs on /data/data, /data/user(_de) and /mnt/expand, so apps no longer
+ * able to access apps data directly.
+ * 3). For each related app, create its app data directory and bind mount the actual content
+ * from apps data mirror directory. This works on both CE and DE storage, as DE storage
+ * is always available even storage is FBE locked, while we use inode number to find
+ * the encrypted DE directory in mirror so we can still bind mount it successfully.
+ *
+ * Example:
+ * 0). Assuming com.android.foo CE data is stored in /data/data and no shared uid
+ * 1). Mount a tmpfs on /data/data, /data/user, /data/user_de, /mnt/expand
+ * List = ["com.android.foo", "null" (volume uuid "null"=default),
+ * 123456 (inode number)]
+ * 2). On DE storage, we create a directory /data/user_de/0/com.com.android.foo, and bind
+ * mount (in the app's mount namespace) it from /data_mirror/data_de/0/com.android.foo.
+ * 3). We do similar for CE storage. But in direct boot mode, as /data_mirror/data_ce/0/ is
+ * encrypted, we can't find a directory with name com.android.foo on it, so we will
+ * use the inode number to find the right directory instead, which that directory content will
+ * be decrypted after storage is decrypted.
+ *
+ */
+static void isolateAppData(JNIEnv* env, jobjectArray pkg_data_info_list,
+ uid_t uid, const char* process_name, jstring managed_nice_name,
+ fail_fn_t fail_fn) {
+
+ const userid_t userId = multiuser_get_user_id(uid);
+
+ auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
+
+ int size = (pkg_data_info_list != nullptr) ? env->GetArrayLength(pkg_data_info_list) : 0;
+ // Size should be a multiple of 3, as it contains list of <package_name, volume_uuid, inode>
+ if ((size % 3) != 0) {
+ fail_fn(CREATE_ERROR("Wrong pkg_inode_list size %d", size));
+ }
+
+ // Mount tmpfs on all possible data directories, so app no longer see the original apps data.
+ char internalCePath[PATH_MAX];
+ char internalLegacyCePath[PATH_MAX];
+ char internalDePath[PATH_MAX];
+ char externalPrivateMountPath[PATH_MAX];
+
+ snprintf(internalCePath, PATH_MAX, "/data/user");
+ snprintf(internalLegacyCePath, PATH_MAX, "/data/data");
+ snprintf(internalDePath, PATH_MAX, "/data/user_de");
+ snprintf(externalPrivateMountPath, PATH_MAX, "/mnt/expand");
+
+ MountAppDataTmpFs(internalLegacyCePath, fail_fn);
+ MountAppDataTmpFs(internalCePath, fail_fn);
+ MountAppDataTmpFs(internalDePath, fail_fn);
+ MountAppDataTmpFs(externalPrivateMountPath, fail_fn);
+
+ for (int i = 0; i < size; i += 3) {
+ jstring package_str = (jstring) (env->GetObjectArrayElement(pkg_data_info_list, i));
+ std::string packageName = extract_fn(package_str).value();
+
+ jstring vol_str = (jstring) (env->GetObjectArrayElement(pkg_data_info_list, i + 1));
+ std::string volUuid = extract_fn(vol_str).value();
+
+ jstring inode_str = (jstring) (env->GetObjectArrayElement(pkg_data_info_list, i + 2));
+ std::string inode = extract_fn(inode_str).value();
+ std::string::size_type sz;
+ long long ceDataInode = std::stoll(inode, &sz);
+
+ std::string actualCePath, actualDePath;
+ if (volUuid.compare("null") != 0) {
+ // Volume that is stored in /mnt/expand
+ char volPath[PATH_MAX];
+ char volCePath[PATH_MAX];
+ char volDePath[PATH_MAX];
+ char volCeUserPath[PATH_MAX];
+ char volDeUserPath[PATH_MAX];
+
+ snprintf(volPath, PATH_MAX, "/mnt/expand/%s", volUuid.c_str());
+ snprintf(volCePath, PATH_MAX, "%s/user", volPath);
+ snprintf(volDePath, PATH_MAX, "%s/user_de", volPath);
+ snprintf(volCeUserPath, PATH_MAX, "%s/%d", volCePath, userId);
+ snprintf(volDeUserPath, PATH_MAX, "%s/%d", volDePath, userId);
+
+ PrepareDirIfNotPresent(volPath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT, fail_fn);
+ PrepareDirIfNotPresent(volCePath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT, fail_fn);
+ PrepareDirIfNotPresent(volDePath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT, fail_fn);
+ PrepareDirIfNotPresent(volCeUserPath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT,
+ fail_fn);
+ PrepareDirIfNotPresent(volDeUserPath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT,
+ fail_fn);
+
+ actualCePath = volCeUserPath;
+ actualDePath = volDeUserPath;
+ } else {
+ // Internal volume that stored in /data
+ char internalCeUserPath[PATH_MAX];
+ char internalDeUserPath[PATH_MAX];
+ snprintf(internalCeUserPath, PATH_MAX, "/data/user/%d", userId);
+ snprintf(internalDeUserPath, PATH_MAX, "/data/user_de/%d", userId);
+ // If it's user 0, create a symlink /data/user/0 -> /data/data,
+ // otherwise create /data/user/$USER
+ if (userId == 0) {
+ symlink(internalLegacyCePath, internalCeUserPath);
+ actualCePath = internalLegacyCePath;
+ } else {
+ PrepareDirIfNotPresent(internalCeUserPath, DEFAULT_DATA_DIR_PERMISSION,
+ AID_ROOT, AID_ROOT, fail_fn);
+ actualCePath = internalCeUserPath;
+ }
+ PrepareDirIfNotPresent(internalDeUserPath, DEFAULT_DATA_DIR_PERMISSION,
+ AID_ROOT, AID_ROOT, fail_fn);
+ actualDePath = internalDeUserPath;
+ }
+ isolateAppDataPerPackage(userId, packageName, volUuid, ceDataInode,
+ actualCePath, actualDePath, fail_fn);
+ }
+}
+
// Utility routine to specialize a zygote child process.
static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
jint runtime_flags, jobjectArray rlimits,
@@ -1014,7 +1282,8 @@ static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
jint mount_external, jstring managed_se_info,
jstring managed_nice_name, bool is_system_server,
bool is_child_zygote, jstring managed_instruction_set,
- jstring managed_app_data_dir, bool is_top_app) {
+ jstring managed_app_data_dir, bool is_top_app,
+ jobjectArray pkg_data_info_list) {
const char* process_name = is_system_server ? "system_server" : "zygote";
auto fail_fn = std::bind(ZygoteFailure, env, process_name, managed_nice_name, _1);
auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
@@ -1050,6 +1319,16 @@ static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
MountEmulatedStorage(uid, mount_external, use_native_bridge, fail_fn);
+ // System services, isolated process, webview/app zygote, old target sdk app, should
+ // give a null in same_uid_pkgs and private_volumes so they don't need app data isolation.
+ // Isolated process / webview / app zygote should be gated by SELinux and file permission
+ // so they can't even traverse CE / DE directories.
+ if (pkg_data_info_list != nullptr
+ && GetBoolProperty(ANDROID_APP_DATA_ISOLATION_ENABLED_PROPERTY, false)) {
+ isolateAppData(env, pkg_data_info_list, uid, process_name, managed_nice_name,
+ fail_fn);
+ }
+
// If this zygote isn't root, it won't be able to create a process group,
// since the directory is owned by root.
if (!is_system_server && getuid() == 0) {
@@ -1389,9 +1668,14 @@ static int DisableExecuteOnly(struct dl_phdr_info* info,
void* data [[maybe_unused]]) {
// Search for any execute-only segments and mark them read+execute.
for (int i = 0; i < info->dlpi_phnum; i++) {
- if ((info->dlpi_phdr[i].p_type == PT_LOAD) && (info->dlpi_phdr[i].p_flags == PF_X)) {
- mprotect(reinterpret_cast<void*>(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr),
- info->dlpi_phdr[i].p_memsz, PROT_READ | PROT_EXEC);
+ const auto& phdr = info->dlpi_phdr[i];
+ if ((phdr.p_type == PT_LOAD) && (phdr.p_flags == PF_X)) {
+ auto addr = reinterpret_cast<void*>(info->dlpi_addr + PAGE_START(phdr.p_vaddr));
+ size_t len = PAGE_OFFSET(phdr.p_vaddr) + phdr.p_memsz;
+ if (mprotect(addr, len, PROT_READ | PROT_EXEC) == -1) {
+ ALOGE("mprotect(%p, %zu, PROT_READ | PROT_EXEC) failed: %m", addr, len);
+ return -1;
+ }
}
}
// Return non-zero to exit dl_iterate_phdr.
@@ -1411,7 +1695,8 @@ static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
jint runtime_flags, jobjectArray rlimits,
jint mount_external, jstring se_info, jstring nice_name,
jintArray managed_fds_to_close, jintArray managed_fds_to_ignore, jboolean is_child_zygote,
- jstring instruction_set, jstring app_data_dir, jboolean is_top_app) {
+ jstring instruction_set, jstring app_data_dir, jboolean is_top_app,
+ jobjectArray pkg_data_info_list) {
jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
if (UNLIKELY(managed_fds_to_close == nullptr)) {
@@ -1443,7 +1728,7 @@ static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
capabilities, capabilities,
mount_external, se_info, nice_name, false,
is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
- is_top_app == JNI_TRUE);
+ is_top_app == JNI_TRUE, pkg_data_info_list);
}
return pid;
}
@@ -1467,10 +1752,13 @@ static jint com_android_internal_os_Zygote_nativeForkSystemServer(
fds_to_ignore,
true);
if (pid == 0) {
+ // System server prcoess does not need data isolation so no need to
+ // know pkg_data_info_list.
SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
permitted_capabilities, effective_capabilities,
MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
- false, nullptr, nullptr, /* is_top_app= */ false);
+ false, nullptr, nullptr, /* is_top_app= */ false,
+ /* pkg_data_info_list */ nullptr);
} else if (pid > 0) {
// The zygote process checks whether the child process has died or not.
ALOGI("System server process %d has been created", pid);
@@ -1593,14 +1881,15 @@ static void com_android_internal_os_Zygote_nativeSpecializeAppProcess(
JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
jint runtime_flags, jobjectArray rlimits,
jint mount_external, jstring se_info, jstring nice_name,
- jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app) {
+ jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app,
+ jobjectArray pkg_data_info_list) {
jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
capabilities, capabilities,
mount_external, se_info, nice_name, false,
is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
- is_top_app == JNI_TRUE);
+ is_top_app == JNI_TRUE, pkg_data_info_list);
}
/**
@@ -1761,7 +2050,7 @@ static void com_android_internal_os_Zygote_nativeBoostUsapPriority(JNIEnv* env,
static const JNINativeMethod gMethods[] = {
{ "nativeForkAndSpecialize",
- "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;Z)I",
+ "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;Z[Ljava/lang/String;)I",
(void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
{ "nativeForkSystemServer", "(II[II[[IJJ)I",
(void *) com_android_internal_os_Zygote_nativeForkSystemServer },
@@ -1774,7 +2063,7 @@ static const JNINativeMethod gMethods[] = {
{ "nativeForkUsap", "(II[IZ)I",
(void *) com_android_internal_os_Zygote_nativeForkUsap },
{ "nativeSpecializeAppProcess",
- "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;Z)V",
+ "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;Z[Ljava/lang/String;)V",
(void *) com_android_internal_os_Zygote_nativeSpecializeAppProcess },
{ "nativeInitNativeState", "(Z)V",
(void *) com_android_internal_os_Zygote_nativeInitNativeState },
diff --git a/core/jni/fd_utils.cpp b/core/jni/fd_utils.cpp
index fd6984b830d7..a46ad6d6a35f 100644
--- a/core/jni/fd_utils.cpp
+++ b/core/jni/fd_utils.cpp
@@ -33,10 +33,16 @@
// Static whitelist of open paths that the zygote is allowed to keep open.
static const char* kPathWhitelist[] = {
+ "/apex/com.android.appsearch/javalib/framework-appsearch.jar",
"/apex/com.android.conscrypt/javalib/conscrypt.jar",
"/apex/com.android.ipsec/javalib/ike.jar",
"/apex/com.android.media/javalib/updatable-media.jar",
+ "/apex/com.android.os.statsd/javalib/framework-statsd.jar",
"/apex/com.android.sdkext/javalib/framework-sdkext.jar",
+ "/apex/com.android.telephony/javalib/telephony-common.jar",
+ "/apex/com.android.telephony/javalib/ims-common.jar",
+ "/apex/com.android.wifi/javalib/framework-wifi.jar",
+ "/apex/com.android.tethering/javalib/framework-tethering.jar",
"/dev/null",
"/dev/socket/zygote",
"/dev/socket/zygote_secondary",
diff --git a/core/proto/android/app/settings_enums.proto b/core/proto/android/app/settings_enums.proto
index ab97fdd74b46..039e45881b80 100644
--- a/core/proto/android/app/settings_enums.proto
+++ b/core/proto/android/app/settings_enums.proto
@@ -2467,4 +2467,51 @@ enum PageId {
// CATEGORY: SETTINGS
// OS: R
ACCOUNT_WORK = 1807;
+
+ // OPEN: Settings > Developer Options > Bug report handler
+ // CATEGORY: SETTINGS
+ // OS: R
+ SETTINGS_BUGREPORT_HANDLER = 1808;
+
+ // Panel for adding Wi-Fi networks
+ // CATEGORY: SETTINGS
+ // OS: R
+ PANEL_ADD_WIFI_NETWORKS = 1809;
+
+ // OPEN: Settings > Accessibility > Enable accessibility service > Show tutorial dialog
+ // CATEGORY: SETTINGS
+ // OS: R
+ DIALOG_TOGGLE_SCREEN_ACCESSIBILITY_BUTTON = 1810;
+
+ // OPEN: Settings > Accessibility > Enable accessibility service > Show tutorial dialog in
+ // gesture mode
+ // CATEGORY: SETTINGS
+ // OS: R
+ DIALOG_TOGGLE_SCREEN_GESTURE_NAVIGATION = 1811;
+
+ // OPEN: Settings > Accessibility > Edit shortcut dialog
+ // CATEGORY: SETTINGS
+ // OS: R
+ DIALOG_ACCESSIBILITY_SERVICE_EDIT_SHORTCUT = 1812;
+
+ // OPEN: Settings > Accessibility > Magnification > Edit shortcut dialog
+ // CATEGORY: SETTINGS
+ // OS: R
+ DIALOG_MAGNIFICATION_EDIT_SHORTCUT = 1813;
+
+ // OPEN: Settings > Accessibility > Color correction > Edit shortcut dialog
+ // CATEGORY: SETTINGS
+ // OS: R
+ DIALOG_DALTONIZER_EDIT_SHORTCUT = 1814;
+
+ // OPEN: Settings > Accessibility > Magnification > Settings
+ // CATEGORY: SETTINGS
+ // OS: R
+ ACCESSIBILITY_MAGNIFICATION_SETTINGS = 1815;
+
+ // OPEN: Settings > Accessibility > Magnification > Settings > Magnification area dialog
+ // CATEGORY: SETTINGS
+ // OS: R
+ DIALOG_MAGNIFICATION_CAPABILITY = 1816;
+
}
diff --git a/core/proto/android/providers/settings/global.proto b/core/proto/android/providers/settings/global.proto
index 31c19ca1be70..a98d7db11913 100644
--- a/core/proto/android/providers/settings/global.proto
+++ b/core/proto/android/providers/settings/global.proto
@@ -566,6 +566,7 @@ message GlobalSettingsProto {
optional LowPowerMode low_power_mode = 70;
optional SettingProto lte_service_forced = 71 [ (android.privacy).dest = DEST_AUTOMATIC ];
+ repeated SettingProto max_error_bytes = 151;
optional SettingProto mdc_initial_max_retry = 72 [ (android.privacy).dest = DEST_AUTOMATIC ];
message Mhl {
@@ -1058,5 +1059,5 @@ message GlobalSettingsProto {
// Please insert fields in alphabetical order and group them into messages
// if possible (to avoid reaching the method limit).
- // Next tag = 151;
+ // Next tag = 152;
}
diff --git a/core/proto/android/providers/settings/secure.proto b/core/proto/android/providers/settings/secure.proto
index 4ea574dadc73..6a1ec6c849c8 100644
--- a/core/proto/android/providers/settings/secure.proto
+++ b/core/proto/android/providers/settings/secure.proto
@@ -219,6 +219,12 @@ message SecureSettingsProto {
}
optional Gesture gesture = 74;
+ message GestureNavigation {
+ optional SettingProto back_gesture_inset_scale_left = 1 [(android.privacy).dest = DEST_AUTOMATIC];
+ optional SettingProto back_gesture_inset_scale_right = 2 [(android.privacy).dest = DEST_AUTOMATIC];
+ }
+ optional GestureNavigation gesture_navigation = 77;
+
optional SettingProto immersive_mode_confirmations = 24 [ (android.privacy).dest = DEST_AUTOMATIC ];
message Incall {
@@ -316,6 +322,7 @@ message SecureSettingsProto {
optional SettingProto multi_press_timeout = 38 [ (android.privacy).dest = DEST_AUTOMATIC ];
optional SettingProto navigation_mode = 76 [ (android.privacy).dest = DEST_AUTOMATIC ];
+
message NfcPayment {
option (android.msg_privacy).dest = DEST_EXPLICIT;
@@ -564,5 +571,5 @@ message SecureSettingsProto {
// Please insert fields in alphabetical order and group them into messages
// if possible (to avoid reaching the method limit).
- // Next tag = 77;
+ // Next tag = 78;
}
diff --git a/core/proto/android/server/windowmanagerservice.proto b/core/proto/android/server/windowmanagerservice.proto
index 24456d80625d..0c7484216367 100644
--- a/core/proto/android/server/windowmanagerservice.proto
+++ b/core/proto/android/server/windowmanagerservice.proto
@@ -163,6 +163,7 @@ message DisplayContentProto {
repeated IdentifierProto opening_apps = 17;
repeated IdentifierProto closing_apps = 18;
repeated IdentifierProto changing_apps = 19;
+ repeated WindowTokenProto overlay_windows = 20;
}
/* represents DisplayFrames */
diff --git a/core/proto/android/stats/devicepolicy/device_policy_enums.proto b/core/proto/android/stats/devicepolicy/device_policy_enums.proto
index f8c304c72f53..ee5144c0f91a 100644
--- a/core/proto/android/stats/devicepolicy/device_policy_enums.proto
+++ b/core/proto/android/stats/devicepolicy/device_policy_enums.proto
@@ -152,4 +152,5 @@ enum EventId {
CROSS_PROFILE_APPS_GET_TARGET_USER_PROFILES = 125;
CROSS_PROFILE_APPS_START_ACTIVITY_AS_USER = 126;
SET_AUTO_TIME = 127;
+ SET_AUTO_TIME_ZONE = 128;
}
diff --git a/core/proto/android/stats/docsui/docsui_enums.proto b/core/proto/android/stats/docsui/docsui_enums.proto
index f648912d36eb..5963f6a7f938 100644
--- a/core/proto/android/stats/docsui/docsui_enums.proto
+++ b/core/proto/android/stats/docsui/docsui_enums.proto
@@ -56,6 +56,7 @@ enum Root {
ROOT_VIDEOS = 9;
ROOT_MTP = 10;
ROOT_THIRD_PARTY_APP = 11;
+ ROOT_DOCUMENTS = 12;
}
enum ContextScope {
diff --git a/core/proto/android/util/quotatracker.proto b/core/proto/android/util/quotatracker.proto
new file mode 100644
index 000000000000..0dea853b0986
--- /dev/null
+++ b/core/proto/android/util/quotatracker.proto
@@ -0,0 +1,219 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+syntax = "proto2";
+
+package android.util.quota;
+
+option java_multiple_files = true;
+
+import "frameworks/base/core/proto/android/privacy.proto";
+
+// A com.android.util.quota.QuotaTracker object.
+message QuotaTrackerProto {
+ option (.android.msg_privacy).dest = DEST_AUTOMATIC;
+
+ optional bool is_enabled = 1;
+
+ // If quota is free for everything in the tracker.
+ optional bool is_global_quota_free = 2;
+
+ // Current elapsed realtime.
+ optional int64 elapsed_realtime = 3;
+
+ message AlarmListener {
+ option (.android.msg_privacy).dest = DEST_AUTOMATIC;
+
+ // Whether the listener is waiting for an alarm or not.
+ optional bool is_waiting = 1;
+ // The time at which the alarm should go off, in the elapsed realtime timebase. Only
+ // valid if is_waiting is true.
+ optional int64 trigger_time_elapsed = 2;
+ }
+
+ // Next tag: 4
+}
+
+// A com.android.util.quota.Category object.
+message CategoryProto {
+ option (.android.msg_privacy).dest = DEST_AUTOMATIC;
+
+ // Name of the category set by the system service.
+ optional string name = 1;
+}
+
+// A com.android.util.quota.Uptc object.
+message UptcProto {
+ option (.android.msg_privacy).dest = DEST_AUTOMATIC;
+
+ // UserHandle value. Should be 0, 10, 11, 12, etc. where 0 is the owner.
+ optional int32 user_id = 1;
+ // Package name
+ optional string name = 2;
+ // Tag set by the system service to differentiate calls.
+ optional string tag = 3;
+}
+
+// A com.android.util.quota.CountQuotaTracker object.
+message CountQuotaTrackerProto {
+ option (.android.msg_privacy).dest = DEST_AUTOMATIC;
+
+ optional QuotaTrackerProto base_quota_data = 1;
+
+ message CountLimit {
+ option (.android.msg_privacy).dest = DEST_AUTOMATIC;
+
+ optional CategoryProto category = 1;
+ optional int32 limit = 2;
+ optional int64 window_size_ms = 3;
+ }
+ repeated CountLimit count_limit = 2;
+
+ message Event {
+ option (.android.msg_privacy).dest = DEST_AUTOMATIC;
+
+ // The time the event occurred, in the elapsed realtime timebase.
+ optional int64 timestamp_elapsed = 1;
+ }
+
+ message ExecutionStats {
+ option (.android.msg_privacy).dest = DEST_AUTOMATIC;
+
+ // The time after which this record should be considered invalid (out of date), in the
+ // elapsed realtime timebase.
+ optional int64 expiration_time_elapsed = 1;
+
+ optional int64 window_size_ms = 2;
+ optional int32 count_limit = 3;
+
+ // The total number of events that occurred in the window.
+ optional int32 count_in_window = 4;
+
+ // The time after which the app will be under the bucket quota. This is only valid if
+ // count_in_window >= count_limit.
+ optional int64 in_quota_time_elapsed = 5;
+ }
+
+ message UptcStats {
+ option (.android.msg_privacy).dest = DEST_AUTOMATIC;
+
+ optional UptcProto uptc = 1;
+
+ // True if the UPTC has been given free quota.
+ optional bool is_quota_free = 2;
+
+ repeated Event events = 3;
+
+ repeated ExecutionStats execution_stats = 4;
+
+ optional QuotaTrackerProto.AlarmListener in_quota_alarm_listener = 5;
+ }
+ repeated UptcStats uptc_stats = 3;
+
+ // Next tag: 4
+}
+
+// A com.android.util.quota.DurationQuotaTracker object.
+message DurationQuotaTrackerProto {
+ option (.android.msg_privacy).dest = DEST_AUTOMATIC;
+
+ optional QuotaTrackerProto base_quota_data = 1;
+
+ message DurationLimit {
+ option (.android.msg_privacy).dest = DEST_AUTOMATIC;
+
+ optional CategoryProto category = 1;
+ optional int64 limit_ms = 2;
+ optional int64 window_size_ms = 3;
+ }
+ repeated DurationLimit duration_limit = 2;
+
+ message ExecutionStats {
+ option (.android.msg_privacy).dest = DEST_AUTOMATIC;
+
+ // The time after which this record should be considered invalid (out of date), in the
+ // elapsed realtime timebase.
+ optional int64 expiration_time_elapsed = 1;
+
+ optional int32 window_size_ms = 2;
+ optional int64 duration_limit_ms = 3;
+
+ // The overall session duration in the window.
+ optional int64 session_duration_in_window_ms = 4;
+ // The number of individual long-running events in the window.
+ optional int32 event_count_in_window = 5;
+
+ // The time after which the app will be under the bucket quota. This is only valid if
+ // session_duration_in_window_ms >= duration_limit_ms.
+ optional int64 in_quota_time_elapsed = 6;
+ }
+
+ message Timer {
+ option (.android.msg_privacy).dest = DEST_AUTOMATIC;
+
+ // True if the Timer is actively tracking long-running events.
+ optional bool is_active = 1;
+ // The time this timer last became active. Only valid if is_active is true.
+ optional int64 start_time_elapsed = 2;
+ // How many long-running events are currently running. Valid only if is_active is true.
+ optional int32 event_count = 3;
+ }
+
+ message TimingSession {
+ option (.android.msg_privacy).dest = DEST_AUTOMATIC;
+
+ optional int64 start_time_elapsed = 1;
+ optional int64 end_time_elapsed = 2;
+ // How many events started during this session. This only count long-running events, not
+ // instantaneous events.
+ optional int32 event_count = 3;
+ }
+
+ message UptcStats {
+ option (.android.msg_privacy).dest = DEST_AUTOMATIC;
+
+ optional UptcProto uptc = 1;
+
+ // True if the UPTC has been given free quota.
+ optional bool is_quota_free = 2;
+
+ optional Timer timer = 3;
+
+ repeated TimingSession saved_sessions = 4;
+
+ repeated ExecutionStats execution_stats = 5;
+
+ optional QuotaTrackerProto.AlarmListener in_quota_alarm_listener = 6;
+ }
+ repeated UptcStats uptc_stats = 3;
+
+ message ReachedQuotaAlarmListener {
+ option (.android.msg_privacy).dest = DEST_AUTOMATIC;
+
+ optional int64 trigger_time_elapsed = 1;
+
+ message UptcTimes {
+ option (.android.msg_privacy).dest = DEST_AUTOMATIC;
+
+ optional UptcProto uptc = 1;
+ optional int64 out_of_quota_time_elapsed = 2;
+ }
+ repeated UptcTimes uptc_times = 2;
+ }
+ optional ReachedQuotaAlarmListener reached_quota_alarm_listener = 4;
+
+ // Next tag: 5
+}
diff --git a/core/proto/android/view/windowlayoutparams.proto b/core/proto/android/view/windowlayoutparams.proto
index 93a9fe2e5848..272a24515367 100644
--- a/core/proto/android/view/windowlayoutparams.proto
+++ b/core/proto/android/view/windowlayoutparams.proto
@@ -56,13 +56,6 @@ message WindowLayoutParamsProto {
optional uint32 input_feature_flags = 19;
optional int64 user_activity_timeout = 20;
- enum NeedsMenuState {
- NEEDS_MENU_UNSET = 0;
- NEEDS_MENU_SET_TRUE = 1;
- NEEDS_MENU_SET_FALSE = 2;
- }
- optional NeedsMenuState needs_menu_key = 22;
-
optional DisplayProto.ColorMode color_mode = 23;
optional uint32 flags = 24;
optional uint32 private_flags = 26;
@@ -70,4 +63,7 @@ message WindowLayoutParamsProto {
optional uint32 subtree_system_ui_visibility_flags = 28;
optional uint32 appearance = 29;
optional uint32 behavior = 30;
+ optional uint32 fit_insets_types = 31;
+ optional uint32 fit_insets_sides = 32;
+ optional bool fit_ignore_visibility = 33;
}
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index f6e91efd2ad7..ee86c162ac6a 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -635,10 +635,9 @@
<protected-broadcast android:name="android.intent.action.DEVICE_CUSTOMIZATION_READY" />
- <!-- NETWORK_SET_TIME / NETWORK_SET_TIMEZONE moved from com.android.phone to system server.
- They should ultimately be removed. -->
- <protected-broadcast android:name="android.intent.action.NETWORK_SET_TIME" />
- <protected-broadcast android:name="android.intent.action.NETWORK_SET_TIMEZONE" />
+ <!-- NETWORK_SET_TIME moved from com.android.phone to system server. It should ultimately be
+ removed. -->
+ <protected-broadcast android:name="android.telephony.action.NETWORK_SET_TIME" />
<!-- For tether entitlement recheck-->
<protected-broadcast
@@ -1851,6 +1850,13 @@
android:description="@string/permdesc_vibrate"
android:protectionLevel="normal|instant" />
+ <!-- Allows access to the vibrator always-on settings.
+ <p>Protection level: signature
+ @hide
+ -->
+ <permission android:name="android.permission.VIBRATE_ALWAYS_ON"
+ android:protectionLevel="signature" />
+
<!-- Allows using PowerManager WakeLocks to keep processor from sleeping or screen
from dimming.
<p>Protection level: normal
@@ -2202,6 +2208,17 @@
<permission android:name="android.permission.MANAGE_DOCUMENTS"
android:protectionLevel="signature|documenter" />
+ <!-- Allows an application to manage access to crates, usually as part
+ of a crates picker.
+ <p>This permission should <em>only</em> be requested by the platform
+ management app. This permission cannot be granted to
+ third-party apps.
+ @hide
+ @TestApi
+ -->
+ <permission android:name="android.permission.MANAGE_CRATES"
+ android:protectionLevel="signature" />
+
<!-- @hide Allows an application to cache content.
<p>Not for use by third-party applications.
-->
@@ -2927,6 +2944,14 @@
<permission android:name="android.permission.BIND_QUICK_SETTINGS_TILE"
android:protectionLevel="signature" />
+ <!-- Allows SystemUI to request third party controls.
+ <p>Should only be requested by the System and required by
+ ControlsService declarations.
+ @hide
+ -->
+ <permission android:name="android.permission.BIND_CONTROLS"
+ android:protectionLevel="signature" />
+
<!-- @SystemApi Allows an application to force a BACK operation on whatever is the
top activity.
<p>Not for use by third-party applications.
@@ -3265,13 +3290,6 @@
<permission android:name="android.permission.BIND_TV_INPUT"
android:protectionLevel="signature|privileged" />
- <!-- Must be required by an {@link android.service.sms.FinancialSmsService}
- to ensure that only the system can bind to it.
- @hide This is not a third-party API (intended for OEMs and system apps).
- -->
- <permission android:name="android.permission.BIND_FINANCIAL_SMS_SERVICE"
- android:protectionLevel="signature" />
-
<!-- @SystemApi
Must be required by a {@link com.android.media.tv.remoteprovider.TvRemoteProvider}
to ensure that only the system can bind to it.
@@ -4418,6 +4436,12 @@
<permission android:name="android.permission.MANAGE_SOUND_TRIGGER"
android:protectionLevel="signature|privileged" />
+ <!-- Allows preempting sound trigger recognitions for the sake of capturing audio on
+ implementations which do not support running both concurrently.
+ @hide -->
+ <permission android:name="android.permission.PREEMPT_SOUND_TRIGGER"
+ android:protectionLevel="signature|privileged" />
+
<!-- Must be required by system/priv apps implementing sound trigger detection services
@hide
@SystemApi -->
diff --git a/core/res/res/layout/chooser_grid.xml b/core/res/res/layout/chooser_grid.xml
index 6807f9af3980..0c45e45e7980 100644
--- a/core/res/res/layout/chooser_grid.xml
+++ b/core/res/res/layout/chooser_grid.xml
@@ -29,7 +29,7 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alwaysShow="true"
- android:elevation="1dp"
+ android:elevation="0dp"
android:background="@drawable/bottomsheet_background">
<ImageView
@@ -55,16 +55,16 @@
android:layout_centerHorizontal="true"/>
</RelativeLayout>
- <com.android.internal.widget.RecyclerView
+ <FrameLayout
+ android:id="@+id/content_preview_container"
android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layoutManager="com.android.internal.widget.GridLayoutManager"
- android:id="@+id/resolver_list"
- android:clipToPadding="false"
- android:background="?attr/colorBackgroundFloating"
- android:scrollbars="none"
- android:elevation="1dp"
- android:nestedScrollingEnabled="true"/>
+ android:layout_height="wrap_content"
+ android:visibility="gone" />
+
+ <com.android.internal.widget.ViewPager
+ android:id="@+id/profile_pager"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"/>
<TextView android:id="@+id/empty"
android:layout_width="match_parent"
diff --git a/core/res/res/layout/chooser_grid_preview_text.xml b/core/res/res/layout/chooser_grid_preview_text.xml
index 9c725b93eec6..4d7846dfb9cc 100644
--- a/core/res/res/layout/chooser_grid_preview_text.xml
+++ b/core/res/res/layout/chooser_grid_preview_text.xml
@@ -45,7 +45,8 @@
android:ellipsize="end"
android:fontFamily="@android:string/config_headlineFontFamily"
android:textColor="?android:attr/textColorPrimary"
- android:maxLines="2"/>
+ android:maxLines="2"
+ android:focusable="true"/>
<LinearLayout
android:id="@+id/copy_button"
diff --git a/core/res/res/layout/chooser_list_per_profile.xml b/core/res/res/layout/chooser_list_per_profile.xml
new file mode 100644
index 000000000000..212813f10bd4
--- /dev/null
+++ b/core/res/res/layout/chooser_list_per_profile.xml
@@ -0,0 +1,27 @@
+<!--
+ ~ Copyright (C) 2019 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.
+ -->
+
+<com.android.internal.widget.RecyclerView
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:layoutManager="com.android.internal.widget.GridLayoutManager"
+ android:id="@+id/resolver_list"
+ android:clipToPadding="false"
+ android:background="?attr/colorBackgroundFloating"
+ android:scrollbars="none"
+ android:elevation="1dp"
+ android:nestedScrollingEnabled="true"/> \ No newline at end of file
diff --git a/core/res/res/layout/resolver_list.xml b/core/res/res/layout/resolver_list.xml
index 6e45e7a4c509..c5d891254227 100644
--- a/core/res/res/layout/resolver_list.xml
+++ b/core/res/res/layout/resolver_list.xml
@@ -63,25 +63,22 @@
</RelativeLayout>
<View
+ android:id="@+id/divider"
android:layout_alwaysShow="true"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="?attr/colorBackgroundFloating"
android:foreground="?attr/dividerVertical" />
- <ListView
+
+ <com.android.internal.app.WrapHeightViewPager
+ android:id="@+id/profile_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:id="@+id/resolver_list"
- android:clipToPadding="false"
- android:background="?attr/colorBackgroundFloating"
- android:elevation="@dimen/resolver_elevation"
- android:nestedScrollingEnabled="true"
- android:scrollbarStyle="outsideOverlay"
- android:scrollIndicators="top|bottom"
android:divider="?attr/dividerVertical"
android:footerDividersEnabled="false"
android:headerDividersEnabled="false"
- android:dividerHeight="1dp" />
+ android:dividerHeight="1dp"/>
+
<View
android:layout_alwaysShow="true"
android:layout_width="match_parent"
@@ -89,7 +86,6 @@
android:background="?attr/colorBackgroundFloating"
android:foreground="?attr/dividerVertical" />
-
<TextView android:id="@+id/empty"
android:layout_width="match_parent"
android:layout_height="wrap_content"
diff --git a/core/res/res/layout/resolver_list_per_profile.xml b/core/res/res/layout/resolver_list_per_profile.xml
new file mode 100644
index 000000000000..68b991755e73
--- /dev/null
+++ b/core/res/res/layout/resolver_list_per_profile.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2019 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.
+ -->
+<ListView
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:id="@+id/resolver_list"
+ android:clipToPadding="false"
+ android:background="?attr/colorBackgroundFloating"
+ android:elevation="@dimen/resolver_elevation"
+ android:nestedScrollingEnabled="true"
+ android:scrollbarStyle="outsideOverlay"
+ android:scrollIndicators="top|bottom"
+ android:divider="?attr/dividerVertical"
+ android:footerDividersEnabled="false"
+ android:headerDividersEnabled="false"
+ android:dividerHeight="1dp" /> \ No newline at end of file
diff --git a/core/res/res/layout/resolver_list_with_default.xml b/core/res/res/layout/resolver_list_with_default.xml
index dbba0b7bcc25..5b3d929d23a5 100644
--- a/core/res/res/layout/resolver_list_with_default.xml
+++ b/core/res/res/layout/resolver_list_with_default.xml
@@ -144,25 +144,21 @@
</LinearLayout>
<View
+ android:id="@+id/divider"
android:layout_alwaysShow="true"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="?attr/colorBackgroundFloating"
android:foreground="?attr/dividerVertical" />
- <ListView
+
+ <com.android.internal.app.WrapHeightViewPager
+ android:id="@+id/profile_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:id="@+id/resolver_list"
- android:clipToPadding="false"
- android:background="?attr/colorBackgroundFloating"
- android:elevation="@dimen/resolver_elevation"
- android:nestedScrollingEnabled="true"
- android:scrollbarStyle="outsideOverlay"
- android:scrollIndicators="top|bottom"
+ android:dividerHeight="1dp"
android:divider="?attr/dividerVertical"
android:footerDividersEnabled="false"
- android:headerDividersEnabled="false"
- android:dividerHeight="1dp" />
+ android:headerDividersEnabled="false"/>
<View
android:layout_alwaysShow="true"
android:layout_width="match_parent"
diff --git a/core/res/res/values-mcc510-mnc08/config.xml b/core/res/res/values-mcc510-mnc08/config.xml
index 7b27554d47b5..58fbb9ea44de 100644
--- a/core/res/res/values-mcc510-mnc08/config.xml
+++ b/core/res/res/values-mcc510-mnc08/config.xml
@@ -23,4 +23,6 @@
and "333" is used for other purpose -->
<string-array translatable="false" name="config_callBarringMMI">
</string-array>
+ <string-array translatable="false" name="config_callBarringMMI_for_ims">
+ </string-array>
</resources>
diff --git a/core/res/res/values-mcc510-mnc89/config.xml b/core/res/res/values-mcc510-mnc89/config.xml
index 82efecffb7c1..c262247f2a88 100644
--- a/core/res/res/values-mcc510-mnc89/config.xml
+++ b/core/res/res/values-mcc510-mnc89/config.xml
@@ -23,4 +23,6 @@
and "333" is used for other purpose -->
<string-array translatable="false" name="config_callBarringMMI">
</string-array>
+ <string-array translatable="false" name="config_callBarringMMI_for_ims">
+ </string-array>
</resources>
diff --git a/core/res/res/values-sw600dp/bools.xml b/core/res/res/values-sw600dp/bools.xml
index 00f45c1512a2..b3397179b5c8 100644
--- a/core/res/res/values-sw600dp/bools.xml
+++ b/core/res/res/values-sw600dp/bools.xml
@@ -15,7 +15,6 @@
-->
<resources>
- <bool name="target_honeycomb_needs_options_menu">false</bool>
<bool name="show_ongoing_ime_switcher">true</bool>
<bool name="kg_share_status_area">false</bool>
<bool name="kg_sim_puk_account_full_screen">false</bool>
diff --git a/core/res/res/values/bools.xml b/core/res/res/values/bools.xml
index b49fe49c087b..29f9f6c2d736 100644
--- a/core/res/res/values/bools.xml
+++ b/core/res/res/values/bools.xml
@@ -23,7 +23,6 @@
<bool name="preferences_prefer_dual_pane">false</bool>
<bool name="show_ongoing_ime_switcher">true</bool>
<bool name="action_bar_expanded_action_views_exclusive">true</bool>
- <bool name="target_honeycomb_needs_options_menu">true</bool>
<!-- Whether or not to use the drawable/lockscreen_notselected and
drawable/lockscreen_selected instead of the generic dots when displaying
the LockPatternView.
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index bfbd959df1a8..85406c7e7cec 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -2357,15 +2357,22 @@
<!-- Whether to only install system packages on a user if they're whitelisted for that user
type. These are flags and can be freely combined.
- 0 (0b000) - disable whitelist (install all system packages; no logging)
- 1 (0b001) - enforce (only install system packages if they are whitelisted)
- 2 (0b010) - log (log when a non-whitelisted package is run)
- 4 (0b100) - treat any package not mentioned in the whitelist file as implicitly whitelisted
- 8 (0b1000) - ignore OTAs (don't install system packages during OTAs)
+ 0 - disable whitelist (install all system packages; no logging)
+ 1 - enforce (only install system packages if they are whitelisted)
+ 2 - log (log when a non-whitelisted package is run)
+ 4 - any package not mentioned in the whitelist file is implicitly whitelisted on all users
+ 8 - same as 4, but just for the SYSTEM user
+ 16 - ignore OTAs (don't install system packages during OTAs)
+ Common scenarios:
+ - to enable feature (fully enforced) for a complete whitelist: 1
+ - to enable feature for an incomplete whitelist (so use implicit whitelist mode): 5
+ - to enable feature but implicitly whitelist for SYSTEM user to ease local development: 9
+ - to disable feature completely if it had never been enabled: 16
+ - to henceforth disable feature and try to undo its previous effects: 0
Note: This list must be kept current with PACKAGE_WHITELIST_MODE_PROP in
frameworks/base/services/core/java/com/android/server/pm/UserSystemPackageInstaller.java -->
- <integer name="config_userTypePackageWhitelistMode">13</integer> <!-- 0b1101 -->
- <!-- TODO(b/143200798): Change to value 5, i.e. 0b0101, when b/143200798 is resolved. -->
+ <integer name="config_userTypePackageWhitelistMode">29</integer> <!-- 1+4+8+16 -->
+ <!-- TODO(b/143200798): Change to value 13, i.e. 1+4+8, when b/143200798 is resolved. -->
<!-- Whether UI for multi user should be shown -->
<bool name="config_enableMultiUserUI">false</bool>
@@ -2544,6 +2551,28 @@
<string name="config_customAdbPublicKeyConfirmationSecondaryUserComponent"
>com.android.systemui/com.android.systemui.usb.UsbDebuggingSecondaryUserActivity</string>
+ <!-- Component name of the activity that shows the usb containment status. -->
+ <string name="config_usbContaminantActivity" translatable="false"
+ >com.android.systemui/com.android.systemui.usb.UsbContaminantActivity</string>
+
+ <!-- Component name of the activity that shows the request for access to a usb device. -->
+ <string name="config_usbPermissionActivity" translatable="false"
+ >com.android.systemui/com.android.systemui.usb.UsbPermissionActivity</string>
+
+ <!-- Component name of the activity that shows more information about a usb accessory. -->
+ <string name="config_usbAccessoryUriActivity" translatable="false"
+ >com.android.systemui/com.android.systemui.usb.UsbAccessoryUriActivity</string>
+
+ <!-- Component name of the activity that confirms the activity to start when a usb device is
+ plugged in. -->
+ <string name="config_usbConfirmActivity" translatable="false"
+ >com.android.systemui/com.android.systemui.usb.UsbConfirmActivity</string>
+
+ <!-- Component name of the activity to select the activity to start when a usb device is plugged
+ in. -->
+ <string name="config_usbResolverActivity" translatable="false"
+ >com.android.systemui/com.android.systemui.usb.UsbResolverActivity</string>
+
<!-- Name of the dialog that is used to request the user's consent to VPN connection -->
<string name="config_customVpnConfirmDialogComponent" translatable="false"
>com.android.vpndialogs/com.android.vpndialogs.ConfirmDialog</string>
@@ -2630,6 +2659,18 @@
<item>353</item>
</string-array>
+ <!-- Ims supported call barring MMI code -->
+ <string-array translatable="false" name="config_callBarringMMI_for_ims">
+ <item>33</item>
+ <item>331</item>
+ <item>332</item>
+ <item>35</item>
+ <item>351</item>
+ <item>330</item>
+ <item>333</item>
+ <item>353</item>
+ </string-array>
+
<!-- Override the default detection behavior for the framework method
android.view.ViewConfiguration#hasPermanentMenuKey().
Valid settings are:
@@ -2652,11 +2693,6 @@
<!-- Package name for default network scorer app; overridden by product overlays. -->
<string name="config_defaultNetworkScorerPackageName"></string>
- <!-- Feature flag to enable memory efficient task snapshots that are used in recents optimized
- for low memory devices and replace the app transition starting window with the splash
- screen. -->
- <bool name="config_lowRamTaskSnapshotsAndRecents">false</bool>
-
<!-- The amount to scale fullscreen snapshots for Overview and snapshot starting windows. -->
<item name="config_fullTaskSnapshotScale" format="float" type="dimen">1.0</item>
@@ -2667,11 +2703,45 @@
property. If this is false, then the following recents config flags are ignored. -->
<bool name="config_hasRecents">true</bool>
- <!-- Component name for the activity that will be presenting the Recents UI, which will receive special permissions for API related
- to fetching and presenting recent tasks. The default configuration uses Launcehr3QuickStep as default launcher and points to
- the corresponding recents component. When using a different default launcher, change this appropriately or use the default
- systemui implementation: com.android.systemui/.recents.RecentsActivity -->
- <string name="config_recentsComponentName" translatable="false">com.android.launcher3/com.android.quickstep.RecentsActivity</string>
+ <!-- Component name for the activity that will be presenting the Recents UI, which will receive
+ special permissions for API related to fetching and presenting recent tasks. The default
+ configuration uses Launcehr3QuickStep as default launcher and points to the corresponding
+ recents component. When using a different default launcher, change this appropriately or
+ use the default systemui implementation: com.android.systemui/.recents.RecentsActivity -->
+ <string name="config_recentsComponentName" translatable="false"
+ >com.android.launcher3/com.android.quickstep.RecentsActivity</string>
+
+ <!-- SystemUi service component -->
+ <string name="config_systemUIServiceComponent" translatable="false"
+ >com.android.systemui/com.android.systemui.SystemUIService</string>
+
+ <!-- Keyguard component -->
+ <string name="config_keyguardComponent" translatable="false"
+ >com.android.systemui/com.android.systemui.keyguard.KeyguardService</string>
+
+ <!-- Screen record dialog component -->
+ <string name="config_screenRecorderComponent" translatable="false"
+ >com.android.systemui/com.android.systemui.screenrecord.ScreenRecordDialog</string>
+
+ <!-- The component name of a special dock app that merely launches a dream.
+ We don't want to launch this app when docked because it causes an unnecessary
+ activity transition. We just want to start the dream. -->
+ <string name="config_somnambulatorComponent" translatable="false"
+ >com.android.systemui/com.android.systemui.Somnambulator</string>
+
+ <!-- The component name of a special dock app that merely launches a dream.
+ We don't want to launch this app when docked because it causes an unnecessary
+ activity transition. We just want to start the dream.. -->
+ <string name="config_screenshotServiceComponent" translatable="false"
+ >com.android.systemui/com.android.systemui.screenshot.TakeScreenshotService</string>
+
+ <!-- The component notified when there is an error while taking a screenshot. -->
+ <string name="config_screenshotErrorReceiverComponent" translatable="false"
+ >com.android.systemui/com.android.systemui.screenshot.ScreenshotServiceErrorReceiver</string>
+
+ <!-- The component for the activity shown to grant permissions for a slice. -->
+ <string name="config_slicePermissionComponent" translatable="false"
+ >com.android.systemui/com.android.systemui.SlicePermissionActivity</string>
<!-- The minimum number of visible recent tasks to be presented to the user through the
SystemUI. Can be -1 if there is no minimum limit. -->
@@ -2844,10 +2914,6 @@
<!-- Whether to use voip audio mode for ims call -->
<bool name="config_use_voip_mode_for_ims">false</bool>
- <!-- ImsService package name to bind to by default. If none is specified in an overlay, an
- empty string is passed in -->
- <string name="config_ims_package"/>
-
<!-- String array containing numbers that shouldn't be logged. Country-specific. -->
<string-array name="unloggable_phone_numbers" />
@@ -3025,9 +3091,6 @@
<!-- Specifies the maximum burn-in offset vertically. -->
<integer name="config_burnInProtectionMaxVerticalOffset">0</integer>
- <!-- Keyguard component -->
- <string name="config_keyguardComponent" translatable="false">com.android.systemui/com.android.systemui.keyguard.KeyguardService</string>
-
<!-- Limit for the number of face templates per user -->
<integer name="config_faceMaxTemplatesPerUser">1</integer>
@@ -3066,7 +3129,9 @@
The path is assumed to be specified in display coordinates with pixel units and in
the display's native orientation, with the origin of the coordinate system at the
- center top of the display.
+ center top of the display. Optionally, you can append either `@left` or `@right` to the
+ end of the path string, in order to change the path origin to either the top left,
+ or top right of the display.
To facilitate writing device-independent emulation overlays, the marker `@dp` can be
appended after the path string to interpret coordinates in dp instead of px units.
@@ -4100,6 +4165,14 @@
<!-- Which binder services to include in incident reports containing restricted images. -->
<string-array name="config_restrictedImagesServices" translatable="false"/>
+ <!-- List of biometric sensors on the device, in decreasing strength. Consumed by AuthService
+ when registering authenticators with BiometricService. Format must be ID:Modality:Strength,
+ where: IDs are unique per device, Modality as defined in BiometricAuthenticator.java,
+ and Strength as defined in Authenticators.java -->
+ <string-array name="config_biometric_sensors" translatable="false" >
+ <item>0:2:15</item> <!-- ID0:Fingerprint:Strong -->
+ </string-array>
+
<!-- Messages that should not be shown to the user during face auth enrollment. This should be
used to hide messages that may be too chatty or messages that the user can't do much about.
Entries are defined in android.hardware.biometrics.face@1.0 types.hal -->
@@ -4185,4 +4258,18 @@
<!-- The package name for the default bug report handler app from power menu short press. This app must be whitelisted. -->
<string name="config_defaultBugReportHandlerApp" translatable="false"></string>
+
+ <!-- The default value used for RawContacts.ACCOUNT_NAME when contacts are inserted without this
+ column set. These contacts are stored locally on the device and will not be removed even
+ if no android.account.Account with this name exists. A null string will be used if the
+ value is left empty. When this is non-empty then config_rawContactsLocalAccountType
+ should also be non-empty. -->
+ <string name="config_rawContactsLocalAccountName" translatable="false"></string>
+
+ <!-- The default value used for RawContacts.ACCOUNT_TYPE when contacts are inserted without this
+ column set. These contacts are stored locally on the device and will not be removed even
+ if no android.account.Account with this type exists. A null string will be used if the
+ value is left empty. When this is non-empty then config_rawContactsLocalAccountName
+ should also be non-empty.-->
+ <string name="config_rawContactsLocalAccountType" translatable="false"></string>
</resources>
diff --git a/core/res/res/values/dimens.xml b/core/res/res/values/dimens.xml
index 9791241a52af..2543967be8a8 100644
--- a/core/res/res/values/dimens.xml
+++ b/core/res/res/values/dimens.xml
@@ -772,4 +772,8 @@
<dimen name="resolver_small_margin">18dp</dimen>
<dimen name="resolver_edge_margin">24dp</dimen>
<dimen name="resolver_elevation">1dp</dimen>
+
+ <!-- Assistant handles -->
+ <dimen name="assist_handle_shadow_radius">2dp</dimen>
+
</resources>
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 0f5da39a2c1e..ab10738327b3 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -1011,53 +1011,32 @@
<!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
<string name="permlab_readContacts">read your contacts</string>
<!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
- <string name="permdesc_readContacts" product="tablet">Allows the app to read
- data about your contacts stored on your tablet, including the frequency
- with which you\'ve called, emailed, or communicated in other ways with
- specific individuals. Apps will also have access to the accounts on your
- tablet that have created contacts. This may include accounts created by
- apps you have installed. This permission allows apps to save your contact
- data, and malicious apps may share contact data without your
- knowledge.</string>
+ <string name="permdesc_readContacts" product="tablet">Allows the app to read data about your contacts stored on your tablet.
+ Apps will also have access to the accounts on your tablet that have created contacts.
+ This may include accounts created by apps you have installed.
+ This permission allows apps to save your contact data, and malicious apps may share contact data without your knowledge.</string>
<!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
- <string name="permdesc_readContacts" product="tv">Allows the app to read
- data about your contacts stored on your Android TV device, including the frequency
- with which you\'ve called, emailed, or communicated in other ways with
- specific individuals. Apps will also have access to the accounts on your
- Android TV device that have created contacts. This may include accounts
- created by apps you have installed. This permission allows apps to save
- your contact data, and malicious apps may share contact data without your
- knowledge.</string>
+ <string name="permdesc_readContacts" product="tv">Allows the app to read data about your contacts stored on your Android TV device.
+ Apps will also have access to the accounts on your Android TV device that have created contacts.
+ This may include accounts created by apps you have installed.
+ This permission allows apps to save your contact data, and malicious apps may share contact data without your knowledge.</string>
<!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
- <string name="permdesc_readContacts" product="default">Allows the app to
- read data about your contacts stored on your phone, including the
- frequency with which you\'ve called, emailed, or communicated in other ways
- with specific individuals. Apps will also have access to the accounts
- on your phone that have created contacts. This may include accounts
- created by apps you have installed. This permission allows apps to
- save your contact data, and malicious apps may share contact data
- without your knowledge.</string>
+ <string name="permdesc_readContacts" product="default">Allows the app to read data about your contacts stored on your phone.
+ Apps will also have access to the accounts on your phone that have created contacts.
+ This may include accounts created by apps you have installed.
+ This permission allows apps to save your contact data, and malicious apps may share contact data without your knowledge.</string>
<!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
<string name="permlab_writeContacts">modify your contacts</string>
<!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
- <string name="permdesc_writeContacts" product="tablet">Allows the app to
- modify the data about your contacts stored on your tablet, including the
- frequency with which you\'ve called, emailed, or communicated in other ways
- with specific contacts. This permission allows apps to delete contact
- data.</string>
+ <string name="permdesc_writeContacts" product="tablet">Allows the app to modify the data about your contacts stored on your tablet.
+ This permission allows apps to delete contact data.</string>
<!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
- <string name="permdesc_writeContacts" product="tv">Allows the app to
- modify the data about your contacts stored on your Android TV device, including the
- frequency with which you\'ve called, emailed, or communicated in other ways
- with specific contacts. This permission allows apps to delete contact
- data.</string>
+ <string name="permdesc_writeContacts" product="tv">Allows the app to modify the data about your contacts stored on your Android TV device.
+ This permission allows apps to delete contact data.</string>
<!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
- <string name="permdesc_writeContacts" product="default">Allows the app to
- modify the data about your contacts stored on your phone, including the
- frequency with which you\'ve called, emailed, or communicated in other ways
- with specific contacts. This permission allows apps to delete contact
- data.</string>
+ <string name="permdesc_writeContacts" product="default">Allows the app to modify the data about your contacts stored on your phone.
+ This permission allows apps to delete contact data.</string>
<!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
<string name="permlab_readCallLog">read call log</string>
@@ -1102,6 +1081,7 @@
<string name="permdesc_writeCalendar" product="default">This app can add, remove, or change calendar events on your phone. This app can send messages that may appear to come from calendar owners, or change events without notifying their owners.</string>
<!-- Title of an application permission, listed so the user can choose whether they want to allow the applicatfion to do this. -->
+ <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
<string name="permlab_accessLocationExtraCommands">access extra location provider commands</string>
<!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
<string name="permdesc_accessLocationExtraCommands">Allows the app to access
@@ -1111,21 +1091,17 @@
<!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
<string name="permlab_accessFineLocation">access precise location only in the foreground</string>
<!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
- <string name="permdesc_accessFineLocation">This app can get your exact location only when it is in the foreground. These location services must be turned on and available on your phone for the app to be able to use them. This may increase battery consumption.</string>
+ <string name="permdesc_accessFineLocation">This app can get your exact location only when it is in the foreground. Location services must be turned on and available on your device for the app to be able to use them. This may increase battery consumption.</string>
<!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
- <string name="permlab_accessCoarseLocation">access approximate location (network-based) only in the foreground</string>
- <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
- <string name="permdesc_accessCoarseLocation" product="tablet">This app can get your location based on network sources such as cell towers and Wi-Fi networks, but only when when the app is in the foreground. These location services must be turned on and available on your tablet for the app to be able to use them.</string>
- <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
- <string name="permdesc_accessCoarseLocation" product="tv">This app can get your location based on network sources such as cell towers and Wi-Fi networks, but only when when the app is in the foreground. These location services must be turned on and available on your Android TV device for the app to be able to use them.</string>
+ <string name="permlab_accessCoarseLocation">access approximate location only in the foreground</string>
<!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
- <string name="permdesc_accessCoarseLocation" product="default">This app can get your location based on network sources such as cell towers and Wi-Fi networks, but only when the app is in the foreground. These location services must be turned on and available on your phone for the app to be able to use them.</string>
+ <string name="permdesc_accessCoarseLocation">This app can get your approximate location only when it is in the foreground. Location services must be turned on and available on your device for the app to be able to use them.</string>
<!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
<string name="permlab_accessBackgroundLocation">access location in the background</string>
<!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
- <string name="permdesc_accessBackgroundLocation">If this is granted additionally to the approximate or precise location access the app can access the location while running in the background.</string>
+ <string name="permdesc_accessBackgroundLocation">This app can access location while running in the background, in addition to foreground location access.</string>
<!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
<string name="permlab_modifyAudioSettings">change your audio settings</string>
@@ -4970,8 +4946,12 @@
<!-- Resolver target actions strings -->
<!-- Pin this app to the top of the Sharesheet app list. [CHAR LIMIT=60]-->
<string name="pin_target">Pin</string>
+ <!-- Pin this app to the top of the Sharesheet app list. [CHAR LIMIT=60]-->
+ <string name="pin_specific_target">Pin <xliff:g id="label" example="Tweet">%1$s</xliff:g></string>
+ <!-- Un-pin this app in the Sharesheet, so that it is sorted normally. [CHAR LIMIT=60]-->
+ <string name="unpin_target">Unpin </string>
<!-- Un-pin this app in the Sharesheet, so that it is sorted normally. [CHAR LIMIT=60]-->
- <string name="unpin_target">Unpin</string>
+ <string name="unpin_specific_target">Unpin <xliff:g id="label" example="Tweet">%1$s</xliff:g></string>
<!-- View application info for a target. -->
<string name="app_info">App info</string>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index ee9287c7d64c..1e59c37c7577 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -247,6 +247,8 @@
<java-symbol type="id" name="mic" />
<java-symbol type="id" name="overlay" />
<java-symbol type="id" name="app_ops" />
+ <java-symbol type="id" name="profile_pager" />
+ <java-symbol type="id" name="content_preview_container" />
<java-symbol type="attr" name="actionModeShareDrawable" />
<java-symbol type="attr" name="alertDialogCenterButtons" />
@@ -293,7 +295,6 @@
<java-symbol type="bool" name="config_enableBurnInProtection" />
<java-symbol type="bool" name="config_hotswapCapable" />
<java-symbol type="bool" name="config_mms_content_disposition_support" />
- <java-symbol type="string" name="config_ims_package" />
<java-symbol type="string" name="config_wwan_network_service_package" />
<java-symbol type="string" name="config_wlan_network_service_package" />
<java-symbol type="string" name="config_wwan_network_service_class" />
@@ -356,9 +357,19 @@
<java-symbol type="bool" name="config_disableUsbPermissionDialogs"/>
<java-symbol type="dimen" name="config_fullTaskSnapshotScale" />
<java-symbol type="bool" name="config_use16BitTaskSnapshotPixelFormat" />
- <java-symbol type="bool" name="config_lowRamTaskSnapshotsAndRecents" />
<java-symbol type="bool" name="config_hasRecents" />
<java-symbol type="string" name="config_recentsComponentName" />
+ <java-symbol type="string" name="config_systemUIServiceComponent" />
+ <java-symbol type="string" name="config_screenRecorderComponent" />
+ <java-symbol type="string" name="config_somnambulatorComponent" />
+ <java-symbol type="string" name="config_screenshotServiceComponent" />
+ <java-symbol type="string" name="config_screenshotErrorReceiverComponent" />
+ <java-symbol type="string" name="config_slicePermissionComponent" />
+ <java-symbol type="string" name="config_usbContaminantActivity" />
+ <java-symbol type="string" name="config_usbPermissionActivity" />
+ <java-symbol type="string" name="config_usbAccessoryUriActivity" />
+ <java-symbol type="string" name="config_usbConfirmActivity" />
+ <java-symbol type="string" name="config_usbResolverActivity" />
<java-symbol type="integer" name="config_minNumVisibleRecentTasks_lowRam" />
<java-symbol type="integer" name="config_maxNumVisibleRecentTasks_lowRam" />
<java-symbol type="integer" name="config_minNumVisibleRecentTasks_grid" />
@@ -440,6 +451,7 @@
<java-symbol type="integer" name="config_multiuserMaxRunningUsers" />
<java-symbol type="bool" name="config_multiuserDelayUserDataLocking" />
<java-symbol type="integer" name="config_userTypePackageWhitelistMode"/>
+ <java-symbol type="xml" name="config_user_types" />
<java-symbol type="integer" name="config_safe_media_volume_index" />
<java-symbol type="integer" name="config_safe_media_volume_usb_mB" />
<java-symbol type="integer" name="config_mobile_mtu" />
@@ -1229,6 +1241,7 @@
<java-symbol type="array" name="config_cdma_dun_supported_types" />
<java-symbol type="array" name="config_disabledUntilUsedPreinstalledImes" />
<java-symbol type="array" name="config_callBarringMMI" />
+ <java-symbol type="array" name="config_callBarringMMI_for_ims" />
<java-symbol type="array" name="config_globalActionsList" />
<java-symbol type="array" name="config_telephonyEuiccDeviceCapabilities" />
<java-symbol type="array" name="config_telephonyHardware" />
@@ -1533,6 +1546,8 @@
<java-symbol type="layout" name="user_switching_dialog" />
<java-symbol type="layout" name="common_tab_settings" />
<java-symbol type="layout" name="notification_material_media_seekbar" />
+ <java-symbol type="layout" name="resolver_list_per_profile" />
+ <java-symbol type="layout" name="chooser_list_per_profile" />
<java-symbol type="anim" name="slide_in_child_bottom" />
<java-symbol type="anim" name="slide_in_right" />
@@ -1657,7 +1672,6 @@
<java-symbol type="bool" name="config_perDisplayFocusEnabled" />
<java-symbol type="bool" name="config_showNavigationBar" />
<java-symbol type="bool" name="config_supportAutoRotation" />
- <java-symbol type="bool" name="target_honeycomb_needs_options_menu" />
<java-symbol type="dimen" name="docked_stack_divider_thickness" />
<java-symbol type="dimen" name="docked_stack_divider_insets" />
<java-symbol type="dimen" name="docked_stack_minimize_thickness" />
@@ -2468,6 +2482,8 @@
<java-symbol type="string" name="face_authenticated_no_confirmation_required" />
<java-symbol type="string" name="face_authenticated_confirmation_required" />
+ <java-symbol type="array" name="config_biometric_sensors" />
+
<java-symbol type="array" name="config_face_acquire_enroll_ignorelist" />
<java-symbol type="array" name="config_face_acquire_vendor_enroll_ignorelist" />
<java-symbol type="array" name="config_face_acquire_keyguard_ignorelist" />
@@ -2941,6 +2957,8 @@
<!-- Resolver target actions -->
<java-symbol type="array" name="resolver_target_actions_pin" />
<java-symbol type="array" name="resolver_target_actions_unpin" />
+ <java-symbol type="string" name="pin_specific_target" />
+ <java-symbol type="string" name="unpin_specific_target" />
<java-symbol type="array" name="non_removable_euicc_slots" />
@@ -3768,4 +3786,13 @@
<java-symbol type="string" name="accessibility_system_action_toggle_split_screen_label" />
<java-symbol type="string" name="accessibility_freeform_caption" />
+
+ <!-- For contacts provider. -->
+ <java-symbol type="string" name="config_rawContactsLocalAccountName" />
+ <java-symbol type="string" name="config_rawContactsLocalAccountType" />
+
+ <!-- Assistant handles -->
+ <java-symbol type="dimen" name="assist_handle_shadow_radius" />
+
+
</resources>
diff --git a/core/res/res/xml/config_user_types.xml b/core/res/res/xml/config_user_types.xml
new file mode 100644
index 000000000000..5fd8a95af64d
--- /dev/null
+++ b/core/res/res/xml/config_user_types.xml
@@ -0,0 +1,98 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+
+<!--
+This xml file allows customization of Android multiuser user types.
+It is parsed by frameworks/base/services/core/java/com/android/server/pm/UserTypeFactory.java.
+
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++ IMPORTANT NOTE ++++++++++++++++++++++++++++++++++++++++
+Although device customization is possible here, it is largely untested.
+In particular, although this file allows new profile types to be created, and allows modifying the
+number of managed profiles allowed on the device, the consequences of doing so is untested.
+OEMs are advised to test very carefully any significant customization.
+Further support is planned for later releases.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+
+Pre-defined (AOSP) user types can be customized and new types can be defined. The syntax is the
+same in both cases.
+
+Currently, only profiles (not full or system users) can be freely customized/defined.
+Full users (i.e. non-system, non-profile) users cannot be defined, and the only property of them
+that can be customized are the default-restrictions.
+System users cannot be customized here; their default-restrictions must be set using
+com.android.internal.R.array.config_defaultFirstUserRestrictions.
+
+The following example modifies two AOSP user types (the FULL user android.os.usertype.full.SECONDARY
+and the PROFILE user android.os.usertype.profile.MANAGED) and creates a new PROFILE user type
+(com.example.profilename):
+
+<user-types>
+ <full-type name="android.os.usertype.full.SECONDARY" >
+ <default-restrictions no_sms="true" />
+ </full-type>
+
+ <profile-type
+ name='android.os.usertype.profile.MANAGED'
+ max-allowed-per-parent='2'
+ icon-badge='@android:drawable/ic_corp_icon_badge_case'
+ badge-plain='@android:drawable/ic_corp_badge_case'
+ badge-no-background='@android:drawable/ic_corp_badge_no_background' >
+ <badge-labels>
+ <item res='@android:string/managed_profile_label_badge' />
+ <item res='@android:string/managed_profile_label_badge_2' />
+ </badge-labels>
+ <badge-colors>
+ <item res='@android:color/profile_badge_1' />
+ <item res='@android:color/profile_badge_2' />
+ </badge-colors>
+ <default-restrictions no_sms="true" no_outgoing_calls="true" />
+ </profile-type>
+
+ <profile-type
+ name="com.example.profilename"
+ max-allowed-per-parent="2" />
+</user-types>
+
+Mandatory attributes:
+ name
+
+Supported optional properties (to be used as shown in the example above) are as follows.
+For profile and full users:
+ default-restrictions (with values defined in UserRestrictionUtils.USER_RESTRICTIONS)
+For profile users only:
+ max-allowed-per-parent
+ icon-badge
+ badge-plain
+ badge-no-background
+ badge-labels
+ badge-colors
+
+See UserTypeFactory.java and UserTypeDetails.java for the meaning (and default values) of these
+fields.
+
+Any property that is specified overwrites the AOSP default. For example, if there is no
+default-restrictions element, then the AOSP defaults for that user type will be used; however, if
+there is a default-restrictions element, then the AOSP default restrictions will be completely
+ignored and will instead obey this configuration.
+
+If this file is updated, the properties of any pre-existing user types will be updated too.
+Note, however, that default-restrictions refers to the restrictions applied at the time of user
+creation; therefore, the active restrictions of any pre-existing users will not be updated.
+
+-->
+<user-types>
+</user-types>
diff --git a/core/tests/bluetoothtests/src/android/bluetooth/BluetoothTestUtils.java b/core/tests/bluetoothtests/src/android/bluetooth/BluetoothTestUtils.java
index b906d84adf52..ed613c36b89b 100644
--- a/core/tests/bluetoothtests/src/android/bluetooth/BluetoothTestUtils.java
+++ b/core/tests/bluetoothtests/src/android/bluetooth/BluetoothTestUtils.java
@@ -176,14 +176,12 @@ public class BluetoothTestUtils extends Assert {
mDevice.setPin(mPin);
break;
case BluetoothDevice.PAIRING_VARIANT_PASSKEY:
- mDevice.setPasskey(mPasskey);
break;
case BluetoothDevice.PAIRING_VARIANT_PASSKEY_CONFIRMATION:
case BluetoothDevice.PAIRING_VARIANT_CONSENT:
mDevice.setPairingConfirmation(true);
break;
case BluetoothDevice.PAIRING_VARIANT_OOB_CONSENT:
- mDevice.setRemoteOutOfBandData();
break;
}
} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(intent.getAction())) {
diff --git a/core/tests/coretests/Android.bp b/core/tests/coretests/Android.bp
index c009f588f8a9..caae9088e9b5 100644
--- a/core/tests/coretests/Android.bp
+++ b/core/tests/coretests/Android.bp
@@ -24,6 +24,7 @@ android_test {
],
static_libs: [
"frameworks-base-testutils",
+ "core-test-rules", // for libcore.dalvik.system.CloseGuardSupport
"core-tests-support",
"android-common",
"frameworks-core-util-lib",
diff --git a/core/tests/coretests/src/android/app/activity/ActivityManagerTest.java b/core/tests/coretests/src/android/app/activity/ActivityManagerTest.java
index bbd442d53f76..6c5d5485664e 100644
--- a/core/tests/coretests/src/android/app/activity/ActivityManagerTest.java
+++ b/core/tests/coretests/src/android/app/activity/ActivityManagerTest.java
@@ -16,7 +16,11 @@
package android.app.activity;
+import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE;
+import static android.content.pm.ActivityInfo.RESIZE_MODE_UNRESIZEABLE;
+
import android.app.ActivityManager;
+import android.app.ActivityManager.TaskDescription;
import android.content.Context;
import android.content.pm.ConfigurationInfo;
import android.content.res.Configuration;
@@ -110,7 +114,123 @@ public class ActivityManagerTest extends AndroidTestCase {
assertNotNull(config.reqInputFeatures & ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD);
}
}
-
+
+ @SmallTest
+ public void testTaskDescriptionCopyFrom() {
+ TaskDescription td1 = new TaskDescription(
+ "test label", // label
+ null, // bitmap
+ 21, // iconRes
+ "dummy file", // iconFilename
+ 0x111111, // colorPrimary
+ 0x222222, // colorBackground
+ 0x333333, // statusBarColor
+ 0x444444, // navigationBarColor
+ true, // ensureStatusBarContrastWhenTransparent
+ true, // ensureNavigationBarContrastWhenTransparent
+ RESIZE_MODE_RESIZEABLE, // resizeMode
+ 10, // minWidth
+ 20 // minHeight
+ );
+
+ TaskDescription td2 = new TaskDescription();
+ // Must overwrite all the fields
+ td2.copyFrom(td1);
+
+ assertEquals(td1.getLabel(), td2.getLabel());
+ assertEquals(td1.getInMemoryIcon(), td2.getInMemoryIcon());
+ assertEquals(td1.getIconFilename(), td2.getIconFilename());
+ assertEquals(td1.getIconResource(), td2.getIconResource());
+ assertEquals(td1.getPrimaryColor(), td2.getPrimaryColor());
+ assertEquals(td1.getBackgroundColor(), td2.getBackgroundColor());
+ assertEquals(td1.getStatusBarColor(), td2.getStatusBarColor());
+ assertEquals(td1.getNavigationBarColor(), td2.getNavigationBarColor());
+ assertEquals(td1.getEnsureStatusBarContrastWhenTransparent(),
+ td2.getEnsureStatusBarContrastWhenTransparent());
+ assertEquals(td1.getEnsureNavigationBarContrastWhenTransparent(),
+ td2.getEnsureNavigationBarContrastWhenTransparent());
+ assertEquals(td1.getResizeMode(), td2.getResizeMode());
+ assertEquals(td1.getMinWidth(), td2.getMinWidth());
+ assertEquals(td1.getMinHeight(), td2.getMinHeight());
+ }
+
+ @SmallTest
+ public void testTaskDescriptionCopyFromPreserveHiddenFields() {
+ TaskDescription td1 = new TaskDescription(
+ "test label", // label
+ null, // bitmap
+ 21, // iconRes
+ "dummy file", // iconFilename
+ 0x111111, // colorPrimary
+ 0x222222, // colorBackground
+ 0x333333, // statusBarColor
+ 0x444444, // navigationBarColor
+ false, // ensureStatusBarContrastWhenTransparent
+ false, // ensureNavigationBarContrastWhenTransparent
+ RESIZE_MODE_UNRESIZEABLE, // resizeMode
+ 10, // minWidth
+ 20 // minHeight
+ );
+
+ TaskDescription td2 = new TaskDescription(
+ "test label2", // label
+ null, // bitmap
+ 212, // iconRes
+ "dummy file2", // iconFilename
+ 0x1111112, // colorPrimary
+ 0x2222222, // colorBackground
+ 0x3333332, // statusBarColor
+ 0x4444442, // navigationBarColor
+ true, // ensureStatusBarContrastWhenTransparent
+ true, // ensureNavigationBarContrastWhenTransparent
+ RESIZE_MODE_RESIZEABLE, // resizeMode
+ 102, // minWidth
+ 202 // minHeight
+ );
+
+ // Must overwrite all public and hidden fields, since other has all fields set.
+ td2.copyFromPreserveHiddenFields(td1);
+
+ assertEquals(td1.getLabel(), td2.getLabel());
+ assertEquals(td1.getInMemoryIcon(), td2.getInMemoryIcon());
+ assertEquals(td1.getIconFilename(), td2.getIconFilename());
+ assertEquals(td1.getIconResource(), td2.getIconResource());
+ assertEquals(td1.getPrimaryColor(), td2.getPrimaryColor());
+ assertEquals(td1.getBackgroundColor(), td2.getBackgroundColor());
+ assertEquals(td1.getStatusBarColor(), td2.getStatusBarColor());
+ assertEquals(td1.getNavigationBarColor(), td2.getNavigationBarColor());
+ assertEquals(td1.getEnsureStatusBarContrastWhenTransparent(),
+ td2.getEnsureStatusBarContrastWhenTransparent());
+ assertEquals(td1.getEnsureNavigationBarContrastWhenTransparent(),
+ td2.getEnsureNavigationBarContrastWhenTransparent());
+ assertEquals(td1.getResizeMode(), td2.getResizeMode());
+ assertEquals(td1.getMinWidth(), td2.getMinWidth());
+ assertEquals(td1.getMinHeight(), td2.getMinHeight());
+
+ TaskDescription td3 = new TaskDescription();
+ // Must overwrite only public fields, and preserve hidden fields.
+ td2.copyFromPreserveHiddenFields(td3);
+
+ // Overwritten fields
+ assertEquals(td3.getLabel(), td2.getLabel());
+ assertEquals(td3.getInMemoryIcon(), td2.getInMemoryIcon());
+ assertEquals(td3.getIconFilename(), td2.getIconFilename());
+ assertEquals(td3.getIconResource(), td2.getIconResource());
+ assertEquals(td3.getPrimaryColor(), td2.getPrimaryColor());
+ assertEquals(td3.getEnsureStatusBarContrastWhenTransparent(),
+ td2.getEnsureStatusBarContrastWhenTransparent());
+ assertEquals(td3.getEnsureNavigationBarContrastWhenTransparent(),
+ td2.getEnsureNavigationBarContrastWhenTransparent());
+
+ // Preserved fields
+ assertEquals(td1.getBackgroundColor(), td2.getBackgroundColor());
+ assertEquals(td1.getStatusBarColor(), td2.getStatusBarColor());
+ assertEquals(td1.getNavigationBarColor(), td2.getNavigationBarColor());
+ assertEquals(td1.getResizeMode(), td2.getResizeMode());
+ assertEquals(td1.getMinWidth(), td2.getMinWidth());
+ assertEquals(td1.getMinHeight(), td2.getMinHeight());
+ }
+
// If any entries in appear in the list, sanity check them against all running applications
private void checkErrorListSanity(List<ActivityManager.ProcessErrorStateInfo> errList) {
if (errList == null) return;
diff --git a/core/tests/coretests/src/android/provider/DeviceConfigTest.java b/core/tests/coretests/src/android/provider/DeviceConfigTest.java
index 8c1c3b569303..ae835e4a1c73 100644
--- a/core/tests/coretests/src/android/provider/DeviceConfigTest.java
+++ b/core/tests/coretests/src/android/provider/DeviceConfigTest.java
@@ -33,9 +33,6 @@ import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
-import java.util.HashMap;
-import java.util.Map;
-
/** Tests that ensure appropriate settings are backed up. */
@Presubmit
@RunWith(AndroidJUnit4.class)
@@ -488,22 +485,20 @@ public class DeviceConfigTest {
}
@Test
- public void setProperties() {
- Map<String, String> keyValues = new HashMap<>();
- keyValues.put(KEY, VALUE);
- keyValues.put(KEY2, VALUE2);
+ public void setProperties() throws DeviceConfig.BadConfigException {
+ Properties properties = new Properties.Builder(NAMESPACE).setString(KEY, VALUE)
+ .setString(KEY2, VALUE2).build();
- DeviceConfig.setProperties(new Properties(NAMESPACE, keyValues));
- Properties properties = DeviceConfig.getProperties(NAMESPACE);
+ DeviceConfig.setProperties(properties);
+ properties = DeviceConfig.getProperties(NAMESPACE);
assertThat(properties.getKeyset()).containsExactly(KEY, KEY2);
assertThat(properties.getString(KEY, DEFAULT_VALUE)).isEqualTo(VALUE);
assertThat(properties.getString(KEY2, DEFAULT_VALUE)).isEqualTo(VALUE2);
- Map<String, String> newKeyValues = new HashMap<>();
- newKeyValues.put(KEY, VALUE2);
- newKeyValues.put(KEY3, VALUE3);
+ properties = new Properties.Builder(NAMESPACE).setString(KEY, VALUE2)
+ .setString(KEY3, VALUE3).build();
- DeviceConfig.setProperties(new Properties(NAMESPACE, newKeyValues));
+ DeviceConfig.setProperties(properties);
properties = DeviceConfig.getProperties(NAMESPACE);
assertThat(properties.getKeyset()).containsExactly(KEY, KEY3);
assertThat(properties.getString(KEY, DEFAULT_VALUE)).isEqualTo(VALUE2);
@@ -514,18 +509,15 @@ public class DeviceConfigTest {
}
@Test
- public void setProperties_multipleNamespaces() {
- Map<String, String> keyValues = new HashMap<>();
- keyValues.put(KEY, VALUE);
- keyValues.put(KEY2, VALUE2);
-
- Map<String, String> keyValues2 = new HashMap<>();
- keyValues2.put(KEY2, VALUE);
- keyValues2.put(KEY3, VALUE2);
-
+ public void setProperties_multipleNamespaces() throws DeviceConfig.BadConfigException {
final String namespace2 = "namespace2";
- DeviceConfig.setProperties(new Properties(NAMESPACE, keyValues));
- DeviceConfig.setProperties(new Properties(namespace2, keyValues2));
+ Properties properties1 = new Properties.Builder(NAMESPACE).setString(KEY, VALUE)
+ .setString(KEY2, VALUE2).build();
+ Properties properties2 = new Properties.Builder(namespace2).setString(KEY2, VALUE)
+ .setString(KEY3, VALUE2).build();
+
+ DeviceConfig.setProperties(properties1);
+ DeviceConfig.setProperties(properties2);
Properties properties = DeviceConfig.getProperties(NAMESPACE);
assertThat(properties.getKeyset()).containsExactly(KEY, KEY2);
@@ -549,6 +541,26 @@ public class DeviceConfigTest {
deleteViaContentProvider(namespace2, KEY3);
}
+ @Test
+ public void propertiesBuilder() {
+ boolean booleanValue = true;
+ int intValue = 123;
+ float floatValue = 4.56f;
+ long longValue = -789L;
+ String key4 = "key4";
+ String key5 = "key5";
+
+ Properties properties = new Properties.Builder(NAMESPACE).setString(KEY, VALUE)
+ .setBoolean(KEY2, booleanValue).setInt(KEY3, intValue).setLong(key4, longValue)
+ .setFloat(key5, floatValue).build();
+ assertThat(properties.getNamespace()).isEqualTo(NAMESPACE);
+ assertThat(properties.getString(KEY, "defaultValue")).isEqualTo(VALUE);
+ assertThat(properties.getBoolean(KEY2, false)).isEqualTo(booleanValue);
+ assertThat(properties.getInt(KEY3, 0)).isEqualTo(intValue);
+ assertThat(properties.getLong("key4", 0L)).isEqualTo(longValue);
+ assertThat(properties.getFloat("key5", 0f)).isEqualTo(floatValue);
+ }
+
// TODO(mpape): resolve b/142727848 and re-enable listener tests
// @Test
// public void onPropertiesChangedListener_setPropertyCallback() throws InterruptedException {
diff --git a/core/tests/coretests/src/android/util/CloseGuardTest.java b/core/tests/coretests/src/android/util/CloseGuardTest.java
new file mode 100644
index 000000000000..d86c7b79fad6
--- /dev/null
+++ b/core/tests/coretests/src/android/util/CloseGuardTest.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2019 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.util;
+
+import libcore.dalvik.system.CloseGuardSupport;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestRule;
+
+/** Unit tests for {@link android.util.CloseGuard} */
+public class CloseGuardTest {
+
+ @Rule
+ public final TestRule rule = CloseGuardSupport.getRule();
+
+ @Test
+ public void testEnabled_NotOpen() throws Throwable {
+ ResourceOwner owner = new ResourceOwner();
+ assertUnreleasedResources(owner, 0);
+ }
+
+ @Test
+ public void testEnabled_OpenNotClosed() throws Throwable {
+ ResourceOwner owner = new ResourceOwner();
+ owner.open();
+ assertUnreleasedResources(owner, 1);
+ }
+
+ @Test
+ public void testEnabled_OpenThenClosed() throws Throwable {
+ ResourceOwner owner = new ResourceOwner();
+ owner.open();
+ owner.close();
+ assertUnreleasedResources(owner, 0);
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void testOpen_withNullMethodName_throwsNPE() throws Throwable {
+ CloseGuard closeGuard = new CloseGuard();
+ closeGuard.open(null);
+ }
+
+ private void assertUnreleasedResources(ResourceOwner owner, int expectedCount)
+ throws Throwable {
+ try {
+ CloseGuardSupport.getFinalizerChecker().accept(owner, expectedCount);
+ } finally {
+ // Close the resource so that CloseGuard does not generate a warning for real when it
+ // is actually finalized.
+ owner.close();
+ }
+ }
+
+ /**
+ * A test user of {@link CloseGuard}.
+ */
+ private static class ResourceOwner {
+
+ private final CloseGuard mCloseGuard;
+
+ ResourceOwner() {
+ mCloseGuard = new CloseGuard();
+ }
+
+ public void open() {
+ mCloseGuard.open("close");
+ }
+
+ public void close() {
+ mCloseGuard.close();
+ }
+
+ /**
+ * Make finalize public so that it can be tested directly without relying on garbage
+ * collection to trigger it.
+ */
+ @Override
+ public void finalize() throws Throwable {
+ mCloseGuard.warnIfOpen();
+ super.finalize();
+ }
+ }
+}
diff --git a/core/tests/coretests/src/android/util/StatsEventTest.java b/core/tests/coretests/src/android/util/StatsEventTest.java
index 097badadcea9..ac25e2734ac9 100644
--- a/core/tests/coretests/src/android/util/StatsEventTest.java
+++ b/core/tests/coretests/src/android/util/StatsEventTest.java
@@ -44,7 +44,7 @@ public class StatsEventTest {
@Test
public void testNoFields() {
final long minTimestamp = SystemClock.elapsedRealtimeNanos();
- final StatsEvent statsEvent = StatsEvent.newBuilder().build();
+ final StatsEvent statsEvent = StatsEvent.newBuilder().usePooledBuffer().build();
final long maxTimestamp = SystemClock.elapsedRealtimeNanos();
final int expectedAtomId = 0;
@@ -99,6 +99,7 @@ public class StatsEventTest {
.writeBoolean(field2)
.writeInt(field3)
.writeInt(field4)
+ .usePooledBuffer()
.build();
final long maxTimestamp = SystemClock.elapsedRealtimeNanos();
@@ -167,6 +168,7 @@ public class StatsEventTest {
.writeString(field1)
.writeFloat(field2)
.writeByteArray(field3)
+ .usePooledBuffer()
.build();
final long maxTimestamp = SystemClock.elapsedRealtimeNanos();
@@ -230,6 +232,7 @@ public class StatsEventTest {
.setAtomId(expectedAtomId)
.writeAttributionChain(uids, tags)
.writeLong(field2)
+ .usePooledBuffer()
.build();
final long maxTimestamp = SystemClock.elapsedRealtimeNanos();
@@ -299,6 +302,7 @@ public class StatsEventTest {
final StatsEvent statsEvent = StatsEvent.newBuilder()
.setAtomId(expectedAtomId)
.writeKeyValuePairs(intMap, longMap, stringMap, floatMap)
+ .usePooledBuffer()
.build();
final long maxTimestamp = SystemClock.elapsedRealtimeNanos();
@@ -392,6 +396,7 @@ public class StatsEventTest {
.addBooleanAnnotation(field1AnnotationId, field1AnnotationValue)
.writeBoolean(field2)
.addIntAnnotation(field2AnnotationId, field2AnnotationValue)
+ .usePooledBuffer()
.build();
final long maxTimestamp = SystemClock.elapsedRealtimeNanos();
diff --git a/core/tests/coretests/src/android/view/InsetsAnimationControlImplTest.java b/core/tests/coretests/src/android/view/InsetsAnimationControlImplTest.java
index 1a482604d782..68d95cd38497 100644
--- a/core/tests/coretests/src/android/view/InsetsAnimationControlImplTest.java
+++ b/core/tests/coretests/src/android/view/InsetsAnimationControlImplTest.java
@@ -19,11 +19,9 @@ package android.view;
import static android.view.InsetsState.ITYPE_NAVIGATION_BAR;
import static android.view.InsetsState.ITYPE_STATUS_BAR;
import static android.view.ViewRootImpl.NEW_INSETS_MODE_FULL;
-import static android.view.WindowInsets.Type.navigationBars;
import static android.view.WindowInsets.Type.systemBars;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.eq;
@@ -118,7 +116,8 @@ public class InsetsAnimationControlImplTest {
consumers.put(ITYPE_NAVIGATION_BAR, navConsumer);
mController = new InsetsAnimationControlImpl(consumers,
new Rect(0, 0, 500, 500), mInsetsState, mMockListener, systemBars(),
- () -> mMockTransactionApplier, mMockController);
+ () -> mMockTransactionApplier, mMockController, 10 /* durationMs */,
+ false /* fade */);
}
@Test
@@ -131,9 +130,11 @@ public class InsetsAnimationControlImplTest {
@Test
public void testChangeInsets() {
- mController.changeInsets(Insets.of(0, 30, 40, 0));
+ mController.setInsetsAndAlpha(Insets.of(0, 30, 40, 0), 1f /* alpha */,
+ 0f /* fraction */);
mController.applyChangeInsets(new InsetsState());
assertEquals(Insets.of(0, 30, 40, 0), mController.getCurrentInsets());
+ assertEquals(1f, mController.getCurrentAlpha(), 1f - mController.getCurrentAlpha());
ArgumentCaptor<SurfaceParams> captor = ArgumentCaptor.forClass(SurfaceParams.class);
verify(mMockTransactionApplier).scheduleApply(captor.capture());
@@ -148,26 +149,43 @@ public class InsetsAnimationControlImplTest {
}
@Test
+ public void testChangeAlphaNoInsets() {
+ Insets initialInsets = mController.getCurrentInsets();
+ mController.setInsetsAndAlpha(null, 0.5f, 0f /* fraction*/);
+ mController.applyChangeInsets(new InsetsState());
+ assertEquals(0.5f, mController.getCurrentAlpha(), 0.5f - mController.getCurrentAlpha());
+ assertEquals(initialInsets, mController.getCurrentInsets());
+ }
+
+ @Test
+ public void testChangeInsetsAndAlpha() {
+ mController.setInsetsAndAlpha(Insets.of(0, 30, 40, 0), 0.5f, 1f);
+ mController.applyChangeInsets(new InsetsState());
+ assertEquals(0.5f, mController.getCurrentAlpha(), 0.5f - mController.getCurrentAlpha());
+ assertEquals(Insets.of(0, 30, 40, 0), mController.getCurrentInsets());
+ }
+
+ @Test
public void testFinishing() {
when(mMockController.getState()).thenReturn(mInsetsState);
- mController.finish(navigationBars());
+ mController.finish(true /* shown */);
mController.applyChangeInsets(mInsetsState);
- assertFalse(mInsetsState.getSource(ITYPE_STATUS_BAR).isVisible());
+ assertTrue(mInsetsState.getSource(ITYPE_STATUS_BAR).isVisible());
assertTrue(mInsetsState.getSource(ITYPE_NAVIGATION_BAR).isVisible());
- assertEquals(Insets.of(0, 0, 100, 0), mController.getCurrentInsets());
- verify(mMockController).notifyFinished(eq(mController), eq(navigationBars()));
+ assertEquals(Insets.of(0, 100, 100, 0), mController.getCurrentInsets());
+ verify(mMockController).notifyFinished(eq(mController), eq(true /* shown */));
}
@Test
public void testCancelled() {
mController.onCancelled();
try {
- mController.changeInsets(Insets.NONE);
+ mController.setInsetsAndAlpha(Insets.NONE, 1f /*alpha */, 0f /* fraction */);
fail("Expected exception to be thrown");
} catch (IllegalStateException ignored) {
}
verify(mMockListener).onCancelled();
- mController.finish(navigationBars());
+ mController.finish(true /* shown */);
}
private void assertPosition(Matrix m, Rect original, Rect transformed) {
diff --git a/core/tests/coretests/src/android/view/InsetsControllerTest.java b/core/tests/coretests/src/android/view/InsetsControllerTest.java
index e4d8279a52cd..a89fc1e6315f 100644
--- a/core/tests/coretests/src/android/view/InsetsControllerTest.java
+++ b/core/tests/coretests/src/android/view/InsetsControllerTest.java
@@ -123,7 +123,7 @@ public class InsetsControllerTest {
WindowInsetsAnimationControlListener mockListener =
mock(WindowInsetsAnimationControlListener.class);
- mController.controlWindowInsetsAnimation(statusBars(), mockListener);
+ mController.controlWindowInsetsAnimation(statusBars(), 10 /* durationMs */, mockListener);
verify(mockListener).onReady(any(), anyInt());
mController.onControlsChanged(new InsetsSourceControl[0]);
verify(mockListener).onCancelled();
@@ -135,7 +135,7 @@ public class InsetsControllerTest {
mController.getState().setDisplayFrame(new Rect(0, 0, 200, 200));
WindowInsetsAnimationControlListener controlListener =
mock(WindowInsetsAnimationControlListener.class);
- mController.controlWindowInsetsAnimation(0, controlListener);
+ mController.controlWindowInsetsAnimation(0, 0 /* durationMs */, controlListener);
verify(controlListener).onCancelled();
verify(controlListener, never()).onReady(any(), anyInt());
}
@@ -331,12 +331,13 @@ public class InsetsControllerTest {
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
WindowInsetsAnimationControlListener mockListener =
mock(WindowInsetsAnimationControlListener.class);
- mController.controlWindowInsetsAnimation(statusBars(), mockListener);
+ mController.controlWindowInsetsAnimation(statusBars(), 0 /* durationMs */,
+ mockListener);
ArgumentCaptor<WindowInsetsAnimationController> controllerCaptor =
ArgumentCaptor.forClass(WindowInsetsAnimationController.class);
verify(mockListener).onReady(controllerCaptor.capture(), anyInt());
- controllerCaptor.getValue().finish(0 /* shownTypes */);
+ controllerCaptor.getValue().finish(false /* shown */);
});
waitUntilNextFrame();
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
diff --git a/core/tests/coretests/src/android/view/ViewRootImplTest.java b/core/tests/coretests/src/android/view/ViewRootImplTest.java
index 9a5784774d1c..cf5d079ba688 100644
--- a/core/tests/coretests/src/android/view/ViewRootImplTest.java
+++ b/core/tests/coretests/src/android/view/ViewRootImplTest.java
@@ -16,13 +16,25 @@
package android.view;
+import static android.view.View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
+import static android.view.View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
+import static android.view.WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
+import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
+import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION;
+import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
+import static android.view.WindowManager.LayoutParams.TYPE_TOAST;
+
import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
+import static org.junit.Assume.assumeTrue;
import android.content.Context;
import android.graphics.Insets;
import android.graphics.Rect;
import android.platform.test.annotations.Presubmit;
+import android.view.WindowInsets.Side;
+import android.view.WindowInsets.Type;
import androidx.test.InstrumentationRegistry;
import androidx.test.filters.SmallTest;
@@ -55,6 +67,8 @@ public class ViewRootImplTest {
@Test
public void negativeInsets_areSetToZero() throws Exception {
+ assumeTrue(ViewRootImpl.sNewInsetsMode != ViewRootImpl.NEW_INSETS_MODE_FULL);
+
mViewRootImpl.getAttachInfo().getContentInsets().set(-10, -20, -30 , -40);
mViewRootImpl.getAttachInfo().getStableInsets().set(-10, -20, -30 , -40);
final WindowInsets insets = mViewRootImpl.getWindowInsets(true /* forceConstruct */);
@@ -65,6 +79,8 @@ public class ViewRootImplTest {
@Test
public void negativeInsets_areSetToZero_positiveAreLeftAsIs() throws Exception {
+ assumeTrue(ViewRootImpl.sNewInsetsMode != ViewRootImpl.NEW_INSETS_MODE_FULL);
+
mViewRootImpl.getAttachInfo().getContentInsets().set(-10, 20, -30 , 40);
mViewRootImpl.getAttachInfo().getStableInsets().set(10, -20, 30 , -40);
final WindowInsets insets = mViewRootImpl.getWindowInsets(true /* forceConstruct */);
@@ -75,6 +91,8 @@ public class ViewRootImplTest {
@Test
public void positiveInsets_areLeftAsIs() throws Exception {
+ assumeTrue(ViewRootImpl.sNewInsetsMode != ViewRootImpl.NEW_INSETS_MODE_FULL);
+
mViewRootImpl.getAttachInfo().getContentInsets().set(10, 20, 30 , 40);
mViewRootImpl.getAttachInfo().getStableInsets().set(10, 20, 30 , 40);
final WindowInsets insets = mViewRootImpl.getWindowInsets(true /* forceConstruct */);
@@ -83,6 +101,80 @@ public class ViewRootImplTest {
assertThat(insets.getStableInsets(), equalTo(Insets.of(10, 20, 30, 40)));
}
+ @Test
+ public void adjustLayoutParamsForInsets_layoutFullscreen() {
+ assumeTrue(ViewRootImpl.sNewInsetsMode == ViewRootImpl.NEW_INSETS_MODE_FULL);
+
+ final WindowManager.LayoutParams attrs = new WindowManager.LayoutParams(TYPE_APPLICATION);
+ attrs.systemUiVisibility = SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
+ ViewRootImpl.adjustLayoutParamsForCompatibility(attrs);
+
+ assertEquals(0, attrs.getFitWindowInsetsTypes() & Type.statusBars());
+ }
+
+ @Test
+ public void adjustLayoutParamsForInsets_layoutInScreen() {
+ assumeTrue(ViewRootImpl.sNewInsetsMode == ViewRootImpl.NEW_INSETS_MODE_FULL);
+
+ final WindowManager.LayoutParams attrs = new WindowManager.LayoutParams(TYPE_APPLICATION);
+ attrs.flags = FLAG_LAYOUT_IN_SCREEN;
+ ViewRootImpl.adjustLayoutParamsForCompatibility(attrs);
+
+ assertEquals(0, attrs.getFitWindowInsetsTypes() & Type.statusBars());
+ }
+
+ @Test
+ public void adjustLayoutParamsForInsets_layoutHideNavigation() {
+ assumeTrue(ViewRootImpl.sNewInsetsMode == ViewRootImpl.NEW_INSETS_MODE_FULL);
+
+ final WindowManager.LayoutParams attrs = new WindowManager.LayoutParams(TYPE_APPLICATION);
+ attrs.systemUiVisibility = SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
+ ViewRootImpl.adjustLayoutParamsForCompatibility(attrs);
+
+ assertEquals(0, attrs.getFitWindowInsetsTypes() & Type.systemBars());
+ }
+
+ @Test
+ public void adjustLayoutParamsForInsets_toast() {
+ assumeTrue(ViewRootImpl.sNewInsetsMode == ViewRootImpl.NEW_INSETS_MODE_FULL);
+
+ final WindowManager.LayoutParams attrs = new WindowManager.LayoutParams(TYPE_TOAST);
+ ViewRootImpl.adjustLayoutParamsForCompatibility(attrs);
+
+ assertEquals(Type.systemBars(), attrs.getFitWindowInsetsTypes() & Type.systemBars());
+ assertEquals(true, attrs.getFitIgnoreVisibility());
+ }
+
+ @Test
+ public void adjustLayoutParamsForInsets_systemAlert() {
+ assumeTrue(ViewRootImpl.sNewInsetsMode == ViewRootImpl.NEW_INSETS_MODE_FULL);
+
+ final WindowManager.LayoutParams attrs = new WindowManager.LayoutParams(TYPE_SYSTEM_ALERT);
+ ViewRootImpl.adjustLayoutParamsForCompatibility(attrs);
+
+ assertEquals(Type.systemBars(), attrs.getFitWindowInsetsTypes() & Type.systemBars());
+ assertEquals(true, attrs.getFitIgnoreVisibility());
+ }
+
+ @Test
+ public void adjustLayoutParamsForInsets_noAdjust() {
+ assumeTrue(ViewRootImpl.sNewInsetsMode == ViewRootImpl.NEW_INSETS_MODE_FULL);
+
+ final WindowManager.LayoutParams attrs = new WindowManager.LayoutParams(TYPE_APPLICATION);
+ final int types = Type.all();
+ final int sides = Side.TOP | Side.LEFT;
+ final boolean fitMaxInsets = true;
+ attrs.flags = FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
+ attrs.setFitWindowInsetsTypes(types);
+ attrs.setFitWindowInsetsSides(sides);
+ attrs.setFitIgnoreVisibility(fitMaxInsets);
+ ViewRootImpl.adjustLayoutParamsForCompatibility(attrs);
+
+ assertEquals(types, attrs.getFitWindowInsetsTypes());
+ assertEquals(sides, attrs.getFitWindowInsetsSides());
+ assertEquals(fitMaxInsets, attrs.getFitIgnoreVisibility());
+ }
+
private static class ViewRootImplAccessor {
private final ViewRootImpl mViewRootImpl;
diff --git a/core/tests/coretests/src/android/view/accessibility/AccessibilityCacheTest.java b/core/tests/coretests/src/android/view/accessibility/AccessibilityCacheTest.java
index 6bce6517a85d..0d5db6d791f1 100644
--- a/core/tests/coretests/src/android/view/accessibility/AccessibilityCacheTest.java
+++ b/core/tests/coretests/src/android/view/accessibility/AccessibilityCacheTest.java
@@ -436,6 +436,22 @@ public class AccessibilityCacheTest {
}
@Test
+ public void windowsChangedWithWindowsChangeA11yFocusedEvent_dontClearCache() {
+ AccessibilityNodeInfo nodeInfo = getNodeWithA11yAndWindowId(SINGLE_VIEW_ID, WINDOW_ID_1);
+ mAccessibilityCache.add(nodeInfo);
+ AccessibilityEvent event = new AccessibilityEvent(AccessibilityEvent.TYPE_WINDOWS_CHANGED);
+ event.setWindowChanges(AccessibilityEvent.WINDOWS_CHANGE_ACCESSIBILITY_FOCUSED);
+ mAccessibilityCache.onAccessibilityEvent(event);
+ AccessibilityNodeInfo cachedNode = mAccessibilityCache.getNode(WINDOW_ID_1,
+ nodeInfo.getSourceNodeId());
+ try {
+ assertNotNull(cachedNode);
+ } finally {
+ nodeInfo.recycle();
+ }
+ }
+
+ @Test
public void subTreeChangeEvent_clearsNodeAndChild() {
AccessibilityEvent event = AccessibilityEvent
.obtain(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
diff --git a/core/tests/coretests/src/android/view/textclassifier/ConfigParserTest.java b/core/tests/coretests/src/android/view/textclassifier/ConfigParserTest.java
deleted file mode 100644
index d54ce51c3c37..000000000000
--- a/core/tests/coretests/src/android/view/textclassifier/ConfigParserTest.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright (C) 2019 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.view.textclassifier;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.provider.DeviceConfig;
-import android.support.test.uiautomator.UiDevice;
-
-import androidx.test.InstrumentationRegistry;
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.IOException;
-import java.util.function.Supplier;
-
-@SmallTest
-@RunWith(AndroidJUnit4.class)
-public class ConfigParserTest {
- private static final Supplier<String> SETTINGS =
- () -> "int=42,float=12.3,boolean=true,string=abc";
- private static final String CLEAR_DEVICE_CONFIG_KEY_CMD =
- "device_config delete " + DeviceConfig.NAMESPACE_TEXTCLASSIFIER;
- private static final String[] DEVICE_CONFIG_KEYS = new String[]{
- "boolean",
- "string",
- "int",
- "float"
- };
-
- private ConfigParser mConfigParser;
-
- @Before
- public void setup() throws IOException {
- mConfigParser = new ConfigParser(SETTINGS);
- clearDeviceConfig();
- }
-
- @After
- public void tearDown() throws IOException {
- clearDeviceConfig();
- }
-
- @Test
- public void getBoolean_deviceConfig() {
- DeviceConfig.setProperty(
- DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- "boolean",
- "false",
- false);
- boolean value = mConfigParser.getBoolean("boolean", true);
- assertThat(value).isFalse();
- }
-
- @Test
- public void getBoolean_settings() {
- boolean value = mConfigParser.getBoolean(
- "boolean",
- false);
- assertThat(value).isTrue();
- }
-
- @Test
- public void getInt_deviceConfig() {
- DeviceConfig.setProperty(
- DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- "int",
- "1",
- false);
- int value = mConfigParser.getInt("int", 0);
- assertThat(value).isEqualTo(1);
- }
-
- @Test
- public void getInt_settings() {
- int value = mConfigParser.getInt("int", 0);
- assertThat(value).isEqualTo(42);
- }
-
- @Test
- public void getFloat_deviceConfig() {
- DeviceConfig.setProperty(
- DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- "float",
- "3.14",
- false);
- float value = mConfigParser.getFloat("float", 0);
- assertThat(value).isWithin(0.0001f).of(3.14f);
- }
-
- @Test
- public void getFloat_settings() {
- float value = mConfigParser.getFloat("float", 0);
- assertThat(value).isWithin(0.0001f).of(12.3f);
- }
-
- @Test
- public void getString_deviceConfig() {
- DeviceConfig.setProperty(
- DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- "string",
- "hello",
- false);
- String value = mConfigParser.getString("string", "");
- assertThat(value).isEqualTo("hello");
- }
-
- @Test
- public void getString_settings() {
- String value = mConfigParser.getString("string", "");
- assertThat(value).isEqualTo("abc");
- }
-
- private static void clearDeviceConfig() throws IOException {
- UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
- for (String key : DEVICE_CONFIG_KEYS) {
- uiDevice.executeShellCommand(CLEAR_DEVICE_CONFIG_KEY_CMD + " " + key);
- }
- }
-}
diff --git a/core/tests/coretests/src/android/view/textclassifier/TextClassificationConstantsTest.java b/core/tests/coretests/src/android/view/textclassifier/TextClassificationConstantsTest.java
index 64fb14190ce2..82fa73f76207 100644
--- a/core/tests/coretests/src/android/view/textclassifier/TextClassificationConstantsTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/TextClassificationConstantsTest.java
@@ -16,230 +16,141 @@
package android.view.textclassifier;
+import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
+import android.provider.DeviceConfig;
+
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
-import org.junit.Assert;
+import com.google.common.primitives.Floats;
+
import org.junit.Test;
import org.junit.runner.RunWith;
@SmallTest
@RunWith(AndroidJUnit4.class)
public class TextClassificationConstantsTest {
-
private static final float EPSILON = 0.0001f;
@Test
- public void testLoadFromString() {
- final String s = "local_textclassifier_enabled=true,"
- + "system_textclassifier_enabled=true,"
- + "model_dark_launch_enabled=true,"
- + "smart_selection_enabled=true,"
- + "smart_text_share_enabled=true,"
- + "smart_linkify_enabled=true,"
- + "smart_select_animation_enabled=true,"
- + "suggest_selection_max_range_length=10,"
- + "classify_text_max_range_length=11,"
- + "generate_links_max_text_length=12,"
- + "generate_links_log_sample_rate=13,"
- + "entity_list_default=phone,"
- + "entity_list_not_editable=address:flight,"
- + "entity_list_editable=date:datetime,"
- + "in_app_conversation_action_types_default=text_reply,"
- + "notification_conversation_action_types_default=send_email:call_phone,"
- + "lang_id_threshold_override=0.3,"
- + "lang_id_context_settings=10:1:0.5,"
- + "detect_language_from_text_enabled=true,"
- + "template_intent_factory_enabled=true,"
- + "translate_in_classification_enabled=true";
- final TextClassificationConstants constants = new TextClassificationConstants(() -> s);
-
- assertWithMessage("local_textclassifier_enabled")
- .that(constants.isLocalTextClassifierEnabled()).isTrue();
- assertWithMessage("system_textclassifier_enabled")
- .that(constants.isSystemTextClassifierEnabled()).isTrue();
- assertWithMessage("model_dark_launch_enabled")
- .that(constants.isModelDarkLaunchEnabled()).isTrue();
- assertWithMessage("smart_selection_enabled")
- .that(constants.isSmartSelectionEnabled()).isTrue();
- assertWithMessage("smart_text_share_enabled")
- .that(constants.isSmartTextShareEnabled()).isTrue();
- assertWithMessage("smart_linkify_enabled")
- .that(constants.isSmartLinkifyEnabled()).isTrue();
- assertWithMessage("smart_select_animation_enabled")
- .that(constants.isSmartSelectionAnimationEnabled()).isTrue();
- assertWithMessage("suggest_selection_max_range_length")
- .that(constants.getSuggestSelectionMaxRangeLength()).isEqualTo(10);
- assertWithMessage("classify_text_max_range_length")
- .that(constants.getClassifyTextMaxRangeLength()).isEqualTo(11);
- assertWithMessage("generate_links_max_text_length")
- .that(constants.getGenerateLinksMaxTextLength()).isEqualTo(12);
- assertWithMessage("generate_links_log_sample_rate")
- .that(constants.getGenerateLinksLogSampleRate()).isEqualTo(13);
- assertWithMessage("entity_list_default")
- .that(constants.getEntityListDefault())
- .containsExactly("phone");
- assertWithMessage("entity_list_not_editable")
- .that(constants.getEntityListNotEditable())
- .containsExactly("address", "flight");
- assertWithMessage("entity_list_editable")
- .that(constants.getEntityListEditable())
- .containsExactly("date", "datetime");
- assertWithMessage("in_app_conversation_action_types_default")
- .that(constants.getInAppConversationActionTypes())
- .containsExactly("text_reply");
- assertWithMessage("notification_conversation_action_types_default")
- .that(constants.getNotificationConversationActionTypes())
- .containsExactly("send_email", "call_phone");
- assertWithMessage("lang_id_threshold_override")
- .that(constants.getLangIdThresholdOverride()).isWithin(EPSILON).of(0.3f);
- Assert.assertArrayEquals("lang_id_context_settings",
- constants.getLangIdContextSettings(), new float[]{10, 1, 0.5f}, EPSILON);
- assertWithMessage("detect_language_from_text_enabled")
- .that(constants.isLocalTextClassifierEnabled()).isTrue();
- assertWithMessage("template_intent_factory_enabled")
- .that(constants.isLocalTextClassifierEnabled()).isTrue();
- assertWithMessage("translate_in_classification_enabled")
- .that(constants.isLocalTextClassifierEnabled()).isTrue();
+ public void testLoadFromDeviceConfig_booleanValue() throws Exception {
+ // Saves config original value.
+ final String originalValue = DeviceConfig.getProperty(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
+ TextClassificationConstants.LOCAL_TEXT_CLASSIFIER_ENABLED);
+
+ final TextClassificationConstants constants = new TextClassificationConstants();
+ try {
+ // Sets and checks different value.
+ setDeviceConfig(TextClassificationConstants.LOCAL_TEXT_CLASSIFIER_ENABLED, "false");
+ assertWithMessage(TextClassificationConstants.LOCAL_TEXT_CLASSIFIER_ENABLED)
+ .that(constants.isLocalTextClassifierEnabled()).isFalse();
+ } finally {
+ // Restores config original value.
+ setDeviceConfig(TextClassificationConstants.LOCAL_TEXT_CLASSIFIER_ENABLED,
+ originalValue);
+ }
+ }
+
+ @Test
+ public void testLoadFromDeviceConfig_IntValue() throws Exception {
+ // Saves config original value.
+ final String originalValue = DeviceConfig.getProperty(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
+ TextClassificationConstants.SUGGEST_SELECTION_MAX_RANGE_LENGTH);
+
+ final TextClassificationConstants constants = new TextClassificationConstants();
+ try {
+ // Sets and checks different value.
+ setDeviceConfig(TextClassificationConstants.SUGGEST_SELECTION_MAX_RANGE_LENGTH, "8");
+ assertWithMessage(TextClassificationConstants.SUGGEST_SELECTION_MAX_RANGE_LENGTH)
+ .that(constants.getSuggestSelectionMaxRangeLength()).isEqualTo(8);
+ } finally {
+ // Restores config original value.
+ setDeviceConfig(TextClassificationConstants.SUGGEST_SELECTION_MAX_RANGE_LENGTH,
+ originalValue);
+ }
+ }
+
+ @Test
+ public void testLoadFromDeviceConfig_StringValue() throws Exception {
+ // Saves config original value.
+ final String originalValue = DeviceConfig.getProperty(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
+ TextClassificationConstants.TEXT_CLASSIFIER_SERVICE_PACKAGE_OVERRIDE);
+
+ final TextClassificationConstants constants = new TextClassificationConstants();
+ try {
+ // Sets and checks different value.
+ final String testTextClassifier = "com.example.textclassifier";
+ setDeviceConfig(TextClassificationConstants.TEXT_CLASSIFIER_SERVICE_PACKAGE_OVERRIDE,
+ testTextClassifier);
+ assertWithMessage(TextClassificationConstants.TEXT_CLASSIFIER_SERVICE_PACKAGE_OVERRIDE)
+ .that(constants.getTextClassifierServicePackageOverride()).isEqualTo(
+ testTextClassifier);
+ } finally {
+ // Restores config original value.
+ setDeviceConfig(TextClassificationConstants.TEXT_CLASSIFIER_SERVICE_PACKAGE_OVERRIDE,
+ originalValue);
+ }
+ }
+
+ @Test
+ public void testLoadFromDeviceConfig_FloatValue() throws Exception {
+ // Saves config original value.
+ final String originalValue = DeviceConfig.getProperty(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
+ TextClassificationConstants.LANG_ID_THRESHOLD_OVERRIDE);
+
+ final TextClassificationConstants constants = new TextClassificationConstants();
+ try {
+ // Sets and checks different value.
+ setDeviceConfig(TextClassificationConstants.LANG_ID_THRESHOLD_OVERRIDE, "2");
+ assertWithMessage(TextClassificationConstants.LANG_ID_THRESHOLD_OVERRIDE)
+ .that(constants.getLangIdThresholdOverride()).isWithin(EPSILON).of(2f);
+ } finally {
+ // Restores config original value.
+ setDeviceConfig(TextClassificationConstants.LANG_ID_THRESHOLD_OVERRIDE, originalValue);
+ }
}
@Test
- public void testLoadFromString_differentValues() {
- final String testTextClassifier = "com.example.textclassifier";
- final String s = "local_textclassifier_enabled=false,"
- + "system_textclassifier_enabled=false,"
- + "model_dark_launch_enabled=false,"
- + "smart_selection_enabled=false,"
- + "smart_text_share_enabled=false,"
- + "smart_linkify_enabled=false,"
- + "smart_select_animation_enabled=false,"
- + "suggest_selection_max_range_length=8,"
- + "classify_text_max_range_length=7,"
- + "generate_links_max_text_length=6,"
- + "generate_links_log_sample_rate=5,"
- + "entity_list_default=email:url,"
- + "entity_list_not_editable=date,"
- + "entity_list_editable=flight,"
- + "in_app_conversation_action_types_default=view_map:track_flight,"
- + "notification_conversation_action_types_default=share_location,"
- + "lang_id_threshold_override=2,"
- + "lang_id_context_settings=30:0.5:0.3,"
- + "detect_language_from_text_enabled=false,"
- + "template_intent_factory_enabled=false,"
- + "textclassifier_service_package_override=" + testTextClassifier + ","
- + "translate_in_classification_enabled=false";
- final TextClassificationConstants constants = new TextClassificationConstants(() -> s);
-
- assertWithMessage("local_textclassifier_enabled")
- .that(constants.isLocalTextClassifierEnabled()).isFalse();
- assertWithMessage("system_textclassifier_enabled")
- .that(constants.isSystemTextClassifierEnabled()).isFalse();
- assertWithMessage("model_dark_launch_enabled")
- .that(constants.isModelDarkLaunchEnabled()).isFalse();
- assertWithMessage("smart_selection_enabled")
- .that(constants.isSmartSelectionEnabled()).isFalse();
- assertWithMessage("smart_text_share_enabled")
- .that(constants.isSmartTextShareEnabled()).isFalse();
- assertWithMessage("smart_linkify_enabled")
- .that(constants.isSmartLinkifyEnabled()).isFalse();
- assertWithMessage("smart_select_animation_enabled")
- .that(constants.isSmartSelectionAnimationEnabled()).isFalse();
- assertWithMessage("suggest_selection_max_range_length")
- .that(constants.getSuggestSelectionMaxRangeLength()).isEqualTo(8);
- assertWithMessage("classify_text_max_range_length")
- .that(constants.getClassifyTextMaxRangeLength()).isEqualTo(7);
- assertWithMessage("generate_links_max_text_length")
- .that(constants.getGenerateLinksMaxTextLength()).isEqualTo(6);
- assertWithMessage("generate_links_log_sample_rate")
- .that(constants.getGenerateLinksLogSampleRate()).isEqualTo(5);
- assertWithMessage("entity_list_default")
- .that(constants.getEntityListDefault())
- .containsExactly("email", "url");
- assertWithMessage("entity_list_not_editable")
- .that(constants.getEntityListNotEditable())
- .containsExactly("date");
- assertWithMessage("entity_list_editable")
- .that(constants.getEntityListEditable())
- .containsExactly("flight");
- assertWithMessage("in_app_conversation_action_types_default")
- .that(constants.getInAppConversationActionTypes())
- .containsExactly("view_map", "track_flight");
- assertWithMessage("notification_conversation_action_types_default")
- .that(constants.getNotificationConversationActionTypes())
- .containsExactly("share_location");
- assertWithMessage("lang_id_threshold_override")
- .that(constants.getLangIdThresholdOverride()).isWithin(EPSILON).of(2f);
- Assert.assertArrayEquals("lang_id_context_settings",
- constants.getLangIdContextSettings(), new float[]{30, 0.5f, 0.3f}, EPSILON);
- assertWithMessage("detect_language_from_text_enabled")
- .that(constants.isLocalTextClassifierEnabled()).isFalse();
- assertWithMessage("template_intent_factory_enabled")
- .that(constants.isLocalTextClassifierEnabled()).isFalse();
- assertWithMessage("translate_in_classification_enabled")
- .that(constants.isLocalTextClassifierEnabled()).isFalse();
- assertWithMessage("textclassifier_service_package_override")
- .that(constants.getTextClassifierServiceName()).isEqualTo(
- testTextClassifier);
+ public void testLoadFromDeviceConfig_StringList() throws Exception {
+ // Saves config original value.
+ final String originalValue = DeviceConfig.getProperty(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
+ TextClassificationConstants.ENTITY_LIST_DEFAULT);
+
+ final TextClassificationConstants constants = new TextClassificationConstants();
+ try {
+ // Sets and checks different value.
+ setDeviceConfig(TextClassificationConstants.ENTITY_LIST_DEFAULT, "email:url");
+ assertWithMessage(TextClassificationConstants.ENTITY_LIST_DEFAULT)
+ .that(constants.getEntityListDefault())
+ .containsExactly("email", "url");
+ } finally {
+ // Restores config original value.
+ setDeviceConfig(TextClassificationConstants.ENTITY_LIST_DEFAULT, originalValue);
+ }
}
@Test
- public void testLoadFromString_defaultValues() {
- final TextClassificationConstants constants = new TextClassificationConstants(() -> "");
-
- assertWithMessage("local_textclassifier_enabled")
- .that(constants.isLocalTextClassifierEnabled()).isTrue();
- assertWithMessage("system_textclassifier_enabled")
- .that(constants.isSystemTextClassifierEnabled()).isTrue();
- assertWithMessage("model_dark_launch_enabled")
- .that(constants.isModelDarkLaunchEnabled()).isFalse();
- assertWithMessage("smart_selection_enabled")
- .that(constants.isSmartSelectionEnabled()).isTrue();
- assertWithMessage("smart_text_share_enabled")
- .that(constants.isSmartTextShareEnabled()).isTrue();
- assertWithMessage("smart_linkify_enabled")
- .that(constants.isSmartLinkifyEnabled()).isTrue();
- assertWithMessage("smart_select_animation_enabled")
- .that(constants.isSmartSelectionAnimationEnabled()).isTrue();
- assertWithMessage("suggest_selection_max_range_length")
- .that(constants.getSuggestSelectionMaxRangeLength()).isEqualTo(10 * 1000);
- assertWithMessage("classify_text_max_range_length")
- .that(constants.getClassifyTextMaxRangeLength()).isEqualTo(10 * 1000);
- assertWithMessage("generate_links_max_text_length")
- .that(constants.getGenerateLinksMaxTextLength()).isEqualTo(100 * 1000);
- assertWithMessage("generate_links_log_sample_rate")
- .that(constants.getGenerateLinksLogSampleRate()).isEqualTo(100);
- assertWithMessage("entity_list_default")
- .that(constants.getEntityListDefault())
- .containsExactly("address", "email", "url", "phone", "date", "datetime", "flight");
- assertWithMessage("entity_list_not_editable")
- .that(constants.getEntityListNotEditable())
- .containsExactly("address", "email", "url", "phone", "date", "datetime", "flight");
- assertWithMessage("entity_list_editable")
- .that(constants.getEntityListEditable())
- .containsExactly("address", "email", "url", "phone", "date", "datetime", "flight");
- assertWithMessage("in_app_conversation_action_types_default")
- .that(constants.getInAppConversationActionTypes())
- .containsExactly("text_reply", "create_reminder", "call_phone", "open_url",
- "send_email", "send_sms", "track_flight", "view_calendar", "view_map",
- "add_contact", "copy");
- assertWithMessage("notification_conversation_action_types_default")
- .that(constants.getNotificationConversationActionTypes())
- .containsExactly("text_reply", "create_reminder", "call_phone", "open_url",
- "send_email", "send_sms", "track_flight", "view_calendar", "view_map",
- "add_contact", "copy");
- assertWithMessage("lang_id_threshold_override")
- .that(constants.getLangIdThresholdOverride()).isWithin(EPSILON).of(-1f);
- Assert.assertArrayEquals("lang_id_context_settings",
- constants.getLangIdContextSettings(), new float[]{20, 1, 0.4f}, EPSILON);
- assertWithMessage("detect_language_from_text_enabled")
- .that(constants.isLocalTextClassifierEnabled()).isTrue();
- assertWithMessage("template_intent_factory_enabled")
- .that(constants.isLocalTextClassifierEnabled()).isTrue();
- assertWithMessage("translate_in_classification_enabled")
- .that(constants.isLocalTextClassifierEnabled()).isTrue();
- assertWithMessage("textclassifier_service_package_override")
- .that(constants.getTextClassifierServiceName()).isNull();
+ public void testLoadFromDeviceConfig_FloatList() throws Exception {
+ // Saves config original value.
+ final String originalValue = DeviceConfig.getProperty(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
+ TextClassificationConstants.LANG_ID_CONTEXT_SETTINGS);
+
+ final TextClassificationConstants constants = new TextClassificationConstants();
+ try {
+ // Sets and checks different value.
+ setDeviceConfig(TextClassificationConstants.LANG_ID_CONTEXT_SETTINGS, "30:0.5:0.3");
+ assertThat(Floats.asList(constants.getLangIdContextSettings())).containsExactly(30f,
+ 0.5f, 0.3f).inOrder();
+ } finally {
+ // Restores config original value.
+ setDeviceConfig(TextClassificationConstants.LANG_ID_CONTEXT_SETTINGS, originalValue);
+ }
+ }
+
+ private void setDeviceConfig(String key, String value) {
+ DeviceConfig.setProperty(DeviceConfig.NAMESPACE_TEXTCLASSIFIER, key,
+ value, /* makeDefault */ false);
}
}
diff --git a/core/tests/coretests/src/android/view/textclassifier/TextClassificationManagerTest.java b/core/tests/coretests/src/android/view/textclassifier/TextClassificationManagerTest.java
index b3f2bbe92c07..8faf790549d5 100644
--- a/core/tests/coretests/src/android/view/textclassifier/TextClassificationManagerTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/TextClassificationManagerTest.java
@@ -78,7 +78,7 @@ public class TextClassificationManagerTest {
TextClassifier fallback = TextClassifier.NO_OP;
TextClassifier classifier = new TextClassifierImpl(
- fakeContext, new TextClassificationConstants(() -> null), fallback);
+ fakeContext, new TextClassificationConstants(), fallback);
String text = "Contact me at +12122537077";
String classifiedText = "+12122537077";
diff --git a/core/tests/coretests/src/android/view/textclassifier/TextClassifierTest.java b/core/tests/coretests/src/android/view/textclassifier/TextClassifierTest.java
index deb0f182156e..2304ba6f6da4 100644
--- a/core/tests/coretests/src/android/view/textclassifier/TextClassifierTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/TextClassifierTest.java
@@ -69,7 +69,7 @@ public class TextClassifierTest {
public String mTextClassifierType;
private static final TextClassificationConstants TC_CONSTANTS =
- new TextClassificationConstants(() -> "");
+ new TextClassificationConstants();
private static final LocaleList LOCALES = LocaleList.forLanguageTags("en-US");
private static final String NO_TYPE = null;
diff --git a/core/tests/coretests/src/com/android/internal/accessibility/AccessibilityShortcutControllerTest.java b/core/tests/coretests/src/com/android/internal/accessibility/AccessibilityShortcutControllerTest.java
index 7b4054348642..82854e5b8a9d 100644
--- a/core/tests/coretests/src/com/android/internal/accessibility/AccessibilityShortcutControllerTest.java
+++ b/core/tests/coretests/src/com/android/internal/accessibility/AccessibilityShortcutControllerTest.java
@@ -20,6 +20,7 @@ import static android.provider.Settings.Secure.ACCESSIBILITY_SHORTCUT_DIALOG_SHO
import static android.provider.Settings.Secure.ACCESSIBILITY_SHORTCUT_ENABLED;
import static android.provider.Settings.Secure.ACCESSIBILITY_SHORTCUT_ON_LOCK_SCREEN;
import static android.provider.Settings.Secure.ACCESSIBILITY_SHORTCUT_TARGET_SERVICE;
+import static android.view.accessibility.AccessibilityManager.ACCESSIBILITY_SHORTCUT_KEY;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
@@ -49,8 +50,10 @@ import android.content.DialogInterface;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
+import android.content.pm.ServiceInfo;
import android.content.res.Resources;
import android.media.Ringtone;
+import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
@@ -157,9 +160,12 @@ public class AccessibilityShortcutControllerTest {
when(mFrameworkObjectProvider.getRingtone(eq(mContext), any())).thenReturn(mRingtone);
when(mResources.getString(anyInt())).thenReturn("Howdy %s");
+ when(mResources.getString(R.string.config_defaultAccessibilityService)).thenReturn(null);
when(mResources.getIntArray(anyInt())).thenReturn(VIBRATOR_PATTERN_INT);
ResolveInfo resolveInfo = mock(ResolveInfo.class);
+ resolveInfo.serviceInfo = mock(ServiceInfo.class);
+ resolveInfo.serviceInfo.applicationInfo = mApplicationInfo;
when(resolveInfo.loadLabel(anyObject())).thenReturn("Service name");
when(mServiceInfo.getResolveInfo()).thenReturn(resolveInfo);
when(mServiceInfo.getComponentName())
@@ -200,42 +206,47 @@ public class AccessibilityShortcutControllerTest {
}
@Test
- public void testShortcutAvailable_enabledButNoServiceWhenCreated_shouldReturnFalse() {
+ public void testShortcutAvailable_enabledButNoServiceWhenCreated_shouldReturnFalse()
+ throws Exception {
configureNoShortcutService();
configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
assertFalse(getController().isAccessibilityShortcutAvailable(false));
}
@Test
- public void testShortcutAvailable_enabledWithValidServiceWhenCreated_shouldReturnTrue() {
+ public void testShortcutAvailable_enabledWithValidServiceWhenCreated_shouldReturnTrue()
+ throws Exception {
configureValidShortcutService();
configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
assertTrue(getController().isAccessibilityShortcutAvailable(false));
}
@Test
- public void testShortcutAvailable_disabledWithValidServiceWhenCreated_shouldReturnFalse() {
+ public void testShortcutAvailable_disabledWithValidServiceWhenCreated_shouldReturnFalse()
+ throws Exception {
configureValidShortcutService();
configureShortcutEnabled(DISABLED_BUT_LOCK_SCREEN_ON);
assertFalse(getController().isAccessibilityShortcutAvailable(false));
}
@Test
- public void testShortcutAvailable_onLockScreenButDisabledThere_shouldReturnFalse() {
+ public void testShortcutAvailable_onLockScreenButDisabledThere_shouldReturnFalse()
+ throws Exception {
configureValidShortcutService();
configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
assertFalse(getController().isAccessibilityShortcutAvailable(true));
}
@Test
- public void testShortcutAvailable_onLockScreenAndEnabledThere_shouldReturnTrue() {
+ public void testShortcutAvailable_onLockScreenAndEnabledThere_shouldReturnTrue()
+ throws Exception {
configureValidShortcutService();
configureShortcutEnabled(ENABLED_INCLUDING_LOCK_SCREEN);
assertTrue(getController().isAccessibilityShortcutAvailable(true));
}
@Test
- public void testShortcutAvailable_onLockScreenAndLockScreenPreferenceUnset() {
+ public void testShortcutAvailable_onLockScreenAndLockScreenPreferenceUnset() throws Exception {
// When the user hasn't specified a lock screen preference, we allow from the lock screen
// as long as the user has agreed to enable the shortcut
configureValidShortcutService();
@@ -249,17 +260,19 @@ public class AccessibilityShortcutControllerTest {
}
@Test
- public void testShortcutAvailable_whenServiceIdBecomesNull_shouldReturnFalse() {
+ public void testShortcutAvailable_whenServiceIdBecomesNull_shouldReturnFalse()
+ throws Exception {
configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
configureValidShortcutService();
AccessibilityShortcutController accessibilityShortcutController = getController();
- Settings.Secure.putString(mContentResolver, ACCESSIBILITY_SHORTCUT_TARGET_SERVICE, "");
+ configureNoShortcutService();
accessibilityShortcutController.onSettingsChanged();
assertFalse(accessibilityShortcutController.isAccessibilityShortcutAvailable(false));
}
@Test
- public void testShortcutAvailable_whenServiceIdBecomesNonNull_shouldReturnTrue() {
+ public void testShortcutAvailable_whenServiceIdBecomesNonNull_shouldReturnTrue()
+ throws Exception {
configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
configureNoShortcutService();
AccessibilityShortcutController accessibilityShortcutController = getController();
@@ -269,7 +282,8 @@ public class AccessibilityShortcutControllerTest {
}
@Test
- public void testShortcutAvailable_whenShortcutBecomesDisabled_shouldReturnFalse() {
+ public void testShortcutAvailable_whenShortcutBecomesDisabled_shouldReturnFalse()
+ throws Exception {
configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
configureValidShortcutService();
AccessibilityShortcutController accessibilityShortcutController = getController();
@@ -279,7 +293,8 @@ public class AccessibilityShortcutControllerTest {
}
@Test
- public void testShortcutAvailable_whenShortcutBecomesEnabled_shouldReturnTrue() {
+ public void testShortcutAvailable_whenShortcutBecomesEnabled_shouldReturnTrue()
+ throws Exception {
configureShortcutEnabled(DISABLED);
configureValidShortcutService();
AccessibilityShortcutController accessibilityShortcutController = getController();
@@ -289,7 +304,8 @@ public class AccessibilityShortcutControllerTest {
}
@Test
- public void testShortcutAvailable_whenLockscreenBecomesDisabled_shouldReturnFalse() {
+ public void testShortcutAvailable_whenLockscreenBecomesDisabled_shouldReturnFalse()
+ throws Exception {
configureShortcutEnabled(ENABLED_INCLUDING_LOCK_SCREEN);
configureValidShortcutService();
AccessibilityShortcutController accessibilityShortcutController = getController();
@@ -299,7 +315,8 @@ public class AccessibilityShortcutControllerTest {
}
@Test
- public void testShortcutAvailable_whenLockscreenBecomesEnabled_shouldReturnTrue() {
+ public void testShortcutAvailable_whenLockscreenBecomesEnabled_shouldReturnTrue()
+ throws Exception {
configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
configureValidShortcutService();
AccessibilityShortcutController accessibilityShortcutController = getController();
@@ -370,7 +387,7 @@ public class AccessibilityShortcutControllerTest {
}
@Test
- public void testClickingDisableButtonInDialog_shouldClearShortcutId() {
+ public void testClickingDisableButtonInDialog_shouldClearShortcutId() throws Exception {
configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
configureValidShortcutService();
Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN, 0);
@@ -458,7 +475,22 @@ public class AccessibilityShortcutControllerTest {
}
@Test
- public void testOnAccessibilityShortcut_showsWarningDialog_shouldTtsSpokenPrompt() {
+ public void testOnAccessibilityShortcut_sdkGreaterThanQ_reqA11yButton_callsServiceWithNoToast()
+ throws Exception {
+ configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
+ configureValidShortcutService();
+ configureApplicationTargetSdkVersion(Build.VERSION_CODES.R);
+ configureRequestAccessibilityButton();
+ Settings.Secure.putInt(mContentResolver, ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN, 1);
+ getController().performAccessibilityShortcut();
+
+ verifyZeroInteractions(mToast);
+ verify(mAccessibilityManagerService).performAccessibilityShortcut();
+ }
+
+ @Test
+ public void testOnAccessibilityShortcut_showsWarningDialog_shouldTtsSpokenPrompt()
+ throws Exception {
configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
configureValidShortcutService();
configureTtsSpokenPromptEnabled();
@@ -482,7 +514,8 @@ public class AccessibilityShortcutControllerTest {
}
@Test
- public void testOnAccessibilityShortcut_showsWarningDialog_ttsInitFail_noSpokenPrompt() {
+ public void testOnAccessibilityShortcut_showsWarningDialog_ttsInitFail_noSpokenPrompt()
+ throws Exception {
configureShortcutEnabled(ENABLED_EXCEPT_LOCK_SCREEN);
configureValidShortcutService();
configureTtsSpokenPromptEnabled();
@@ -500,19 +533,28 @@ public class AccessibilityShortcutControllerTest {
verify(mRingtone).play();
}
- private void configureNoShortcutService() {
+ private void configureNoShortcutService() throws Exception {
+ when(mAccessibilityManagerService
+ .getAccessibilityShortcutTargets(ACCESSIBILITY_SHORTCUT_KEY))
+ .thenReturn(Collections.emptyList());
Settings.Secure.putString(mContentResolver, ACCESSIBILITY_SHORTCUT_TARGET_SERVICE, "");
}
- private void configureValidShortcutService() {
+ private void configureValidShortcutService() throws Exception {
+ when(mAccessibilityManagerService
+ .getAccessibilityShortcutTargets(ACCESSIBILITY_SHORTCUT_KEY))
+ .thenReturn(Collections.singletonList(SERVICE_NAME_STRING));
Settings.Secure.putString(
mContentResolver, ACCESSIBILITY_SHORTCUT_TARGET_SERVICE, SERVICE_NAME_STRING);
}
- private void configureFirstFrameworkFeature() {
+ private void configureFirstFrameworkFeature() throws Exception {
ComponentName featureComponentName =
(ComponentName) AccessibilityShortcutController.getFrameworkShortcutFeaturesMap()
.keySet().toArray()[0];
+ when(mAccessibilityManagerService
+ .getAccessibilityShortcutTargets(ACCESSIBILITY_SHORTCUT_KEY))
+ .thenReturn(Collections.singletonList(featureComponentName.flattenToString()));
Settings.Secure.putString(mContentResolver, ACCESSIBILITY_SHORTCUT_TARGET_SERVICE,
featureComponentName.flattenToString());
}
@@ -552,6 +594,15 @@ public class AccessibilityShortcutControllerTest {
.FLAG_REQUEST_SHORTCUT_WARNING_DIALOG_SPOKEN_FEEDBACK;
}
+ private void configureRequestAccessibilityButton() {
+ mServiceInfo.flags |= AccessibilityServiceInfo
+ .FLAG_REQUEST_ACCESSIBILITY_BUTTON;
+ }
+
+ private void configureApplicationTargetSdkVersion(int versionCode) {
+ mApplicationInfo.targetSdkVersion = versionCode;
+ }
+
private void configureHandlerCallbackInvocation() {
doAnswer((InvocationOnMock invocation) -> {
Message m = (Message) invocation.getArguments()[0];
diff --git a/core/tests/coretests/src/com/android/internal/app/ChooserActivityTest.java b/core/tests/coretests/src/com/android/internal/app/ChooserActivityTest.java
index d427cbda7fb6..8622b7efeee7 100644
--- a/core/tests/coretests/src/com/android/internal/app/ChooserActivityTest.java
+++ b/core/tests/coretests/src/com/android/internal/app/ChooserActivityTest.java
@@ -313,7 +313,7 @@ public class ChooserActivityTest {
assertThat(activity.isFinishing(), is(false));
onView(withId(R.id.empty)).check(matches(isDisplayed()));
- onView(withId(R.id.resolver_list)).check(matches(not(isDisplayed())));
+ onView(withId(R.id.profile_pager)).check(matches(not(isDisplayed())));
InstrumentationRegistry.getInstrumentation().runOnMainSync(
() -> activity.getAdapter().handlePackagesChanged()
);
@@ -674,12 +674,12 @@ public class ChooserActivityTest {
mActivityRule.launchActivity(Intent.createChooser(sendIntent, null));
waitForIdle();
+ // Second invocation is from onCreate
verify(mockLogger, Mockito.times(2)).write(logMakerCaptor.capture());
- // First invocation is from onCreate
- assertThat(logMakerCaptor.getAllValues().get(1).getCategory(),
- is(MetricsEvent.ACTION_SHARE_WITH_PREVIEW));
- assertThat(logMakerCaptor.getAllValues().get(1).getSubtype(),
+ assertThat(logMakerCaptor.getAllValues().get(0).getSubtype(),
is(CONTENT_PREVIEW_TEXT));
+ assertThat(logMakerCaptor.getAllValues().get(0).getCategory(),
+ is(MetricsEvent.ACTION_SHARE_WITH_PREVIEW));
}
@Test
@@ -706,10 +706,10 @@ public class ChooserActivityTest {
waitForIdle();
verify(mockLogger, Mockito.times(2)).write(logMakerCaptor.capture());
// First invocation is from onCreate
- assertThat(logMakerCaptor.getAllValues().get(1).getCategory(),
- is(MetricsEvent.ACTION_SHARE_WITH_PREVIEW));
- assertThat(logMakerCaptor.getAllValues().get(1).getSubtype(),
+ assertThat(logMakerCaptor.getAllValues().get(0).getSubtype(),
is(CONTENT_PREVIEW_IMAGE));
+ assertThat(logMakerCaptor.getAllValues().get(0).getCategory(),
+ is(MetricsEvent.ACTION_SHARE_WITH_PREVIEW));
}
@Test
diff --git a/core/tests/coretests/src/com/android/internal/app/ChooserWrapperActivity.java b/core/tests/coretests/src/com/android/internal/app/ChooserWrapperActivity.java
index 03705d0599e5..2a1044361d42 100644
--- a/core/tests/coretests/src/com/android/internal/app/ChooserWrapperActivity.java
+++ b/core/tests/coretests/src/com/android/internal/app/ChooserWrapperActivity.java
@@ -29,6 +29,7 @@ import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
+import android.os.UserHandle;
import android.util.Size;
import com.android.internal.app.ResolverListAdapter.ResolveInfoPresentationGetter;
@@ -47,7 +48,7 @@ public class ChooserWrapperActivity extends ChooserActivity {
private UsageStatsManager mUsm;
ChooserListAdapter getAdapter() {
- return (ChooserListAdapter) mAdapter;
+ return mChooserMultiProfilePagerAdapter.getActiveListAdapter();
}
boolean getIsSelected() { return mIsSuccessfullySelected; }
@@ -77,7 +78,7 @@ public class ChooserWrapperActivity extends ChooserActivity {
}
@Override
- protected ResolverListController createListController() {
+ protected ResolverListController createListController(UserHandle userHandle) {
return sOverrides.resolverListController;
}
diff --git a/core/tests/coretests/src/com/android/internal/app/ResolverActivityTest.java b/core/tests/coretests/src/com/android/internal/app/ResolverActivityTest.java
index 344c28679568..923ce3e3935d 100644
--- a/core/tests/coretests/src/com/android/internal/app/ResolverActivityTest.java
+++ b/core/tests/coretests/src/com/android/internal/app/ResolverActivityTest.java
@@ -116,14 +116,14 @@ public class ResolverActivityTest {
waitForIdle();
final ResolverWrapperActivity activity = mActivityRule.launchActivity(sendIntent);
- final View resolverList = activity.findViewById(R.id.resolver_list);
- final int initialResolverHeight = resolverList.getHeight();
+ final View viewPager = activity.findViewById(R.id.profile_pager);
+ final int initialResolverHeight = viewPager.getHeight();
activity.runOnUiThread(() -> {
ResolverDrawerLayout layout = (ResolverDrawerLayout)
activity.findViewById(
R.id.contentPanel);
- ((ResolverDrawerLayout.LayoutParams) resolverList.getLayoutParams()).maxHeight
+ ((ResolverDrawerLayout.LayoutParams) viewPager.getLayoutParams()).maxHeight
= initialResolverHeight - 1;
// Force a relayout
layout.invalidate();
@@ -131,13 +131,13 @@ public class ResolverActivityTest {
});
waitForIdle();
assertThat("Drawer should be capped at maxHeight",
- resolverList.getHeight() == (initialResolverHeight - 1));
+ viewPager.getHeight() == (initialResolverHeight - 1));
activity.runOnUiThread(() -> {
ResolverDrawerLayout layout = (ResolverDrawerLayout)
activity.findViewById(
R.id.contentPanel);
- ((ResolverDrawerLayout.LayoutParams) resolverList.getLayoutParams()).maxHeight
+ ((ResolverDrawerLayout.LayoutParams) viewPager.getLayoutParams()).maxHeight
= initialResolverHeight + 1;
// Force a relayout
layout.invalidate();
@@ -145,7 +145,7 @@ public class ResolverActivityTest {
});
waitForIdle();
assertThat("Drawer should not change height if its height is less than maxHeight",
- resolverList.getHeight() == initialResolverHeight);
+ viewPager.getHeight() == initialResolverHeight);
}
@Ignore // Failing - b/144929805
@@ -160,11 +160,13 @@ public class ResolverActivityTest {
waitForIdle();
final ResolverWrapperActivity activity = mActivityRule.launchActivity(sendIntent);
- final View resolverList = activity.findViewById(R.id.resolver_list);
+ final View viewPager = activity.findViewById(R.id.profile_pager);
+ final View divider = activity.findViewById(R.id.divider);
final RelativeLayout profileView =
(RelativeLayout) activity.findViewById(R.id.profile_button).getParent();
assertThat("Drawer should show at bottom by default",
- profileView.getBottom() == resolverList.getTop() && profileView.getTop() > 0);
+ profileView.getBottom() + divider.getHeight() == viewPager.getTop()
+ && profileView.getTop() > 0);
activity.runOnUiThread(() -> {
ResolverDrawerLayout layout = (ResolverDrawerLayout)
@@ -174,7 +176,8 @@ public class ResolverActivityTest {
});
waitForIdle();
assertThat("Drawer should show at top with new attribute",
- profileView.getBottom() == resolverList.getTop() && profileView.getTop() == 0);
+ profileView.getBottom() + divider.getHeight() == viewPager.getTop()
+ && profileView.getTop() == 0);
}
@Test
diff --git a/core/tests/coretests/src/com/android/internal/app/ResolverListControllerTest.java b/core/tests/coretests/src/com/android/internal/app/ResolverListControllerTest.java
index 5ac1489bcfef..64906bb27ff0 100644
--- a/core/tests/coretests/src/com/android/internal/app/ResolverListControllerTest.java
+++ b/core/tests/coretests/src/com/android/internal/app/ResolverListControllerTest.java
@@ -115,7 +115,7 @@ public class ResolverListControllerTest {
mUsm = new UsageStatsManager(mMockContext, mMockService);
when(mMockContext.getSystemService(Context.USAGE_STATS_SERVICE)).thenReturn(mUsm);
mController = new ResolverListController(mMockContext, mMockPackageManager, sendIntent,
- refererPackage, UserHandle.USER_CURRENT);
+ refererPackage, UserHandle.USER_CURRENT, /* userHandle */ UserHandle.SYSTEM);
mController.sort(new ArrayList<ResolvedComponentInfo>());
long beforeReport = getCount(mUsm, packageName, action, annotation);
mController.updateChooserCounts(packageName, UserHandle.USER_CURRENT, action);
@@ -132,7 +132,7 @@ public class ResolverListControllerTest {
mUsm = new UsageStatsManager(mMockContext, mMockService);
when(mMockContext.getSystemService(Context.USAGE_STATS_SERVICE)).thenReturn(mUsm);
mController = new ResolverListController(mMockContext, mMockPackageManager, sendIntent,
- refererPackage, UserHandle.USER_CURRENT);
+ refererPackage, UserHandle.USER_CURRENT, /* userHandle */ UserHandle.SYSTEM);
List<ResolvedComponentInfo> topKList = new ArrayList<>(resolvedComponents);
mController.topK(topKList, 5);
List<ResolvedComponentInfo> sortList = new ArrayList<>(topKList);
diff --git a/core/tests/coretests/src/com/android/internal/app/ResolverWrapperActivity.java b/core/tests/coretests/src/com/android/internal/app/ResolverWrapperActivity.java
index 39cc83c3bc43..c5d2cfaa9512 100644
--- a/core/tests/coretests/src/com/android/internal/app/ResolverWrapperActivity.java
+++ b/core/tests/coretests/src/com/android/internal/app/ResolverWrapperActivity.java
@@ -23,6 +23,7 @@ import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
+import android.os.UserHandle;
import com.android.internal.app.chooser.TargetInfo;
@@ -37,15 +38,15 @@ public class ResolverWrapperActivity extends ResolverActivity {
private UsageStatsManager mUsm;
@Override
- public ResolverListAdapter createAdapter(Context context, List<Intent> payloadIntents,
- Intent[] initialIntents, List<ResolveInfo> rList, boolean filterLastUsed,
- boolean useLayoutForBrowsables) {
+ public ResolverListAdapter createResolverListAdapter(Context context,
+ List<Intent> payloadIntents, Intent[] initialIntents, List<ResolveInfo> rList,
+ boolean filterLastUsed, boolean useLayoutForBrowsables, UserHandle userHandle) {
return new ResolverWrapperAdapter(context, payloadIntents, initialIntents, rList,
- filterLastUsed, createListController(), useLayoutForBrowsables, this);
+ filterLastUsed, createListController(userHandle), useLayoutForBrowsables, this);
}
ResolverWrapperAdapter getAdapter() {
- return (ResolverWrapperAdapter) mAdapter;
+ return (ResolverWrapperAdapter) mMultiProfilePagerAdapter.getActiveListAdapter();
}
@Override
@@ -66,7 +67,7 @@ public class ResolverWrapperActivity extends ResolverActivity {
}
@Override
- protected ResolverListController createListController() {
+ protected ResolverListController createListController(UserHandle userHandle) {
return sOverrides.resolverListController;
}
diff --git a/core/tests/coretests/src/com/android/internal/infra/AndroidFutureTest.java b/core/tests/coretests/src/com/android/internal/infra/AndroidFutureTest.java
new file mode 100644
index 000000000000..ffc925ff82cd
--- /dev/null
+++ b/core/tests/coretests/src/com/android/internal/infra/AndroidFutureTest.java
@@ -0,0 +1,152 @@
+/*
+ * Copyright (C) 2019 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 com.android.internal.infra;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.testng.Assert.expectThrows;
+
+import android.os.Parcel;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+
+/**
+ * Unit test for {@link AndroidFuture}.
+ *
+ * <p>To run it:
+ * {@code atest FrameworksCoreTests:com.android.internal.infra.AndroidFutureTest}
+ */
+
+@RunWith(AndroidJUnit4.class)
+public class AndroidFutureTest {
+ @Test
+ public void testGet() throws Exception {
+ AndroidFuture<Integer> future = new AndroidFuture<>();
+ future.complete(5);
+ assertThat(future.get()).isEqualTo(5);
+ }
+
+ @Test
+ public void testWhenComplete_AlreadyComplete() throws Exception {
+ AndroidFuture<Integer> future = new AndroidFuture<>();
+ future.complete(5);
+ CountDownLatch latch = new CountDownLatch(1);
+ future.whenComplete((obj, err) -> {
+ assertThat(obj).isEqualTo(5);
+ assertThat(err).isNull();
+ latch.countDown();
+ });
+ latch.await();
+ }
+
+ @Test
+ public void testWhenComplete_NotYetComplete() throws Exception {
+ AndroidFuture<Integer> future = new AndroidFuture<>();
+ CountDownLatch latch = new CountDownLatch(1);
+ future.whenComplete((obj, err) -> {
+ assertThat(obj).isEqualTo(5);
+ assertThat(err).isNull();
+ latch.countDown();
+ });
+ assertThat(latch.getCount()).isEqualTo(1);
+ future.complete(5);
+ latch.await();
+ assertThat(latch.getCount()).isEqualTo(0);
+ }
+
+ @Test
+ public void testCompleteExceptionally() {
+ AndroidFuture<Integer> future = new AndroidFuture<>();
+ Exception origException = new UnsupportedOperationException();
+ future.completeExceptionally(origException);
+ ExecutionException executionException =
+ expectThrows(ExecutionException.class, future::get);
+ assertThat(executionException.getCause()).isSameAs(origException);
+ }
+
+ @Test
+ public void testCompleteExceptionally_Listener() throws Exception {
+ AndroidFuture<Integer> future = new AndroidFuture<>();
+ Exception origException = new UnsupportedOperationException();
+ future.completeExceptionally(origException);
+ CountDownLatch latch = new CountDownLatch(1);
+ future.whenComplete((obj, err) -> {
+ assertThat(obj).isNull();
+ assertThat(err).isSameAs(origException);
+ latch.countDown();
+ });
+ latch.await();
+ }
+
+ @Test
+ public void testWriteToParcel() throws Exception {
+ Parcel parcel = Parcel.obtain();
+ AndroidFuture<Integer> future1 = new AndroidFuture<>();
+ future1.complete(5);
+ future1.writeToParcel(parcel, 0);
+
+ parcel.setDataPosition(0);
+ AndroidFuture future2 = AndroidFuture.CREATOR.createFromParcel(parcel);
+ assertThat(future2.get()).isEqualTo(5);
+ }
+
+ @Test
+ public void testWriteToParcel_Exception() throws Exception {
+ Parcel parcel = Parcel.obtain();
+ AndroidFuture<Integer> future1 = new AndroidFuture<>();
+ future1.completeExceptionally(new UnsupportedOperationException());
+ future1.writeToParcel(parcel, 0);
+
+ parcel.setDataPosition(0);
+ AndroidFuture future2 = AndroidFuture.CREATOR.createFromParcel(parcel);
+ ExecutionException executionException =
+ expectThrows(ExecutionException.class, future2::get);
+ assertThat(executionException.getCause()).isInstanceOf(UnsupportedOperationException.class);
+ }
+
+ @Test
+ public void testWriteToParcel_Incomplete() throws Exception {
+ Parcel parcel = Parcel.obtain();
+ AndroidFuture<Integer> future1 = new AndroidFuture<>();
+ future1.writeToParcel(parcel, 0);
+
+ parcel.setDataPosition(0);
+ AndroidFuture future2 = AndroidFuture.CREATOR.createFromParcel(parcel);
+ future2.complete(5);
+ assertThat(future1.get()).isEqualTo(5);
+ }
+
+ @Test
+ public void testWriteToParcel_Incomplete_Exception() throws Exception {
+ Parcel parcel = Parcel.obtain();
+ AndroidFuture<Integer> future1 = new AndroidFuture<>();
+ future1.writeToParcel(parcel, 0);
+
+ parcel.setDataPosition(0);
+ AndroidFuture future2 = AndroidFuture.CREATOR.createFromParcel(parcel);
+ future2.completeExceptionally(new UnsupportedOperationException());
+ ExecutionException executionException =
+ expectThrows(ExecutionException.class, future1::get);
+ assertThat(executionException.getCause()).isInstanceOf(UnsupportedOperationException.class);
+ }
+}
diff --git a/core/tests/screenshothelpertests/src/com/android/internal/util/ScreenshotHelperTest.java b/core/tests/screenshothelpertests/src/com/android/internal/util/ScreenshotHelperTest.java
index e16d1caa98eb..1472b9034249 100644
--- a/core/tests/screenshothelpertests/src/com/android/internal/util/ScreenshotHelperTest.java
+++ b/core/tests/screenshothelpertests/src/com/android/internal/util/ScreenshotHelperTest.java
@@ -24,8 +24,13 @@ import static junit.framework.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
import android.content.Context;
+import android.content.res.Resources;
import android.os.Handler;
import android.os.Looper;
@@ -54,9 +59,15 @@ public final class ScreenshotHelperTest {
// This raises a `SecurityException` if the device is locked. Calling either `Context`
// method results in a broadcast of `android.intent.action. USER_PRESENT`. Only the system
// process is allowed to broadcast that `Intent`.
+ Resources res = mock(Resources.class);
mContext = Mockito.spy(Context.class);
- Mockito.doNothing().when(mContext).sendBroadcastAsUser(any(), any());
- Mockito.doReturn(true).when(mContext).bindServiceAsUser(any(), any(), anyInt(), any());
+ doNothing().when(mContext).sendBroadcastAsUser(any(), any());
+ doReturn(true).when(mContext).bindServiceAsUser(any(), any(), anyInt(), any());
+ doReturn(res).when(mContext).getResources();
+ doReturn("com.android.systemui/.Service").when(res).getString(
+ eq(com.android.internal.R.string.config_screenshotServiceComponent));
+ doReturn("com.android.systemui/.ErrorReceiver").when(res).getString(
+ eq(com.android.internal.R.string.config_screenshotErrorReceiverComponent));
mHandler = new Handler(Looper.getMainLooper());
mScreenshotHelper = new ScreenshotHelper(mContext);
diff --git a/data/etc/Android.bp b/data/etc/Android.bp
index ff521be82599..20395fb049ef 100644
--- a/data/etc/Android.bp
+++ b/data/etc/Android.bp
@@ -88,7 +88,7 @@ prebuilt_etc {
prebuilt_etc {
name: "privapp_whitelist_com.android.launcher3",
- product_specific: true,
+ system_ext_specific: true,
sub_dir: "permissions",
src: "com.android.launcher3.xml",
filename_from_src: true,
@@ -120,7 +120,7 @@ prebuilt_etc {
prebuilt_etc {
name: "privapp_whitelist_com.android.storagemanager",
- product_specific: true,
+ system_ext_specific: true,
sub_dir: "permissions",
src: "com.android.storagemanager.xml",
filename_from_src: true,
@@ -128,7 +128,7 @@ prebuilt_etc {
prebuilt_etc {
name: "privapp_whitelist_com.android.systemui",
- product_specific: true,
+ system_ext_specific: true,
sub_dir: "permissions",
src: "com.android.systemui.xml",
filename_from_src: true,
diff --git a/data/etc/CleanSpec.mk b/data/etc/CleanSpec.mk
index 3fe421e530cb..783a7edadeb7 100644
--- a/data/etc/CleanSpec.mk
+++ b/data/etc/CleanSpec.mk
@@ -51,6 +51,10 @@ $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/product/etc/permissions/com.
$(call add-clean-step, rm -rf $(PRODUCT_OUT)/product/etc/permissions/com.android.provision.xml)
$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/product/etc/permissions/com.android.settings.xml)
$(call add-clean-step, rm -rf $(PRODUCT_OUT)/product/etc/permissions/com.android.settings.xml)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/product/etc/permissions/com.android.launcher3.xml)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/product/etc/permissions/com.android.launcher3.xml)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/product/etc/permissions/com.android.systemui.xml)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/product/etc/permissions/com.android.systemui.xml)
# ******************************************************************
# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST ABOVE THIS BANNER
# ******************************************************************
diff --git a/data/etc/com.android.settings.xml b/data/etc/com.android.settings.xml
index ba877f8d0d02..ee989cca1787 100644
--- a/data/etc/com.android.settings.xml
+++ b/data/etc/com.android.settings.xml
@@ -51,5 +51,6 @@
<permission name="android.permission.WRITE_MEDIA_STORAGE"/>
<permission name="android.permission.WRITE_SECURE_SETTINGS"/>
<permission name="android.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS" />
+ <permission name="android.permission.INSTALL_DYNAMIC_SYSTEM"/>
</privapp-permissions>
</permissions>
diff --git a/data/etc/platform.xml b/data/etc/platform.xml
index 80098c5a81f5..0574775712a6 100644
--- a/data/etc/platform.xml
+++ b/data/etc/platform.xml
@@ -157,6 +157,7 @@
<assign-permission name="android.permission.UPDATE_DEVICE_STATS" uid="audioserver" />
<assign-permission name="android.permission.UPDATE_APP_OPS_STATS" uid="audioserver" />
<assign-permission name="android.permission.PACKAGE_USAGE_STATS" uid="audioserver" />
+ <assign-permission name="android.permission.PREEMPT_SOUND_TRIGGER" uid="audioserver" />
<assign-permission name="android.permission.MODIFY_AUDIO_SETTINGS" uid="cameraserver" />
<assign-permission name="android.permission.ACCESS_SURFACE_FLINGER" uid="cameraserver" />
diff --git a/data/etc/privapp-permissions-platform.xml b/data/etc/privapp-permissions-platform.xml
index 322cbd798203..238afd4d42e1 100644
--- a/data/etc/privapp-permissions-platform.xml
+++ b/data/etc/privapp-permissions-platform.xml
@@ -145,7 +145,7 @@ applications that come with the platform
<permission name="android.permission.CHANGE_COMPONENT_ENABLED_STATE"/>
<permission name="android.permission.CHANGE_CONFIGURATION"/>
<permission name="android.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST"/>
- <permission name="android.permission.CONNECTIVITY_INTERNAL"/>
+ <permission name="android.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS"/>
<permission name="android.permission.CONTROL_INCALL_EXPERIENCE"/>
<permission name="android.permission.DUMP"/>
<permission name="android.permission.INTERACT_ACROSS_USERS"/>
@@ -240,6 +240,13 @@ applications that come with the platform
<permission name="android.permission.WRITE_SECURE_SETTINGS"/>
</privapp-permissions>
+ <privapp-permissions package="com.android.networkstack.tethering">
+ <permission name="android.permission.MANAGE_USB"/>
+ <permission name="android.permission.MODIFY_PHONE_STATE"/>
+ <permission name="android.permission.READ_NETWORK_USAGE_HISTORY"/>
+ <permission name="android.permission.UPDATE_APP_OPS_STATS"/>
+ </privapp-permissions>
+
<privapp-permissions package="com.android.server.telecom">
<permission name="android.permission.BIND_CONNECTION_SERVICE"/>
<permission name="android.permission.BIND_INCALL_SERVICE"/>
@@ -343,6 +350,8 @@ applications that come with the platform
<permission name="android.permission.ENTER_CAR_MODE_PRIORITIZED"/>
<!-- Permission required for Telecom car mode CTS tests. -->
<permission name="android.permission.CONTROL_INCALL_EXPERIENCE"/>
+ <!-- Permission required for Tethering CTS tests. -->
+ <permission name="android.permission.TETHER_PRIVILEGED"/>
</privapp-permissions>
<privapp-permissions package="com.android.statementservice">
diff --git a/data/etc/services.core.protolog.json b/data/etc/services.core.protolog.json
index 440b885b4574..9917cee00eaf 100644
--- a/data/etc/services.core.protolog.json
+++ b/data/etc/services.core.protolog.json
@@ -7,12 +7,6 @@
"group": "WM_DEBUG_KEEP_SCREEN_ON",
"at": "com\/android\/server\/wm\/WindowManagerService.java"
},
- "-2138637148": {
- "message": "Clearing focused app, displayId=%d",
- "level": "VERBOSE",
- "group": "WM_DEBUG_FOCUS_LIGHT",
- "at": "com\/android\/server\/wm\/ActivityDisplay.java"
- },
"-2127842445": {
"message": "Clearing startingData for token=%s",
"level": "VERBOSE",
@@ -79,12 +73,6 @@
"group": "WM_ERROR",
"at": "com\/android\/server\/wm\/WindowManagerService.java"
},
- "-1976550065": {
- "message": "commitVisibility: %s: visible=%b visibleRequested=%b",
- "level": "VERBOSE",
- "group": "WM_DEBUG_APP_TRANSITIONS",
- "at": "com\/android\/server\/wm\/ActivityRecord.java"
- },
"-1963461591": {
"message": "Removing %s from %s",
"level": "VERBOSE",
@@ -283,6 +271,12 @@
"group": "WM_ERROR",
"at": "com\/android\/server\/wm\/WindowManagerService.java"
},
+ "-1521427940": {
+ "message": "commitVisibility: %s: visible=%b mVisibleRequested=%b",
+ "level": "VERBOSE",
+ "group": "WM_DEBUG_APP_TRANSITIONS",
+ "at": "com\/android\/server\/wm\/ActivityRecord.java"
+ },
"-1515151503": {
"message": ">>> OPEN TRANSACTION removeReplacedWindows",
"level": "INFO",
@@ -391,6 +385,12 @@
"group": "WM_ERROR",
"at": "com\/android\/server\/wm\/WindowManagerService.java"
},
+ "-1263316010": {
+ "message": "Computed rotation=%s (%d) for display id=%d based on lastOrientation=%s (%d) and oldRotation=%s (%d)",
+ "level": "VERBOSE",
+ "group": "WM_DEBUG_ORIENTATION",
+ "at": "com\/android\/server\/wm\/DisplayRotation.java"
+ },
"-1259022216": {
"message": "SURFACE HIDE ( %s ): %s",
"level": "INFO",
@@ -469,6 +469,12 @@
"group": "WM_ERROR",
"at": "com\/android\/server\/wm\/WindowManagerService.java"
},
+ "-1108775960": {
+ "message": "%s is requesting orientation %d (%s)",
+ "level": "VERBOSE",
+ "group": "WM_DEBUG_ORIENTATION",
+ "at": "com\/android\/server\/wm\/WindowContainer.java"
+ },
"-1103716954": {
"message": "Not removing %s due to exit animation",
"level": "VERBOSE",
@@ -637,6 +643,12 @@
"group": "WM_DEBUG_FOCUS_LIGHT",
"at": "com\/android\/server\/wm\/ActivityRecord.java"
},
+ "-766059044": {
+ "message": "Display id=%d selected orientation %s (%d), got rotation %s (%d)",
+ "level": "VERBOSE",
+ "group": "WM_DEBUG_ORIENTATION",
+ "at": "com\/android\/server\/wm\/DisplayRotation.java"
+ },
"-760801764": {
"message": "onAnimationCancelled",
"level": "DEBUG",
@@ -697,12 +709,6 @@
"group": "WM_DEBUG_SCREEN_ON",
"at": "com\/android\/server\/wm\/DisplayContent.java"
},
- "-633961578": {
- "message": "applyAnimation: transition animation is disabled or skipped. container=%s",
- "level": "VERBOSE",
- "group": "WM_DEBUG_APP_TRANSITIONS_ANIM",
- "at": "com\/android\/server\/wm\/ActivityRecord.java"
- },
"-622997754": {
"message": "postWindowRemoveCleanupLocked: %s",
"level": "VERBOSE",
@@ -715,6 +721,12 @@
"group": "WM_DEBUG_BOOT",
"at": "com\/android\/server\/wm\/WindowManagerService.java"
},
+ "-603199586": {
+ "message": "Clearing focused app, displayId=%d",
+ "level": "VERBOSE",
+ "group": "WM_DEBUG_FOCUS_LIGHT",
+ "at": "com\/android\/server\/wm\/DisplayContent.java"
+ },
"-583031528": {
"message": "%s",
"level": "INFO",
@@ -1273,12 +1285,6 @@
"group": "WM_DEBUG_RECENTS_ANIMATIONS",
"at": "com\/android\/server\/wm\/RecentsAnimation.java"
},
- "481370485": {
- "message": "Computed rotation=%d for display id=%d based on lastOrientation=%d and oldRotation=%d",
- "level": "VERBOSE",
- "group": "WM_DEBUG_ORIENTATION",
- "at": "com\/android\/server\/wm\/DisplayRotation.java"
- },
"490877640": {
"message": "onStackOrderChanged(): stack=%s",
"level": "DEBUG",
@@ -1321,6 +1327,12 @@
"group": "WM_SHOW_TRANSACTIONS",
"at": "com\/android\/server\/wm\/WindowSurfaceController.java"
},
+ "584499099": {
+ "message": "Set focused app to: %s moveFocusNow=%b displayId=%d",
+ "level": "VERBOSE",
+ "group": "WM_DEBUG_FOCUS_LIGHT",
+ "at": "com\/android\/server\/wm\/DisplayContent.java"
+ },
"585096182": {
"message": "SURFACE isColorSpaceAgnostic=%b: %s",
"level": "INFO",
@@ -1477,12 +1489,6 @@
"group": "WM_DEBUG_REMOTE_ANIMATIONS",
"at": "com\/android\/server\/wm\/RemoteAnimationController.java"
},
- "841702299": {
- "message": "Changing app %s visible=%b performLayout=%b",
- "level": "VERBOSE",
- "group": "WM_DEBUG_APP_TRANSITIONS",
- "at": "com\/android\/server\/wm\/ActivityRecord.java"
- },
"845234215": {
"message": "App is requesting an orientation, return %d for display id=%d",
"level": "VERBOSE",
@@ -1525,12 +1531,6 @@
"group": "WM_DEBUG_ORIENTATION",
"at": "com\/android\/server\/wm\/WindowStateAnimator.java"
},
- "917739349": {
- "message": "Set focused app to: %s moveFocusNow=%b displayId=%d",
- "level": "VERBOSE",
- "group": "WM_DEBUG_FOCUS_LIGHT",
- "at": "com\/android\/server\/wm\/ActivityDisplay.java"
- },
"954470154": {
"message": "FORCED DISPLAY SCALING DISABLED",
"level": "INFO",
@@ -1807,12 +1807,6 @@
"group": "WM_ERROR",
"at": "com\/android\/server\/wm\/WindowManagerService.java"
},
- "1573332272": {
- "message": "Display id=%d selected orientation %d, got rotation %d",
- "level": "VERBOSE",
- "group": "WM_DEBUG_ORIENTATION",
- "at": "com\/android\/server\/wm\/DisplayRotation.java"
- },
"1577579529": {
"message": "win=%s destroySurfaces: appStopped=%b win.mWindowRemovalAllowed=%b win.mRemoveOnExit=%b",
"level": "ERROR",
@@ -1993,6 +1987,12 @@
"group": "WM_DEBUG_REMOTE_ANIMATIONS",
"at": "com\/android\/server\/wm\/RemoteAnimationController.java"
},
+ "1967975839": {
+ "message": "Changing app %s visible=%b performLayout=%b",
+ "level": "VERBOSE",
+ "group": "WM_DEBUG_APP_TRANSITIONS",
+ "at": "com\/android\/server\/wm\/AppTransitionController.java"
+ },
"1984470582": {
"message": "Creating TaskScreenshotAnimatable: task: %s width: %d height: %d",
"level": "DEBUG",
diff --git a/framework-jarjar-rules.txt b/framework-jarjar-rules.txt
new file mode 100644
index 000000000000..d8af726ffa72
--- /dev/null
+++ b/framework-jarjar-rules.txt
@@ -0,0 +1,2 @@
+rule android.hidl.** android.internal.hidl.@1
+rule android.net.wifi.WifiAnnotations* android.internal.wifi.WifiAnnotations@1
diff --git a/graphics/java/android/graphics/HardwareRenderer.java b/graphics/java/android/graphics/HardwareRenderer.java
index 3f3ad578e8d7..3b864139cf71 100644
--- a/graphics/java/android/graphics/HardwareRenderer.java
+++ b/graphics/java/android/graphics/HardwareRenderer.java
@@ -28,7 +28,6 @@ import android.os.RemoteException;
import android.os.ServiceManager;
import android.util.Log;
import android.util.TimeUtils;
-import android.view.FrameMetricsObserver;
import android.view.IGraphicsStats;
import android.view.IGraphicsStatsCallback;
import android.view.NativeVectorDrawableAnimator;
@@ -38,8 +37,6 @@ import android.view.SurfaceHolder;
import android.view.TextureLayer;
import android.view.animation.AnimationUtils;
-import com.android.internal.util.VirtualRefBasePtr;
-
import java.io.File;
import java.io.FileDescriptor;
import java.lang.annotation.Retention;
@@ -598,9 +595,8 @@ public class HardwareRenderer {
*
* @hide
*/
- public void addFrameMetricsObserver(FrameMetricsObserver observer) {
- long nativeObserver = nAddFrameMetricsObserver(mNativeProxy, observer);
- observer.mNative = new VirtualRefBasePtr(nativeObserver);
+ public void addObserver(HardwareRendererObserver observer) {
+ nAddObserver(mNativeProxy, observer.getNativeInstance());
}
/**
@@ -608,9 +604,8 @@ public class HardwareRenderer {
*
* @hide
*/
- public void removeFrameMetricsObserver(FrameMetricsObserver observer) {
- nRemoveFrameMetricsObserver(mNativeProxy, observer.mNative.get());
- observer.mNative = null;
+ public void removeObserver(HardwareRendererObserver observer) {
+ nRemoveObserver(mNativeProxy, observer.getNativeInstance());
}
/**
@@ -1170,10 +1165,9 @@ public class HardwareRenderer {
private static native void nSetFrameCompleteCallback(long nativeProxy,
FrameCompleteCallback callback);
- private static native long nAddFrameMetricsObserver(long nativeProxy,
- FrameMetricsObserver observer);
+ private static native void nAddObserver(long nativeProxy, long nativeObserver);
- private static native void nRemoveFrameMetricsObserver(long nativeProxy, long nativeObserver);
+ private static native void nRemoveObserver(long nativeProxy, long nativeObserver);
private static native int nCopySurfaceInto(Surface surface,
int srcLeft, int srcTop, int srcRight, int srcBottom, long bitmapHandle);
diff --git a/graphics/java/android/graphics/HardwareRendererObserver.java b/graphics/java/android/graphics/HardwareRendererObserver.java
new file mode 100644
index 000000000000..da9d03c639f7
--- /dev/null
+++ b/graphics/java/android/graphics/HardwareRendererObserver.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2019 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.graphics;
+
+import android.annotation.NonNull;
+import android.os.Handler;
+
+import com.android.internal.util.VirtualRefBasePtr;
+
+/**
+ * Provides streaming access to frame stats information from HardwareRenderer to apps.
+ *
+ * @hide
+ */
+public class HardwareRendererObserver {
+ private final long[] mFrameMetrics;
+ private final Handler mHandler;
+ private final OnFrameMetricsAvailableListener mListener;
+ private VirtualRefBasePtr mNativePtr;
+
+ /**
+ * Interface for clients that want frame timing information for each frame rendered.
+ * @hide
+ */
+ public interface OnFrameMetricsAvailableListener {
+ /**
+ * Called when information is available for the previously rendered frame.
+ *
+ * Reports can be dropped if this callback takes too long to execute, as the report producer
+ * cannot wait for the consumer to complete.
+ *
+ * It is highly recommended that clients copy the metrics array within this method
+ * and defer additional computation or storage to another thread to avoid unnecessarily
+ * dropping reports.
+ *
+ * @param dropCountSinceLastInvocation the number of reports dropped since the last time
+ * this callback was invoked.
+ */
+ void onFrameMetricsAvailable(int dropCountSinceLastInvocation);
+ }
+
+ /**
+ * Creates a FrameMetricsObserver
+ *
+ * @param frameMetrics the available metrics. This array is reused on every call to the listener
+ * and thus <strong>this reference should only be used within the scope of the listener callback
+ * as data is not guaranteed to be valid outside the scope of that method</strong>.
+ * @param handler the Handler to use when invoking callbacks
+ */
+ public HardwareRendererObserver(@NonNull OnFrameMetricsAvailableListener listener,
+ @NonNull long[] frameMetrics, @NonNull Handler handler) {
+ if (handler == null || handler.getLooper() == null) {
+ throw new NullPointerException("handler and its looper cannot be null");
+ }
+
+ if (handler.getLooper().getQueue() == null) {
+ throw new IllegalStateException("invalid looper, null message queue\n");
+ }
+
+ mFrameMetrics = frameMetrics;
+ mHandler = handler;
+ mListener = listener;
+ mNativePtr = new VirtualRefBasePtr(nCreateObserver());
+ }
+
+ /*package*/ long getNativeInstance() {
+ return mNativePtr.get();
+ }
+
+ // Called by native on the provided Handler
+ @SuppressWarnings("unused")
+ private void notifyDataAvailable() {
+ mHandler.post(() -> {
+ boolean hasMoreData = true;
+ while (hasMoreData) {
+ // a drop count of -1 is a sentinel that no more buffers are available
+ int dropCount = nGetNextBuffer(mNativePtr.get(), mFrameMetrics);
+ if (dropCount >= 0) {
+ mListener.onFrameMetricsAvailable(dropCount);
+ } else {
+ hasMoreData = false;
+ }
+ }
+ });
+ }
+
+ private native long nCreateObserver();
+ private static native int nGetNextBuffer(long nativePtr, long[] data);
+}
diff --git a/graphics/java/android/graphics/ImageDecoder.java b/graphics/java/android/graphics/ImageDecoder.java
index 6619dba159c2..aecef8ee3413 100644
--- a/graphics/java/android/graphics/ImageDecoder.java
+++ b/graphics/java/android/graphics/ImageDecoder.java
@@ -270,7 +270,7 @@ public final class ImageDecoder implements AutoCloseable {
public ImageDecoder createImageDecoder(boolean preferAnimation) throws IOException {
AssetFileDescriptor assetFd = null;
try {
- if (mUri.getScheme() == ContentResolver.SCHEME_CONTENT) {
+ if (mUri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
assetFd = mResolver.openTypedAssetFileDescriptor(mUri,
"image/*", null);
} else {
@@ -1675,6 +1675,9 @@ public final class ImageDecoder implements AutoCloseable {
if (r == null) {
return;
}
+ if (r.width() <= 0 || r.height() <= 0) {
+ throw new IllegalStateException("Subset " + r + " is empty/unsorted");
+ }
if (r.left < 0 || r.top < 0 || r.right > width || r.bottom > height) {
throw new IllegalStateException("Subset " + r + " not contained by "
+ "scaled image bounds: (" + width + " x " + height + ")");
diff --git a/graphics/java/android/graphics/drawable/ColorDrawable.java b/graphics/java/android/graphics/drawable/ColorDrawable.java
index f5fa8c546bed..e93e7dfbe22c 100644
--- a/graphics/java/android/graphics/drawable/ColorDrawable.java
+++ b/graphics/java/android/graphics/drawable/ColorDrawable.java
@@ -20,7 +20,7 @@ import android.annotation.ColorInt;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo.Config;
import android.content.res.ColorStateList;
import android.content.res.Resources;
diff --git a/graphics/java/android/graphics/drawable/Drawable.java b/graphics/java/android/graphics/drawable/Drawable.java
index 08409869c626..e70529b6cd1a 100644
--- a/graphics/java/android/graphics/drawable/Drawable.java
+++ b/graphics/java/android/graphics/drawable/Drawable.java
@@ -22,7 +22,7 @@ import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo.Config;
import android.content.res.ColorStateList;
import android.content.res.Resources;
diff --git a/graphics/java/android/graphics/drawable/DrawableContainer.java b/graphics/java/android/graphics/drawable/DrawableContainer.java
index 090d915a2f67..51b299c9ee5e 100644
--- a/graphics/java/android/graphics/drawable/DrawableContainer.java
+++ b/graphics/java/android/graphics/drawable/DrawableContainer.java
@@ -17,7 +17,7 @@
package android.graphics.drawable;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo.Config;
import android.content.res.ColorStateList;
import android.content.res.Resources;
diff --git a/graphics/java/android/graphics/drawable/DrawableInflater.java b/graphics/java/android/graphics/drawable/DrawableInflater.java
index bad3791a9c24..3408b64e7536 100644
--- a/graphics/java/android/graphics/drawable/DrawableInflater.java
+++ b/graphics/java/android/graphics/drawable/DrawableInflater.java
@@ -16,19 +16,19 @@
package android.graphics.drawable;
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
import android.annotation.DrawableRes;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.Resources.Theme;
import android.util.AttributeSet;
import android.view.InflateException;
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.HashMap;
diff --git a/graphics/java/android/graphics/drawable/DrawableWrapper.java b/graphics/java/android/graphics/drawable/DrawableWrapper.java
index 6c90c4c6c8a4..e197e7123fed 100644
--- a/graphics/java/android/graphics/drawable/DrawableWrapper.java
+++ b/graphics/java/android/graphics/drawable/DrawableWrapper.java
@@ -18,7 +18,7 @@ package android.graphics.drawable;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo.Config;
import android.content.res.ColorStateList;
import android.content.res.Resources;
diff --git a/graphics/java/android/graphics/drawable/GradientDrawable.java b/graphics/java/android/graphics/drawable/GradientDrawable.java
index 45b2de5f4b31..3881955d2632 100644
--- a/graphics/java/android/graphics/drawable/GradientDrawable.java
+++ b/graphics/java/android/graphics/drawable/GradientDrawable.java
@@ -22,7 +22,7 @@ import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.Px;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo.Config;
import android.content.res.ColorStateList;
import android.content.res.Resources;
@@ -784,9 +784,7 @@ public class GradientDrawable extends Drawable {
mFillPaint.setDither(st.mDither);
mFillPaint.setColorFilter(colorFilter);
if (colorFilter != null && st.mSolidColors == null) {
- // If we don't have a solid color and we don't have a gradient,
- // the app is stroking the shape, set the color to transparent
- mFillPaint.setColor(st.mGradientColors != null ? mAlpha << 24 : 0);
+ mFillPaint.setColor(mAlpha << 24);
}
if (haveStroke) {
mStrokePaint.setAlpha(currStrokeAlpha);
diff --git a/graphics/java/android/graphics/drawable/Icon.java b/graphics/java/android/graphics/drawable/Icon.java
index c2e3c6419400..cc7182c3fd1c 100644
--- a/graphics/java/android/graphics/drawable/Icon.java
+++ b/graphics/java/android/graphics/drawable/Icon.java
@@ -21,7 +21,7 @@ import android.annotation.DrawableRes;
import android.annotation.IdRes;
import android.annotation.IntDef;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.ApplicationInfo;
diff --git a/graphics/java/android/graphics/drawable/InsetDrawable.java b/graphics/java/android/graphics/drawable/InsetDrawable.java
index bc8a4cbd7e9d..005a4d175fd5 100644
--- a/graphics/java/android/graphics/drawable/InsetDrawable.java
+++ b/graphics/java/android/graphics/drawable/InsetDrawable.java
@@ -18,7 +18,7 @@ package android.graphics.drawable;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.res.Resources;
import android.content.res.Resources.Theme;
import android.content.res.TypedArray;
diff --git a/graphics/java/android/graphics/drawable/LayerDrawable.java b/graphics/java/android/graphics/drawable/LayerDrawable.java
index 760d554888ee..fb4146f04bc9 100644
--- a/graphics/java/android/graphics/drawable/LayerDrawable.java
+++ b/graphics/java/android/graphics/drawable/LayerDrawable.java
@@ -18,7 +18,7 @@ package android.graphics.drawable;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo.Config;
import android.content.res.ColorStateList;
import android.content.res.Resources;
diff --git a/graphics/java/android/graphics/drawable/NinePatchDrawable.java b/graphics/java/android/graphics/drawable/NinePatchDrawable.java
index 8561d95ddd88..99d27ba4c469 100644
--- a/graphics/java/android/graphics/drawable/NinePatchDrawable.java
+++ b/graphics/java/android/graphics/drawable/NinePatchDrawable.java
@@ -18,7 +18,7 @@ package android.graphics.drawable;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo.Config;
import android.content.res.ColorStateList;
import android.content.res.Resources;
diff --git a/graphics/java/android/graphics/drawable/RippleDrawable.java b/graphics/java/android/graphics/drawable/RippleDrawable.java
index 1540cc22e295..e5e4d4527fca 100644
--- a/graphics/java/android/graphics/drawable/RippleDrawable.java
+++ b/graphics/java/android/graphics/drawable/RippleDrawable.java
@@ -18,7 +18,7 @@ package android.graphics.drawable;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo.Config;
import android.content.res.ColorStateList;
import android.content.res.Resources;
diff --git a/graphics/java/android/graphics/drawable/RotateDrawable.java b/graphics/java/android/graphics/drawable/RotateDrawable.java
index db5f082bd853..43766b636adb 100644
--- a/graphics/java/android/graphics/drawable/RotateDrawable.java
+++ b/graphics/java/android/graphics/drawable/RotateDrawable.java
@@ -16,22 +16,22 @@
package android.graphics.drawable;
-import com.android.internal.R;
-
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
-import android.graphics.Canvas;
-import android.graphics.Rect;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.res.Resources;
-import android.content.res.TypedArray;
import android.content.res.Resources.Theme;
+import android.content.res.TypedArray;
+import android.graphics.Canvas;
+import android.graphics.Rect;
+import android.util.AttributeSet;
import android.util.MathUtils;
import android.util.TypedValue;
-import android.util.AttributeSet;
+
+import com.android.internal.R;
+
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
diff --git a/graphics/java/android/graphics/drawable/ScaleDrawable.java b/graphics/java/android/graphics/drawable/ScaleDrawable.java
index 91ed061e511d..af7eed4b3897 100644
--- a/graphics/java/android/graphics/drawable/ScaleDrawable.java
+++ b/graphics/java/android/graphics/drawable/ScaleDrawable.java
@@ -16,14 +16,9 @@
package android.graphics.drawable;
-import com.android.internal.R;
-
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.res.Resources;
import android.content.res.Resources.Theme;
import android.content.res.TypedArray;
@@ -34,6 +29,11 @@ import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
+import com.android.internal.R;
+
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+
import java.io.IOException;
/**
diff --git a/graphics/java/android/graphics/drawable/StateListDrawable.java b/graphics/java/android/graphics/drawable/StateListDrawable.java
index f67188c22609..2920acbe514c 100644
--- a/graphics/java/android/graphics/drawable/StateListDrawable.java
+++ b/graphics/java/android/graphics/drawable/StateListDrawable.java
@@ -18,7 +18,7 @@ package android.graphics.drawable;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.res.Resources;
import android.content.res.Resources.Theme;
import android.content.res.TypedArray;
diff --git a/graphics/java/android/graphics/drawable/TransitionDrawable.java b/graphics/java/android/graphics/drawable/TransitionDrawable.java
index 276f3662189b..401e05ffc139 100644
--- a/graphics/java/android/graphics/drawable/TransitionDrawable.java
+++ b/graphics/java/android/graphics/drawable/TransitionDrawable.java
@@ -16,7 +16,7 @@
package android.graphics.drawable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo.Config;
import android.content.res.Resources;
import android.graphics.Canvas;
diff --git a/graphics/java/android/graphics/drawable/VectorDrawable.java b/graphics/java/android/graphics/drawable/VectorDrawable.java
index aa19b2a0e94c..e6fa866df3ab 100644
--- a/graphics/java/android/graphics/drawable/VectorDrawable.java
+++ b/graphics/java/android/graphics/drawable/VectorDrawable.java
@@ -16,7 +16,7 @@ package android.graphics.drawable;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ActivityInfo.Config;
import android.content.res.ColorStateList;
import android.content.res.ComplexColor;
diff --git a/graphics/java/android/graphics/fonts/FontVariationAxis.java b/graphics/java/android/graphics/fonts/FontVariationAxis.java
index bcee559d8291..4e6580ea5f53 100644
--- a/graphics/java/android/graphics/fonts/FontVariationAxis.java
+++ b/graphics/java/android/graphics/fonts/FontVariationAxis.java
@@ -18,7 +18,7 @@ package android.graphics.fonts;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.text.TextUtils;
diff --git a/graphics/java/android/graphics/pdf/PdfRenderer.java b/graphics/java/android/graphics/pdf/PdfRenderer.java
index bd1a49205fd5..54710e58687c 100644
--- a/graphics/java/android/graphics/pdf/PdfRenderer.java
+++ b/graphics/java/android/graphics/pdf/PdfRenderer.java
@@ -19,7 +19,7 @@ package android.graphics.pdf;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Matrix;
@@ -29,7 +29,9 @@ import android.os.ParcelFileDescriptor;
import android.system.ErrnoException;
import android.system.Os;
import android.system.OsConstants;
+
import com.android.internal.util.Preconditions;
+
import dalvik.system.CloseGuard;
import libcore.io.IoUtils;
diff --git a/jarjar_rules_hidl.txt b/jarjar_rules_hidl.txt
deleted file mode 100644
index 4b2331db7c34..000000000000
--- a/jarjar_rules_hidl.txt
+++ /dev/null
@@ -1 +0,0 @@
-rule android.hidl.** android.internal.hidl.@1
diff --git a/keystore/java/android/security/Credentials.java b/keystore/java/android/security/Credentials.java
index 572fa8c529df..f53a7dc922f0 100644
--- a/keystore/java/android/security/Credentials.java
+++ b/keystore/java/android/security/Credentials.java
@@ -16,7 +16,7 @@
package android.security;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import com.android.org.bouncycastle.util.io.pem.PemObject;
import com.android.org.bouncycastle.util.io.pem.PemReader;
@@ -65,6 +65,9 @@ public class Credentials {
/** Key prefix for VPN. */
public static final String VPN = "VPN_";
+ /** Key prefix for platform VPNs. */
+ public static final String PLATFORM_VPN = "PLATFORM_VPN_";
+
/** Key prefix for WIFI. */
public static final String WIFI = "WIFI_";
diff --git a/keystore/java/android/security/GateKeeper.java b/keystore/java/android/security/GateKeeper.java
index a50ff7984341..af188a95c929 100644
--- a/keystore/java/android/security/GateKeeper.java
+++ b/keystore/java/android/security/GateKeeper.java
@@ -16,7 +16,7 @@
package android.security;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.RemoteException;
import android.os.ServiceManager;
diff --git a/keystore/java/android/security/KeyStore.java b/keystore/java/android/security/KeyStore.java
index d9ed5f32cfc3..dc57f55bb4af 100644
--- a/keystore/java/android/security/KeyStore.java
+++ b/keystore/java/android/security/KeyStore.java
@@ -16,10 +16,10 @@
package android.security;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityThread;
import android.app.Application;
import android.app.KeyguardManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.face.FaceManager;
@@ -31,7 +31,6 @@ import android.os.Process;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.UserHandle;
-import android.security.KeyStoreException;
import android.security.keymaster.ExportResult;
import android.security.keymaster.KeyCharacteristics;
import android.security.keymaster.KeymasterArguments;
diff --git a/keystore/java/android/security/keystore/AndroidKeyStoreProvider.java b/keystore/java/android/security/keystore/AndroidKeyStoreProvider.java
index d03329445b18..71e6559c53c6 100644
--- a/keystore/java/android/security/keystore/AndroidKeyStoreProvider.java
+++ b/keystore/java/android/security/keystore/AndroidKeyStoreProvider.java
@@ -18,7 +18,7 @@ package android.security.keystore;
import android.annotation.NonNull;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.security.KeyStore;
import android.security.keymaster.ExportResult;
import android.security.keymaster.KeyCharacteristics;
diff --git a/keystore/java/android/security/keystore/AttestationUtils.java b/keystore/java/android/security/keystore/AttestationUtils.java
index 94499ce24ed0..8a7b62332ffa 100644
--- a/keystore/java/android/security/keystore/AttestationUtils.java
+++ b/keystore/java/android/security/keystore/AttestationUtils.java
@@ -204,10 +204,7 @@ public abstract class AttestationUtils {
break;
}
case USE_INDIVIDUAL_ATTESTATION: {
- //TODO: Add the Keymaster tag for requesting the use of individual
- //attestation certificate, which should be
- //KeymasterDefs.KM_TAG_DEVICE_UNIQUE_ATTESTATION
- attestArgs.addBoolean(720);
+ attestArgs.addBoolean(KeymasterDefs.KM_TAG_DEVICE_UNIQUE_ATTESTATION);
break;
}
default:
diff --git a/keystore/java/android/security/keystore/KeyGenParameterSpec.java b/keystore/java/android/security/keystore/KeyGenParameterSpec.java
index 6df3b8c7661e..52ff9e0449ca 100644
--- a/keystore/java/android/security/keystore/KeyGenParameterSpec.java
+++ b/keystore/java/android/security/keystore/KeyGenParameterSpec.java
@@ -21,8 +21,8 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.KeyguardManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.hardware.biometrics.BiometricManager;
import android.hardware.biometrics.BiometricPrompt;
import android.security.GateKeeper;
diff --git a/libs/androidfw/LocaleDataTables.cpp b/libs/androidfw/LocaleDataTables.cpp
index c276a238e2e1..c462eb7f2401 100644
--- a/libs/androidfw/LocaleDataTables.cpp
+++ b/libs/androidfw/LocaleDataTables.cpp
@@ -10,1439 +10,1466 @@ const char SCRIPT_CODES[][4] = {
/* 6 */ {'B', 'a', 's', 's'},
/* 7 */ {'B', 'e', 'n', 'g'},
/* 8 */ {'B', 'r', 'a', 'h'},
- /* 9 */ {'C', 'a', 'n', 's'},
- /* 10 */ {'C', 'a', 'r', 'i'},
- /* 11 */ {'C', 'h', 'a', 'm'},
- /* 12 */ {'C', 'h', 'e', 'r'},
- /* 13 */ {'C', 'o', 'p', 't'},
- /* 14 */ {'C', 'p', 'r', 't'},
- /* 15 */ {'C', 'y', 'r', 'l'},
- /* 16 */ {'D', 'e', 'v', 'a'},
- /* 17 */ {'E', 'g', 'y', 'p'},
- /* 18 */ {'E', 't', 'h', 'i'},
- /* 19 */ {'G', 'e', 'o', 'r'},
- /* 20 */ {'G', 'o', 't', 'h'},
- /* 21 */ {'G', 'r', 'e', 'k'},
- /* 22 */ {'G', 'u', 'j', 'r'},
- /* 23 */ {'G', 'u', 'r', 'u'},
- /* 24 */ {'H', 'a', 'n', 's'},
- /* 25 */ {'H', 'a', 'n', 't'},
- /* 26 */ {'H', 'a', 't', 'r'},
- /* 27 */ {'H', 'e', 'b', 'r'},
- /* 28 */ {'H', 'l', 'u', 'w'},
- /* 29 */ {'H', 'm', 'n', 'g'},
- /* 30 */ {'I', 't', 'a', 'l'},
- /* 31 */ {'J', 'p', 'a', 'n'},
- /* 32 */ {'K', 'a', 'l', 'i'},
- /* 33 */ {'K', 'a', 'n', 'a'},
- /* 34 */ {'K', 'h', 'a', 'r'},
- /* 35 */ {'K', 'h', 'm', 'r'},
- /* 36 */ {'K', 'n', 'd', 'a'},
- /* 37 */ {'K', 'o', 'r', 'e'},
- /* 38 */ {'L', 'a', 'n', 'a'},
- /* 39 */ {'L', 'a', 'o', 'o'},
- /* 40 */ {'L', 'a', 't', 'n'},
- /* 41 */ {'L', 'e', 'p', 'c'},
- /* 42 */ {'L', 'i', 'n', 'a'},
- /* 43 */ {'L', 'i', 's', 'u'},
- /* 44 */ {'L', 'y', 'c', 'i'},
- /* 45 */ {'L', 'y', 'd', 'i'},
- /* 46 */ {'M', 'a', 'n', 'd'},
- /* 47 */ {'M', 'a', 'n', 'i'},
- /* 48 */ {'M', 'e', 'r', 'c'},
- /* 49 */ {'M', 'l', 'y', 'm'},
- /* 50 */ {'M', 'o', 'n', 'g'},
- /* 51 */ {'M', 'r', 'o', 'o'},
- /* 52 */ {'M', 'y', 'm', 'r'},
- /* 53 */ {'N', 'a', 'r', 'b'},
- /* 54 */ {'N', 'k', 'o', 'o'},
- /* 55 */ {'O', 'g', 'a', 'm'},
- /* 56 */ {'O', 'r', 'k', 'h'},
- /* 57 */ {'O', 'r', 'y', 'a'},
- /* 58 */ {'O', 's', 'g', 'e'},
- /* 59 */ {'P', 'a', 'u', 'c'},
- /* 60 */ {'P', 'h', 'l', 'i'},
- /* 61 */ {'P', 'h', 'n', 'x'},
- /* 62 */ {'P', 'l', 'r', 'd'},
- /* 63 */ {'P', 'r', 't', 'i'},
- /* 64 */ {'R', 'u', 'n', 'r'},
- /* 65 */ {'S', 'a', 'm', 'r'},
- /* 66 */ {'S', 'a', 'r', 'b'},
- /* 67 */ {'S', 'a', 'u', 'r'},
- /* 68 */ {'S', 'g', 'n', 'w'},
- /* 69 */ {'S', 'i', 'n', 'h'},
- /* 70 */ {'S', 'o', 'r', 'a'},
- /* 71 */ {'S', 'y', 'r', 'c'},
- /* 72 */ {'T', 'a', 'l', 'e'},
- /* 73 */ {'T', 'a', 'l', 'u'},
- /* 74 */ {'T', 'a', 'm', 'l'},
- /* 75 */ {'T', 'a', 'n', 'g'},
- /* 76 */ {'T', 'a', 'v', 't'},
- /* 77 */ {'T', 'e', 'l', 'u'},
- /* 78 */ {'T', 'f', 'n', 'g'},
- /* 79 */ {'T', 'h', 'a', 'a'},
- /* 80 */ {'T', 'h', 'a', 'i'},
- /* 81 */ {'T', 'i', 'b', 't'},
- /* 82 */ {'U', 'g', 'a', 'r'},
- /* 83 */ {'V', 'a', 'i', 'i'},
- /* 84 */ {'X', 'p', 'e', 'o'},
- /* 85 */ {'X', 's', 'u', 'x'},
- /* 86 */ {'Y', 'i', 'i', 'i'},
- /* 87 */ {'~', '~', '~', 'A'},
- /* 88 */ {'~', '~', '~', 'B'},
+ /* 9 */ {'C', 'a', 'k', 'm'},
+ /* 10 */ {'C', 'a', 'n', 's'},
+ /* 11 */ {'C', 'a', 'r', 'i'},
+ /* 12 */ {'C', 'h', 'a', 'm'},
+ /* 13 */ {'C', 'h', 'e', 'r'},
+ /* 14 */ {'C', 'o', 'p', 't'},
+ /* 15 */ {'C', 'p', 'r', 't'},
+ /* 16 */ {'C', 'y', 'r', 'l'},
+ /* 17 */ {'D', 'e', 'v', 'a'},
+ /* 18 */ {'E', 'g', 'y', 'p'},
+ /* 19 */ {'E', 't', 'h', 'i'},
+ /* 20 */ {'G', 'e', 'o', 'r'},
+ /* 21 */ {'G', 'o', 'n', 'g'},
+ /* 22 */ {'G', 'o', 'n', 'm'},
+ /* 23 */ {'G', 'o', 't', 'h'},
+ /* 24 */ {'G', 'r', 'e', 'k'},
+ /* 25 */ {'G', 'u', 'j', 'r'},
+ /* 26 */ {'G', 'u', 'r', 'u'},
+ /* 27 */ {'H', 'a', 'n', 's'},
+ /* 28 */ {'H', 'a', 'n', 't'},
+ /* 29 */ {'H', 'a', 't', 'r'},
+ /* 30 */ {'H', 'e', 'b', 'r'},
+ /* 31 */ {'H', 'l', 'u', 'w'},
+ /* 32 */ {'H', 'm', 'n', 'g'},
+ /* 33 */ {'H', 'm', 'n', 'p'},
+ /* 34 */ {'I', 't', 'a', 'l'},
+ /* 35 */ {'J', 'p', 'a', 'n'},
+ /* 36 */ {'K', 'a', 'l', 'i'},
+ /* 37 */ {'K', 'a', 'n', 'a'},
+ /* 38 */ {'K', 'h', 'a', 'r'},
+ /* 39 */ {'K', 'h', 'm', 'r'},
+ /* 40 */ {'K', 'n', 'd', 'a'},
+ /* 41 */ {'K', 'o', 'r', 'e'},
+ /* 42 */ {'L', 'a', 'n', 'a'},
+ /* 43 */ {'L', 'a', 'o', 'o'},
+ /* 44 */ {'L', 'a', 't', 'n'},
+ /* 45 */ {'L', 'e', 'p', 'c'},
+ /* 46 */ {'L', 'i', 'n', 'a'},
+ /* 47 */ {'L', 'i', 's', 'u'},
+ /* 48 */ {'L', 'y', 'c', 'i'},
+ /* 49 */ {'L', 'y', 'd', 'i'},
+ /* 50 */ {'M', 'a', 'n', 'd'},
+ /* 51 */ {'M', 'a', 'n', 'i'},
+ /* 52 */ {'M', 'e', 'r', 'c'},
+ /* 53 */ {'M', 'l', 'y', 'm'},
+ /* 54 */ {'M', 'o', 'n', 'g'},
+ /* 55 */ {'M', 'r', 'o', 'o'},
+ /* 56 */ {'M', 'y', 'm', 'r'},
+ /* 57 */ {'N', 'a', 'r', 'b'},
+ /* 58 */ {'N', 'k', 'o', 'o'},
+ /* 59 */ {'N', 's', 'h', 'u'},
+ /* 60 */ {'O', 'g', 'a', 'm'},
+ /* 61 */ {'O', 'r', 'k', 'h'},
+ /* 62 */ {'O', 'r', 'y', 'a'},
+ /* 63 */ {'O', 's', 'g', 'e'},
+ /* 64 */ {'P', 'a', 'u', 'c'},
+ /* 65 */ {'P', 'h', 'l', 'i'},
+ /* 66 */ {'P', 'h', 'n', 'x'},
+ /* 67 */ {'P', 'l', 'r', 'd'},
+ /* 68 */ {'P', 'r', 't', 'i'},
+ /* 69 */ {'R', 'u', 'n', 'r'},
+ /* 70 */ {'S', 'a', 'm', 'r'},
+ /* 71 */ {'S', 'a', 'r', 'b'},
+ /* 72 */ {'S', 'a', 'u', 'r'},
+ /* 73 */ {'S', 'g', 'n', 'w'},
+ /* 74 */ {'S', 'i', 'n', 'h'},
+ /* 75 */ {'S', 'o', 'g', 'd'},
+ /* 76 */ {'S', 'o', 'r', 'a'},
+ /* 77 */ {'S', 'o', 'y', 'o'},
+ /* 78 */ {'S', 'y', 'r', 'c'},
+ /* 79 */ {'T', 'a', 'l', 'e'},
+ /* 80 */ {'T', 'a', 'l', 'u'},
+ /* 81 */ {'T', 'a', 'm', 'l'},
+ /* 82 */ {'T', 'a', 'n', 'g'},
+ /* 83 */ {'T', 'a', 'v', 't'},
+ /* 84 */ {'T', 'e', 'l', 'u'},
+ /* 85 */ {'T', 'f', 'n', 'g'},
+ /* 86 */ {'T', 'h', 'a', 'a'},
+ /* 87 */ {'T', 'h', 'a', 'i'},
+ /* 88 */ {'T', 'i', 'b', 't'},
+ /* 89 */ {'U', 'g', 'a', 'r'},
+ /* 90 */ {'V', 'a', 'i', 'i'},
+ /* 91 */ {'W', 'c', 'h', 'o'},
+ /* 92 */ {'X', 'p', 'e', 'o'},
+ /* 93 */ {'X', 's', 'u', 'x'},
+ /* 94 */ {'Y', 'i', 'i', 'i'},
+ /* 95 */ {'~', '~', '~', 'A'},
+ /* 96 */ {'~', '~', '~', 'B'},
};
const std::unordered_map<uint32_t, uint8_t> LIKELY_SCRIPTS({
- {0x61610000u, 40u}, // aa -> Latn
- {0xA0000000u, 40u}, // aai -> Latn
- {0xA8000000u, 40u}, // aak -> Latn
- {0xD0000000u, 40u}, // aau -> Latn
- {0x61620000u, 15u}, // ab -> Cyrl
- {0xA0200000u, 40u}, // abi -> Latn
- {0xC4200000u, 40u}, // abr -> Latn
- {0xCC200000u, 40u}, // abt -> Latn
- {0xE0200000u, 40u}, // aby -> Latn
- {0x8C400000u, 40u}, // acd -> Latn
- {0x90400000u, 40u}, // ace -> Latn
- {0x9C400000u, 40u}, // ach -> Latn
- {0x80600000u, 40u}, // ada -> Latn
- {0x90600000u, 40u}, // ade -> Latn
- {0xA4600000u, 40u}, // adj -> Latn
- {0xE0600000u, 15u}, // ady -> Cyrl
- {0xE4600000u, 40u}, // adz -> Latn
+ {0x61610000u, 44u}, // aa -> Latn
+ {0xA0000000u, 44u}, // aai -> Latn
+ {0xA8000000u, 44u}, // aak -> Latn
+ {0xD0000000u, 44u}, // aau -> Latn
+ {0x61620000u, 16u}, // ab -> Cyrl
+ {0xA0200000u, 44u}, // abi -> Latn
+ {0xC0200000u, 16u}, // abq -> Cyrl
+ {0xC4200000u, 44u}, // abr -> Latn
+ {0xCC200000u, 44u}, // abt -> Latn
+ {0xE0200000u, 44u}, // aby -> Latn
+ {0x8C400000u, 44u}, // acd -> Latn
+ {0x90400000u, 44u}, // ace -> Latn
+ {0x9C400000u, 44u}, // ach -> Latn
+ {0x80600000u, 44u}, // ada -> Latn
+ {0x90600000u, 44u}, // ade -> Latn
+ {0xA4600000u, 44u}, // adj -> Latn
+ {0xE0600000u, 16u}, // ady -> Cyrl
+ {0xE4600000u, 44u}, // adz -> Latn
{0x61650000u, 4u}, // ae -> Avst
{0x84800000u, 1u}, // aeb -> Arab
- {0xE0800000u, 40u}, // aey -> Latn
- {0x61660000u, 40u}, // af -> Latn
- {0x88C00000u, 40u}, // agc -> Latn
- {0x8CC00000u, 40u}, // agd -> Latn
- {0x98C00000u, 40u}, // agg -> Latn
- {0xB0C00000u, 40u}, // agm -> Latn
- {0xB8C00000u, 40u}, // ago -> Latn
- {0xC0C00000u, 40u}, // agq -> Latn
- {0x80E00000u, 40u}, // aha -> Latn
- {0xACE00000u, 40u}, // ahl -> Latn
+ {0xE0800000u, 44u}, // aey -> Latn
+ {0x61660000u, 44u}, // af -> Latn
+ {0x88C00000u, 44u}, // agc -> Latn
+ {0x8CC00000u, 44u}, // agd -> Latn
+ {0x98C00000u, 44u}, // agg -> Latn
+ {0xB0C00000u, 44u}, // agm -> Latn
+ {0xB8C00000u, 44u}, // ago -> Latn
+ {0xC0C00000u, 44u}, // agq -> Latn
+ {0x80E00000u, 44u}, // aha -> Latn
+ {0xACE00000u, 44u}, // ahl -> Latn
{0xB8E00000u, 0u}, // aho -> Ahom
- {0x99200000u, 40u}, // ajg -> Latn
- {0x616B0000u, 40u}, // ak -> Latn
- {0xA9400000u, 85u}, // akk -> Xsux
- {0x81600000u, 40u}, // ala -> Latn
- {0xA1600000u, 40u}, // ali -> Latn
- {0xB5600000u, 40u}, // aln -> Latn
- {0xCD600000u, 15u}, // alt -> Cyrl
- {0x616D0000u, 18u}, // am -> Ethi
- {0xB1800000u, 40u}, // amm -> Latn
- {0xB5800000u, 40u}, // amn -> Latn
- {0xB9800000u, 40u}, // amo -> Latn
- {0xBD800000u, 40u}, // amp -> Latn
- {0x89A00000u, 40u}, // anc -> Latn
- {0xA9A00000u, 40u}, // ank -> Latn
- {0xB5A00000u, 40u}, // ann -> Latn
- {0xE1A00000u, 40u}, // any -> Latn
- {0xA5C00000u, 40u}, // aoj -> Latn
- {0xB1C00000u, 40u}, // aom -> Latn
- {0xE5C00000u, 40u}, // aoz -> Latn
+ {0x99200000u, 44u}, // ajg -> Latn
+ {0x616B0000u, 44u}, // ak -> Latn
+ {0xA9400000u, 93u}, // akk -> Xsux
+ {0x81600000u, 44u}, // ala -> Latn
+ {0xA1600000u, 44u}, // ali -> Latn
+ {0xB5600000u, 44u}, // aln -> Latn
+ {0xCD600000u, 16u}, // alt -> Cyrl
+ {0x616D0000u, 19u}, // am -> Ethi
+ {0xB1800000u, 44u}, // amm -> Latn
+ {0xB5800000u, 44u}, // amn -> Latn
+ {0xB9800000u, 44u}, // amo -> Latn
+ {0xBD800000u, 44u}, // amp -> Latn
+ {0x89A00000u, 44u}, // anc -> Latn
+ {0xA9A00000u, 44u}, // ank -> Latn
+ {0xB5A00000u, 44u}, // ann -> Latn
+ {0xE1A00000u, 44u}, // any -> Latn
+ {0xA5C00000u, 44u}, // aoj -> Latn
+ {0xB1C00000u, 44u}, // aom -> Latn
+ {0xE5C00000u, 44u}, // aoz -> Latn
{0x89E00000u, 1u}, // apc -> Arab
{0x8DE00000u, 1u}, // apd -> Arab
- {0x91E00000u, 40u}, // ape -> Latn
- {0xC5E00000u, 40u}, // apr -> Latn
- {0xC9E00000u, 40u}, // aps -> Latn
- {0xE5E00000u, 40u}, // apz -> Latn
+ {0x91E00000u, 44u}, // ape -> Latn
+ {0xC5E00000u, 44u}, // apr -> Latn
+ {0xC9E00000u, 44u}, // aps -> Latn
+ {0xE5E00000u, 44u}, // apz -> Latn
{0x61720000u, 1u}, // ar -> Arab
- {0x61725842u, 88u}, // ar-XB -> ~~~B
+ {0x61725842u, 96u}, // ar-XB -> ~~~B
{0x8A200000u, 2u}, // arc -> Armi
- {0x9E200000u, 40u}, // arh -> Latn
- {0xB6200000u, 40u}, // arn -> Latn
- {0xBA200000u, 40u}, // aro -> Latn
+ {0x9E200000u, 44u}, // arh -> Latn
+ {0xB6200000u, 44u}, // arn -> Latn
+ {0xBA200000u, 44u}, // aro -> Latn
{0xC2200000u, 1u}, // arq -> Arab
{0xE2200000u, 1u}, // ary -> Arab
{0xE6200000u, 1u}, // arz -> Arab
{0x61730000u, 7u}, // as -> Beng
- {0x82400000u, 40u}, // asa -> Latn
- {0x92400000u, 68u}, // ase -> Sgnw
- {0x9A400000u, 40u}, // asg -> Latn
- {0xBA400000u, 40u}, // aso -> Latn
- {0xCE400000u, 40u}, // ast -> Latn
- {0x82600000u, 40u}, // ata -> Latn
- {0x9A600000u, 40u}, // atg -> Latn
- {0xA6600000u, 40u}, // atj -> Latn
- {0xE2800000u, 40u}, // auy -> Latn
- {0x61760000u, 15u}, // av -> Cyrl
+ {0x82400000u, 44u}, // asa -> Latn
+ {0x92400000u, 73u}, // ase -> Sgnw
+ {0x9A400000u, 44u}, // asg -> Latn
+ {0xBA400000u, 44u}, // aso -> Latn
+ {0xCE400000u, 44u}, // ast -> Latn
+ {0x82600000u, 44u}, // ata -> Latn
+ {0x9A600000u, 44u}, // atg -> Latn
+ {0xA6600000u, 44u}, // atj -> Latn
+ {0xE2800000u, 44u}, // auy -> Latn
+ {0x61760000u, 16u}, // av -> Cyrl
{0xAEA00000u, 1u}, // avl -> Arab
- {0xB6A00000u, 40u}, // avn -> Latn
- {0xCEA00000u, 40u}, // avt -> Latn
- {0xD2A00000u, 40u}, // avu -> Latn
- {0x82C00000u, 16u}, // awa -> Deva
- {0x86C00000u, 40u}, // awb -> Latn
- {0xBAC00000u, 40u}, // awo -> Latn
- {0xDEC00000u, 40u}, // awx -> Latn
- {0x61790000u, 40u}, // ay -> Latn
- {0x87000000u, 40u}, // ayb -> Latn
- {0x617A0000u, 40u}, // az -> Latn
+ {0xB6A00000u, 44u}, // avn -> Latn
+ {0xCEA00000u, 44u}, // avt -> Latn
+ {0xD2A00000u, 44u}, // avu -> Latn
+ {0x82C00000u, 17u}, // awa -> Deva
+ {0x86C00000u, 44u}, // awb -> Latn
+ {0xBAC00000u, 44u}, // awo -> Latn
+ {0xDEC00000u, 44u}, // awx -> Latn
+ {0x61790000u, 44u}, // ay -> Latn
+ {0x87000000u, 44u}, // ayb -> Latn
+ {0x617A0000u, 44u}, // az -> Latn
{0x617A4951u, 1u}, // az-IQ -> Arab
{0x617A4952u, 1u}, // az-IR -> Arab
- {0x617A5255u, 15u}, // az-RU -> Cyrl
- {0x62610000u, 15u}, // ba -> Cyrl
+ {0x617A5255u, 16u}, // az-RU -> Cyrl
+ {0x62610000u, 16u}, // ba -> Cyrl
{0xAC010000u, 1u}, // bal -> Arab
- {0xB4010000u, 40u}, // ban -> Latn
- {0xBC010000u, 16u}, // bap -> Deva
- {0xC4010000u, 40u}, // bar -> Latn
- {0xC8010000u, 40u}, // bas -> Latn
- {0xD4010000u, 40u}, // bav -> Latn
+ {0xB4010000u, 44u}, // ban -> Latn
+ {0xBC010000u, 17u}, // bap -> Deva
+ {0xC4010000u, 44u}, // bar -> Latn
+ {0xC8010000u, 44u}, // bas -> Latn
+ {0xD4010000u, 44u}, // bav -> Latn
{0xDC010000u, 5u}, // bax -> Bamu
- {0x80210000u, 40u}, // bba -> Latn
- {0x84210000u, 40u}, // bbb -> Latn
- {0x88210000u, 40u}, // bbc -> Latn
- {0x8C210000u, 40u}, // bbd -> Latn
- {0xA4210000u, 40u}, // bbj -> Latn
- {0xBC210000u, 40u}, // bbp -> Latn
- {0xC4210000u, 40u}, // bbr -> Latn
- {0x94410000u, 40u}, // bcf -> Latn
- {0x9C410000u, 40u}, // bch -> Latn
- {0xA0410000u, 40u}, // bci -> Latn
- {0xB0410000u, 40u}, // bcm -> Latn
- {0xB4410000u, 40u}, // bcn -> Latn
- {0xB8410000u, 40u}, // bco -> Latn
- {0xC0410000u, 18u}, // bcq -> Ethi
- {0xD0410000u, 40u}, // bcu -> Latn
- {0x8C610000u, 40u}, // bdd -> Latn
- {0x62650000u, 15u}, // be -> Cyrl
- {0x94810000u, 40u}, // bef -> Latn
- {0x9C810000u, 40u}, // beh -> Latn
+ {0x80210000u, 44u}, // bba -> Latn
+ {0x84210000u, 44u}, // bbb -> Latn
+ {0x88210000u, 44u}, // bbc -> Latn
+ {0x8C210000u, 44u}, // bbd -> Latn
+ {0xA4210000u, 44u}, // bbj -> Latn
+ {0xBC210000u, 44u}, // bbp -> Latn
+ {0xC4210000u, 44u}, // bbr -> Latn
+ {0x94410000u, 44u}, // bcf -> Latn
+ {0x9C410000u, 44u}, // bch -> Latn
+ {0xA0410000u, 44u}, // bci -> Latn
+ {0xB0410000u, 44u}, // bcm -> Latn
+ {0xB4410000u, 44u}, // bcn -> Latn
+ {0xB8410000u, 44u}, // bco -> Latn
+ {0xC0410000u, 19u}, // bcq -> Ethi
+ {0xD0410000u, 44u}, // bcu -> Latn
+ {0x8C610000u, 44u}, // bdd -> Latn
+ {0x62650000u, 16u}, // be -> Cyrl
+ {0x94810000u, 44u}, // bef -> Latn
+ {0x9C810000u, 44u}, // beh -> Latn
{0xA4810000u, 1u}, // bej -> Arab
- {0xB0810000u, 40u}, // bem -> Latn
- {0xCC810000u, 40u}, // bet -> Latn
- {0xD8810000u, 40u}, // bew -> Latn
- {0xDC810000u, 40u}, // bex -> Latn
- {0xE4810000u, 40u}, // bez -> Latn
- {0x8CA10000u, 40u}, // bfd -> Latn
- {0xC0A10000u, 74u}, // bfq -> Taml
+ {0xB0810000u, 44u}, // bem -> Latn
+ {0xCC810000u, 44u}, // bet -> Latn
+ {0xD8810000u, 44u}, // bew -> Latn
+ {0xDC810000u, 44u}, // bex -> Latn
+ {0xE4810000u, 44u}, // bez -> Latn
+ {0x8CA10000u, 44u}, // bfd -> Latn
+ {0xC0A10000u, 81u}, // bfq -> Taml
{0xCCA10000u, 1u}, // bft -> Arab
- {0xE0A10000u, 16u}, // bfy -> Deva
- {0x62670000u, 15u}, // bg -> Cyrl
- {0x88C10000u, 16u}, // bgc -> Deva
+ {0xE0A10000u, 17u}, // bfy -> Deva
+ {0x62670000u, 16u}, // bg -> Cyrl
+ {0x88C10000u, 17u}, // bgc -> Deva
{0xB4C10000u, 1u}, // bgn -> Arab
- {0xDCC10000u, 21u}, // bgx -> Grek
- {0x84E10000u, 16u}, // bhb -> Deva
- {0x98E10000u, 40u}, // bhg -> Latn
- {0xA0E10000u, 16u}, // bhi -> Deva
- {0xA8E10000u, 40u}, // bhk -> Latn
- {0xACE10000u, 40u}, // bhl -> Latn
- {0xB8E10000u, 16u}, // bho -> Deva
- {0xE0E10000u, 40u}, // bhy -> Latn
- {0x62690000u, 40u}, // bi -> Latn
- {0x85010000u, 40u}, // bib -> Latn
- {0x99010000u, 40u}, // big -> Latn
- {0xA9010000u, 40u}, // bik -> Latn
- {0xB1010000u, 40u}, // bim -> Latn
- {0xB5010000u, 40u}, // bin -> Latn
- {0xB9010000u, 40u}, // bio -> Latn
- {0xC1010000u, 40u}, // biq -> Latn
- {0x9D210000u, 40u}, // bjh -> Latn
- {0xA1210000u, 18u}, // bji -> Ethi
- {0xA5210000u, 16u}, // bjj -> Deva
- {0xB5210000u, 40u}, // bjn -> Latn
- {0xB9210000u, 40u}, // bjo -> Latn
- {0xC5210000u, 40u}, // bjr -> Latn
- {0xE5210000u, 40u}, // bjz -> Latn
- {0x89410000u, 40u}, // bkc -> Latn
- {0xB1410000u, 40u}, // bkm -> Latn
- {0xC1410000u, 40u}, // bkq -> Latn
- {0xD1410000u, 40u}, // bku -> Latn
- {0xD5410000u, 40u}, // bkv -> Latn
- {0xCD610000u, 76u}, // blt -> Tavt
- {0x626D0000u, 40u}, // bm -> Latn
- {0x9D810000u, 40u}, // bmh -> Latn
- {0xA9810000u, 40u}, // bmk -> Latn
- {0xC1810000u, 40u}, // bmq -> Latn
- {0xD1810000u, 40u}, // bmu -> Latn
+ {0xDCC10000u, 24u}, // bgx -> Grek
+ {0x84E10000u, 17u}, // bhb -> Deva
+ {0x98E10000u, 44u}, // bhg -> Latn
+ {0xA0E10000u, 17u}, // bhi -> Deva
+ {0xA8E10000u, 44u}, // bhk -> Latn
+ {0xACE10000u, 44u}, // bhl -> Latn
+ {0xB8E10000u, 17u}, // bho -> Deva
+ {0xE0E10000u, 44u}, // bhy -> Latn
+ {0x62690000u, 44u}, // bi -> Latn
+ {0x85010000u, 44u}, // bib -> Latn
+ {0x99010000u, 44u}, // big -> Latn
+ {0xA9010000u, 44u}, // bik -> Latn
+ {0xB1010000u, 44u}, // bim -> Latn
+ {0xB5010000u, 44u}, // bin -> Latn
+ {0xB9010000u, 44u}, // bio -> Latn
+ {0xC1010000u, 44u}, // biq -> Latn
+ {0x9D210000u, 44u}, // bjh -> Latn
+ {0xA1210000u, 19u}, // bji -> Ethi
+ {0xA5210000u, 17u}, // bjj -> Deva
+ {0xB5210000u, 44u}, // bjn -> Latn
+ {0xB9210000u, 44u}, // bjo -> Latn
+ {0xC5210000u, 44u}, // bjr -> Latn
+ {0xCD210000u, 44u}, // bjt -> Latn
+ {0xE5210000u, 44u}, // bjz -> Latn
+ {0x89410000u, 44u}, // bkc -> Latn
+ {0xB1410000u, 44u}, // bkm -> Latn
+ {0xC1410000u, 44u}, // bkq -> Latn
+ {0xD1410000u, 44u}, // bku -> Latn
+ {0xD5410000u, 44u}, // bkv -> Latn
+ {0xCD610000u, 83u}, // blt -> Tavt
+ {0x626D0000u, 44u}, // bm -> Latn
+ {0x9D810000u, 44u}, // bmh -> Latn
+ {0xA9810000u, 44u}, // bmk -> Latn
+ {0xC1810000u, 44u}, // bmq -> Latn
+ {0xD1810000u, 44u}, // bmu -> Latn
{0x626E0000u, 7u}, // bn -> Beng
- {0x99A10000u, 40u}, // bng -> Latn
- {0xB1A10000u, 40u}, // bnm -> Latn
- {0xBDA10000u, 40u}, // bnp -> Latn
- {0x626F0000u, 81u}, // bo -> Tibt
- {0xA5C10000u, 40u}, // boj -> Latn
- {0xB1C10000u, 40u}, // bom -> Latn
- {0xB5C10000u, 40u}, // bon -> Latn
+ {0x99A10000u, 44u}, // bng -> Latn
+ {0xB1A10000u, 44u}, // bnm -> Latn
+ {0xBDA10000u, 44u}, // bnp -> Latn
+ {0x626F0000u, 88u}, // bo -> Tibt
+ {0xA5C10000u, 44u}, // boj -> Latn
+ {0xB1C10000u, 44u}, // bom -> Latn
+ {0xB5C10000u, 44u}, // bon -> Latn
{0xE1E10000u, 7u}, // bpy -> Beng
- {0x8A010000u, 40u}, // bqc -> Latn
+ {0x8A010000u, 44u}, // bqc -> Latn
{0xA2010000u, 1u}, // bqi -> Arab
- {0xBE010000u, 40u}, // bqp -> Latn
- {0xD6010000u, 40u}, // bqv -> Latn
- {0x62720000u, 40u}, // br -> Latn
- {0x82210000u, 16u}, // bra -> Deva
+ {0xBE010000u, 44u}, // bqp -> Latn
+ {0xD6010000u, 44u}, // bqv -> Latn
+ {0x62720000u, 44u}, // br -> Latn
+ {0x82210000u, 17u}, // bra -> Deva
{0x9E210000u, 1u}, // brh -> Arab
- {0xDE210000u, 16u}, // brx -> Deva
- {0xE6210000u, 40u}, // brz -> Latn
- {0x62730000u, 40u}, // bs -> Latn
- {0xA6410000u, 40u}, // bsj -> Latn
+ {0xDE210000u, 17u}, // brx -> Deva
+ {0xE6210000u, 44u}, // brz -> Latn
+ {0x62730000u, 44u}, // bs -> Latn
+ {0xA6410000u, 44u}, // bsj -> Latn
{0xC2410000u, 6u}, // bsq -> Bass
- {0xCA410000u, 40u}, // bss -> Latn
- {0xCE410000u, 18u}, // bst -> Ethi
- {0xBA610000u, 40u}, // bto -> Latn
- {0xCE610000u, 40u}, // btt -> Latn
- {0xD6610000u, 16u}, // btv -> Deva
- {0x82810000u, 15u}, // bua -> Cyrl
- {0x8A810000u, 40u}, // buc -> Latn
- {0x8E810000u, 40u}, // bud -> Latn
- {0x9A810000u, 40u}, // bug -> Latn
- {0xAA810000u, 40u}, // buk -> Latn
- {0xB2810000u, 40u}, // bum -> Latn
- {0xBA810000u, 40u}, // buo -> Latn
- {0xCA810000u, 40u}, // bus -> Latn
- {0xD2810000u, 40u}, // buu -> Latn
- {0x86A10000u, 40u}, // bvb -> Latn
- {0x8EC10000u, 40u}, // bwd -> Latn
- {0xC6C10000u, 40u}, // bwr -> Latn
- {0x9EE10000u, 40u}, // bxh -> Latn
- {0x93010000u, 40u}, // bye -> Latn
- {0xB7010000u, 18u}, // byn -> Ethi
- {0xC7010000u, 40u}, // byr -> Latn
- {0xCB010000u, 40u}, // bys -> Latn
- {0xD7010000u, 40u}, // byv -> Latn
- {0xDF010000u, 40u}, // byx -> Latn
- {0x83210000u, 40u}, // bza -> Latn
- {0x93210000u, 40u}, // bze -> Latn
- {0x97210000u, 40u}, // bzf -> Latn
- {0x9F210000u, 40u}, // bzh -> Latn
- {0xDB210000u, 40u}, // bzw -> Latn
- {0x63610000u, 40u}, // ca -> Latn
- {0xB4020000u, 40u}, // can -> Latn
- {0xA4220000u, 40u}, // cbj -> Latn
- {0x9C420000u, 40u}, // cch -> Latn
- {0xBC420000u, 7u}, // ccp -> Beng
- {0x63650000u, 15u}, // ce -> Cyrl
- {0x84820000u, 40u}, // ceb -> Latn
- {0x80A20000u, 40u}, // cfa -> Latn
- {0x98C20000u, 40u}, // cgg -> Latn
- {0x63680000u, 40u}, // ch -> Latn
- {0xA8E20000u, 40u}, // chk -> Latn
- {0xB0E20000u, 15u}, // chm -> Cyrl
- {0xB8E20000u, 40u}, // cho -> Latn
- {0xBCE20000u, 40u}, // chp -> Latn
- {0xC4E20000u, 12u}, // chr -> Cher
+ {0xCA410000u, 44u}, // bss -> Latn
+ {0xCE410000u, 19u}, // bst -> Ethi
+ {0xBA610000u, 44u}, // bto -> Latn
+ {0xCE610000u, 44u}, // btt -> Latn
+ {0xD6610000u, 17u}, // btv -> Deva
+ {0x82810000u, 16u}, // bua -> Cyrl
+ {0x8A810000u, 44u}, // buc -> Latn
+ {0x8E810000u, 44u}, // bud -> Latn
+ {0x9A810000u, 44u}, // bug -> Latn
+ {0xAA810000u, 44u}, // buk -> Latn
+ {0xB2810000u, 44u}, // bum -> Latn
+ {0xBA810000u, 44u}, // buo -> Latn
+ {0xCA810000u, 44u}, // bus -> Latn
+ {0xD2810000u, 44u}, // buu -> Latn
+ {0x86A10000u, 44u}, // bvb -> Latn
+ {0x8EC10000u, 44u}, // bwd -> Latn
+ {0xC6C10000u, 44u}, // bwr -> Latn
+ {0x9EE10000u, 44u}, // bxh -> Latn
+ {0x93010000u, 44u}, // bye -> Latn
+ {0xB7010000u, 19u}, // byn -> Ethi
+ {0xC7010000u, 44u}, // byr -> Latn
+ {0xCB010000u, 44u}, // bys -> Latn
+ {0xD7010000u, 44u}, // byv -> Latn
+ {0xDF010000u, 44u}, // byx -> Latn
+ {0x83210000u, 44u}, // bza -> Latn
+ {0x93210000u, 44u}, // bze -> Latn
+ {0x97210000u, 44u}, // bzf -> Latn
+ {0x9F210000u, 44u}, // bzh -> Latn
+ {0xDB210000u, 44u}, // bzw -> Latn
+ {0x63610000u, 44u}, // ca -> Latn
+ {0xB4020000u, 44u}, // can -> Latn
+ {0xA4220000u, 44u}, // cbj -> Latn
+ {0x9C420000u, 44u}, // cch -> Latn
+ {0xBC420000u, 9u}, // ccp -> Cakm
+ {0x63650000u, 16u}, // ce -> Cyrl
+ {0x84820000u, 44u}, // ceb -> Latn
+ {0x80A20000u, 44u}, // cfa -> Latn
+ {0x98C20000u, 44u}, // cgg -> Latn
+ {0x63680000u, 44u}, // ch -> Latn
+ {0xA8E20000u, 44u}, // chk -> Latn
+ {0xB0E20000u, 16u}, // chm -> Cyrl
+ {0xB8E20000u, 44u}, // cho -> Latn
+ {0xBCE20000u, 44u}, // chp -> Latn
+ {0xC4E20000u, 13u}, // chr -> Cher
{0x81220000u, 1u}, // cja -> Arab
- {0xB1220000u, 11u}, // cjm -> Cham
- {0xD5220000u, 40u}, // cjv -> Latn
+ {0xB1220000u, 12u}, // cjm -> Cham
+ {0xD5220000u, 44u}, // cjv -> Latn
{0x85420000u, 1u}, // ckb -> Arab
- {0xAD420000u, 40u}, // ckl -> Latn
- {0xB9420000u, 40u}, // cko -> Latn
- {0xE1420000u, 40u}, // cky -> Latn
- {0x81620000u, 40u}, // cla -> Latn
- {0x91820000u, 40u}, // cme -> Latn
- {0x636F0000u, 40u}, // co -> Latn
- {0xBDC20000u, 13u}, // cop -> Copt
- {0xC9E20000u, 40u}, // cps -> Latn
- {0x63720000u, 9u}, // cr -> Cans
- {0xA6220000u, 9u}, // crj -> Cans
- {0xAA220000u, 9u}, // crk -> Cans
- {0xAE220000u, 9u}, // crl -> Cans
- {0xB2220000u, 9u}, // crm -> Cans
- {0xCA220000u, 40u}, // crs -> Latn
- {0x63730000u, 40u}, // cs -> Latn
- {0x86420000u, 40u}, // csb -> Latn
- {0xDA420000u, 9u}, // csw -> Cans
- {0x8E620000u, 59u}, // ctd -> Pauc
- {0x63750000u, 15u}, // cu -> Cyrl
- {0x63760000u, 15u}, // cv -> Cyrl
- {0x63790000u, 40u}, // cy -> Latn
- {0x64610000u, 40u}, // da -> Latn
- {0x8C030000u, 40u}, // dad -> Latn
- {0x94030000u, 40u}, // daf -> Latn
- {0x98030000u, 40u}, // dag -> Latn
- {0x9C030000u, 40u}, // dah -> Latn
- {0xA8030000u, 40u}, // dak -> Latn
- {0xC4030000u, 15u}, // dar -> Cyrl
- {0xD4030000u, 40u}, // dav -> Latn
- {0x8C230000u, 40u}, // dbd -> Latn
- {0xC0230000u, 40u}, // dbq -> Latn
+ {0xAD420000u, 44u}, // ckl -> Latn
+ {0xB9420000u, 44u}, // cko -> Latn
+ {0xE1420000u, 44u}, // cky -> Latn
+ {0x81620000u, 44u}, // cla -> Latn
+ {0x91820000u, 44u}, // cme -> Latn
+ {0x99820000u, 77u}, // cmg -> Soyo
+ {0x636F0000u, 44u}, // co -> Latn
+ {0xBDC20000u, 14u}, // cop -> Copt
+ {0xC9E20000u, 44u}, // cps -> Latn
+ {0x63720000u, 10u}, // cr -> Cans
+ {0x9E220000u, 16u}, // crh -> Cyrl
+ {0xA6220000u, 10u}, // crj -> Cans
+ {0xAA220000u, 10u}, // crk -> Cans
+ {0xAE220000u, 10u}, // crl -> Cans
+ {0xB2220000u, 10u}, // crm -> Cans
+ {0xCA220000u, 44u}, // crs -> Latn
+ {0x63730000u, 44u}, // cs -> Latn
+ {0x86420000u, 44u}, // csb -> Latn
+ {0xDA420000u, 10u}, // csw -> Cans
+ {0x8E620000u, 64u}, // ctd -> Pauc
+ {0x63750000u, 16u}, // cu -> Cyrl
+ {0x63760000u, 16u}, // cv -> Cyrl
+ {0x63790000u, 44u}, // cy -> Latn
+ {0x64610000u, 44u}, // da -> Latn
+ {0x8C030000u, 44u}, // dad -> Latn
+ {0x94030000u, 44u}, // daf -> Latn
+ {0x98030000u, 44u}, // dag -> Latn
+ {0x9C030000u, 44u}, // dah -> Latn
+ {0xA8030000u, 44u}, // dak -> Latn
+ {0xC4030000u, 16u}, // dar -> Cyrl
+ {0xD4030000u, 44u}, // dav -> Latn
+ {0x8C230000u, 44u}, // dbd -> Latn
+ {0xC0230000u, 44u}, // dbq -> Latn
{0x88430000u, 1u}, // dcc -> Arab
- {0xB4630000u, 40u}, // ddn -> Latn
- {0x64650000u, 40u}, // de -> Latn
- {0x8C830000u, 40u}, // ded -> Latn
- {0xB4830000u, 40u}, // den -> Latn
- {0x80C30000u, 40u}, // dga -> Latn
- {0x9CC30000u, 40u}, // dgh -> Latn
- {0xA0C30000u, 40u}, // dgi -> Latn
+ {0xB4630000u, 44u}, // ddn -> Latn
+ {0x64650000u, 44u}, // de -> Latn
+ {0x8C830000u, 44u}, // ded -> Latn
+ {0xB4830000u, 44u}, // den -> Latn
+ {0x80C30000u, 44u}, // dga -> Latn
+ {0x9CC30000u, 44u}, // dgh -> Latn
+ {0xA0C30000u, 44u}, // dgi -> Latn
{0xACC30000u, 1u}, // dgl -> Arab
- {0xC4C30000u, 40u}, // dgr -> Latn
- {0xE4C30000u, 40u}, // dgz -> Latn
- {0x81030000u, 40u}, // dia -> Latn
- {0x91230000u, 40u}, // dje -> Latn
- {0xA5A30000u, 40u}, // dnj -> Latn
- {0x85C30000u, 40u}, // dob -> Latn
+ {0xC4C30000u, 44u}, // dgr -> Latn
+ {0xE4C30000u, 44u}, // dgz -> Latn
+ {0x81030000u, 44u}, // dia -> Latn
+ {0x91230000u, 44u}, // dje -> Latn
+ {0xA5A30000u, 44u}, // dnj -> Latn
+ {0x85C30000u, 44u}, // dob -> Latn
{0xA1C30000u, 1u}, // doi -> Arab
- {0xBDC30000u, 40u}, // dop -> Latn
- {0xD9C30000u, 40u}, // dow -> Latn
- {0xA2230000u, 40u}, // dri -> Latn
- {0xCA230000u, 18u}, // drs -> Ethi
- {0x86430000u, 40u}, // dsb -> Latn
- {0xB2630000u, 40u}, // dtm -> Latn
- {0xBE630000u, 40u}, // dtp -> Latn
- {0xCA630000u, 40u}, // dts -> Latn
- {0xE2630000u, 16u}, // dty -> Deva
- {0x82830000u, 40u}, // dua -> Latn
- {0x8A830000u, 40u}, // duc -> Latn
- {0x8E830000u, 40u}, // dud -> Latn
- {0x9A830000u, 40u}, // dug -> Latn
- {0x64760000u, 79u}, // dv -> Thaa
- {0x82A30000u, 40u}, // dva -> Latn
- {0xDAC30000u, 40u}, // dww -> Latn
- {0xBB030000u, 40u}, // dyo -> Latn
- {0xD3030000u, 40u}, // dyu -> Latn
- {0x647A0000u, 81u}, // dz -> Tibt
- {0x9B230000u, 40u}, // dzg -> Latn
- {0xD0240000u, 40u}, // ebu -> Latn
- {0x65650000u, 40u}, // ee -> Latn
- {0xA0A40000u, 40u}, // efi -> Latn
- {0xACC40000u, 40u}, // egl -> Latn
- {0xE0C40000u, 17u}, // egy -> Egyp
- {0xE1440000u, 32u}, // eky -> Kali
- {0x656C0000u, 21u}, // el -> Grek
- {0x81840000u, 40u}, // ema -> Latn
- {0xA1840000u, 40u}, // emi -> Latn
- {0x656E0000u, 40u}, // en -> Latn
- {0x656E5841u, 87u}, // en-XA -> ~~~A
- {0xB5A40000u, 40u}, // enn -> Latn
- {0xC1A40000u, 40u}, // enq -> Latn
- {0x656F0000u, 40u}, // eo -> Latn
- {0xA2240000u, 40u}, // eri -> Latn
- {0x65730000u, 40u}, // es -> Latn
- {0xD2440000u, 40u}, // esu -> Latn
- {0x65740000u, 40u}, // et -> Latn
- {0xC6640000u, 40u}, // etr -> Latn
- {0xCE640000u, 30u}, // ett -> Ital
- {0xD2640000u, 40u}, // etu -> Latn
- {0xDE640000u, 40u}, // etx -> Latn
- {0x65750000u, 40u}, // eu -> Latn
- {0xBAC40000u, 40u}, // ewo -> Latn
- {0xCEE40000u, 40u}, // ext -> Latn
+ {0xBDC30000u, 44u}, // dop -> Latn
+ {0xD9C30000u, 44u}, // dow -> Latn
+ {0xA2230000u, 44u}, // dri -> Latn
+ {0xCA230000u, 19u}, // drs -> Ethi
+ {0x86430000u, 44u}, // dsb -> Latn
+ {0xB2630000u, 44u}, // dtm -> Latn
+ {0xBE630000u, 44u}, // dtp -> Latn
+ {0xCA630000u, 44u}, // dts -> Latn
+ {0xE2630000u, 17u}, // dty -> Deva
+ {0x82830000u, 44u}, // dua -> Latn
+ {0x8A830000u, 44u}, // duc -> Latn
+ {0x8E830000u, 44u}, // dud -> Latn
+ {0x9A830000u, 44u}, // dug -> Latn
+ {0x64760000u, 86u}, // dv -> Thaa
+ {0x82A30000u, 44u}, // dva -> Latn
+ {0xDAC30000u, 44u}, // dww -> Latn
+ {0xBB030000u, 44u}, // dyo -> Latn
+ {0xD3030000u, 44u}, // dyu -> Latn
+ {0x647A0000u, 88u}, // dz -> Tibt
+ {0x9B230000u, 44u}, // dzg -> Latn
+ {0xD0240000u, 44u}, // ebu -> Latn
+ {0x65650000u, 44u}, // ee -> Latn
+ {0xA0A40000u, 44u}, // efi -> Latn
+ {0xACC40000u, 44u}, // egl -> Latn
+ {0xE0C40000u, 18u}, // egy -> Egyp
+ {0x81440000u, 44u}, // eka -> Latn
+ {0xE1440000u, 36u}, // eky -> Kali
+ {0x656C0000u, 24u}, // el -> Grek
+ {0x81840000u, 44u}, // ema -> Latn
+ {0xA1840000u, 44u}, // emi -> Latn
+ {0x656E0000u, 44u}, // en -> Latn
+ {0x656E5841u, 95u}, // en-XA -> ~~~A
+ {0xB5A40000u, 44u}, // enn -> Latn
+ {0xC1A40000u, 44u}, // enq -> Latn
+ {0x656F0000u, 44u}, // eo -> Latn
+ {0xA2240000u, 44u}, // eri -> Latn
+ {0x65730000u, 44u}, // es -> Latn
+ {0x9A440000u, 22u}, // esg -> Gonm
+ {0xD2440000u, 44u}, // esu -> Latn
+ {0x65740000u, 44u}, // et -> Latn
+ {0xC6640000u, 44u}, // etr -> Latn
+ {0xCE640000u, 34u}, // ett -> Ital
+ {0xD2640000u, 44u}, // etu -> Latn
+ {0xDE640000u, 44u}, // etx -> Latn
+ {0x65750000u, 44u}, // eu -> Latn
+ {0xBAC40000u, 44u}, // ewo -> Latn
+ {0xCEE40000u, 44u}, // ext -> Latn
{0x66610000u, 1u}, // fa -> Arab
- {0x80050000u, 40u}, // faa -> Latn
- {0x84050000u, 40u}, // fab -> Latn
- {0x98050000u, 40u}, // fag -> Latn
- {0xA0050000u, 40u}, // fai -> Latn
- {0xB4050000u, 40u}, // fan -> Latn
- {0x66660000u, 40u}, // ff -> Latn
- {0xA0A50000u, 40u}, // ffi -> Latn
- {0xB0A50000u, 40u}, // ffm -> Latn
- {0x66690000u, 40u}, // fi -> Latn
+ {0x80050000u, 44u}, // faa -> Latn
+ {0x84050000u, 44u}, // fab -> Latn
+ {0x98050000u, 44u}, // fag -> Latn
+ {0xA0050000u, 44u}, // fai -> Latn
+ {0xB4050000u, 44u}, // fan -> Latn
+ {0x66660000u, 44u}, // ff -> Latn
+ {0xA0A50000u, 44u}, // ffi -> Latn
+ {0xB0A50000u, 44u}, // ffm -> Latn
+ {0x66690000u, 44u}, // fi -> Latn
{0x81050000u, 1u}, // fia -> Arab
- {0xAD050000u, 40u}, // fil -> Latn
- {0xCD050000u, 40u}, // fit -> Latn
- {0x666A0000u, 40u}, // fj -> Latn
- {0xC5650000u, 40u}, // flr -> Latn
- {0xBD850000u, 40u}, // fmp -> Latn
- {0x666F0000u, 40u}, // fo -> Latn
- {0x8DC50000u, 40u}, // fod -> Latn
- {0xB5C50000u, 40u}, // fon -> Latn
- {0xC5C50000u, 40u}, // for -> Latn
- {0x91E50000u, 40u}, // fpe -> Latn
- {0xCA050000u, 40u}, // fqs -> Latn
- {0x66720000u, 40u}, // fr -> Latn
- {0x8A250000u, 40u}, // frc -> Latn
- {0xBE250000u, 40u}, // frp -> Latn
- {0xC6250000u, 40u}, // frr -> Latn
- {0xCA250000u, 40u}, // frs -> Latn
+ {0xAD050000u, 44u}, // fil -> Latn
+ {0xCD050000u, 44u}, // fit -> Latn
+ {0x666A0000u, 44u}, // fj -> Latn
+ {0xC5650000u, 44u}, // flr -> Latn
+ {0xBD850000u, 44u}, // fmp -> Latn
+ {0x666F0000u, 44u}, // fo -> Latn
+ {0x8DC50000u, 44u}, // fod -> Latn
+ {0xB5C50000u, 44u}, // fon -> Latn
+ {0xC5C50000u, 44u}, // for -> Latn
+ {0x91E50000u, 44u}, // fpe -> Latn
+ {0xCA050000u, 44u}, // fqs -> Latn
+ {0x66720000u, 44u}, // fr -> Latn
+ {0x8A250000u, 44u}, // frc -> Latn
+ {0xBE250000u, 44u}, // frp -> Latn
+ {0xC6250000u, 44u}, // frr -> Latn
+ {0xCA250000u, 44u}, // frs -> Latn
{0x86850000u, 1u}, // fub -> Arab
- {0x8E850000u, 40u}, // fud -> Latn
- {0x92850000u, 40u}, // fue -> Latn
- {0x96850000u, 40u}, // fuf -> Latn
- {0x9E850000u, 40u}, // fuh -> Latn
- {0xC2850000u, 40u}, // fuq -> Latn
- {0xC6850000u, 40u}, // fur -> Latn
- {0xD6850000u, 40u}, // fuv -> Latn
- {0xE2850000u, 40u}, // fuy -> Latn
- {0xC6A50000u, 40u}, // fvr -> Latn
- {0x66790000u, 40u}, // fy -> Latn
- {0x67610000u, 40u}, // ga -> Latn
- {0x80060000u, 40u}, // gaa -> Latn
- {0x94060000u, 40u}, // gaf -> Latn
- {0x98060000u, 40u}, // gag -> Latn
- {0x9C060000u, 40u}, // gah -> Latn
- {0xA4060000u, 40u}, // gaj -> Latn
- {0xB0060000u, 40u}, // gam -> Latn
- {0xB4060000u, 24u}, // gan -> Hans
- {0xD8060000u, 40u}, // gaw -> Latn
- {0xE0060000u, 40u}, // gay -> Latn
- {0x94260000u, 40u}, // gbf -> Latn
- {0xB0260000u, 16u}, // gbm -> Deva
- {0xE0260000u, 40u}, // gby -> Latn
+ {0x8E850000u, 44u}, // fud -> Latn
+ {0x92850000u, 44u}, // fue -> Latn
+ {0x96850000u, 44u}, // fuf -> Latn
+ {0x9E850000u, 44u}, // fuh -> Latn
+ {0xC2850000u, 44u}, // fuq -> Latn
+ {0xC6850000u, 44u}, // fur -> Latn
+ {0xD6850000u, 44u}, // fuv -> Latn
+ {0xE2850000u, 44u}, // fuy -> Latn
+ {0xC6A50000u, 44u}, // fvr -> Latn
+ {0x66790000u, 44u}, // fy -> Latn
+ {0x67610000u, 44u}, // ga -> Latn
+ {0x80060000u, 44u}, // gaa -> Latn
+ {0x94060000u, 44u}, // gaf -> Latn
+ {0x98060000u, 44u}, // gag -> Latn
+ {0x9C060000u, 44u}, // gah -> Latn
+ {0xA4060000u, 44u}, // gaj -> Latn
+ {0xB0060000u, 44u}, // gam -> Latn
+ {0xB4060000u, 27u}, // gan -> Hans
+ {0xD8060000u, 44u}, // gaw -> Latn
+ {0xE0060000u, 44u}, // gay -> Latn
+ {0x80260000u, 44u}, // gba -> Latn
+ {0x94260000u, 44u}, // gbf -> Latn
+ {0xB0260000u, 17u}, // gbm -> Deva
+ {0xE0260000u, 44u}, // gby -> Latn
{0xE4260000u, 1u}, // gbz -> Arab
- {0xC4460000u, 40u}, // gcr -> Latn
- {0x67640000u, 40u}, // gd -> Latn
- {0x90660000u, 40u}, // gde -> Latn
- {0xB4660000u, 40u}, // gdn -> Latn
- {0xC4660000u, 40u}, // gdr -> Latn
- {0x84860000u, 40u}, // geb -> Latn
- {0xA4860000u, 40u}, // gej -> Latn
- {0xAC860000u, 40u}, // gel -> Latn
- {0xE4860000u, 18u}, // gez -> Ethi
- {0xA8A60000u, 40u}, // gfk -> Latn
- {0xB4C60000u, 16u}, // ggn -> Deva
- {0xC8E60000u, 40u}, // ghs -> Latn
- {0xAD060000u, 40u}, // gil -> Latn
- {0xB1060000u, 40u}, // gim -> Latn
+ {0xC4460000u, 44u}, // gcr -> Latn
+ {0x67640000u, 44u}, // gd -> Latn
+ {0x90660000u, 44u}, // gde -> Latn
+ {0xB4660000u, 44u}, // gdn -> Latn
+ {0xC4660000u, 44u}, // gdr -> Latn
+ {0x84860000u, 44u}, // geb -> Latn
+ {0xA4860000u, 44u}, // gej -> Latn
+ {0xAC860000u, 44u}, // gel -> Latn
+ {0xE4860000u, 19u}, // gez -> Ethi
+ {0xA8A60000u, 44u}, // gfk -> Latn
+ {0xB4C60000u, 17u}, // ggn -> Deva
+ {0xC8E60000u, 44u}, // ghs -> Latn
+ {0xAD060000u, 44u}, // gil -> Latn
+ {0xB1060000u, 44u}, // gim -> Latn
{0xA9260000u, 1u}, // gjk -> Arab
- {0xB5260000u, 40u}, // gjn -> Latn
+ {0xB5260000u, 44u}, // gjn -> Latn
{0xD1260000u, 1u}, // gju -> Arab
- {0xB5460000u, 40u}, // gkn -> Latn
- {0xBD460000u, 40u}, // gkp -> Latn
- {0x676C0000u, 40u}, // gl -> Latn
+ {0xB5460000u, 44u}, // gkn -> Latn
+ {0xBD460000u, 44u}, // gkp -> Latn
+ {0x676C0000u, 44u}, // gl -> Latn
{0xA9660000u, 1u}, // glk -> Arab
- {0xB1860000u, 40u}, // gmm -> Latn
- {0xD5860000u, 18u}, // gmv -> Ethi
- {0x676E0000u, 40u}, // gn -> Latn
- {0x8DA60000u, 40u}, // gnd -> Latn
- {0x99A60000u, 40u}, // gng -> Latn
- {0x8DC60000u, 40u}, // god -> Latn
- {0x95C60000u, 18u}, // gof -> Ethi
- {0xA1C60000u, 40u}, // goi -> Latn
- {0xB1C60000u, 16u}, // gom -> Deva
- {0xB5C60000u, 77u}, // gon -> Telu
- {0xC5C60000u, 40u}, // gor -> Latn
- {0xC9C60000u, 40u}, // gos -> Latn
- {0xCDC60000u, 20u}, // got -> Goth
- {0x8A260000u, 14u}, // grc -> Cprt
+ {0xB1860000u, 44u}, // gmm -> Latn
+ {0xD5860000u, 19u}, // gmv -> Ethi
+ {0x676E0000u, 44u}, // gn -> Latn
+ {0x8DA60000u, 44u}, // gnd -> Latn
+ {0x99A60000u, 44u}, // gng -> Latn
+ {0x8DC60000u, 44u}, // god -> Latn
+ {0x95C60000u, 19u}, // gof -> Ethi
+ {0xA1C60000u, 44u}, // goi -> Latn
+ {0xB1C60000u, 17u}, // gom -> Deva
+ {0xB5C60000u, 84u}, // gon -> Telu
+ {0xC5C60000u, 44u}, // gor -> Latn
+ {0xC9C60000u, 44u}, // gos -> Latn
+ {0xCDC60000u, 23u}, // got -> Goth
+ {0x86260000u, 44u}, // grb -> Latn
+ {0x8A260000u, 15u}, // grc -> Cprt
{0xCE260000u, 7u}, // grt -> Beng
- {0xDA260000u, 40u}, // grw -> Latn
- {0xDA460000u, 40u}, // gsw -> Latn
- {0x67750000u, 22u}, // gu -> Gujr
- {0x86860000u, 40u}, // gub -> Latn
- {0x8A860000u, 40u}, // guc -> Latn
- {0x8E860000u, 40u}, // gud -> Latn
- {0xC6860000u, 40u}, // gur -> Latn
- {0xDA860000u, 40u}, // guw -> Latn
- {0xDE860000u, 40u}, // gux -> Latn
- {0xE6860000u, 40u}, // guz -> Latn
- {0x67760000u, 40u}, // gv -> Latn
- {0x96A60000u, 40u}, // gvf -> Latn
- {0xC6A60000u, 16u}, // gvr -> Deva
- {0xCAA60000u, 40u}, // gvs -> Latn
+ {0xDA260000u, 44u}, // grw -> Latn
+ {0xDA460000u, 44u}, // gsw -> Latn
+ {0x67750000u, 25u}, // gu -> Gujr
+ {0x86860000u, 44u}, // gub -> Latn
+ {0x8A860000u, 44u}, // guc -> Latn
+ {0x8E860000u, 44u}, // gud -> Latn
+ {0xC6860000u, 44u}, // gur -> Latn
+ {0xDA860000u, 44u}, // guw -> Latn
+ {0xDE860000u, 44u}, // gux -> Latn
+ {0xE6860000u, 44u}, // guz -> Latn
+ {0x67760000u, 44u}, // gv -> Latn
+ {0x96A60000u, 44u}, // gvf -> Latn
+ {0xC6A60000u, 17u}, // gvr -> Deva
+ {0xCAA60000u, 44u}, // gvs -> Latn
{0x8AC60000u, 1u}, // gwc -> Arab
- {0xA2C60000u, 40u}, // gwi -> Latn
+ {0xA2C60000u, 44u}, // gwi -> Latn
{0xCEC60000u, 1u}, // gwt -> Arab
- {0xA3060000u, 40u}, // gyi -> Latn
- {0x68610000u, 40u}, // ha -> Latn
+ {0xA3060000u, 44u}, // gyi -> Latn
+ {0x68610000u, 44u}, // ha -> Latn
{0x6861434Du, 1u}, // ha-CM -> Arab
{0x68615344u, 1u}, // ha-SD -> Arab
- {0x98070000u, 40u}, // hag -> Latn
- {0xA8070000u, 24u}, // hak -> Hans
- {0xB0070000u, 40u}, // ham -> Latn
- {0xD8070000u, 40u}, // haw -> Latn
+ {0x98070000u, 44u}, // hag -> Latn
+ {0xA8070000u, 27u}, // hak -> Hans
+ {0xB0070000u, 44u}, // ham -> Latn
+ {0xD8070000u, 44u}, // haw -> Latn
{0xE4070000u, 1u}, // haz -> Arab
- {0x84270000u, 40u}, // hbb -> Latn
- {0xE0670000u, 18u}, // hdy -> Ethi
- {0x68650000u, 27u}, // he -> Hebr
- {0xE0E70000u, 40u}, // hhy -> Latn
- {0x68690000u, 16u}, // hi -> Deva
- {0x81070000u, 40u}, // hia -> Latn
- {0x95070000u, 40u}, // hif -> Latn
- {0x99070000u, 40u}, // hig -> Latn
- {0x9D070000u, 40u}, // hih -> Latn
- {0xAD070000u, 40u}, // hil -> Latn
- {0x81670000u, 40u}, // hla -> Latn
- {0xD1670000u, 28u}, // hlu -> Hluw
- {0x8D870000u, 62u}, // hmd -> Plrd
- {0xCD870000u, 40u}, // hmt -> Latn
+ {0x84270000u, 44u}, // hbb -> Latn
+ {0xE0670000u, 19u}, // hdy -> Ethi
+ {0x68650000u, 30u}, // he -> Hebr
+ {0xE0E70000u, 44u}, // hhy -> Latn
+ {0x68690000u, 17u}, // hi -> Deva
+ {0x81070000u, 44u}, // hia -> Latn
+ {0x95070000u, 44u}, // hif -> Latn
+ {0x99070000u, 44u}, // hig -> Latn
+ {0x9D070000u, 44u}, // hih -> Latn
+ {0xAD070000u, 44u}, // hil -> Latn
+ {0x81670000u, 44u}, // hla -> Latn
+ {0xD1670000u, 31u}, // hlu -> Hluw
+ {0x8D870000u, 67u}, // hmd -> Plrd
+ {0xCD870000u, 44u}, // hmt -> Latn
{0x8DA70000u, 1u}, // hnd -> Arab
- {0x91A70000u, 16u}, // hne -> Deva
- {0xA5A70000u, 29u}, // hnj -> Hmng
- {0xB5A70000u, 40u}, // hnn -> Latn
+ {0x91A70000u, 17u}, // hne -> Deva
+ {0xA5A70000u, 32u}, // hnj -> Hmng
+ {0xB5A70000u, 44u}, // hnn -> Latn
{0xB9A70000u, 1u}, // hno -> Arab
- {0x686F0000u, 40u}, // ho -> Latn
- {0x89C70000u, 16u}, // hoc -> Deva
- {0xA5C70000u, 16u}, // hoj -> Deva
- {0xCDC70000u, 40u}, // hot -> Latn
- {0x68720000u, 40u}, // hr -> Latn
- {0x86470000u, 40u}, // hsb -> Latn
- {0xB6470000u, 24u}, // hsn -> Hans
- {0x68740000u, 40u}, // ht -> Latn
- {0x68750000u, 40u}, // hu -> Latn
- {0xA2870000u, 40u}, // hui -> Latn
+ {0x686F0000u, 44u}, // ho -> Latn
+ {0x89C70000u, 17u}, // hoc -> Deva
+ {0xA5C70000u, 17u}, // hoj -> Deva
+ {0xCDC70000u, 44u}, // hot -> Latn
+ {0x68720000u, 44u}, // hr -> Latn
+ {0x86470000u, 44u}, // hsb -> Latn
+ {0xB6470000u, 27u}, // hsn -> Hans
+ {0x68740000u, 44u}, // ht -> Latn
+ {0x68750000u, 44u}, // hu -> Latn
+ {0xA2870000u, 44u}, // hui -> Latn
{0x68790000u, 3u}, // hy -> Armn
- {0x687A0000u, 40u}, // hz -> Latn
- {0x69610000u, 40u}, // ia -> Latn
- {0xB4080000u, 40u}, // ian -> Latn
- {0xC4080000u, 40u}, // iar -> Latn
- {0x80280000u, 40u}, // iba -> Latn
- {0x84280000u, 40u}, // ibb -> Latn
- {0xE0280000u, 40u}, // iby -> Latn
- {0x80480000u, 40u}, // ica -> Latn
- {0x9C480000u, 40u}, // ich -> Latn
- {0x69640000u, 40u}, // id -> Latn
- {0x8C680000u, 40u}, // idd -> Latn
- {0xA0680000u, 40u}, // idi -> Latn
- {0xD0680000u, 40u}, // idu -> Latn
- {0x69670000u, 40u}, // ig -> Latn
- {0x84C80000u, 40u}, // igb -> Latn
- {0x90C80000u, 40u}, // ige -> Latn
- {0x69690000u, 86u}, // ii -> Yiii
- {0xA5280000u, 40u}, // ijj -> Latn
- {0x696B0000u, 40u}, // ik -> Latn
- {0xA9480000u, 40u}, // ikk -> Latn
- {0xCD480000u, 40u}, // ikt -> Latn
- {0xD9480000u, 40u}, // ikw -> Latn
- {0xDD480000u, 40u}, // ikx -> Latn
- {0xB9680000u, 40u}, // ilo -> Latn
- {0xB9880000u, 40u}, // imo -> Latn
- {0x696E0000u, 40u}, // in -> Latn
- {0x9DA80000u, 15u}, // inh -> Cyrl
- {0xD1C80000u, 40u}, // iou -> Latn
- {0xA2280000u, 40u}, // iri -> Latn
- {0x69730000u, 40u}, // is -> Latn
- {0x69740000u, 40u}, // it -> Latn
- {0x69750000u, 9u}, // iu -> Cans
- {0x69770000u, 27u}, // iw -> Hebr
- {0xB2C80000u, 40u}, // iwm -> Latn
- {0xCAC80000u, 40u}, // iws -> Latn
- {0x9F280000u, 40u}, // izh -> Latn
- {0xA3280000u, 40u}, // izi -> Latn
- {0x6A610000u, 31u}, // ja -> Jpan
- {0x84090000u, 40u}, // jab -> Latn
- {0xB0090000u, 40u}, // jam -> Latn
- {0xD0290000u, 40u}, // jbu -> Latn
- {0xB4890000u, 40u}, // jen -> Latn
- {0xA8C90000u, 40u}, // jgk -> Latn
- {0xB8C90000u, 40u}, // jgo -> Latn
- {0x6A690000u, 27u}, // ji -> Hebr
- {0x85090000u, 40u}, // jib -> Latn
- {0x89890000u, 40u}, // jmc -> Latn
- {0xAD890000u, 16u}, // jml -> Deva
- {0x82290000u, 40u}, // jra -> Latn
- {0xCE890000u, 40u}, // jut -> Latn
- {0x6A760000u, 40u}, // jv -> Latn
- {0x6A770000u, 40u}, // jw -> Latn
- {0x6B610000u, 19u}, // ka -> Geor
- {0x800A0000u, 15u}, // kaa -> Cyrl
- {0x840A0000u, 40u}, // kab -> Latn
- {0x880A0000u, 40u}, // kac -> Latn
- {0x8C0A0000u, 40u}, // kad -> Latn
- {0xA00A0000u, 40u}, // kai -> Latn
- {0xA40A0000u, 40u}, // kaj -> Latn
- {0xB00A0000u, 40u}, // kam -> Latn
- {0xB80A0000u, 40u}, // kao -> Latn
- {0x8C2A0000u, 15u}, // kbd -> Cyrl
- {0xB02A0000u, 40u}, // kbm -> Latn
- {0xBC2A0000u, 40u}, // kbp -> Latn
- {0xC02A0000u, 40u}, // kbq -> Latn
- {0xDC2A0000u, 40u}, // kbx -> Latn
+ {0x687A0000u, 44u}, // hz -> Latn
+ {0x69610000u, 44u}, // ia -> Latn
+ {0xB4080000u, 44u}, // ian -> Latn
+ {0xC4080000u, 44u}, // iar -> Latn
+ {0x80280000u, 44u}, // iba -> Latn
+ {0x84280000u, 44u}, // ibb -> Latn
+ {0xE0280000u, 44u}, // iby -> Latn
+ {0x80480000u, 44u}, // ica -> Latn
+ {0x9C480000u, 44u}, // ich -> Latn
+ {0x69640000u, 44u}, // id -> Latn
+ {0x8C680000u, 44u}, // idd -> Latn
+ {0xA0680000u, 44u}, // idi -> Latn
+ {0xD0680000u, 44u}, // idu -> Latn
+ {0x90A80000u, 44u}, // ife -> Latn
+ {0x69670000u, 44u}, // ig -> Latn
+ {0x84C80000u, 44u}, // igb -> Latn
+ {0x90C80000u, 44u}, // ige -> Latn
+ {0x69690000u, 94u}, // ii -> Yiii
+ {0xA5280000u, 44u}, // ijj -> Latn
+ {0x696B0000u, 44u}, // ik -> Latn
+ {0xA9480000u, 44u}, // ikk -> Latn
+ {0xCD480000u, 44u}, // ikt -> Latn
+ {0xD9480000u, 44u}, // ikw -> Latn
+ {0xDD480000u, 44u}, // ikx -> Latn
+ {0xB9680000u, 44u}, // ilo -> Latn
+ {0xB9880000u, 44u}, // imo -> Latn
+ {0x696E0000u, 44u}, // in -> Latn
+ {0x9DA80000u, 16u}, // inh -> Cyrl
+ {0x696F0000u, 44u}, // io -> Latn
+ {0xD1C80000u, 44u}, // iou -> Latn
+ {0xA2280000u, 44u}, // iri -> Latn
+ {0x69730000u, 44u}, // is -> Latn
+ {0x69740000u, 44u}, // it -> Latn
+ {0x69750000u, 10u}, // iu -> Cans
+ {0x69770000u, 30u}, // iw -> Hebr
+ {0xB2C80000u, 44u}, // iwm -> Latn
+ {0xCAC80000u, 44u}, // iws -> Latn
+ {0x9F280000u, 44u}, // izh -> Latn
+ {0xA3280000u, 44u}, // izi -> Latn
+ {0x6A610000u, 35u}, // ja -> Jpan
+ {0x84090000u, 44u}, // jab -> Latn
+ {0xB0090000u, 44u}, // jam -> Latn
+ {0xB8290000u, 44u}, // jbo -> Latn
+ {0xD0290000u, 44u}, // jbu -> Latn
+ {0xB4890000u, 44u}, // jen -> Latn
+ {0xA8C90000u, 44u}, // jgk -> Latn
+ {0xB8C90000u, 44u}, // jgo -> Latn
+ {0x6A690000u, 30u}, // ji -> Hebr
+ {0x85090000u, 44u}, // jib -> Latn
+ {0x89890000u, 44u}, // jmc -> Latn
+ {0xAD890000u, 17u}, // jml -> Deva
+ {0x82290000u, 44u}, // jra -> Latn
+ {0xCE890000u, 44u}, // jut -> Latn
+ {0x6A760000u, 44u}, // jv -> Latn
+ {0x6A770000u, 44u}, // jw -> Latn
+ {0x6B610000u, 20u}, // ka -> Geor
+ {0x800A0000u, 16u}, // kaa -> Cyrl
+ {0x840A0000u, 44u}, // kab -> Latn
+ {0x880A0000u, 44u}, // kac -> Latn
+ {0x8C0A0000u, 44u}, // kad -> Latn
+ {0xA00A0000u, 44u}, // kai -> Latn
+ {0xA40A0000u, 44u}, // kaj -> Latn
+ {0xB00A0000u, 44u}, // kam -> Latn
+ {0xB80A0000u, 44u}, // kao -> Latn
+ {0x8C2A0000u, 16u}, // kbd -> Cyrl
+ {0xB02A0000u, 44u}, // kbm -> Latn
+ {0xBC2A0000u, 44u}, // kbp -> Latn
+ {0xC02A0000u, 44u}, // kbq -> Latn
+ {0xDC2A0000u, 44u}, // kbx -> Latn
{0xE02A0000u, 1u}, // kby -> Arab
- {0x984A0000u, 40u}, // kcg -> Latn
- {0xA84A0000u, 40u}, // kck -> Latn
- {0xAC4A0000u, 40u}, // kcl -> Latn
- {0xCC4A0000u, 40u}, // kct -> Latn
- {0x906A0000u, 40u}, // kde -> Latn
+ {0x984A0000u, 44u}, // kcg -> Latn
+ {0xA84A0000u, 44u}, // kck -> Latn
+ {0xAC4A0000u, 44u}, // kcl -> Latn
+ {0xCC4A0000u, 44u}, // kct -> Latn
+ {0x906A0000u, 44u}, // kde -> Latn
{0x9C6A0000u, 1u}, // kdh -> Arab
- {0xAC6A0000u, 40u}, // kdl -> Latn
- {0xCC6A0000u, 80u}, // kdt -> Thai
- {0x808A0000u, 40u}, // kea -> Latn
- {0xB48A0000u, 40u}, // ken -> Latn
- {0xE48A0000u, 40u}, // kez -> Latn
- {0xB8AA0000u, 40u}, // kfo -> Latn
- {0xC4AA0000u, 16u}, // kfr -> Deva
- {0xE0AA0000u, 16u}, // kfy -> Deva
- {0x6B670000u, 40u}, // kg -> Latn
- {0x90CA0000u, 40u}, // kge -> Latn
- {0x94CA0000u, 40u}, // kgf -> Latn
- {0xBCCA0000u, 40u}, // kgp -> Latn
- {0x80EA0000u, 40u}, // kha -> Latn
- {0x84EA0000u, 73u}, // khb -> Talu
- {0xB4EA0000u, 16u}, // khn -> Deva
- {0xC0EA0000u, 40u}, // khq -> Latn
- {0xC8EA0000u, 40u}, // khs -> Latn
- {0xCCEA0000u, 52u}, // kht -> Mymr
+ {0xAC6A0000u, 44u}, // kdl -> Latn
+ {0xCC6A0000u, 87u}, // kdt -> Thai
+ {0x808A0000u, 44u}, // kea -> Latn
+ {0xB48A0000u, 44u}, // ken -> Latn
+ {0xE48A0000u, 44u}, // kez -> Latn
+ {0xB8AA0000u, 44u}, // kfo -> Latn
+ {0xC4AA0000u, 17u}, // kfr -> Deva
+ {0xE0AA0000u, 17u}, // kfy -> Deva
+ {0x6B670000u, 44u}, // kg -> Latn
+ {0x90CA0000u, 44u}, // kge -> Latn
+ {0x94CA0000u, 44u}, // kgf -> Latn
+ {0xBCCA0000u, 44u}, // kgp -> Latn
+ {0x80EA0000u, 44u}, // kha -> Latn
+ {0x84EA0000u, 80u}, // khb -> Talu
+ {0xB4EA0000u, 17u}, // khn -> Deva
+ {0xC0EA0000u, 44u}, // khq -> Latn
+ {0xC8EA0000u, 44u}, // khs -> Latn
+ {0xCCEA0000u, 56u}, // kht -> Mymr
{0xD8EA0000u, 1u}, // khw -> Arab
- {0xE4EA0000u, 40u}, // khz -> Latn
- {0x6B690000u, 40u}, // ki -> Latn
- {0xA50A0000u, 40u}, // kij -> Latn
- {0xD10A0000u, 40u}, // kiu -> Latn
- {0xD90A0000u, 40u}, // kiw -> Latn
- {0x6B6A0000u, 40u}, // kj -> Latn
- {0x8D2A0000u, 40u}, // kjd -> Latn
- {0x992A0000u, 39u}, // kjg -> Laoo
- {0xC92A0000u, 40u}, // kjs -> Latn
- {0xE12A0000u, 40u}, // kjy -> Latn
- {0x6B6B0000u, 15u}, // kk -> Cyrl
+ {0xE4EA0000u, 44u}, // khz -> Latn
+ {0x6B690000u, 44u}, // ki -> Latn
+ {0xA50A0000u, 44u}, // kij -> Latn
+ {0xD10A0000u, 44u}, // kiu -> Latn
+ {0xD90A0000u, 44u}, // kiw -> Latn
+ {0x6B6A0000u, 44u}, // kj -> Latn
+ {0x8D2A0000u, 44u}, // kjd -> Latn
+ {0x992A0000u, 43u}, // kjg -> Laoo
+ {0xC92A0000u, 44u}, // kjs -> Latn
+ {0xE12A0000u, 44u}, // kjy -> Latn
+ {0x6B6B0000u, 16u}, // kk -> Cyrl
{0x6B6B4146u, 1u}, // kk-AF -> Arab
{0x6B6B434Eu, 1u}, // kk-CN -> Arab
{0x6B6B4952u, 1u}, // kk-IR -> Arab
{0x6B6B4D4Eu, 1u}, // kk-MN -> Arab
- {0x894A0000u, 40u}, // kkc -> Latn
- {0xA54A0000u, 40u}, // kkj -> Latn
- {0x6B6C0000u, 40u}, // kl -> Latn
- {0xB56A0000u, 40u}, // kln -> Latn
- {0xC16A0000u, 40u}, // klq -> Latn
- {0xCD6A0000u, 40u}, // klt -> Latn
- {0xDD6A0000u, 40u}, // klx -> Latn
- {0x6B6D0000u, 35u}, // km -> Khmr
- {0x858A0000u, 40u}, // kmb -> Latn
- {0x9D8A0000u, 40u}, // kmh -> Latn
- {0xB98A0000u, 40u}, // kmo -> Latn
- {0xC98A0000u, 40u}, // kms -> Latn
- {0xD18A0000u, 40u}, // kmu -> Latn
- {0xD98A0000u, 40u}, // kmw -> Latn
- {0x6B6E0000u, 36u}, // kn -> Knda
- {0xBDAA0000u, 40u}, // knp -> Latn
- {0x6B6F0000u, 37u}, // ko -> Kore
- {0xA1CA0000u, 15u}, // koi -> Cyrl
- {0xA9CA0000u, 16u}, // kok -> Deva
- {0xADCA0000u, 40u}, // kol -> Latn
- {0xC9CA0000u, 40u}, // kos -> Latn
- {0xE5CA0000u, 40u}, // koz -> Latn
- {0x91EA0000u, 40u}, // kpe -> Latn
- {0x95EA0000u, 40u}, // kpf -> Latn
- {0xB9EA0000u, 40u}, // kpo -> Latn
- {0xC5EA0000u, 40u}, // kpr -> Latn
- {0xDDEA0000u, 40u}, // kpx -> Latn
- {0x860A0000u, 40u}, // kqb -> Latn
- {0x960A0000u, 40u}, // kqf -> Latn
- {0xCA0A0000u, 40u}, // kqs -> Latn
- {0xE20A0000u, 18u}, // kqy -> Ethi
- {0x8A2A0000u, 15u}, // krc -> Cyrl
- {0xA22A0000u, 40u}, // kri -> Latn
- {0xA62A0000u, 40u}, // krj -> Latn
- {0xAE2A0000u, 40u}, // krl -> Latn
- {0xCA2A0000u, 40u}, // krs -> Latn
- {0xD22A0000u, 16u}, // kru -> Deva
+ {0x894A0000u, 44u}, // kkc -> Latn
+ {0xA54A0000u, 44u}, // kkj -> Latn
+ {0x6B6C0000u, 44u}, // kl -> Latn
+ {0xB56A0000u, 44u}, // kln -> Latn
+ {0xC16A0000u, 44u}, // klq -> Latn
+ {0xCD6A0000u, 44u}, // klt -> Latn
+ {0xDD6A0000u, 44u}, // klx -> Latn
+ {0x6B6D0000u, 39u}, // km -> Khmr
+ {0x858A0000u, 44u}, // kmb -> Latn
+ {0x9D8A0000u, 44u}, // kmh -> Latn
+ {0xB98A0000u, 44u}, // kmo -> Latn
+ {0xC98A0000u, 44u}, // kms -> Latn
+ {0xD18A0000u, 44u}, // kmu -> Latn
+ {0xD98A0000u, 44u}, // kmw -> Latn
+ {0x6B6E0000u, 40u}, // kn -> Knda
+ {0x95AA0000u, 44u}, // knf -> Latn
+ {0xBDAA0000u, 44u}, // knp -> Latn
+ {0x6B6F0000u, 41u}, // ko -> Kore
+ {0xA1CA0000u, 16u}, // koi -> Cyrl
+ {0xA9CA0000u, 17u}, // kok -> Deva
+ {0xADCA0000u, 44u}, // kol -> Latn
+ {0xC9CA0000u, 44u}, // kos -> Latn
+ {0xE5CA0000u, 44u}, // koz -> Latn
+ {0x91EA0000u, 44u}, // kpe -> Latn
+ {0x95EA0000u, 44u}, // kpf -> Latn
+ {0xB9EA0000u, 44u}, // kpo -> Latn
+ {0xC5EA0000u, 44u}, // kpr -> Latn
+ {0xDDEA0000u, 44u}, // kpx -> Latn
+ {0x860A0000u, 44u}, // kqb -> Latn
+ {0x960A0000u, 44u}, // kqf -> Latn
+ {0xCA0A0000u, 44u}, // kqs -> Latn
+ {0xE20A0000u, 19u}, // kqy -> Ethi
+ {0x6B720000u, 44u}, // kr -> Latn
+ {0x8A2A0000u, 16u}, // krc -> Cyrl
+ {0xA22A0000u, 44u}, // kri -> Latn
+ {0xA62A0000u, 44u}, // krj -> Latn
+ {0xAE2A0000u, 44u}, // krl -> Latn
+ {0xCA2A0000u, 44u}, // krs -> Latn
+ {0xD22A0000u, 17u}, // kru -> Deva
{0x6B730000u, 1u}, // ks -> Arab
- {0x864A0000u, 40u}, // ksb -> Latn
- {0x8E4A0000u, 40u}, // ksd -> Latn
- {0x964A0000u, 40u}, // ksf -> Latn
- {0x9E4A0000u, 40u}, // ksh -> Latn
- {0xA64A0000u, 40u}, // ksj -> Latn
- {0xC64A0000u, 40u}, // ksr -> Latn
- {0x866A0000u, 18u}, // ktb -> Ethi
- {0xB26A0000u, 40u}, // ktm -> Latn
- {0xBA6A0000u, 40u}, // kto -> Latn
- {0x6B750000u, 40u}, // ku -> Latn
+ {0x864A0000u, 44u}, // ksb -> Latn
+ {0x8E4A0000u, 44u}, // ksd -> Latn
+ {0x964A0000u, 44u}, // ksf -> Latn
+ {0x9E4A0000u, 44u}, // ksh -> Latn
+ {0xA64A0000u, 44u}, // ksj -> Latn
+ {0xC64A0000u, 44u}, // ksr -> Latn
+ {0x866A0000u, 19u}, // ktb -> Ethi
+ {0xB26A0000u, 44u}, // ktm -> Latn
+ {0xBA6A0000u, 44u}, // kto -> Latn
+ {0x6B750000u, 44u}, // ku -> Latn
{0x6B754952u, 1u}, // ku-IR -> Arab
{0x6B754C42u, 1u}, // ku-LB -> Arab
- {0x868A0000u, 40u}, // kub -> Latn
- {0x8E8A0000u, 40u}, // kud -> Latn
- {0x928A0000u, 40u}, // kue -> Latn
- {0xA68A0000u, 40u}, // kuj -> Latn
- {0xB28A0000u, 15u}, // kum -> Cyrl
- {0xB68A0000u, 40u}, // kun -> Latn
- {0xBE8A0000u, 40u}, // kup -> Latn
- {0xCA8A0000u, 40u}, // kus -> Latn
- {0x6B760000u, 15u}, // kv -> Cyrl
- {0x9AAA0000u, 40u}, // kvg -> Latn
- {0xC6AA0000u, 40u}, // kvr -> Latn
+ {0x868A0000u, 44u}, // kub -> Latn
+ {0x8E8A0000u, 44u}, // kud -> Latn
+ {0x928A0000u, 44u}, // kue -> Latn
+ {0xA68A0000u, 44u}, // kuj -> Latn
+ {0xB28A0000u, 16u}, // kum -> Cyrl
+ {0xB68A0000u, 44u}, // kun -> Latn
+ {0xBE8A0000u, 44u}, // kup -> Latn
+ {0xCA8A0000u, 44u}, // kus -> Latn
+ {0x6B760000u, 16u}, // kv -> Cyrl
+ {0x9AAA0000u, 44u}, // kvg -> Latn
+ {0xC6AA0000u, 44u}, // kvr -> Latn
{0xDEAA0000u, 1u}, // kvx -> Arab
- {0x6B770000u, 40u}, // kw -> Latn
- {0xA6CA0000u, 40u}, // kwj -> Latn
- {0xBACA0000u, 40u}, // kwo -> Latn
- {0x82EA0000u, 40u}, // kxa -> Latn
- {0x8AEA0000u, 18u}, // kxc -> Ethi
- {0xB2EA0000u, 80u}, // kxm -> Thai
+ {0x6B770000u, 44u}, // kw -> Latn
+ {0xA6CA0000u, 44u}, // kwj -> Latn
+ {0xBACA0000u, 44u}, // kwo -> Latn
+ {0x82EA0000u, 44u}, // kxa -> Latn
+ {0x8AEA0000u, 19u}, // kxc -> Ethi
+ {0xB2EA0000u, 87u}, // kxm -> Thai
{0xBEEA0000u, 1u}, // kxp -> Arab
- {0xDAEA0000u, 40u}, // kxw -> Latn
- {0xE6EA0000u, 40u}, // kxz -> Latn
- {0x6B790000u, 15u}, // ky -> Cyrl
+ {0xDAEA0000u, 44u}, // kxw -> Latn
+ {0xE6EA0000u, 44u}, // kxz -> Latn
+ {0x6B790000u, 16u}, // ky -> Cyrl
{0x6B79434Eu, 1u}, // ky-CN -> Arab
- {0x6B795452u, 40u}, // ky-TR -> Latn
- {0x930A0000u, 40u}, // kye -> Latn
- {0xDF0A0000u, 40u}, // kyx -> Latn
- {0xC72A0000u, 40u}, // kzr -> Latn
- {0x6C610000u, 40u}, // la -> Latn
- {0x840B0000u, 42u}, // lab -> Lina
- {0x8C0B0000u, 27u}, // lad -> Hebr
- {0x980B0000u, 40u}, // lag -> Latn
+ {0x6B795452u, 44u}, // ky-TR -> Latn
+ {0x930A0000u, 44u}, // kye -> Latn
+ {0xDF0A0000u, 44u}, // kyx -> Latn
+ {0xC72A0000u, 44u}, // kzr -> Latn
+ {0x6C610000u, 44u}, // la -> Latn
+ {0x840B0000u, 46u}, // lab -> Lina
+ {0x8C0B0000u, 30u}, // lad -> Hebr
+ {0x980B0000u, 44u}, // lag -> Latn
{0x9C0B0000u, 1u}, // lah -> Arab
- {0xA40B0000u, 40u}, // laj -> Latn
- {0xC80B0000u, 40u}, // las -> Latn
- {0x6C620000u, 40u}, // lb -> Latn
- {0x902B0000u, 15u}, // lbe -> Cyrl
- {0xD02B0000u, 40u}, // lbu -> Latn
- {0xD82B0000u, 40u}, // lbw -> Latn
- {0xB04B0000u, 40u}, // lcm -> Latn
- {0xBC4B0000u, 80u}, // lcp -> Thai
- {0x846B0000u, 40u}, // ldb -> Latn
- {0x8C8B0000u, 40u}, // led -> Latn
- {0x908B0000u, 40u}, // lee -> Latn
- {0xB08B0000u, 40u}, // lem -> Latn
- {0xBC8B0000u, 41u}, // lep -> Lepc
- {0xC08B0000u, 40u}, // leq -> Latn
- {0xD08B0000u, 40u}, // leu -> Latn
- {0xE48B0000u, 15u}, // lez -> Cyrl
- {0x6C670000u, 40u}, // lg -> Latn
- {0x98CB0000u, 40u}, // lgg -> Latn
- {0x6C690000u, 40u}, // li -> Latn
- {0x810B0000u, 40u}, // lia -> Latn
- {0x8D0B0000u, 40u}, // lid -> Latn
- {0x950B0000u, 16u}, // lif -> Deva
- {0x990B0000u, 40u}, // lig -> Latn
- {0x9D0B0000u, 40u}, // lih -> Latn
- {0xA50B0000u, 40u}, // lij -> Latn
- {0xC90B0000u, 43u}, // lis -> Lisu
- {0xBD2B0000u, 40u}, // ljp -> Latn
+ {0xA40B0000u, 44u}, // laj -> Latn
+ {0xC80B0000u, 44u}, // las -> Latn
+ {0x6C620000u, 44u}, // lb -> Latn
+ {0x902B0000u, 16u}, // lbe -> Cyrl
+ {0xD02B0000u, 44u}, // lbu -> Latn
+ {0xD82B0000u, 44u}, // lbw -> Latn
+ {0xB04B0000u, 44u}, // lcm -> Latn
+ {0xBC4B0000u, 87u}, // lcp -> Thai
+ {0x846B0000u, 44u}, // ldb -> Latn
+ {0x8C8B0000u, 44u}, // led -> Latn
+ {0x908B0000u, 44u}, // lee -> Latn
+ {0xB08B0000u, 44u}, // lem -> Latn
+ {0xBC8B0000u, 45u}, // lep -> Lepc
+ {0xC08B0000u, 44u}, // leq -> Latn
+ {0xD08B0000u, 44u}, // leu -> Latn
+ {0xE48B0000u, 16u}, // lez -> Cyrl
+ {0x6C670000u, 44u}, // lg -> Latn
+ {0x98CB0000u, 44u}, // lgg -> Latn
+ {0x6C690000u, 44u}, // li -> Latn
+ {0x810B0000u, 44u}, // lia -> Latn
+ {0x8D0B0000u, 44u}, // lid -> Latn
+ {0x950B0000u, 17u}, // lif -> Deva
+ {0x990B0000u, 44u}, // lig -> Latn
+ {0x9D0B0000u, 44u}, // lih -> Latn
+ {0xA50B0000u, 44u}, // lij -> Latn
+ {0xC90B0000u, 47u}, // lis -> Lisu
+ {0xBD2B0000u, 44u}, // ljp -> Latn
{0xA14B0000u, 1u}, // lki -> Arab
- {0xCD4B0000u, 40u}, // lkt -> Latn
- {0x916B0000u, 40u}, // lle -> Latn
- {0xB56B0000u, 40u}, // lln -> Latn
- {0xB58B0000u, 77u}, // lmn -> Telu
- {0xB98B0000u, 40u}, // lmo -> Latn
- {0xBD8B0000u, 40u}, // lmp -> Latn
- {0x6C6E0000u, 40u}, // ln -> Latn
- {0xC9AB0000u, 40u}, // lns -> Latn
- {0xD1AB0000u, 40u}, // lnu -> Latn
- {0x6C6F0000u, 39u}, // lo -> Laoo
- {0xA5CB0000u, 40u}, // loj -> Latn
- {0xA9CB0000u, 40u}, // lok -> Latn
- {0xADCB0000u, 40u}, // lol -> Latn
- {0xC5CB0000u, 40u}, // lor -> Latn
- {0xC9CB0000u, 40u}, // los -> Latn
- {0xE5CB0000u, 40u}, // loz -> Latn
+ {0xCD4B0000u, 44u}, // lkt -> Latn
+ {0x916B0000u, 44u}, // lle -> Latn
+ {0xB56B0000u, 44u}, // lln -> Latn
+ {0xB58B0000u, 84u}, // lmn -> Telu
+ {0xB98B0000u, 44u}, // lmo -> Latn
+ {0xBD8B0000u, 44u}, // lmp -> Latn
+ {0x6C6E0000u, 44u}, // ln -> Latn
+ {0xC9AB0000u, 44u}, // lns -> Latn
+ {0xD1AB0000u, 44u}, // lnu -> Latn
+ {0x6C6F0000u, 43u}, // lo -> Laoo
+ {0xA5CB0000u, 44u}, // loj -> Latn
+ {0xA9CB0000u, 44u}, // lok -> Latn
+ {0xADCB0000u, 44u}, // lol -> Latn
+ {0xC5CB0000u, 44u}, // lor -> Latn
+ {0xC9CB0000u, 44u}, // los -> Latn
+ {0xE5CB0000u, 44u}, // loz -> Latn
{0x8A2B0000u, 1u}, // lrc -> Arab
- {0x6C740000u, 40u}, // lt -> Latn
- {0x9A6B0000u, 40u}, // ltg -> Latn
- {0x6C750000u, 40u}, // lu -> Latn
- {0x828B0000u, 40u}, // lua -> Latn
- {0xBA8B0000u, 40u}, // luo -> Latn
- {0xE28B0000u, 40u}, // luy -> Latn
+ {0x6C740000u, 44u}, // lt -> Latn
+ {0x9A6B0000u, 44u}, // ltg -> Latn
+ {0x6C750000u, 44u}, // lu -> Latn
+ {0x828B0000u, 44u}, // lua -> Latn
+ {0xBA8B0000u, 44u}, // luo -> Latn
+ {0xE28B0000u, 44u}, // luy -> Latn
{0xE68B0000u, 1u}, // luz -> Arab
- {0x6C760000u, 40u}, // lv -> Latn
- {0xAECB0000u, 80u}, // lwl -> Thai
- {0x9F2B0000u, 24u}, // lzh -> Hans
- {0xE72B0000u, 40u}, // lzz -> Latn
- {0x8C0C0000u, 40u}, // mad -> Latn
- {0x940C0000u, 40u}, // maf -> Latn
- {0x980C0000u, 16u}, // mag -> Deva
- {0xA00C0000u, 16u}, // mai -> Deva
- {0xA80C0000u, 40u}, // mak -> Latn
- {0xB40C0000u, 40u}, // man -> Latn
- {0xB40C474Eu, 54u}, // man-GN -> Nkoo
- {0xC80C0000u, 40u}, // mas -> Latn
- {0xD80C0000u, 40u}, // maw -> Latn
- {0xE40C0000u, 40u}, // maz -> Latn
- {0x9C2C0000u, 40u}, // mbh -> Latn
- {0xB82C0000u, 40u}, // mbo -> Latn
- {0xC02C0000u, 40u}, // mbq -> Latn
- {0xD02C0000u, 40u}, // mbu -> Latn
- {0xD82C0000u, 40u}, // mbw -> Latn
- {0xA04C0000u, 40u}, // mci -> Latn
- {0xBC4C0000u, 40u}, // mcp -> Latn
- {0xC04C0000u, 40u}, // mcq -> Latn
- {0xC44C0000u, 40u}, // mcr -> Latn
- {0xD04C0000u, 40u}, // mcu -> Latn
- {0x806C0000u, 40u}, // mda -> Latn
+ {0x6C760000u, 44u}, // lv -> Latn
+ {0xAECB0000u, 87u}, // lwl -> Thai
+ {0x9F2B0000u, 27u}, // lzh -> Hans
+ {0xE72B0000u, 44u}, // lzz -> Latn
+ {0x8C0C0000u, 44u}, // mad -> Latn
+ {0x940C0000u, 44u}, // maf -> Latn
+ {0x980C0000u, 17u}, // mag -> Deva
+ {0xA00C0000u, 17u}, // mai -> Deva
+ {0xA80C0000u, 44u}, // mak -> Latn
+ {0xB40C0000u, 44u}, // man -> Latn
+ {0xB40C474Eu, 58u}, // man-GN -> Nkoo
+ {0xC80C0000u, 44u}, // mas -> Latn
+ {0xD80C0000u, 44u}, // maw -> Latn
+ {0xE40C0000u, 44u}, // maz -> Latn
+ {0x9C2C0000u, 44u}, // mbh -> Latn
+ {0xB82C0000u, 44u}, // mbo -> Latn
+ {0xC02C0000u, 44u}, // mbq -> Latn
+ {0xD02C0000u, 44u}, // mbu -> Latn
+ {0xD82C0000u, 44u}, // mbw -> Latn
+ {0xA04C0000u, 44u}, // mci -> Latn
+ {0xBC4C0000u, 44u}, // mcp -> Latn
+ {0xC04C0000u, 44u}, // mcq -> Latn
+ {0xC44C0000u, 44u}, // mcr -> Latn
+ {0xD04C0000u, 44u}, // mcu -> Latn
+ {0x806C0000u, 44u}, // mda -> Latn
{0x906C0000u, 1u}, // mde -> Arab
- {0x946C0000u, 15u}, // mdf -> Cyrl
- {0x9C6C0000u, 40u}, // mdh -> Latn
- {0xA46C0000u, 40u}, // mdj -> Latn
- {0xC46C0000u, 40u}, // mdr -> Latn
- {0xDC6C0000u, 18u}, // mdx -> Ethi
- {0x8C8C0000u, 40u}, // med -> Latn
- {0x908C0000u, 40u}, // mee -> Latn
- {0xA88C0000u, 40u}, // mek -> Latn
- {0xB48C0000u, 40u}, // men -> Latn
- {0xC48C0000u, 40u}, // mer -> Latn
- {0xCC8C0000u, 40u}, // met -> Latn
- {0xD08C0000u, 40u}, // meu -> Latn
+ {0x946C0000u, 16u}, // mdf -> Cyrl
+ {0x9C6C0000u, 44u}, // mdh -> Latn
+ {0xA46C0000u, 44u}, // mdj -> Latn
+ {0xC46C0000u, 44u}, // mdr -> Latn
+ {0xDC6C0000u, 19u}, // mdx -> Ethi
+ {0x8C8C0000u, 44u}, // med -> Latn
+ {0x908C0000u, 44u}, // mee -> Latn
+ {0xA88C0000u, 44u}, // mek -> Latn
+ {0xB48C0000u, 44u}, // men -> Latn
+ {0xC48C0000u, 44u}, // mer -> Latn
+ {0xCC8C0000u, 44u}, // met -> Latn
+ {0xD08C0000u, 44u}, // meu -> Latn
{0x80AC0000u, 1u}, // mfa -> Arab
- {0x90AC0000u, 40u}, // mfe -> Latn
- {0xB4AC0000u, 40u}, // mfn -> Latn
- {0xB8AC0000u, 40u}, // mfo -> Latn
- {0xC0AC0000u, 40u}, // mfq -> Latn
- {0x6D670000u, 40u}, // mg -> Latn
- {0x9CCC0000u, 40u}, // mgh -> Latn
- {0xACCC0000u, 40u}, // mgl -> Latn
- {0xB8CC0000u, 40u}, // mgo -> Latn
- {0xBCCC0000u, 16u}, // mgp -> Deva
- {0xE0CC0000u, 40u}, // mgy -> Latn
- {0x6D680000u, 40u}, // mh -> Latn
- {0xA0EC0000u, 40u}, // mhi -> Latn
- {0xACEC0000u, 40u}, // mhl -> Latn
- {0x6D690000u, 40u}, // mi -> Latn
- {0x950C0000u, 40u}, // mif -> Latn
- {0xB50C0000u, 40u}, // min -> Latn
- {0xC90C0000u, 26u}, // mis -> Hatr
- {0xD90C0000u, 40u}, // miw -> Latn
- {0x6D6B0000u, 15u}, // mk -> Cyrl
+ {0x90AC0000u, 44u}, // mfe -> Latn
+ {0xB4AC0000u, 44u}, // mfn -> Latn
+ {0xB8AC0000u, 44u}, // mfo -> Latn
+ {0xC0AC0000u, 44u}, // mfq -> Latn
+ {0x6D670000u, 44u}, // mg -> Latn
+ {0x9CCC0000u, 44u}, // mgh -> Latn
+ {0xACCC0000u, 44u}, // mgl -> Latn
+ {0xB8CC0000u, 44u}, // mgo -> Latn
+ {0xBCCC0000u, 17u}, // mgp -> Deva
+ {0xE0CC0000u, 44u}, // mgy -> Latn
+ {0x6D680000u, 44u}, // mh -> Latn
+ {0xA0EC0000u, 44u}, // mhi -> Latn
+ {0xACEC0000u, 44u}, // mhl -> Latn
+ {0x6D690000u, 44u}, // mi -> Latn
+ {0x950C0000u, 44u}, // mif -> Latn
+ {0xB50C0000u, 44u}, // min -> Latn
+ {0xC90C0000u, 29u}, // mis -> Hatr
+ {0xD90C0000u, 44u}, // miw -> Latn
+ {0x6D6B0000u, 16u}, // mk -> Cyrl
{0xA14C0000u, 1u}, // mki -> Arab
- {0xAD4C0000u, 40u}, // mkl -> Latn
- {0xBD4C0000u, 40u}, // mkp -> Latn
- {0xD94C0000u, 40u}, // mkw -> Latn
- {0x6D6C0000u, 49u}, // ml -> Mlym
- {0x916C0000u, 40u}, // mle -> Latn
- {0xBD6C0000u, 40u}, // mlp -> Latn
- {0xC96C0000u, 40u}, // mls -> Latn
- {0xB98C0000u, 40u}, // mmo -> Latn
- {0xD18C0000u, 40u}, // mmu -> Latn
- {0xDD8C0000u, 40u}, // mmx -> Latn
- {0x6D6E0000u, 15u}, // mn -> Cyrl
- {0x6D6E434Eu, 50u}, // mn-CN -> Mong
- {0x81AC0000u, 40u}, // mna -> Latn
- {0x95AC0000u, 40u}, // mnf -> Latn
+ {0xAD4C0000u, 44u}, // mkl -> Latn
+ {0xBD4C0000u, 44u}, // mkp -> Latn
+ {0xD94C0000u, 44u}, // mkw -> Latn
+ {0x6D6C0000u, 53u}, // ml -> Mlym
+ {0x916C0000u, 44u}, // mle -> Latn
+ {0xBD6C0000u, 44u}, // mlp -> Latn
+ {0xC96C0000u, 44u}, // mls -> Latn
+ {0xB98C0000u, 44u}, // mmo -> Latn
+ {0xD18C0000u, 44u}, // mmu -> Latn
+ {0xDD8C0000u, 44u}, // mmx -> Latn
+ {0x6D6E0000u, 16u}, // mn -> Cyrl
+ {0x6D6E434Eu, 54u}, // mn-CN -> Mong
+ {0x81AC0000u, 44u}, // mna -> Latn
+ {0x95AC0000u, 44u}, // mnf -> Latn
{0xA1AC0000u, 7u}, // mni -> Beng
- {0xD9AC0000u, 52u}, // mnw -> Mymr
- {0x81CC0000u, 40u}, // moa -> Latn
- {0x91CC0000u, 40u}, // moe -> Latn
- {0x9DCC0000u, 40u}, // moh -> Latn
- {0xC9CC0000u, 40u}, // mos -> Latn
- {0xDDCC0000u, 40u}, // mox -> Latn
- {0xBDEC0000u, 40u}, // mpp -> Latn
- {0xC9EC0000u, 40u}, // mps -> Latn
- {0xCDEC0000u, 40u}, // mpt -> Latn
- {0xDDEC0000u, 40u}, // mpx -> Latn
- {0xAE0C0000u, 40u}, // mql -> Latn
- {0x6D720000u, 16u}, // mr -> Deva
- {0x8E2C0000u, 16u}, // mrd -> Deva
- {0xA62C0000u, 15u}, // mrj -> Cyrl
- {0xBA2C0000u, 51u}, // mro -> Mroo
- {0x6D730000u, 40u}, // ms -> Latn
+ {0xD9AC0000u, 56u}, // mnw -> Mymr
+ {0x81CC0000u, 44u}, // moa -> Latn
+ {0x91CC0000u, 44u}, // moe -> Latn
+ {0x9DCC0000u, 44u}, // moh -> Latn
+ {0xC9CC0000u, 44u}, // mos -> Latn
+ {0xDDCC0000u, 44u}, // mox -> Latn
+ {0xBDEC0000u, 44u}, // mpp -> Latn
+ {0xC9EC0000u, 44u}, // mps -> Latn
+ {0xCDEC0000u, 44u}, // mpt -> Latn
+ {0xDDEC0000u, 44u}, // mpx -> Latn
+ {0xAE0C0000u, 44u}, // mql -> Latn
+ {0x6D720000u, 17u}, // mr -> Deva
+ {0x8E2C0000u, 17u}, // mrd -> Deva
+ {0xA62C0000u, 16u}, // mrj -> Cyrl
+ {0xBA2C0000u, 55u}, // mro -> Mroo
+ {0x6D730000u, 44u}, // ms -> Latn
{0x6D734343u, 1u}, // ms-CC -> Arab
{0x6D734944u, 1u}, // ms-ID -> Arab
- {0x6D740000u, 40u}, // mt -> Latn
- {0x8A6C0000u, 40u}, // mtc -> Latn
- {0x966C0000u, 40u}, // mtf -> Latn
- {0xA26C0000u, 40u}, // mti -> Latn
- {0xC66C0000u, 16u}, // mtr -> Deva
- {0x828C0000u, 40u}, // mua -> Latn
- {0xC68C0000u, 40u}, // mur -> Latn
- {0xCA8C0000u, 40u}, // mus -> Latn
- {0x82AC0000u, 40u}, // mva -> Latn
- {0xB6AC0000u, 40u}, // mvn -> Latn
+ {0x6D740000u, 44u}, // mt -> Latn
+ {0x8A6C0000u, 44u}, // mtc -> Latn
+ {0x966C0000u, 44u}, // mtf -> Latn
+ {0xA26C0000u, 44u}, // mti -> Latn
+ {0xC66C0000u, 17u}, // mtr -> Deva
+ {0x828C0000u, 44u}, // mua -> Latn
+ {0xC68C0000u, 44u}, // mur -> Latn
+ {0xCA8C0000u, 44u}, // mus -> Latn
+ {0x82AC0000u, 44u}, // mva -> Latn
+ {0xB6AC0000u, 44u}, // mvn -> Latn
{0xE2AC0000u, 1u}, // mvy -> Arab
- {0xAACC0000u, 40u}, // mwk -> Latn
- {0xC6CC0000u, 16u}, // mwr -> Deva
- {0xD6CC0000u, 40u}, // mwv -> Latn
- {0x8AEC0000u, 40u}, // mxc -> Latn
- {0xB2EC0000u, 40u}, // mxm -> Latn
- {0x6D790000u, 52u}, // my -> Mymr
- {0xAB0C0000u, 40u}, // myk -> Latn
- {0xB30C0000u, 18u}, // mym -> Ethi
- {0xD70C0000u, 15u}, // myv -> Cyrl
- {0xDB0C0000u, 40u}, // myw -> Latn
- {0xDF0C0000u, 40u}, // myx -> Latn
- {0xE70C0000u, 46u}, // myz -> Mand
- {0xAB2C0000u, 40u}, // mzk -> Latn
- {0xB32C0000u, 40u}, // mzm -> Latn
+ {0xAACC0000u, 44u}, // mwk -> Latn
+ {0xC6CC0000u, 17u}, // mwr -> Deva
+ {0xD6CC0000u, 44u}, // mwv -> Latn
+ {0xDACC0000u, 33u}, // mww -> Hmnp
+ {0x8AEC0000u, 44u}, // mxc -> Latn
+ {0xB2EC0000u, 44u}, // mxm -> Latn
+ {0x6D790000u, 56u}, // my -> Mymr
+ {0xAB0C0000u, 44u}, // myk -> Latn
+ {0xB30C0000u, 19u}, // mym -> Ethi
+ {0xD70C0000u, 16u}, // myv -> Cyrl
+ {0xDB0C0000u, 44u}, // myw -> Latn
+ {0xDF0C0000u, 44u}, // myx -> Latn
+ {0xE70C0000u, 50u}, // myz -> Mand
+ {0xAB2C0000u, 44u}, // mzk -> Latn
+ {0xB32C0000u, 44u}, // mzm -> Latn
{0xB72C0000u, 1u}, // mzn -> Arab
- {0xBF2C0000u, 40u}, // mzp -> Latn
- {0xDB2C0000u, 40u}, // mzw -> Latn
- {0xE72C0000u, 40u}, // mzz -> Latn
- {0x6E610000u, 40u}, // na -> Latn
- {0x880D0000u, 40u}, // nac -> Latn
- {0x940D0000u, 40u}, // naf -> Latn
- {0xA80D0000u, 40u}, // nak -> Latn
- {0xB40D0000u, 24u}, // nan -> Hans
- {0xBC0D0000u, 40u}, // nap -> Latn
- {0xC00D0000u, 40u}, // naq -> Latn
- {0xC80D0000u, 40u}, // nas -> Latn
- {0x6E620000u, 40u}, // nb -> Latn
- {0x804D0000u, 40u}, // nca -> Latn
- {0x904D0000u, 40u}, // nce -> Latn
- {0x944D0000u, 40u}, // ncf -> Latn
- {0x9C4D0000u, 40u}, // nch -> Latn
- {0xB84D0000u, 40u}, // nco -> Latn
- {0xD04D0000u, 40u}, // ncu -> Latn
- {0x6E640000u, 40u}, // nd -> Latn
- {0x886D0000u, 40u}, // ndc -> Latn
- {0xC86D0000u, 40u}, // nds -> Latn
- {0x6E650000u, 16u}, // ne -> Deva
- {0x848D0000u, 40u}, // neb -> Latn
- {0xD88D0000u, 16u}, // new -> Deva
- {0xDC8D0000u, 40u}, // nex -> Latn
- {0xC4AD0000u, 40u}, // nfr -> Latn
- {0x6E670000u, 40u}, // ng -> Latn
- {0x80CD0000u, 40u}, // nga -> Latn
- {0x84CD0000u, 40u}, // ngb -> Latn
- {0xACCD0000u, 40u}, // ngl -> Latn
- {0x84ED0000u, 40u}, // nhb -> Latn
- {0x90ED0000u, 40u}, // nhe -> Latn
- {0xD8ED0000u, 40u}, // nhw -> Latn
- {0x950D0000u, 40u}, // nif -> Latn
- {0xA10D0000u, 40u}, // nii -> Latn
- {0xA50D0000u, 40u}, // nij -> Latn
- {0xB50D0000u, 40u}, // nin -> Latn
- {0xD10D0000u, 40u}, // niu -> Latn
- {0xE10D0000u, 40u}, // niy -> Latn
- {0xE50D0000u, 40u}, // niz -> Latn
- {0xB92D0000u, 40u}, // njo -> Latn
- {0x994D0000u, 40u}, // nkg -> Latn
- {0xB94D0000u, 40u}, // nko -> Latn
- {0x6E6C0000u, 40u}, // nl -> Latn
- {0x998D0000u, 40u}, // nmg -> Latn
- {0xE58D0000u, 40u}, // nmz -> Latn
- {0x6E6E0000u, 40u}, // nn -> Latn
- {0x95AD0000u, 40u}, // nnf -> Latn
- {0x9DAD0000u, 40u}, // nnh -> Latn
- {0xA9AD0000u, 40u}, // nnk -> Latn
- {0xB1AD0000u, 40u}, // nnm -> Latn
- {0x6E6F0000u, 40u}, // no -> Latn
- {0x8DCD0000u, 38u}, // nod -> Lana
- {0x91CD0000u, 16u}, // noe -> Deva
- {0xB5CD0000u, 64u}, // non -> Runr
- {0xBDCD0000u, 40u}, // nop -> Latn
- {0xD1CD0000u, 40u}, // nou -> Latn
- {0xBA0D0000u, 54u}, // nqo -> Nkoo
- {0x6E720000u, 40u}, // nr -> Latn
- {0x862D0000u, 40u}, // nrb -> Latn
- {0xAA4D0000u, 9u}, // nsk -> Cans
- {0xB64D0000u, 40u}, // nsn -> Latn
- {0xBA4D0000u, 40u}, // nso -> Latn
- {0xCA4D0000u, 40u}, // nss -> Latn
- {0xB26D0000u, 40u}, // ntm -> Latn
- {0xC66D0000u, 40u}, // ntr -> Latn
- {0xA28D0000u, 40u}, // nui -> Latn
- {0xBE8D0000u, 40u}, // nup -> Latn
- {0xCA8D0000u, 40u}, // nus -> Latn
- {0xD68D0000u, 40u}, // nuv -> Latn
- {0xDE8D0000u, 40u}, // nux -> Latn
- {0x6E760000u, 40u}, // nv -> Latn
- {0x86CD0000u, 40u}, // nwb -> Latn
- {0xC2ED0000u, 40u}, // nxq -> Latn
- {0xC6ED0000u, 40u}, // nxr -> Latn
- {0x6E790000u, 40u}, // ny -> Latn
- {0xB30D0000u, 40u}, // nym -> Latn
- {0xB70D0000u, 40u}, // nyn -> Latn
- {0xA32D0000u, 40u}, // nzi -> Latn
- {0x6F630000u, 40u}, // oc -> Latn
- {0x88CE0000u, 40u}, // ogc -> Latn
- {0xC54E0000u, 40u}, // okr -> Latn
- {0xD54E0000u, 40u}, // okv -> Latn
- {0x6F6D0000u, 40u}, // om -> Latn
- {0x99AE0000u, 40u}, // ong -> Latn
- {0xB5AE0000u, 40u}, // onn -> Latn
- {0xC9AE0000u, 40u}, // ons -> Latn
- {0xB1EE0000u, 40u}, // opm -> Latn
- {0x6F720000u, 57u}, // or -> Orya
- {0xBA2E0000u, 40u}, // oro -> Latn
+ {0xBF2C0000u, 44u}, // mzp -> Latn
+ {0xDB2C0000u, 44u}, // mzw -> Latn
+ {0xE72C0000u, 44u}, // mzz -> Latn
+ {0x6E610000u, 44u}, // na -> Latn
+ {0x880D0000u, 44u}, // nac -> Latn
+ {0x940D0000u, 44u}, // naf -> Latn
+ {0xA80D0000u, 44u}, // nak -> Latn
+ {0xB40D0000u, 27u}, // nan -> Hans
+ {0xBC0D0000u, 44u}, // nap -> Latn
+ {0xC00D0000u, 44u}, // naq -> Latn
+ {0xC80D0000u, 44u}, // nas -> Latn
+ {0x6E620000u, 44u}, // nb -> Latn
+ {0x804D0000u, 44u}, // nca -> Latn
+ {0x904D0000u, 44u}, // nce -> Latn
+ {0x944D0000u, 44u}, // ncf -> Latn
+ {0x9C4D0000u, 44u}, // nch -> Latn
+ {0xB84D0000u, 44u}, // nco -> Latn
+ {0xD04D0000u, 44u}, // ncu -> Latn
+ {0x6E640000u, 44u}, // nd -> Latn
+ {0x886D0000u, 44u}, // ndc -> Latn
+ {0xC86D0000u, 44u}, // nds -> Latn
+ {0x6E650000u, 17u}, // ne -> Deva
+ {0x848D0000u, 44u}, // neb -> Latn
+ {0xD88D0000u, 17u}, // new -> Deva
+ {0xDC8D0000u, 44u}, // nex -> Latn
+ {0xC4AD0000u, 44u}, // nfr -> Latn
+ {0x6E670000u, 44u}, // ng -> Latn
+ {0x80CD0000u, 44u}, // nga -> Latn
+ {0x84CD0000u, 44u}, // ngb -> Latn
+ {0xACCD0000u, 44u}, // ngl -> Latn
+ {0x84ED0000u, 44u}, // nhb -> Latn
+ {0x90ED0000u, 44u}, // nhe -> Latn
+ {0xD8ED0000u, 44u}, // nhw -> Latn
+ {0x950D0000u, 44u}, // nif -> Latn
+ {0xA10D0000u, 44u}, // nii -> Latn
+ {0xA50D0000u, 44u}, // nij -> Latn
+ {0xB50D0000u, 44u}, // nin -> Latn
+ {0xD10D0000u, 44u}, // niu -> Latn
+ {0xE10D0000u, 44u}, // niy -> Latn
+ {0xE50D0000u, 44u}, // niz -> Latn
+ {0xB92D0000u, 44u}, // njo -> Latn
+ {0x994D0000u, 44u}, // nkg -> Latn
+ {0xB94D0000u, 44u}, // nko -> Latn
+ {0x6E6C0000u, 44u}, // nl -> Latn
+ {0x998D0000u, 44u}, // nmg -> Latn
+ {0xE58D0000u, 44u}, // nmz -> Latn
+ {0x6E6E0000u, 44u}, // nn -> Latn
+ {0x95AD0000u, 44u}, // nnf -> Latn
+ {0x9DAD0000u, 44u}, // nnh -> Latn
+ {0xA9AD0000u, 44u}, // nnk -> Latn
+ {0xB1AD0000u, 44u}, // nnm -> Latn
+ {0xBDAD0000u, 91u}, // nnp -> Wcho
+ {0x6E6F0000u, 44u}, // no -> Latn
+ {0x8DCD0000u, 42u}, // nod -> Lana
+ {0x91CD0000u, 17u}, // noe -> Deva
+ {0xB5CD0000u, 69u}, // non -> Runr
+ {0xBDCD0000u, 44u}, // nop -> Latn
+ {0xD1CD0000u, 44u}, // nou -> Latn
+ {0xBA0D0000u, 58u}, // nqo -> Nkoo
+ {0x6E720000u, 44u}, // nr -> Latn
+ {0x862D0000u, 44u}, // nrb -> Latn
+ {0xAA4D0000u, 10u}, // nsk -> Cans
+ {0xB64D0000u, 44u}, // nsn -> Latn
+ {0xBA4D0000u, 44u}, // nso -> Latn
+ {0xCA4D0000u, 44u}, // nss -> Latn
+ {0xB26D0000u, 44u}, // ntm -> Latn
+ {0xC66D0000u, 44u}, // ntr -> Latn
+ {0xA28D0000u, 44u}, // nui -> Latn
+ {0xBE8D0000u, 44u}, // nup -> Latn
+ {0xCA8D0000u, 44u}, // nus -> Latn
+ {0xD68D0000u, 44u}, // nuv -> Latn
+ {0xDE8D0000u, 44u}, // nux -> Latn
+ {0x6E760000u, 44u}, // nv -> Latn
+ {0x86CD0000u, 44u}, // nwb -> Latn
+ {0xC2ED0000u, 44u}, // nxq -> Latn
+ {0xC6ED0000u, 44u}, // nxr -> Latn
+ {0x6E790000u, 44u}, // ny -> Latn
+ {0xB30D0000u, 44u}, // nym -> Latn
+ {0xB70D0000u, 44u}, // nyn -> Latn
+ {0xA32D0000u, 44u}, // nzi -> Latn
+ {0x6F630000u, 44u}, // oc -> Latn
+ {0x88CE0000u, 44u}, // ogc -> Latn
+ {0xC54E0000u, 44u}, // okr -> Latn
+ {0xD54E0000u, 44u}, // okv -> Latn
+ {0x6F6D0000u, 44u}, // om -> Latn
+ {0x99AE0000u, 44u}, // ong -> Latn
+ {0xB5AE0000u, 44u}, // onn -> Latn
+ {0xC9AE0000u, 44u}, // ons -> Latn
+ {0xB1EE0000u, 44u}, // opm -> Latn
+ {0x6F720000u, 62u}, // or -> Orya
+ {0xBA2E0000u, 44u}, // oro -> Latn
{0xD22E0000u, 1u}, // oru -> Arab
- {0x6F730000u, 15u}, // os -> Cyrl
- {0x824E0000u, 58u}, // osa -> Osge
+ {0x6F730000u, 16u}, // os -> Cyrl
+ {0x824E0000u, 63u}, // osa -> Osge
{0x826E0000u, 1u}, // ota -> Arab
- {0xAA6E0000u, 56u}, // otk -> Orkh
- {0xB32E0000u, 40u}, // ozm -> Latn
- {0x70610000u, 23u}, // pa -> Guru
+ {0xAA6E0000u, 61u}, // otk -> Orkh
+ {0xB32E0000u, 44u}, // ozm -> Latn
+ {0x70610000u, 26u}, // pa -> Guru
{0x7061504Bu, 1u}, // pa-PK -> Arab
- {0x980F0000u, 40u}, // pag -> Latn
- {0xAC0F0000u, 60u}, // pal -> Phli
- {0xB00F0000u, 40u}, // pam -> Latn
- {0xBC0F0000u, 40u}, // pap -> Latn
- {0xD00F0000u, 40u}, // pau -> Latn
- {0xA02F0000u, 40u}, // pbi -> Latn
- {0x8C4F0000u, 40u}, // pcd -> Latn
- {0xB04F0000u, 40u}, // pcm -> Latn
- {0x886F0000u, 40u}, // pdc -> Latn
- {0xCC6F0000u, 40u}, // pdt -> Latn
- {0x8C8F0000u, 40u}, // ped -> Latn
- {0xB88F0000u, 84u}, // peo -> Xpeo
- {0xDC8F0000u, 40u}, // pex -> Latn
- {0xACAF0000u, 40u}, // pfl -> Latn
+ {0x980F0000u, 44u}, // pag -> Latn
+ {0xAC0F0000u, 65u}, // pal -> Phli
+ {0xB00F0000u, 44u}, // pam -> Latn
+ {0xBC0F0000u, 44u}, // pap -> Latn
+ {0xD00F0000u, 44u}, // pau -> Latn
+ {0xA02F0000u, 44u}, // pbi -> Latn
+ {0x8C4F0000u, 44u}, // pcd -> Latn
+ {0xB04F0000u, 44u}, // pcm -> Latn
+ {0x886F0000u, 44u}, // pdc -> Latn
+ {0xCC6F0000u, 44u}, // pdt -> Latn
+ {0x8C8F0000u, 44u}, // ped -> Latn
+ {0xB88F0000u, 92u}, // peo -> Xpeo
+ {0xDC8F0000u, 44u}, // pex -> Latn
+ {0xACAF0000u, 44u}, // pfl -> Latn
{0xACEF0000u, 1u}, // phl -> Arab
- {0xB4EF0000u, 61u}, // phn -> Phnx
- {0xAD0F0000u, 40u}, // pil -> Latn
- {0xBD0F0000u, 40u}, // pip -> Latn
+ {0xB4EF0000u, 66u}, // phn -> Phnx
+ {0xAD0F0000u, 44u}, // pil -> Latn
+ {0xBD0F0000u, 44u}, // pip -> Latn
{0x814F0000u, 8u}, // pka -> Brah
- {0xB94F0000u, 40u}, // pko -> Latn
- {0x706C0000u, 40u}, // pl -> Latn
- {0x816F0000u, 40u}, // pla -> Latn
- {0xC98F0000u, 40u}, // pms -> Latn
- {0x99AF0000u, 40u}, // png -> Latn
- {0xB5AF0000u, 40u}, // pnn -> Latn
- {0xCDAF0000u, 21u}, // pnt -> Grek
- {0xB5CF0000u, 40u}, // pon -> Latn
- {0xB9EF0000u, 40u}, // ppo -> Latn
- {0x822F0000u, 34u}, // pra -> Khar
+ {0xB94F0000u, 44u}, // pko -> Latn
+ {0x706C0000u, 44u}, // pl -> Latn
+ {0x816F0000u, 44u}, // pla -> Latn
+ {0xC98F0000u, 44u}, // pms -> Latn
+ {0x99AF0000u, 44u}, // png -> Latn
+ {0xB5AF0000u, 44u}, // pnn -> Latn
+ {0xCDAF0000u, 24u}, // pnt -> Grek
+ {0xB5CF0000u, 44u}, // pon -> Latn
+ {0xB9EF0000u, 44u}, // ppo -> Latn
+ {0x822F0000u, 38u}, // pra -> Khar
{0x8E2F0000u, 1u}, // prd -> Arab
- {0x9A2F0000u, 40u}, // prg -> Latn
+ {0x9A2F0000u, 44u}, // prg -> Latn
{0x70730000u, 1u}, // ps -> Arab
- {0xCA4F0000u, 40u}, // pss -> Latn
- {0x70740000u, 40u}, // pt -> Latn
- {0xBE6F0000u, 40u}, // ptp -> Latn
- {0xD28F0000u, 40u}, // puu -> Latn
- {0x82CF0000u, 40u}, // pwa -> Latn
- {0x71750000u, 40u}, // qu -> Latn
- {0x8A900000u, 40u}, // quc -> Latn
- {0x9A900000u, 40u}, // qug -> Latn
- {0xA0110000u, 40u}, // rai -> Latn
- {0xA4110000u, 16u}, // raj -> Deva
- {0xB8110000u, 40u}, // rao -> Latn
- {0x94510000u, 40u}, // rcf -> Latn
- {0xA4910000u, 40u}, // rej -> Latn
- {0xAC910000u, 40u}, // rel -> Latn
- {0xC8910000u, 40u}, // res -> Latn
- {0xB4D10000u, 40u}, // rgn -> Latn
+ {0xCA4F0000u, 44u}, // pss -> Latn
+ {0x70740000u, 44u}, // pt -> Latn
+ {0xBE6F0000u, 44u}, // ptp -> Latn
+ {0xD28F0000u, 44u}, // puu -> Latn
+ {0x82CF0000u, 44u}, // pwa -> Latn
+ {0x71750000u, 44u}, // qu -> Latn
+ {0x8A900000u, 44u}, // quc -> Latn
+ {0x9A900000u, 44u}, // qug -> Latn
+ {0xA0110000u, 44u}, // rai -> Latn
+ {0xA4110000u, 17u}, // raj -> Deva
+ {0xB8110000u, 44u}, // rao -> Latn
+ {0x94510000u, 44u}, // rcf -> Latn
+ {0xA4910000u, 44u}, // rej -> Latn
+ {0xAC910000u, 44u}, // rel -> Latn
+ {0xC8910000u, 44u}, // res -> Latn
+ {0xB4D10000u, 44u}, // rgn -> Latn
{0x98F10000u, 1u}, // rhg -> Arab
- {0x81110000u, 40u}, // ria -> Latn
- {0x95110000u, 78u}, // rif -> Tfng
- {0x95114E4Cu, 40u}, // rif-NL -> Latn
- {0xC9310000u, 16u}, // rjs -> Deva
+ {0x81110000u, 44u}, // ria -> Latn
+ {0x95110000u, 85u}, // rif -> Tfng
+ {0x95114E4Cu, 44u}, // rif-NL -> Latn
+ {0xC9310000u, 17u}, // rjs -> Deva
{0xCD510000u, 7u}, // rkt -> Beng
- {0x726D0000u, 40u}, // rm -> Latn
- {0x95910000u, 40u}, // rmf -> Latn
- {0xB9910000u, 40u}, // rmo -> Latn
+ {0x726D0000u, 44u}, // rm -> Latn
+ {0x95910000u, 44u}, // rmf -> Latn
+ {0xB9910000u, 44u}, // rmo -> Latn
{0xCD910000u, 1u}, // rmt -> Arab
- {0xD1910000u, 40u}, // rmu -> Latn
- {0x726E0000u, 40u}, // rn -> Latn
- {0x81B10000u, 40u}, // rna -> Latn
- {0x99B10000u, 40u}, // rng -> Latn
- {0x726F0000u, 40u}, // ro -> Latn
- {0x85D10000u, 40u}, // rob -> Latn
- {0x95D10000u, 40u}, // rof -> Latn
- {0xB9D10000u, 40u}, // roo -> Latn
- {0xBA310000u, 40u}, // rro -> Latn
- {0xB2710000u, 40u}, // rtm -> Latn
- {0x72750000u, 15u}, // ru -> Cyrl
- {0x92910000u, 15u}, // rue -> Cyrl
- {0x9A910000u, 40u}, // rug -> Latn
- {0x72770000u, 40u}, // rw -> Latn
- {0xAAD10000u, 40u}, // rwk -> Latn
- {0xBAD10000u, 40u}, // rwo -> Latn
- {0xD3110000u, 33u}, // ryu -> Kana
- {0x73610000u, 16u}, // sa -> Deva
- {0x94120000u, 40u}, // saf -> Latn
- {0x9C120000u, 15u}, // sah -> Cyrl
- {0xC0120000u, 40u}, // saq -> Latn
- {0xC8120000u, 40u}, // sas -> Latn
- {0xCC120000u, 40u}, // sat -> Latn
- {0xE4120000u, 67u}, // saz -> Saur
- {0x80320000u, 40u}, // sba -> Latn
- {0x90320000u, 40u}, // sbe -> Latn
- {0xBC320000u, 40u}, // sbp -> Latn
- {0x73630000u, 40u}, // sc -> Latn
- {0xA8520000u, 16u}, // sck -> Deva
+ {0xD1910000u, 44u}, // rmu -> Latn
+ {0x726E0000u, 44u}, // rn -> Latn
+ {0x81B10000u, 44u}, // rna -> Latn
+ {0x99B10000u, 44u}, // rng -> Latn
+ {0x726F0000u, 44u}, // ro -> Latn
+ {0x85D10000u, 44u}, // rob -> Latn
+ {0x95D10000u, 44u}, // rof -> Latn
+ {0xB9D10000u, 44u}, // roo -> Latn
+ {0xBA310000u, 44u}, // rro -> Latn
+ {0xB2710000u, 44u}, // rtm -> Latn
+ {0x72750000u, 16u}, // ru -> Cyrl
+ {0x92910000u, 16u}, // rue -> Cyrl
+ {0x9A910000u, 44u}, // rug -> Latn
+ {0x72770000u, 44u}, // rw -> Latn
+ {0xAAD10000u, 44u}, // rwk -> Latn
+ {0xBAD10000u, 44u}, // rwo -> Latn
+ {0xD3110000u, 37u}, // ryu -> Kana
+ {0x73610000u, 17u}, // sa -> Deva
+ {0x94120000u, 44u}, // saf -> Latn
+ {0x9C120000u, 16u}, // sah -> Cyrl
+ {0xC0120000u, 44u}, // saq -> Latn
+ {0xC8120000u, 44u}, // sas -> Latn
+ {0xCC120000u, 44u}, // sat -> Latn
+ {0xD4120000u, 44u}, // sav -> Latn
+ {0xE4120000u, 72u}, // saz -> Saur
+ {0x80320000u, 44u}, // sba -> Latn
+ {0x90320000u, 44u}, // sbe -> Latn
+ {0xBC320000u, 44u}, // sbp -> Latn
+ {0x73630000u, 44u}, // sc -> Latn
+ {0xA8520000u, 17u}, // sck -> Deva
{0xAC520000u, 1u}, // scl -> Arab
- {0xB4520000u, 40u}, // scn -> Latn
- {0xB8520000u, 40u}, // sco -> Latn
- {0xC8520000u, 40u}, // scs -> Latn
+ {0xB4520000u, 44u}, // scn -> Latn
+ {0xB8520000u, 44u}, // sco -> Latn
+ {0xC8520000u, 44u}, // scs -> Latn
{0x73640000u, 1u}, // sd -> Arab
- {0x88720000u, 40u}, // sdc -> Latn
+ {0x88720000u, 44u}, // sdc -> Latn
{0x9C720000u, 1u}, // sdh -> Arab
- {0x73650000u, 40u}, // se -> Latn
- {0x94920000u, 40u}, // sef -> Latn
- {0x9C920000u, 40u}, // seh -> Latn
- {0xA0920000u, 40u}, // sei -> Latn
- {0xC8920000u, 40u}, // ses -> Latn
- {0x73670000u, 40u}, // sg -> Latn
- {0x80D20000u, 55u}, // sga -> Ogam
- {0xC8D20000u, 40u}, // sgs -> Latn
- {0xD8D20000u, 18u}, // sgw -> Ethi
- {0xE4D20000u, 40u}, // sgz -> Latn
- {0x73680000u, 40u}, // sh -> Latn
- {0xA0F20000u, 78u}, // shi -> Tfng
- {0xA8F20000u, 40u}, // shk -> Latn
- {0xB4F20000u, 52u}, // shn -> Mymr
+ {0x73650000u, 44u}, // se -> Latn
+ {0x94920000u, 44u}, // sef -> Latn
+ {0x9C920000u, 44u}, // seh -> Latn
+ {0xA0920000u, 44u}, // sei -> Latn
+ {0xC8920000u, 44u}, // ses -> Latn
+ {0x73670000u, 44u}, // sg -> Latn
+ {0x80D20000u, 60u}, // sga -> Ogam
+ {0xC8D20000u, 44u}, // sgs -> Latn
+ {0xD8D20000u, 19u}, // sgw -> Ethi
+ {0xE4D20000u, 44u}, // sgz -> Latn
+ {0x73680000u, 44u}, // sh -> Latn
+ {0xA0F20000u, 85u}, // shi -> Tfng
+ {0xA8F20000u, 44u}, // shk -> Latn
+ {0xB4F20000u, 56u}, // shn -> Mymr
{0xD0F20000u, 1u}, // shu -> Arab
- {0x73690000u, 69u}, // si -> Sinh
- {0x8D120000u, 40u}, // sid -> Latn
- {0x99120000u, 40u}, // sig -> Latn
- {0xAD120000u, 40u}, // sil -> Latn
- {0xB1120000u, 40u}, // sim -> Latn
- {0xC5320000u, 40u}, // sjr -> Latn
- {0x736B0000u, 40u}, // sk -> Latn
- {0x89520000u, 40u}, // skc -> Latn
+ {0x73690000u, 74u}, // si -> Sinh
+ {0x8D120000u, 44u}, // sid -> Latn
+ {0x99120000u, 44u}, // sig -> Latn
+ {0xAD120000u, 44u}, // sil -> Latn
+ {0xB1120000u, 44u}, // sim -> Latn
+ {0xC5320000u, 44u}, // sjr -> Latn
+ {0x736B0000u, 44u}, // sk -> Latn
+ {0x89520000u, 44u}, // skc -> Latn
{0xC5520000u, 1u}, // skr -> Arab
- {0xC9520000u, 40u}, // sks -> Latn
- {0x736C0000u, 40u}, // sl -> Latn
- {0x8D720000u, 40u}, // sld -> Latn
- {0xA1720000u, 40u}, // sli -> Latn
- {0xAD720000u, 40u}, // sll -> Latn
- {0xE1720000u, 40u}, // sly -> Latn
- {0x736D0000u, 40u}, // sm -> Latn
- {0x81920000u, 40u}, // sma -> Latn
- {0xA5920000u, 40u}, // smj -> Latn
- {0xB5920000u, 40u}, // smn -> Latn
- {0xBD920000u, 65u}, // smp -> Samr
- {0xC1920000u, 40u}, // smq -> Latn
- {0xC9920000u, 40u}, // sms -> Latn
- {0x736E0000u, 40u}, // sn -> Latn
- {0x89B20000u, 40u}, // snc -> Latn
- {0xA9B20000u, 40u}, // snk -> Latn
- {0xBDB20000u, 40u}, // snp -> Latn
- {0xDDB20000u, 40u}, // snx -> Latn
- {0xE1B20000u, 40u}, // sny -> Latn
- {0x736F0000u, 40u}, // so -> Latn
- {0xA9D20000u, 40u}, // sok -> Latn
- {0xC1D20000u, 40u}, // soq -> Latn
- {0xD1D20000u, 80u}, // sou -> Thai
- {0xE1D20000u, 40u}, // soy -> Latn
- {0x8DF20000u, 40u}, // spd -> Latn
- {0xADF20000u, 40u}, // spl -> Latn
- {0xC9F20000u, 40u}, // sps -> Latn
- {0x73710000u, 40u}, // sq -> Latn
- {0x73720000u, 15u}, // sr -> Cyrl
- {0x73724D45u, 40u}, // sr-ME -> Latn
- {0x7372524Fu, 40u}, // sr-RO -> Latn
- {0x73725255u, 40u}, // sr-RU -> Latn
- {0x73725452u, 40u}, // sr-TR -> Latn
- {0x86320000u, 70u}, // srb -> Sora
- {0xB6320000u, 40u}, // srn -> Latn
- {0xC6320000u, 40u}, // srr -> Latn
- {0xDE320000u, 16u}, // srx -> Deva
- {0x73730000u, 40u}, // ss -> Latn
- {0x8E520000u, 40u}, // ssd -> Latn
- {0x9A520000u, 40u}, // ssg -> Latn
- {0xE2520000u, 40u}, // ssy -> Latn
- {0x73740000u, 40u}, // st -> Latn
- {0xAA720000u, 40u}, // stk -> Latn
- {0xC2720000u, 40u}, // stq -> Latn
- {0x73750000u, 40u}, // su -> Latn
- {0x82920000u, 40u}, // sua -> Latn
- {0x92920000u, 40u}, // sue -> Latn
- {0xAA920000u, 40u}, // suk -> Latn
- {0xC6920000u, 40u}, // sur -> Latn
- {0xCA920000u, 40u}, // sus -> Latn
- {0x73760000u, 40u}, // sv -> Latn
- {0x73770000u, 40u}, // sw -> Latn
+ {0xC9520000u, 44u}, // sks -> Latn
+ {0x736C0000u, 44u}, // sl -> Latn
+ {0x8D720000u, 44u}, // sld -> Latn
+ {0xA1720000u, 44u}, // sli -> Latn
+ {0xAD720000u, 44u}, // sll -> Latn
+ {0xE1720000u, 44u}, // sly -> Latn
+ {0x736D0000u, 44u}, // sm -> Latn
+ {0x81920000u, 44u}, // sma -> Latn
+ {0xA5920000u, 44u}, // smj -> Latn
+ {0xB5920000u, 44u}, // smn -> Latn
+ {0xBD920000u, 70u}, // smp -> Samr
+ {0xC1920000u, 44u}, // smq -> Latn
+ {0xC9920000u, 44u}, // sms -> Latn
+ {0x736E0000u, 44u}, // sn -> Latn
+ {0x89B20000u, 44u}, // snc -> Latn
+ {0xA9B20000u, 44u}, // snk -> Latn
+ {0xBDB20000u, 44u}, // snp -> Latn
+ {0xDDB20000u, 44u}, // snx -> Latn
+ {0xE1B20000u, 44u}, // sny -> Latn
+ {0x736F0000u, 44u}, // so -> Latn
+ {0x99D20000u, 75u}, // sog -> Sogd
+ {0xA9D20000u, 44u}, // sok -> Latn
+ {0xC1D20000u, 44u}, // soq -> Latn
+ {0xD1D20000u, 87u}, // sou -> Thai
+ {0xE1D20000u, 44u}, // soy -> Latn
+ {0x8DF20000u, 44u}, // spd -> Latn
+ {0xADF20000u, 44u}, // spl -> Latn
+ {0xC9F20000u, 44u}, // sps -> Latn
+ {0x73710000u, 44u}, // sq -> Latn
+ {0x73720000u, 16u}, // sr -> Cyrl
+ {0x73724D45u, 44u}, // sr-ME -> Latn
+ {0x7372524Fu, 44u}, // sr-RO -> Latn
+ {0x73725255u, 44u}, // sr-RU -> Latn
+ {0x73725452u, 44u}, // sr-TR -> Latn
+ {0x86320000u, 76u}, // srb -> Sora
+ {0xB6320000u, 44u}, // srn -> Latn
+ {0xC6320000u, 44u}, // srr -> Latn
+ {0xDE320000u, 17u}, // srx -> Deva
+ {0x73730000u, 44u}, // ss -> Latn
+ {0x8E520000u, 44u}, // ssd -> Latn
+ {0x9A520000u, 44u}, // ssg -> Latn
+ {0xE2520000u, 44u}, // ssy -> Latn
+ {0x73740000u, 44u}, // st -> Latn
+ {0xAA720000u, 44u}, // stk -> Latn
+ {0xC2720000u, 44u}, // stq -> Latn
+ {0x73750000u, 44u}, // su -> Latn
+ {0x82920000u, 44u}, // sua -> Latn
+ {0x92920000u, 44u}, // sue -> Latn
+ {0xAA920000u, 44u}, // suk -> Latn
+ {0xC6920000u, 44u}, // sur -> Latn
+ {0xCA920000u, 44u}, // sus -> Latn
+ {0x73760000u, 44u}, // sv -> Latn
+ {0x73770000u, 44u}, // sw -> Latn
{0x86D20000u, 1u}, // swb -> Arab
- {0x8AD20000u, 40u}, // swc -> Latn
- {0x9AD20000u, 40u}, // swg -> Latn
- {0xBED20000u, 40u}, // swp -> Latn
- {0xD6D20000u, 16u}, // swv -> Deva
- {0xB6F20000u, 40u}, // sxn -> Latn
- {0xDAF20000u, 40u}, // sxw -> Latn
+ {0x8AD20000u, 44u}, // swc -> Latn
+ {0x9AD20000u, 44u}, // swg -> Latn
+ {0xBED20000u, 44u}, // swp -> Latn
+ {0xD6D20000u, 17u}, // swv -> Deva
+ {0xB6F20000u, 44u}, // sxn -> Latn
+ {0xDAF20000u, 44u}, // sxw -> Latn
{0xAF120000u, 7u}, // syl -> Beng
- {0xC7120000u, 71u}, // syr -> Syrc
- {0xAF320000u, 40u}, // szl -> Latn
- {0x74610000u, 74u}, // ta -> Taml
- {0xA4130000u, 16u}, // taj -> Deva
- {0xAC130000u, 40u}, // tal -> Latn
- {0xB4130000u, 40u}, // tan -> Latn
- {0xC0130000u, 40u}, // taq -> Latn
- {0x88330000u, 40u}, // tbc -> Latn
- {0x8C330000u, 40u}, // tbd -> Latn
- {0x94330000u, 40u}, // tbf -> Latn
- {0x98330000u, 40u}, // tbg -> Latn
- {0xB8330000u, 40u}, // tbo -> Latn
- {0xD8330000u, 40u}, // tbw -> Latn
- {0xE4330000u, 40u}, // tbz -> Latn
- {0xA0530000u, 40u}, // tci -> Latn
- {0xE0530000u, 36u}, // tcy -> Knda
- {0x8C730000u, 72u}, // tdd -> Tale
- {0x98730000u, 16u}, // tdg -> Deva
- {0x9C730000u, 16u}, // tdh -> Deva
- {0x74650000u, 77u}, // te -> Telu
- {0x8C930000u, 40u}, // ted -> Latn
- {0xB0930000u, 40u}, // tem -> Latn
- {0xB8930000u, 40u}, // teo -> Latn
- {0xCC930000u, 40u}, // tet -> Latn
- {0xA0B30000u, 40u}, // tfi -> Latn
- {0x74670000u, 15u}, // tg -> Cyrl
+ {0xC7120000u, 78u}, // syr -> Syrc
+ {0xAF320000u, 44u}, // szl -> Latn
+ {0x74610000u, 81u}, // ta -> Taml
+ {0xA4130000u, 17u}, // taj -> Deva
+ {0xAC130000u, 44u}, // tal -> Latn
+ {0xB4130000u, 44u}, // tan -> Latn
+ {0xC0130000u, 44u}, // taq -> Latn
+ {0x88330000u, 44u}, // tbc -> Latn
+ {0x8C330000u, 44u}, // tbd -> Latn
+ {0x94330000u, 44u}, // tbf -> Latn
+ {0x98330000u, 44u}, // tbg -> Latn
+ {0xB8330000u, 44u}, // tbo -> Latn
+ {0xD8330000u, 44u}, // tbw -> Latn
+ {0xE4330000u, 44u}, // tbz -> Latn
+ {0xA0530000u, 44u}, // tci -> Latn
+ {0xE0530000u, 40u}, // tcy -> Knda
+ {0x8C730000u, 79u}, // tdd -> Tale
+ {0x98730000u, 17u}, // tdg -> Deva
+ {0x9C730000u, 17u}, // tdh -> Deva
+ {0x74650000u, 84u}, // te -> Telu
+ {0x8C930000u, 44u}, // ted -> Latn
+ {0xB0930000u, 44u}, // tem -> Latn
+ {0xB8930000u, 44u}, // teo -> Latn
+ {0xCC930000u, 44u}, // tet -> Latn
+ {0xA0B30000u, 44u}, // tfi -> Latn
+ {0x74670000u, 16u}, // tg -> Cyrl
{0x7467504Bu, 1u}, // tg-PK -> Arab
- {0x88D30000u, 40u}, // tgc -> Latn
- {0xB8D30000u, 40u}, // tgo -> Latn
- {0xD0D30000u, 40u}, // tgu -> Latn
- {0x74680000u, 80u}, // th -> Thai
- {0xACF30000u, 16u}, // thl -> Deva
- {0xC0F30000u, 16u}, // thq -> Deva
- {0xC4F30000u, 16u}, // thr -> Deva
- {0x74690000u, 18u}, // ti -> Ethi
- {0x95130000u, 40u}, // tif -> Latn
- {0x99130000u, 18u}, // tig -> Ethi
- {0xA9130000u, 40u}, // tik -> Latn
- {0xB1130000u, 40u}, // tim -> Latn
- {0xB9130000u, 40u}, // tio -> Latn
- {0xD5130000u, 40u}, // tiv -> Latn
- {0x746B0000u, 40u}, // tk -> Latn
- {0xAD530000u, 40u}, // tkl -> Latn
- {0xC5530000u, 40u}, // tkr -> Latn
- {0xCD530000u, 16u}, // tkt -> Deva
- {0x746C0000u, 40u}, // tl -> Latn
- {0x95730000u, 40u}, // tlf -> Latn
- {0xDD730000u, 40u}, // tlx -> Latn
- {0xE1730000u, 40u}, // tly -> Latn
- {0x9D930000u, 40u}, // tmh -> Latn
- {0xE1930000u, 40u}, // tmy -> Latn
- {0x746E0000u, 40u}, // tn -> Latn
- {0x9DB30000u, 40u}, // tnh -> Latn
- {0x746F0000u, 40u}, // to -> Latn
- {0x95D30000u, 40u}, // tof -> Latn
- {0x99D30000u, 40u}, // tog -> Latn
- {0xC1D30000u, 40u}, // toq -> Latn
- {0xA1F30000u, 40u}, // tpi -> Latn
- {0xB1F30000u, 40u}, // tpm -> Latn
- {0xE5F30000u, 40u}, // tpz -> Latn
- {0xBA130000u, 40u}, // tqo -> Latn
- {0x74720000u, 40u}, // tr -> Latn
- {0xD2330000u, 40u}, // tru -> Latn
- {0xD6330000u, 40u}, // trv -> Latn
+ {0x88D30000u, 44u}, // tgc -> Latn
+ {0xB8D30000u, 44u}, // tgo -> Latn
+ {0xD0D30000u, 44u}, // tgu -> Latn
+ {0x74680000u, 87u}, // th -> Thai
+ {0xACF30000u, 17u}, // thl -> Deva
+ {0xC0F30000u, 17u}, // thq -> Deva
+ {0xC4F30000u, 17u}, // thr -> Deva
+ {0x74690000u, 19u}, // ti -> Ethi
+ {0x95130000u, 44u}, // tif -> Latn
+ {0x99130000u, 19u}, // tig -> Ethi
+ {0xA9130000u, 44u}, // tik -> Latn
+ {0xB1130000u, 44u}, // tim -> Latn
+ {0xB9130000u, 44u}, // tio -> Latn
+ {0xD5130000u, 44u}, // tiv -> Latn
+ {0x746B0000u, 44u}, // tk -> Latn
+ {0xAD530000u, 44u}, // tkl -> Latn
+ {0xC5530000u, 44u}, // tkr -> Latn
+ {0xCD530000u, 17u}, // tkt -> Deva
+ {0x746C0000u, 44u}, // tl -> Latn
+ {0x95730000u, 44u}, // tlf -> Latn
+ {0xDD730000u, 44u}, // tlx -> Latn
+ {0xE1730000u, 44u}, // tly -> Latn
+ {0x9D930000u, 44u}, // tmh -> Latn
+ {0xE1930000u, 44u}, // tmy -> Latn
+ {0x746E0000u, 44u}, // tn -> Latn
+ {0x9DB30000u, 44u}, // tnh -> Latn
+ {0x746F0000u, 44u}, // to -> Latn
+ {0x95D30000u, 44u}, // tof -> Latn
+ {0x99D30000u, 44u}, // tog -> Latn
+ {0xC1D30000u, 44u}, // toq -> Latn
+ {0xA1F30000u, 44u}, // tpi -> Latn
+ {0xB1F30000u, 44u}, // tpm -> Latn
+ {0xE5F30000u, 44u}, // tpz -> Latn
+ {0xBA130000u, 44u}, // tqo -> Latn
+ {0x74720000u, 44u}, // tr -> Latn
+ {0xD2330000u, 44u}, // tru -> Latn
+ {0xD6330000u, 44u}, // trv -> Latn
{0xDA330000u, 1u}, // trw -> Arab
- {0x74730000u, 40u}, // ts -> Latn
- {0x8E530000u, 21u}, // tsd -> Grek
- {0x96530000u, 16u}, // tsf -> Deva
- {0x9A530000u, 40u}, // tsg -> Latn
- {0xA6530000u, 81u}, // tsj -> Tibt
- {0xDA530000u, 40u}, // tsw -> Latn
- {0x74740000u, 15u}, // tt -> Cyrl
- {0x8E730000u, 40u}, // ttd -> Latn
- {0x92730000u, 40u}, // tte -> Latn
- {0xA6730000u, 40u}, // ttj -> Latn
- {0xC6730000u, 40u}, // ttr -> Latn
- {0xCA730000u, 80u}, // tts -> Thai
- {0xCE730000u, 40u}, // ttt -> Latn
- {0x9E930000u, 40u}, // tuh -> Latn
- {0xAE930000u, 40u}, // tul -> Latn
- {0xB2930000u, 40u}, // tum -> Latn
- {0xC2930000u, 40u}, // tuq -> Latn
- {0x8EB30000u, 40u}, // tvd -> Latn
- {0xAEB30000u, 40u}, // tvl -> Latn
- {0xD2B30000u, 40u}, // tvu -> Latn
- {0x9ED30000u, 40u}, // twh -> Latn
- {0xC2D30000u, 40u}, // twq -> Latn
- {0x9AF30000u, 75u}, // txg -> Tang
- {0x74790000u, 40u}, // ty -> Latn
- {0x83130000u, 40u}, // tya -> Latn
- {0xD7130000u, 15u}, // tyv -> Cyrl
- {0xB3330000u, 40u}, // tzm -> Latn
- {0xD0340000u, 40u}, // ubu -> Latn
- {0xB0740000u, 15u}, // udm -> Cyrl
+ {0x74730000u, 44u}, // ts -> Latn
+ {0x8E530000u, 24u}, // tsd -> Grek
+ {0x96530000u, 17u}, // tsf -> Deva
+ {0x9A530000u, 44u}, // tsg -> Latn
+ {0xA6530000u, 88u}, // tsj -> Tibt
+ {0xDA530000u, 44u}, // tsw -> Latn
+ {0x74740000u, 16u}, // tt -> Cyrl
+ {0x8E730000u, 44u}, // ttd -> Latn
+ {0x92730000u, 44u}, // tte -> Latn
+ {0xA6730000u, 44u}, // ttj -> Latn
+ {0xC6730000u, 44u}, // ttr -> Latn
+ {0xCA730000u, 87u}, // tts -> Thai
+ {0xCE730000u, 44u}, // ttt -> Latn
+ {0x9E930000u, 44u}, // tuh -> Latn
+ {0xAE930000u, 44u}, // tul -> Latn
+ {0xB2930000u, 44u}, // tum -> Latn
+ {0xC2930000u, 44u}, // tuq -> Latn
+ {0x8EB30000u, 44u}, // tvd -> Latn
+ {0xAEB30000u, 44u}, // tvl -> Latn
+ {0xD2B30000u, 44u}, // tvu -> Latn
+ {0x9ED30000u, 44u}, // twh -> Latn
+ {0xC2D30000u, 44u}, // twq -> Latn
+ {0x9AF30000u, 82u}, // txg -> Tang
+ {0x74790000u, 44u}, // ty -> Latn
+ {0x83130000u, 44u}, // tya -> Latn
+ {0xD7130000u, 16u}, // tyv -> Cyrl
+ {0xB3330000u, 44u}, // tzm -> Latn
+ {0xD0340000u, 44u}, // ubu -> Latn
+ {0xB0740000u, 16u}, // udm -> Cyrl
{0x75670000u, 1u}, // ug -> Arab
- {0x75674B5Au, 15u}, // ug-KZ -> Cyrl
- {0x75674D4Eu, 15u}, // ug-MN -> Cyrl
- {0x80D40000u, 82u}, // uga -> Ugar
- {0x756B0000u, 15u}, // uk -> Cyrl
- {0xA1740000u, 40u}, // uli -> Latn
- {0x85940000u, 40u}, // umb -> Latn
+ {0x75674B5Au, 16u}, // ug-KZ -> Cyrl
+ {0x75674D4Eu, 16u}, // ug-MN -> Cyrl
+ {0x80D40000u, 89u}, // uga -> Ugar
+ {0x756B0000u, 16u}, // uk -> Cyrl
+ {0xA1740000u, 44u}, // uli -> Latn
+ {0x85940000u, 44u}, // umb -> Latn
{0xC5B40000u, 7u}, // unr -> Beng
- {0xC5B44E50u, 16u}, // unr-NP -> Deva
+ {0xC5B44E50u, 17u}, // unr-NP -> Deva
{0xDDB40000u, 7u}, // unx -> Beng
{0x75720000u, 1u}, // ur -> Arab
- {0xA2340000u, 40u}, // uri -> Latn
- {0xCE340000u, 40u}, // urt -> Latn
- {0xDA340000u, 40u}, // urw -> Latn
- {0x82540000u, 40u}, // usa -> Latn
- {0xC6740000u, 40u}, // utr -> Latn
- {0x9EB40000u, 40u}, // uvh -> Latn
- {0xAEB40000u, 40u}, // uvl -> Latn
- {0x757A0000u, 40u}, // uz -> Latn
+ {0xA2340000u, 44u}, // uri -> Latn
+ {0xCE340000u, 44u}, // urt -> Latn
+ {0xDA340000u, 44u}, // urw -> Latn
+ {0x82540000u, 44u}, // usa -> Latn
+ {0xC6740000u, 44u}, // utr -> Latn
+ {0x9EB40000u, 44u}, // uvh -> Latn
+ {0xAEB40000u, 44u}, // uvl -> Latn
+ {0x757A0000u, 44u}, // uz -> Latn
{0x757A4146u, 1u}, // uz-AF -> Arab
- {0x757A434Eu, 15u}, // uz-CN -> Cyrl
- {0x98150000u, 40u}, // vag -> Latn
- {0xA0150000u, 83u}, // vai -> Vaii
- {0xB4150000u, 40u}, // van -> Latn
- {0x76650000u, 40u}, // ve -> Latn
- {0x88950000u, 40u}, // vec -> Latn
- {0xBC950000u, 40u}, // vep -> Latn
- {0x76690000u, 40u}, // vi -> Latn
- {0x89150000u, 40u}, // vic -> Latn
- {0xD5150000u, 40u}, // viv -> Latn
- {0xC9750000u, 40u}, // vls -> Latn
- {0x95950000u, 40u}, // vmf -> Latn
- {0xD9950000u, 40u}, // vmw -> Latn
- {0x766F0000u, 40u}, // vo -> Latn
- {0xCDD50000u, 40u}, // vot -> Latn
- {0xBA350000u, 40u}, // vro -> Latn
- {0xB6950000u, 40u}, // vun -> Latn
- {0xCE950000u, 40u}, // vut -> Latn
- {0x77610000u, 40u}, // wa -> Latn
- {0x90160000u, 40u}, // wae -> Latn
- {0xA4160000u, 40u}, // waj -> Latn
- {0xAC160000u, 18u}, // wal -> Ethi
- {0xB4160000u, 40u}, // wan -> Latn
- {0xC4160000u, 40u}, // war -> Latn
- {0xBC360000u, 40u}, // wbp -> Latn
- {0xC0360000u, 77u}, // wbq -> Telu
- {0xC4360000u, 16u}, // wbr -> Deva
- {0xA0560000u, 40u}, // wci -> Latn
- {0xC4960000u, 40u}, // wer -> Latn
- {0xA0D60000u, 40u}, // wgi -> Latn
- {0x98F60000u, 40u}, // whg -> Latn
- {0x85160000u, 40u}, // wib -> Latn
- {0xD1160000u, 40u}, // wiu -> Latn
- {0xD5160000u, 40u}, // wiv -> Latn
- {0x81360000u, 40u}, // wja -> Latn
- {0xA1360000u, 40u}, // wji -> Latn
- {0xC9760000u, 40u}, // wls -> Latn
- {0xB9960000u, 40u}, // wmo -> Latn
- {0x89B60000u, 40u}, // wnc -> Latn
+ {0x757A434Eu, 16u}, // uz-CN -> Cyrl
+ {0x98150000u, 44u}, // vag -> Latn
+ {0xA0150000u, 90u}, // vai -> Vaii
+ {0xB4150000u, 44u}, // van -> Latn
+ {0x76650000u, 44u}, // ve -> Latn
+ {0x88950000u, 44u}, // vec -> Latn
+ {0xBC950000u, 44u}, // vep -> Latn
+ {0x76690000u, 44u}, // vi -> Latn
+ {0x89150000u, 44u}, // vic -> Latn
+ {0xD5150000u, 44u}, // viv -> Latn
+ {0xC9750000u, 44u}, // vls -> Latn
+ {0x95950000u, 44u}, // vmf -> Latn
+ {0xD9950000u, 44u}, // vmw -> Latn
+ {0x766F0000u, 44u}, // vo -> Latn
+ {0xCDD50000u, 44u}, // vot -> Latn
+ {0xBA350000u, 44u}, // vro -> Latn
+ {0xB6950000u, 44u}, // vun -> Latn
+ {0xCE950000u, 44u}, // vut -> Latn
+ {0x77610000u, 44u}, // wa -> Latn
+ {0x90160000u, 44u}, // wae -> Latn
+ {0xA4160000u, 44u}, // waj -> Latn
+ {0xAC160000u, 19u}, // wal -> Ethi
+ {0xB4160000u, 44u}, // wan -> Latn
+ {0xC4160000u, 44u}, // war -> Latn
+ {0xBC360000u, 44u}, // wbp -> Latn
+ {0xC0360000u, 84u}, // wbq -> Telu
+ {0xC4360000u, 17u}, // wbr -> Deva
+ {0xA0560000u, 44u}, // wci -> Latn
+ {0xC4960000u, 44u}, // wer -> Latn
+ {0xA0D60000u, 44u}, // wgi -> Latn
+ {0x98F60000u, 44u}, // whg -> Latn
+ {0x85160000u, 44u}, // wib -> Latn
+ {0xD1160000u, 44u}, // wiu -> Latn
+ {0xD5160000u, 44u}, // wiv -> Latn
+ {0x81360000u, 44u}, // wja -> Latn
+ {0xA1360000u, 44u}, // wji -> Latn
+ {0xC9760000u, 44u}, // wls -> Latn
+ {0xB9960000u, 44u}, // wmo -> Latn
+ {0x89B60000u, 44u}, // wnc -> Latn
{0xA1B60000u, 1u}, // wni -> Arab
- {0xD1B60000u, 40u}, // wnu -> Latn
- {0x776F0000u, 40u}, // wo -> Latn
- {0x85D60000u, 40u}, // wob -> Latn
- {0xC9D60000u, 40u}, // wos -> Latn
- {0xCA360000u, 40u}, // wrs -> Latn
- {0xAA560000u, 40u}, // wsk -> Latn
- {0xB2760000u, 16u}, // wtm -> Deva
- {0xD2960000u, 24u}, // wuu -> Hans
- {0xD6960000u, 40u}, // wuv -> Latn
- {0x82D60000u, 40u}, // wwa -> Latn
- {0xD4170000u, 40u}, // xav -> Latn
- {0xA0370000u, 40u}, // xbi -> Latn
- {0xC4570000u, 10u}, // xcr -> Cari
- {0xC8970000u, 40u}, // xes -> Latn
- {0x78680000u, 40u}, // xh -> Latn
- {0x81770000u, 40u}, // xla -> Latn
- {0x89770000u, 44u}, // xlc -> Lyci
- {0x8D770000u, 45u}, // xld -> Lydi
- {0x95970000u, 19u}, // xmf -> Geor
- {0xB5970000u, 47u}, // xmn -> Mani
- {0xC5970000u, 48u}, // xmr -> Merc
- {0x81B70000u, 53u}, // xna -> Narb
- {0xC5B70000u, 16u}, // xnr -> Deva
- {0x99D70000u, 40u}, // xog -> Latn
- {0xB5D70000u, 40u}, // xon -> Latn
- {0xC5F70000u, 63u}, // xpr -> Prti
- {0x86370000u, 40u}, // xrb -> Latn
- {0x82570000u, 66u}, // xsa -> Sarb
- {0xA2570000u, 40u}, // xsi -> Latn
- {0xB2570000u, 40u}, // xsm -> Latn
- {0xC6570000u, 16u}, // xsr -> Deva
- {0x92D70000u, 40u}, // xwe -> Latn
- {0xB0180000u, 40u}, // yam -> Latn
- {0xB8180000u, 40u}, // yao -> Latn
- {0xBC180000u, 40u}, // yap -> Latn
- {0xC8180000u, 40u}, // yas -> Latn
- {0xCC180000u, 40u}, // yat -> Latn
- {0xD4180000u, 40u}, // yav -> Latn
- {0xE0180000u, 40u}, // yay -> Latn
- {0xE4180000u, 40u}, // yaz -> Latn
- {0x80380000u, 40u}, // yba -> Latn
- {0x84380000u, 40u}, // ybb -> Latn
- {0xE0380000u, 40u}, // yby -> Latn
- {0xC4980000u, 40u}, // yer -> Latn
- {0xC4D80000u, 40u}, // ygr -> Latn
- {0xD8D80000u, 40u}, // ygw -> Latn
- {0x79690000u, 27u}, // yi -> Hebr
- {0xB9580000u, 40u}, // yko -> Latn
- {0x91780000u, 40u}, // yle -> Latn
- {0x99780000u, 40u}, // ylg -> Latn
- {0xAD780000u, 40u}, // yll -> Latn
- {0xAD980000u, 40u}, // yml -> Latn
- {0x796F0000u, 40u}, // yo -> Latn
- {0xB5D80000u, 40u}, // yon -> Latn
- {0x86380000u, 40u}, // yrb -> Latn
- {0x92380000u, 40u}, // yre -> Latn
- {0xAE380000u, 40u}, // yrl -> Latn
- {0xCA580000u, 40u}, // yss -> Latn
- {0x82980000u, 40u}, // yua -> Latn
- {0x92980000u, 25u}, // yue -> Hant
- {0x9298434Eu, 24u}, // yue-CN -> Hans
- {0xA6980000u, 40u}, // yuj -> Latn
- {0xCE980000u, 40u}, // yut -> Latn
- {0xDA980000u, 40u}, // yuw -> Latn
- {0x7A610000u, 40u}, // za -> Latn
- {0x98190000u, 40u}, // zag -> Latn
+ {0xD1B60000u, 44u}, // wnu -> Latn
+ {0x776F0000u, 44u}, // wo -> Latn
+ {0x85D60000u, 44u}, // wob -> Latn
+ {0xC9D60000u, 44u}, // wos -> Latn
+ {0xCA360000u, 44u}, // wrs -> Latn
+ {0x9A560000u, 21u}, // wsg -> Gong
+ {0xAA560000u, 44u}, // wsk -> Latn
+ {0xB2760000u, 17u}, // wtm -> Deva
+ {0xD2960000u, 27u}, // wuu -> Hans
+ {0xD6960000u, 44u}, // wuv -> Latn
+ {0x82D60000u, 44u}, // wwa -> Latn
+ {0xD4170000u, 44u}, // xav -> Latn
+ {0xA0370000u, 44u}, // xbi -> Latn
+ {0xC4570000u, 11u}, // xcr -> Cari
+ {0xC8970000u, 44u}, // xes -> Latn
+ {0x78680000u, 44u}, // xh -> Latn
+ {0x81770000u, 44u}, // xla -> Latn
+ {0x89770000u, 48u}, // xlc -> Lyci
+ {0x8D770000u, 49u}, // xld -> Lydi
+ {0x95970000u, 20u}, // xmf -> Geor
+ {0xB5970000u, 51u}, // xmn -> Mani
+ {0xC5970000u, 52u}, // xmr -> Merc
+ {0x81B70000u, 57u}, // xna -> Narb
+ {0xC5B70000u, 17u}, // xnr -> Deva
+ {0x99D70000u, 44u}, // xog -> Latn
+ {0xB5D70000u, 44u}, // xon -> Latn
+ {0xC5F70000u, 68u}, // xpr -> Prti
+ {0x86370000u, 44u}, // xrb -> Latn
+ {0x82570000u, 71u}, // xsa -> Sarb
+ {0xA2570000u, 44u}, // xsi -> Latn
+ {0xB2570000u, 44u}, // xsm -> Latn
+ {0xC6570000u, 17u}, // xsr -> Deva
+ {0x92D70000u, 44u}, // xwe -> Latn
+ {0xB0180000u, 44u}, // yam -> Latn
+ {0xB8180000u, 44u}, // yao -> Latn
+ {0xBC180000u, 44u}, // yap -> Latn
+ {0xC8180000u, 44u}, // yas -> Latn
+ {0xCC180000u, 44u}, // yat -> Latn
+ {0xD4180000u, 44u}, // yav -> Latn
+ {0xE0180000u, 44u}, // yay -> Latn
+ {0xE4180000u, 44u}, // yaz -> Latn
+ {0x80380000u, 44u}, // yba -> Latn
+ {0x84380000u, 44u}, // ybb -> Latn
+ {0xE0380000u, 44u}, // yby -> Latn
+ {0xC4980000u, 44u}, // yer -> Latn
+ {0xC4D80000u, 44u}, // ygr -> Latn
+ {0xD8D80000u, 44u}, // ygw -> Latn
+ {0x79690000u, 30u}, // yi -> Hebr
+ {0xB9580000u, 44u}, // yko -> Latn
+ {0x91780000u, 44u}, // yle -> Latn
+ {0x99780000u, 44u}, // ylg -> Latn
+ {0xAD780000u, 44u}, // yll -> Latn
+ {0xAD980000u, 44u}, // yml -> Latn
+ {0x796F0000u, 44u}, // yo -> Latn
+ {0xB5D80000u, 44u}, // yon -> Latn
+ {0x86380000u, 44u}, // yrb -> Latn
+ {0x92380000u, 44u}, // yre -> Latn
+ {0xAE380000u, 44u}, // yrl -> Latn
+ {0xCA580000u, 44u}, // yss -> Latn
+ {0x82980000u, 44u}, // yua -> Latn
+ {0x92980000u, 28u}, // yue -> Hant
+ {0x9298434Eu, 27u}, // yue-CN -> Hans
+ {0xA6980000u, 44u}, // yuj -> Latn
+ {0xCE980000u, 44u}, // yut -> Latn
+ {0xDA980000u, 44u}, // yuw -> Latn
+ {0x7A610000u, 44u}, // za -> Latn
+ {0x98190000u, 44u}, // zag -> Latn
{0xA4790000u, 1u}, // zdj -> Arab
- {0x80990000u, 40u}, // zea -> Latn
- {0x9CD90000u, 78u}, // zgh -> Tfng
- {0x7A680000u, 24u}, // zh -> Hans
- {0x7A684155u, 25u}, // zh-AU -> Hant
- {0x7A68424Eu, 25u}, // zh-BN -> Hant
- {0x7A684742u, 25u}, // zh-GB -> Hant
- {0x7A684746u, 25u}, // zh-GF -> Hant
- {0x7A68484Bu, 25u}, // zh-HK -> Hant
- {0x7A684944u, 25u}, // zh-ID -> Hant
- {0x7A684D4Fu, 25u}, // zh-MO -> Hant
- {0x7A684D59u, 25u}, // zh-MY -> Hant
- {0x7A685041u, 25u}, // zh-PA -> Hant
- {0x7A685046u, 25u}, // zh-PF -> Hant
- {0x7A685048u, 25u}, // zh-PH -> Hant
- {0x7A685352u, 25u}, // zh-SR -> Hant
- {0x7A685448u, 25u}, // zh-TH -> Hant
- {0x7A685457u, 25u}, // zh-TW -> Hant
- {0x7A685553u, 25u}, // zh-US -> Hant
- {0x7A68564Eu, 25u}, // zh-VN -> Hant
- {0x81190000u, 40u}, // zia -> Latn
- {0xB1790000u, 40u}, // zlm -> Latn
- {0xA1990000u, 40u}, // zmi -> Latn
- {0x91B90000u, 40u}, // zne -> Latn
- {0x7A750000u, 40u}, // zu -> Latn
- {0x83390000u, 40u}, // zza -> Latn
+ {0x80990000u, 44u}, // zea -> Latn
+ {0x9CD90000u, 85u}, // zgh -> Tfng
+ {0x7A680000u, 27u}, // zh -> Hans
+ {0x7A684155u, 28u}, // zh-AU -> Hant
+ {0x7A68424Eu, 28u}, // zh-BN -> Hant
+ {0x7A684742u, 28u}, // zh-GB -> Hant
+ {0x7A684746u, 28u}, // zh-GF -> Hant
+ {0x7A68484Bu, 28u}, // zh-HK -> Hant
+ {0x7A684944u, 28u}, // zh-ID -> Hant
+ {0x7A684D4Fu, 28u}, // zh-MO -> Hant
+ {0x7A684D59u, 28u}, // zh-MY -> Hant
+ {0x7A685041u, 28u}, // zh-PA -> Hant
+ {0x7A685046u, 28u}, // zh-PF -> Hant
+ {0x7A685048u, 28u}, // zh-PH -> Hant
+ {0x7A685352u, 28u}, // zh-SR -> Hant
+ {0x7A685448u, 28u}, // zh-TH -> Hant
+ {0x7A685457u, 28u}, // zh-TW -> Hant
+ {0x7A685553u, 28u}, // zh-US -> Hant
+ {0x7A68564Eu, 28u}, // zh-VN -> Hant
+ {0xDCF90000u, 59u}, // zhx -> Nshu
+ {0x81190000u, 44u}, // zia -> Latn
+ {0xB1790000u, 44u}, // zlm -> Latn
+ {0xA1990000u, 44u}, // zmi -> Latn
+ {0x91B90000u, 44u}, // zne -> Latn
+ {0x7A750000u, 44u}, // zu -> Latn
+ {0x83390000u, 44u}, // zza -> Latn
});
std::unordered_set<uint64_t> REPRESENTATIVE_LOCALES({
@@ -1517,6 +1544,7 @@ std::unordered_set<uint64_t> REPRESENTATIVE_LOCALES({
0xB5014E474C61746ELLU, // bin_Latn_NG
0xA521494E44657661LLU, // bjj_Deva_IN
0xB52149444C61746ELLU, // bjn_Latn_ID
+ 0xCD21534E4C61746ELLU, // bjt_Latn_SN
0xB141434D4C61746ELLU, // bkm_Latn_CM
0xD14150484C61746ELLU, // bku_Latn_PH
0xCD61564E54617674LLU, // blt_Tavt_VN
@@ -1546,7 +1574,6 @@ std::unordered_set<uint64_t> REPRESENTATIVE_LOCALES({
0x93214D4C4C61746ELLU, // bze_Latn_ML
0x636145534C61746ELLU, // ca_Latn_ES
0x9C424E474C61746ELLU, // cch_Latn_NG
- 0xBC42494E42656E67LLU, // ccp_Beng_IN
0xBC42424443616B6DLLU, // ccp_Cakm_BD
0x636552554379726CLLU, // ce_Cyrl_RU
0x848250484C61746ELLU, // ceb_Latn_PH
@@ -1560,10 +1587,12 @@ std::unordered_set<uint64_t> REPRESENTATIVE_LOCALES({
0x81224B4841726162LLU, // cja_Arab_KH
0xB122564E4368616DLLU, // cjm_Cham_VN
0x8542495141726162LLU, // ckb_Arab_IQ
+ 0x99824D4E536F796FLLU, // cmg_Soyo_MN
0x636F46524C61746ELLU, // co_Latn_FR
0xBDC24547436F7074LLU, // cop_Copt_EG
0xC9E250484C61746ELLU, // cps_Latn_PH
0x6372434143616E73LLU, // cr_Cans_CA
+ 0x9E2255414379726CLLU, // crh_Cyrl_UA
0xA622434143616E73LLU, // crj_Cans_CA
0xAA22434143616E73LLU, // crk_Cans_CA
0xAE22434143616E73LLU, // crl_Cans_CA
@@ -1610,6 +1639,7 @@ std::unordered_set<uint64_t> REPRESENTATIVE_LOCALES({
0x657345534C61746ELLU, // es_Latn_ES
0x65734D584C61746ELLU, // es_Latn_MX
0x657355534C61746ELLU, // es_Latn_US
+ 0x9A44494E476F6E6DLLU, // esg_Gonm_IN
0xD24455534C61746ELLU, // esu_Latn_US
0x657445454C61746ELLU, // et_Latn_EE
0xCE6449544974616CLLU, // ett_Ital_IT
@@ -1700,10 +1730,10 @@ std::unordered_set<uint64_t> REPRESENTATIVE_LOCALES({
0x687548554C61746ELLU, // hu_Latn_HU
0x6879414D41726D6ELLU, // hy_Armn_AM
0x687A4E414C61746ELLU, // hz_Latn_NA
- 0x696146524C61746ELLU, // ia_Latn_FR
0x80284D594C61746ELLU, // iba_Latn_MY
0x84284E474C61746ELLU, // ibb_Latn_NG
0x696449444C61746ELLU, // id_Latn_ID
+ 0x90A854474C61746ELLU, // ife_Latn_TG
0x69674E474C61746ELLU, // ig_Latn_NG
0x6969434E59696969LLU, // ii_Yiii_CN
0x696B55534C61746ELLU, // ik_Latn_US
@@ -1764,6 +1794,7 @@ std::unordered_set<uint64_t> REPRESENTATIVE_LOCALES({
0x6B6D4B484B686D72LLU, // km_Khmr_KH
0x858A414F4C61746ELLU, // kmb_Latn_AO
0x6B6E494E4B6E6461LLU, // kn_Knda_IN
+ 0x95AA47574C61746ELLU, // knf_Latn_GW
0x6B6F4B524B6F7265LLU, // ko_Kore_KR
0xA1CA52554379726CLLU, // koi_Cyrl_RU
0xA9CA494E44657661LLU, // kok_Deva_IN
@@ -1854,6 +1885,7 @@ std::unordered_set<uint64_t> REPRESENTATIVE_LOCALES({
0x6D694E5A4C61746ELLU, // mi_Latn_NZ
0xB50C49444C61746ELLU, // min_Latn_ID
0xC90C495148617472LLU, // mis_Hatr_IQ
+ 0xC90C4E474D656466LLU, // mis_Medf_NG
0x6D6B4D4B4379726CLLU, // mk_Cyrl_MK
0x6D6C494E4D6C796DLLU, // ml_Mlym_IN
0xC96C53444C61746ELLU, // mls_Latn_SD
@@ -1877,6 +1909,7 @@ std::unordered_set<uint64_t> REPRESENTATIVE_LOCALES({
0xAACC4D4C4C61746ELLU, // mwk_Latn_ML
0xC6CC494E44657661LLU, // mwr_Deva_IN
0xD6CC49444C61746ELLU, // mwv_Latn_ID
+ 0xDACC5553486D6E70LLU, // mww_Hmnp_US
0x8AEC5A574C61746ELLU, // mxc_Latn_ZW
0x6D794D4D4D796D72LLU, // my_Mymr_MM
0xD70C52554379726CLLU, // myv_Cyrl_RU
@@ -1905,6 +1938,7 @@ std::unordered_set<uint64_t> REPRESENTATIVE_LOCALES({
0x998D434D4C61746ELLU, // nmg_Latn_CM
0x6E6E4E4F4C61746ELLU, // nn_Latn_NO
0x9DAD434D4C61746ELLU, // nnh_Latn_CM
+ 0xBDAD494E5763686FLLU, // nnp_Wcho_IN
0x6E6F4E4F4C61746ELLU, // no_Latn_NO
0x8DCD54484C616E61LLU, // nod_Lana_TH
0x91CD494E44657661LLU, // noe_Deva_IN
@@ -1959,6 +1993,7 @@ std::unordered_set<uint64_t> REPRESENTATIVE_LOCALES({
0x945152454C61746ELLU, // rcf_Latn_RE
0xA49149444C61746ELLU, // rej_Latn_ID
0xB4D149544C61746ELLU, // rgn_Latn_IT
+ 0x98F14D4D41726162LLU, // rhg_Arab_MM
0x8111494E4C61746ELLU, // ria_Latn_IN
0x95114D4154666E67LLU, // rif_Tfng_MA
0xC9314E5044657661LLU, // rjs_Deva_NP
@@ -1986,6 +2021,7 @@ std::unordered_set<uint64_t> REPRESENTATIVE_LOCALES({
0xC0124B454C61746ELLU, // saq_Latn_KE
0xC81249444C61746ELLU, // sas_Latn_ID
0xCC12494E4C61746ELLU, // sat_Latn_IN
+ 0xD412534E4C61746ELLU, // sav_Latn_SN
0xE412494E53617572LLU, // saz_Saur_IN
0xBC32545A4C61746ELLU, // sbp_Latn_TZ
0x736349544C61746ELLU, // sc_Latn_IT
@@ -2025,6 +2061,7 @@ std::unordered_set<uint64_t> REPRESENTATIVE_LOCALES({
0x736E5A574C61746ELLU, // sn_Latn_ZW
0xA9B24D4C4C61746ELLU, // snk_Latn_ML
0x736F534F4C61746ELLU, // so_Latn_SO
+ 0x99D2555A536F6764LLU, // sog_Sogd_UZ
0xD1D2544854686169LLU, // sou_Thai_TH
0x7371414C4C61746ELLU, // sq_Latn_AL
0x737252534379726CLLU, // sr_Cyrl_RS
@@ -2135,6 +2172,7 @@ std::unordered_set<uint64_t> REPRESENTATIVE_LOCALES({
0xC97657464C61746ELLU, // wls_Latn_WF
0xA1B64B4D41726162LLU, // wni_Arab_KM
0x776F534E4C61746ELLU, // wo_Latn_SN
+ 0x9A56494E476F6E67LLU, // wsg_Gong_IN
0xB276494E44657661LLU, // wtm_Deva_IN
0xD296434E48616E73LLU, // wuu_Hans_CN
0xD41742524C61746ELLU, // xav_Latn_BR
@@ -2169,6 +2207,7 @@ std::unordered_set<uint64_t> REPRESENTATIVE_LOCALES({
0x7A68545748616E62LLU, // zh_Hanb_TW
0x7A68434E48616E73LLU, // zh_Hans_CN
0x7A68545748616E74LLU, // zh_Hant_TW
+ 0xDCF9434E4E736875LLU, // zhx_Nshu_CN
0xB17954474C61746ELLU, // zlm_Latn_TG
0xA1994D594C61746ELLU, // zmi_Latn_MY
0x7A755A414C61746ELLU, // zu_Latn_ZA
@@ -2194,7 +2233,7 @@ const std::unordered_map<uint32_t, uint32_t> LATN_PARENTS({
{0x656E4154u, 0x656E80A1u}, // en-AT -> en-150
{0x656E4155u, 0x656E8400u}, // en-AU -> en-001
{0x656E4242u, 0x656E8400u}, // en-BB -> en-001
- {0x656E4245u, 0x656E8400u}, // en-BE -> en-001
+ {0x656E4245u, 0x656E80A1u}, // en-BE -> en-150
{0x656E424Du, 0x656E8400u}, // en-BM -> en-001
{0x656E4253u, 0x656E8400u}, // en-BS -> en-001
{0x656E4257u, 0x656E8400u}, // en-BW -> en-001
@@ -2285,6 +2324,7 @@ const std::unordered_map<uint32_t, uint32_t> LATN_PARENTS({
{0x65734152u, 0x6573A424u}, // es-AR -> es-419
{0x6573424Fu, 0x6573A424u}, // es-BO -> es-419
{0x65734252u, 0x6573A424u}, // es-BR -> es-419
+ {0x6573425Au, 0x6573A424u}, // es-BZ -> es-419
{0x6573434Cu, 0x6573A424u}, // es-CL -> es-419
{0x6573434Fu, 0x6573A424u}, // es-CO -> es-419
{0x65734352u, 0x6573A424u}, // es-CR -> es-419
@@ -2315,6 +2355,10 @@ const std::unordered_map<uint32_t, uint32_t> LATN_PARENTS({
{0x7074544Cu, 0x70745054u}, // pt-TL -> pt-PT
});
+const std::unordered_map<uint32_t, uint32_t> ___B_PARENTS({
+ {0x61725842u, 0x61729420u}, // ar-XB -> ar-015
+});
+
const struct {
const char script[4];
const std::unordered_map<uint32_t, uint32_t>* map;
@@ -2322,6 +2366,7 @@ const struct {
{{'A', 'r', 'a', 'b'}, &ARAB_PARENTS},
{{'H', 'a', 'n', 't'}, &HANT_PARENTS},
{{'L', 'a', 't', 'n'}, &LATN_PARENTS},
+ {{'~', '~', '~', 'B'}, &___B_PARENTS},
};
const size_t MAX_PARENT_DEPTH = 3;
diff --git a/libs/hwui/Android.bp b/libs/hwui/Android.bp
index f670cf97e0c2..d945fc49ec88 100644
--- a/libs/hwui/Android.bp
+++ b/libs/hwui/Android.bp
@@ -176,6 +176,7 @@ cc_defaults {
"hwui/AnimatedImageThread.cpp",
"hwui/Bitmap.cpp",
"hwui/Canvas.cpp",
+ "hwui/ImageDecoder.cpp",
"hwui/MinikinSkia.cpp",
"hwui/MinikinUtils.cpp",
"hwui/PaintImpl.cpp",
diff --git a/libs/hwui/hwui/Bitmap.cpp b/libs/hwui/hwui/Bitmap.cpp
index 2ba6fbe76de1..f4149b9b4d7d 100644
--- a/libs/hwui/hwui/Bitmap.cpp
+++ b/libs/hwui/hwui/Bitmap.cpp
@@ -44,9 +44,7 @@
namespace android {
-// returns true if rowBytes * height can be represented by a positive int32_t value
-// and places that value in size.
-static bool computeAllocationSize(size_t rowBytes, int height, size_t* size) {
+bool Bitmap::computeAllocationSize(size_t rowBytes, int height, size_t* size) {
return 0 <= height && height <= std::numeric_limits<size_t>::max() &&
!__builtin_mul_overflow(rowBytes, (size_t)height, size) &&
*size <= std::numeric_limits<int32_t>::max();
@@ -66,7 +64,7 @@ static sk_sp<Bitmap> allocateBitmap(SkBitmap* bitmap, AllocPixelRef alloc) {
// we must respect the rowBytes value already set on the bitmap instead of
// attempting to compute our own.
const size_t rowBytes = bitmap->rowBytes();
- if (!computeAllocationSize(rowBytes, bitmap->height(), &size)) {
+ if (!Bitmap::computeAllocationSize(rowBytes, bitmap->height(), &size)) {
return nullptr;
}
diff --git a/libs/hwui/hwui/Bitmap.h b/libs/hwui/hwui/Bitmap.h
index 00733c6b245b..1cda0465ae64 100644
--- a/libs/hwui/hwui/Bitmap.h
+++ b/libs/hwui/hwui/Bitmap.h
@@ -138,6 +138,10 @@ public:
return mPalette;
}
+ // returns true if rowBytes * height can be represented by a positive int32_t value
+ // and places that value in size.
+ static bool computeAllocationSize(size_t rowBytes, int height, size_t* size);
+
private:
static sk_sp<Bitmap> allocateAshmemBitmap(size_t size, const SkImageInfo& i, size_t rowBytes);
static sk_sp<Bitmap> allocateHeapBitmap(size_t size, const SkImageInfo& i, size_t rowBytes);
diff --git a/libs/hwui/hwui/ImageDecoder.cpp b/libs/hwui/hwui/ImageDecoder.cpp
new file mode 100644
index 000000000000..4f2027d978a1
--- /dev/null
+++ b/libs/hwui/hwui/ImageDecoder.cpp
@@ -0,0 +1,213 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#include "ImageDecoder.h"
+
+#include <hwui/Bitmap.h>
+
+#include <SkAndroidCodec.h>
+#include <SkCanvas.h>
+#include <SkPaint.h>
+
+using namespace android;
+
+ImageDecoder::ImageDecoder(std::unique_ptr<SkAndroidCodec> codec, sk_sp<SkPngChunkReader> peeker)
+ : mCodec(std::move(codec))
+ , mPeeker(std::move(peeker))
+ , mTargetSize(mCodec->getInfo().dimensions())
+ , mDecodeSize(mTargetSize)
+ , mOutColorType(mCodec->computeOutputColorType(kN32_SkColorType))
+ , mOutAlphaType(mCodec->getInfo().isOpaque() ?
+ kOpaque_SkAlphaType : kPremul_SkAlphaType)
+ , mOutColorSpace(mCodec->getInfo().refColorSpace())
+ , mSampleSize(1)
+{
+}
+
+bool ImageDecoder::setTargetSize(int width, int height) {
+ if (width <= 0 || height <= 0) {
+ return false;
+ }
+
+ auto info = SkImageInfo::Make(width, height, mOutColorType, mOutAlphaType);
+ size_t rowBytes = info.minRowBytes();
+ if (rowBytes == 0) {
+ // This would have overflowed.
+ return false;
+ }
+
+ size_t pixelMemorySize;
+ if (!Bitmap::computeAllocationSize(rowBytes, height, &pixelMemorySize)) {
+ return false;
+ }
+
+ if (mCropRect) {
+ if (mCropRect->right() > width || mCropRect->bottom() > height) {
+ return false;
+ }
+ }
+
+ SkISize targetSize = { width, height }, decodeSize = targetSize;
+ int sampleSize = mCodec->computeSampleSize(&decodeSize);
+
+ if (decodeSize != targetSize && mOutAlphaType == kUnpremul_SkAlphaType
+ && !mCodec->getInfo().isOpaque()) {
+ return false;
+ }
+
+ mTargetSize = targetSize;
+ mDecodeSize = decodeSize;
+ mSampleSize = sampleSize;
+ return true;
+}
+
+bool ImageDecoder::setCropRect(const SkIRect* crop) {
+ if (!crop) {
+ mCropRect.reset();
+ return true;
+ }
+
+ if (crop->left() >= crop->right() || crop->top() >= crop->bottom()) {
+ return false;
+ }
+
+ const auto& size = mTargetSize;
+ if (crop->left() < 0 || crop->top() < 0
+ || crop->right() > size.width() || crop->bottom() > size.height()) {
+ return false;
+ }
+
+ mCropRect.emplace(*crop);
+ return true;
+}
+
+bool ImageDecoder::setOutColorType(SkColorType colorType) {
+ switch (colorType) {
+ case kRGB_565_SkColorType:
+ if (!opaque()) {
+ return false;
+ }
+ break;
+ case kGray_8_SkColorType:
+ if (!gray()) {
+ return false;
+ }
+ mOutColorSpace = nullptr;
+ break;
+ case kN32_SkColorType:
+ break;
+ case kRGBA_F16_SkColorType:
+ break;
+ default:
+ return false;
+ }
+
+ mOutColorType = colorType;
+ return true;
+}
+
+bool ImageDecoder::setOutAlphaType(SkAlphaType alpha) {
+ switch (alpha) {
+ case kOpaque_SkAlphaType:
+ return opaque();
+ case kPremul_SkAlphaType:
+ if (opaque()) {
+ // Opaque can be treated as premul.
+ return true;
+ }
+ break;
+ case kUnpremul_SkAlphaType:
+ if (opaque()) {
+ // Opaque can be treated as unpremul.
+ return true;
+ }
+ if (mDecodeSize != mTargetSize) {
+ return false;
+ }
+ break;
+ default:
+ return false;
+ }
+ mOutAlphaType = alpha;
+ return true;
+}
+
+void ImageDecoder::setOutColorSpace(sk_sp<SkColorSpace> colorSpace) {
+ mOutColorSpace = std::move(colorSpace);
+}
+
+SkImageInfo ImageDecoder::getOutputInfo() const {
+ SkISize size = mCropRect ? mCropRect->size() : mTargetSize;
+ return SkImageInfo::Make(size, mOutColorType, mOutAlphaType, mOutColorSpace);
+}
+
+bool ImageDecoder::opaque() const {
+ return mOutAlphaType == kOpaque_SkAlphaType;
+}
+
+bool ImageDecoder::gray() const {
+ return mCodec->getInfo().colorType() == kGray_8_SkColorType;
+}
+
+SkCodec::Result ImageDecoder::decode(void* pixels, size_t rowBytes) {
+ void* decodePixels = pixels;
+ size_t decodeRowBytes = rowBytes;
+ auto decodeInfo = SkImageInfo::Make(mDecodeSize, mOutColorType, mOutAlphaType, mOutColorSpace);
+ // Used if we need a temporary before scaling or subsetting.
+ // FIXME: Use scanline decoding on only a couple lines to save memory. b/70709380.
+ SkBitmap tmp;
+ const bool scale = mDecodeSize != mTargetSize;
+ if (scale || mCropRect) {
+ if (!tmp.setInfo(decodeInfo)) {
+ return SkCodec::kInternalError;
+ }
+ if (!Bitmap::allocateHeapBitmap(&tmp)) {
+ return SkCodec::kInternalError;
+ }
+ decodePixels = tmp.getPixels();
+ decodeRowBytes = tmp.rowBytes();
+ }
+
+ SkAndroidCodec::AndroidOptions options;
+ options.fSampleSize = mSampleSize;
+ auto result = mCodec->getAndroidPixels(decodeInfo, decodePixels, decodeRowBytes, &options);
+
+ if (scale || mCropRect) {
+ SkBitmap scaledBm;
+ if (!scaledBm.installPixels(getOutputInfo(), pixels, rowBytes)) {
+ return SkCodec::kInternalError;
+ }
+
+ SkPaint paint;
+ paint.setBlendMode(SkBlendMode::kSrc);
+ paint.setFilterQuality(kLow_SkFilterQuality); // bilinear filtering
+
+ SkCanvas canvas(scaledBm, SkCanvas::ColorBehavior::kLegacy);
+ if (mCropRect) {
+ canvas.translate(-mCropRect->fLeft, -mCropRect->fTop);
+ }
+ if (scale) {
+ float scaleX = (float) mTargetSize.width() / mDecodeSize.width();
+ float scaleY = (float) mTargetSize.height() / mDecodeSize.height();
+ canvas.scale(scaleX, scaleY);
+ }
+
+ canvas.drawBitmap(tmp, 0.0f, 0.0f, &paint);
+ }
+
+ return result;
+}
+
diff --git a/libs/hwui/hwui/ImageDecoder.h b/libs/hwui/hwui/ImageDecoder.h
new file mode 100644
index 000000000000..b956f4a77793
--- /dev/null
+++ b/libs/hwui/hwui/ImageDecoder.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+#pragma once
+
+#include <SkCodec.h>
+#include <SkImageInfo.h>
+#include <SkPngChunkReader.h>
+#include <SkRect.h>
+#include <SkSize.h>
+#include <cutils/compiler.h>
+
+#include <optional>
+
+class SkAndroidCodec;
+
+namespace android {
+
+class ANDROID_API ImageDecoder {
+public:
+ std::unique_ptr<SkAndroidCodec> mCodec;
+ sk_sp<SkPngChunkReader> mPeeker;
+
+ ImageDecoder(std::unique_ptr<SkAndroidCodec> codec,
+ sk_sp<SkPngChunkReader> peeker = nullptr);
+
+ bool setTargetSize(int width, int height);
+ bool setCropRect(const SkIRect*);
+
+ bool setOutColorType(SkColorType outColorType);
+
+ bool setOutAlphaType(SkAlphaType outAlphaType);
+
+ void setOutColorSpace(sk_sp<SkColorSpace> cs);
+
+ // The size is the final size after scaling and cropping.
+ SkImageInfo getOutputInfo() const;
+ SkColorType getOutColorType() const { return mOutColorType; }
+ SkAlphaType getOutAlphaType() const { return mOutAlphaType; }
+
+ bool opaque() const;
+ bool gray() const;
+
+ SkCodec::Result decode(void* pixels, size_t rowBytes);
+
+private:
+ SkISize mTargetSize;
+ SkISize mDecodeSize;
+ SkColorType mOutColorType;
+ SkAlphaType mOutAlphaType;
+ sk_sp<SkColorSpace> mOutColorSpace;
+ int mSampleSize;
+ std::optional<SkIRect> mCropRect;
+
+ ImageDecoder(const ImageDecoder&) = delete;
+ ImageDecoder& operator=(const ImageDecoder&) = delete;
+};
+
+} // namespace android
diff --git a/libs/hwui/pipeline/skia/RenderNodeDrawable.cpp b/libs/hwui/pipeline/skia/RenderNodeDrawable.cpp
index 9c8463417e0a..00ceb2d84f9e 100644
--- a/libs/hwui/pipeline/skia/RenderNodeDrawable.cpp
+++ b/libs/hwui/pipeline/skia/RenderNodeDrawable.cpp
@@ -41,7 +41,7 @@ RenderNodeDrawable::~RenderNodeDrawable() {
void RenderNodeDrawable::drawBackwardsProjectedNodes(SkCanvas* canvas,
const SkiaDisplayList& displayList,
- int nestLevel) {
+ int nestLevel) const {
LOG_ALWAYS_FATAL_IF(0 == nestLevel && !displayList.mProjectionReceiver);
for (auto& child : displayList.mChildNodes) {
const RenderProperties& childProperties = child.getNodeProperties();
@@ -132,7 +132,7 @@ private:
RenderNode& mNode;
};
-void RenderNodeDrawable::forceDraw(SkCanvas* canvas) {
+void RenderNodeDrawable::forceDraw(SkCanvas* canvas) const {
RenderNode* renderNode = mRenderNode.get();
MarkDraw _marker{*canvas, *renderNode};
@@ -230,7 +230,14 @@ void RenderNodeDrawable::drawContent(SkCanvas* canvas) const {
// we need to restrict the portion of the surface drawn to the size of the renderNode.
SkASSERT(renderNode->getLayerSurface()->width() >= bounds.width());
SkASSERT(renderNode->getLayerSurface()->height() >= bounds.height());
- canvas->drawImageRect(renderNode->getLayerSurface()->makeImageSnapshot().get(), bounds,
+
+ // If SKP recording is active save an annotation that indicates this drawImageRect
+ // could also be rendered with the commands saved at ID associated with this node.
+ if (CC_UNLIKELY(Properties::skpCaptureEnabled)) {
+ canvas->drawAnnotation(bounds, String8::format(
+ "SurfaceID|%" PRId64, renderNode->uniqueId()).c_str(), nullptr);
+ }
+ canvas->drawImageRect(renderNode->getLayerSurface()->makeImageSnapshot(), bounds,
bounds, &paint);
if (!renderNode->getSkiaLayer()->hasRenderedSinceRepaint) {
diff --git a/libs/hwui/pipeline/skia/RenderNodeDrawable.h b/libs/hwui/pipeline/skia/RenderNodeDrawable.h
index 6ba8e599818c..6c390c3fce24 100644
--- a/libs/hwui/pipeline/skia/RenderNodeDrawable.h
+++ b/libs/hwui/pipeline/skia/RenderNodeDrawable.h
@@ -58,7 +58,7 @@ public:
* projection receiver then all projected children (excluding direct children) will be drawn
* last. Any projected node not matching those requirements will not be drawn by this function.
*/
- void forceDraw(SkCanvas* canvas);
+ void forceDraw(SkCanvas* canvas) const;
/**
* Returns readonly render properties for this render node.
@@ -113,7 +113,7 @@ private:
* @param nestLevel should be always 0. Used to track how far we are from the receiver.
*/
void drawBackwardsProjectedNodes(SkCanvas* canvas, const SkiaDisplayList& displayList,
- int nestLevel = 0);
+ int nestLevel = 0) const;
/**
* Applies the rendering properties of a view onto a SkCanvas.
diff --git a/libs/hwui/pipeline/skia/SkiaPipeline.cpp b/libs/hwui/pipeline/skia/SkiaPipeline.cpp
index 06479776fc73..11dc013af6bc 100644
--- a/libs/hwui/pipeline/skia/SkiaPipeline.cpp
+++ b/libs/hwui/pipeline/skia/SkiaPipeline.cpp
@@ -26,11 +26,11 @@
#include <SkPictureRecorder.h>
#include <SkSerialProcs.h>
#include "LightingInfo.h"
-#include "TreeInfo.h"
#include "VectorDrawable.h"
#include "thread/CommonPool.h"
#include "tools/SkSharingProc.h"
#include "utils/TraceUtils.h"
+#include "utils/String8.h"
#include <unistd.h>
@@ -90,58 +90,61 @@ void SkiaPipeline::renderLayersImpl(const LayerUpdateQueue& layers, bool opaque)
// only schedule repaint if node still on layer - possible it may have been
// removed during a dropped frame, but layers may still remain scheduled so
// as not to lose info on what portion is damaged
- if (CC_LIKELY(layerNode->getLayerSurface() != nullptr)) {
- SkASSERT(layerNode->getLayerSurface());
- SkiaDisplayList* displayList = (SkiaDisplayList*)layerNode->getDisplayList();
- if (!displayList || displayList->isEmpty()) {
- ALOGE("%p drawLayers(%s) : missing drawable", layerNode, layerNode->getName());
- return;
- }
+ if (CC_UNLIKELY(layerNode->getLayerSurface() == nullptr)) {
+ continue;
+ }
+ SkASSERT(layerNode->getLayerSurface());
+ SkiaDisplayList* displayList = (SkiaDisplayList*)layerNode->getDisplayList();
+ if (!displayList || displayList->isEmpty()) {
+ ALOGE("%p drawLayers(%s) : missing drawable", layerNode, layerNode->getName());
+ return;
+ }
- const Rect& layerDamage = layers.entries()[i].damage;
+ const Rect& layerDamage = layers.entries()[i].damage;
- SkCanvas* layerCanvas = layerNode->getLayerSurface()->getCanvas();
+ SkCanvas* layerCanvas = layerNode->getLayerSurface()->getCanvas();
- int saveCount = layerCanvas->save();
- SkASSERT(saveCount == 1);
+ int saveCount = layerCanvas->save();
+ SkASSERT(saveCount == 1);
- layerCanvas->androidFramework_setDeviceClipRestriction(layerDamage.toSkIRect());
+ layerCanvas->androidFramework_setDeviceClipRestriction(layerDamage.toSkIRect());
- // TODO: put localized light center calculation and storage to a drawable related code.
- // It does not seem right to store something localized in a global state
- const Vector3 savedLightCenter(LightingInfo::getLightCenterRaw());
- Vector3 transformedLightCenter(savedLightCenter);
- // map current light center into RenderNode's coordinate space
- layerNode->getSkiaLayer()->inverseTransformInWindow.mapPoint3d(transformedLightCenter);
- LightingInfo::setLightCenterRaw(transformedLightCenter);
+ // TODO: put localized light center calculation and storage to a drawable related code.
+ // It does not seem right to store something localized in a global state
+ // fix here and in recordLayers
+ const Vector3 savedLightCenter(LightingInfo::getLightCenterRaw());
+ Vector3 transformedLightCenter(savedLightCenter);
+ // map current light center into RenderNode's coordinate space
+ layerNode->getSkiaLayer()->inverseTransformInWindow.mapPoint3d(transformedLightCenter);
+ LightingInfo::setLightCenterRaw(transformedLightCenter);
- const RenderProperties& properties = layerNode->properties();
- const SkRect bounds = SkRect::MakeWH(properties.getWidth(), properties.getHeight());
- if (properties.getClipToBounds() && layerCanvas->quickReject(bounds)) {
- return;
- }
+ const RenderProperties& properties = layerNode->properties();
+ const SkRect bounds = SkRect::MakeWH(properties.getWidth(), properties.getHeight());
+ if (properties.getClipToBounds() && layerCanvas->quickReject(bounds)) {
+ return;
+ }
- ATRACE_FORMAT("drawLayer [%s] %.1f x %.1f", layerNode->getName(), bounds.width(),
- bounds.height());
-
- layerNode->getSkiaLayer()->hasRenderedSinceRepaint = false;
- layerCanvas->clear(SK_ColorTRANSPARENT);
-
- RenderNodeDrawable root(layerNode, layerCanvas, false);
- root.forceDraw(layerCanvas);
- layerCanvas->restoreToCount(saveCount);
- LightingInfo::setLightCenterRaw(savedLightCenter);
-
- // cache the current context so that we can defer flushing it until
- // either all the layers have been rendered or the context changes
- GrContext* currentContext = layerNode->getLayerSurface()->getCanvas()->getGrContext();
- if (cachedContext.get() != currentContext) {
- if (cachedContext.get()) {
- ATRACE_NAME("flush layers (context changed)");
- cachedContext->flush();
- }
- cachedContext.reset(SkSafeRef(currentContext));
+ ATRACE_FORMAT("drawLayer [%s] %.1f x %.1f", layerNode->getName(), bounds.width(),
+ bounds.height());
+
+ layerNode->getSkiaLayer()->hasRenderedSinceRepaint = false;
+ layerCanvas->clear(SK_ColorTRANSPARENT);
+
+ RenderNodeDrawable root(layerNode, layerCanvas, false);
+ root.forceDraw(layerCanvas);
+ layerCanvas->restoreToCount(saveCount);
+
+ LightingInfo::setLightCenterRaw(savedLightCenter);
+
+ // cache the current context so that we can defer flushing it until
+ // either all the layers have been rendered or the context changes
+ GrContext* currentContext = layerNode->getLayerSurface()->getCanvas()->getGrContext();
+ if (cachedContext.get() != currentContext) {
+ if (cachedContext.get()) {
+ ATRACE_NAME("flush layers (context changed)");
+ cachedContext->flush();
}
+ cachedContext.reset(SkSafeRef(currentContext));
}
}
@@ -275,12 +278,60 @@ bool SkiaPipeline::setupMultiFrameCapture() {
}
}
-SkCanvas* SkiaPipeline::tryCapture(SkSurface* surface) {
+// recurse through the rendernode's children, add any nodes which are layers to the queue.
+static void collectLayers(RenderNode* node, LayerUpdateQueue* layers) {
+ SkiaDisplayList* dl = (SkiaDisplayList*)node->getDisplayList();
+ if (dl) {
+ const auto& prop = node->properties();
+ if (node->hasLayer()) {
+ layers->enqueueLayerWithDamage(node, Rect(prop.getWidth(), prop.getHeight()));
+ }
+ // The way to recurse through rendernodes is to call this with a lambda.
+ dl->updateChildren([&](RenderNode* child) { collectLayers(child, layers); });
+ }
+}
+
+// record the provided layers to the provided canvas as self-contained skpictures.
+static void recordLayers(const LayerUpdateQueue& layers,
+ SkCanvas* mskpCanvas) {
+ const Vector3 savedLightCenter(LightingInfo::getLightCenterRaw());
+ // Record the commands to re-draw each dirty layer into an SkPicture
+ for (size_t i = 0; i < layers.entries().size(); i++) {
+ RenderNode* layerNode = layers.entries()[i].renderNode.get();
+ const Rect& layerDamage = layers.entries()[i].damage;
+ const RenderProperties& properties = layerNode->properties();
+
+ // Temporarily map current light center into RenderNode's coordinate space
+ Vector3 transformedLightCenter(savedLightCenter);
+ layerNode->getSkiaLayer()->inverseTransformInWindow.mapPoint3d(transformedLightCenter);
+ LightingInfo::setLightCenterRaw(transformedLightCenter);
+
+ SkPictureRecorder layerRec;
+ auto* recCanvas = layerRec.beginRecording(properties.getWidth(),
+ properties.getHeight());
+ // This is not recorded but still causes clipping.
+ recCanvas->androidFramework_setDeviceClipRestriction(layerDamage.toSkIRect());
+ RenderNodeDrawable root(layerNode, recCanvas, false);
+ root.forceDraw(recCanvas);
+ // Now write this picture into the SKP canvas with an annotation indicating what it is
+ mskpCanvas->drawAnnotation(layerDamage.toSkRect(), String8::format(
+ "OffscreenLayerDraw|%" PRId64, layerNode->uniqueId()).c_str(), nullptr);
+ mskpCanvas->drawPicture(layerRec.finishRecordingAsPicture());
+ }
+ LightingInfo::setLightCenterRaw(savedLightCenter);
+}
+
+SkCanvas* SkiaPipeline::tryCapture(SkSurface* surface, RenderNode* root,
+ const LayerUpdateQueue& dirtyLayers) {
if (CC_LIKELY(!Properties::skpCaptureEnabled)) {
return surface->getCanvas(); // Bail out early when capture is not turned on.
}
// Note that shouldStartNewFileCapture tells us if this is the *first* frame of a capture.
+ bool firstFrameOfAnim = false;
if (shouldStartNewFileCapture() && mCaptureMode == CaptureMode::MultiFrameSKP) {
+ // set a reminder to record every layer near the end of this method, after we have set up
+ // the nway canvas.
+ firstFrameOfAnim = true;
if (!setupMultiFrameCapture()) {
return surface->getCanvas();
}
@@ -309,6 +360,20 @@ SkCanvas* SkiaPipeline::tryCapture(SkSurface* surface) {
mNwayCanvas = std::make_unique<SkNWayCanvas>(surface->width(), surface->height());
mNwayCanvas->addCanvas(surface->getCanvas());
mNwayCanvas->addCanvas(pictureCanvas);
+
+ if (firstFrameOfAnim) {
+ // On the first frame of any mskp capture we want to record any layers that are needed in
+ // frame but may have been rendered offscreen before recording began.
+ // We do not maintain a list of all layers, since it isn't needed outside this rare,
+ // recording use case. Traverse the tree to find them and put them in this LayerUpdateQueue.
+ LayerUpdateQueue luq;
+ collectLayers(root, &luq);
+ recordLayers(luq, mNwayCanvas.get());
+ } else {
+ // on non-first frames, we record any normal layer draws (dirty regions)
+ recordLayers(dirtyLayers, mNwayCanvas.get());
+ }
+
return mNwayCanvas.get();
}
@@ -359,13 +424,13 @@ void SkiaPipeline::renderFrame(const LayerUpdateQueue& layers, const SkRect& cli
Properties::skpCaptureEnabled = true;
}
+ // Initialize the canvas for the current frame, that might be a recording canvas if SKP
+ // capture is enabled.
+ SkCanvas* canvas = tryCapture(surface.get(), nodes[0].get(), layers);
+
// draw all layers up front
renderLayersImpl(layers, opaque);
- // initialize the canvas for the current frame, that might be a recording canvas if SKP
- // capture is enabled.
- SkCanvas* canvas = tryCapture(surface.get());
-
renderFrameImpl(clip, nodes, opaque, contentDrawBounds, canvas, preTransform);
endCapture(surface.get());
diff --git a/libs/hwui/pipeline/skia/SkiaPipeline.h b/libs/hwui/pipeline/skia/SkiaPipeline.h
index 7d575ad01936..af8414de4bc1 100644
--- a/libs/hwui/pipeline/skia/SkiaPipeline.h
+++ b/libs/hwui/pipeline/skia/SkiaPipeline.h
@@ -45,6 +45,8 @@ public:
void renderLayers(const LightGeometry& lightGeometry, LayerUpdateQueue* layerUpdateQueue,
bool opaque, const LightInfo& lightInfo) override;
+ // If the given node didn't have a layer surface, or had one of the wrong size, this method
+ // creates a new one and returns true. Otherwise does nothing and returns false.
bool createOrUpdateLayer(RenderNode* node, const DamageAccumulator& damageAccumulator,
ErrorHandler* errorHandler) override;
@@ -92,7 +94,7 @@ private:
// Called every frame. Normally returns early with screen canvas.
// But when capture is enabled, returns an nwaycanvas where commands are also recorded.
- SkCanvas* tryCapture(SkSurface* surface);
+ SkCanvas* tryCapture(SkSurface* surface, RenderNode* root, const LayerUpdateQueue& dirtyLayers);
// Called at the end of every frame, closes the recording if necessary.
void endCapture(SkSurface* surface);
// Determine if a new file-based capture should be started.
diff --git a/libs/services/Android.bp b/libs/services/Android.bp
index b0fad57dfd29..901ffaa59cd1 100644
--- a/libs/services/Android.bp
+++ b/libs/services/Android.bp
@@ -22,17 +22,16 @@ cc_library_shared {
"src/os/DropBoxManager.cpp",
"src/os/StatsDimensionsValue.cpp",
"src/os/StatsLogEventWrapper.cpp",
- "src/util/StatsEvent.cpp",
],
shared_libs: [
"libbinder",
- "liblog",
"libcutils",
+ "liblog",
"libutils",
],
header_libs: [
- "libbase_headers",
+ "libbase_headers",
],
aidl: {
include_dirs: ["frameworks/base/core/java/"],
diff --git a/libs/services/src/util/StatsEvent.cpp b/libs/services/src/util/StatsEvent.cpp
deleted file mode 100644
index 8b8579167b00..000000000000
--- a/libs/services/src/util/StatsEvent.cpp
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2019 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.
- */
-#include <android/util/StatsEvent.h>
-
-#include <binder/Parcel.h>
-#include <binder/Parcelable.h>
-#include <binder/Status.h>
-#include <vector>
-
-using android::Parcel;
-using android::Parcelable;
-using android::status_t;
-using std::vector;
-
-namespace android {
-namespace util {
-
-StatsEvent::StatsEvent(){};
-
-status_t StatsEvent::writeToParcel(Parcel* out) const {
- // Implement me if desired. We don't currently use this.
- ALOGE("Cannot do c++ StatsEvent.writeToParcel(); it is not implemented.");
- (void)out; // To prevent compile error of unused parameter 'out'
- return UNKNOWN_ERROR;
-};
-
-status_t StatsEvent::readFromParcel(const Parcel* in) {
- status_t res = OK;
- if (in == NULL) {
- ALOGE("statsd received parcel argument was NULL.");
- return BAD_VALUE;
- }
- if ((res = in->readInt32(&mAtomTag)) != OK) {
- ALOGE("statsd could not read atom tag from parcel");
- return res;
- }
- if ((res = in->readByteVector(&mBuffer)) != OK) {
- ALOGE("statsd could not read buffer from parcel");
- return res;
- }
- return NO_ERROR;
-};
-
-} // Namespace util
-} // Namespace android
diff --git a/location/java/android/location/Country.java b/location/java/android/location/Country.java
index f3c2a1684cda..8c40338e80fc 100644
--- a/location/java/android/location/Country.java
+++ b/location/java/android/location/Country.java
@@ -16,7 +16,7 @@
package android.location;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
diff --git a/location/java/android/location/CountryDetector.java b/location/java/android/location/CountryDetector.java
index ae139499eeb2..e344b820ca2a 100644
--- a/location/java/android/location/CountryDetector.java
+++ b/location/java/android/location/CountryDetector.java
@@ -16,10 +16,8 @@
package android.location;
-import java.util.HashMap;
-
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
@@ -27,6 +25,8 @@ import android.os.Looper;
import android.os.RemoteException;
import android.util.Log;
+import java.util.HashMap;
+
/**
* This class provides access to the system country detector service. This
* service allows applications to obtain the country that the user is in.
diff --git a/location/java/android/location/CountryListener.java b/location/java/android/location/CountryListener.java
index 70a83c5acdd9..eb67205f4de9 100644
--- a/location/java/android/location/CountryListener.java
+++ b/location/java/android/location/CountryListener.java
@@ -16,7 +16,7 @@
package android.location;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/**
* The listener for receiving the notification when the country is detected or
diff --git a/location/java/android/location/GeocoderParams.java b/location/java/android/location/GeocoderParams.java
index 45d92ee7cc34..1c6e9b6e1836 100644
--- a/location/java/android/location/GeocoderParams.java
+++ b/location/java/android/location/GeocoderParams.java
@@ -16,7 +16,7 @@
package android.location;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/location/java/android/location/Geofence.java b/location/java/android/location/Geofence.java
index 9570b26452e4..af57bfd30984 100644
--- a/location/java/android/location/Geofence.java
+++ b/location/java/android/location/Geofence.java
@@ -16,7 +16,7 @@
package android.location;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/location/java/android/location/Location.java b/location/java/android/location/Location.java
index db48ee7f2cf9..7a12cee899d8 100644
--- a/location/java/android/location/Location.java
+++ b/location/java/android/location/Location.java
@@ -19,7 +19,7 @@ package android.location;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
diff --git a/location/java/android/location/LocationManager.java b/location/java/android/location/LocationManager.java
index 1f8c1d5352b0..687535c3304b 100644
--- a/location/java/android/location/LocationManager.java
+++ b/location/java/android/location/LocationManager.java
@@ -31,9 +31,9 @@ import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.AlarmManager;
import android.app.PendingIntent;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Binder;
@@ -125,6 +125,7 @@ public class LocationManager {
*
* @hide
*/
+ @TestApi
public static final String FUSED_PROVIDER = "fused";
/**
@@ -1837,12 +1838,9 @@ public class LocationManager {
@Deprecated
@RequiresPermission(ACCESS_FINE_LOCATION)
public @Nullable GpsStatus getGpsStatus(@Nullable GpsStatus status) {
- UnsupportedOperationException ex = new UnsupportedOperationException(
- "GpsStatus APIs not supported in S and above, use GnssStatus APIs instead");
if (mContext.getApplicationInfo().targetSdkVersion > Build.VERSION_CODES.R) {
- throw ex;
- } else {
- Log.w(TAG, ex);
+ throw new UnsupportedOperationException(
+ "GpsStatus APIs not supported in S and above, use GnssStatus APIs instead");
}
GnssStatus gnssStatus = mGnssStatusListenerManager.getGnssStatus();
diff --git a/location/java/android/location/LocationRequest.java b/location/java/android/location/LocationRequest.java
index ca8f2ac82e94..f3e4d81285bd 100644
--- a/location/java/android/location/LocationRequest.java
+++ b/location/java/android/location/LocationRequest.java
@@ -22,7 +22,7 @@ import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/location/java/com/android/internal/location/GpsNetInitiatedHandler.java b/location/java/com/android/internal/location/GpsNetInitiatedHandler.java
index f9b2fe057995..9846436b3ac8 100644
--- a/location/java/com/android/internal/location/GpsNetInitiatedHandler.java
+++ b/location/java/com/android/internal/location/GpsNetInitiatedHandler.java
@@ -19,6 +19,7 @@ package com.android.internal.location;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
@@ -37,8 +38,6 @@ import com.android.internal.R;
import com.android.internal.notification.SystemNotificationChannels;
import com.android.internal.telephony.GsmAlphabet;
-import dalvik.annotation.compat.UnsupportedAppUsage;
-
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;
@@ -126,7 +125,7 @@ public class GpsNetInitiatedHandler {
public static class GpsNiNotification
{
- @android.annotation.UnsupportedAppUsage
+ @android.compat.annotation.UnsupportedAppUsage
public GpsNiNotification() {
}
public int notificationId;
diff --git a/location/java/com/android/internal/location/ProviderRequest.java b/location/java/com/android/internal/location/ProviderRequest.java
index 155f788cb33e..c23f49976799 100644
--- a/location/java/com/android/internal/location/ProviderRequest.java
+++ b/location/java/com/android/internal/location/ProviderRequest.java
@@ -16,7 +16,7 @@
package com.android.internal.location;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.location.LocationRequest;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/media/Android.bp b/media/Android.bp
index 1912930f2081..75ccb227e5c5 100644
--- a/media/Android.bp
+++ b/media/Android.bp
@@ -77,20 +77,13 @@ filegroup {
path: "apex/java"
}
-metalava_updatable_media_args = " --error UnhiddenSystemApi " +
- "--hide RequiresPermission " +
- "--hide MissingPermission --hide BroadcastBehavior " +
- "--hide HiddenSuperclass --hide DeprecationMismatch --hide UnavailableSymbol " +
- "--hide SdkConstant --hide HiddenTypeParameter --hide Todo --hide Typo " +
- "--hide HiddenTypedefConstant --show-annotation android.annotation.SystemApi "
-
droidstubs {
name: "updatable-media-stubs",
srcs: [
":updatable-media-srcs",
":framework-media-annotation-srcs",
],
- args: metalava_updatable_media_args,
+ defaults: [ "framework-module-stubs-defaults-systemapi" ],
aidl: {
// TODO(b/135922046) remove this
include_dirs: ["frameworks/base/core/java"],
@@ -109,3 +102,67 @@ java_library {
srcs: [":framework-media-annotation-srcs"],
installable: false,
}
+
+aidl_interface {
+ name: "audio_common-aidl",
+ local_include_dir: "java",
+ srcs: [
+ "java/android/media/audio/common/AudioChannelMask.aidl",
+ "java/android/media/audio/common/AudioConfig.aidl",
+ "java/android/media/audio/common/AudioFormat.aidl",
+ "java/android/media/audio/common/AudioOffloadInfo.aidl",
+ "java/android/media/audio/common/AudioStreamType.aidl",
+ "java/android/media/audio/common/AudioUsage.aidl",
+ ],
+ backend:
+ {
+ cpp: {
+ enabled: true,
+ },
+ java: {
+ // Already generated as part of the entire media java library.
+ enabled: false,
+ },
+ },
+}
+
+aidl_interface {
+ name: "soundtrigger_middleware-aidl",
+ local_include_dir: "java",
+ srcs: [
+ "java/android/media/soundtrigger_middleware/ConfidenceLevel.aidl",
+ "java/android/media/soundtrigger_middleware/ISoundTriggerCallback.aidl",
+ "java/android/media/soundtrigger_middleware/ISoundTriggerMiddlewareService.aidl",
+ "java/android/media/soundtrigger_middleware/ISoundTriggerModule.aidl",
+ "java/android/media/soundtrigger_middleware/ModelParameter.aidl",
+ "java/android/media/soundtrigger_middleware/ModelParameterRange.aidl",
+ "java/android/media/soundtrigger_middleware/Phrase.aidl",
+ "java/android/media/soundtrigger_middleware/PhraseRecognitionEvent.aidl",
+ "java/android/media/soundtrigger_middleware/PhraseRecognitionExtra.aidl",
+ "java/android/media/soundtrigger_middleware/PhraseSoundModel.aidl",
+ "java/android/media/soundtrigger_middleware/RecognitionConfig.aidl",
+ "java/android/media/soundtrigger_middleware/RecognitionEvent.aidl",
+ "java/android/media/soundtrigger_middleware/RecognitionMode.aidl",
+ "java/android/media/soundtrigger_middleware/RecognitionStatus.aidl",
+ "java/android/media/soundtrigger_middleware/SoundModel.aidl",
+ "java/android/media/soundtrigger_middleware/SoundModelType.aidl",
+ "java/android/media/soundtrigger_middleware/SoundTriggerModuleDescriptor.aidl",
+ "java/android/media/soundtrigger_middleware/SoundTriggerModuleProperties.aidl",
+ "java/android/media/soundtrigger_middleware/Status.aidl",
+ ],
+ backend:
+ {
+ cpp: {
+ enabled: true,
+ },
+ java: {
+ // Already generated as part of the entire media java library.
+ enabled: false,
+ },
+ ndk: {
+ // Not currently needed, and disabled because of b/146172425
+ enabled: false,
+ },
+ },
+ imports: [ "audio_common-aidl" ],
+}
diff --git a/media/apex/java/android/media/MediaParser.java b/media/apex/java/android/media/MediaParser.java
index 8824269ea0c0..ac66d1b7f4ad 100644
--- a/media/apex/java/android/media/MediaParser.java
+++ b/media/apex/java/android/media/MediaParser.java
@@ -102,7 +102,8 @@ import java.util.Map;
* public void onSeekMap(int i, @NonNull MediaFormat mediaFormat) { \/* Do nothing. *\/ }
*
* \@Override
- * public void onFormat(int i, @NonNull MediaFormat mediaFormat) {
+ * public void onTrackData(int i, @NonNull TrackData trackData) {
+ * MediaFormat mediaFormat = trackData.mediaFormat;
* if (videoTrackIndex == -1 && mediaFormat
* .getString(MediaFormat.KEY_MIME, \/* defaultValue= *\/ "").startsWith("video/")) {
* videoTrackIndex = i;
@@ -156,19 +157,29 @@ public final class MediaParser {
* <p>A {@link SeekPoint} is a position in the stream from which a player may successfully start
* playing media samples.
*/
- public interface SeekMap {
+ public static final class SeekMap {
/** Returned by {@link #getDurationUs()} when the duration is unknown. */
- int UNKNOWN_DURATION = Integer.MIN_VALUE;
+ public static final int UNKNOWN_DURATION = Integer.MIN_VALUE;
+
+ private final com.google.android.exoplayer2.extractor.SeekMap mExoPlayerSeekMap;
+
+ private SeekMap(com.google.android.exoplayer2.extractor.SeekMap exoplayerSeekMap) {
+ mExoPlayerSeekMap = exoplayerSeekMap;
+ }
/** Returns whether seeking is supported. */
- boolean isSeekable();
+ public boolean isSeekable() {
+ return mExoPlayerSeekMap.isSeekable();
+ }
/**
* Returns the duration of the stream in microseconds or {@link #UNKNOWN_DURATION} if the
* duration is unknown.
*/
- long getDurationUs();
+ public long getDurationUs() {
+ return mExoPlayerSeekMap.getDurationUs();
+ }
/**
* Obtains {@link SeekPoint SeekPoints} for the specified seek time in microseconds.
@@ -184,7 +195,28 @@ public final class MediaParser {
* @return The corresponding {@link SeekPoint SeekPoints}.
*/
@NonNull
- Pair<SeekPoint, SeekPoint> getSeekPoints(long timeUs);
+ public Pair<SeekPoint, SeekPoint> getSeekPoints(long timeUs) {
+ SeekPoints seekPoints = mExoPlayerSeekMap.getSeekPoints(timeUs);
+ return new Pair<>(toSeekPoint(seekPoints.first), toSeekPoint(seekPoints.second));
+ }
+ }
+
+ /** Holds information associated with a track. */
+ public static final class TrackData {
+
+ /** Holds {@link MediaFormat} information for the track. */
+ @NonNull public final MediaFormat mediaFormat;
+
+ /**
+ * Holds {@link DrmInitData} necessary to acquire keys associated with the track, or null if
+ * the track has no encryption data.
+ */
+ @Nullable public final DrmInitData drmInitData;
+
+ private TrackData(MediaFormat mediaFormat, DrmInitData drmInitData) {
+ this.mediaFormat = mediaFormat;
+ this.drmInitData = drmInitData;
+ }
}
/** Defines a seek point in a media stream. */
@@ -295,12 +327,12 @@ public final class MediaParser {
void onTracksFound(int numberOfTracks);
/**
- * Called when the {@link MediaFormat} of the track is extracted from the stream.
+ * Called when new {@link TrackData} is extracted from the stream.
*
- * @param trackIndex The index of the track for which the {@link MediaFormat} was found.
- * @param format The extracted {@link MediaFormat}.
+ * @param trackIndex The index of the track for which the {@link TrackData} was extracted.
+ * @param trackData The extracted {@link TrackData}.
*/
- void onFormat(int trackIndex, @NonNull MediaFormat format);
+ void onTrackData(int trackIndex, @NonNull TrackData trackData);
/**
* Called to write sample data to the output.
@@ -647,7 +679,7 @@ public final class MediaParser {
@Override
public void seekMap(com.google.android.exoplayer2.extractor.SeekMap exoplayerSeekMap) {
- mOutputConsumer.onSeekMap(new ExoToMediaParserSeekMapAdapter(exoplayerSeekMap));
+ mOutputConsumer.onSeekMap(new SeekMap(exoplayerSeekMap));
}
}
@@ -661,7 +693,10 @@ public final class MediaParser {
@Override
public void format(Format format) {
- mOutputConsumer.onFormat(mTrackIndex, toMediaFormat(format));
+ mOutputConsumer.onTrackData(
+ mTrackIndex,
+ new TrackData(
+ toMediaFormat(format), toFrameworkDrmInitData(format.drmInitData)));
}
@Override
@@ -764,32 +799,6 @@ public final class MediaParser {
Extractor createInstance();
}
- private static class ExoToMediaParserSeekMapAdapter implements SeekMap {
-
- private final com.google.android.exoplayer2.extractor.SeekMap mExoPlayerSeekMap;
-
- private ExoToMediaParserSeekMapAdapter(
- com.google.android.exoplayer2.extractor.SeekMap exoplayerSeekMap) {
- mExoPlayerSeekMap = exoplayerSeekMap;
- }
-
- @Override
- public boolean isSeekable() {
- return mExoPlayerSeekMap.isSeekable();
- }
-
- @Override
- public long getDurationUs() {
- return mExoPlayerSeekMap.getDurationUs();
- }
-
- @Override
- public Pair<SeekPoint, SeekPoint> getSeekPoints(long timeUs) {
- SeekPoints seekPoints = mExoPlayerSeekMap.getSeekPoints(timeUs);
- return new Pair<>(toSeekPoint(seekPoints.first), toSeekPoint(seekPoints.second));
- }
- }
-
// Private static methods.
private static MediaFormat toMediaFormat(Format format) {
@@ -859,6 +868,12 @@ public final class MediaParser {
return 0;
}
+ private static DrmInitData toFrameworkDrmInitData(
+ com.google.android.exoplayer2.drm.DrmInitData drmInitData) {
+ // TODO: Implement.
+ return null;
+ }
+
private static MediaCodec.CryptoInfo toCryptoInfo(TrackOutput.CryptoData encryptionData) {
// TODO: Implement.
return null;
diff --git a/media/java/android/media/AmrInputStream.java b/media/java/android/media/AmrInputStream.java
index 5088798a2910..3cb224dd58cd 100644
--- a/media/java/android/media/AmrInputStream.java
+++ b/media/java/android/media/AmrInputStream.java
@@ -16,14 +16,14 @@
package android.media;
-import java.io.InputStream;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.media.MediaCodec.BufferInfo;
import android.util.Log;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+
/**
* DO NOT USE
diff --git a/media/java/android/media/AsyncPlayer.java b/media/java/android/media/AsyncPlayer.java
index 8ac26553bab4..c3dc118fec7e 100644
--- a/media/java/android/media/AsyncPlayer.java
+++ b/media/java/android/media/AsyncPlayer.java
@@ -17,9 +17,8 @@
package android.media;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
-import android.media.PlayerBase;
import android.net.Uri;
import android.os.PowerManager;
import android.os.SystemClock;
diff --git a/media/java/android/media/AudioAttributes.java b/media/java/android/media/AudioAttributes.java
index c03e8e20175d..ece53353c871 100644
--- a/media/java/android/media/AudioAttributes.java
+++ b/media/java/android/media/AudioAttributes.java
@@ -18,8 +18,9 @@ package android.media;
import android.annotation.IntDef;
import android.annotation.NonNull;
+import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.media.audiopolicy.AudioProductStrategy;
import android.os.Build;
import android.os.Bundle;
@@ -178,6 +179,13 @@ public final class AudioAttributes implements Parcelable {
* utterances.
*/
public final static int USAGE_ASSISTANT = 16;
+ /**
+ * @hide
+ * Usage value to use for assistant voice interaction with remote caller on Cell and VoIP calls.
+ */
+ @SystemApi
+ @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
+ public static final int USAGE_CALL_ASSISTANT = 17;
/**
* IMPORTANT: when adding new usage types, add them to SDK_USAGES and update SUPPRESSIBLE_USAGES
@@ -254,6 +262,7 @@ public final class AudioAttributes implements Parcelable {
SUPPRESSIBLE_USAGES.put(USAGE_ASSISTANCE_NAVIGATION_GUIDANCE, SUPPRESSIBLE_MEDIA);
SUPPRESSIBLE_USAGES.put(USAGE_GAME, SUPPRESSIBLE_MEDIA);
SUPPRESSIBLE_USAGES.put(USAGE_ASSISTANT, SUPPRESSIBLE_MEDIA);
+ SUPPRESSIBLE_USAGES.put(USAGE_CALL_ASSISTANT, SUPPRESSIBLE_NEVER);
/** default volume assignment is STREAM_MUSIC, handle unknown usage as media */
SUPPRESSIBLE_USAGES.put(USAGE_UNKNOWN, SUPPRESSIBLE_MEDIA);
SUPPRESSIBLE_USAGES.put(USAGE_ASSISTANCE_SONIFICATION, SUPPRESSIBLE_SYSTEM);
@@ -682,6 +691,7 @@ public final class AudioAttributes implements Parcelable {
case USAGE_GAME:
case USAGE_VIRTUAL_SOURCE:
case USAGE_ASSISTANT:
+ case USAGE_CALL_ASSISTANT:
mUsage = usage;
break;
default:
@@ -1135,6 +1145,8 @@ public final class AudioAttributes implements Parcelable {
return new String("USAGE_GAME");
case USAGE_ASSISTANT:
return new String("USAGE_ASSISTANT");
+ case USAGE_CALL_ASSISTANT:
+ return new String("USAGE_CALL_ASSISTANT");
default:
return new String("unknown usage " + usage);
}
@@ -1238,6 +1250,7 @@ public final class AudioAttributes implements Parcelable {
case USAGE_ASSISTANCE_SONIFICATION:
return AudioSystem.STREAM_SYSTEM;
case USAGE_VOICE_COMMUNICATION:
+ case USAGE_CALL_ASSISTANT:
return AudioSystem.STREAM_VOICE_CALL;
case USAGE_VOICE_COMMUNICATION_SIGNALLING:
return fromGetVolumeControlStream ?
@@ -1302,6 +1315,7 @@ public final class AudioAttributes implements Parcelable {
USAGE_ASSISTANCE_SONIFICATION,
USAGE_GAME,
USAGE_ASSISTANT,
+ USAGE_CALL_ASSISTANT,
})
@Retention(RetentionPolicy.SOURCE)
public @interface AttributeUsage {}
diff --git a/media/java/android/media/AudioDeviceAddress.java b/media/java/android/media/AudioDeviceAddress.java
index 415e77dc4049..3d8fc373006e 100644
--- a/media/java/android/media/AudioDeviceAddress.java
+++ b/media/java/android/media/AudioDeviceAddress.java
@@ -72,10 +72,12 @@ public final class AudioDeviceAddress implements Parcelable {
private final @Role int mRole;
/**
+ * @hide
* Constructor from a valid {@link AudioDeviceInfo}
* @param deviceInfo the connected audio device from which to obtain the device-identifying
* type and address.
*/
+ @SystemApi
public AudioDeviceAddress(@NonNull AudioDeviceInfo deviceInfo) {
Objects.requireNonNull(deviceInfo);
mRole = deviceInfo.isSink() ? ROLE_OUTPUT : ROLE_INPUT;
@@ -83,6 +85,14 @@ public final class AudioDeviceAddress implements Parcelable {
mAddress = deviceInfo.getAddress();
}
+ /**
+ * @hide
+ * Constructor from role, device type and address
+ * @param role indicates input or output role
+ * @param type the device type, as defined in {@link AudioDeviceInfo}
+ * @param address the address of the device, or an empty string for devices without one
+ */
+ @SystemApi
public AudioDeviceAddress(@Role int role, @AudioDeviceInfo.AudioDeviceType int type,
@NonNull String address) {
Objects.requireNonNull(address);
@@ -101,14 +111,38 @@ public final class AudioDeviceAddress implements Parcelable {
mAddress = address;
}
+ /*package*/ AudioDeviceAddress(int nativeType, @NonNull String address) {
+ mRole = (nativeType & AudioSystem.DEVICE_BIT_IN) != 0 ? ROLE_INPUT : ROLE_OUTPUT;
+ mType = AudioDeviceInfo.convertInternalDeviceToDeviceType(nativeType);
+ mAddress = address;
+ }
+
+ /**
+ * @hide
+ * Returns the role of a device
+ * @return the role
+ */
+ @SystemApi
public @Role int getRole() {
return mRole;
}
+ /**
+ * @hide
+ * Returns the audio device type of a device
+ * @return the type, as defined in {@link AudioDeviceInfo}
+ */
+ @SystemApi
public @AudioDeviceInfo.AudioDeviceType int getType() {
return mType;
}
+ /**
+ * @hide
+ * Returns the address of the audio device, or an empty string for devices without one
+ * @return the device address
+ */
+ @SystemApi
public @NonNull String getAddress() {
return mAddress;
}
diff --git a/media/java/android/media/AudioDeviceInfo.java b/media/java/android/media/AudioDeviceInfo.java
index a39bc51acb24..8293b5f36c04 100644
--- a/media/java/android/media/AudioDeviceInfo.java
+++ b/media/java/android/media/AudioDeviceInfo.java
@@ -155,7 +155,9 @@ public final class AudioDeviceInfo {
TYPE_TV_TUNER }
)
@Retention(RetentionPolicy.SOURCE)
- public @interface AudioDeviceType {} /** @hide */
+ public @interface AudioDeviceType {}
+
+ /** @hide */
@IntDef(flag = false, prefix = "TYPE", value = {
TYPE_BUILTIN_MIC,
TYPE_BLUETOOTH_SCO,
diff --git a/media/java/android/media/AudioDevicePort.java b/media/java/android/media/AudioDevicePort.java
index 62b18cbafcb1..51909db11a09 100644
--- a/media/java/android/media/AudioDevicePort.java
+++ b/media/java/android/media/AudioDevicePort.java
@@ -16,8 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
-import android.media.AudioSystem;
+import android.compat.annotation.UnsupportedAppUsage;
/**
* The AudioDevicePort is a specialized type of AudioPort
diff --git a/media/java/android/media/AudioDevicePortConfig.java b/media/java/android/media/AudioDevicePortConfig.java
index 0c647ea85c60..51b8037b82f8 100644
--- a/media/java/android/media/AudioDevicePortConfig.java
+++ b/media/java/android/media/AudioDevicePortConfig.java
@@ -16,7 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/**
* An AudioDevicePortConfig describes a possible configuration of an output or input device
diff --git a/media/java/android/media/AudioFormat.java b/media/java/android/media/AudioFormat.java
index f0787e93dc8b..489d0501280d 100644
--- a/media/java/android/media/AudioFormat.java
+++ b/media/java/android/media/AudioFormat.java
@@ -20,7 +20,7 @@ import android.annotation.IntDef;
import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/media/java/android/media/AudioGain.java b/media/java/android/media/AudioGain.java
index dd129a26ee59..cae1b59d46a7 100644
--- a/media/java/android/media/AudioGain.java
+++ b/media/java/android/media/AudioGain.java
@@ -16,7 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/**
* The AudioGain describes a gain controller. Gain controllers are exposed by
diff --git a/media/java/android/media/AudioGainConfig.java b/media/java/android/media/AudioGainConfig.java
index f5ebef85d302..dfefa8621ef8 100644
--- a/media/java/android/media/AudioGainConfig.java
+++ b/media/java/android/media/AudioGainConfig.java
@@ -16,7 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/**
* The AudioGainConfig is used by APIs setting or getting values on a given gain
diff --git a/media/java/android/media/AudioHandle.java b/media/java/android/media/AudioHandle.java
index 24f81f918af2..8fc834f8d0a9 100644
--- a/media/java/android/media/AudioHandle.java
+++ b/media/java/android/media/AudioHandle.java
@@ -16,7 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/**
* The AudioHandle is used by the audio framework implementation to
diff --git a/media/java/android/media/AudioManager.java b/media/java/android/media/AudioManager.java
index d5524915f423..c8a7ef590838 100644
--- a/media/java/android/media/AudioManager.java
+++ b/media/java/android/media/AudioManager.java
@@ -28,12 +28,12 @@ import android.annotation.SuppressLint;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothCodecConfig;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
@@ -78,6 +78,7 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
@@ -1536,6 +1537,76 @@ public class AudioManager {
}
//====================================================================
+ // Audio Product Strategy routing
+
+ /**
+ * @hide
+ * Set the preferred device for a given strategy, i.e. the audio routing to be used by
+ * this audio strategy. Note that the device may not be available at the time the preferred
+ * device is set, but it will be used once made available.
+ * <p>Use {@link #removePreferredDeviceForStrategy(AudioProductStrategy)} to cancel setting
+ * this preference for this strategy.</p>
+ * @param strategy the audio strategy whose routing will be affected
+ * @param device the audio device to route to when available
+ * @return true if the operation was successful, false otherwise
+ */
+ @SystemApi
+ @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
+ public boolean setPreferredDeviceForStrategy(@NonNull AudioProductStrategy strategy,
+ @NonNull AudioDeviceAddress device) {
+ Objects.requireNonNull(strategy);
+ Objects.requireNonNull(device);
+ try {
+ final int status =
+ getService().setPreferredDeviceForStrategy(strategy.getId(), device);
+ return status == AudioSystem.SUCCESS;
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * @hide
+ * Removes the preferred audio device previously set with
+ * {@link #setPreferredDeviceForStrategy(AudioProductStrategy, AudioDeviceAddress)}.
+ * @param strategy the audio strategy whose routing will be affected
+ * @return true if the operation was successful, false otherwise (invalid strategy, or no
+ * device set for example)
+ */
+ @SystemApi
+ @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
+ public boolean removePreferredDeviceForStrategy(@NonNull AudioProductStrategy strategy) {
+ Objects.requireNonNull(strategy);
+ try {
+ final int status =
+ getService().removePreferredDeviceForStrategy(strategy.getId());
+ return status == AudioSystem.SUCCESS;
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * @hide
+ * Return the preferred device for an audio strategy, previously set with
+ * {@link #setPreferredDeviceForStrategy(AudioProductStrategy, AudioDeviceAddress)}
+ * @param strategy the strategy to query
+ * @return the preferred device for that strategy, or null if none was ever set or if the
+ * strategy is invalid
+ */
+ @SystemApi
+ @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
+ public @Nullable AudioDeviceAddress getPreferredDeviceForStrategy(
+ @NonNull AudioProductStrategy strategy) {
+ Objects.requireNonNull(strategy);
+ try {
+ return getService().getPreferredDeviceForStrategy(strategy.getId());
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ //====================================================================
// Offload query
/**
* Returns whether offloaded playback of an audio format is supported on the device.
@@ -4962,6 +5033,14 @@ public class AudioManager {
*/
public static final int GET_DEVICES_OUTPUTS = 0x0002;
+ /** @hide */
+ @IntDef(flag = true, prefix = "GET_DEVICES", value = {
+ GET_DEVICES_INPUTS,
+ GET_DEVICES_OUTPUTS }
+ )
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface AudioDeviceRole {}
+
/**
* Specifies to the {@link AudioManager#getDevices(int)} method to include both
* source and sink devices.
@@ -4994,7 +5073,7 @@ public class AudioManager {
* @see #GET_DEVICES_ALL
* @return A (possibly zero-length) array of AudioDeviceInfo objects.
*/
- public AudioDeviceInfo[] getDevices(int flags) {
+ public AudioDeviceInfo[] getDevices(@AudioDeviceRole int flags) {
return getDevicesStatic(flags);
}
diff --git a/media/java/android/media/AudioMixPort.java b/media/java/android/media/AudioMixPort.java
index c4a5c4d86a41..33d603f0b9da 100644
--- a/media/java/android/media/AudioMixPort.java
+++ b/media/java/android/media/AudioMixPort.java
@@ -16,7 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/**
* The AudioMixPort is a specialized type of AudioPort
diff --git a/media/java/android/media/AudioMixPortConfig.java b/media/java/android/media/AudioMixPortConfig.java
index 315e46b725ad..9d8120624a45 100644
--- a/media/java/android/media/AudioMixPortConfig.java
+++ b/media/java/android/media/AudioMixPortConfig.java
@@ -16,7 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/**
* An AudioMixPortConfig describes a possible configuration of an output or input mixer.
diff --git a/media/java/android/media/AudioPatch.java b/media/java/android/media/AudioPatch.java
index d1f800694f50..e5107d4e3309 100644
--- a/media/java/android/media/AudioPatch.java
+++ b/media/java/android/media/AudioPatch.java
@@ -16,7 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/**
diff --git a/media/java/android/media/AudioPort.java b/media/java/android/media/AudioPort.java
index 83eb240be743..7c3ca24e1c9a 100644
--- a/media/java/android/media/AudioPort.java
+++ b/media/java/android/media/AudioPort.java
@@ -16,7 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/**
* An audio port is a node of the audio framework or hardware that can be connected to or
diff --git a/media/java/android/media/AudioPortConfig.java b/media/java/android/media/AudioPortConfig.java
index ac19bb167905..16fb5b80eb3e 100644
--- a/media/java/android/media/AudioPortConfig.java
+++ b/media/java/android/media/AudioPortConfig.java
@@ -16,7 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
/**
* An AudioPortConfig contains a possible configuration of an audio port chosen
diff --git a/media/java/android/media/AudioPortEventHandler.java b/media/java/android/media/AudioPortEventHandler.java
index 6d9d6265f5e7..14249cbe8945 100644
--- a/media/java/android/media/AudioPortEventHandler.java
+++ b/media/java/android/media/AudioPortEventHandler.java
@@ -16,7 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
diff --git a/media/java/android/media/AudioRecord.java b/media/java/android/media/AudioRecord.java
index 95afb090fcca..fd3523de4d0f 100644
--- a/media/java/android/media/AudioRecord.java
+++ b/media/java/android/media/AudioRecord.java
@@ -23,8 +23,8 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityThread;
+import android.compat.annotation.UnsupportedAppUsage;
import android.media.MediaRecorder.Source;
import android.media.audiopolicy.AudioMix;
import android.media.audiopolicy.AudioPolicy;
diff --git a/media/java/android/media/AudioRecordingConfiguration.java b/media/java/android/media/AudioRecordingConfiguration.java
index 874a215e4975..5f32c0f3f4a8 100644
--- a/media/java/android/media/AudioRecordingConfiguration.java
+++ b/media/java/android/media/AudioRecordingConfiguration.java
@@ -19,7 +19,7 @@ package android.media;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.media.audiofx.AudioEffect;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/media/java/android/media/AudioSystem.java b/media/java/android/media/AudioSystem.java
index d64e4ef00164..8e76fcf6605c 100644
--- a/media/java/android/media/AudioSystem.java
+++ b/media/java/android/media/AudioSystem.java
@@ -19,12 +19,13 @@ package android.media;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.bluetooth.BluetoothCodecConfig;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.audiofx.AudioEffect;
import android.media.audiopolicy.AudioMix;
+import android.telephony.TelephonyManager;
import android.util.Log;
import java.lang.annotation.Retention;
@@ -902,6 +903,18 @@ public class AudioSystem
}
}
+ /**
+ * Returns a human readable name for a given device type
+ * @param device a native device type, NOT an AudioDeviceInfo type
+ * @return a string describing the device type
+ */
+ public static @NonNull String getDeviceName(int device) {
+ if ((device & DEVICE_BIT_IN) != 0) {
+ return getInputDeviceName(device);
+ }
+ return getOutputDeviceName(device);
+ }
+
// phone state, match audio_mode???
public static final int PHONE_STATE_OFFCALL = 0;
public static final int PHONE_STATE_RINGING = 1;
@@ -1173,6 +1186,48 @@ public class AudioSystem
*/
public static native boolean isCallScreeningModeSupported();
+ // use case routing by product strategy
+
+ /**
+ * Sets the preferred device to use for a given audio strategy in the audio policy engine
+ * @param strategy the id of the strategy to configure
+ * @param device the device type and address to route to when available
+ * @return {@link #SUCCESS} if successfully set
+ */
+ public static int setPreferredDeviceForStrategy(
+ int strategy, @NonNull AudioDeviceAddress device) {
+ return setPreferredDeviceForStrategy(strategy,
+ AudioDeviceInfo.convertDeviceTypeToInternalDevice(device.getType()),
+ device.getAddress());
+ }
+ /**
+ * Set device routing per product strategy.
+ * @param strategy the id of the strategy to configure
+ * @param deviceType the native device type, NOT AudioDeviceInfo types
+ * @param deviceAddress the address of the device
+ * @return {@link #SUCCESS} if successfully set
+ */
+ private static native int setPreferredDeviceForStrategy(
+ int strategy, int deviceType, String deviceAddress);
+
+ /**
+ * Remove preferred routing for the strategy
+ * @param strategy the id of the strategy to configure
+ * @return {@link #SUCCESS} if successfully removed
+ */
+ public static native int removePreferredDeviceForStrategy(int strategy);
+
+ /**
+ * Query previously set preferred device for a strategy
+ * @param strategy the id of the strategy to query for
+ * @param device an array of size 1 that will contain the preferred device, or null if
+ * none was set
+ * @return {@link #SUCCESS} if there is a preferred device and it was successfully retrieved
+ * and written to the array
+ */
+ public static native int getPreferredDeviceForStrategy(int strategy,
+ AudioDeviceAddress[] device);
+
// Items shared with audio service
/**
@@ -1246,7 +1301,8 @@ public class AudioSystem
* </ul>
*/
public static int getPlatformType(Context context) {
- if (context.getResources().getBoolean(com.android.internal.R.bool.config_voice_capable)) {
+ if (((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
+ .isVoiceCapable()) {
return PLATFORM_VOICE;
} else if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
return PLATFORM_TELEVISION;
diff --git a/media/java/android/media/AudioTrack.java b/media/java/android/media/AudioTrack.java
index 7cd09de41346..0ced68ef8695 100644
--- a/media/java/android/media/AudioTrack.java
+++ b/media/java/android/media/AudioTrack.java
@@ -23,7 +23,7 @@ import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Binder;
import android.os.Handler;
import android.os.HandlerThread;
diff --git a/media/java/android/media/CamcorderProfile.java b/media/java/android/media/CamcorderProfile.java
index 963b1d1504e2..e4bab7466a70 100644
--- a/media/java/android/media/CamcorderProfile.java
+++ b/media/java/android/media/CamcorderProfile.java
@@ -16,7 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.os.Build;
diff --git a/media/java/android/media/DecoderCapabilities.java b/media/java/android/media/DecoderCapabilities.java
index df5e918ba8d5..ebfc63bd9bcd 100644
--- a/media/java/android/media/DecoderCapabilities.java
+++ b/media/java/android/media/DecoderCapabilities.java
@@ -16,9 +16,10 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
-import java.util.List;
+import android.compat.annotation.UnsupportedAppUsage;
+
import java.util.ArrayList;
+import java.util.List;
/**
* {@hide}
diff --git a/media/java/android/media/EncoderCapabilities.java b/media/java/android/media/EncoderCapabilities.java
index c09c5fae1213..67ce0f7cc0b9 100644
--- a/media/java/android/media/EncoderCapabilities.java
+++ b/media/java/android/media/EncoderCapabilities.java
@@ -16,9 +16,10 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
-import java.util.List;
+import android.compat.annotation.UnsupportedAppUsage;
+
import java.util.ArrayList;
+import java.util.List;
/**
* The EncoderCapabilities class is used to retrieve the
diff --git a/media/java/android/media/ExifInterface.java b/media/java/android/media/ExifInterface.java
index ce4aac9bdb7f..767b67b7e885 100644
--- a/media/java/android/media/ExifInterface.java
+++ b/media/java/android/media/ExifInterface.java
@@ -20,7 +20,7 @@ import android.annotation.CurrentTimeMillisLong;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
diff --git a/media/java/android/media/IAudioService.aidl b/media/java/android/media/IAudioService.aidl
index ef451ce401e6..ad7335e5b683 100644
--- a/media/java/android/media/IAudioService.aidl
+++ b/media/java/android/media/IAudioService.aidl
@@ -18,6 +18,7 @@ package android.media;
import android.bluetooth.BluetoothDevice;
import android.media.AudioAttributes;
+import android.media.AudioDeviceAddress;
import android.media.AudioFocusInfo;
import android.media.AudioPlaybackConfiguration;
import android.media.AudioRecordingConfiguration;
@@ -265,6 +266,12 @@ interface IAudioService {
boolean isCallScreeningModeSupported();
+ int setPreferredDeviceForStrategy(in int strategy, in AudioDeviceAddress device);
+
+ int removePreferredDeviceForStrategy(in int strategy);
+
+ AudioDeviceAddress getPreferredDeviceForStrategy(in int strategy);
+
// WARNING: read warning at top of file, new methods that need to be used by native
// code via IAudioManager.h need to be added to the top section.
}
diff --git a/media/java/android/media/Image.java b/media/java/android/media/Image.java
index 7ba122baeca1..79b861136b64 100644
--- a/media/java/android/media/Image.java
+++ b/media/java/android/media/Image.java
@@ -16,14 +16,13 @@
package android.media;
-import java.nio.ByteBuffer;
-import java.lang.AutoCloseable;
-
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.Rect;
import android.hardware.HardwareBuffer;
+import java.nio.ByteBuffer;
+
/**
* <p>A single complete image buffer to use with a media source such as a
* {@link MediaCodec} or a
diff --git a/media/java/android/media/JetPlayer.java b/media/java/android/media/JetPlayer.java
index e85b3ff99104..84ee09b35b81 100644
--- a/media/java/android/media/JetPlayer.java
+++ b/media/java/android/media/JetPlayer.java
@@ -17,7 +17,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.res.AssetFileDescriptor;
import android.os.Handler;
import android.os.Looper;
diff --git a/media/java/android/media/MediaCodec.java b/media/java/android/media/MediaCodec.java
index d16a216a4cc9..176bb37130a7 100644
--- a/media/java/android/media/MediaCodec.java
+++ b/media/java/android/media/MediaCodec.java
@@ -19,7 +19,7 @@ package android.media;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
diff --git a/media/java/android/media/MediaCodecInfo.java b/media/java/android/media/MediaCodecInfo.java
index 91d644b5db74..cbc9683b9cc1 100644
--- a/media/java/android/media/MediaCodecInfo.java
+++ b/media/java/android/media/MediaCodecInfo.java
@@ -23,7 +23,7 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SuppressLint;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.SystemProperties;
import android.util.Log;
diff --git a/media/java/android/media/MediaDrm.java b/media/java/android/media/MediaDrm.java
index 6523e30c13cc..13bd85634fda 100644
--- a/media/java/android/media/MediaDrm.java
+++ b/media/java/android/media/MediaDrm.java
@@ -21,17 +21,17 @@ import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.StringDef;
-import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityThread;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Handler;
import android.os.HandlerExecutor;
import android.os.Looper;
-import android.os.Message;
import android.os.Parcel;
import android.os.PersistableBundle;
import android.util.Log;
+
import dalvik.system.CloseGuard;
+
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
diff --git a/media/java/android/media/MediaFile.java b/media/java/android/media/MediaFile.java
index c4eb0310f292..9908e042c6a4 100644
--- a/media/java/android/media/MediaFile.java
+++ b/media/java/android/media/MediaFile.java
@@ -20,7 +20,7 @@ import static android.content.ContentResolver.MIME_TYPE_DEFAULT;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.mtp.MtpConstants;
import libcore.content.type.MimeMap;
diff --git a/media/java/android/media/MediaFormat.java b/media/java/android/media/MediaFormat.java
index 8080f45642dc..79b3886338b1 100644
--- a/media/java/android/media/MediaFormat.java
+++ b/media/java/android/media/MediaFormat.java
@@ -19,7 +19,7 @@ package android.media;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -46,6 +46,8 @@ import java.util.stream.Collectors;
* <tr><th>Name</th><th>Value Type</th><th>Description</th></tr>
* <tr><td>{@link #KEY_MIME}</td><td>String</td><td>The type of the format.</td></tr>
* <tr><td>{@link #KEY_MAX_INPUT_SIZE}</td><td>Integer</td><td>optional, maximum size of a buffer of input data</td></tr>
+ * <tr><td>{@link #KEY_PIXEL_ASPECT_RATIO_WIDTH}</td><td>Integer</td><td>optional, the pixel aspect ratio width</td></tr>
+ * <tr><td>{@link #KEY_PIXEL_ASPECT_RATIO_HEIGHT}</td><td>Integer</td><td>optional, the pixel aspect ratio height</td></tr>
* <tr><td>{@link #KEY_BIT_RATE}</td><td>Integer</td><td><b>encoder-only</b>, desired bitrate in bits/second</td></tr>
* </table>
*
@@ -99,6 +101,8 @@ import java.util.stream.Collectors;
* <tr><td>{@link #KEY_AAC_MAX_OUTPUT_CHANNEL_COUNT}</td><td>Integer</td><td><b>decoder-only</b>, optional, if content is AAC audio, specifies the maximum number of channels the decoder outputs.</td></tr>
* <tr><td>{@link #KEY_AAC_DRC_EFFECT_TYPE}</td><td>Integer</td><td><b>decoder-only</b>, optional, if content is AAC audio, specifies the MPEG-D DRC effect type to use.</td></tr>
* <tr><td>{@link #KEY_CHANNEL_MASK}</td><td>Integer</td><td>optional, a mask of audio channel assignments</td></tr>
+ * <tr><td>{@link #KEY_ENCODER_DELAY}</td><td>Integer</td><td>optional, the number of frames to trim from the start of the decoded audio stream.</td></tr>
+ * <tr><td>{@link #KEY_ENCODER_PADDING}</td><td>Integer</td><td>optional, the number of frames to trim from the end of the decoded audio stream.</td></tr>
* <tr><td>{@link #KEY_FLAC_COMPRESSION_LEVEL}</td><td>Integer</td><td><b>encoder-only</b>, optional, if content is FLAC audio, specifies the desired compression level.</td></tr>
* </table>
*
@@ -270,6 +274,18 @@ public final class MediaFormat {
public static final String KEY_MAX_INPUT_SIZE = "max-input-size";
/**
+ * A key describing the pixel aspect ratio width.
+ * The associated value is an integer
+ */
+ public static final String KEY_PIXEL_ASPECT_RATIO_WIDTH = "sar-width";
+
+ /**
+ * A key describing the pixel aspect ratio height.
+ * The associated value is an integer
+ */
+ public static final String KEY_PIXEL_ASPECT_RATIO_HEIGHT = "sar-height";
+
+ /**
* A key describing the average bitrate in bits/sec.
* The associated value is an integer
*/
@@ -569,6 +585,18 @@ public final class MediaFormat {
public static final String KEY_CHANNEL_MASK = "channel-mask";
/**
+ * A key describing the number of frames to trim from the start of the decoded audio stream.
+ * The associated value is an integer.
+ */
+ public static final String KEY_ENCODER_DELAY = "encoder-delay";
+
+ /**
+ * A key describing the number of frames to trim from the end of the decoded audio stream.
+ * The associated value is an integer.
+ */
+ public static final String KEY_ENCODER_PADDING = "encoder-padding";
+
+ /**
* A key describing the AAC profile to be used (AAC audio formats only).
* Constants are declared in {@link android.media.MediaCodecInfo.CodecProfileLevel}.
*/
diff --git a/media/java/android/media/MediaHTTPConnection.java b/media/java/android/media/MediaHTTPConnection.java
index 8ee929e77899..a17ff825e21b 100644
--- a/media/java/android/media/MediaHTTPConnection.java
+++ b/media/java/android/media/MediaHTTPConnection.java
@@ -18,13 +18,14 @@ package android.media;
import static android.media.MediaPlayer.MEDIA_ERROR_UNSUPPORTED;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.net.NetworkUtils;
import android.os.IBinder;
import android.os.StrictMode;
import android.util.Log;
import com.android.internal.annotations.GuardedBy;
+
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
diff --git a/media/java/android/media/MediaHTTPService.java b/media/java/android/media/MediaHTTPService.java
index 97a0df799101..3008067daefb 100644
--- a/media/java/android/media/MediaHTTPService.java
+++ b/media/java/android/media/MediaHTTPService.java
@@ -17,7 +17,7 @@
package android.media;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.IBinder;
import android.util.Log;
diff --git a/media/java/android/media/MediaInserter.java b/media/java/android/media/MediaInserter.java
index 0749f58e460d..ca7a01cb990d 100644
--- a/media/java/android/media/MediaInserter.java
+++ b/media/java/android/media/MediaInserter.java
@@ -16,7 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentProviderClient;
import android.content.ContentValues;
import android.net.Uri;
diff --git a/media/java/android/media/MediaMetadata.java b/media/java/android/media/MediaMetadata.java
index 8512dbe8d224..a23191f36efc 100644
--- a/media/java/android/media/MediaMetadata.java
+++ b/media/java/android/media/MediaMetadata.java
@@ -17,7 +17,7 @@ package android.media;
import android.annotation.NonNull;
import android.annotation.StringDef;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentResolver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
diff --git a/media/java/android/media/MediaMetadataRetriever.java b/media/java/android/media/MediaMetadataRetriever.java
index 5d2bdd756840..7fca03cdfd57 100644
--- a/media/java/android/media/MediaMetadataRetriever.java
+++ b/media/java/android/media/MediaMetadataRetriever.java
@@ -19,7 +19,7 @@ package android.media;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
diff --git a/media/java/android/media/MediaMetrics.java b/media/java/android/media/MediaMetrics.java
new file mode 100644
index 000000000000..88a829546989
--- /dev/null
+++ b/media/java/android/media/MediaMetrics.java
@@ -0,0 +1,634 @@
+/*
+ * Copyright 2019 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.media;
+
+import android.annotation.NonNull;
+import android.annotation.TestApi;
+import android.os.Bundle;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+
+/**
+ * MediaMetrics is the Java interface to the MediaMetrics service.
+ *
+ * This is used to collect media statistics by the framework.
+ * It is not intended for direct application use.
+ *
+ * @hide
+ */
+public class MediaMetrics {
+ public static final String TAG = "MediaMetrics";
+
+ /**
+ * The TYPE constants below should match those in native MediaMetricsItem.h
+ */
+ private static final int TYPE_NONE = 0;
+ private static final int TYPE_INT32 = 1; // Java integer
+ private static final int TYPE_INT64 = 2; // Java long
+ private static final int TYPE_DOUBLE = 3; // Java double
+ private static final int TYPE_CSTRING = 4; // Java string
+ private static final int TYPE_RATE = 5; // Two longs, ignored in Java
+
+ // The charset used for encoding Strings to bytes.
+ private static final Charset MEDIAMETRICS_CHARSET = StandardCharsets.UTF_8;
+
+ /**
+ * Item records properties and delivers to the MediaMetrics service
+ *
+ */
+ public static class Item {
+
+ /*
+ * MediaMetrics Item
+ *
+ * Creates a Byte String and sends to the MediaMetrics service.
+ * The Byte String serves as a compact form for logging data
+ * with low overhead for storage.
+ *
+ * The Byte String format is as follows:
+ *
+ * For Java
+ * int64 corresponds to long
+ * int32, uint32 corresponds to int
+ * uint16 corresponds to char
+ * uint8, int8 corresponds to byte
+ *
+ * For items transmitted from Java, uint8 and uint32 values are limited
+ * to INT8_MAX and INT32_MAX. This constrains the size of large items
+ * to 2GB, which is consistent with ByteBuffer max size. A native item
+ * can conceivably have size of 4GB.
+ *
+ * Physical layout of integers and doubles within the MediaMetrics byte string
+ * is in Native / host order, which is usually little endian.
+ *
+ * Note that primitive data (ints, doubles) within a Byte String has
+ * no extra padding or alignment requirements, like ByteBuffer.
+ *
+ * -- begin of item
+ * -- begin of header
+ * (uint32) item size: including the item size field
+ * (uint32) header size, including the item size and header size fields.
+ * (uint16) version: exactly 0
+ * (uint16) key size, that is key strlen + 1 for zero termination.
+ * (int8)+ key, a string which is 0 terminated (UTF-8).
+ * (int32) pid
+ * (int32) uid
+ * (int64) timestamp
+ * -- end of header
+ * -- begin body
+ * (uint32) number of properties
+ * -- repeat for number of properties
+ * (uint16) property size, including property size field itself
+ * (uint8) type of property
+ * (int8)+ key string, including 0 termination
+ * based on type of property (given above), one of:
+ * (int32)
+ * (int64)
+ * (double)
+ * (int8)+ for TYPE_CSTRING, including 0 termination
+ * (int64, int64) for rate
+ * -- end body
+ * -- end of item
+ *
+ * To record a MediaMetrics event, one creates a new item with an id,
+ * then use a series of puts to add properties
+ * and then a record() to send to the MediaMetrics service.
+ *
+ * The properties may not be unique, and putting a later property with
+ * the same name as an earlier property will overwrite the value and type
+ * of the prior property.
+ *
+ * The timestamp can only be recorded by a system service (and is ignored otherwise;
+ * the MediaMetrics service will fill in the timestamp as needed).
+ *
+ * The units of time are in SystemClock.elapsedRealtimeNanos().
+ *
+ * A clear() may be called to reset the properties to empty, the time to 0, but keep
+ * the other entries the same. This may be called after record().
+ * Additional properties may be added after calling record(). Changing the same property
+ * repeatedly is discouraged as - for this particular implementation - extra data
+ * is stored per change.
+ *
+ * new MediaMetrics.Item(mSomeId)
+ * .putString("event", "javaCreate")
+ * .putInt("value", intValue)
+ * .record();
+ */
+
+ /**
+ * Creates an Item with server added uid, time.
+ *
+ * This is the typical way to record a MediaMetrics item.
+ *
+ * @param key the Metrics ID associated with the item.
+ */
+ public Item(String key) {
+ this(key, -1 /* pid */, -1 /* uid */, 0 /* SystemClock.elapsedRealtimeNanos() */,
+ 2048 /* capacity */);
+ }
+
+ /**
+ * Creates an Item specifying pid, uid, time, and initial Item capacity.
+ *
+ * This might be used by a service to specify a different PID or UID for a client.
+ *
+ * @param key the Metrics ID associated with the item.
+ * An app may only set properties on an item which has already been
+ * logged previously by a service.
+ * @param pid the process ID corresponding to the item.
+ * A value of -1 (or a record() from an app instead of a service) causes
+ * the MediaMetrics service to fill this in.
+ * @param uid the user ID corresponding to the item.
+ * A value of -1 (or a record() from an app instead of a service) causes
+ * the MediaMetrics service to fill this in.
+ * @param timeNs the time when the item occurred (may be in the past).
+ * A value of 0 (or a record() from an app instead of a service) causes
+ * the MediaMetrics service to fill it in.
+ * Should be obtained from SystemClock.elapsedRealtimeNanos().
+ * @param capacity the anticipated size to use for the buffer.
+ * If the capacity is too small, the buffer will be resized to accommodate.
+ * This is amortized to copy data no more than twice.
+ */
+ public Item(String key, int pid, int uid, long timeNs, int capacity) {
+ final byte[] keyBytes = key.getBytes(MEDIAMETRICS_CHARSET);
+ final int keyLength = keyBytes.length;
+ if (keyLength > Character.MAX_VALUE - 1) {
+ throw new IllegalArgumentException("Key length too large");
+ }
+
+ // Version 0 - compute the header offsets here.
+ mHeaderSize = 4 + 4 + 2 + 2 + keyLength + 1 + 4 + 4 + 8; // see format above.
+ mPidOffset = mHeaderSize - 16;
+ mUidOffset = mHeaderSize - 12;
+ mTimeNsOffset = mHeaderSize - 8;
+ mPropertyCountOffset = mHeaderSize;
+ mPropertyStartOffset = mHeaderSize + 4;
+
+ mKey = key;
+ mBuffer = ByteBuffer.allocateDirect(
+ Math.max(capacity, mHeaderSize + MINIMUM_PAYLOAD_SIZE));
+
+ // Version 0 - fill the ByteBuffer with the header (some details updated later).
+ mBuffer.order(ByteOrder.nativeOrder())
+ .putInt((int) 0) // total size in bytes (filled in later)
+ .putInt((int) mHeaderSize) // size of header
+ .putChar((char) FORMAT_VERSION) // version
+ .putChar((char) (keyLength + 1)) // length, with zero termination
+ .put(keyBytes).put((byte) 0)
+ .putInt(pid)
+ .putInt(uid)
+ .putLong(timeNs);
+ if (mHeaderSize != mBuffer.position()) {
+ throw new IllegalStateException("Mismatched sizing");
+ }
+ mBuffer.putInt(0); // number of properties (to be later filled in by record()).
+ }
+
+ /**
+ * Sets the property with key to an integer (32 bit) value.
+ *
+ * @param key
+ * @param value
+ * @return itself
+ */
+ public Item putInt(String key, int value) {
+ final byte[] keyBytes = key.getBytes(MEDIAMETRICS_CHARSET);
+ final char propSize = (char) reserveProperty(keyBytes, 4 /* payloadSize */);
+ final int estimatedFinalPosition = mBuffer.position() + propSize;
+ mBuffer.putChar(propSize)
+ .put((byte) TYPE_INT32)
+ .put(keyBytes).put((byte) 0) // key, zero terminated
+ .putInt(value);
+ ++mPropertyCount;
+ if (mBuffer.position() != estimatedFinalPosition) {
+ throw new IllegalStateException("Final position " + mBuffer.position()
+ + " != estimatedFinalPosition " + estimatedFinalPosition);
+ }
+ return this;
+ }
+
+ /**
+ * Sets the property with key to a long (64 bit) value.
+ *
+ * @param key
+ * @param value
+ * @return itself
+ */
+ public Item putLong(String key, long value) {
+ final byte[] keyBytes = key.getBytes(MEDIAMETRICS_CHARSET);
+ final char propSize = (char) reserveProperty(keyBytes, 8 /* payloadSize */);
+ final int estimatedFinalPosition = mBuffer.position() + propSize;
+ mBuffer.putChar(propSize)
+ .put((byte) TYPE_INT64)
+ .put(keyBytes).put((byte) 0) // key, zero terminated
+ .putLong(value);
+ ++mPropertyCount;
+ if (mBuffer.position() != estimatedFinalPosition) {
+ throw new IllegalStateException("Final position " + mBuffer.position()
+ + " != estimatedFinalPosition " + estimatedFinalPosition);
+ }
+ return this;
+ }
+
+ /**
+ * Sets the property with key to a double value.
+ *
+ * @param key
+ * @param value
+ * @return itself
+ */
+ public Item putDouble(String key, double value) {
+ final byte[] keyBytes = key.getBytes(MEDIAMETRICS_CHARSET);
+ final char propSize = (char) reserveProperty(keyBytes, 8 /* payloadSize */);
+ final int estimatedFinalPosition = mBuffer.position() + propSize;
+ mBuffer.putChar(propSize)
+ .put((byte) TYPE_DOUBLE)
+ .put(keyBytes).put((byte) 0) // key, zero terminated
+ .putDouble(value);
+ ++mPropertyCount;
+ if (mBuffer.position() != estimatedFinalPosition) {
+ throw new IllegalStateException("Final position " + mBuffer.position()
+ + " != estimatedFinalPosition " + estimatedFinalPosition);
+ }
+ return this;
+ }
+
+ /**
+ * Sets the property with key to a String value.
+ *
+ * @param key
+ * @param value
+ * @return itself
+ */
+ public Item putString(String key, String value) {
+ final byte[] keyBytes = key.getBytes(MEDIAMETRICS_CHARSET);
+ final byte[] valueBytes = value.getBytes(MEDIAMETRICS_CHARSET);
+ final char propSize = (char) reserveProperty(keyBytes, valueBytes.length + 1);
+ final int estimatedFinalPosition = mBuffer.position() + propSize;
+ mBuffer.putChar(propSize)
+ .put((byte) TYPE_CSTRING)
+ .put(keyBytes).put((byte) 0) // key, zero terminated
+ .put(valueBytes).put((byte) 0); // value, zero term.
+ ++mPropertyCount;
+ if (mBuffer.position() != estimatedFinalPosition) {
+ throw new IllegalStateException("Final position " + mBuffer.position()
+ + " != estimatedFinalPosition " + estimatedFinalPosition);
+ }
+ return this;
+ }
+
+ /**
+ * Sets the pid to the provided value.
+ *
+ * @param pid which can be -1 if the service is to fill it in from the calling info.
+ * @return itself
+ */
+ public Item setPid(int pid) {
+ mBuffer.putInt(mPidOffset, pid); // pid location in byte string.
+ return this;
+ }
+
+ /**
+ * Sets the uid to the provided value.
+ *
+ * The UID represents the client associated with the property. This must be the UID
+ * of the application if it comes from the application client.
+ *
+ * Trusted services are allowed to set the uid for a client-related item.
+ *
+ * @param uid which can be -1 if the service is to fill it in from calling info.
+ * @return itself
+ */
+ public Item setUid(int uid) {
+ mBuffer.putInt(mUidOffset, uid); // uid location in byte string.
+ return this;
+ }
+
+ /**
+ * Sets the timestamp to the provided value.
+ *
+ * The time is referenced by the Boottime obtained by SystemClock.elapsedRealtimeNanos().
+ * This should be associated with the occurrence of the event. It is recommended that
+ * the event be registered immediately when it occurs, and no later than 500ms
+ * (and certainly not in the future).
+ *
+ * @param timeNs which can be 0 if the service is to fill it in at the time of call.
+ * @return itself
+ */
+ public Item setTimestamp(long timeNs) {
+ mBuffer.putLong(mTimeNsOffset, timeNs); // time location in byte string.
+ return this;
+ }
+
+ /**
+ * Clears the properties and resets the time to 0.
+ *
+ * No other values are changed.
+ *
+ * @return itself
+ */
+ public Item clear() {
+ mBuffer.position(mPropertyStartOffset);
+ mBuffer.limit(mBuffer.capacity());
+ mBuffer.putLong(mTimeNsOffset, 0); // reset time.
+ mPropertyCount = 0;
+ return this;
+ }
+
+ /**
+ * Sends the item to the MediaMetrics service.
+ *
+ * The item properties are unchanged, hence record() may be called more than once
+ * to send the same item twice. Also, record() may be called without any properties.
+ *
+ * @return true if successful.
+ */
+ public boolean record() {
+ updateHeader();
+ return native_submit_bytebuffer(mBuffer, mBuffer.limit()) >= 0;
+ }
+
+ /**
+ * Converts the Item to a Bundle.
+ *
+ * This is primarily used as a test API for CTS.
+ *
+ * @return a Bundle with the keys set according to data in the Item's buffer.
+ */
+ @TestApi
+ public Bundle toBundle() {
+ updateHeader();
+
+ final ByteBuffer buffer = mBuffer.duplicate();
+ buffer.order(ByteOrder.nativeOrder()) // restore order property
+ .flip(); // convert from write buffer to read buffer
+
+ return toBundle(buffer);
+ }
+
+ // The following constants are used for tests to extract
+ // the content of the Bundle for CTS testing.
+ @TestApi
+ public static final String BUNDLE_TOTAL_SIZE = "_totalSize";
+ @TestApi
+ public static final String BUNDLE_HEADER_SIZE = "_headerSize";
+ @TestApi
+ public static final String BUNDLE_VERSION = "_version";
+ @TestApi
+ public static final String BUNDLE_KEY_SIZE = "_keySize";
+ @TestApi
+ public static final String BUNDLE_KEY = "_key";
+ @TestApi
+ public static final String BUNDLE_PID = "_pid";
+ @TestApi
+ public static final String BUNDLE_UID = "_uid";
+ @TestApi
+ public static final String BUNDLE_TIMESTAMP = "_timestamp";
+ @TestApi
+ public static final String BUNDLE_PROPERTY_COUNT = "_propertyCount";
+
+ /**
+ * Converts a buffer contents to a bundle
+ *
+ * This is primarily used as a test API for CTS.
+ *
+ * @param buffer contains the byte data serialized according to the byte string version.
+ * @return a Bundle with the keys set according to data in the buffer.
+ */
+ @TestApi
+ public static Bundle toBundle(ByteBuffer buffer) {
+ final Bundle bundle = new Bundle();
+
+ final int totalSize = buffer.getInt();
+ final int headerSize = buffer.getInt();
+ final char version = buffer.getChar();
+ final char keySize = buffer.getChar(); // includes zero termination, i.e. keyLength + 1
+
+ if (totalSize < 0 || headerSize < 0) {
+ throw new IllegalArgumentException("Item size cannot be > " + Integer.MAX_VALUE);
+ }
+ final String key;
+ if (keySize > 0) {
+ key = getStringFromBuffer(buffer, keySize);
+ } else {
+ throw new IllegalArgumentException("Illegal null key");
+ }
+
+ final int pid = buffer.getInt();
+ final int uid = buffer.getInt();
+ final long timestamp = buffer.getLong();
+
+ // Verify header size (depending on version).
+ final int headerRead = buffer.position();
+ if (version == 0) {
+ if (headerRead != headerSize) {
+ throw new IllegalArgumentException(
+ "Item key:" + key
+ + " headerRead:" + headerRead + " != headerSize:" + headerSize);
+ }
+ } else {
+ // future versions should only increase header size
+ // by adding to the end.
+ if (headerRead > headerSize) {
+ throw new IllegalArgumentException(
+ "Item key:" + key
+ + " headerRead:" + headerRead + " > headerSize:" + headerSize);
+ } else if (headerRead < headerSize) {
+ buffer.position(headerSize);
+ }
+ }
+
+ // Body always starts with properties.
+ final int propertyCount = buffer.getInt();
+ if (propertyCount < 0) {
+ throw new IllegalArgumentException(
+ "Cannot have more than " + Integer.MAX_VALUE + " properties");
+ }
+ bundle.putInt(BUNDLE_TOTAL_SIZE, totalSize);
+ bundle.putInt(BUNDLE_HEADER_SIZE, headerSize);
+ bundle.putChar(BUNDLE_VERSION, version);
+ bundle.putChar(BUNDLE_KEY_SIZE, keySize);
+ bundle.putString(BUNDLE_KEY, key);
+ bundle.putInt(BUNDLE_PID, pid);
+ bundle.putInt(BUNDLE_UID, uid);
+ bundle.putLong(BUNDLE_TIMESTAMP, timestamp);
+ bundle.putInt(BUNDLE_PROPERTY_COUNT, propertyCount);
+
+ for (int i = 0; i < propertyCount; ++i) {
+ final int initialBufferPosition = buffer.position();
+ final char propSize = buffer.getChar();
+ final byte type = buffer.get();
+
+ // Log.d(TAG, "(" + i + ") propSize:" + ((int)propSize) + " type:" + type);
+ final String propKey = getStringFromBuffer(buffer);
+ switch (type) {
+ case TYPE_INT32:
+ bundle.putInt(propKey, buffer.getInt());
+ break;
+ case TYPE_INT64:
+ bundle.putLong(propKey, buffer.getLong());
+ break;
+ case TYPE_DOUBLE:
+ bundle.putDouble(propKey, buffer.getDouble());
+ break;
+ case TYPE_CSTRING:
+ bundle.putString(propKey, getStringFromBuffer(buffer));
+ break;
+ case TYPE_NONE:
+ break; // ignore on Java side
+ case TYPE_RATE:
+ buffer.getLong(); // consume the first int64_t of rate
+ buffer.getLong(); // consume the second int64_t of rate
+ break; // ignore on Java side
+ default:
+ // These are unsupported types for version 0
+ // We ignore them if the version is greater than 0.
+ if (version == 0) {
+ throw new IllegalArgumentException(
+ "Property " + propKey + " has unsupported type " + type);
+ }
+ buffer.position(initialBufferPosition + propSize); // advance and skip
+ break;
+ }
+ final int deltaPosition = buffer.position() - initialBufferPosition;
+ if (deltaPosition != propSize) {
+ throw new IllegalArgumentException("propSize:" + propSize
+ + " != deltaPosition:" + deltaPosition);
+ }
+ }
+
+ final int finalPosition = buffer.position();
+ if (finalPosition != totalSize) {
+ throw new IllegalArgumentException("totalSize:" + totalSize
+ + " != finalPosition:" + finalPosition);
+ }
+ return bundle;
+ }
+
+ // Version 0 byte offsets for the header.
+ private static final int FORMAT_VERSION = 0;
+ private static final int TOTAL_SIZE_OFFSET = 0;
+ private static final int HEADER_SIZE_OFFSET = 4;
+ private static final int MINIMUM_PAYLOAD_SIZE = 4;
+ private final int mPidOffset; // computed in constructor
+ private final int mUidOffset; // computed in constructor
+ private final int mTimeNsOffset; // computed in constructor
+ private final int mPropertyCountOffset; // computed in constructor
+ private final int mPropertyStartOffset; // computed in constructor
+ private final int mHeaderSize; // computed in constructor
+
+ private final String mKey;
+
+ private ByteBuffer mBuffer; // may be reallocated if capacity is insufficient.
+ private int mPropertyCount = 0; // overflow not checked (mBuffer would overflow first).
+
+ private int reserveProperty(byte[] keyBytes, int payloadSize) {
+ final int keyLength = keyBytes.length;
+ if (keyLength > Character.MAX_VALUE) {
+ throw new IllegalStateException("property key too long "
+ + new String(keyBytes, MEDIAMETRICS_CHARSET));
+ }
+ if (payloadSize > Character.MAX_VALUE) {
+ throw new IllegalStateException("payload too large " + payloadSize);
+ }
+
+ // See the byte string property format above.
+ final int size = 2 /* length */
+ + 1 /* type */
+ + keyLength + 1 /* key length with zero termination */
+ + payloadSize; /* payload size */
+
+ if (size > Character.MAX_VALUE) {
+ throw new IllegalStateException("Item property "
+ + new String(keyBytes, MEDIAMETRICS_CHARSET) + " is too large to send");
+ }
+
+ if (mBuffer.remaining() < size) {
+ int newCapacity = mBuffer.position() + size;
+ if (newCapacity > Integer.MAX_VALUE >> 1) {
+ throw new IllegalStateException(
+ "Item memory requirements too large: " + newCapacity);
+ }
+ newCapacity <<= 1;
+ ByteBuffer buffer = ByteBuffer.allocateDirect(newCapacity);
+ buffer.order(ByteOrder.nativeOrder());
+
+ // Copy data from old buffer to new buffer.
+ mBuffer.flip();
+ buffer.put(mBuffer);
+
+ // set buffer to new buffer
+ mBuffer = buffer;
+ }
+ return size;
+ }
+
+ // Used for test
+ private static String getStringFromBuffer(ByteBuffer buffer) {
+ return getStringFromBuffer(buffer, Integer.MAX_VALUE);
+ }
+
+ // Used for test
+ private static String getStringFromBuffer(ByteBuffer buffer, int size) {
+ int i = buffer.position();
+ int limit = buffer.limit();
+ if (size < Integer.MAX_VALUE - i && i + size < limit) {
+ limit = i + size;
+ }
+ for (; i < limit; ++i) {
+ if (buffer.get(i) == 0) {
+ final int newPosition = i + 1;
+ if (size != Integer.MAX_VALUE && newPosition - buffer.position() != size) {
+ throw new IllegalArgumentException("chars consumed at " + i + ": "
+ + (newPosition - buffer.position()) + " != size: " + size);
+ }
+ final String found;
+ if (buffer.hasArray()) {
+ found = new String(
+ buffer.array(), buffer.position() + buffer.arrayOffset(),
+ i - buffer.position(), MEDIAMETRICS_CHARSET);
+ buffer.position(newPosition);
+ } else {
+ final byte[] array = new byte[i - buffer.position()];
+ buffer.get(array);
+ found = new String(array, MEDIAMETRICS_CHARSET);
+ buffer.get(); // remove 0.
+ }
+ return found;
+ }
+ }
+ throw new IllegalArgumentException(
+ "No zero termination found in string position: "
+ + buffer.position() + " end: " + i);
+ }
+
+ /**
+ * May be called multiple times - just makes the header consistent with the current
+ * properties written.
+ */
+ private void updateHeader() {
+ // Buffer sized properly in constructor.
+ mBuffer.putInt(TOTAL_SIZE_OFFSET, mBuffer.position()) // set total length
+ .putInt(mPropertyCountOffset, (char) mPropertyCount); // set number of properties
+ }
+ }
+
+ private static native int native_submit_bytebuffer(@NonNull ByteBuffer buffer, int length);
+}
diff --git a/media/java/android/media/MediaMuxer.java b/media/java/android/media/MediaMuxer.java
index 0fb392bfc0fe..14a48d72f9bb 100644
--- a/media/java/android/media/MediaMuxer.java
+++ b/media/java/android/media/MediaMuxer.java
@@ -18,8 +18,7 @@ package android.media;
import android.annotation.IntDef;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
-import android.media.MediaCodec;
+import android.compat.annotation.UnsupportedAppUsage;
import android.media.MediaCodec.BufferInfo;
import dalvik.system.CloseGuard;
diff --git a/media/java/android/media/MediaPlayer.java b/media/java/android/media/MediaPlayer.java
index 7d107ddbe978..71c97534c216 100644
--- a/media/java/android/media/MediaPlayer.java
+++ b/media/java/android/media/MediaPlayer.java
@@ -19,8 +19,8 @@ package android.media;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityThread;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.Context;
diff --git a/media/java/android/media/MediaRecorder.java b/media/java/android/media/MediaRecorder.java
index abb820645ae7..4198d7917932 100644
--- a/media/java/android/media/MediaRecorder.java
+++ b/media/java/android/media/MediaRecorder.java
@@ -23,8 +23,8 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityThread;
+import android.compat.annotation.UnsupportedAppUsage;
import android.hardware.Camera;
import android.os.Build;
import android.os.Handler;
diff --git a/media/java/android/media/MediaRoute2ProviderInfo.java b/media/java/android/media/MediaRoute2ProviderInfo.java
index 4f203dea49f5..b5de88ae1da9 100644
--- a/media/java/android/media/MediaRoute2ProviderInfo.java
+++ b/media/java/android/media/MediaRoute2ProviderInfo.java
@@ -51,9 +51,8 @@ public final class MediaRoute2ProviderInfo implements Parcelable {
private final ArrayMap<String, MediaRoute2Info> mRoutes;
MediaRoute2ProviderInfo(@NonNull Builder builder) {
- if (builder == null) {
- throw new NullPointerException("Builder must not be null.");
- }
+ Objects.requireNonNull(builder, "builder must not be null.");
+
mUniqueId = builder.mUniqueId;
mRoutes = builder.mRoutes;
}
diff --git a/media/java/android/media/MediaRouter.java b/media/java/android/media/MediaRouter.java
index d72231f40dcf..9837e1cc62b3 100644
--- a/media/java/android/media/MediaRouter.java
+++ b/media/java/android/media/MediaRouter.java
@@ -22,8 +22,8 @@ import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityThread;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
diff --git a/media/java/android/media/MediaRouter2.java b/media/java/android/media/MediaRouter2.java
index 3e6f4c01873c..bad0ef4104fe 100644
--- a/media/java/android/media/MediaRouter2.java
+++ b/media/java/android/media/MediaRouter2.java
@@ -23,6 +23,7 @@ import static java.lang.annotation.RetentionPolicy.SOURCE;
import android.annotation.CallbackExecutor;
import android.annotation.IntDef;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
@@ -51,7 +52,6 @@ import java.util.concurrent.Executor;
* @hide
*/
public class MediaRouter2 {
-
/** @hide */
@Retention(SOURCE)
@IntDef(value = {
@@ -102,13 +102,11 @@ public class MediaRouter2 {
new CopyOnWriteArrayList<>();
private final String mPackageName;
+ @GuardedBy("sLock")
private final Map<String, MediaRoute2Info> mRoutes = new HashMap<>();
- //TODO: Use a lock for this to cover the below use case
- // mRouter.setControlCategories(...);
- // routes = mRouter.getRoutes();
- // The current implementation returns empty list
- private volatile List<String> mControlCategories = Collections.emptyList();
+ @GuardedBy("sLock")
+ private List<String> mControlCategories = Collections.emptyList();
private MediaRoute2Info mSelectedRoute;
@GuardedBy("sLock")
@@ -117,7 +115,9 @@ public class MediaRouter2 {
private Client2 mClient;
final Handler mHandler;
- volatile List<MediaRoute2Info> mFilteredRoutes = Collections.emptyList();
+ @GuardedBy("sLock")
+ private boolean mShouldUpdateRoutes;
+ private volatile List<MediaRoute2Info> mFilteredRoutes = Collections.emptyList();
/**
* Gets an instance of the media router associated with the context.
@@ -171,8 +171,7 @@ public class MediaRouter2 {
/**
* Registers a callback to discover routes and to receive events when they change.
* <p>
- * If you register the same callback twice or more, the previous arguments will be overwritten
- * with the new arguments.
+ * If you register the same callback twice or more, it will be ignored.
* </p>
*/
public void registerCallback(@NonNull @CallbackExecutor Executor executor,
@@ -180,18 +179,10 @@ public class MediaRouter2 {
Objects.requireNonNull(executor, "executor must not be null");
Objects.requireNonNull(callback, "callback must not be null");
- CallbackRecord record;
- // This is required to prevent adding the same callback twice.
- synchronized (mCallbackRecords) {
- final int index = findCallbackRecordIndexLocked(callback);
- if (index < 0) {
- record = new CallbackRecord(callback);
- mCallbackRecords.add(record);
- } else {
- record = mCallbackRecords.get(index);
- }
- record.mExecutor = executor;
- record.mFlags = flags;
+ CallbackRecord record = new CallbackRecord(callback, executor, flags);
+ if (!mCallbackRecords.addIfAbsent(record)) {
+ Log.w(TAG, "Ignoring the same callback");
+ return;
}
synchronized (sLock) {
@@ -206,8 +197,6 @@ public class MediaRouter2 {
}
}
}
- //TODO: Is it thread-safe?
- record.notifyRoutes();
//TODO: Update discovery request here.
}
@@ -222,23 +211,20 @@ public class MediaRouter2 {
public void unregisterCallback(@NonNull Callback callback) {
Objects.requireNonNull(callback, "callback must not be null");
- synchronized (mCallbackRecords) {
- final int index = findCallbackRecordIndexLocked(callback);
- if (index < 0) {
- Log.w(TAG, "Ignoring to remove unknown callback. " + callback);
- return;
- }
- mCallbackRecords.remove(index);
- synchronized (sLock) {
- if (mCallbackRecords.size() == 0 && mClient != null) {
- try {
- mMediaRouterService.unregisterClient2(mClient);
- } catch (RemoteException ex) {
- Log.e(TAG, "Unable to unregister media router.", ex);
- }
- //TODO: Clean up mRoutes. (onHandler?)
- mClient = null;
+ if (!mCallbackRecords.remove(new CallbackRecord(callback, null, 0))) {
+ Log.w(TAG, "Ignoring unknown callback");
+ return;
+ }
+
+ synchronized (sLock) {
+ if (mCallbackRecords.size() == 0 && mClient != null) {
+ try {
+ mMediaRouterService.unregisterClient2(mClient);
+ } catch (RemoteException ex) {
+ Log.e(TAG, "Unable to unregister media router.", ex);
}
+ //TODO: Clean up mRoutes. (onHandler?)
+ mClient = null;
}
}
}
@@ -246,26 +232,52 @@ public class MediaRouter2 {
//TODO(b/139033746): Rename "Control Category" when it's finalized.
/**
* Sets the control categories of the application.
- * Routes that support at least one of the given control categories only exists and are handled
+ * Routes that support at least one of the given control categories are handled
* by the media router.
*/
public void setControlCategories(@NonNull Collection<String> controlCategories) {
Objects.requireNonNull(controlCategories, "control categories must not be null");
- // To ensure invoking callbacks correctly according to control categories
- mHandler.sendMessage(obtainMessage(MediaRouter2::setControlCategoriesOnHandler,
- MediaRouter2.this, new ArrayList<>(controlCategories)));
+ List<String> newControlCategories = new ArrayList<>(controlCategories);
+
+ synchronized (sLock) {
+ mShouldUpdateRoutes = true;
+
+ // invoke callbacks due to control categories change
+ handleControlCategoriesChangedLocked(newControlCategories);
+ if (mClient != null) {
+ try {
+ mMediaRouterService.setControlCategories(mClient, mControlCategories);
+ } catch (RemoteException ex) {
+ Log.e(TAG, "Unable to set control categories.", ex);
+ }
+ }
+ }
}
/**
* Gets the unmodifiable list of {@link MediaRoute2Info routes} currently
* known to the media router.
+ * Please note that the list can be changed before callbacks are invoked.
*
* @return the list of routes that support at least one of the control categories set by
* the application
*/
@NonNull
public List<MediaRoute2Info> getRoutes() {
+ synchronized (sLock) {
+ if (mShouldUpdateRoutes) {
+ mShouldUpdateRoutes = false;
+
+ List<MediaRoute2Info> filteredRoutes = new ArrayList<>();
+ for (MediaRoute2Info route : mRoutes.values()) {
+ if (route.supportsControlCategory(mControlCategories)) {
+ filteredRoutes.add(route);
+ }
+ }
+ mFilteredRoutes = Collections.unmodifiableList(filteredRoutes);
+ }
+ }
return mFilteredRoutes;
}
@@ -379,43 +391,16 @@ public class MediaRouter2 {
}
}
- @GuardedBy("mCallbackRecords")
- private int findCallbackRecordIndexLocked(Callback callback) {
- final int count = mCallbackRecords.size();
- for (int i = 0; i < count; i++) {
- CallbackRecord callbackRecord = mCallbackRecords.get(i);
- if (callbackRecord.mCallback == callback) {
- return i;
- }
- }
- return -1;
- }
-
- private void setControlCategoriesOnHandler(List<String> newControlCategories) {
- List<String> prevControlCategories = mControlCategories;
+ private void handleControlCategoriesChangedLocked(List<String> newControlCategories) {
List<MediaRoute2Info> addedRoutes = new ArrayList<>();
List<MediaRoute2Info> removedRoutes = new ArrayList<>();
- List<MediaRoute2Info> filteredRoutes = new ArrayList<>();
+ List<String> prevControlCategories = mControlCategories;
mControlCategories = newControlCategories;
- Client2 client;
- synchronized (sLock) {
- client = mClient;
- }
- if (client != null) {
- try {
- mMediaRouterService.setControlCategories(client, mControlCategories);
- } catch (RemoteException ex) {
- Log.e(TAG, "Unable to set control categories.", ex);
- }
- }
for (MediaRoute2Info route : mRoutes.values()) {
boolean preSupported = route.supportsControlCategory(prevControlCategories);
boolean postSupported = route.supportsControlCategory(newControlCategories);
- if (postSupported) {
- filteredRoutes.add(route);
- }
if (preSupported == postSupported) {
continue;
}
@@ -425,13 +410,14 @@ public class MediaRouter2 {
addedRoutes.add(route);
}
}
- mFilteredRoutes = Collections.unmodifiableList(filteredRoutes);
if (removedRoutes.size() > 0) {
- notifyRoutesRemoved(removedRoutes);
+ mHandler.sendMessage(obtainMessage(MediaRouter2::notifyRoutesRemoved,
+ MediaRouter2.this, removedRoutes));
}
if (addedRoutes.size() > 0) {
- notifyRoutesAdded(addedRoutes);
+ mHandler.sendMessage(obtainMessage(MediaRouter2::notifyRoutesAdded,
+ MediaRouter2.this, addedRoutes));
}
}
@@ -441,42 +427,47 @@ public class MediaRouter2 {
// 2) Call onRouteSelected(system_route, reason_fallback) if previously selected route
// does not exist anymore. => We may need 'boolean MediaRoute2Info#isSystemRoute()'.
List<MediaRoute2Info> addedRoutes = new ArrayList<>();
- for (MediaRoute2Info route : routes) {
- mRoutes.put(route.getUniqueId(), route);
- if (route.supportsControlCategory(mControlCategories)) {
- addedRoutes.add(route);
+ synchronized (sLock) {
+ for (MediaRoute2Info route : routes) {
+ mRoutes.put(route.getUniqueId(), route);
+ if (route.supportsControlCategory(mControlCategories)) {
+ addedRoutes.add(route);
+ }
}
+ mShouldUpdateRoutes = true;
}
if (addedRoutes.size() > 0) {
- refreshFilteredRoutes();
notifyRoutesAdded(addedRoutes);
}
}
void removeRoutesOnHandler(List<MediaRoute2Info> routes) {
List<MediaRoute2Info> removedRoutes = new ArrayList<>();
- for (MediaRoute2Info route : routes) {
- mRoutes.remove(route.getUniqueId());
- if (route.supportsControlCategory(mControlCategories)) {
- removedRoutes.add(route);
+ synchronized (sLock) {
+ for (MediaRoute2Info route : routes) {
+ mRoutes.remove(route.getUniqueId());
+ if (route.supportsControlCategory(mControlCategories)) {
+ removedRoutes.add(route);
+ }
}
+ mShouldUpdateRoutes = true;
}
if (removedRoutes.size() > 0) {
- refreshFilteredRoutes();
notifyRoutesRemoved(removedRoutes);
}
}
void changeRoutesOnHandler(List<MediaRoute2Info> routes) {
List<MediaRoute2Info> changedRoutes = new ArrayList<>();
- for (MediaRoute2Info route : routes) {
- mRoutes.put(route.getUniqueId(), route);
- if (route.supportsControlCategory(mControlCategories)) {
- changedRoutes.add(route);
+ synchronized (sLock) {
+ for (MediaRoute2Info route : routes) {
+ mRoutes.put(route.getUniqueId(), route);
+ if (route.supportsControlCategory(mControlCategories)) {
+ changedRoutes.add(route);
+ }
}
}
if (changedRoutes.size() > 0) {
- refreshFilteredRoutes();
notifyRoutesChanged(changedRoutes);
}
}
@@ -500,17 +491,6 @@ public class MediaRouter2 {
notifyRouteSelected(route, reason, controlHints);
}
- private void refreshFilteredRoutes() {
- List<MediaRoute2Info> filteredRoutes = new ArrayList<>();
-
- for (MediaRoute2Info route : mRoutes.values()) {
- if (route.supportsControlCategory(mControlCategories)) {
- filteredRoutes.add(route);
- }
- }
- mFilteredRoutes = Collections.unmodifiableList(filteredRoutes);
- }
-
private void notifyRoutesAdded(List<MediaRoute2Info> routes) {
for (CallbackRecord record: mCallbackRecords) {
record.mExecutor.execute(
@@ -544,13 +524,16 @@ public class MediaRouter2 {
*/
public static class Callback {
/**
- * Called when routes are added.
+ * Called when routes are added. Whenever you registers a callback, this will
+ * be invoked with known routes.
+ *
* @param routes the list of routes that have been added. It's never empty.
*/
public void onRoutesAdded(@NonNull List<MediaRoute2Info> routes) {}
/**
* Called when routes are removed.
+ *
* @param routes the list of routes that have been removed. It's never empty.
*/
public void onRoutesRemoved(@NonNull List<MediaRoute2Info> routes) {}
@@ -569,6 +552,7 @@ public class MediaRouter2 {
/**
* Called when a route is selected. Exactly one route can be selected at a time.
+ *
* @param route the selected route.
* @param reason the reason why the route is selected.
* @param controlHints An optional bundle of provider-specific arguments which may be
@@ -587,16 +571,26 @@ public class MediaRouter2 {
public Executor mExecutor;
public int mFlags;
- CallbackRecord(@NonNull Callback callback) {
+ CallbackRecord(@NonNull Callback callback, @Nullable Executor executor, int flags) {
mCallback = callback;
+ mExecutor = executor;
+ mFlags = flags;
}
- void notifyRoutes() {
- final List<MediaRoute2Info> routes = mFilteredRoutes;
- // notify only when bound to media router service.
- if (routes.size() > 0) {
- mExecutor.execute(() -> mCallback.onRoutesAdded(routes));
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
}
+ if (!(obj instanceof CallbackRecord)) {
+ return false;
+ }
+ return mCallback == ((CallbackRecord) obj).mCallback;
+ }
+
+ @Override
+ public int hashCode() {
+ return mCallback.hashCode();
}
}
diff --git a/media/java/android/media/MediaRouter2Manager.java b/media/java/android/media/MediaRouter2Manager.java
index d56dd11fb8f2..502538d375ac 100644
--- a/media/java/android/media/MediaRouter2Manager.java
+++ b/media/java/android/media/MediaRouter2Manager.java
@@ -57,7 +57,7 @@ public class MediaRouter2Manager {
private Client mClient;
private final IMediaRouterService mMediaRouterService;
final Handler mHandler;
- final List<CallbackRecord> mCallbackRecords = new CopyOnWriteArrayList<>();
+ final CopyOnWriteArrayList<CallbackRecord> mCallbackRecords = new CopyOnWriteArrayList<>();
private final Object mRoutesLock = new Object();
@GuardedBy("mRoutesLock")
@@ -99,14 +99,10 @@ public class MediaRouter2Manager {
Objects.requireNonNull(executor, "executor must not be null");
Objects.requireNonNull(callback, "callback must not be null");
- CallbackRecord callbackRecord;
- synchronized (mCallbackRecords) {
- if (findCallbackRecordIndexLocked(callback) >= 0) {
- Log.w(TAG, "Ignoring to add the same callback twice.");
- return;
- }
- callbackRecord = new CallbackRecord(executor, callback);
- mCallbackRecords.add(callbackRecord);
+ CallbackRecord callbackRecord = new CallbackRecord(executor, callback);
+ if (!mCallbackRecords.addIfAbsent(callbackRecord)) {
+ Log.w(TAG, "Ignoring to add the same callback twice.");
+ return;
}
synchronized (sLock) {
@@ -118,8 +114,6 @@ public class MediaRouter2Manager {
} catch (RemoteException ex) {
Log.e(TAG, "Unable to register media router manager.", ex);
}
- } else {
- callbackRecord.notifyRoutes();
}
}
}
@@ -132,36 +126,23 @@ public class MediaRouter2Manager {
public void unregisterCallback(@NonNull Callback callback) {
Objects.requireNonNull(callback, "callback must not be null");
- synchronized (mCallbackRecords) {
- final int index = findCallbackRecordIndexLocked(callback);
- if (index < 0) {
- Log.w(TAG, "Ignore removing unknown callback. " + callback);
- return;
- }
- mCallbackRecords.remove(index);
- synchronized (sLock) {
- if (mCallbackRecords.size() == 0 && mClient != null) {
- try {
- mMediaRouterService.unregisterManager(mClient);
- } catch (RemoteException ex) {
- Log.e(TAG, "Unable to unregister media router manager", ex);
- }
- //TODO: clear mRoutes?
- mClient = null;
- }
- }
+ if (!mCallbackRecords.remove(new CallbackRecord(null, callback))) {
+ Log.w(TAG, "Ignore removing unknown callback. " + callback);
+ return;
}
- }
- @GuardedBy("mCallbackRecords")
- private int findCallbackRecordIndexLocked(Callback callback) {
- final int count = mCallbackRecords.size();
- for (int i = 0; i < count; i++) {
- if (mCallbackRecords.get(i).mCallback == callback) {
- return i;
+ synchronized (sLock) {
+ if (mCallbackRecords.size() == 0 && mClient != null) {
+ try {
+ mMediaRouterService.unregisterManager(mClient);
+ } catch (RemoteException ex) {
+ Log.e(TAG, "Unable to unregister media router manager", ex);
+ }
+ //TODO: clear mRoutes?
+ mClient = null;
+ mControlCategoryMap.clear();
}
}
- return -1;
}
//TODO: Use cache not to create array. For now, it's unclear when to purge the cache.
@@ -187,7 +168,6 @@ public class MediaRouter2Manager {
}
}
}
- //TODO: Should we cache this?
return routes;
}
@@ -342,10 +322,14 @@ public class MediaRouter2Manager {
}
void updateControlCategories(String packageName, List<String> categories) {
- mControlCategoryMap.put(packageName, categories);
+ List<String> prevCategories = mControlCategoryMap.put(packageName, categories);
+ if ((prevCategories == null && categories.size() == 0)
+ || Objects.equals(categories, prevCategories)) {
+ return;
+ }
for (CallbackRecord record : mCallbackRecords) {
record.mExecutor.execute(
- () -> record.mCallback.onControlCategoriesChanged(packageName));
+ () -> record.mCallback.onControlCategoriesChanged(packageName, categories));
}
}
@@ -386,8 +370,10 @@ public class MediaRouter2Manager {
* Called when the control categories of an app is changed.
*
* @param packageName the package name of the application
+ * @param controlCategories the list of control categories set by an application.
*/
- public void onControlCategoriesChanged(@NonNull String packageName) {}
+ public void onControlCategoriesChanged(@NonNull String packageName,
+ @NonNull List<String> controlCategories) {}
}
final class CallbackRecord {
@@ -399,14 +385,20 @@ public class MediaRouter2Manager {
mCallback = callback;
}
- void notifyRoutes() {
- List<MediaRoute2Info> routes;
- synchronized (mRoutesLock) {
- routes = new ArrayList<>(mRoutes.values());
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
}
- if (routes.size() > 0) {
- mExecutor.execute(() -> mCallback.onRoutesAdded(routes));
+ if (!(obj instanceof CallbackRecord)) {
+ return false;
}
+ return mCallback == ((CallbackRecord) obj).mCallback;
+ }
+
+ @Override
+ public int hashCode() {
+ return mCallback.hashCode();
}
}
diff --git a/media/java/android/media/MediaScanner.java b/media/java/android/media/MediaScanner.java
index ca96c9ab5670..aae2606bcf5e 100644
--- a/media/java/android/media/MediaScanner.java
+++ b/media/java/android/media/MediaScanner.java
@@ -16,7 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
diff --git a/media/java/android/media/MediaScannerConnection.java b/media/java/android/media/MediaScannerConnection.java
index 515f6a8ce8a2..40e90731f2a2 100644
--- a/media/java/android/media/MediaScannerConnection.java
+++ b/media/java/android/media/MediaScannerConnection.java
@@ -19,6 +19,7 @@ package android.media;
import android.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.ContentProviderClient;
+import android.content.ContentResolver;
import android.content.Context;
import android.content.ServiceConnection;
import android.net.Uri;
@@ -197,7 +198,7 @@ public class MediaScannerConnection implements ServiceConnection {
private static Uri scanFileQuietly(ContentProviderClient client, File file) {
Uri uri = null;
try {
- uri = MediaStore.scanFile(client, file.getCanonicalFile());
+ uri = MediaStore.scanFile(ContentResolver.wrap(client), file.getCanonicalFile());
Log.d(TAG, "Scanned " + file + " to " + uri);
} catch (Exception e) {
Log.w(TAG, "Failed to scan " + file + ": " + e);
diff --git a/media/java/android/media/Metadata.java b/media/java/android/media/Metadata.java
index 792a2ba678fd..ef17073654a6 100644
--- a/media/java/android/media/Metadata.java
+++ b/media/java/android/media/Metadata.java
@@ -16,7 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.util.Log;
import android.util.MathUtils;
diff --git a/media/java/android/media/MicrophoneInfo.java b/media/java/android/media/MicrophoneInfo.java
index f805975d53b0..876628fefff4 100644
--- a/media/java/android/media/MicrophoneInfo.java
+++ b/media/java/android/media/MicrophoneInfo.java
@@ -18,7 +18,7 @@ package android.media;
import android.annotation.IntDef;
import android.annotation.NonNull;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.util.Pair;
import java.lang.annotation.Retention;
diff --git a/media/java/android/media/PlaybackParams.java b/media/java/android/media/PlaybackParams.java
index b4325b6ea53d..f24f831d0333 100644
--- a/media/java/android/media/PlaybackParams.java
+++ b/media/java/android/media/PlaybackParams.java
@@ -18,7 +18,7 @@ package android.media;
import android.annotation.IntDef;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/media/java/android/media/RemoteControlClient.java b/media/java/android/media/RemoteControlClient.java
index 325420b06122..c5fd3c30236d 100644
--- a/media/java/android/media/RemoteControlClient.java
+++ b/media/java/android/media/RemoteControlClient.java
@@ -16,8 +16,8 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
import android.app.PendingIntent;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
diff --git a/media/java/android/media/RemoteController.java b/media/java/android/media/RemoteController.java
index f70963a982e4..9e48f1e05391 100644
--- a/media/java/android/media/RemoteController.java
+++ b/media/java/android/media/RemoteController.java
@@ -16,8 +16,8 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityManager;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.graphics.Bitmap;
diff --git a/media/java/android/media/RemoteDisplay.java b/media/java/android/media/RemoteDisplay.java
index 2be206f2f462..e529af9da935 100644
--- a/media/java/android/media/RemoteDisplay.java
+++ b/media/java/android/media/RemoteDisplay.java
@@ -16,12 +16,12 @@
package android.media;
-import dalvik.system.CloseGuard;
-
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Handler;
import android.view.Surface;
+import dalvik.system.CloseGuard;
+
/**
* Listens for Wifi remote display connections managed by the media server.
*
diff --git a/media/java/android/media/RemoteDisplayState.java b/media/java/android/media/RemoteDisplayState.java
index 2f4ace0c8fdd..fed361a960e6 100644
--- a/media/java/android/media/RemoteDisplayState.java
+++ b/media/java/android/media/RemoteDisplayState.java
@@ -16,7 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
diff --git a/media/java/android/media/Ringtone.java b/media/java/android/media/Ringtone.java
index eb680c8377f4..d35bc4176cb3 100644
--- a/media/java/android/media/Ringtone.java
+++ b/media/java/android/media/Ringtone.java
@@ -17,7 +17,7 @@
package android.media;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.Context;
diff --git a/media/java/android/media/RingtoneManager.java b/media/java/android/media/RingtoneManager.java
index 9064e6891be6..d058243a6fcb 100644
--- a/media/java/android/media/RingtoneManager.java
+++ b/media/java/android/media/RingtoneManager.java
@@ -23,9 +23,9 @@ import android.annotation.RequiresPermission;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.SystemApi;
-import android.annotation.UnsupportedAppUsage;
import android.annotation.WorkerThread;
import android.app.Activity;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
@@ -908,7 +908,7 @@ public class RingtoneManager {
}
// Tell MediaScanner about the new file. Wait for it to assign a {@link Uri}.
- return MediaStore.scanFile(mContext, outFile);
+ return MediaStore.scanFile(mContext.getContentResolver(), outFile);
}
private static final String getExternalDirectoryForType(final int type) {
diff --git a/media/java/android/media/RouteSessionController.java b/media/java/android/media/RouteSessionController.java
new file mode 100644
index 000000000000..5ff721837573
--- /dev/null
+++ b/media/java/android/media/RouteSessionController.java
@@ -0,0 +1,208 @@
+/*
+ * Copyright 2019 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.media;
+
+import android.annotation.NonNull;
+
+import com.android.internal.annotations.GuardedBy;
+
+import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
+
+/**
+ * A class to control media route session in media route provider.
+ * For example, adding/removing/transferring routes to session can be done through this class.
+ * Instances are created by {@link MediaRouter2}.
+ *
+ * TODO: When session is introduced, change Javadoc of all methods/classes by using [@link Session].
+ *
+ * @hide
+ */
+public class RouteSessionController {
+ private final int mSessionId;
+ private final String mCategory;
+ private final Object mLock = new Object();
+
+ @GuardedBy("mLock")
+ private final CopyOnWriteArrayList<CallbackRecord> mCallbackRecords =
+ new CopyOnWriteArrayList<>();
+
+ private volatile boolean mIsReleased;
+
+ /**
+ * @param sessionId the ID of the session.
+ * @param category The category of media routes that the session includes.
+ */
+ RouteSessionController(int sessionId, @NonNull String category) {
+ mSessionId = sessionId;
+ mCategory = category;
+ }
+
+ /**
+ * @return the ID of this controller
+ */
+ public int getSessionId() {
+ return mSessionId;
+ }
+
+ /**
+ * @return the category of routes that the session includes.
+ */
+ @NonNull
+ public String getCategory() {
+ return mCategory;
+ }
+
+ /**
+ * @return the list of currently connected routes
+ */
+ @NonNull
+ public List<MediaRoute2Info> getRoutes() {
+ // TODO: Implement this when SessionInfo is introduced.
+ return null;
+ }
+
+ /**
+ * Returns true if the session is released, false otherwise.
+ * If it is released, then all other getters from this instance may return invalid values.
+ * Also, any operations to this instance will be ignored once released.
+ *
+ * @see #release
+ * @see Callback#onReleased
+ */
+ public boolean isReleased() {
+ return mIsReleased;
+ }
+
+ /**
+ * Add routes to the remote session.
+ *
+ * @see #getRoutes()
+ * @see Callback#onSessionInfoChanged
+ */
+ public void addRoutes(List<MediaRoute2Info> routes) {
+ // TODO: Implement this when the actual connection logic is implemented.
+ }
+
+ /**
+ * Remove routes from this session. Media may be stopped on those devices.
+ * Route removal requests that are not currently in {@link #getRoutes()} will be ignored.
+ *
+ * @see #getRoutes()
+ * @see Callback#onSessionInfoChanged
+ */
+ public void removeRoutes(List<MediaRoute2Info> routes) {
+ // TODO: Implement this when the actual connection logic is implemented.
+ }
+
+ /**
+ * Registers a {@link Callback} for monitoring route changes.
+ * If the same callback is registered previously, previous executor will be overwritten with the
+ * new one.
+ */
+ public void registerCallback(Executor executor, Callback callback) {
+ if (mIsReleased) {
+ return;
+ }
+ Objects.requireNonNull(executor, "executor must not be null");
+ Objects.requireNonNull(callback, "callback must not be null");
+
+ synchronized (mLock) {
+ CallbackRecord recordWithSameCallback = null;
+ for (CallbackRecord record : mCallbackRecords) {
+ if (callback == record.mCallback) {
+ recordWithSameCallback = record;
+ break;
+ }
+ }
+
+ if (recordWithSameCallback != null) {
+ recordWithSameCallback.mExecutor = executor;
+ } else {
+ mCallbackRecords.add(new CallbackRecord(executor, callback));
+ }
+ }
+ }
+
+ /**
+ * Unregisters a previously registered {@link Callback}.
+ */
+ public void unregisterCallback(Callback callback) {
+ Objects.requireNonNull(callback, "callback must not be null");
+
+ synchronized (mLock) {
+ CallbackRecord recordToRemove = null;
+ for (CallbackRecord record : mCallbackRecords) {
+ if (callback == record.mCallback) {
+ recordToRemove = record;
+ break;
+ }
+ }
+
+ if (recordToRemove != null) {
+ mCallbackRecords.remove(recordToRemove);
+ }
+ }
+ }
+
+ /**
+ * Release this session.
+ * Any operation on this session after calling this method will be ignored.
+ *
+ * @param stopMedia Should the device where the media is played
+ * be stopped after this session is released.
+ */
+ public void release(boolean stopMedia) {
+ mIsReleased = true;
+ mCallbackRecords.clear();
+ // TODO: Use stopMedia variable when the actual connection logic is implemented.
+ }
+
+ /**
+ * Callback class for getting updates on routes and session release.
+ */
+ public static class Callback {
+
+ /**
+ * Called when the session info has changed.
+ * TODO: When SessionInfo is introduced, uncomment below argument.
+ */
+ void onSessionInfoChanged(/* SessionInfo info */) {}
+
+ /**
+ * Called when the session is released. Session can be released by the controller using
+ * {@link #release(boolean)}, or by the {@link MediaRoute2ProviderService} itself.
+ * One can do clean-ups here.
+ *
+ * TODO: When SessionInfo is introduced, change the javadoc of releasing session on
+ * provider side.
+ */
+ void onReleased(int reason, boolean shouldStop) {}
+ }
+
+ private class CallbackRecord {
+ public final Callback mCallback;
+ public Executor mExecutor;
+
+ CallbackRecord(@NonNull Executor executor, @NonNull Callback callback) {
+ mExecutor = executor;
+ mCallback = callback;
+ }
+ }
+}
diff --git a/media/java/android/media/RouteSessionInfo.aidl b/media/java/android/media/RouteSessionInfo.aidl
new file mode 100644
index 000000000000..fb5d836da98e
--- /dev/null
+++ b/media/java/android/media/RouteSessionInfo.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright 2019 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.media;
+
+parcelable RouteSessionInfo;
diff --git a/media/java/android/media/RouteSessionInfo.java b/media/java/android/media/RouteSessionInfo.java
new file mode 100644
index 000000000000..0878e6b31ec6
--- /dev/null
+++ b/media/java/android/media/RouteSessionInfo.java
@@ -0,0 +1,300 @@
+/*
+ * Copyright 2019 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.media;
+
+import android.annotation.NonNull;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.text.TextUtils;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * Describes a route session that is made when a media route is selected.
+ * @hide
+ */
+public class RouteSessionInfo implements Parcelable {
+ @NonNull
+ public static final Creator<RouteSessionInfo> CREATOR =
+ new Creator<RouteSessionInfo>() {
+ @Override
+ public RouteSessionInfo createFromParcel(Parcel in) {
+ return new RouteSessionInfo(in);
+ }
+ @Override
+ public RouteSessionInfo[] newArray(int size) {
+ return new RouteSessionInfo[size];
+ }
+ };
+
+ final int mSessionId;
+ final String mPackageName;
+ final String mControlCategory;
+ final List<String> mSelectedRoutes;
+ final List<String> mDeselectableRoutes;
+ final List<String> mGroupableRoutes;
+ final List<String> mTransferrableRoutes;
+
+ RouteSessionInfo(@NonNull Builder builder) {
+ Objects.requireNonNull(builder, "builder must not be null.");
+
+ mSessionId = builder.mSessionId;
+ mPackageName = builder.mPackageName;
+ mControlCategory = builder.mControlCategory;
+
+ mSelectedRoutes = Collections.unmodifiableList(builder.mSelectedRoutes);
+ mDeselectableRoutes = Collections.unmodifiableList(builder.mDeselectableRoutes);
+ mGroupableRoutes = Collections.unmodifiableList(builder.mGroupableRoutes);
+ mTransferrableRoutes = Collections.unmodifiableList(builder.mTransferrableRoutes);
+ }
+
+ RouteSessionInfo(@NonNull Parcel src) {
+ Objects.requireNonNull(src, "src must not be null.");
+
+ mSessionId = src.readInt();
+ mPackageName = ensureString(src.readString());
+ mControlCategory = ensureString(src.readString());
+
+ mSelectedRoutes = ensureList(src.createStringArrayList());
+ mDeselectableRoutes = ensureList(src.createStringArrayList());
+ mGroupableRoutes = ensureList(src.createStringArrayList());
+ mTransferrableRoutes = ensureList(src.createStringArrayList());
+ }
+
+ private static String ensureString(String str) {
+ if (str != null) {
+ return str;
+ }
+ return "";
+ }
+
+ private static <T> List<T> ensureList(List<? extends T> list) {
+ if (list != null) {
+ return Collections.unmodifiableList(list);
+ }
+ return Collections.emptyList();
+ }
+
+ /**
+ * Returns whether the session info is valid or not
+ */
+ public boolean isValid() {
+ return !TextUtils.isEmpty(mPackageName)
+ && !TextUtils.isEmpty(mControlCategory)
+ && mSelectedRoutes.size() > 0;
+ }
+
+ /**
+ * Gets the id of the session
+ */
+ @NonNull
+ public int getSessionId() {
+ return mSessionId;
+ }
+
+ /**
+ * Gets the control category of the session.
+ * Routes that don't support the category can't be added to the session.
+ */
+ @NonNull
+ public String getControlCategory() {
+ return mControlCategory;
+ }
+
+ /**
+ * Gets the list of ids of selected routes for the session. It shouldn't be empty.
+ */
+ @NonNull
+ public List<String> getSelectedRoutes() {
+ return mSelectedRoutes;
+ }
+
+ /**
+ * Gets the list of ids of deselectable routes for the session.
+ */
+ @NonNull
+ public List<String> getDeselectableRoutes() {
+ return mDeselectableRoutes;
+ }
+
+ /**
+ * Gets the list of ids of groupable routes for the session.
+ */
+ @NonNull
+ public List<String> getGroupableRoutes() {
+ return mGroupableRoutes;
+ }
+
+ /**
+ * Gets the list of ids of transferrable routes for the session.
+ */
+ @NonNull
+ public List<String> getTransferrableRoutes() {
+ return mTransferrableRoutes;
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ dest.writeInt(mSessionId);
+ dest.writeString(mPackageName);
+ dest.writeString(mControlCategory);
+ dest.writeStringList(mSelectedRoutes);
+ dest.writeStringList(mDeselectableRoutes);
+ dest.writeStringList(mGroupableRoutes);
+ dest.writeStringList(mTransferrableRoutes);
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder result = new StringBuilder()
+ .append("RouteSessionInfo{ ")
+ .append("sessionId=").append(mSessionId)
+ .append(", selectedRoutes={");
+ for (int i = 0; i < mSelectedRoutes.size(); i++) {
+ if (i > 0) result.append(", ");
+ result.append(mSelectedRoutes.get(i));
+ }
+ result.append("}");
+ result.append(" }");
+ return result.toString();
+ }
+
+ /**
+ * Builder class for {@link RouteSessionInfo}.
+ */
+ public static final class Builder {
+ final String mPackageName;
+ final int mSessionId;
+ final String mControlCategory;
+ final List<String> mSelectedRoutes;
+ final List<String> mDeselectableRoutes;
+ final List<String> mGroupableRoutes;
+ final List<String> mTransferrableRoutes;
+
+ public Builder(int sessionId, @NonNull String packageName,
+ @NonNull String controlCategory) {
+ mSessionId = sessionId;
+ mPackageName = Objects.requireNonNull(packageName, "packageName must not be null");
+ mControlCategory = Objects.requireNonNull(controlCategory,
+ "controlCategory must not be null");
+
+ mSelectedRoutes = new ArrayList<>();
+ mDeselectableRoutes = new ArrayList<>();
+ mGroupableRoutes = new ArrayList<>();
+ mTransferrableRoutes = new ArrayList<>();
+ }
+
+ public Builder(RouteSessionInfo sessionInfo) {
+ mSessionId = sessionInfo.mSessionId;
+ mPackageName = sessionInfo.mPackageName;
+ mControlCategory = sessionInfo.mControlCategory;
+
+ mSelectedRoutes = new ArrayList<>(sessionInfo.mSelectedRoutes);
+ mDeselectableRoutes = new ArrayList<>(sessionInfo.mDeselectableRoutes);
+ mGroupableRoutes = new ArrayList<>(sessionInfo.mGroupableRoutes);
+ mTransferrableRoutes = new ArrayList<>(sessionInfo.mTransferrableRoutes);
+ }
+
+ /**
+ * Adds a selected route
+ */
+ @NonNull
+ public Builder addSelectedRoute(String routeId) {
+ mSelectedRoutes.add(routeId);
+ return this;
+ }
+
+ /**
+ * Removes a selected route
+ */
+ @NonNull
+ public Builder removeSelectedRoute(String routeId) {
+ mSelectedRoutes.remove(routeId);
+ return this;
+ }
+
+ /**
+ * Adds a deselectable route
+ */
+ @NonNull
+ public Builder addDeselectableRoute(String routeId) {
+ mDeselectableRoutes.add(routeId);
+ return this;
+ }
+
+ /**
+ * Removes a deselecable route
+ */
+ @NonNull
+ public Builder removeDeselectableRoute(String routeId) {
+ mDeselectableRoutes.remove(routeId);
+ return this;
+ }
+
+ /**
+ * Adds a groupable route
+ */
+ @NonNull
+ public Builder addGroupableRoute(String routeId) {
+ mGroupableRoutes.add(routeId);
+ return this;
+ }
+
+ /**
+ * Removes a groupable route
+ */
+ @NonNull
+ public Builder removeGroupableRoute(String routeId) {
+ mGroupableRoutes.remove(routeId);
+ return this;
+ }
+
+ /**
+ * Adds a transferrable route
+ */
+ @NonNull
+ public Builder addTransferrableRoute(String routeId) {
+ mTransferrableRoutes.add(routeId);
+ return this;
+ }
+
+ /**
+ * Removes a transferrable route
+ */
+ @NonNull
+ public Builder removeTransferrableRoute(String routeId) {
+ mTransferrableRoutes.remove(routeId);
+ return this;
+ }
+
+ /**
+ * Builds a route session info
+ */
+ @NonNull
+ public RouteSessionInfo build() {
+ return new RouteSessionInfo(this);
+ }
+ }
+}
diff --git a/media/java/android/media/SubtitleController.java b/media/java/android/media/SubtitleController.java
index 1a241af7345d..48657a6c810f 100644
--- a/media/java/android/media/SubtitleController.java
+++ b/media/java/android/media/SubtitleController.java
@@ -16,10 +16,7 @@
package android.media;
-import java.util.Locale;
-import java.util.Vector;
-
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.media.MediaPlayer.TrackInfo;
import android.media.SubtitleTrack.RenderingWidget;
@@ -28,6 +25,9 @@ import android.os.Looper;
import android.os.Message;
import android.view.accessibility.CaptioningManager;
+import java.util.Locale;
+import java.util.Vector;
+
/**
* The subtitle controller provides the architecture to display subtitles for a
* media source. It allows specifying which tracks to display, on which anchor
diff --git a/media/java/android/media/SubtitleTrack.java b/media/java/android/media/SubtitleTrack.java
index 0705d97a9edf..10669f466fe5 100644
--- a/media/java/android/media/SubtitleTrack.java
+++ b/media/java/android/media/SubtitleTrack.java
@@ -16,7 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.Canvas;
import android.media.MediaPlayer.TrackInfo;
import android.os.Handler;
diff --git a/media/java/android/media/ThumbnailUtils.java b/media/java/android/media/ThumbnailUtils.java
index a315c1eefb52..1f7b5ad51d9c 100644
--- a/media/java/android/media/ThumbnailUtils.java
+++ b/media/java/android/media/ThumbnailUtils.java
@@ -24,7 +24,7 @@ import static android.os.Environment.MEDIA_UNKNOWN;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentResolver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
@@ -33,14 +33,13 @@ import android.graphics.ImageDecoder;
import android.graphics.ImageDecoder.ImageInfo;
import android.graphics.ImageDecoder.Source;
import android.graphics.Matrix;
-import android.graphics.Point;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.CancellationSignal;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
-import android.provider.MediaStore.ThumbnailConstants;
+import android.provider.MediaStore;
import android.util.Log;
import android.util.Size;
@@ -77,15 +76,7 @@ public class ThumbnailUtils {
public static final int OPTIONS_RECYCLE_INPUT = 0x2;
private static Size convertKind(int kind) {
- if (kind == ThumbnailConstants.MICRO_KIND) {
- return Point.convert(ThumbnailConstants.MICRO_SIZE);
- } else if (kind == ThumbnailConstants.FULL_SCREEN_KIND) {
- return Point.convert(ThumbnailConstants.FULL_SCREEN_SIZE);
- } else if (kind == ThumbnailConstants.MINI_KIND) {
- return Point.convert(ThumbnailConstants.MINI_SIZE);
- } else {
- throw new IllegalArgumentException("Unsupported kind: " + kind);
- }
+ return MediaStore.Images.Thumbnails.getKindSize(kind);
}
private static class Resizer implements ImageDecoder.OnHeaderDecodedListener {
diff --git a/media/java/android/media/TimedText.java b/media/java/android/media/TimedText.java
index d8cdf9c12e09..120642a8e7cb 100644
--- a/media/java/android/media/TimedText.java
+++ b/media/java/android/media/TimedText.java
@@ -16,14 +16,15 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.Rect;
import android.os.Parcel;
import android.util.Log;
+
+import java.util.ArrayList;
import java.util.HashMap;
-import java.util.Set;
import java.util.List;
-import java.util.ArrayList;
+import java.util.Set;
/**
* Class to hold the timed text's metadata, including:
diff --git a/media/java/android/media/ToneGenerator.java b/media/java/android/media/ToneGenerator.java
index c6d5ba3f9953..cc114a9092e1 100644
--- a/media/java/android/media/ToneGenerator.java
+++ b/media/java/android/media/ToneGenerator.java
@@ -16,7 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
diff --git a/media/java/android/media/TtmlRenderer.java b/media/java/android/media/TtmlRenderer.java
index 34154ce93a8c..e5782642f4eb 100644
--- a/media/java/android/media/TtmlRenderer.java
+++ b/media/java/android/media/TtmlRenderer.java
@@ -16,7 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
@@ -27,6 +27,10 @@ import android.view.accessibility.CaptioningManager;
import android.widget.LinearLayout;
import android.widget.TextView;
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+import org.xmlpull.v1.XmlPullParserFactory;
+
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
@@ -37,10 +41,6 @@ import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-import org.xmlpull.v1.XmlPullParserFactory;
-
/** @hide */
public class TtmlRenderer extends SubtitleController.Renderer {
private final Context mContext;
diff --git a/media/java/android/media/VolumeShaper.java b/media/java/android/media/VolumeShaper.java
index 663d564af23e..99dfe1e8e32f 100644
--- a/media/java/android/media/VolumeShaper.java
+++ b/media/java/android/media/VolumeShaper.java
@@ -19,13 +19,12 @@ import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
-import java.lang.AutoCloseable;
import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.Objects;
diff --git a/media/java/android/media/WebVttRenderer.java b/media/java/android/media/WebVttRenderer.java
index 36458d7e1746..bc1429499e70 100644
--- a/media/java/android/media/WebVttRenderer.java
+++ b/media/java/android/media/WebVttRenderer.java
@@ -16,7 +16,7 @@
package android.media;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.text.Layout.Alignment;
import android.text.SpannableStringBuilder;
diff --git a/media/java/android/media/audio/common/AudioChannelMask.aidl b/media/java/android/media/audio/common/AudioChannelMask.aidl
new file mode 100644
index 000000000000..b9b08e6921bc
--- /dev/null
+++ b/media/java/android/media/audio/common/AudioChannelMask.aidl
@@ -0,0 +1,217 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+ // This file has been semi-automatically generated using hidl2aidl from its counterpart in
+ // hardware/interfaces/audio/common/5.0/types.hal
+
+package android.media.audio.common;
+
+/**
+ * A channel mask per se only defines the presence or absence of a channel, not
+ * the order.
+ *
+ * The channel order convention is that channels are interleaved in order from
+ * least significant channel mask bit to most significant channel mask bit,
+ * with unused bits skipped. For example for stereo, LEFT would be first,
+ * followed by RIGHT.
+ * Any exceptions to this convention are noted at the appropriate API.
+ *
+ * AudioChannelMask is an opaque type and its internal layout should not be
+ * assumed as it may change in the future. Instead, always use functions
+ * to examine it.
+ *
+ * These are the current representations:
+ *
+ * REPRESENTATION_POSITION
+ * is a channel mask representation for position assignment. Each low-order
+ * bit corresponds to the spatial position of a transducer (output), or
+ * interpretation of channel (input). The user of a channel mask needs to
+ * know the context of whether it is for output or input. The constants
+ * OUT_* or IN_* apply to the bits portion. It is not permitted for no bits
+ * to be set.
+ *
+ * REPRESENTATION_INDEX
+ * is a channel mask representation for index assignment. Each low-order
+ * bit corresponds to a selected channel. There is no platform
+ * interpretation of the various bits. There is no concept of output or
+ * input. It is not permitted for no bits to be set.
+ *
+ * All other representations are reserved for future use.
+ *
+ * Warning: current representation distinguishes between input and output, but
+ * this will not the be case in future revisions of the platform. Wherever there
+ * is an ambiguity between input and output that is currently resolved by
+ * checking the channel mask, the implementer should look for ways to fix it
+ * with additional information outside of the mask.
+ *
+ * {@hide}
+ */
+@Backing(type="int")
+enum AudioChannelMask {
+ /**
+ * must be 0 for compatibility
+ */
+ REPRESENTATION_POSITION = 0,
+ /**
+ * 1 is reserved for future use
+ */
+ REPRESENTATION_INDEX = 2,
+ /**
+ * 3 is reserved for future use
+ *
+ *
+ * These can be a complete value of AudioChannelMask
+ */
+ NONE = 0x0,
+ INVALID = 0xC0000000,
+ /**
+ * These can be the bits portion of an AudioChannelMask
+ * with representation REPRESENTATION_POSITION.
+ *
+ *
+ * output channels
+ */
+ OUT_FRONT_LEFT = 0x1,
+ OUT_FRONT_RIGHT = 0x2,
+ OUT_FRONT_CENTER = 0x4,
+ OUT_LOW_FREQUENCY = 0x8,
+ OUT_BACK_LEFT = 0x10,
+ OUT_BACK_RIGHT = 0x20,
+ OUT_FRONT_LEFT_OF_CENTER = 0x40,
+ OUT_FRONT_RIGHT_OF_CENTER = 0x80,
+ OUT_BACK_CENTER = 0x100,
+ OUT_SIDE_LEFT = 0x200,
+ OUT_SIDE_RIGHT = 0x400,
+ OUT_TOP_CENTER = 0x800,
+ OUT_TOP_FRONT_LEFT = 0x1000,
+ OUT_TOP_FRONT_CENTER = 0x2000,
+ OUT_TOP_FRONT_RIGHT = 0x4000,
+ OUT_TOP_BACK_LEFT = 0x8000,
+ OUT_TOP_BACK_CENTER = 0x10000,
+ OUT_TOP_BACK_RIGHT = 0x20000,
+ OUT_TOP_SIDE_LEFT = 0x40000,
+ OUT_TOP_SIDE_RIGHT = 0x80000,
+ /**
+ * Haptic channel characteristics are specific to a device and
+ * only used to play device specific resources (eg: ringtones).
+ * The HAL can freely map A and B to haptic controllers, the
+ * framework shall not interpret those values and forward them
+ * from the device audio assets.
+ */
+ OUT_HAPTIC_A = 0x20000000,
+ OUT_HAPTIC_B = 0x10000000,
+// TODO(ytai): Aliases not currently supported in AIDL - can inline the values.
+// OUT_MONO = OUT_FRONT_LEFT,
+// OUT_STEREO = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT),
+// OUT_2POINT1 = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_LOW_FREQUENCY),
+// OUT_2POINT0POINT2 = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT),
+// OUT_2POINT1POINT2 = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT | OUT_LOW_FREQUENCY),
+// OUT_3POINT0POINT2 = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT),
+// OUT_3POINT1POINT2 = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT | OUT_LOW_FREQUENCY),
+// OUT_QUAD = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_BACK_LEFT | OUT_BACK_RIGHT),
+// OUT_QUAD_BACK = OUT_QUAD,
+// /**
+// * like OUT_QUAD_BACK with *_SIDE_* instead of *_BACK_*
+// */
+// OUT_QUAD_SIDE = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_SIDE_LEFT | OUT_SIDE_RIGHT),
+// OUT_SURROUND = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_BACK_CENTER),
+// OUT_PENTA = (OUT_QUAD | OUT_FRONT_CENTER),
+// OUT_5POINT1 = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_LOW_FREQUENCY | OUT_BACK_LEFT | OUT_BACK_RIGHT),
+// OUT_5POINT1_BACK = OUT_5POINT1,
+// /**
+// * like OUT_5POINT1_BACK with *_SIDE_* instead of *_BACK_*
+// */
+// OUT_5POINT1_SIDE = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_LOW_FREQUENCY | OUT_SIDE_LEFT | OUT_SIDE_RIGHT),
+// OUT_5POINT1POINT2 = (OUT_5POINT1 | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT),
+// OUT_5POINT1POINT4 = (OUT_5POINT1 | OUT_TOP_FRONT_LEFT | OUT_TOP_FRONT_RIGHT | OUT_TOP_BACK_LEFT | OUT_TOP_BACK_RIGHT),
+// OUT_6POINT1 = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_LOW_FREQUENCY | OUT_BACK_LEFT | OUT_BACK_RIGHT | OUT_BACK_CENTER),
+// /**
+// * matches the correct AudioFormat.CHANNEL_OUT_7POINT1_SURROUND
+// */
+// OUT_7POINT1 = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_LOW_FREQUENCY | OUT_BACK_LEFT | OUT_BACK_RIGHT | OUT_SIDE_LEFT | OUT_SIDE_RIGHT),
+// OUT_7POINT1POINT2 = (OUT_7POINT1 | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT),
+// OUT_7POINT1POINT4 = (OUT_7POINT1 | OUT_TOP_FRONT_LEFT | OUT_TOP_FRONT_RIGHT | OUT_TOP_BACK_LEFT | OUT_TOP_BACK_RIGHT),
+// OUT_MONO_HAPTIC_A = (OUT_FRONT_LEFT | OUT_HAPTIC_A),
+// OUT_STEREO_HAPTIC_A = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_HAPTIC_A),
+// OUT_HAPTIC_AB = (OUT_HAPTIC_A | OUT_HAPTIC_B),
+// OUT_MONO_HAPTIC_AB = (OUT_FRONT_LEFT | OUT_HAPTIC_A | OUT_HAPTIC_B),
+// OUT_STEREO_HAPTIC_AB = (OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_HAPTIC_A | OUT_HAPTIC_B),
+ /**
+ * These are bits only, not complete values
+ *
+ *
+ * input channels
+ */
+ IN_LEFT = 0x4,
+ IN_RIGHT = 0x8,
+ IN_FRONT = 0x10,
+ IN_BACK = 0x20,
+ IN_LEFT_PROCESSED = 0x40,
+ IN_RIGHT_PROCESSED = 0x80,
+ IN_FRONT_PROCESSED = 0x100,
+ IN_BACK_PROCESSED = 0x200,
+ IN_PRESSURE = 0x400,
+ IN_X_AXIS = 0x800,
+ IN_Y_AXIS = 0x1000,
+ IN_Z_AXIS = 0x2000,
+ IN_BACK_LEFT = 0x10000,
+ IN_BACK_RIGHT = 0x20000,
+ IN_CENTER = 0x40000,
+ IN_LOW_FREQUENCY = 0x100000,
+ IN_TOP_LEFT = 0x200000,
+ IN_TOP_RIGHT = 0x400000,
+ IN_VOICE_UPLINK = 0x4000,
+ IN_VOICE_DNLINK = 0x8000,
+// TODO(ytai): Aliases not currently supported in AIDL - can inline the values.
+// IN_MONO = IN_FRONT,
+// IN_STEREO = (IN_LEFT | IN_RIGHT),
+// IN_FRONT_BACK = (IN_FRONT | IN_BACK),
+// IN_6 = (IN_LEFT | IN_RIGHT | IN_FRONT | IN_BACK | IN_LEFT_PROCESSED | IN_RIGHT_PROCESSED),
+// IN_2POINT0POINT2 = (IN_LEFT | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT),
+// IN_2POINT1POINT2 = (IN_LEFT | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT | IN_LOW_FREQUENCY),
+// IN_3POINT0POINT2 = (IN_LEFT | IN_CENTER | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT),
+// IN_3POINT1POINT2 = (IN_LEFT | IN_CENTER | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT | IN_LOW_FREQUENCY),
+// IN_5POINT1 = (IN_LEFT | IN_CENTER | IN_RIGHT | IN_BACK_LEFT | IN_BACK_RIGHT | IN_LOW_FREQUENCY),
+// IN_VOICE_UPLINK_MONO = (IN_VOICE_UPLINK | IN_MONO),
+// IN_VOICE_DNLINK_MONO = (IN_VOICE_DNLINK | IN_MONO),
+// IN_VOICE_CALL_MONO = (IN_VOICE_UPLINK_MONO | IN_VOICE_DNLINK_MONO),
+// COUNT_MAX = 30,
+// INDEX_HDR = REPRESENTATION_INDEX << COUNT_MAX,
+// INDEX_MASK_1 = INDEX_HDR | ((1 << 1) - 1),
+// INDEX_MASK_2 = INDEX_HDR | ((1 << 2) - 1),
+// INDEX_MASK_3 = INDEX_HDR | ((1 << 3) - 1),
+// INDEX_MASK_4 = INDEX_HDR | ((1 << 4) - 1),
+// INDEX_MASK_5 = INDEX_HDR | ((1 << 5) - 1),
+// INDEX_MASK_6 = INDEX_HDR | ((1 << 6) - 1),
+// INDEX_MASK_7 = INDEX_HDR | ((1 << 7) - 1),
+// INDEX_MASK_8 = INDEX_HDR | ((1 << 8) - 1),
+// INDEX_MASK_9 = INDEX_HDR | ((1 << 9) - 1),
+// INDEX_MASK_10 = INDEX_HDR | ((1 << 10) - 1),
+// INDEX_MASK_11 = INDEX_HDR | ((1 << 11) - 1),
+// INDEX_MASK_12 = INDEX_HDR | ((1 << 12) - 1),
+// INDEX_MASK_13 = INDEX_HDR | ((1 << 13) - 1),
+// INDEX_MASK_14 = INDEX_HDR | ((1 << 14) - 1),
+// INDEX_MASK_15 = INDEX_HDR | ((1 << 15) - 1),
+// INDEX_MASK_16 = INDEX_HDR | ((1 << 16) - 1),
+// INDEX_MASK_17 = INDEX_HDR | ((1 << 17) - 1),
+// INDEX_MASK_18 = INDEX_HDR | ((1 << 18) - 1),
+// INDEX_MASK_19 = INDEX_HDR | ((1 << 19) - 1),
+// INDEX_MASK_20 = INDEX_HDR | ((1 << 20) - 1),
+// INDEX_MASK_21 = INDEX_HDR | ((1 << 21) - 1),
+// INDEX_MASK_22 = INDEX_HDR | ((1 << 22) - 1),
+// INDEX_MASK_23 = INDEX_HDR | ((1 << 23) - 1),
+// INDEX_MASK_24 = INDEX_HDR | ((1 << 24) - 1),
+}
diff --git a/media/java/android/media/audio/common/AudioConfig.aidl b/media/java/android/media/audio/common/AudioConfig.aidl
new file mode 100644
index 000000000000..50dd796e1fa0
--- /dev/null
+++ b/media/java/android/media/audio/common/AudioConfig.aidl
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+ // This file has been semi-automatically generated using hidl2aidl from its counterpart in
+ // hardware/interfaces/audio/common/5.0/types.hal
+
+package android.media.audio.common;
+
+import android.media.audio.common.AudioFormat;
+import android.media.audio.common.AudioOffloadInfo;
+
+/**
+ * Commonly used audio stream configuration parameters.
+ *
+ * {@hide}
+ */
+parcelable AudioConfig {
+ int sampleRateHz;
+ int channelMask;
+ AudioFormat format;
+ AudioOffloadInfo offloadInfo;
+ long frameCount;
+}
diff --git a/media/java/android/media/audio/common/AudioFormat.aidl b/media/java/android/media/audio/common/AudioFormat.aidl
new file mode 100644
index 000000000000..aadc8e26cce3
--- /dev/null
+++ b/media/java/android/media/audio/common/AudioFormat.aidl
@@ -0,0 +1,170 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+ // This file has been semi-automatically generated using hidl2aidl from its counterpart in
+ // hardware/interfaces/audio/common/5.0/types.hal
+
+package android.media.audio.common;
+
+/**
+ * Audio format is a 32-bit word that consists of:
+ * main format field (upper 8 bits)
+ * sub format field (lower 24 bits).
+ *
+ * The main format indicates the main codec type. The sub format field indicates
+ * options and parameters for each format. The sub format is mainly used for
+ * record to indicate for instance the requested bitrate or profile. It can
+ * also be used for certain formats to give informations not present in the
+ * encoded audio stream (e.g. octet alignement for AMR).
+ *
+ * {@hide}
+ */
+@Backing(type="int")
+enum AudioFormat {
+ INVALID = 0xFFFFFFFF,
+ DEFAULT = 0,
+ PCM = 0x00000000,
+ MP3 = 0x01000000,
+ AMR_NB = 0x02000000,
+ AMR_WB = 0x03000000,
+ AAC = 0x04000000,
+ /**
+ * Deprecated, Use AAC_HE_V1
+ */
+ HE_AAC_V1 = 0x05000000,
+ /**
+ * Deprecated, Use AAC_HE_V2
+ */
+ HE_AAC_V2 = 0x06000000,
+ VORBIS = 0x07000000,
+ OPUS = 0x08000000,
+ AC3 = 0x09000000,
+ E_AC3 = 0x0A000000,
+ DTS = 0x0B000000,
+ DTS_HD = 0x0C000000,
+ /**
+ * IEC61937 is encoded audio wrapped in 16-bit PCM.
+ */
+ IEC61937 = 0x0D000000,
+ DOLBY_TRUEHD = 0x0E000000,
+ EVRC = 0x10000000,
+ EVRCB = 0x11000000,
+ EVRCWB = 0x12000000,
+ EVRCNW = 0x13000000,
+ AAC_ADIF = 0x14000000,
+ WMA = 0x15000000,
+ WMA_PRO = 0x16000000,
+ AMR_WB_PLUS = 0x17000000,
+ MP2 = 0x18000000,
+ QCELP = 0x19000000,
+ DSD = 0x1A000000,
+ FLAC = 0x1B000000,
+ ALAC = 0x1C000000,
+ APE = 0x1D000000,
+ AAC_ADTS = 0x1E000000,
+ SBC = 0x1F000000,
+ APTX = 0x20000000,
+ APTX_HD = 0x21000000,
+ AC4 = 0x22000000,
+ LDAC = 0x23000000,
+ /**
+ * Dolby Metadata-enhanced Audio Transmission
+ */
+ MAT = 0x24000000,
+ AAC_LATM = 0x25000000,
+ CELT = 0x26000000,
+ APTX_ADAPTIVE = 0x27000000,
+ LHDC = 0x28000000,
+ LHDC_LL = 0x29000000,
+ APTX_TWSP = 0x2A000000,
+ /**
+ * Deprecated
+ */
+ MAIN_MASK = 0xFF000000,
+ SUB_MASK = 0x00FFFFFF,
+ /**
+ * Subformats
+ */
+ PCM_SUB_16_BIT = 0x1,
+ PCM_SUB_8_BIT = 0x2,
+ PCM_SUB_32_BIT = 0x3,
+ PCM_SUB_8_24_BIT = 0x4,
+ PCM_SUB_FLOAT = 0x5,
+ PCM_SUB_24_BIT_PACKED = 0x6,
+ MP3_SUB_NONE = 0x0,
+ AMR_SUB_NONE = 0x0,
+ AAC_SUB_MAIN = 0x1,
+ AAC_SUB_LC = 0x2,
+ AAC_SUB_SSR = 0x4,
+ AAC_SUB_LTP = 0x8,
+ AAC_SUB_HE_V1 = 0x10,
+ AAC_SUB_SCALABLE = 0x20,
+ AAC_SUB_ERLC = 0x40,
+ AAC_SUB_LD = 0x80,
+ AAC_SUB_HE_V2 = 0x100,
+ AAC_SUB_ELD = 0x200,
+ AAC_SUB_XHE = 0x300,
+ VORBIS_SUB_NONE = 0x0,
+ E_AC3_SUB_JOC = 0x1,
+ MAT_SUB_1_0 = 0x1,
+ MAT_SUB_2_0 = 0x2,
+ MAT_SUB_2_1 = 0x3,
+// TODO(ytai): Aliases not currently supported in AIDL - can inline the values.
+// /**
+// * Aliases
+// *
+// *
+// * note != AudioFormat.ENCODING_PCM_16BIT
+// */
+// PCM_16_BIT = (PCM | PCM_SUB_16_BIT),
+// /**
+// * note != AudioFormat.ENCODING_PCM_8BIT
+// */
+// PCM_8_BIT = (PCM | PCM_SUB_8_BIT),
+// PCM_32_BIT = (PCM | PCM_SUB_32_BIT),
+// PCM_8_24_BIT = (PCM | PCM_SUB_8_24_BIT),
+// PCM_FLOAT = (PCM | PCM_SUB_FLOAT),
+// PCM_24_BIT_PACKED = (PCM | PCM_SUB_24_BIT_PACKED),
+// AAC_MAIN = (AAC | AAC_SUB_MAIN),
+// AAC_LC = (AAC | AAC_SUB_LC),
+// AAC_SSR = (AAC | AAC_SUB_SSR),
+// AAC_LTP = (AAC | AAC_SUB_LTP),
+// AAC_HE_V1 = (AAC | AAC_SUB_HE_V1),
+// AAC_SCALABLE = (AAC | AAC_SUB_SCALABLE),
+// AAC_ERLC = (AAC | AAC_SUB_ERLC),
+// AAC_LD = (AAC | AAC_SUB_LD),
+// AAC_HE_V2 = (AAC | AAC_SUB_HE_V2),
+// AAC_ELD = (AAC | AAC_SUB_ELD),
+// AAC_XHE = (AAC | AAC_SUB_XHE),
+// AAC_ADTS_MAIN = (AAC_ADTS | AAC_SUB_MAIN),
+// AAC_ADTS_LC = (AAC_ADTS | AAC_SUB_LC),
+// AAC_ADTS_SSR = (AAC_ADTS | AAC_SUB_SSR),
+// AAC_ADTS_LTP = (AAC_ADTS | AAC_SUB_LTP),
+// AAC_ADTS_HE_V1 = (AAC_ADTS | AAC_SUB_HE_V1),
+// AAC_ADTS_SCALABLE = (AAC_ADTS | AAC_SUB_SCALABLE),
+// AAC_ADTS_ERLC = (AAC_ADTS | AAC_SUB_ERLC),
+// AAC_ADTS_LD = (AAC_ADTS | AAC_SUB_LD),
+// AAC_ADTS_HE_V2 = (AAC_ADTS | AAC_SUB_HE_V2),
+// AAC_ADTS_ELD = (AAC_ADTS | AAC_SUB_ELD),
+// AAC_ADTS_XHE = (AAC_ADTS | AAC_SUB_XHE),
+// E_AC3_JOC = (E_AC3 | E_AC3_SUB_JOC),
+// MAT_1_0 = (MAT | MAT_SUB_1_0),
+// MAT_2_0 = (MAT | MAT_SUB_2_0),
+// MAT_2_1 = (MAT | MAT_SUB_2_1),
+// AAC_LATM_LC = (AAC_LATM | AAC_SUB_LC),
+// AAC_LATM_HE_V1 = (AAC_LATM | AAC_SUB_HE_V1),
+// AAC_LATM_HE_V2 = (AAC_LATM | AAC_SUB_HE_V2),
+}
diff --git a/media/java/android/media/audio/common/AudioOffloadInfo.aidl b/media/java/android/media/audio/common/AudioOffloadInfo.aidl
new file mode 100644
index 000000000000..ec10d71135ae
--- /dev/null
+++ b/media/java/android/media/audio/common/AudioOffloadInfo.aidl
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+ // This file has been semi-automatically generated using hidl2aidl from its counterpart in
+ // hardware/interfaces/audio/common/5.0/types.hal
+
+package android.media.audio.common;
+
+import android.media.audio.common.AudioFormat;
+import android.media.audio.common.AudioStreamType;
+import android.media.audio.common.AudioUsage;
+
+/**
+ * Additional information about the stream passed to hardware decoders.
+ *
+ * {@hide}
+ */
+parcelable AudioOffloadInfo {
+ int sampleRateHz;
+ int channelMask;
+ AudioFormat format;
+ AudioStreamType streamType;
+ int bitRatePerSecond;
+ long durationMicroseconds;
+ boolean hasVideo;
+ boolean isStreaming;
+ int bitWidth;
+ int bufferSize;
+ AudioUsage usage;
+}
+
diff --git a/media/java/android/media/audio/common/AudioStreamType.aidl b/media/java/android/media/audio/common/AudioStreamType.aidl
new file mode 100644
index 000000000000..c54566726350
--- /dev/null
+++ b/media/java/android/media/audio/common/AudioStreamType.aidl
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+ // This file has been semi-automatically generated using hidl2aidl from its counterpart in
+ // hardware/interfaces/audio/common/5.0/types.hal
+
+package android.media.audio.common;
+
+/**
+ * Audio streams
+ *
+ * Audio stream type describing the intended use case of a stream.
+ *
+ * {@hide}
+ */
+@Backing(type="int")
+enum AudioStreamType {
+ DEFAULT = -1,
+ MIN = 0,
+ VOICE_CALL = 0,
+ SYSTEM = 1,
+ RING = 2,
+ MUSIC = 3,
+ ALARM = 4,
+ NOTIFICATION = 5,
+ BLUETOOTH_SCO = 6,
+ ENFORCED_AUDIBLE = 7,
+ DTMF = 8,
+ TTS = 9,
+ ACCESSIBILITY = 10,
+}
diff --git a/media/java/android/media/audio/common/AudioUsage.aidl b/media/java/android/media/audio/common/AudioUsage.aidl
new file mode 100644
index 000000000000..ef348165b22c
--- /dev/null
+++ b/media/java/android/media/audio/common/AudioUsage.aidl
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+ // This file has been semi-automatically generated using hidl2aidl from its counterpart in
+ // hardware/interfaces/audio/common/5.0/types.hal
+
+package android.media.audio.common;
+
+/**
+ * {@hide}
+ */
+@Backing(type="int")
+enum AudioUsage {
+ UNKNOWN = 0,
+ MEDIA = 1,
+ VOICE_COMMUNICATION = 2,
+ VOICE_COMMUNICATION_SIGNALLING = 3,
+ ALARM = 4,
+ NOTIFICATION = 5,
+ NOTIFICATION_TELEPHONY_RINGTONE = 6,
+ ASSISTANCE_ACCESSIBILITY = 11,
+ ASSISTANCE_NAVIGATION_GUIDANCE = 12,
+ ASSISTANCE_SONIFICATION = 13,
+ GAME = 14,
+ VIRTUAL_SOURCE = 15,
+ ASSISTANT = 16,
+}
diff --git a/media/java/android/media/audiofx/AudioEffect.java b/media/java/android/media/audiofx/AudioEffect.java
index 5b4bbce91784..4a40c627ecb0 100644
--- a/media/java/android/media/audiofx/AudioEffect.java
+++ b/media/java/android/media/audiofx/AudioEffect.java
@@ -19,8 +19,8 @@ package android.media.audiofx;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityThread;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
diff --git a/media/java/android/media/audiofx/Visualizer.java b/media/java/android/media/audiofx/Visualizer.java
index 89a509f64a1b..392e8fe7543f 100644
--- a/media/java/android/media/audiofx/Visualizer.java
+++ b/media/java/android/media/audiofx/Visualizer.java
@@ -16,8 +16,8 @@
package android.media.audiofx;
-import android.annotation.UnsupportedAppUsage;
import android.app.ActivityThread;
+import android.compat.annotation.UnsupportedAppUsage;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
diff --git a/media/java/android/media/audiopolicy/AudioMix.java b/media/java/android/media/audiopolicy/AudioMix.java
index a82c78fad271..dd9877a9c706 100644
--- a/media/java/android/media/audiopolicy/AudioMix.java
+++ b/media/java/android/media/audiopolicy/AudioMix.java
@@ -20,7 +20,7 @@ import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.media.AudioDeviceInfo;
import android.media.AudioFormat;
import android.media.AudioSystem;
diff --git a/media/java/android/media/audiopolicy/AudioMixingRule.java b/media/java/android/media/audiopolicy/AudioMixingRule.java
index c4afd95be9ac..8c204d222cd4 100644
--- a/media/java/android/media/audiopolicy/AudioMixingRule.java
+++ b/media/java/android/media/audiopolicy/AudioMixingRule.java
@@ -19,7 +19,7 @@ package android.media.audiopolicy;
import android.annotation.NonNull;
import android.annotation.SystemApi;
import android.annotation.TestApi;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.media.AudioAttributes;
import android.os.Parcel;
import android.util.Log;
diff --git a/media/java/android/media/audiopolicy/AudioProductStrategy.java b/media/java/android/media/audiopolicy/AudioProductStrategy.java
index 2799d46cbb47..612f83a14e12 100644
--- a/media/java/android/media/audiopolicy/AudioProductStrategy.java
+++ b/media/java/android/media/audiopolicy/AudioProductStrategy.java
@@ -19,6 +19,7 @@ package android.media.audiopolicy;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
+import android.annotation.TestApi;
import android.media.AudioAttributes;
import android.media.AudioSystem;
import android.media.MediaRecorder;
@@ -82,6 +83,18 @@ public final class AudioProductStrategy implements Parcelable {
/**
* @hide
+ * Create an invalid AudioProductStrategy instance for testing
+ * @param id the ID for the invalid strategy, always use a different one than in use
+ * @return an invalid instance that cannot successfully be used for volume groups or routing
+ */
+ @TestApi
+ @SystemApi
+ public static @NonNull AudioProductStrategy createInvalidAudioProductStrategy(int id) {
+ return new AudioProductStrategy("dummy strategy", id, new AudioAttributesGroup[0]);
+ }
+
+ /**
+ * @hide
* @param streamType to match against AudioProductStrategy
* @return the AudioAttributes for the first strategy found with the associated stream type
* If no match is found, returns AudioAttributes with unknown content_type and usage
@@ -222,6 +235,7 @@ public final class AudioProductStrategy implements Parcelable {
* @return true if the {@link AudioProductStrategy} supports the given {@link AudioAttributes},
* false otherwise.
*/
+ @SystemApi
public boolean supportsAudioAttributes(@NonNull AudioAttributes aa) {
Preconditions.checkNotNull(aa, "AudioAttributes must not be null");
for (final AudioAttributesGroup aag : mAudioAttributesGroups) {
diff --git a/media/java/android/media/session/ICallback.aidl b/media/java/android/media/session/IOnMediaKeyEventDispatchedListener.aidl
index 322bffa96c9e..90d913459edc 100644
--- a/media/java/android/media/session/ICallback.aidl
+++ b/media/java/android/media/session/IOnMediaKeyEventDispatchedListener.aidl
@@ -1,4 +1,5 @@
-/* Copyright (C) 2016 The Android Open Source Project
+/*
+ * Copyright 2019 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.
@@ -15,21 +16,13 @@
package android.media.session;
-import android.app.PendingIntent;
-import android.content.ComponentName;
import android.media.session.MediaSession;
import android.view.KeyEvent;
/**
* @hide
*/
-oneway interface ICallback {
- void onMediaKeyEventDispatchedToMediaSession(in KeyEvent event,
+oneway interface IOnMediaKeyEventDispatchedListener {
+ void onMediaKeyEventDispatched(in KeyEvent event, in String packageName,
in MediaSession.Token sessionToken);
- void onMediaKeyEventDispatchedToMediaButtonReceiver(in KeyEvent event,
- in ComponentName mediaButtonReceiver);
-
- void onAddressedPlayerChangedToMediaSession(in MediaSession.Token sessionToken);
- void onAddressedPlayerChangedToMediaButtonReceiver(in ComponentName mediaButtonReceiver);
}
-
diff --git a/media/java/android/media/session/IOnMediaKeyEventSessionChangedListener.aidl b/media/java/android/media/session/IOnMediaKeyEventSessionChangedListener.aidl
new file mode 100644
index 000000000000..9566e756162c
--- /dev/null
+++ b/media/java/android/media/session/IOnMediaKeyEventSessionChangedListener.aidl
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2019 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.media.session;
+
+import android.media.session.MediaSession;
+
+/**
+ * @hide
+ */
+oneway interface IOnMediaKeyEventSessionChangedListener {
+ void onMediaKeyEventSessionChanged(in String packageName,
+ in MediaSession.Token mediaKeyEventSessionToken);
+}
+
diff --git a/media/java/android/media/session/ISessionManager.aidl b/media/java/android/media/session/ISessionManager.aidl
index 01e6ed5e9f35..c8502a51ee23 100644
--- a/media/java/android/media/session/ISessionManager.aidl
+++ b/media/java/android/media/session/ISessionManager.aidl
@@ -20,7 +20,8 @@ import android.content.pm.ParceledListSlice;
import android.media.IRemoteVolumeController;
import android.media.Session2Token;
import android.media.session.IActiveSessionsListener;
-import android.media.session.ICallback;
+import android.media.session.IOnMediaKeyEventDispatchedListener;
+import android.media.session.IOnMediaKeyEventSessionChangedListener;
import android.media.session.IOnMediaKeyListener;
import android.media.session.IOnVolumeKeyLongPressListener;
import android.media.session.ISession;
@@ -62,8 +63,12 @@ interface ISessionManager {
// For PhoneWindowManager to precheck media keys
boolean isGlobalPriorityActive();
- void registerCallback(in ICallback callback);
- void unregisterCallback(in ICallback callback);
+ void addOnMediaKeyEventDispatchedListener(in IOnMediaKeyEventDispatchedListener listener);
+ void removeOnMediaKeyEventDispatchedListener(in IOnMediaKeyEventDispatchedListener listener);
+ void addOnMediaKeyEventSessionChangedListener(
+ in IOnMediaKeyEventSessionChangedListener listener);
+ void removeOnMediaKeyEventSessionChangedListener(
+ in IOnMediaKeyEventSessionChangedListener listener);
void setOnVolumeKeyLongPressListener(in IOnVolumeKeyLongPressListener listener);
void setOnMediaKeyListener(in IOnMediaKeyListener listener);
diff --git a/media/java/android/media/session/MediaController.java b/media/java/android/media/session/MediaController.java
index 1fc4f7d59ca5..646fc0620b5e 100644
--- a/media/java/android/media/session/MediaController.java
+++ b/media/java/android/media/session/MediaController.java
@@ -18,8 +18,8 @@ package android.media.session;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
import android.app.PendingIntent;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.ParceledListSlice;
import android.media.AudioAttributes;
@@ -443,8 +443,8 @@ public final class MediaController {
* Get the session's tag for debugging purposes.
*
* @return The session's tag.
- * @hide
*/
+ @NonNull
public String getTag() {
if (mTag == null) {
try {
diff --git a/media/java/android/media/session/MediaSession.java b/media/java/android/media/session/MediaSession.java
index e11715ff7299..5db4e8c1e3f7 100644
--- a/media/java/android/media/session/MediaSession.java
+++ b/media/java/android/media/session/MediaSession.java
@@ -19,9 +19,9 @@ package android.media.session;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
import android.app.Activity;
import android.app.PendingIntent;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ParceledListSlice;
diff --git a/media/java/android/media/session/MediaSessionLegacyHelper.java b/media/java/android/media/session/MediaSessionLegacyHelper.java
index 123c4f75d5b6..0d506f0eb52c 100644
--- a/media/java/android/media/session/MediaSessionLegacyHelper.java
+++ b/media/java/android/media/session/MediaSessionLegacyHelper.java
@@ -16,9 +16,9 @@
package android.media.session;
-import android.annotation.UnsupportedAppUsage;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
@@ -26,7 +26,6 @@ import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
-import android.media.AudioManager;
import android.media.MediaMetadata;
import android.media.MediaMetadataEditor;
import android.media.MediaMetadataRetriever;
diff --git a/media/java/android/media/session/MediaSessionManager.java b/media/java/android/media/session/MediaSessionManager.java
index 92fb31bd4de8..aff725734ee1 100644
--- a/media/java/android/media/session/MediaSessionManager.java
+++ b/media/java/android/media/session/MediaSessionManager.java
@@ -22,7 +22,7 @@ import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.SystemService;
-import android.annotation.UnsupportedAppUsage;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ParceledListSlice;
@@ -32,7 +32,6 @@ import android.media.MediaSession2;
import android.media.Session2Token;
import android.os.Bundle;
import android.os.Handler;
-import android.os.HandlerExecutor;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.ResultReceiver;
@@ -78,29 +77,33 @@ public final class MediaSessionManager {
*/
public static final int RESULT_MEDIA_KEY_HANDLED = 1;
private final ISessionManager mService;
+ private final OnMediaKeyEventDispatchedListenerStub mOnMediaKeyEventDispatchedListenerStub =
+ new OnMediaKeyEventDispatchedListenerStub();
+ private final OnMediaKeyEventSessionChangedListenerStub
+ mOnMediaKeyEventSessionChangedListenerStub =
+ new OnMediaKeyEventSessionChangedListenerStub();
private final Object mLock = new Object();
@GuardedBy("mLock")
- private final ArrayMap<OnActiveSessionsChangedListener, SessionsChangedWrapper> mListeners
- = new ArrayMap<OnActiveSessionsChangedListener, SessionsChangedWrapper>();
+ private final ArrayMap<OnActiveSessionsChangedListener, SessionsChangedWrapper> mListeners =
+ new ArrayMap<OnActiveSessionsChangedListener, SessionsChangedWrapper>();
@GuardedBy("mLock")
private final ArrayMap<OnSession2TokensChangedListener, Session2TokensChangedWrapper>
mSession2TokensListeners = new ArrayMap<>();
@GuardedBy("mLock")
- private final CallbackStub mCbStub = new CallbackStub();
+ private final Map<OnMediaKeyEventDispatchedListener, Executor>
+ mOnMediaKeyEventDispatchedListeners = new HashMap<>();
@GuardedBy("mLock")
- private final Map<Callback, Executor> mCallbacks = new HashMap<>();
+ private final Map<OnMediaKeyEventSessionChangedListener, Executor>
+ mMediaKeyEventSessionChangedCallbacks = new HashMap<>();
@GuardedBy("mLock")
- private MediaSession.Token mCurMediaButtonSession;
+ private String mCurMediaKeyEventSessionPackage;
@GuardedBy("mLock")
- private ComponentName mCurMediaButtonReceiver;
+ private MediaSession.Token mCurMediaKeyEventSession;
private Context mContext;
private OnVolumeKeyLongPressListenerImpl mOnVolumeKeyLongPressListener;
private OnMediaKeyListenerImpl mOnMediaKeyListener;
- // TODO: Remove mLegacyCallback once Bluetooth app stop calling setCallback() method.
- @GuardedBy("mLock")
- private Callback mLegacyCallback;
/**
* @hide
@@ -756,89 +759,118 @@ public final class MediaSessionManager {
}
/**
- * Set a {@link Callback}.
- *
- * <p>System can only have a single callback, and the callback can only be set by
- * Bluetooth service process.
+ * Add a {@link OnMediaKeyEventDispatchedListener}.
*
- * @param callback A {@link Callback}. {@code null} to reset.
- * @param handler The handler on which the callback should be invoked, or {@code null}
- * if the callback should be invoked on the calling thread's looper.
+ * @param executor The executor on which the callback should be invoked
+ * @param listener A {@link OnMediaKeyEventDispatchedListener}.
* @hide
*/
- // TODO: Remove this method once Bluetooth app stop calling it.
- public void setCallback(@Nullable Callback callback, @Nullable Handler handler) {
- if (handler == null) {
- handler = new Handler();
+ @SystemApi
+ @RequiresPermission(value = android.Manifest.permission.MEDIA_CONTENT_CONTROL)
+ public void addOnMediaKeyEventDispatchedListener(
+ @NonNull @CallbackExecutor Executor executor,
+ @NonNull OnMediaKeyEventDispatchedListener listener) {
+ if (executor == null) {
+ throw new NullPointerException("executor shouldn't be null");
+ }
+ if (listener == null) {
+ throw new NullPointerException("listener shouldn't be null");
}
synchronized (mLock) {
- if (mLegacyCallback != null) {
- unregisterCallback(mLegacyCallback);
+ try {
+ mOnMediaKeyEventDispatchedListeners.put(listener, executor);
+ if (mOnMediaKeyEventDispatchedListeners.size() == 1) {
+ mService.addOnMediaKeyEventDispatchedListener(
+ mOnMediaKeyEventDispatchedListenerStub);
+ }
+ } catch (RemoteException e) {
+ Log.e(TAG, "Failed to set media key listener", e);
}
- mLegacyCallback = callback;
- if (callback != null) {
- registerCallback(new HandlerExecutor(handler), callback);
+ }
+ }
+
+ /**
+ * Remove a {@link OnMediaKeyEventDispatchedListener}.
+ *
+ * @param listener A {@link OnMediaKeyEventDispatchedListener}.
+ * @hide
+ */
+ @SystemApi
+ @RequiresPermission(value = android.Manifest.permission.MEDIA_CONTENT_CONTROL)
+ public void removeOnMediaKeyEventDispatchedListener(
+ @NonNull OnMediaKeyEventDispatchedListener listener) {
+ if (listener == null) {
+ throw new NullPointerException("listener shouldn't be null");
+ }
+ synchronized (mLock) {
+ try {
+ mOnMediaKeyEventDispatchedListeners.remove(listener);
+ if (mOnMediaKeyEventDispatchedListeners.size() == 0) {
+ mService.removeOnMediaKeyEventDispatchedListener(
+ mOnMediaKeyEventDispatchedListenerStub);
+ }
+ } catch (RemoteException e) {
+ Log.e(TAG, "Failed to set media key event dispatched listener", e);
}
}
}
/**
- * Register a {@link Callback}.
+ * Add a {@link OnMediaKeyEventDispatchedListener}.
*
* @param executor The executor on which the callback should be invoked
- * @param callback A {@link Callback}.
+ * @param listener A {@link OnMediaKeyEventSessionChangedListener}.
* @hide
*/
@SystemApi
@RequiresPermission(value = android.Manifest.permission.MEDIA_CONTENT_CONTROL)
- public void registerCallback(@NonNull @CallbackExecutor Executor executor,
- @NonNull Callback callback) {
+ public void addOnMediaKeyEventSessionChangedListener(
+ @NonNull @CallbackExecutor Executor executor,
+ @NonNull OnMediaKeyEventSessionChangedListener listener) {
if (executor == null) {
throw new NullPointerException("executor shouldn't be null");
}
- if (callback == null) {
- throw new NullPointerException("callback shouldn't be null");
+ if (listener == null) {
+ throw new NullPointerException("listener shouldn't be null");
}
synchronized (mLock) {
try {
- mCallbacks.put(callback, executor);
- if (mCurMediaButtonSession != null) {
- executor.execute(
- () -> callback.onAddressedPlayerChanged(mCurMediaButtonSession));
- } else if (mCurMediaButtonReceiver != null) {
- executor.execute(
- () -> callback.onAddressedPlayerChanged(mCurMediaButtonReceiver));
- }
-
- if (mCallbacks.size() == 1) {
- mService.registerCallback(mCbStub);
+ mMediaKeyEventSessionChangedCallbacks.put(listener, executor);
+ executor.execute(
+ () -> listener.onMediaKeyEventSessionChanged(
+ mCurMediaKeyEventSessionPackage, mCurMediaKeyEventSession));
+ if (mMediaKeyEventSessionChangedCallbacks.size() == 1) {
+ mService.addOnMediaKeyEventSessionChangedListener(
+ mOnMediaKeyEventSessionChangedListenerStub);
}
} catch (RemoteException e) {
- Log.e(TAG, "Failed to set media key callback", e);
+ Log.e(TAG, "Failed to set media key listener", e);
}
}
}
/**
- * Unregister a {@link Callback}.
+ * Remove a {@link OnMediaKeyEventSessionChangedListener}.
*
- * @param callback A {@link Callback}.
+ * @param listener A {@link OnMediaKeyEventSessionChangedListener}.
* @hide
*/
@SystemApi
@RequiresPermission(value = android.Manifest.permission.MEDIA_CONTENT_CONTROL)
- public void unregisterCallback(@NonNull Callback callback) {
- if (callback == null) {
- throw new NullPointerException("callback shouldn't be null");
+ public void removeOnMediaKeyEventSessionChangedListener(
+ @NonNull OnMediaKeyEventSessionChangedListener listener) {
+ if (listener == null) {
+ throw new NullPointerException("listener shouldn't be null");
}
synchronized (mLock) {
try {
- mCallbacks.remove(callback);
- if (mCallbacks.size() == 0) {
- mService.unregisterCallback(mCbStub);
+ mMediaKeyEventSessionChangedCallbacks.remove(listener);
+ if (mMediaKeyEventSessionChangedCallbacks.size() == 0) {
+ mService.removeOnMediaKeyEventSessionChangedListener(
+ mOnMediaKeyEventSessionChangedListenerStub);
}
} catch (RemoteException e) {
- Log.e(TAG, "Failed to set media key callback", e);
+ Log.e(TAG, "Failed to set media key listener", e);
}
}
}
@@ -900,54 +932,46 @@ public final class MediaSessionManager {
}
/**
- * Callbacks for the media session service.
- *
- * <p>Called when a media key event is dispatched or the addressed player is changed.
- * The addressed player is either the media session or the media button receiver that will
- * receive media key events.
+ * Listener to receive when the media session service
* @hide
*/
@SystemApi
- public static abstract class Callback {
+ public interface OnMediaKeyEventDispatchedListener {
/**
- * Called when a media key event is dispatched to the media session
- * through the media session service.
+ * Called when a media key event is dispatched through the media session service. The
+ * session token can be {@link null} if the framework has sent the media key event to the
+ * media button receiver to revive the media app's playback.
*
- * @param event Dispatched media key event.
- * @param sessionToken The media session's token.
- */
- public abstract void onMediaKeyEventDispatched(KeyEvent event,
- MediaSession.Token sessionToken);
-
- /**
- * Called when a media key event is dispatched to the media button receiver
- * through the media session service.
- * <p>MediaSessionService may broadcast key events to the media button receiver
- * when reviving playback after the media session is released.
+ * the session is dead when , but the framework sent
*
* @param event Dispatched media key event.
- * @param mediaButtonReceiver The media button receiver.
+ * @param packageName Package
+ * @param sessionToken The media session's token. Can be {@code null}.
*/
- public abstract void onMediaKeyEventDispatched(KeyEvent event,
- ComponentName mediaButtonReceiver);
-
- /**
- * Called when the addressed player is changed to a media session.
- * <p>One of the {@ #onAddressedPlayerChanged} will be also called immediately after
- * {@link #registerCallback} if the addressed player exists.
- *
- * @param sessionToken The media session's token.
- */
- public abstract void onAddressedPlayerChanged(MediaSession.Token sessionToken);
+ default void onMediaKeyEventDispatched(@NonNull KeyEvent event, @NonNull String packageName,
+ @NonNull MediaSession.Token sessionToken) { }
+ }
+ /**
+ * Listener to receive changes in the media key event session, which would receive the media key
+ * event unless specified.
+ * @hide
+ */
+ @SystemApi
+ public interface OnMediaKeyEventSessionChangedListener {
/**
- * Called when the addressed player is changed to the media button receiver.
- * <p>One of the {@ #onAddressedPlayerChanged} will be also called immediately after
- * {@link #registerCallback} if the addressed player exists.
+ * Called when the media key session is changed to the given media session. The key event
+ * session is the media session which would receive key event by default, unless the caller
+ * has specified the target.
+ * <p>
+ * The session token can be {@link null} if the media button session is unset. In that case,
+ * framework would dispatch to the last sessions's media button receiver.
*
- * @param mediaButtonReceiver The media button receiver.
+ * @param packageName The package name who would receive the media key event. Can be empty.
+ * @param sessionToken The media session's token. Can be {@code null.}
*/
- public abstract void onAddressedPlayerChanged(ComponentName mediaButtonReceiver);
+ default void onMediaKeyEventSessionChanged(@NonNull String packageName,
+ @Nullable MediaSession.Token sessionToken) { }
}
/**
@@ -1149,50 +1173,35 @@ public final class MediaSessionManager {
}
}
- private final class CallbackStub extends ICallback.Stub {
+ private final class OnMediaKeyEventDispatchedListenerStub
+ extends IOnMediaKeyEventDispatchedListener.Stub {
@Override
- public void onMediaKeyEventDispatchedToMediaSession(KeyEvent event,
+ public void onMediaKeyEventDispatched(KeyEvent event, String packageName,
MediaSession.Token sessionToken) {
synchronized (mLock) {
- for (Map.Entry<Callback, Executor> e : mCallbacks.entrySet()) {
- e.getValue().execute(
- () -> e.getKey().onMediaKeyEventDispatched(event, sessionToken));
- }
- }
- }
-
- @Override
- public void onMediaKeyEventDispatchedToMediaButtonReceiver(KeyEvent event,
- ComponentName mediaButtonReceiver) {
- synchronized (mLock) {
- for (Map.Entry<Callback, Executor> e : mCallbacks.entrySet()) {
+ for (Map.Entry<OnMediaKeyEventDispatchedListener, Executor> e
+ : mOnMediaKeyEventDispatchedListeners.entrySet()) {
e.getValue().execute(
- () -> e.getKey().onMediaKeyEventDispatched(event, mediaButtonReceiver));
- }
- }
- }
-
- @Override
- public void onAddressedPlayerChangedToMediaSession(MediaSession.Token sessionToken) {
- synchronized (mLock) {
- mCurMediaButtonSession = sessionToken;
- mCurMediaButtonReceiver = null;
- for (Map.Entry<Callback, Executor> e : mCallbacks.entrySet()) {
- e.getValue().execute(() -> e.getKey().onAddressedPlayerChanged(sessionToken));
+ () -> e.getKey().onMediaKeyEventDispatched(event, packageName,
+ sessionToken));
}
}
}
+ }
+ private final class OnMediaKeyEventSessionChangedListenerStub
+ extends IOnMediaKeyEventSessionChangedListener.Stub {
@Override
- public void onAddressedPlayerChangedToMediaButtonReceiver(
- ComponentName mediaButtonReceiver) {
+ public void onMediaKeyEventSessionChanged(String packageName,
+ MediaSession.Token sessionToken) {
synchronized (mLock) {
- mCurMediaButtonSession = null;
- mCurMediaButtonReceiver = mediaButtonReceiver;
- for (Map.Entry<Callback, Executor> e : mCallbacks.entrySet()) {
- e.getValue().execute(() -> e.getKey().onAddressedPlayerChanged(
- mediaButtonReceiver));
+ mCurMediaKeyEventSessionPackage = packageName;
+ mCurMediaKeyEventSession = sessionToken;
+ for (Map.Entry<OnMediaKeyEventSessionChangedListener, Executor> e
+ : mMediaKeyEventSessionChangedCallbacks.entrySet()) {
+ e.getValue().execute(() -> e.getKey().onMediaKeyEventSessionChanged(packageName,
+ sessionToken));
}
}
}
diff --git a/media/java/android/media/soundtrigger/SoundTriggerManager.java b/media/java/android/media/soundtrigger/SoundTriggerManager.java
index dc400ad26eed..61b3e76e7cee 100644
--- a/media/java/android/media/soundtrigger/SoundTriggerManager.java
+++ b/media/java/android/media/soundtrigger/SoundTriggerManager.java
@@ -26,9 +26,11 @@ import android.annotation.SystemService;
import android.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
+import android.hardware.soundtrigger.ModelParams;
import android.hardware.soundtrigger.SoundTrigger;
import android.hardware.soundtrigger.SoundTrigger.GenericSoundModel;
import android.hardware.soundtrigger.SoundTrigger.KeyphraseSoundModel;
+import android.hardware.soundtrigger.SoundTrigger.ModelParamRange;
import android.hardware.soundtrigger.SoundTrigger.RecognitionConfig;
import android.hardware.soundtrigger.SoundTrigger.SoundModel;
import android.os.Bundle;
@@ -67,7 +69,7 @@ public final class SoundTriggerManager {
/**
* @hide
*/
- public SoundTriggerManager(Context context, ISoundTriggerService soundTriggerService ) {
+ public SoundTriggerManager(Context context, ISoundTriggerService soundTriggerService) {
if (DBG) {
Slog.i(TAG, "SoundTriggerManager created.");
}
@@ -89,14 +91,22 @@ public final class SoundTriggerManager {
}
/**
- * Returns the sound trigger model represented by the given UUID. An instance of {@link Model}
- * is returned.
+ * Get {@link SoundTriggerManager.Model} which is registered with the passed UUID
+ *
+ * @param soundModelId UUID associated with a loaded model
+ * @return {@link SoundTriggerManager.Model} associated with UUID soundModelId
*/
@RequiresPermission(android.Manifest.permission.MANAGE_SOUND_TRIGGER)
+ @Nullable
public Model getModel(UUID soundModelId) {
try {
- return new Model(mSoundTriggerService.getSoundModel(
- new ParcelUuid(soundModelId)));
+ GenericSoundModel model =
+ mSoundTriggerService.getSoundModel(new ParcelUuid(soundModelId));
+ if (model == null) {
+ return null;
+ }
+
+ return new Model(model);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -399,4 +409,80 @@ public final class SoundTriggerManager {
throw e.rethrowFromSystemServer();
}
}
+
+ /**
+ * Set a model specific {@link ModelParams} with the given value. This
+ * parameter will keep its value for the duration the model is loaded regardless of starting and
+ * stopping recognition. Once the model is unloaded, the value will be lost.
+ * {@link SoundTriggerManager#queryParameter} should be checked first before calling this
+ * method.
+ *
+ * @param soundModelId UUID of model to apply the parameter value to.
+ * @param modelParam {@link ModelParams}
+ * @param value Value to set
+ * @return - {@link SoundTrigger#STATUS_OK} in case of success
+ * - {@link SoundTrigger#STATUS_NO_INIT} if the native service cannot be reached
+ * - {@link SoundTrigger#STATUS_BAD_VALUE} invalid input parameter
+ * - {@link SoundTrigger#STATUS_INVALID_OPERATION} if the call is out of sequence or
+ * if API is not supported by HAL
+ */
+ @RequiresPermission(android.Manifest.permission.MANAGE_SOUND_TRIGGER)
+ public int setParameter(@Nullable UUID soundModelId,
+ @ModelParams int modelParam, int value)
+ throws UnsupportedOperationException, IllegalArgumentException {
+ try {
+ return mSoundTriggerService.setParameter(new ParcelUuid(soundModelId), modelParam,
+ value);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Get a model specific {@link ModelParams}. This parameter will keep its value
+ * for the duration the model is loaded regardless of starting and stopping recognition.
+ * Once the model is unloaded, the value will be lost. If the value is not set, a default
+ * value is returned. See {@link ModelParams} for parameter default values.
+ * {@link SoundTriggerManager#queryParameter} should be checked first before
+ * calling this method. Otherwise, an exception can be thrown.
+ *
+ * @param soundModelId UUID of model to get parameter
+ * @param modelParam {@link ModelParams}
+ * @return value of parameter
+ * @throws UnsupportedOperationException if hal or model do not support this API.
+ * {@link SoundTriggerManager#queryParameter} should be checked first.
+ * @throws IllegalArgumentException if invalid model handle or parameter is passed.
+ * {@link SoundTriggerManager#queryParameter} should be checked first.
+ */
+ @RequiresPermission(android.Manifest.permission.MANAGE_SOUND_TRIGGER)
+ public int getParameter(@NonNull UUID soundModelId,
+ @ModelParams int modelParam)
+ throws UnsupportedOperationException, IllegalArgumentException {
+ try {
+ return mSoundTriggerService.getParameter(new ParcelUuid(soundModelId), modelParam);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Determine if parameter control is supported for the given model handle.
+ * This method should be checked prior to calling {@link SoundTriggerManager#setParameter} or
+ * {@link SoundTriggerManager#getParameter}.
+ *
+ * @param soundModelId handle of model to get parameter
+ * @param modelParam {@link ModelParams}
+ * @return supported range of parameter, null if not supported
+ */
+ @RequiresPermission(android.Manifest.permission.MANAGE_SOUND_TRIGGER)
+ @Nullable
+ public ModelParamRange queryParameter(@Nullable UUID soundModelId,
+ @ModelParams int modelParam) {
+ try {
+ return mSoundTriggerService.queryParameter(new ParcelUuid(soundModelId),
+ modelParam);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
}
diff --git a/media/java/android/media/soundtrigger_middleware/ConfidenceLevel.aidl b/media/java/android/media/soundtrigger_middleware/ConfidenceLevel.aidl
new file mode 100644
index 000000000000..3dbc70556bd3
--- /dev/null
+++ b/media/java/android/media/soundtrigger_middleware/ConfidenceLevel.aidl
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2019 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.media.soundtrigger_middleware;
+
+/**
+ * A recognition confidence level.
+ * This type is used to represent either a threshold or an actual detection confidence level.
+ *
+ * {@hide}
+ */
+parcelable ConfidenceLevel {
+ /** user ID. */
+ int userId;
+ /**
+ * Confidence level in percent (0 - 100).
+ * <ul>
+ * <li>Min level for recognition configuration
+ * <li>Detected level for recognition event.
+ * </ul>
+ */
+ int levelPercent;
+}
diff --git a/media/java/android/media/soundtrigger_middleware/ISoundTriggerCallback.aidl b/media/java/android/media/soundtrigger_middleware/ISoundTriggerCallback.aidl
new file mode 100644
index 000000000000..149c1cd0447b
--- /dev/null
+++ b/media/java/android/media/soundtrigger_middleware/ISoundTriggerCallback.aidl
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2019 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.media.soundtrigger_middleware;
+
+import android.media.soundtrigger_middleware.RecognitionEvent;
+import android.media.soundtrigger_middleware.PhraseRecognitionEvent;
+
+/**
+ * Main interface for a client to get notifications of events coming from this module.
+ *
+ * {@hide}
+ */
+oneway interface ISoundTriggerCallback {
+ /**
+ * Invoked whenever a recognition event is triggered (typically, on recognition, but also in
+ * case of external aborting of a recognition or a forced recognition event - see the status
+ * code in the event for determining).
+ */
+ void onRecognition(int modelHandle, in RecognitionEvent event);
+ /**
+ * Invoked whenever a phrase recognition event is triggered (typically, on recognition, but
+ * also in case of external aborting of a recognition or a forced recognition event - see the
+ * status code in the event for determining).
+ */
+ void onPhraseRecognition(int modelHandle, in PhraseRecognitionEvent event);
+ /**
+ * Notifies the client the recognition has become available after previously having been
+ * unavailable, or vice versa. This method will always be invoked once immediately after
+ * attachment, and then every time there is a change in availability.
+ * When availability changes from available to unavailable, all active recognitions are aborted,
+ * and this event will be sent in addition to the abort event.
+ */
+ void onRecognitionAvailabilityChange(boolean available);
+}
diff --git a/media/java/android/media/soundtrigger_middleware/ISoundTriggerMiddlewareService.aidl b/media/java/android/media/soundtrigger_middleware/ISoundTriggerMiddlewareService.aidl
new file mode 100644
index 000000000000..80333070b7ce
--- /dev/null
+++ b/media/java/android/media/soundtrigger_middleware/ISoundTriggerMiddlewareService.aidl
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2019 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.media.soundtrigger_middleware;
+
+import android.media.soundtrigger_middleware.ISoundTriggerModule;
+import android.media.soundtrigger_middleware.ISoundTriggerCallback;
+import android.media.soundtrigger_middleware.SoundTriggerModuleDescriptor;
+
+/**
+ * Main entry point into this module.
+ *
+ * Allows the client to enumerate the available soundtrigger devices and their capabilities, then
+ * attach to either one of them in order to use it.
+ *
+ * {@hide}
+ */
+interface ISoundTriggerMiddlewareService {
+ /**
+ * Query the available modules and their capabilities.
+ */
+ SoundTriggerModuleDescriptor[] listModules();
+
+ /**
+ * Attach to one of the available modules.
+ * listModules() must be called prior to calling this method and the provided handle must be
+ * one of the handles from the returned list.
+ */
+ ISoundTriggerModule attach(int handle, ISoundTriggerCallback callback);
+
+ /**
+ * Notify the service that external input capture is taking place. This may cause some of the
+ * active recognitions to be aborted.
+ */
+ void setExternalCaptureState(boolean active);
+} \ No newline at end of file
diff --git a/media/java/android/media/soundtrigger_middleware/ISoundTriggerModule.aidl b/media/java/android/media/soundtrigger_middleware/ISoundTriggerModule.aidl
new file mode 100644
index 000000000000..c4a57857dd3d
--- /dev/null
+++ b/media/java/android/media/soundtrigger_middleware/ISoundTriggerModule.aidl
@@ -0,0 +1,148 @@
+/*
+ * Copyright (C) 2019 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.media.soundtrigger_middleware;
+
+import android.media.soundtrigger_middleware.ModelParameter;
+import android.media.soundtrigger_middleware.ModelParameterRange;
+import android.media.soundtrigger_middleware.SoundModel;
+import android.media.soundtrigger_middleware.PhraseSoundModel;
+import android.media.soundtrigger_middleware.RecognitionConfig;
+
+/**
+ * A sound-trigger module.
+ *
+ * This interface allows a client to operate a sound-trigger device, intended for low-power
+ * detection of various sound patterns, represented by a "sound model".
+ *
+ * Basic operation is to load a sound model (either a generic one or a "phrase" model), then
+ * initiate recognition on this model. A trigger will be delivered asynchronously via a callback
+ * provided by the caller earlier, when attaching to this interface.
+ *
+ * In additon to recognition events, this module will also produce abort events in cases where
+ * recognition has been externally preempted.
+ *
+ * {@hide}
+ */
+interface ISoundTriggerModule {
+ /**
+ * Load a sound model. Will return a handle to the model on success or will throw a
+ * ServiceSpecificException with one of the {@link Status} error codes upon a recoverable error
+ * (for example, lack of resources of loading a model at the time of call.
+ * Model must eventually be unloaded using {@link #unloadModel(int)} prior to detaching.
+ *
+ * May throw a ServiceSpecificException with an RESOURCE_CONTENTION status to indicate that
+ * resources required for loading the model are currently consumed by other clients.
+ */
+ int loadModel(in SoundModel model);
+
+ /**
+ * Load a phrase sound model. Will return a handle to the model on success or will throw a
+ * ServiceSpecificException with one of the {@link Status} error codes upon a recoverable error
+ * (for example, lack of resources of loading a model at the time of call.
+ * Model must eventually be unloaded using unloadModel prior to detaching.
+ *
+ * May throw a ServiceSpecificException with an RESOURCE_CONTENTION status to indicate that
+ * resources required for loading the model are currently consumed by other clients.
+ */
+ int loadPhraseModel(in PhraseSoundModel model);
+
+ /**
+ * Unload a model, previously loaded with loadModel or loadPhraseModel. After unloading, model
+ * can no longer be used for recognition and the resources occupied by it are released.
+ * Model must not be active at the time of unloading. Cient may call stopRecognition to ensure
+ * that.
+ */
+ void unloadModel(int modelHandle);
+
+ /**
+ * Initiate recognition on a previously loaded model.
+ * Recognition event would eventually be delivered via the client-provided callback, typically
+ * supplied during attachment to this interface.
+ *
+ * Once a recognition event is passed to the client, the recognition automatically become
+ * inactive, unless the event is of the RecognitionStatus.FORCED kind. Client can also shut down
+ * the recognition explicitly, via stopRecognition.
+ */
+ void startRecognition(int modelHandle, in RecognitionConfig config);
+
+ /**
+ * Stop a recognition of a previously active recognition. Will NOT generate a recognition event.
+ * This call is idempotent - calling it on an inactive model has no effect. However, it must
+ * only be used with a loaded model handle.
+ */
+ void stopRecognition(int modelHandle);
+
+ /**
+ * Force generation of a recognition event. Handle must be that of a loaded model. If
+ * recognition is inactive, will do nothing. If recognition is active, will asynchronously
+ * deliever an event with RecognitionStatus.FORCED status and leave recognition in active state.
+ * To avoid any race conditions, once an event signalling the automatic stopping of recognition
+ * is sent, no more forced events will get sent (even if previously requested) until recognition
+ * is explicitly started again.
+ *
+ * Since not all module implementations support this feature, may throw a
+ * ServiceSpecificException with an OPERATION_NOT_SUPPORTED status.
+ */
+ void forceRecognitionEvent(int modelHandle);
+
+ /**
+ * Set a model specific parameter with the given value. This parameter
+ * will keep its value for the duration the model is loaded regardless of starting and stopping
+ * recognition. Once the model is unloaded, the value will be lost.
+ * It is expected to check if the handle supports the parameter via the
+ * queryModelParameterSupport API prior to calling this method.
+ *
+ * @param modelHandle The sound model handle indicating which model to modify parameters
+ * @param modelParam Parameter to set which will be validated against the
+ * ModelParameter type.
+ * @param value The value to set for the given model parameter
+ */
+ void setModelParameter(int modelHandle, ModelParameter modelParam, int value);
+
+ /**
+ * Get a model specific parameter. This parameter will keep its value
+ * for the duration the model is loaded regardless of starting and stopping recognition.
+ * Once the model is unloaded, the value will be lost. If the value is not set, a default
+ * value is returned. See ModelParameter for parameter default values.
+ * It is expected to check if the handle supports the parameter via the
+ * queryModelParameterSupport API prior to calling this method.
+ *
+ * @param modelHandle The sound model associated with given modelParam
+ * @param modelParam Parameter to set which will be validated against the
+ * ModelParameter type.
+ * @return Value set to the requested parameter.
+ */
+ int getModelParameter(int modelHandle, ModelParameter modelParam);
+
+ /**
+ * Determine if parameter control is supported for the given model handle, and its valid value
+ * range if it is.
+ *
+ * @param modelHandle The sound model handle indicating which model to query
+ * @param modelParam Parameter to set which will be validated against the
+ * ModelParameter type.
+ * @return If parameter is supported, the return value is its valid range, otherwise null.
+ */
+ @nullable ModelParameterRange queryModelParameterSupport(int modelHandle,
+ ModelParameter modelParam);
+
+ /**
+ * Detach from the module, releasing any active resources.
+ * This will ensure the client callback is no longer called after this call returns.
+ * All models must have been unloaded prior to calling this method.
+ */
+ void detach();
+} \ No newline at end of file
diff --git a/media/java/android/media/soundtrigger_middleware/ModelParameter.aidl b/media/java/android/media/soundtrigger_middleware/ModelParameter.aidl
new file mode 100644
index 000000000000..09936278e93a
--- /dev/null
+++ b/media/java/android/media/soundtrigger_middleware/ModelParameter.aidl
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2019 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.media.soundtrigger_middleware;
+
+/**
+ * Model specific parameters to be used with parameter set and get APIs.
+ *
+ * {@hide}
+ */
+@Backing(type="int")
+enum ModelParameter {
+ /**
+ * Placeholder for invalid model parameter used for returning error or
+ * passing an invalid value.
+ */
+ INVALID = -1,
+
+ /**
+ * Controls the sensitivity threshold adjustment factor for a given model.
+ * Negative value corresponds to less sensitive model (high threshold) and
+ * a positive value corresponds to a more sensitive model (low threshold).
+ * Default value is 0.
+ */
+ THRESHOLD_FACTOR = 0,
+}
diff --git a/media/java/android/media/soundtrigger_middleware/ModelParameterRange.aidl b/media/java/android/media/soundtrigger_middleware/ModelParameterRange.aidl
new file mode 100644
index 000000000000..d6948a87dc6d
--- /dev/null
+++ b/media/java/android/media/soundtrigger_middleware/ModelParameterRange.aidl
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2019 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.media.soundtrigger_middleware;
+
+/**
+ * Value range for a model parameter.
+ *
+ * {@hide}
+ */
+parcelable ModelParameterRange {
+ /** Minimum (inclusive) */
+ int minInclusive;
+ /** Maximum (inclusive) */
+ int maxInclusive;
+}
diff --git a/media/java/android/media/soundtrigger_middleware/Phrase.aidl b/media/java/android/media/soundtrigger_middleware/Phrase.aidl
new file mode 100644
index 000000000000..98a489f8a6a9
--- /dev/null
+++ b/media/java/android/media/soundtrigger_middleware/Phrase.aidl
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2019 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.media.soundtrigger_middleware;
+
+/**
+ * Key phrase descriptor.
+ *
+ * {@hide}
+ */
+parcelable Phrase {
+ /** Unique keyphrase ID assigned at enrollment time. */
+ int id;
+ /** Recognition modes supported by this key phrase (bitfield of RecognitionMode enum). */
+ int recognitionModes;
+ /** List of users IDs associated with this key phrase. */
+ int[] users;
+ /** Locale - Java Locale style (e.g. en_US). */
+ String locale;
+ /** Phrase text. */
+ String text;
+}
diff --git a/media/java/android/media/soundtrigger_middleware/PhraseRecognitionEvent.aidl b/media/java/android/media/soundtrigger_middleware/PhraseRecognitionEvent.aidl
new file mode 100644
index 000000000000..6a3ec61d1ebf
--- /dev/null
+++ b/media/java/android/media/soundtrigger_middleware/PhraseRecognitionEvent.aidl
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2019 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.media.soundtrigger_middleware;
+
+import android.media.soundtrigger_middleware.PhraseRecognitionExtra;
+import android.media.soundtrigger_middleware.RecognitionEvent;
+
+/**
+ * An event that gets sent to indicate a phrase recognition (or aborting of the recognition
+ process).
+ * {@hide}
+ */
+parcelable PhraseRecognitionEvent {
+ /** Common recognition event. */
+ RecognitionEvent common;
+ /** List of descriptors for each recognized key phrase */
+ PhraseRecognitionExtra[] phraseExtras;
+}
diff --git a/media/java/android/media/soundtrigger_middleware/PhraseRecognitionExtra.aidl b/media/java/android/media/soundtrigger_middleware/PhraseRecognitionExtra.aidl
new file mode 100644
index 000000000000..cb96bf37a95d
--- /dev/null
+++ b/media/java/android/media/soundtrigger_middleware/PhraseRecognitionExtra.aidl
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2019 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.media.soundtrigger_middleware;
+
+import android.media.soundtrigger_middleware.ConfidenceLevel;
+
+/**
+ * Specialized recognition event for key phrase detection.
+ * {@hide}
+ */
+parcelable PhraseRecognitionExtra {
+ // TODO(ytai): Constants / enums.
+
+ /** keyphrase ID */
+ int id;
+ /** recognition modes used for this keyphrase */
+ int recognitionModes;
+ /** confidence level for mode RECOGNITION_MODE_VOICE_TRIGGER */
+ int confidenceLevel;
+ /** number of user confidence levels */
+ ConfidenceLevel[] levels;
+}
diff --git a/media/java/android/media/soundtrigger_middleware/PhraseSoundModel.aidl b/media/java/android/media/soundtrigger_middleware/PhraseSoundModel.aidl
new file mode 100644
index 000000000000..81028c1608ea
--- /dev/null
+++ b/media/java/android/media/soundtrigger_middleware/PhraseSoundModel.aidl
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2019 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.media.soundtrigger_middleware;
+
+import android.media.soundtrigger_middleware.SoundModel;
+import android.media.soundtrigger_middleware.Phrase;
+
+/**
+ * Specialized sound model for key phrase detection.
+ * Proprietary representation of key phrases in binary data must match
+ * information indicated by phrases field.
+ * {@hide}
+ */
+parcelable PhraseSoundModel {
+ /** Common part of sound model descriptor */
+ SoundModel common;
+ /** List of descriptors for key phrases supported by this sound model */
+ Phrase[] phrases;
+}
diff --git a/media/java/android/media/soundtrigger_middleware/RecognitionConfig.aidl b/media/java/android/media/soundtrigger_middleware/RecognitionConfig.aidl
new file mode 100644
index 000000000000..c7642e8c1241
--- /dev/null
+++ b/media/java/android/media/soundtrigger_middleware/RecognitionConfig.aidl
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2019 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.media.soundtrigger_middleware;
+
+import android.media.soundtrigger_middleware.PhraseRecognitionExtra;
+
+/**
+ * Configuration for tuning behavior of an active recognition process.
+ * {@hide}
+ */
+parcelable RecognitionConfig {
+ /* Capture and buffer audio for this recognition instance. */
+ boolean captureRequested;
+
+ /* Configuration for each key phrase. */
+ PhraseRecognitionExtra[] phraseRecognitionExtras;
+
+ /** Opaque capture configuration data. */
+ byte[] data;
+}
diff --git a/media/java/android/media/soundtrigger_middleware/RecognitionEvent.aidl b/media/java/android/media/soundtrigger_middleware/RecognitionEvent.aidl
new file mode 100644
index 000000000000..de4d060ce484
--- /dev/null
+++ b/media/java/android/media/soundtrigger_middleware/RecognitionEvent.aidl
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2019 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.media.soundtrigger_middleware;
+
+import android.media.audio.common.AudioConfig;
+import android.media.soundtrigger_middleware.RecognitionStatus;
+import android.media.soundtrigger_middleware.SoundModelType;
+
+/**
+ * An event that gets sent to indicate a recognition (or aborting of the recognition process).
+ * {@hide}
+ */
+parcelable RecognitionEvent {
+ /** Recognition status. */
+ RecognitionStatus status;
+ /** Event type, same as sound model type. */
+ SoundModelType type;
+ /** Is it possible to capture audio from this utterance buffered by the implementation. */
+ boolean captureAvailable;
+ /* Audio session ID. framework use. */
+ int captureSession;
+ /**
+ * Delay in ms between end of model detection and start of audio available for capture.
+ * A negative value is possible (e.g. if key phrase is also available for Capture.
+ */
+ int captureDelayMs;
+ /** Duration in ms of audio captured before the start of the trigger. 0 if none. */
+ int capturePreambleMs;
+ /** If true, the 'data' field below contains the capture of the trigger sound. */
+ boolean triggerInData;
+ /**
+ * Audio format of either the trigger in event data or to use for capture of the rest of the
+ * utterance.
+ */
+ AudioConfig audioConfig;
+ /** Additional data. */
+ byte[] data;
+}
diff --git a/media/java/android/media/soundtrigger_middleware/RecognitionMode.aidl b/media/java/android/media/soundtrigger_middleware/RecognitionMode.aidl
new file mode 100644
index 000000000000..d8bfff4bec6f
--- /dev/null
+++ b/media/java/android/media/soundtrigger_middleware/RecognitionMode.aidl
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2019 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.media.soundtrigger_middleware;
+
+/**
+ * Recognition mode.
+ * {@hide}
+ */
+@Backing(type="int")
+enum RecognitionMode {
+ /** Simple voice trigger. */
+ VOICE_TRIGGER = 0x1,
+ /** Trigger only if one user in model identified. */
+ USER_IDENTIFICATION = 0x2,
+ /** Trigger only if one user in model authenticated. */
+ USER_AUTHENTICATION = 0x4,
+ /** Generic sound trigger. */
+ GENERIC_TRIGGER = 0x8,
+}
diff --git a/media/java/android/media/soundtrigger_middleware/RecognitionStatus.aidl b/media/java/android/media/soundtrigger_middleware/RecognitionStatus.aidl
new file mode 100644
index 000000000000..d563edca547d
--- /dev/null
+++ b/media/java/android/media/soundtrigger_middleware/RecognitionStatus.aidl
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2019 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.media.soundtrigger_middleware;
+
+/**
+ * A status for indicating the type of a recognition event.
+ * {@hide}
+ */
+@Backing(type="int")
+enum RecognitionStatus {
+ /** Recognition success. */
+ SUCCESS = 0,
+ /** Recognition aborted (e.g. capture preempted by another use-case. */
+ ABORTED = 1,
+ /** Recognition failure. */
+ FAILURE = 2,
+ /**
+ * Recognition event was triggered by a forceRecognitionEvent request, not by the DSP.
+ * Note that forced detections *do not* stop the active recognition, unlike the other types.
+ */
+ FORCED = 3
+}
diff --git a/media/java/android/media/soundtrigger_middleware/SoundModel.aidl b/media/java/android/media/soundtrigger_middleware/SoundModel.aidl
new file mode 100644
index 000000000000..fba1ee507836
--- /dev/null
+++ b/media/java/android/media/soundtrigger_middleware/SoundModel.aidl
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2019 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.media.soundtrigger_middleware;
+
+import android.media.soundtrigger_middleware.SoundModelType;
+
+/**
+ * Base sound model descriptor. This struct can be extended for various specific types by way of
+ * aggregation.
+ * {@hide}
+ */
+parcelable SoundModel {
+ /** Model type. */
+ SoundModelType type;
+ /** Unique sound model ID. */
+ String uuid;
+ /**
+ * Unique vendor ID. Identifies the engine the sound model
+ * was build for */
+ String vendorUuid;
+ /** Opaque data transparent to Android framework */
+ byte[] data;
+}
diff --git a/media/java/android/media/soundtrigger_middleware/SoundModelType.aidl b/media/java/android/media/soundtrigger_middleware/SoundModelType.aidl
new file mode 100644
index 000000000000..f2abc9af7780
--- /dev/null
+++ b/media/java/android/media/soundtrigger_middleware/SoundModelType.aidl
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2019 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.media.soundtrigger_middleware;
+
+/**
+ * Sound model type.
+ * {@hide}
+ */
+@Backing(type="int")
+enum SoundModelType {
+ /** Unspecified sound model type */
+ UNKNOWN = -1,
+ /** Key phrase sound models */
+ KEYPHRASE = 0,
+ /** All models other than keyphrase */
+ GENERIC = 1,
+}
diff --git a/media/java/android/media/soundtrigger_middleware/SoundTriggerModuleDescriptor.aidl b/media/java/android/media/soundtrigger_middleware/SoundTriggerModuleDescriptor.aidl
new file mode 100644
index 000000000000..667135ff61b9
--- /dev/null
+++ b/media/java/android/media/soundtrigger_middleware/SoundTriggerModuleDescriptor.aidl
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2019 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.media.soundtrigger_middleware;
+
+import android.media.soundtrigger_middleware.SoundTriggerModuleProperties;
+
+/**
+ * A descriptor of an available sound trigger module, containing the handle used to reference the
+ * module, as well its capabilities.
+ * {@hide}
+ */
+parcelable SoundTriggerModuleDescriptor {
+ /** Module handle to be used for attaching to it. */
+ int handle;
+ /** Module capabilities. */
+ SoundTriggerModuleProperties properties;
+}
+
diff --git a/media/java/android/media/soundtrigger_middleware/SoundTriggerModuleProperties.aidl b/media/java/android/media/soundtrigger_middleware/SoundTriggerModuleProperties.aidl
new file mode 100644
index 000000000000..1a3b40261a62
--- /dev/null
+++ b/media/java/android/media/soundtrigger_middleware/SoundTriggerModuleProperties.aidl
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2019 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.media.soundtrigger_middleware;
+
+/**
+ * Capabilities of a sound trigger module.
+ * {@hide}
+ */
+parcelable SoundTriggerModuleProperties {
+ /** Implementor name */
+ String implementor;
+ /** Implementation description */
+ String description;
+ /** Implementation version */
+ int version;
+ /**
+ * Unique implementation ID. The UUID must change with each version of
+ the engine implementation */
+ String uuid;
+ /** Maximum number of concurrent sound models loaded */
+ int maxSoundModels;
+ /** Maximum number of key phrases */
+ int maxKeyPhrases;
+ /** Maximum number of concurrent users detected */
+ int maxUsers;
+ /** All supported modes. e.g RecognitionMode.VOICE_TRIGGER */
+ int recognitionModes;
+ /** Supports seamless transition from detection to capture */
+ boolean captureTransition;
+ /** Maximum buffering capacity in ms if captureTransition is true */
+ int maxBufferMs;
+ /** Supports capture by other use cases while detection is active */
+ boolean concurrentCapture;
+ /** Returns the trigger capture in event */
+ boolean triggerInEvent;
+ /**
+ * Rated power consumption when detection is active with TDB
+ * silence/sound/speech ratio */
+ int powerConsumptionMw;
+}
diff --git a/media/java/android/media/soundtrigger_middleware/Status.aidl b/media/java/android/media/soundtrigger_middleware/Status.aidl
new file mode 100644
index 000000000000..d8f9d8f7e891
--- /dev/null
+++ b/media/java/android/media/soundtrigger_middleware/Status.aidl
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2019 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.media.soundtrigger_middleware;
+
+/**
+ * {@hide}
+ */
+@Backing(type="int")
+enum Status {
+ /** Success. */
+ SUCCESS = 0,
+ /** Failure due to resource contention. This is typically a temporary condition. */
+ RESOURCE_CONTENTION = 1,
+ /** Operation is not supported in this implementation. This is a permanent condition. */
+ OPERATION_NOT_SUPPORTED = 2,
+}
diff --git a/media/java/android/media/tv/ITvInputService.aidl b/media/java/android/media/tv/ITvInputService.aidl
index bd0518493557..f90c50491129 100644..100755
--- a/media/java/android/media/tv/ITvInputService.aidl
+++ b/media/java/android/media/tv/ITvInputService.aidl
@@ -38,4 +38,5 @@ oneway interface ITvInputService {
void notifyHardwareRemoved(in TvInputHardwareInfo hardwareInfo);
void notifyHdmiDeviceAdded(in HdmiDeviceInfo deviceInfo);
void notifyHdmiDeviceRemoved(in HdmiDeviceInfo deviceInfo);
+ void notifyHdmiDeviceUpdated(in HdmiDeviceInfo deviceInfo);
}
diff --git a/media/java/android/media/tv/TvInputService.java b/media/java/android/media/tv/TvInputService.java
index ff6977914ac3..5c11ed9bb7b4 100644..100755
--- a/media/java/android/media/tv/TvInputService.java
+++ b/media/java/android/media/tv/TvInputService.java
@@ -173,6 +173,12 @@ public abstract class TvInputService extends Service {
mServiceHandler.obtainMessage(ServiceHandler.DO_REMOVE_HDMI_INPUT,
deviceInfo).sendToTarget();
}
+
+ @Override
+ public void notifyHdmiDeviceUpdated(HdmiDeviceInfo deviceInfo) {
+ mServiceHandler.obtainMessage(ServiceHandler.DO_UPDATE_HDMI_INPUT,
+ deviceInfo).sendToTarget();
+ }
};
}
@@ -257,6 +263,24 @@ public abstract class TvInputService extends Service {
return null;
}
+ /**
+ * Called when {@code deviceInfo} is updated.
+ *
+ * <p>The changes are usually cuased by the corresponding HDMI-CEC logical device.
+ *
+ * <p>The default behavior ignores all changes.
+ *
+ * <p>The TV input service responsible for {@code deviceInfo} can update the {@link TvInputInfo}
+ * object based on the updated {@code deviceInfo} (e.g. update the label based on the preferred
+ * device OSD name).
+ *
+ * @param deviceInfo the updated {@link HdmiDeviceInfo} object.
+ * @hide
+ */
+ @SystemApi
+ public void onHdmiDeviceUpdated(@NonNull HdmiDeviceInfo deviceInfo) {
+ }
+
private boolean isPassthroughInput(String inputId) {
if (mTvInputManager == null) {
mTvInputManager = (TvInputManager) getSystemService(Context.TV_INPUT_SERVICE);
@@ -1962,6 +1986,7 @@ public abstract class TvInputService extends Service {
private static final int DO_REMOVE_HARDWARE_INPUT = 5;
private static final int DO_ADD_HDMI_INPUT = 6;
private static final int DO_REMOVE_HDMI_INPUT = 7;
+ private static final int DO_UPDATE_HDMI_INPUT = 8;
private void broadcastAddHardwareInput(int deviceId, TvInputInfo inputInfo) {
int n = mCallbacks.beginBroadcast();
@@ -2131,6 +2156,11 @@ public abstract class TvInputService extends Service {
}
return;
}
+ case DO_UPDATE_HDMI_INPUT: {
+ HdmiDeviceInfo deviceInfo = (HdmiDeviceInfo) msg.obj;
+ onHdmiDeviceUpdated(deviceInfo);
+ return;
+ }
default: {
Log.w(TAG, "Unhandled message code: " + msg.what);
return;
diff --git a/media/java/android/media/tv/tuner/DvrSettings.java b/media/java/android/media/tv/tuner/DvrSettings.java
new file mode 100644
index 000000000000..76160dc9fcf8
--- /dev/null
+++ b/media/java/android/media/tv/tuner/DvrSettings.java
@@ -0,0 +1,124 @@
+/*
+ * Copyright 2019 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.media.tv.tuner;
+
+import android.media.tv.tuner.TunerConstants.DataFormat;
+import android.media.tv.tuner.TunerConstants.DvrSettingsType;
+
+/**
+ * DVR settings.
+ *
+ * @hide
+ */
+public class DvrSettings {
+ private int mStatusMask;
+ private int mLowThreshold;
+ private int mHighThreshold;
+ private int mPacketSize;
+
+ @DataFormat
+ private int mDataFormat;
+ @DvrSettingsType
+ private int mType;
+
+ private DvrSettings(int statusMask, int lowThreshold, int highThreshold, int packetSize,
+ @DataFormat int dataFormat, @DvrSettingsType int type) {
+ mStatusMask = statusMask;
+ mLowThreshold = lowThreshold;
+ mHighThreshold = highThreshold;
+ mPacketSize = packetSize;
+ mDataFormat = dataFormat;
+ mType = type;
+ }
+
+ /**
+ * Creates a new builder.
+ */
+ public static Builder newBuilder() {
+ return new Builder();
+ }
+
+ /**
+ * Builder for DvrSettings.
+ */
+ public static final class Builder {
+ private int mStatusMask;
+ private int mLowThreshold;
+ private int mHighThreshold;
+ private int mPacketSize;
+ @DataFormat
+ private int mDataFormat;
+ @DvrSettingsType
+ private int mType;
+
+ /**
+ * Sets status mask.
+ */
+ public Builder setStatusMask(int statusMask) {
+ this.mStatusMask = statusMask;
+ return this;
+ }
+
+ /**
+ * Sets low threshold.
+ */
+ public Builder setLowThreshold(int lowThreshold) {
+ this.mLowThreshold = lowThreshold;
+ return this;
+ }
+
+ /**
+ * Sets high threshold.
+ */
+ public Builder setHighThreshold(int highThreshold) {
+ this.mHighThreshold = highThreshold;
+ return this;
+ }
+
+ /**
+ * Sets packet size.
+ */
+ public Builder setPacketSize(int packetSize) {
+ this.mPacketSize = packetSize;
+ return this;
+ }
+
+ /**
+ * Sets data format.
+ */
+ public Builder setDataFormat(@DataFormat int dataFormat) {
+ this.mDataFormat = dataFormat;
+ return this;
+ }
+
+ /**
+ * Sets settings type.
+ */
+ public Builder setType(@DvrSettingsType int type) {
+ this.mType = type;
+ return this;
+ }
+
+ /**
+ * Builds a DvrSettings instance.
+ */
+ public DvrSettings build() {
+ return new DvrSettings(
+ mStatusMask, mLowThreshold, mHighThreshold, mPacketSize, mDataFormat, mType);
+ }
+ }
+}
diff --git a/media/java/android/media/tv/tuner/Tuner.java b/media/java/android/media/tv/tuner/Tuner.java
index 6537f6fb5a2b..4c93101bc0b5 100644
--- a/media/java/android/media/tv/tuner/Tuner.java
+++ b/media/java/android/media/tv/tuner/Tuner.java
@@ -368,6 +368,7 @@ public final class Tuner implements AutoCloseable {
private native boolean nativeAttachFilter(Filter filter);
private native boolean nativeDetachFilter(Filter filter);
+ private native int nativeConfigureDvr(DvrSettings settings);
private native boolean nativeStartDvr();
private native boolean nativeStopDvr();
private native boolean nativeFlushDvr();
@@ -380,6 +381,9 @@ public final class Tuner implements AutoCloseable {
public boolean detachFilter(Filter filter) {
return nativeDetachFilter(filter);
}
+ public int configure(DvrSettings settings) {
+ return nativeConfigureDvr(settings);
+ }
public boolean start() {
return nativeStartDvr();
}
diff --git a/media/java/android/media/tv/tuner/TunerConstants.java b/media/java/android/media/tv/tuner/TunerConstants.java
index f2d5e939f532..261b2deebac9 100644
--- a/media/java/android/media/tv/tuner/TunerConstants.java
+++ b/media/java/android/media/tv/tuner/TunerConstants.java
@@ -101,6 +101,13 @@ final class TunerConstants {
public static final int FILTER_SETTINGS_TLV = Constants.DemuxFilterMainType.TLV;
public static final int FILTER_SETTINGS_ALP = Constants.DemuxFilterMainType.ALP;
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef({DVR_SETTINGS_RECORD, DVR_SETTINGS_PLAYBACK})
+ public @interface DvrSettingsType {}
+
+ public static final int DVR_SETTINGS_RECORD = Constants.DvrType.RECORD;
+ public static final int DVR_SETTINGS_PLAYBACK = Constants.DvrType.PLAYBACK;
+
private TunerConstants() {
}
}
diff --git a/media/java/android/mtp/MtpDatabase.java b/media/java/android/mtp/MtpDatabase.java
index 16ba63bf031b..f3c071a06eba 100755
--- a/media/java/android/mtp/MtpDatabase.java
+++ b/media/java/android/mtp/MtpDatabase.java
@@ -16,8 +16,10 @@
package android.mtp;
+import android.annotation.NonNull;
import android.content.BroadcastReceiver;
import android.content.ContentProviderClient;
+import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
@@ -422,13 +424,13 @@ public class MtpDatabase implements AutoCloseable {
}
// Add the new file to MediaProvider
if (succeeded) {
- MediaStore.scanFile(mContext, obj.getPath().toFile());
+ MediaStore.scanFile(mContext.getContentResolver(), obj.getPath().toFile());
}
}
@VisibleForNative
private void rescanFile(String path, int handle, int format) {
- MediaStore.scanFile(mContext, new File(path));
+ MediaStore.scanFile(mContext.getContentResolver(), new File(path));
}
@VisibleForNative
@@ -577,7 +579,7 @@ public class MtpDatabase implements AutoCloseable {
try {
// note - we are relying on a special case in MediaProvider.update() to update
// the paths for all children in the case where this is a directory.
- final Uri objectsUri = MediaStore.Files.getMtpObjectsUri(obj.getVolumeName());
+ final Uri objectsUri = MediaStore.Files.getContentUri(obj.getVolumeName());
mMediaProvider.update(objectsUri, values, PATH_WHERE, whereArgs);
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in mMediaProvider.update", e);
@@ -587,13 +589,13 @@ public class MtpDatabase implements AutoCloseable {
if (obj.isDir()) {
// for directories, check if renamed from something hidden to something non-hidden
if (oldPath.getFileName().startsWith(".") && !newPath.startsWith(".")) {
- MediaStore.scanFile(mContext, newPath.toFile());
+ MediaStore.scanFile(mContext.getContentResolver(), newPath.toFile());
}
} else {
// for files, check if renamed from .nomedia to something else
if (oldPath.getFileName().toString().toLowerCase(Locale.US).equals(NO_MEDIA)
&& !newPath.getFileName().toString().toLowerCase(Locale.US).equals(NO_MEDIA)) {
- MediaStore.scanFile(mContext, newPath.getParent().toFile());
+ MediaStore.scanFile(mContext.getContentResolver(), newPath.getParent().toFile());
}
}
return MtpConstants.RESPONSE_OK;
@@ -658,11 +660,11 @@ public class MtpDatabase implements AutoCloseable {
// Old parent exists in MediaProvider - perform a move
// note - we are relying on a special case in MediaProvider.update() to update
// the paths for all children in the case where this is a directory.
- final Uri objectsUri = MediaStore.Files.getMtpObjectsUri(obj.getVolumeName());
+ final Uri objectsUri = MediaStore.Files.getContentUri(obj.getVolumeName());
mMediaProvider.update(objectsUri, values, PATH_WHERE, whereArgs);
} else {
// Old parent doesn't exist - add the object
- MediaStore.scanFile(mContext, path.toFile());
+ MediaStore.scanFile(mContext.getContentResolver(), path.toFile());
}
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in mMediaProvider.update", e);
@@ -689,7 +691,7 @@ public class MtpDatabase implements AutoCloseable {
if (!success) {
return;
}
- MediaStore.scanFile(mContext, obj.getPath().toFile());
+ MediaStore.scanFile(mContext.getContentResolver(), obj.getPath().toFile());
}
@VisibleForNative
@@ -873,7 +875,7 @@ public class MtpDatabase implements AutoCloseable {
}
private int findInMedia(MtpStorageManager.MtpObject obj, Path path) {
- final Uri objectsUri = MediaStore.Files.getMtpObjectsUri(obj.getVolumeName());
+ final Uri objectsUri = MediaStore.Files.getContentUri(obj.getVolumeName());
int ret = -1;
Cursor c = null;
@@ -893,7 +895,7 @@ public class MtpDatabase implements AutoCloseable {
}
private void deleteFromMedia(MtpStorageManager.MtpObject obj, Path path, boolean isDir) {
- final Uri objectsUri = MediaStore.Files.getMtpObjectsUri(obj.getVolumeName());
+ final Uri objectsUri = MediaStore.Files.getContentUri(obj.getVolumeName());
try {
// Delete the object(s) from MediaProvider, but ignore errors.
if (isDir) {
@@ -909,7 +911,7 @@ public class MtpDatabase implements AutoCloseable {
String[] whereArgs = new String[]{path.toString()};
if (mMediaProvider.delete(objectsUri, PATH_WHERE, whereArgs) > 0) {
if (!isDir && path.toString().toLowerCase(Locale.US).endsWith(NO_MEDIA)) {
- MediaStore.scanFile(mContext, path.getParent().toFile());
+ MediaStore.scanFile(mContext.getContentResolver(), path.getParent().toFile());
}
} else {
Log.i(TAG, "Mediaprovider didn't delete " + path);
@@ -921,71 +923,12 @@ public class MtpDatabase implements AutoCloseable {
@VisibleForNative
private int[] getObjectReferences(int handle) {
- MtpStorageManager.MtpObject obj = mManager.getObject(handle);
- if (obj == null)
- return null;
- // Translate this handle to the MediaProvider Handle
- handle = findInMedia(obj, obj.getPath());
- if (handle == -1)
- return null;
- Uri uri = Files.getMtpReferencesUri(obj.getVolumeName(), handle);
- Cursor c = null;
- try {
- c = mMediaProvider.query(uri, PATH_PROJECTION, null, null, null, null);
- if (c == null) {
- return null;
- }
- ArrayList<Integer> result = new ArrayList<>();
- while (c.moveToNext()) {
- // Translate result handles back into handles for this session.
- String refPath = c.getString(0);
- MtpStorageManager.MtpObject refObj = mManager.getByPath(refPath);
- if (refObj != null) {
- result.add(refObj.getId());
- }
- }
- return result.stream().mapToInt(Integer::intValue).toArray();
- } catch (RemoteException e) {
- Log.e(TAG, "RemoteException in getObjectList", e);
- } finally {
- if (c != null) {
- c.close();
- }
- }
return null;
}
@VisibleForNative
private int setObjectReferences(int handle, int[] references) {
- MtpStorageManager.MtpObject obj = mManager.getObject(handle);
- if (obj == null)
- return MtpConstants.RESPONSE_INVALID_OBJECT_HANDLE;
- // Translate this handle to the MediaProvider Handle
- handle = findInMedia(obj, obj.getPath());
- if (handle == -1)
- return MtpConstants.RESPONSE_GENERAL_ERROR;
- Uri uri = Files.getMtpReferencesUri(obj.getVolumeName(), handle);
- ArrayList<ContentValues> valuesList = new ArrayList<>();
- for (int id : references) {
- // Translate each reference id to the MediaProvider Id
- MtpStorageManager.MtpObject refObj = mManager.getObject(id);
- if (refObj == null)
- continue;
- int refHandle = findInMedia(refObj, refObj.getPath());
- if (refHandle == -1)
- continue;
- ContentValues values = new ContentValues();
- values.put(Files.FileColumns._ID, refHandle);
- valuesList.add(values);
- }
- try {
- if (mMediaProvider.bulkInsert(uri, valuesList.toArray(new ContentValues[0])) > 0) {
- return MtpConstants.RESPONSE_OK;
- }
- } catch (RemoteException e) {
- Log.e(TAG, "RemoteException in setObjectReferences", e);
- }
- return MtpConstants.RESPONSE_GENERAL_ERROR;
+ return MtpConstants.RESPONSE_OPERATION_NOT_SUPPORTED;
}
@VisibleForNative
diff --git a/media/java/android/mtp/MtpStorage.java b/media/java/android/mtp/MtpStorage.java
index 65d0fef74b25..c7dbca61f90a 100644
--- a/media/java/android/mtp/MtpStorage.java
+++ b/media/java/android/mtp/MtpStorage.java
@@ -41,11 +41,7 @@ public class MtpStorage {
mDescription = volume.getDescription(null);
mRemovable = volume.isRemovable();
mMaxFileSize = volume.getMaxFileSize();
- if (volume.isPrimary()) {
- mVolumeName = MediaStore.VOLUME_EXTERNAL_PRIMARY;
- } else {
- mVolumeName = volume.getNormalizedUuid();
- }
+ mVolumeName = volume.getMediaStoreVolumeName();
}
/**
diff --git a/media/jni/android_media_MediaCodec.cpp b/media/jni/android_media_MediaCodec.cpp
index 05aaa82f8ac8..20980a90e9fe 100644
--- a/media/jni/android_media_MediaCodec.cpp
+++ b/media/jni/android_media_MediaCodec.cpp
@@ -742,11 +742,11 @@ status_t JMediaCodec::getCodecInfo(JNIEnv *env, jobject *codecInfoObject) const
return OK;
}
-status_t JMediaCodec::getMetrics(JNIEnv *, MediaAnalyticsItem * &reply) const {
- mediametrics_handle_t reply2 = MediaAnalyticsItem::convert(reply);
+status_t JMediaCodec::getMetrics(JNIEnv *, mediametrics::Item * &reply) const {
+ mediametrics_handle_t reply2 = mediametrics::Item::convert(reply);
status_t status = mCodec->getMetrics(reply2);
// getMetrics() updates reply2, pass the converted update along to our caller.
- reply = MediaAnalyticsItem::convert(reply2);
+ reply = mediametrics::Item::convert(reply2);
return status;
}
@@ -1850,7 +1850,7 @@ android_media_MediaCodec_native_getMetrics(JNIEnv *env, jobject thiz)
}
// get what we have for the metrics from the codec
- MediaAnalyticsItem *item = 0;
+ mediametrics::Item *item = 0;
status_t err = codec->getMetrics(env, item);
if (err != OK) {
diff --git a/media/jni/android_media_MediaCodec.h b/media/jni/android_media_MediaCodec.h
index dfe30a3f5909..ce1c805b6366 100644
--- a/media/jni/android_media_MediaCodec.h
+++ b/media/jni/android_media_MediaCodec.h
@@ -21,7 +21,7 @@
#include "jni.h"
-#include <media/MediaAnalyticsItem.h>
+#include <media/MediaMetricsItem.h>
#include <media/hardware/CryptoAPI.h>
#include <media/stagefright/foundation/ABase.h>
#include <media/stagefright/foundation/AHandler.h>
@@ -124,7 +124,7 @@ struct JMediaCodec : public AHandler {
status_t getCodecInfo(JNIEnv *env, jobject *codecInfo) const;
- status_t getMetrics(JNIEnv *env, MediaAnalyticsItem * &reply) const;
+ status_t getMetrics(JNIEnv *env, mediametrics::Item * &reply) const;
status_t setParameters(const sp<AMessage> &params);
diff --git a/media/jni/android_media_MediaExtractor.cpp b/media/jni/android_media_MediaExtractor.cpp
index f5ae9d0d5d2f..528dc62c3016 100644
--- a/media/jni/android_media_MediaExtractor.cpp
+++ b/media/jni/android_media_MediaExtractor.cpp
@@ -913,7 +913,7 @@ android_media_MediaExtractor_native_getMetrics(JNIEnv * env, jobject thiz)
}
// build and return the Bundle
- std::unique_ptr<MediaAnalyticsItem> item(MediaAnalyticsItem::create());
+ std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create());
item->readFromParcel(reply);
jobject mybundle = MediaMetricsJNI::writeMetricsToBundle(env, item.get(), NULL);
diff --git a/media/jni/android_media_MediaMetricsJNI.cpp b/media/jni/android_media_MediaMetricsJNI.cpp
index d3151545333c..37aca08643b2 100644
--- a/media/jni/android_media_MediaMetricsJNI.cpp
+++ b/media/jni/android_media_MediaMetricsJNI.cpp
@@ -18,11 +18,13 @@
#include <binder/Parcel.h>
#include <jni.h>
-#include <media/MediaAnalyticsItem.h>
+#include <media/MediaMetricsItem.h>
#include <nativehelper/JNIHelp.h>
+#include <variant>
#include "android_media_MediaMetricsJNI.h"
#include "android_os_Parcel.h"
+#include "android_runtime/AndroidRuntime.h"
// This source file is compiled and linked into:
// core/jni/ (libandroid_runtime.so)
@@ -52,7 +54,7 @@ struct BundleHelper {
const jmethodID constructID;
jobject const bundle;
- // We use templated put to access MediaAnalyticsItem based on data type not type enum.
+ // We use templated put to access mediametrics::Item based on data type not type enum.
// See std::variant and std::visit.
template<typename T>
void put(jstring keyName, const T& value) = delete;
@@ -73,18 +75,30 @@ struct BundleHelper {
}
template<>
- void put(jstring keyName, const char * const& value) {
- env->CallVoidMethod(bundle, putStringID, keyName, env->NewStringUTF(value));
+ void put(jstring keyName, const std::string& value) {
+ env->CallVoidMethod(bundle, putStringID, keyName, env->NewStringUTF(value.c_str()));
}
template<>
- void put(jstring keyName, char * const& value) {
+ void put(jstring keyName, const std::pair<int64_t, int64_t>& value) {
+ ; // rate is currently ignored
+ }
+
+ template<>
+ void put(jstring keyName, const std::monostate& value) {
+ ; // none is currently ignored
+ }
+
+ // string char * helpers
+
+ template<>
+ void put(jstring keyName, const char * const& value) {
env->CallVoidMethod(bundle, putStringID, keyName, env->NewStringUTF(value));
}
template<>
- void put(jstring keyName, const std::pair<int64_t, int64_t>& value) {
- ; // rate is currently ignored
+ void put(jstring keyName, char * const& value) {
+ env->CallVoidMethod(bundle, putStringID, keyName, env->NewStringUTF(value));
}
// We allow both jstring and non-jstring variants.
@@ -97,7 +111,7 @@ struct BundleHelper {
// place the attributes into a java PersistableBundle object
jobject MediaMetricsJNI::writeMetricsToBundle(
- JNIEnv* env, MediaAnalyticsItem *item, jobject bundle)
+ JNIEnv* env, mediametrics::Item *item, jobject bundle)
{
BundleHelper bh(env, bundle);
@@ -124,6 +138,28 @@ jobject MediaMetricsJNI::writeMetricsToBundle(
return bh.bundle;
}
+// Implementation of MediaMetrics.native_submit_bytebuffer(),
+// Delivers the byte buffer to the mediametrics service.
+static jint android_media_MediaMetrics_submit_bytebuffer(
+ JNIEnv* env, jobject thiz, jobject byteBuffer, jint length)
+{
+ const jbyte* buffer =
+ reinterpret_cast<const jbyte*>(env->GetDirectBufferAddress(byteBuffer));
+ if (buffer == nullptr) {
+ ALOGE("Error retrieving source of audio data to play, can't play");
+ return (jint)BAD_VALUE;
+ }
+
+ // TODO: directly record item to MediaMetrics service.
+ mediametrics::Item item;
+ if (item.readFromByteString((char *)buffer, length) != NO_ERROR) {
+ ALOGW("%s: cannot read from byte string", __func__);
+ return (jint)BAD_VALUE;
+ }
+ item.selfrecord();
+ return (jint)NO_ERROR;
+}
+
// Helper function to convert a native PersistableBundle to a Java
// PersistableBundle.
jobject MediaMetricsJNI::nativeToJavaPersistableBundle(JNIEnv *env,
@@ -191,5 +227,18 @@ jobject MediaMetricsJNI::nativeToJavaPersistableBundle(JNIEnv *env,
return newBundle;
}
-}; // namespace android
+// ----------------------------------------------------------------------------
+
+static constexpr JNINativeMethod gMethods[] = {
+ {"native_submit_bytebuffer", "(Ljava/nio/ByteBuffer;I)I",
+ (void *)android_media_MediaMetrics_submit_bytebuffer},
+};
+// Registers the native methods, called from core/jni/AndroidRuntime.cpp
+int register_android_media_MediaMetrics(JNIEnv *env)
+{
+ return AndroidRuntime::registerNativeMethods(
+ env, "android/media/MediaMetrics", gMethods, std::size(gMethods));
+}
+
+}; // namespace android
diff --git a/media/jni/android_media_MediaMetricsJNI.h b/media/jni/android_media_MediaMetricsJNI.h
index 63ec27aa58ee..bcad5587d909 100644
--- a/media/jni/android_media_MediaMetricsJNI.h
+++ b/media/jni/android_media_MediaMetricsJNI.h
@@ -19,7 +19,7 @@
#include <jni.h>
#include <nativehelper/JNIHelp.h>
-#include <media/MediaAnalyticsItem.h>
+#include <media/MediaMetricsItem.h>
#include <binder/PersistableBundle.h>
// Copeid from core/jni/ (libandroid_runtime.so)
@@ -27,7 +27,7 @@ namespace android {
class MediaMetricsJNI {
public:
- static jobject writeMetricsToBundle(JNIEnv* env, MediaAnalyticsItem *item, jobject mybundle);
+ static jobject writeMetricsToBundle(JNIEnv* env, mediametrics::Item *item, jobject mybundle);
static jobject nativeToJavaPersistableBundle(JNIEnv*, os::PersistableBundle*);
};
diff --git a/media/jni/android_media_MediaPlayer.cpp b/media/jni/android_media_MediaPlayer.cpp
index b4fa07bd7420..963b650292e4 100644
--- a/media/jni/android_media_MediaPlayer.cpp
+++ b/media/jni/android_media_MediaPlayer.cpp
@@ -23,7 +23,7 @@
#include <media/AudioResamplerPublic.h>
#include <media/IMediaHTTPService.h>
#include <media/MediaPlayerInterface.h>
-#include <media/MediaAnalyticsItem.h>
+#include <media/MediaMetricsItem.h>
#include <media/stagefright/foundation/ByteUtils.h> // for FOURCC definition
#include <stdio.h>
#include <assert.h>
@@ -682,7 +682,7 @@ android_media_MediaPlayer_native_getMetrics(JNIEnv *env, jobject thiz)
return (jobject) NULL;
}
- std::unique_ptr<MediaAnalyticsItem> item(MediaAnalyticsItem::create());
+ std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create());
item->readFromParcel(p);
jobject mybundle = MediaMetricsJNI::writeMetricsToBundle(env, item.get(), NULL);
diff --git a/media/jni/android_media_MediaRecorder.cpp b/media/jni/android_media_MediaRecorder.cpp
index f8ba36d99de7..6eeccf0e5a77 100644
--- a/media/jni/android_media_MediaRecorder.cpp
+++ b/media/jni/android_media_MediaRecorder.cpp
@@ -29,7 +29,7 @@
#include <gui/Surface.h>
#include <camera/Camera.h>
#include <media/mediarecorder.h>
-#include <media/MediaAnalyticsItem.h>
+#include <media/MediaMetricsItem.h>
#include <media/MicrophoneInfo.h>
#include <media/stagefright/PersistentSurface.h>
#include <utils/threads.h>
@@ -694,7 +694,7 @@ android_media_MediaRecorder_native_getMetrics(JNIEnv *env, jobject thiz)
}
// build and return the Bundle
- std::unique_ptr<MediaAnalyticsItem> item(MediaAnalyticsItem::create());
+ std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create());
item->readFromParcel(reply);
jobject mybundle = MediaMetricsJNI::writeMetricsToBundle(env, item.get(), NULL);
diff --git a/media/jni/android_media_tv_Tuner.cpp b/media/jni/android_media_tv_Tuner.cpp
index a0be12ebecfc..9304450dc271 100644
--- a/media/jni/android_media_tv_Tuner.cpp
+++ b/media/jni/android_media_tv_Tuner.cpp
@@ -27,6 +27,7 @@
using ::android::hardware::Void;
using ::android::hardware::hidl_vec;
+using ::android::hardware::tv::tuner::V1_0::DataFormat;
using ::android::hardware::tv::tuner::V1_0::DemuxFilterMainType;
using ::android::hardware::tv::tuner::V1_0::DemuxFilterPesDataSettings;
using ::android::hardware::tv::tuner::V1_0::DemuxFilterSettings;
@@ -35,10 +36,13 @@ using ::android::hardware::tv::tuner::V1_0::DemuxQueueNotifyBits;
using ::android::hardware::tv::tuner::V1_0::DemuxTpid;
using ::android::hardware::tv::tuner::V1_0::DemuxTsFilterSettings;
using ::android::hardware::tv::tuner::V1_0::DemuxTsFilterType;
+using ::android::hardware::tv::tuner::V1_0::DvrSettings;
using ::android::hardware::tv::tuner::V1_0::FrontendAnalogSettings;
using ::android::hardware::tv::tuner::V1_0::FrontendAnalogSifStandard;
using ::android::hardware::tv::tuner::V1_0::FrontendAnalogType;
using ::android::hardware::tv::tuner::V1_0::ITuner;
+using ::android::hardware::tv::tuner::V1_0::PlaybackSettings;
+using ::android::hardware::tv::tuner::V1_0::RecordSettings;
using ::android::hardware::tv::tuner::V1_0::Result;
struct fields_t {
@@ -93,6 +97,14 @@ void DvrCallback::setDvr(const jobject dvr) {
mDvr = env->NewWeakGlobalRef(dvr);
}
+/////////////// Dvr ///////////////////////
+
+Dvr::Dvr(sp<IDvr> sp, jweak obj) : mDvrSp(sp), mDvrObj(obj) {}
+
+sp<IDvr> Dvr::getIDvr() {
+ return mDvrSp;
+}
+
/////////////// FilterCallback ///////////////////////
//TODO: implement filter callback
Return<void> FilterCallback::onFilterEvent(const DemuxFilterEvent& /*filterEvent*/) {
@@ -391,14 +403,14 @@ jobject JTuner::openDvr(DvrType type, int bufferSize) {
return NULL;
}
}
- sp<IDvr> dvrSp;
+ sp<IDvr> iDvrSp;
sp<DvrCallback> callback = new DvrCallback();
mDemux->openDvr(type, bufferSize, callback,
[&](Result, const sp<IDvr>& dvr) {
- dvrSp = dvr;
+ iDvrSp = dvr;
});
- if (dvrSp == NULL) {
+ if (iDvrSp == NULL) {
return NULL;
}
@@ -408,7 +420,7 @@ jobject JTuner::openDvr(DvrType type, int bufferSize) {
env->FindClass("android/media/tv/tuner/Tuner$Dvr"),
gFields.dvrInitID,
mObject);
-
+ sp<Dvr> dvrSp = new Dvr(iDvrSp, dvrObj);
dvrSp->incStrong(dvrObj);
env->SetLongField(dvrObj, gFields.dvrContext, (jlong)dvrSp.get());
@@ -485,8 +497,51 @@ static sp<Filter> getFilter(JNIEnv *env, jobject filter) {
return (Filter *)env->GetLongField(filter, gFields.filterContext);
}
-static sp<IDvr> getDvr(JNIEnv *env, jobject dvr) {
- return (IDvr *)env->GetLongField(dvr, gFields.dvrContext);
+static DvrSettings getDvrSettings(JNIEnv *env, jobject settings) {
+ DvrSettings dvrSettings;
+ jclass clazz = env->FindClass("android/media/tv/tuner/DvrSettings");
+ uint32_t statusMask =
+ static_cast<uint32_t>(env->GetIntField(
+ settings, env->GetFieldID(clazz, "mStatusMask", "I")));
+ uint32_t lowThreshold =
+ static_cast<uint32_t>(env->GetIntField(
+ settings, env->GetFieldID(clazz, "mLowThreshold", "I")));
+ uint32_t highThreshold =
+ static_cast<uint32_t>(env->GetIntField(
+ settings, env->GetFieldID(clazz, "mHighThreshold", "I")));
+ uint8_t packetSize =
+ static_cast<uint8_t>(env->GetIntField(
+ settings, env->GetFieldID(clazz, "mPacketSize", "I")));
+ DataFormat dataFormat =
+ static_cast<DataFormat>(env->GetIntField(
+ settings, env->GetFieldID(clazz, "mDataFormat", "I")));
+ DvrType type =
+ static_cast<DvrType>(env->GetIntField(
+ settings, env->GetFieldID(clazz, "mType", "I")));
+ if (type == DvrType::RECORD) {
+ RecordSettings recordSettings {
+ .statusMask = static_cast<unsigned char>(statusMask),
+ .lowThreshold = lowThreshold,
+ .highThreshold = highThreshold,
+ .dataFormat = dataFormat,
+ .packetSize = packetSize,
+ };
+ dvrSettings.record(recordSettings);
+ } else if (type == DvrType::PLAYBACK) {
+ PlaybackSettings PlaybackSettings {
+ .statusMask = statusMask,
+ .lowThreshold = lowThreshold,
+ .highThreshold = highThreshold,
+ .dataFormat = dataFormat,
+ .packetSize = packetSize,
+ };
+ dvrSettings.playback(PlaybackSettings);
+ }
+ return dvrSettings;
+}
+
+static sp<Dvr> getDvr(JNIEnv *env, jobject dvr) {
+ return (Dvr *)env->GetLongField(dvr, gFields.dvrContext);
}
static void android_media_tv_Tuner_native_init(JNIEnv *env) {
@@ -730,7 +785,7 @@ static jobject android_media_tv_Tuner_open_dvr(JNIEnv *env, jobject thiz, jint t
}
static bool android_media_tv_Tuner_attach_filter(JNIEnv *env, jobject dvr, jobject filter) {
- sp<IDvr> dvrSp = getDvr(env, dvr);
+ sp<IDvr> dvrSp = getDvr(env, dvr)->getIDvr();
sp<IFilter> filterSp = getFilter(env, filter)->getIFilter();
if (dvrSp == NULL || filterSp == NULL) {
return false;
@@ -740,7 +795,7 @@ static bool android_media_tv_Tuner_attach_filter(JNIEnv *env, jobject dvr, jobje
}
static bool android_media_tv_Tuner_detach_filter(JNIEnv *env, jobject dvr, jobject filter) {
- sp<IDvr> dvrSp = getDvr(env, dvr);
+ sp<IDvr> dvrSp = getDvr(env, dvr)->getIDvr();
sp<IFilter> filterSp = getFilter(env, filter)->getIFilter();
if (dvrSp == NULL || filterSp == NULL) {
return false;
@@ -749,8 +804,18 @@ static bool android_media_tv_Tuner_detach_filter(JNIEnv *env, jobject dvr, jobje
return result == Result::SUCCESS;
}
+static int android_media_tv_Tuner_configure_dvr(JNIEnv *env, jobject dvr, jobject settings) {
+ sp<IDvr> dvrSp = getDvr(env, dvr)->getIDvr();
+ if (dvrSp == NULL) {
+ ALOGD("Failed to configure dvr: dvr not found");
+ return (int)Result::INVALID_STATE;
+ }
+ Result result = dvrSp->configure(getDvrSettings(env, settings));
+ return (int)result;
+}
+
static bool android_media_tv_Tuner_start_dvr(JNIEnv *env, jobject dvr) {
- sp<IDvr> dvrSp = getDvr(env, dvr);
+ sp<IDvr> dvrSp = getDvr(env, dvr)->getIDvr();
if (dvrSp == NULL) {
ALOGD("Failed to start dvr: dvr not found");
return false;
@@ -759,7 +824,7 @@ static bool android_media_tv_Tuner_start_dvr(JNIEnv *env, jobject dvr) {
}
static bool android_media_tv_Tuner_stop_dvr(JNIEnv *env, jobject dvr) {
- sp<IDvr> dvrSp = getDvr(env, dvr);
+ sp<IDvr> dvrSp = getDvr(env, dvr)->getIDvr();
if (dvrSp == NULL) {
ALOGD("Failed to stop dvr: dvr not found");
return false;
@@ -768,7 +833,7 @@ static bool android_media_tv_Tuner_stop_dvr(JNIEnv *env, jobject dvr) {
}
static bool android_media_tv_Tuner_flush_dvr(JNIEnv *env, jobject dvr) {
- sp<IDvr> dvrSp = getDvr(env, dvr);
+ sp<IDvr> dvrSp = getDvr(env, dvr)->getIDvr();
if (dvrSp == NULL) {
ALOGD("Failed to flush dvr: dvr not found");
return false;
@@ -818,6 +883,8 @@ static const JNINativeMethod gDvrMethods[] = {
(void *)android_media_tv_Tuner_attach_filter },
{ "nativeDetachFilter", "(Landroid/media/tv/tuner/Tuner$Filter;)Z",
(void *)android_media_tv_Tuner_detach_filter },
+ { "nativeConfigureDvr", "(Landroid/media/tv/tuner/DvrSettings;)I",
+ (void *)android_media_tv_Tuner_configure_dvr },
{ "nativeStartDvr", "()Z", (void *)android_media_tv_Tuner_start_dvr },
{ "nativeStopDvr", "()Z", (void *)android_media_tv_Tuner_stop_dvr },
{ "nativeFlushDvr", "()Z", (void *)android_media_tv_Tuner_flush_dvr },
diff --git a/media/jni/android_media_tv_Tuner.h b/media/jni/android_media_tv_Tuner.h
index 467acb8cdbdd..9f9fb2748581 100644
--- a/media/jni/android_media_tv_Tuner.h
+++ b/media/jni/android_media_tv_Tuner.h
@@ -77,6 +77,13 @@ private:
jweak mDvr;
};
+struct Dvr : public RefBase {
+ Dvr(sp<IDvr> sp, jweak obj);
+ sp<IDvr> getIDvr();
+ sp<IDvr> mDvrSp;
+ jweak mDvrObj;
+};
+
struct FilterCallback : public IFilterCallback {
virtual Return<void> onFilterEvent(const DemuxFilterEvent& filterEvent);
virtual Return<void> onFilterStatus(const DemuxFilterStatus status);
diff --git a/media/jni/audioeffect/Android.bp b/media/jni/audioeffect/Android.bp
index 41ab6703a579..5ba5c0159275 100644
--- a/media/jni/audioeffect/Android.bp
+++ b/media/jni/audioeffect/Android.bp
@@ -17,6 +17,7 @@ cc_library_shared {
"libnativehelper",
"libaudioclient",
"libaudioutils",
+ "libaudiofoundation",
],
version_script: "exports.lds",
diff --git a/media/jni/soundpool/StreamManager.cpp b/media/jni/soundpool/StreamManager.cpp
index c8f0ff10ca3f..79e4d8ae6e26 100644
--- a/media/jni/soundpool/StreamManager.cpp
+++ b/media/jni/soundpool/StreamManager.cpp
@@ -38,7 +38,7 @@ static constexpr bool kStealActiveStream_OldestFirst = true;
// kPlayOnCallingThread = true prior to R.
// Changing to false means calls to play() are almost instantaneous instead of taking around
// ~10ms to launch the AudioTrack. It is perhaps 100x faster.
-static constexpr bool kPlayOnCallingThread = false;
+static constexpr bool kPlayOnCallingThread = true;
// Amount of time for a StreamManager thread to wait before closing.
static constexpr int64_t kWaitTimeBeforeCloseNs = 9 * NANOS_PER_SECOND;
@@ -170,6 +170,7 @@ int32_t StreamManager::queueForPlay(const std::shared_ptr<Sound> &sound,
if (stream->getSoundID() == soundID) {
ALOGV("%s: found soundID %d in restart queue", __func__, soundID);
newStream = stream;
+ fromAvailableQueue = false;
break;
} else if (newStream == nullptr) {
ALOGV("%s: found stream in restart queue", __func__);
diff --git a/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouter2Test.java b/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouter2Test.java
index 2c60d6b3dec7..326628587837 100644
--- a/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouter2Test.java
+++ b/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouter2Test.java
@@ -16,7 +16,15 @@
package com.android.mediaroutertest;
+import static com.android.mediaroutertest.MediaRouterManagerTest.CATEGORIES_ALL;
+import static com.android.mediaroutertest.MediaRouterManagerTest.CATEGORIES_SPECIAL;
+import static com.android.mediaroutertest.MediaRouterManagerTest.ROUTE_ID_SPECIAL_CATEGORY;
+import static com.android.mediaroutertest.MediaRouterManagerTest.ROUTE_ID_VARIABLE_VOLUME;
+import static com.android.mediaroutertest.MediaRouterManagerTest.SYSTEM_PROVIDER_ID;
+
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import android.content.Context;
import android.media.MediaRoute2Info;
@@ -24,20 +32,37 @@ import android.media.MediaRouter2;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;
+import android.text.TextUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executor;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+
@RunWith(AndroidJUnit4.class)
@SmallTest
public class MediaRouter2Test {
+ private static final String TAG = "MediaRouter2Test";
Context mContext;
+ private MediaRouter2 mRouter2;
+ private Executor mExecutor;
+
+ private static final int TIMEOUT_MS = 5000;
@Before
public void setUp() throws Exception {
mContext = InstrumentationRegistry.getTargetContext();
+ mRouter2 = MediaRouter2.getInstance(mContext);
+ mExecutor = Executors.newSingleThreadExecutor();
}
@After
@@ -50,4 +75,95 @@ public class MediaRouter2Test {
MediaRoute2Info initiallySelectedRoute = router.getSelectedRoute();
assertNotNull(initiallySelectedRoute);
}
+
+ /**
+ * Tests if we get proper routes for application that has special control category.
+ */
+ @Test
+ public void testGetRoutes() throws Exception {
+ Map<String, MediaRoute2Info> routes = waitAndGetRoutes(CATEGORIES_SPECIAL);
+
+ assertEquals(1, routes.size());
+ assertNotNull(routes.get(ROUTE_ID_SPECIAL_CATEGORY));
+ }
+
+ @Test
+ public void testControlVolumeWithRouter() throws Exception {
+ Map<String, MediaRoute2Info> routes = waitAndGetRoutes(CATEGORIES_ALL);
+
+ MediaRoute2Info volRoute = routes.get(ROUTE_ID_VARIABLE_VOLUME);
+ assertNotNull(volRoute);
+
+ int originalVolume = volRoute.getVolume();
+ int deltaVolume = (originalVolume == volRoute.getVolumeMax() ? -1 : 1);
+
+ awaitOnRouteChanged(
+ () -> mRouter2.requestUpdateVolume(volRoute, deltaVolume),
+ ROUTE_ID_VARIABLE_VOLUME,
+ (route -> route.getVolume() == originalVolume + deltaVolume));
+
+ awaitOnRouteChanged(
+ () -> mRouter2.requestSetVolume(volRoute, originalVolume),
+ ROUTE_ID_VARIABLE_VOLUME,
+ (route -> route.getVolume() == originalVolume));
+ }
+
+
+ // Helper for getting routes easily
+ static Map<String, MediaRoute2Info> createRouteMap(List<MediaRoute2Info> routes) {
+ Map<String, MediaRoute2Info> routeMap = new HashMap<>();
+ for (MediaRoute2Info route : routes) {
+ // intentionally not using route.getUniqueId() for convenience.
+ routeMap.put(route.getId(), route);
+ }
+ return routeMap;
+ }
+
+ Map<String, MediaRoute2Info> waitAndGetRoutes(List<String> controlCategories)
+ throws Exception {
+ CountDownLatch latch = new CountDownLatch(1);
+
+ // A dummy callback is required to send control category info.
+ MediaRouter2.Callback routerCallback = new MediaRouter2.Callback() {
+ @Override
+ public void onRoutesAdded(List<MediaRoute2Info> routes) {
+ for (int i = 0; i < routes.size(); i++) {
+ //TODO: use isSystem() or similar method when it's ready
+ if (!TextUtils.equals(routes.get(i).getProviderId(), SYSTEM_PROVIDER_ID)) {
+ latch.countDown();
+ }
+ }
+ }
+ };
+
+ mRouter2.setControlCategories(controlCategories);
+ mRouter2.registerCallback(mExecutor, routerCallback);
+ try {
+ latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS);
+ return createRouteMap(mRouter2.getRoutes());
+ } finally {
+ mRouter2.unregisterCallback(routerCallback);
+ }
+ }
+
+ void awaitOnRouteChanged(Runnable task, String routeId,
+ Predicate<MediaRoute2Info> predicate) throws Exception {
+ CountDownLatch latch = new CountDownLatch(1);
+ MediaRouter2.Callback callback = new MediaRouter2.Callback() {
+ @Override
+ public void onRoutesChanged(List<MediaRoute2Info> changed) {
+ MediaRoute2Info route = createRouteMap(changed).get(routeId);
+ if (route != null && predicate.test(route)) {
+ latch.countDown();
+ }
+ }
+ };
+ mRouter2.registerCallback(mExecutor, callback);
+ try {
+ task.run();
+ assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
+ } finally {
+ mRouter2.unregisterCallback(callback);
+ }
+ }
}
diff --git a/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouterManagerTest.java b/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouterManagerTest.java
index c70ad8d8755c..b380aff20334 100644
--- a/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouterManagerTest.java
+++ b/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouterManagerTest.java
@@ -64,6 +64,9 @@ public class MediaRouterManagerTest {
public static final String ROUTE_ID_SPECIAL_CATEGORY = "route_special_category";
public static final String ROUTE_NAME_SPECIAL_CATEGORY = "Special Category Route";
+ public static final String SYSTEM_PROVIDER_ID =
+ "com.android.server.media/.SystemMediaRoute2Provider";
+
public static final int VOLUME_MAX = 100;
public static final String ROUTE_ID_FIXED_VOLUME = "route_fixed_volume";
public static final String ROUTE_NAME_FIXED_VOLUME = "Fixed Volume Route";
@@ -78,10 +81,7 @@ public class MediaRouterManagerTest {
public static final String CATEGORY_SPECIAL =
"com.android.mediarouteprovider.CATEGORY_SPECIAL";
- // system routes
- private static final String DEFAULT_ROUTE_ID = "DEFAULT_ROUTE";
private static final String CATEGORY_LIVE_AUDIO = "android.media.intent.category.LIVE_AUDIO";
- private static final String CATEGORY_LIVE_VIDEO = "android.media.intent.category.LIVE_VIDEO";
private static final int TIMEOUT_MS = 5000;
@@ -93,10 +93,9 @@ public class MediaRouterManagerTest {
private final List<MediaRouter2Manager.Callback> mManagerCallbacks = new ArrayList<>();
private final List<MediaRouter2.Callback> mRouterCallbacks = new ArrayList<>();
- private Map<String, MediaRoute2Info> mRoutes;
- private static final List<String> CATEGORIES_ALL = new ArrayList();
- private static final List<String> CATEGORIES_SPECIAL = new ArrayList();
+ public static final List<String> CATEGORIES_ALL = new ArrayList();
+ public static final List<String> CATEGORIES_SPECIAL = new ArrayList();
private static final List<String> CATEGORIES_LIVE_AUDIO = new ArrayList<>();
static {
@@ -109,7 +108,6 @@ public class MediaRouterManagerTest {
CATEGORIES_LIVE_AUDIO.add(CATEGORY_LIVE_AUDIO);
}
-
@Before
public void setUp() throws Exception {
mContext = InstrumentationRegistry.getTargetContext();
@@ -118,10 +116,6 @@ public class MediaRouterManagerTest {
//TODO: If we need to support thread pool executors, change this to thread pool executor.
mExecutor = Executors.newSingleThreadExecutor();
mPackageName = mContext.getPackageName();
-
- // ensure media router 2 client
- addRouterCallback(new MediaRouter2.Callback());
- mRoutes = waitAndGetRoutesWithManager(CATEGORIES_ALL);
}
@After
@@ -168,6 +162,9 @@ public class MediaRouterManagerTest {
@Test
public void testOnRoutesRemoved() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
+ Map<String, MediaRoute2Info> routes = waitAndGetRoutesWithManager(CATEGORIES_ALL);
+
+ addRouterCallback(new MediaRouter2.Callback());
addManagerCallback(new MediaRouter2Manager.Callback() {
@Override
public void onRoutesRemoved(List<MediaRoute2Info> routes) {
@@ -182,7 +179,7 @@ public class MediaRouterManagerTest {
//TODO: Figure out a more proper way to test.
// (Control requests shouldn't be used in this way.)
- mRouter2.sendControlRequest(mRoutes.get(ROUTE_ID2), new Intent(ACTION_REMOVE_ROUTE));
+ mRouter2.sendControlRequest(routes.get(ROUTE_ID2), new Intent(ACTION_REMOVE_ROUTE));
assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
}
@@ -198,23 +195,15 @@ public class MediaRouterManagerTest {
}
/**
- * Tests if we get proper routes for application that has special control category.
- */
- @Test
- public void testGetRoutes() throws Exception {
- Map<String, MediaRoute2Info> routes = waitAndGetRoutes(CATEGORIES_SPECIAL);
-
- assertEquals(1, routes.size());
- assertNotNull(routes.get(ROUTE_ID_SPECIAL_CATEGORY));
- }
-
- /**
* Tests if MR2.Callback.onRouteSelected is called when a route is selected from MR2Manager.
*/
@Test
public void testRouterOnRouteSelected() throws Exception {
+ Map<String, MediaRoute2Info> routes = waitAndGetRoutesWithManager(CATEGORIES_ALL);
+
CountDownLatch latch = new CountDownLatch(1);
+ addManagerCallback(new MediaRouter2Manager.Callback());
addRouterCallback(new MediaRouter2.Callback() {
@Override
public void onRouteSelected(MediaRoute2Info route, int reason, Bundle controlHints) {
@@ -224,12 +213,16 @@ public class MediaRouterManagerTest {
}
});
- MediaRoute2Info routeToSelect = mRoutes.get(ROUTE_ID1);
+ MediaRoute2Info routeToSelect = routes.get(ROUTE_ID1);
assertNotNull(routeToSelect);
- mManager.selectRoute(mPackageName, routeToSelect);
+ try {
+ mManager.selectRoute(mPackageName, routeToSelect);
- assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
+ assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
+ } finally {
+ mManager.unselectRoute(mPackageName);
+ }
}
/**
@@ -239,7 +232,9 @@ public class MediaRouterManagerTest {
@Test
public void testManagerOnRouteSelected() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
+ Map<String, MediaRoute2Info> routes = waitAndGetRoutesWithManager(CATEGORIES_ALL);
+ addRouterCallback(new MediaRouter2.Callback());
addManagerCallback(new MediaRouter2Manager.Callback() {
@Override
public void onRouteSelected(String packageName, MediaRoute2Info route) {
@@ -250,12 +245,15 @@ public class MediaRouterManagerTest {
}
});
- MediaRoute2Info routeToSelect = mRoutes.get(ROUTE_ID1);
+ MediaRoute2Info routeToSelect = routes.get(ROUTE_ID1);
assertNotNull(routeToSelect);
- mManager.selectRoute(mPackageName, routeToSelect);
-
- assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
+ try {
+ mManager.selectRoute(mPackageName, routeToSelect);
+ assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
+ } finally {
+ mManager.unselectRoute(mPackageName);
+ }
}
/**
@@ -263,13 +261,16 @@ public class MediaRouterManagerTest {
*/
@Test
public void testSingleProviderSelect() throws Exception {
+ Map<String, MediaRoute2Info> routes = waitAndGetRoutesWithManager(CATEGORIES_ALL);
+ addRouterCallback(new MediaRouter2.Callback());
+
awaitOnRouteChangedManager(
- () -> mManager.selectRoute(mPackageName, mRoutes.get(ROUTE_ID1)),
+ () -> mManager.selectRoute(mPackageName, routes.get(ROUTE_ID1)),
ROUTE_ID1,
route -> TextUtils.equals(route.getClientPackageName(), mPackageName));
awaitOnRouteChangedManager(
- () -> mManager.selectRoute(mPackageName, mRoutes.get(ROUTE_ID2)),
+ () -> mManager.selectRoute(mPackageName, routes.get(ROUTE_ID2)),
ROUTE_ID2,
route -> TextUtils.equals(route.getClientPackageName(), mPackageName));
@@ -280,27 +281,10 @@ public class MediaRouterManagerTest {
}
@Test
- public void testControlVolumeWithRouter() throws Exception {
- Map<String, MediaRoute2Info> routes = waitAndGetRoutes(CATEGORIES_ALL);
-
+ public void testControlVolumeWithManager() throws Exception {
+ Map<String, MediaRoute2Info> routes = waitAndGetRoutesWithManager(CATEGORIES_ALL);
MediaRoute2Info volRoute = routes.get(ROUTE_ID_VARIABLE_VOLUME);
- int originalVolume = volRoute.getVolume();
- int deltaVolume = (originalVolume == volRoute.getVolumeMax() ? -1 : 1);
-
- awaitOnRouteChanged(
- () -> mRouter2.requestUpdateVolume(volRoute, deltaVolume),
- ROUTE_ID_VARIABLE_VOLUME,
- (route -> route.getVolume() == originalVolume + deltaVolume));
- awaitOnRouteChanged(
- () -> mRouter2.requestSetVolume(volRoute, originalVolume),
- ROUTE_ID_VARIABLE_VOLUME,
- (route -> route.getVolume() == originalVolume));
- }
-
- @Test
- public void testControlVolumeWithManager() throws Exception {
- MediaRoute2Info volRoute = mRoutes.get(ROUTE_ID_VARIABLE_VOLUME);
int originalVolume = volRoute.getVolume();
int deltaVolume = (originalVolume == volRoute.getVolumeMax() ? -1 : 1);
@@ -317,39 +301,16 @@ public class MediaRouterManagerTest {
@Test
public void testVolumeHandling() throws Exception {
- MediaRoute2Info fixedVolumeRoute = mRoutes.get(ROUTE_ID_FIXED_VOLUME);
- MediaRoute2Info variableVolumeRoute = mRoutes.get(ROUTE_ID_VARIABLE_VOLUME);
+ Map<String, MediaRoute2Info> routes = waitAndGetRoutesWithManager(CATEGORIES_ALL);
+
+ MediaRoute2Info fixedVolumeRoute = routes.get(ROUTE_ID_FIXED_VOLUME);
+ MediaRoute2Info variableVolumeRoute = routes.get(ROUTE_ID_VARIABLE_VOLUME);
assertEquals(PLAYBACK_VOLUME_FIXED, fixedVolumeRoute.getVolumeHandling());
assertEquals(PLAYBACK_VOLUME_VARIABLE, variableVolumeRoute.getVolumeHandling());
assertEquals(VOLUME_MAX, variableVolumeRoute.getVolumeMax());
}
- @Test
- public void testDefaultRoute() throws Exception {
- Map<String, MediaRoute2Info> routes = waitAndGetRoutes(CATEGORIES_LIVE_AUDIO);
-
- assertNotNull(routes.get(DEFAULT_ROUTE_ID));
- }
-
- Map<String, MediaRoute2Info> waitAndGetRoutes(List<String> controlCategories) throws Exception {
- CountDownLatch latch = new CountDownLatch(1);
- MediaRouter2.Callback callback = new MediaRouter2.Callback() {
- @Override
- public void onRoutesAdded(List<MediaRoute2Info> added) {
- if (added.size() > 0) latch.countDown();
- }
- };
- mRouter2.setControlCategories(controlCategories);
- mRouter2.registerCallback(mExecutor, callback);
- try {
- assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
- return createRouteMap(mRouter2.getRoutes());
- } finally {
- mRouter2.unregisterCallback(callback);
- }
- }
-
Map<String, MediaRoute2Info> waitAndGetRoutesWithManager(List<String> controlCategories)
throws Exception {
CountDownLatch latch = new CountDownLatch(2);
@@ -359,13 +320,17 @@ public class MediaRouterManagerTest {
MediaRouter2Manager.Callback managerCallback = new MediaRouter2Manager.Callback() {
@Override
public void onRoutesAdded(List<MediaRoute2Info> routes) {
- if (routes.size() > 0) {
- latch.countDown();
+ for (int i = 0; i < routes.size(); i++) {
+ //TODO: use isSystem() or similar method when it's ready
+ if (!TextUtils.equals(routes.get(i).getProviderId(), SYSTEM_PROVIDER_ID)) {
+ latch.countDown();
+ break;
+ }
}
}
@Override
- public void onControlCategoriesChanged(String packageName) {
+ public void onControlCategoriesChanged(String packageName, List<String> categories) {
if (TextUtils.equals(mPackageName, packageName)) {
latch.countDown();
}
@@ -375,7 +340,7 @@ public class MediaRouterManagerTest {
mRouter2.setControlCategories(controlCategories);
mRouter2.registerCallback(mExecutor, routerCallback);
try {
- assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
+ latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS);
return createRouteMap(mManager.getAvailableRoutes(mPackageName));
} finally {
mRouter2.unregisterCallback(routerCallback);
@@ -383,27 +348,6 @@ public class MediaRouterManagerTest {
}
}
- void awaitOnRouteChanged(Runnable task, String routeId,
- Predicate<MediaRoute2Info> predicate) throws Exception {
- CountDownLatch latch = new CountDownLatch(1);
- MediaRouter2.Callback callback = new MediaRouter2.Callback() {
- @Override
- public void onRoutesChanged(List<MediaRoute2Info> changed) {
- MediaRoute2Info route = createRouteMap(changed).get(routeId);
- if (route != null && predicate.test(route)) {
- latch.countDown();
- }
- }
- };
- mRouter2.registerCallback(mExecutor, callback);
- try {
- task.run();
- assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
- } finally {
- mRouter2.unregisterCallback(callback);
- }
- }
-
void awaitOnRouteChangedManager(Runnable task, String routeId,
Predicate<MediaRoute2Info> predicate) throws Exception {
CountDownLatch latch = new CountDownLatch(1);
diff --git a/media/tests/MediaRouter/src/com/android/mediaroutertest/RouteSessionTest.java b/media/tests/MediaRouter/src/com/android/mediaroutertest/RouteSessionTest.java
new file mode 100644
index 000000000000..2e81a646b0db
--- /dev/null
+++ b/media/tests/MediaRouter/src/com/android/mediaroutertest/RouteSessionTest.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2019 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 com.android.mediaroutertest;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import android.media.RouteSessionInfo;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class RouteSessionTest {
+ private static final String TEST_PACKAGE_NAME = "com.android.mediaroutertest";
+ private static final String TEST_CONTROL_CATEGORY = "com.android.mediaroutertest.category";
+
+ private static final String TEST_ROUTE_ID1 = "route_id1";
+
+ @Test
+ public void testValidity() {
+ RouteSessionInfo emptyPackageSession = new RouteSessionInfo.Builder(1,
+ "",
+ TEST_CONTROL_CATEGORY)
+ .addSelectedRoute(TEST_ROUTE_ID1)
+ .build();
+ RouteSessionInfo emptyCategorySession = new RouteSessionInfo.Builder(1,
+ TEST_PACKAGE_NAME, "")
+ .addSelectedRoute(TEST_ROUTE_ID1)
+ .build();
+
+ RouteSessionInfo emptySelectedRouteSession = new RouteSessionInfo.Builder(1,
+ TEST_PACKAGE_NAME, TEST_CONTROL_CATEGORY)
+ .build();
+
+ RouteSessionInfo validSession = new RouteSessionInfo.Builder(emptySelectedRouteSession)
+ .addSelectedRoute(TEST_ROUTE_ID1)
+ .build();
+
+ assertFalse(emptySelectedRouteSession.isValid());
+ assertFalse(emptyPackageSession.isValid());
+ assertFalse(emptyCategorySession.isValid());
+ assertTrue(validSession.isValid());
+ }
+}
diff --git a/packages/CarSystemUI/Android.bp b/packages/CarSystemUI/Android.bp
index b2451c91057c..2a8a39a1fe1a 100644
--- a/packages/CarSystemUI/Android.bp
+++ b/packages/CarSystemUI/Android.bp
@@ -53,7 +53,6 @@ android_library {
],
libs: [
- "telephony-common",
"android.car",
],
@@ -108,7 +107,6 @@ android_library {
],
libs: [
"android.test.runner",
- "telephony-common",
"android.test.base",
"android.car",
],
@@ -129,7 +127,6 @@ android_app {
],
libs: [
- "telephony-common",
"android.car",
],
@@ -140,7 +137,7 @@ android_app {
],
platform_apis: true,
- product_specific: true,
+ system_ext_specific: true,
certificate: "platform",
privileged: true,
diff --git a/packages/CarSystemUI/CleanSpec.mk b/packages/CarSystemUI/CleanSpec.mk
new file mode 100644
index 000000000000..ceac67c55f09
--- /dev/null
+++ b/packages/CarSystemUI/CleanSpec.mk
@@ -0,0 +1,50 @@
+# Copyright (C) 2019 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.
+#
+
+# If you don't need to do a full clean build but would like to touch
+# a file or delete some intermediate files, add a clean step to the end
+# of the list. These steps will only be run once, if they haven't been
+# run before.
+#
+# E.g.:
+# $(call add-clean-step, touch -c external/sqlite/sqlite3.h)
+# $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/STATIC_LIBRARIES/libz_intermediates)
+#
+# Always use "touch -c" and "rm -f" or "rm -rf" to gracefully deal with
+# files that are missing or have been moved.
+#
+# Use $(PRODUCT_OUT) to get to the "out/target/product/blah/" directory.
+# Use $(OUT_DIR) to refer to the "out" directory.
+#
+# If you need to re-do something that's already mentioned, just copy
+# the command and add it to the bottom of the list. E.g., if a change
+# that you made last week required touching a file and a change you
+# made today requires touching the same file, just copy the old
+# touch step and add it to the end of the list.
+#
+# *****************************************************************
+# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST ABOVE THE BANNER
+# *****************************************************************
+
+# For example:
+#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/AndroidTests_intermediates)
+#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/core_intermediates)
+#$(call add-clean-step, find $(OUT_DIR) -type f -name "IGTalkSession*" -print0 | xargs -0 rm -f)
+#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/data/*)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/product/priv-app/CarSystemUI)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/product/priv-app/CarSystemUI)
+# ******************************************************************
+# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST ABOVE THIS BANNER
+# ******************************************************************
diff --git a/packages/CarSystemUI/src/com/android/systemui/CarSystemUIModule.java b/packages/CarSystemUI/src/com/android/systemui/CarSystemUIModule.java
index bffc6b912146..b862e955ecf1 100644
--- a/packages/CarSystemUI/src/com/android/systemui/CarSystemUIModule.java
+++ b/packages/CarSystemUI/src/com/android/systemui/CarSystemUIModule.java
@@ -21,6 +21,7 @@ import static com.android.systemui.Dependency.LEAK_REPORT_EMAIL_NAME;
import android.content.Context;
+import com.android.systemui.car.CarDeviceProvisionedControllerImpl;
import com.android.systemui.car.CarNotificationEntryManager;
import com.android.systemui.car.CarNotificationInterruptionStateProvider;
import com.android.systemui.dagger.SystemUIRootComponent;
@@ -35,6 +36,7 @@ import com.android.systemui.stackdivider.Divider;
import com.android.systemui.statusbar.CommandQueue;
import com.android.systemui.statusbar.NotificationLockscreenUserManager;
import com.android.systemui.statusbar.NotificationLockscreenUserManagerImpl;
+import com.android.systemui.statusbar.car.CarShadeControllerImpl;
import com.android.systemui.statusbar.car.CarStatusBar;
import com.android.systemui.statusbar.car.CarStatusBarKeyguardViewManager;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
@@ -45,6 +47,7 @@ import com.android.systemui.statusbar.phone.KeyguardEnvironmentImpl;
import com.android.systemui.statusbar.phone.ShadeController;
import com.android.systemui.statusbar.phone.StatusBar;
import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager;
+import com.android.systemui.statusbar.policy.DeviceProvisionedController;
import com.android.systemui.statusbar.policy.HeadsUpManager;
import com.android.systemui.volume.CarVolumeDialogComponent;
import com.android.systemui.volume.VolumeDialogComponent;
@@ -119,7 +122,7 @@ abstract class CarSystemUIModule {
KeyguardEnvironmentImpl keyguardEnvironment);
@Binds
- abstract ShadeController provideShadeController(CarStatusBar statusBar);
+ abstract ShadeController provideShadeController(CarShadeControllerImpl shadeController);
@Provides
@Singleton
@@ -142,4 +145,8 @@ abstract class CarSystemUIModule {
@Binds
abstract StatusBarKeyguardViewManager bindStatusBarKeyguardViewManager(
CarStatusBarKeyguardViewManager keyguardViewManager);
+
+ @Binds
+ abstract DeviceProvisionedController bindDeviceProvisionedController(
+ CarDeviceProvisionedControllerImpl deviceProvisionedController);
}
diff --git a/packages/CarSystemUI/src/com/android/systemui/car/CarDeviceProvisionedController.java b/packages/CarSystemUI/src/com/android/systemui/car/CarDeviceProvisionedController.java
new file mode 100644
index 000000000000..c870cec67314
--- /dev/null
+++ b/packages/CarSystemUI/src/com/android/systemui/car/CarDeviceProvisionedController.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.car;
+
+import com.android.systemui.statusbar.policy.DeviceProvisionedController;
+
+/**
+ * This interface defines controller that monitors the status of SUW progress for each user in
+ * addition to the functionality defined by {@link DeviceProvisionedController}.
+ */
+public interface CarDeviceProvisionedController extends DeviceProvisionedController {
+ /**
+ * Returns {@code true} then SUW is in progress for the given user.
+ */
+ boolean isUserSetupInProgress(int user);
+
+ /**
+ * Returns {@code true} then SUW is in progress for the current user.
+ */
+ default boolean isCurrentUserSetupInProgress() {
+ return isUserSetupInProgress(getCurrentUser());
+ }
+}
diff --git a/packages/CarSystemUI/src/com/android/systemui/car/CarDeviceProvisionedControllerImpl.java b/packages/CarSystemUI/src/com/android/systemui/car/CarDeviceProvisionedControllerImpl.java
new file mode 100644
index 000000000000..ab1feefd8b3c
--- /dev/null
+++ b/packages/CarSystemUI/src/com/android/systemui/car/CarDeviceProvisionedControllerImpl.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.car;
+
+import android.app.ActivityManager;
+import android.car.settings.CarSettings;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.database.ContentObserver;
+import android.net.Uri;
+import android.os.Handler;
+import android.provider.Settings;
+
+import com.android.systemui.Dependency;
+import com.android.systemui.broadcast.BroadcastDispatcher;
+import com.android.systemui.dagger.qualifiers.MainHandler;
+import com.android.systemui.statusbar.policy.DeviceProvisionedControllerImpl;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+/**
+ * A controller that monitors the status of SUW progress for each user in addition to the
+ * functionality provided by {@link DeviceProvisionedControllerImpl}.
+ */
+@Singleton
+public class CarDeviceProvisionedControllerImpl extends DeviceProvisionedControllerImpl implements
+ CarDeviceProvisionedController {
+ private static final Uri USER_SETUP_IN_PROGRESS_URI = Settings.Secure.getUriFor(
+ CarSettings.Secure.KEY_SETUP_WIZARD_IN_PROGRESS);
+ private final ContentObserver mCarSettingsObserver = new ContentObserver(
+ Dependency.get(Dependency.MAIN_HANDLER)) {
+ @Override
+ public void onChange(boolean selfChange, Uri uri, int userId) {
+ if (USER_SETUP_IN_PROGRESS_URI.equals(uri)) {
+ notifyUserSetupInProgressChanged();
+ }
+ }
+ };
+ private final ContentResolver mContentResolver;
+
+ @Inject
+ public CarDeviceProvisionedControllerImpl(Context context, @MainHandler Handler mainHandler,
+ BroadcastDispatcher broadcastDispatcher) {
+ super(context, mainHandler, broadcastDispatcher);
+ mContentResolver = context.getContentResolver();
+ }
+
+ @Override
+ public boolean isUserSetupInProgress(int user) {
+ return Settings.Secure.getIntForUser(mContentResolver,
+ CarSettings.Secure.KEY_SETUP_WIZARD_IN_PROGRESS, /* def= */ 0, user) != 0;
+ }
+
+ @Override
+ public boolean isCurrentUserSetupInProgress() {
+ return isUserSetupInProgress(ActivityManager.getCurrentUser());
+ }
+
+ @Override
+ public void addCallback(DeviceProvisionedListener listener) {
+ super.addCallback(listener);
+ if (listener instanceof CarDeviceProvisionedListener) {
+ ((CarDeviceProvisionedListener) listener).onUserSetupInProgressChanged();
+ }
+ }
+
+ @Override
+ protected void startListening(int user) {
+ mContentResolver.registerContentObserver(
+ USER_SETUP_IN_PROGRESS_URI, /* notifyForDescendants= */ true, mCarSettingsObserver,
+ user);
+ // The SUW Flag observer is registered before super.startListening() so that the observer is
+ // in place before DeviceProvisionedController starts to track user switches which avoids
+ // an edge case where our observer gets registered twice.
+ super.startListening(user);
+ }
+
+ @Override
+ protected void stopListening() {
+ super.stopListening();
+ mContentResolver.unregisterContentObserver(mCarSettingsObserver);
+ }
+
+ @Override
+ public void onUserSwitched(int newUserId) {
+ super.onUserSwitched(newUserId);
+ mContentResolver.unregisterContentObserver(mCarSettingsObserver);
+ mContentResolver.registerContentObserver(
+ USER_SETUP_IN_PROGRESS_URI, /* notifyForDescendants= */ true, mCarSettingsObserver,
+ newUserId);
+ }
+
+ private void notifyUserSetupInProgressChanged() {
+ for (int i = mListeners.size() - 1; i >= 0; --i) {
+ DeviceProvisionedListener listener = mListeners.get(i);
+ if (listener instanceof CarDeviceProvisionedListener) {
+ ((CarDeviceProvisionedListener) listener).onUserSetupInProgressChanged();
+ }
+ }
+ }
+}
diff --git a/packages/CarSystemUI/src/com/android/systemui/car/CarDeviceProvisionedListener.java b/packages/CarSystemUI/src/com/android/systemui/car/CarDeviceProvisionedListener.java
new file mode 100644
index 000000000000..008632223f3f
--- /dev/null
+++ b/packages/CarSystemUI/src/com/android/systemui/car/CarDeviceProvisionedListener.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.car;
+
+import com.android.systemui.statusbar.policy.DeviceProvisionedController.DeviceProvisionedListener;
+
+/**
+ * A listener that listens for changes in SUW progress for a user in addition to the
+ * functionality defined by {@link DeviceProvisionedListener}.
+ */
+public interface CarDeviceProvisionedListener extends DeviceProvisionedListener {
+ @Override
+ default void onUserSwitched() {
+ onUserSetupChanged();
+ onUserSetupInProgressChanged();
+ }
+ /**
+ * A callback for when a change occurs in SUW progress for a user.
+ */
+ default void onUserSetupInProgressChanged() {
+ }
+}
diff --git a/packages/CarSystemUI/src/com/android/systemui/navigationbar/car/CarNavigationBar.java b/packages/CarSystemUI/src/com/android/systemui/navigationbar/car/CarNavigationBar.java
index 08ab4928adfe..e0b0922e913f 100644
--- a/packages/CarSystemUI/src/com/android/systemui/navigationbar/car/CarNavigationBar.java
+++ b/packages/CarSystemUI/src/com/android/systemui/navigationbar/car/CarNavigationBar.java
@@ -33,6 +33,8 @@ import com.android.internal.statusbar.IStatusBarService;
import com.android.internal.statusbar.RegisterStatusBarResult;
import com.android.systemui.R;
import com.android.systemui.SystemUI;
+import com.android.systemui.car.CarDeviceProvisionedController;
+import com.android.systemui.car.CarDeviceProvisionedListener;
import com.android.systemui.dagger.qualifiers.MainHandler;
import com.android.systemui.shared.system.ActivityManagerWrapper;
import com.android.systemui.statusbar.CommandQueue;
@@ -53,7 +55,7 @@ public class CarNavigationBar extends SystemUI implements CommandQueue.Callbacks
private final CarNavigationBarController mCarNavigationBarController;
private final WindowManager mWindowManager;
- private final DeviceProvisionedController mDeviceProvisionedController;
+ private final CarDeviceProvisionedController mCarDeviceProvisionedController;
private final CommandQueue mCommandQueue;
private final Lazy<FacetButtonTaskStackListener> mFacetButtonTaskStackListenerLazy;
private final Handler mMainHandler;
@@ -82,6 +84,7 @@ public class CarNavigationBar extends SystemUI implements CommandQueue.Callbacks
// To be attached to the navigation bars such that they can close the notification panel if
// it's open.
private boolean mDeviceIsSetUpForUser = true;
+ private boolean mIsUserSetupInProgress = false;
@Inject
public CarNavigationBar(Context context,
@@ -98,7 +101,8 @@ public class CarNavigationBar extends SystemUI implements CommandQueue.Callbacks
super(context);
mCarNavigationBarController = carNavigationBarController;
mWindowManager = windowManager;
- mDeviceProvisionedController = deviceProvisionedController;
+ mCarDeviceProvisionedController = (CarDeviceProvisionedController)
+ deviceProvisionedController;
mCommandQueue = commandQueue;
mFacetButtonTaskStackListenerLazy = facetButtonTaskStackListenerLazy;
mMainHandler = mainHandler;
@@ -129,9 +133,15 @@ public class CarNavigationBar extends SystemUI implements CommandQueue.Callbacks
ex.rethrowFromSystemServer();
}
- mDeviceIsSetUpForUser = mDeviceProvisionedController.isCurrentUserSetup();
- mDeviceProvisionedController.addCallback(
- new DeviceProvisionedController.DeviceProvisionedListener() {
+ mDeviceIsSetUpForUser = mCarDeviceProvisionedController.isCurrentUserSetup();
+ mIsUserSetupInProgress = mCarDeviceProvisionedController.isCurrentUserSetupInProgress();
+ mCarDeviceProvisionedController.addCallback(
+ new CarDeviceProvisionedListener() {
+ @Override
+ public void onUserSetupInProgressChanged() {
+ mMainHandler.post(() -> restartNavBarsIfNecessary());
+ }
+
@Override
public void onUserSetupChanged() {
mMainHandler.post(() -> restartNavBarsIfNecessary());
@@ -152,9 +162,13 @@ public class CarNavigationBar extends SystemUI implements CommandQueue.Callbacks
}
private void restartNavBarsIfNecessary() {
- boolean currentUserSetup = mDeviceProvisionedController.isCurrentUserSetup();
- if (mDeviceIsSetUpForUser != currentUserSetup) {
+ boolean currentUserSetup = mCarDeviceProvisionedController.isCurrentUserSetup();
+ boolean currentUserSetupInProgress = mCarDeviceProvisionedController
+ .isCurrentUserSetupInProgress();
+ if (mIsUserSetupInProgress != currentUserSetupInProgress
+ || mDeviceIsSetUpForUser != currentUserSetup) {
mDeviceIsSetUpForUser = currentUserSetup;
+ mIsUserSetupInProgress = currentUserSetupInProgress;
restartNavBars();
}
}
@@ -193,10 +207,14 @@ public class CarNavigationBar extends SystemUI implements CommandQueue.Callbacks
// If the UI was rebuilt (day/night change) while the keyguard was up we need to
// correctly respect that state.
if (mKeyguardStateControllerLazy.get().isShowing()) {
- mCarNavigationBarController.showAllKeyguardButtons(mDeviceIsSetUpForUser);
+ mCarNavigationBarController.showAllKeyguardButtons(isDeviceSetupForUser());
}
}
+ private boolean isDeviceSetupForUser() {
+ return mDeviceIsSetUpForUser && !mIsUserSetupInProgress;
+ }
+
private void createNavigationBar(RegisterStatusBarResult result) {
buildNavBarWindows();
buildNavBarContent();
@@ -225,22 +243,22 @@ public class CarNavigationBar extends SystemUI implements CommandQueue.Callbacks
}
private void buildNavBarContent() {
- mTopNavigationBarView = mCarNavigationBarController.getTopBar(mDeviceIsSetUpForUser);
+ mTopNavigationBarView = mCarNavigationBarController.getTopBar(isDeviceSetupForUser());
if (mTopNavigationBarView != null) {
mTopNavigationBarWindow.addView(mTopNavigationBarView);
}
- mBottomNavigationBarView = mCarNavigationBarController.getBottomBar(mDeviceIsSetUpForUser);
+ mBottomNavigationBarView = mCarNavigationBarController.getBottomBar(isDeviceSetupForUser());
if (mBottomNavigationBarView != null) {
mBottomNavigationBarWindow.addView(mBottomNavigationBarView);
}
- mLeftNavigationBarView = mCarNavigationBarController.getLeftBar(mDeviceIsSetUpForUser);
+ mLeftNavigationBarView = mCarNavigationBarController.getLeftBar(isDeviceSetupForUser());
if (mLeftNavigationBarView != null) {
mLeftNavigationBarWindow.addView(mLeftNavigationBarView);
}
- mRightNavigationBarView = mCarNavigationBarController.getRightBar(mDeviceIsSetUpForUser);
+ mRightNavigationBarView = mCarNavigationBarController.getRightBar(isDeviceSetupForUser());
if (mRightNavigationBarView != null) {
mRightNavigationBarWindow.addView(mRightNavigationBarView);
}
@@ -278,6 +296,7 @@ public class CarNavigationBar extends SystemUI implements CommandQueue.Callbacks
leftlp.windowAnimations = 0;
leftlp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_IS_SCREEN_DECOR;
leftlp.gravity = Gravity.LEFT;
+ leftlp.setFitWindowInsetsTypes(0 /* types */);
mWindowManager.addView(mLeftNavigationBarWindow, leftlp);
}
if (mRightNavigationBarWindow != null) {
@@ -295,6 +314,7 @@ public class CarNavigationBar extends SystemUI implements CommandQueue.Callbacks
rightlp.windowAnimations = 0;
rightlp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_IS_SCREEN_DECOR;
rightlp.gravity = Gravity.RIGHT;
+ rightlp.setFitWindowInsetsTypes(0 /* types */);
mWindowManager.addView(mRightNavigationBarWindow, rightlp);
}
}
diff --git a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarShadeControllerImpl.java b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarShadeControllerImpl.java
new file mode 100644
index 000000000000..d1d352a08908
--- /dev/null
+++ b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarShadeControllerImpl.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.statusbar.car;
+
+import android.view.View;
+import android.view.WindowManager;
+
+import com.android.car.notification.CarNotificationView;
+import com.android.systemui.assist.AssistManager;
+import com.android.systemui.bubbles.BubbleController;
+import com.android.systemui.plugins.statusbar.StatusBarStateController;
+import com.android.systemui.statusbar.CommandQueue;
+import com.android.systemui.statusbar.phone.ShadeControllerImpl;
+import com.android.systemui.statusbar.phone.StatusBar;
+import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager;
+import com.android.systemui.statusbar.phone.StatusBarWindowController;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import dagger.Lazy;
+
+/** Car specific implementation of {@link com.android.systemui.statusbar.phone.ShadeController}. */
+@Singleton
+public class CarShadeControllerImpl extends ShadeControllerImpl {
+
+ @Inject
+ public CarShadeControllerImpl(CommandQueue commandQueue,
+ StatusBarStateController statusBarStateController,
+ StatusBarWindowController statusBarWindowController,
+ StatusBarKeyguardViewManager statusBarKeyguardViewManager,
+ WindowManager windowManager,
+ Lazy<StatusBar> statusBarLazy,
+ Lazy<AssistManager> assistManagerLazy,
+ Lazy<BubbleController> bubbleControllerLazy) {
+ super(commandQueue, statusBarStateController, statusBarWindowController,
+ statusBarKeyguardViewManager, windowManager,
+ statusBarLazy, assistManagerLazy, bubbleControllerLazy);
+ }
+
+ @Override
+ public void animateCollapsePanels(int flags, boolean force, boolean delayed,
+ float speedUpFactor) {
+ super.animateCollapsePanels(flags, force, delayed, speedUpFactor);
+ if (!getCarStatusBar().isPanelExpanded()
+ || getCarNotificationView().getVisibility() == View.INVISIBLE) {
+ return;
+ }
+
+ mStatusBarWindowController.setStatusBarFocusable(false);
+ getCarStatusBar().getStatusBarWindowViewController().cancelExpandHelper();
+ getStatusBarView().collapsePanel(true /* animate */, delayed, speedUpFactor);
+
+ getCarStatusBar().animateNotificationPanel(getCarStatusBar().getClosingVelocity(), true);
+
+ if (!getCarStatusBar().isTracking()) {
+ mStatusBarWindowController.setPanelVisible(false);
+ getCarNotificationView().setVisibility(View.INVISIBLE);
+ }
+
+ getCarStatusBar().setPanelExpanded(false);
+ }
+
+ private CarStatusBar getCarStatusBar() {
+ return (CarStatusBar) mStatusBarLazy.get();
+ }
+
+ private CarNotificationView getCarNotificationView() {
+ return getCarStatusBar().getCarNotificationView();
+ }
+}
diff --git a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
index c8532e006489..1b171e87bf4a 100644
--- a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
+++ b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
@@ -63,6 +63,8 @@ import com.android.systemui.UiOffloadThread;
import com.android.systemui.assist.AssistManager;
import com.android.systemui.broadcast.BroadcastDispatcher;
import com.android.systemui.bubbles.BubbleController;
+import com.android.systemui.car.CarDeviceProvisionedController;
+import com.android.systemui.car.CarDeviceProvisionedListener;
import com.android.systemui.car.CarServiceProvider;
import com.android.systemui.classifier.FalsingLog;
import com.android.systemui.colorextraction.SysuiColorExtractor;
@@ -118,6 +120,7 @@ import com.android.systemui.statusbar.phone.LockscreenWallpaper;
import com.android.systemui.statusbar.phone.NotificationGroupAlertTransferHelper;
import com.android.systemui.statusbar.phone.NotificationGroupManager;
import com.android.systemui.statusbar.phone.ScrimController;
+import com.android.systemui.statusbar.phone.ShadeController;
import com.android.systemui.statusbar.phone.StatusBar;
import com.android.systemui.statusbar.phone.StatusBarComponent;
import com.android.systemui.statusbar.phone.StatusBarIconController;
@@ -174,10 +177,14 @@ public class CarStatusBar extends StatusBar implements CarBatteryController.Batt
private final Object mQueueLock = new Object();
private final CarNavigationBarController mCarNavigationBarController;
+ private final FlingAnimationUtils.Builder mFlingAnimationUtilsBuilder;
private final Lazy<PowerManagerHelper> mPowerManagerHelperLazy;
+ private final ShadeController mShadeController;
private final CarServiceProvider mCarServiceProvider;
+ private final CarDeviceProvisionedController mCarDeviceProvisionedController;
- private DeviceProvisionedController mDeviceProvisionedController;
+ private boolean mDeviceIsSetUpForUser = true;
+ private boolean mIsUserSetupInProgress = false;
private PowerManagerHelper mPowerManagerHelper;
private FlingAnimationUtils mFlingAnimationUtils;
private NotificationDataManager mNotificationDataManager;
@@ -308,6 +315,7 @@ public class CarStatusBar extends StatusBar implements CarBatteryController.Batt
LightsOutNotifController lightsOutNotifController,
StatusBarNotificationActivityStarter.Builder
statusBarNotificationActivityStarterBuilder,
+ ShadeController shadeController,
StatusBarKeyguardViewManager statusBarKeyguardViewManager,
ViewMediatorCallback viewMediatorCallback,
DismissCallbackRegistry dismissCallbackRegistry,
@@ -315,7 +323,8 @@ public class CarStatusBar extends StatusBar implements CarBatteryController.Batt
CarServiceProvider carServiceProvider,
Lazy<PowerManagerHelper> powerManagerHelperLazy,
Lazy<FullscreenUserSwitcher> fullscreenUserSwitcherLazy,
- CarNavigationBarController carNavigationBarController) {
+ CarNavigationBarController carNavigationBarController,
+ FlingAnimationUtils.Builder flingAnimationUtilsBuilder) {
super(
context,
featureFlags,
@@ -385,21 +394,28 @@ public class CarStatusBar extends StatusBar implements CarBatteryController.Batt
dividerOptional,
lightsOutNotifController,
statusBarNotificationActivityStarterBuilder,
+ shadeController,
superStatusBarViewFactory,
statusBarKeyguardViewManager,
viewMediatorCallback,
dismissCallbackRegistry);
mScrimController = scrimController;
mLockscreenLockIconController = lockscreenLockIconController;
- mDeviceProvisionedController = deviceProvisionedController;
+ mCarDeviceProvisionedController =
+ (CarDeviceProvisionedController) deviceProvisionedController;
+ mShadeController = shadeController;
mCarServiceProvider = carServiceProvider;
mPowerManagerHelperLazy = powerManagerHelperLazy;
mFullscreenUserSwitcherLazy = fullscreenUserSwitcherLazy;
mCarNavigationBarController = carNavigationBarController;
+ mFlingAnimationUtilsBuilder = flingAnimationUtilsBuilder;
}
@Override
public void start() {
+ mDeviceIsSetUpForUser = mCarDeviceProvisionedController.isCurrentUserSetup();
+ mIsUserSetupInProgress = mCarDeviceProvisionedController.isCurrentUserSetupInProgress();
+
// Need to initialize screen lifecycle before calling super.start - before switcher is
// created.
mScreenLifecycle = Dependency.get(ScreenLifecycle.class);
@@ -431,8 +447,10 @@ public class CarStatusBar extends StatusBar implements CarBatteryController.Batt
R.integer.notification_settle_open_percentage);
mSettleClosePercentage = mContext.getResources().getInteger(
R.integer.notification_settle_close_percentage);
- mFlingAnimationUtils = new FlingAnimationUtils(mContext,
- FLING_ANIMATION_MAX_TIME, FLING_SPEED_UP_FACTOR);
+ mFlingAnimationUtils = mFlingAnimationUtilsBuilder
+ .setMaxLengthSeconds(FLING_ANIMATION_MAX_TIME)
+ .setSpeedUpFactor(FLING_SPEED_UP_FACTOR)
+ .build();
createBatteryController();
mCarBatteryController.startListening();
@@ -440,6 +458,33 @@ public class CarStatusBar extends StatusBar implements CarBatteryController.Batt
mPowerManagerHelper = mPowerManagerHelperLazy.get();
mPowerManagerHelper.setCarPowerStateListener(mCarPowerStateListener);
mPowerManagerHelper.connectToCarService();
+
+ mCarDeviceProvisionedController.addCallback(
+ new CarDeviceProvisionedListener() {
+ @Override
+ public void onUserSetupInProgressChanged() {
+ mDeviceIsSetUpForUser = mCarDeviceProvisionedController
+ .isCurrentUserSetup();
+ mIsUserSetupInProgress = mCarDeviceProvisionedController
+ .isCurrentUserSetupInProgress();
+ }
+
+ @Override
+ public void onUserSetupChanged() {
+ mDeviceIsSetUpForUser = mCarDeviceProvisionedController
+ .isCurrentUserSetup();
+ mIsUserSetupInProgress = mCarDeviceProvisionedController
+ .isCurrentUserSetupInProgress();
+ }
+
+ @Override
+ public void onUserSwitched() {
+ mDeviceIsSetUpForUser = mCarDeviceProvisionedController
+ .isCurrentUserSetup();
+ mIsUserSetupInProgress = mCarDeviceProvisionedController
+ .isCurrentUserSetupInProgress();
+ }
+ });
}
/**
@@ -455,16 +500,18 @@ public class CarStatusBar extends StatusBar implements CarBatteryController.Batt
@Override
public boolean hideKeyguard() {
boolean result = super.hideKeyguard();
- mCarNavigationBarController.hideAllKeyguardButtons(
- mDeviceProvisionedController.isCurrentUserSetup());
+ mCarNavigationBarController.hideAllKeyguardButtons(isDeviceSetupForUser());
return result;
}
@Override
public void showKeyguard() {
super.showKeyguard();
- mCarNavigationBarController.showAllKeyguardButtons(
- mDeviceProvisionedController.isCurrentUserSetup());
+ mCarNavigationBarController.showAllKeyguardButtons(isDeviceSetupForUser());
+ }
+
+ private boolean isDeviceSetupForUser() {
+ return mDeviceIsSetUpForUser && !mIsUserSetupInProgress;
}
@Override
@@ -506,7 +553,7 @@ public class CarStatusBar extends StatusBar implements CarBatteryController.Batt
@Override
protected void close() {
if (mPanelExpanded) {
- animateCollapsePanels();
+ mShadeController.animateCollapsePanels();
}
}
});
@@ -516,7 +563,7 @@ public class CarStatusBar extends StatusBar implements CarBatteryController.Batt
@Override
protected void close() {
if (mPanelExpanded) {
- animateCollapsePanels();
+ mShadeController.animateCollapsePanels();
}
}
});
@@ -526,7 +573,7 @@ public class CarStatusBar extends StatusBar implements CarBatteryController.Batt
new HandleBarCloseNotificationGestureListener());
mTopNavBarNotificationTouchListener = (v, event) -> {
- if (!mDeviceProvisionedController.isCurrentUserSetup()) {
+ if (!isDeviceSetupForUser()) {
return true;
}
boolean consumed = openGestureDetector.onTouchEvent(event);
@@ -551,14 +598,19 @@ public class CarStatusBar extends StatusBar implements CarBatteryController.Batt
mNotificationClickHandlerFactory.registerClickListener((launchResult, alertEntry) -> {
if (launchResult == ActivityManager.START_TASK_TO_FRONT
|| launchResult == ActivityManager.START_SUCCESS) {
- animateCollapsePanels();
+ mShadeController.animateCollapsePanels();
}
});
CarNotificationListener carNotificationListener = new CarNotificationListener();
mCarUxRestrictionManagerWrapper = new CarUxRestrictionManagerWrapper();
mNotificationDataManager = new NotificationDataManager();
- mNotificationDataManager.setOnUnseenCountUpdateListener(this::onUnseenCountUpdate);
+
+ mNotificationDataManager.setOnUnseenCountUpdateListener(() -> {
+ if (mNotificationDataManager != null) {
+ onUseenCountUpdate(mNotificationDataManager.getUnseenNotificationCount());
+ }
+ });
mEnableHeadsUpNotificationWhenNotificationShadeOpen = mContext.getResources().getBoolean(
R.bool.config_enableHeadsUpNotificationWhenNotificationShadeOpen);
@@ -680,15 +732,13 @@ public class CarStatusBar extends StatusBar implements CarBatteryController.Batt
}
/**
- * This method is called whenever there is an update to the number of unseen notifications.
- * This method can be extended by OEMs to customize the desired logic.
+ * This method is automatically called whenever there is an update to the number of unseen
+ * notifications. This method can be extended by OEMs to customize the desired logic.
*/
- protected void onUnseenCountUpdate() {
- if (mNotificationDataManager != null) {
- boolean hasUnseen = mNotificationDataManager.getUnseenNotificationCount() > 0;
- mCarNavigationBarController.toggleAllNotificationsUnseenIndicator(
- mDeviceProvisionedController.isCurrentUserSetup(), hasUnseen);
- }
+ protected void onUseenCountUpdate(int unseenNotificationCount) {
+ boolean hasUnseen = unseenNotificationCount > 0;
+ mCarNavigationBarController.toggleAllNotificationsUnseenIndicator(isDeviceSetupForUser(),
+ hasUnseen);
}
/**
@@ -712,25 +762,16 @@ public class CarStatusBar extends StatusBar implements CarBatteryController.Batt
setPanelExpanded(true);
}
- @Override
- public void animateCollapsePanels(int flags, boolean force, boolean delayed,
- float speedUpFactor) {
- super.animateCollapsePanels(flags, force, delayed, speedUpFactor);
- if (!mPanelExpanded || mNotificationView.getVisibility() == View.INVISIBLE) {
- return;
- }
- mStatusBarWindowController.setStatusBarFocusable(false);
- mStatusBarWindowViewController.cancelExpandHelper();
- mStatusBarView.collapsePanel(true /* animate */, delayed, speedUpFactor);
-
- animateNotificationPanel(mClosingVelocity, true);
+ public CarNotificationView getCarNotificationView() {
+ return mNotificationView;
+ }
- if (!mIsTracking) {
- mStatusBarWindowController.setPanelVisible(false);
- mNotificationView.setVisibility(View.INVISIBLE);
- }
+ public float getClosingVelocity() {
+ return mClosingVelocity;
+ }
- setPanelExpanded(false);
+ public boolean isTracking() {
+ return mIsTracking;
}
private void maybeCompleteAnimation(MotionEvent event) {
@@ -749,7 +790,7 @@ public class CarStatusBar extends StatusBar implements CarBatteryController.Batt
* close the notification shade completely with a velocity. If the animation is to close the
* notification shade this method also makes the view invisible after animation ends.
*/
- private void animateNotificationPanel(float velocity, boolean isClosing) {
+ void animateNotificationPanel(float velocity, boolean isClosing) {
float to = 0;
if (!isClosing) {
to = mNotificationView.getHeight();
@@ -1263,8 +1304,10 @@ public class CarStatusBar extends StatusBar implements CarBatteryController.Batt
@Override
protected void setHeadsUpVisible() {
- // if the Notifications panel is showing don't show the Heads up
- if (!mEnableHeadsUpNotificationWhenNotificationShadeOpen && mPanelExpanded) {
+ // if the Notifications panel is showing or SUW for user is in progress then don't show
+ // heads up notifications
+ if ((!mEnableHeadsUpNotificationWhenNotificationShadeOpen && mPanelExpanded)
+ || !isDeviceSetupForUser()) {
return;
}
diff --git a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBarModule.java b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBarModule.java
index eff60fa246a4..7b21d9d8a2d7 100644
--- a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBarModule.java
+++ b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBarModule.java
@@ -43,6 +43,7 @@ import com.android.systemui.shared.plugins.PluginManager;
import com.android.systemui.stackdivider.Divider;
import com.android.systemui.statusbar.CommandQueue;
import com.android.systemui.statusbar.FeatureFlags;
+import com.android.systemui.statusbar.FlingAnimationUtils;
import com.android.systemui.statusbar.NavigationBarController;
import com.android.systemui.statusbar.NotificationListener;
import com.android.systemui.statusbar.NotificationLockscreenUserManager;
@@ -78,6 +79,7 @@ import com.android.systemui.statusbar.phone.LockscreenWallpaper;
import com.android.systemui.statusbar.phone.NotificationGroupAlertTransferHelper;
import com.android.systemui.statusbar.phone.NotificationGroupManager;
import com.android.systemui.statusbar.phone.ScrimController;
+import com.android.systemui.statusbar.phone.ShadeController;
import com.android.systemui.statusbar.phone.StatusBarComponent;
import com.android.systemui.statusbar.phone.StatusBarIconController;
import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager;
@@ -183,13 +185,15 @@ public class CarStatusBarModule {
LightsOutNotifController lightsOutNotifController,
StatusBarNotificationActivityStarter.Builder
statusBarNotificationActivityStarterBuilder,
+ ShadeController shadeController,
StatusBarKeyguardViewManager statusBarKeyguardViewManager,
ViewMediatorCallback viewMediatorCallback,
DismissCallbackRegistry dismissCallbackRegistry,
CarServiceProvider carServiceProvider,
Lazy<PowerManagerHelper> powerManagerHelperLazy,
Lazy<FullscreenUserSwitcher> fullscreenUserSwitcherLazy,
- CarNavigationBarController carNavigationBarController) {
+ CarNavigationBarController carNavigationBarController,
+ FlingAnimationUtils.Builder flingAnimationUtilsBuilder) {
return new CarStatusBar(
context,
featureFlags,
@@ -259,12 +263,14 @@ public class CarStatusBarModule {
superStatusBarViewFactory,
lightsOutNotifController,
statusBarNotificationActivityStarterBuilder,
+ shadeController,
statusBarKeyguardViewManager,
viewMediatorCallback,
dismissCallbackRegistry,
carServiceProvider,
powerManagerHelperLazy,
fullscreenUserSwitcherLazy,
- carNavigationBarController);
+ carNavigationBarController,
+ flingAnimationUtilsBuilder);
}
}
diff --git a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarTrustAgentUnlockDialogHelper.java b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarTrustAgentUnlockDialogHelper.java
index ec4643302a05..2d57be177333 100644
--- a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarTrustAgentUnlockDialogHelper.java
+++ b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarTrustAgentUnlockDialogHelper.java
@@ -240,7 +240,7 @@ class CarTrustAgentUnlockDialogHelper extends BroadcastReceiver{
}
private WindowManager.LayoutParams createLayoutParams() {
- return new WindowManager.LayoutParams(
+ final WindowManager.LayoutParams attrs = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG,
@@ -249,6 +249,8 @@ class CarTrustAgentUnlockDialogHelper extends BroadcastReceiver{
| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
PixelFormat.TRANSLUCENT
);
+ attrs.setFitWindowInsetsTypes(0 /* types */);
+ return attrs;
}
private void logd(String message) {
diff --git a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/FullscreenUserSwitcher.java b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/FullscreenUserSwitcher.java
index 291cdd5ea3d8..3d7486859686 100644
--- a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/FullscreenUserSwitcher.java
+++ b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/FullscreenUserSwitcher.java
@@ -131,10 +131,7 @@ public class FullscreenUserSwitcher {
private void showDialogForInitialUser() {
int initialUser = mCarUserManagerHelper.getInitialUser();
UserInfo initialUserInfo = mUserManager.getUserInfo(initialUser);
- mSelectedUser = new UserRecord(initialUserInfo,
- /* isStartGuestSession= */ false,
- /* isAddUser= */ false,
- /* isForeground= */ true);
+ mSelectedUser = new UserRecord(initialUserInfo, UserRecord.FOREGROUND_USER);
// If the initial user has screen lock and trusted device, display the unlock dialog on the
// keyguard.
@@ -180,12 +177,14 @@ public class FullscreenUserSwitcher {
*/
private void onUserSelected(UserGridRecyclerView.UserRecord record) {
mSelectedUser = record;
- if (hasScreenLock(record.mInfo.id) && hasTrustedDevice(record.mInfo.id)) {
- mUnlockDialogHelper.showUnlockDialog(record.mInfo.id, mOnHideListener);
- return;
- }
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "no trusted device enrolled for uid: " + record.mInfo.id);
+ if (record.mInfo != null) {
+ if (hasScreenLock(record.mInfo.id) && hasTrustedDevice(record.mInfo.id)) {
+ mUnlockDialogHelper.showUnlockDialog(record.mInfo.id, mOnHideListener);
+ return;
+ }
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "no trusted device enrolled for uid: " + record.mInfo.id);
+ }
}
dismissUserSwitcher();
}
@@ -195,7 +194,7 @@ public class FullscreenUserSwitcher {
Log.e(TAG, "Request to dismiss user switcher, but no user selected");
return;
}
- if (mSelectedUser.mIsForeground) {
+ if (mSelectedUser.mType == UserRecord.FOREGROUND_USER) {
hide();
mStatusBar.dismissKeyguard();
return;
diff --git a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/UserGridRecyclerView.java b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/UserGridRecyclerView.java
index 0a5f80f4f95e..cdabeebe2819 100644
--- a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/UserGridRecyclerView.java
+++ b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/UserGridRecyclerView.java
@@ -21,6 +21,7 @@ import static android.content.DialogInterface.BUTTON_POSITIVE;
import static android.os.UserManager.DISALLOW_ADD_USER;
import static android.os.UserManager.SWITCHABILITY_STATUS_OK;
+import android.annotation.IntDef;
import android.annotation.Nullable;
import android.app.ActivityManager;
import android.app.AlertDialog;
@@ -54,6 +55,8 @@ import com.android.internal.util.UserIcons;
import com.android.systemui.R;
import com.android.systemui.statusbar.phone.SystemUIDialog;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@@ -142,8 +145,8 @@ public class UserGridRecyclerView extends RecyclerView {
}
boolean isForeground = fgUserId == userInfo.id;
- UserRecord record = new UserRecord(userInfo, false /* isStartGuestSession */,
- false /* isAddUser */, isForeground);
+ UserRecord record = new UserRecord(userInfo,
+ isForeground ? UserRecord.FOREGROUND_USER : UserRecord.BACKGROUND_USER);
userRecords.add(record);
}
@@ -160,27 +163,21 @@ public class UserGridRecyclerView extends RecyclerView {
private UserRecord createForegroundUserRecord() {
return new UserRecord(mUserManager.getUserInfo(ActivityManager.getCurrentUser()),
- false /* isStartGuestSession */, false /* isAddUser */, true /* isForeground */);
+ UserRecord.FOREGROUND_USER);
}
/**
* Create guest user record
*/
private UserRecord createStartGuestUserRecord() {
- UserInfo userInfo = new UserInfo();
- userInfo.name = mContext.getString(R.string.start_guest_session);
- return new UserRecord(userInfo, true /* isStartGuestSession */, false /* isAddUser */,
- false /* isForeground */);
+ return new UserRecord(null /* userInfo */, UserRecord.START_GUEST);
}
/**
* Create add user record
*/
private UserRecord createAddUserRecord() {
- UserInfo userInfo = new UserInfo();
- userInfo.name = mContext.getString(R.string.car_add_user);
- return new UserRecord(userInfo, false /* isStartGuestSession */,
- true /* isAddUser */, false /* isForeground */);
+ return new UserRecord(null /* userInfo */, UserRecord.ADD_USER);
}
public void setUserSelectionListener(UserSelectionListener userSelectionListener) {
@@ -258,35 +255,36 @@ public class UserGridRecyclerView extends RecyclerView {
UserRecord userRecord = mUsers.get(position);
RoundedBitmapDrawable circleIcon = getCircularUserRecordIcon(userRecord);
holder.mUserAvatarImageView.setImageDrawable(circleIcon);
- holder.mUserNameTextView.setText(userRecord.mInfo.name);
+ holder.mUserNameTextView.setText(getUserRecordName(userRecord));
holder.mView.setOnClickListener(v -> {
if (userRecord == null) {
return;
}
- if (userRecord.mIsStartGuestSession) {
- notifyUserSelected(userRecord);
- UserInfo guest = createNewOrFindExistingGuest(mContext);
- if (guest != null) {
- mCarUserManagerHelper.switchToUser(guest);
- }
- return;
+ switch (userRecord.mType) {
+ case UserRecord.START_GUEST:
+ notifyUserSelected(userRecord);
+ UserInfo guest = createNewOrFindExistingGuest(mContext);
+ if (guest != null) {
+ mCarUserManagerHelper.switchToUser(guest);
+ }
+ break;
+ case UserRecord.ADD_USER:
+ // If the user wants to add a user, show dialog to confirm adding a user
+ // Disable button so it cannot be clicked multiple times
+ mAddUserView = holder.mView;
+ mAddUserView.setEnabled(false);
+ mAddUserRecord = userRecord;
+
+ handleAddUserClicked();
+ break;
+ default:
+ // If the user doesn't want to be a guest or add a user, switch to the user
+ // selected
+ notifyUserSelected(userRecord);
+ mCarUserManagerHelper.switchToUser(userRecord.mInfo);
}
-
- // If the user wants to add a user, show dialog to confirm adding a user
- if (userRecord.mIsAddUser) {
- // Disable button so it cannot be clicked multiple times
- mAddUserView = holder.mView;
- mAddUserView.setEnabled(false);
- mAddUserRecord = userRecord;
-
- handleAddUserClicked();
- return;
- }
- // If the user doesn't want to be a guest or add a user, switch to the user selected
- notifyUserSelected(userRecord);
- mCarUserManagerHelper.switchToUser(userRecord.mInfo);
});
}
@@ -372,19 +370,44 @@ public class UserGridRecyclerView extends RecyclerView {
private RoundedBitmapDrawable getCircularUserRecordIcon(UserRecord userRecord) {
Resources resources = mContext.getResources();
RoundedBitmapDrawable circleIcon;
- if (userRecord.mIsStartGuestSession) {
- circleIcon = mUserIconProvider.getRoundedGuestDefaultIcon(resources);
- } else if (userRecord.mIsAddUser) {
- circleIcon = RoundedBitmapDrawableFactory.create(mRes, UserIcons.convertToBitmap(
- mContext.getDrawable(R.drawable.car_add_circle_round)));
- circleIcon.setCircular(true);
- } else {
- circleIcon = mUserIconProvider.getRoundedUserIcon(userRecord.mInfo, mContext);
+ switch (userRecord.mType) {
+ case UserRecord.START_GUEST:
+ circleIcon = mUserIconProvider.getRoundedGuestDefaultIcon(resources);
+ break;
+ case UserRecord.ADD_USER:
+ circleIcon = getCircularAddUserIcon();
+ break;
+ default:
+ circleIcon = mUserIconProvider.getRoundedUserIcon(userRecord.mInfo, mContext);
+ break;
}
+ return circleIcon;
+ }
+ private RoundedBitmapDrawable getCircularAddUserIcon() {
+ RoundedBitmapDrawable circleIcon =
+ RoundedBitmapDrawableFactory.create(mRes, UserIcons.convertToBitmap(
+ mContext.getDrawable(R.drawable.car_add_circle_round)));
+ circleIcon.setCircular(true);
return circleIcon;
}
+ private String getUserRecordName(UserRecord userRecord) {
+ String recordName;
+ switch (userRecord.mType) {
+ case UserRecord.START_GUEST:
+ recordName = mContext.getString(R.string.start_guest_session);
+ break;
+ case UserRecord.ADD_USER:
+ recordName = mContext.getString(R.string.car_add_user);
+ break;
+ default:
+ recordName = userRecord.mInfo.name;
+ break;
+ }
+ return recordName;
+ }
+
/**
* Finds the existing Guest user, or creates one if it doesn't exist.
* @param context App context
@@ -468,18 +491,21 @@ public class UserGridRecyclerView extends RecyclerView {
* guest profile, add user profile, or the foreground user.
*/
public static final class UserRecord {
-
public final UserInfo mInfo;
- public final boolean mIsStartGuestSession;
- public final boolean mIsAddUser;
- public final boolean mIsForeground;
+ public final @UserRecordType int mType;
+
+ public static final int START_GUEST = 0;
+ public static final int ADD_USER = 1;
+ public static final int FOREGROUND_USER = 2;
+ public static final int BACKGROUND_USER = 3;
+
+ @IntDef({START_GUEST, ADD_USER, FOREGROUND_USER, BACKGROUND_USER})
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface UserRecordType{}
- public UserRecord(UserInfo userInfo, boolean isStartGuestSession, boolean isAddUser,
- boolean isForeground) {
+ public UserRecord(@Nullable UserInfo userInfo, @UserRecordType int recordType) {
mInfo = userInfo;
- mIsStartGuestSession = isStartGuestSession;
- mIsAddUser = isAddUser;
- mIsForeground = isForeground;
+ mType = recordType;
}
}
diff --git a/packages/CarrierDefaultApp/src/com/android/carrierdefaultapp/CarrierActionUtils.java b/packages/CarrierDefaultApp/src/com/android/carrierdefaultapp/CarrierActionUtils.java
index 3258d57ba8e0..2697a1066ed2 100644
--- a/packages/CarrierDefaultApp/src/com/android/carrierdefaultapp/CarrierActionUtils.java
+++ b/packages/CarrierDefaultApp/src/com/android/carrierdefaultapp/CarrierActionUtils.java
@@ -29,6 +29,7 @@ import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
+
import com.android.internal.telephony.PhoneConstants;
/**
@@ -138,7 +139,7 @@ public class CarrierActionUtils {
SubscriptionManager.getDefaultVoiceSubscriptionId());
logd("onRegisterDefaultNetworkAvail subId: " + subId);
final TelephonyManager telephonyMgr = context.getSystemService(TelephonyManager.class);
- telephonyMgr.carrierActionReportDefaultNetworkStatus(subId, true);
+ telephonyMgr.createForSubscriptionId(subId).reportDefaultNetworkStatus(true);
}
private static void onDeregisterDefaultNetworkAvail(Intent intent, Context context) {
@@ -146,7 +147,7 @@ public class CarrierActionUtils {
SubscriptionManager.getDefaultVoiceSubscriptionId());
logd("onDeregisterDefaultNetworkAvail subId: " + subId);
final TelephonyManager telephonyMgr = context.getSystemService(TelephonyManager.class);
- telephonyMgr.carrierActionReportDefaultNetworkStatus(subId, false);
+ telephonyMgr.createForSubscriptionId(subId).reportDefaultNetworkStatus(false);
}
private static void onDisableRadio(Intent intent, Context context) {
@@ -154,7 +155,7 @@ public class CarrierActionUtils {
SubscriptionManager.getDefaultVoiceSubscriptionId());
logd("onDisableRadio subId: " + subId);
final TelephonyManager telephonyMgr = context.getSystemService(TelephonyManager.class);
- telephonyMgr.carrierActionSetRadioEnabled(subId, !ENABLE);
+ telephonyMgr.createForSubscriptionId(subId).setRadioEnabled(!ENABLE);
}
private static void onEnableRadio(Intent intent, Context context) {
@@ -162,7 +163,7 @@ public class CarrierActionUtils {
SubscriptionManager.getDefaultVoiceSubscriptionId());
logd("onEnableRadio subId: " + subId);
final TelephonyManager telephonyMgr = context.getSystemService(TelephonyManager.class);
- telephonyMgr.carrierActionSetRadioEnabled(subId, ENABLE);
+ telephonyMgr.createForSubscriptionId(subId).setRadioEnabled(ENABLE);
}
private static void onShowCaptivePortalNotification(Intent intent, Context context) {
@@ -205,7 +206,7 @@ public class CarrierActionUtils {
SubscriptionManager.getDefaultVoiceSubscriptionId());
logd("onResetAllCarrierActions subId: " + subId);
final TelephonyManager telephonyMgr = context.getSystemService(TelephonyManager.class);
- telephonyMgr.carrierActionResetAll(subId);
+ telephonyMgr.createForSubscriptionId(subId).resetAllCarrierActions();
}
private static Notification getNotification(Context context, int titleId, int textId,
diff --git a/packages/Incremental/NativeAdbDataLoader/Android.bp b/packages/Incremental/NativeAdbDataLoader/Android.bp
new file mode 100644
index 000000000000..5d7b5b6c229d
--- /dev/null
+++ b/packages/Incremental/NativeAdbDataLoader/Android.bp
@@ -0,0 +1,22 @@
+// Copyright 2019, 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.
+
+android_app {
+ name: "NativeAdbDataLoaderService",
+ srcs: ["src/**/*.java"],
+ jni_libs: [ "libnativeadbdataloaderservice_jni"],
+ privileged: true,
+ certificate: "platform",
+ platform_apis: true,
+}
diff --git a/packages/Incremental/NativeAdbDataLoader/AndroidManifest.xml b/packages/Incremental/NativeAdbDataLoader/AndroidManifest.xml
new file mode 100644
index 000000000000..a06dc546f85c
--- /dev/null
+++ b/packages/Incremental/NativeAdbDataLoader/AndroidManifest.xml
@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+/*
+** Copyright 2019, 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.
+*/
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ coreApp="true"
+ package="com.android.incremental.nativeadb"
+ android:sharedUserId="android.uid.system">
+ <uses-permission android:name="android.permission.INTERNET" />
+
+ <application android:label="@string/app_name"
+ android:directBootAware="true">
+
+ <service android:enabled="true"
+ android:name="com.android.incremental.nativeadb.NativeAdbDataLoaderService"
+ android:label="@string/app_name"
+ android:exported="true">
+ <intent-filter>
+ <action android:name="android.intent.action.LOAD_DATA" />
+ </intent-filter>
+ </service>
+ </application>
+
+</manifest>
diff --git a/packages/Incremental/NativeAdbDataLoader/jni/Android.bp b/packages/Incremental/NativeAdbDataLoader/jni/Android.bp
new file mode 100644
index 000000000000..0fcfd28cf28c
--- /dev/null
+++ b/packages/Incremental/NativeAdbDataLoader/jni/Android.bp
@@ -0,0 +1,37 @@
+// Copyright 2019, 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.
+
+cc_library_shared {
+ name: "libnativeadbdataloaderservice_jni",
+ cpp_std: "c++2a",
+ cflags: [
+ "-Wall",
+ "-Werror",
+ "-Wunused",
+ "-Wunreachable-code",
+ "-Wno-unused-parameter",
+ ],
+
+ srcs: ["com_android_incremental_nativeadb_DataLoaderService.cpp"],
+
+ shared_libs: [
+ "libbase",
+ "libcutils",
+ "libincfs",
+ "libdataloader",
+ "liblog",
+ "libnativehelper",
+ "libutils",
+ ],
+}
diff --git a/packages/Incremental/NativeAdbDataLoader/jni/com_android_incremental_nativeadb_DataLoaderService.cpp b/packages/Incremental/NativeAdbDataLoader/jni/com_android_incremental_nativeadb_DataLoaderService.cpp
new file mode 100644
index 000000000000..de92fcd5b2e8
--- /dev/null
+++ b/packages/Incremental/NativeAdbDataLoader/jni/com_android_incremental_nativeadb_DataLoaderService.cpp
@@ -0,0 +1,519 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#define ATRACE_TAG ATRACE_TAG_ADB
+#define LOG_TAG "NativeAdbDataLoaderService"
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/properties.h>
+#include <android-base/stringprintf.h>
+#include <android-base/thread_annotations.h>
+#include <android-base/unique_fd.h>
+#include <cutils/trace.h>
+#include <fcntl.h>
+#include <sys/eventfd.h>
+#include <sys/poll.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <utils/Log.h>
+
+#include <charconv>
+#include <string>
+#include <thread>
+#include <type_traits>
+#include <unordered_map>
+#include <unordered_set>
+
+#include "dataloader.h"
+
+#ifndef _WIN32
+#include <endian.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#else
+#define be32toh(x) _byteswap_ulong(x)
+#define be16toh(x) _byteswap_ushort(x)
+#endif
+
+namespace {
+
+using android::base::unique_fd;
+
+using namespace std::literals;
+
+using BlockSize = int16_t;
+using FileId = int16_t;
+using BlockIdx = int32_t;
+using NumBlocks = int32_t;
+using CompressionType = int16_t;
+using RequestType = int16_t;
+
+static constexpr int COMMAND_SIZE = 2 + 2 + 4; // bytes
+static constexpr int HEADER_SIZE = 2 + 2 + 4 + 2; // bytes
+static constexpr std::string_view OKAY = "OKAY"sv;
+
+static constexpr auto PollTimeoutMs = 5000;
+
+static constexpr auto ReadLogBufferSize = 128 * 1024 * 1024;
+static constexpr auto ReadLogMaxEntrySize = 128;
+
+struct BlockHeader {
+ FileId fileId = -1;
+ CompressionType compressionType = -1;
+ BlockIdx blockIdx = -1;
+ BlockSize blockSize = -1;
+} __attribute__((packed));
+
+static_assert(sizeof(BlockHeader) == HEADER_SIZE);
+
+static constexpr RequestType EXIT = 0;
+static constexpr RequestType BLOCK_MISSING = 1;
+static constexpr RequestType PREFETCH = 2;
+
+struct RequestCommand {
+ RequestType requestType;
+ FileId fileId;
+ BlockIdx blockIdx;
+} __attribute__((packed));
+
+static_assert(COMMAND_SIZE == sizeof(RequestCommand));
+
+static bool sendRequest(int fd,
+ RequestType requestType,
+ FileId fileId = -1,
+ BlockIdx blockIdx = -1) {
+ const RequestCommand command{
+ .requestType = static_cast<int16_t>(be16toh(requestType)),
+ .fileId = static_cast<int16_t>(be16toh(fileId)),
+ .blockIdx = static_cast<int32_t>(be32toh(blockIdx))};
+ return android::base::WriteFully(fd, &command, sizeof(command));
+}
+
+static int waitForDataOrSignal(int fd, int event_fd) {
+ struct pollfd pfds[2] = {{fd, POLLIN, 0}, {event_fd, POLLIN, 0}};
+ // Wait indefinitely until either data is ready or stop signal is received
+ int res = poll(pfds, 2, PollTimeoutMs);
+ if (res <= 0) {
+ return res;
+ }
+ // First check if there is a stop signal
+ if (pfds[1].revents == POLLIN) {
+ return event_fd;
+ }
+ // Otherwise check if incoming data is ready
+ if (pfds[0].revents == POLLIN) {
+ return fd;
+ }
+ return -1;
+}
+
+static bool readChunk(int fd, std::vector<uint8_t>& data) {
+ int32_t size;
+ if (!android::base::ReadFully(fd, &size, sizeof(size))) {
+ return false;
+ }
+ size = int32_t(be32toh(size));
+ if (size <= 0) {
+ return false;
+ }
+ data.resize(size);
+ return android::base::ReadFully(fd, data.data(), data.size());
+}
+
+static BlockHeader readHeader(std::span<uint8_t>& data) {
+ BlockHeader header;
+ if (data.size() < sizeof(header)) {
+ return header;
+ }
+
+ header.fileId = static_cast<FileId>(
+ be16toh(*reinterpret_cast<uint16_t*>(&data[0])));
+ header.compressionType = static_cast<CompressionType>(
+ be16toh(*reinterpret_cast<uint16_t*>(&data[2])));
+ header.blockIdx = static_cast<BlockIdx>(
+ be32toh(*reinterpret_cast<uint32_t*>(&data[4])));
+ header.blockSize = static_cast<BlockSize>(
+ be16toh(*reinterpret_cast<uint16_t*>(&data[8])));
+ data = data.subspan(sizeof(header));
+
+ return header;
+}
+
+static std::string extractPackageName(const std::string& staticArgs) {
+ static constexpr auto kPrefix = "package="sv;
+ static constexpr auto kSuffix = "&"sv;
+
+ const auto startPos = staticArgs.find(kPrefix);
+ if (startPos == staticArgs.npos || startPos + kPrefix.size() >= staticArgs.size()) {
+ return {};
+ }
+ const auto endPos = staticArgs.find(kSuffix, startPos + kPrefix.size());
+ return staticArgs.substr(startPos + kPrefix.size(),
+ endPos == staticArgs.npos ? staticArgs.npos
+ : (endPos - (startPos + kPrefix.size())));
+}
+
+class AdbDataLoader : public android::dataloader::DataLoader {
+private:
+ // Lifecycle.
+ bool onCreate(const android::dataloader::DataLoaderParams& params,
+ android::dataloader::FilesystemConnectorPtr ifs,
+ android::dataloader::StatusListenerPtr statusListener,
+ android::dataloader::ServiceConnectorPtr,
+ android::dataloader::ServiceParamsPtr) final {
+ CHECK(ifs) << "ifs can't be null";
+ CHECK(statusListener) << "statusListener can't be null";
+ ALOGE("[AdbDataLoader] onCreate: %s/%s/%d", params.staticArgs().c_str(),
+ params.packageName().c_str(), (int)params.dynamicArgs().size());
+
+ if (params.dynamicArgs().empty()) {
+ ALOGE("[AdbDataLoader] Invalid DataLoaderParams. Need in/out FDs.");
+ return false;
+ }
+ for (auto const& namedFd : params.dynamicArgs()) {
+ if (namedFd.name == "inFd") {
+ mInFd.reset(dup(namedFd.fd));
+ }
+ if (namedFd.name == "outFd") {
+ mOutFd.reset(dup(namedFd.fd));
+ }
+ }
+ if (mInFd < 0 || mOutFd < 0) {
+ ALOGE("[AdbDataLoader] Failed to dup FDs.");
+ return false;
+ }
+
+ mEventFd.reset(eventfd(0, EFD_CLOEXEC));
+ if (mEventFd < 0) {
+ ALOGE("[AdbDataLoader] Failed to create eventfd.");
+ return false;
+ }
+
+ std::string logFile;
+ if (const auto packageName = extractPackageName(params.staticArgs()); !packageName.empty()) {
+ logFile = android::base::GetProperty("adb.readlog." + packageName, "");
+ }
+ if (logFile.empty()) {
+ logFile = android::base::GetProperty("adb.readlog", "");
+ }
+ if (!logFile.empty()) {
+ int flags = O_WRONLY | O_CREAT | O_CLOEXEC;
+ mReadLogFd.reset(
+ TEMP_FAILURE_RETRY(open(logFile.c_str(), flags, 0666)));
+ }
+
+ mIfs = ifs;
+ mStatusListener = statusListener;
+ ALOGE("[AdbDataLoader] Successfully created data loader.");
+ return true;
+ }
+
+ bool onStart() final {
+ char okay_buf[OKAY.size()];
+ if (!android::base::ReadFully(mInFd, okay_buf, OKAY.size())) {
+ ALOGE("[AdbDataLoader] Failed to receive OKAY. Abort.");
+ return false;
+ }
+ if (std::string_view(okay_buf, OKAY.size()) != OKAY) {
+ ALOGE("[AdbDataLoader] Received '%.*s', expecting '%.*s'",
+ (int)OKAY.size(), okay_buf, (int)OKAY.size(), OKAY.data());
+ return false;
+ }
+
+ mReceiverThread = std::thread([this]() { receiver(); });
+ ALOGI("[AdbDataLoader] started loading...");
+ return true;
+ }
+
+ void onStop() final {
+ mStopReceiving = true;
+ eventfd_write(mEventFd, 1);
+ if (mReceiverThread.joinable()) {
+ mReceiverThread.join();
+ }
+ }
+
+ void onDestroy() final {
+ ALOGE("[AdbDataLoader] Sending EXIT to server.");
+ sendRequest(mOutFd, EXIT);
+ // Make sure the receiver thread was stopped
+ CHECK(!mReceiverThread.joinable());
+
+ mInFd.reset();
+ mOutFd.reset();
+
+ mNodeToMetaMap.clear();
+ mIdToNodeMap.clear();
+
+ flushReadLog();
+ mReadLogFd.reset();
+ }
+
+ // IFS callbacks.
+ void onPendingReads(const android::dataloader::PendingReads& pendingReads) final {
+ std::lock_guard lock{mMapsMutex};
+ CHECK(mIfs);
+ for (auto&& pendingRead : pendingReads) {
+ const android::dataloader::Inode ino = pendingRead.file_ino;
+ const auto blockIdx =
+ static_cast<BlockIdx>(pendingRead.block_index);
+ /*
+ ALOGI("[AdbDataLoader] Missing: %d", (int) blockIdx);
+ */
+ auto fileIdOr = getFileId(ino);
+ if (!fileIdOr) {
+ ALOGE("[AdbDataLoader] Failed to handle event for inode=%d. "
+ "Ignore.",
+ static_cast<int>(ino));
+ continue;
+ }
+ const FileId fileId = *fileIdOr;
+ if (mRequestedFiles.insert(fileId).second) {
+ if (!sendRequest(mOutFd, PREFETCH, fileId, blockIdx)) {
+ ALOGE("[AdbDataLoader] Failed to request prefetch for "
+ "inode=%d. Ignore.",
+ static_cast<int>(ino));
+ mRequestedFiles.erase(fileId);
+ mStatusListener->reportStatus(
+ INCREMENTAL_DATA_LOADER_NO_CONNECTION);
+ }
+ }
+ sendRequest(mOutFd, BLOCK_MISSING, fileId, blockIdx);
+ }
+ }
+
+ struct TracedRead {
+ uint64_t timestampUs;
+ uint64_t fileIno;
+ uint32_t firstBlockIdx;
+ uint32_t count;
+ };
+ void onPageReads(const android::dataloader::PageReads& pageReads) final {
+ auto trace = atrace_is_tag_enabled(ATRACE_TAG);
+ auto log = mReadLogFd != -1;
+ if (CC_LIKELY(!(trace || log))) {
+ return;
+ }
+
+ TracedRead last = {0, 0, 0, 0};
+ std::lock_guard lock{mMapsMutex};
+ for (auto&& read : pageReads) {
+ if (read.file_ino != last.fileIno ||
+ read.block_index != last.firstBlockIdx + last.count) {
+ traceOrLogRead(last, trace, log);
+ last = {read.timestamp_us, read.file_ino, read.block_index, 1};
+ } else {
+ ++last.count;
+ }
+ }
+ traceOrLogRead(last, trace, log);
+ }
+ void onFileCreated(android::dataloader::Inode inode, const android::dataloader::RawMetadata& metadata) {
+ }
+
+private:
+ void receiver() {
+ std::vector<uint8_t> data;
+ std::vector<incfs_new_data_block> instructions;
+ while (!mStopReceiving) {
+ const int res = waitForDataOrSignal(mInFd, mEventFd);
+ if (res == 0) {
+ flushReadLog();
+ continue;
+ }
+ if (res < 0) {
+ ALOGE("[AdbDataLoader] failed to poll. Abort.");
+ mStatusListener->reportStatus(INCREMENTAL_DATA_LOADER_NO_CONNECTION);
+ break;
+ }
+ if (res == mEventFd) {
+ ALOGE("[AdbDataLoader] received stop signal. Exit.");
+ break;
+ }
+ if (!readChunk(mInFd, data)) {
+ ALOGE("[AdbDataLoader] failed to read a message. Abort.");
+ mStatusListener->reportStatus(INCREMENTAL_DATA_LOADER_NO_CONNECTION);
+ break;
+ }
+ auto remainingData = std::span(data);
+ while (!remainingData.empty()) {
+ auto header = readHeader(remainingData);
+ if (header.fileId == -1 && header.compressionType == 0 &&
+ header.blockIdx == 0 && header.blockSize == 0) {
+ ALOGI("[AdbDataLoader] stop signal received. Sending "
+ "exit command (remaining bytes: %d).",
+ int(remainingData.size()));
+
+ sendRequest(mOutFd, EXIT);
+ mStopReceiving = true;
+ break;
+ }
+ if (header.fileId < 0 || header.blockSize <= 0 ||
+ header.compressionType < 0 || header.blockIdx < 0) {
+ ALOGE("[AdbDataLoader] invalid header received. Abort.");
+ mStopReceiving = true;
+ break;
+ }
+ const android::dataloader::Inode ino = mIdToNodeMap[header.fileId];
+ if (!ino) {
+ ALOGE("Unknown data destination for file ID %d. "
+ "Ignore.",
+ header.fileId);
+ continue;
+ }
+ auto inst = incfs_new_data_block{
+ .file_ino = static_cast<__aligned_u64>(ino),
+ .block_index = static_cast<uint32_t>(header.blockIdx),
+ .data_len = static_cast<uint16_t>(header.blockSize),
+ .data = reinterpret_cast<uint64_t>(
+ remainingData.data()),
+ .compression =
+ static_cast<uint8_t>(header.compressionType)};
+ instructions.push_back(inst);
+ remainingData = remainingData.subspan(header.blockSize);
+ }
+ writeInstructions(instructions);
+ }
+ writeInstructions(instructions);
+ flushReadLog();
+ }
+
+ void writeInstructions(std::vector<incfs_new_data_block>& instructions) {
+ auto res = this->mIfs->writeBlocks(instructions.data(),
+ instructions.size());
+ if (res != instructions.size()) {
+ ALOGE("[AdbDataLoader] failed to write data to Incfs (res=%d when "
+ "expecting %d)",
+ res, int(instructions.size()));
+ }
+ instructions.clear();
+ }
+
+ struct MetaPair {
+ android::dataloader::RawMetadata meta;
+ FileId fileId;
+ };
+
+ MetaPair* updateMapsForFile(android::dataloader::Inode ino) {
+ android::dataloader::RawMetadata meta = mIfs->getRawMetadata(ino);
+ FileId fileId;
+ auto res =
+ std::from_chars(meta.data(), meta.data() + meta.size(), fileId);
+ if (res.ec != std::errc{} || fileId < 0) {
+ ALOGE("[AdbDataLoader] Invalid metadata for inode=%d (%s)",
+ static_cast<int>(ino), meta.data());
+ return nullptr;
+ }
+ mIdToNodeMap[fileId] = ino;
+ auto& metaPair = mNodeToMetaMap[ino];
+ metaPair.meta = std::move(meta);
+ metaPair.fileId = fileId;
+ return &metaPair;
+ }
+
+ android::dataloader::RawMetadata* getMeta(android::dataloader::Inode ino) {
+ auto it = mNodeToMetaMap.find(ino);
+ if (it != mNodeToMetaMap.end()) {
+ return &it->second.meta;
+ }
+
+ auto metaPair = updateMapsForFile(ino);
+ if (!metaPair) {
+ return nullptr;
+ }
+
+ return &metaPair->meta;
+ }
+
+ FileId* getFileId(android::dataloader::Inode ino) {
+ auto it = mNodeToMetaMap.find(ino);
+ if (it != mNodeToMetaMap.end()) {
+ return &it->second.fileId;
+ }
+
+ auto* metaPair = updateMapsForFile(ino);
+ if (!metaPair) {
+ return nullptr;
+ }
+
+ return &metaPair->fileId;
+ }
+
+ void traceOrLogRead(const TracedRead& read, bool trace, bool log) {
+ if (!read.count) {
+ return;
+ }
+ if (trace) {
+ auto* meta = getMeta(read.fileIno);
+ auto str = android::base::StringPrintf(
+ "page_read: index=%lld count=%lld meta=%.*s",
+ static_cast<long long>(read.firstBlockIdx),
+ static_cast<long long>(read.count),
+ meta ? int(meta->size()) : 0, meta ? meta->data() : "");
+ ATRACE_BEGIN(str.c_str());
+ ATRACE_END();
+ }
+ if (log) {
+ mReadLog.reserve(ReadLogBufferSize);
+
+ auto fileId = getFileId(read.fileIno);
+ android::base::StringAppendF(
+ &mReadLog, "%lld:%lld:%lld:%lld\n",
+ static_cast<long long>(read.timestampUs),
+ static_cast<long long>(fileId ? *fileId : -1),
+ static_cast<long long>(read.firstBlockIdx),
+ static_cast<long long>(read.count));
+
+ if (mReadLog.size() >= mReadLog.capacity() - ReadLogMaxEntrySize) {
+ flushReadLog();
+ }
+ }
+ }
+
+ void flushReadLog() {
+ if (mReadLog.empty() || mReadLogFd == -1) {
+ return;
+ }
+
+ android::base::WriteStringToFd(mReadLog, mReadLogFd);
+ mReadLog.clear();
+ }
+
+private:
+ android::dataloader::FilesystemConnectorPtr mIfs = nullptr;
+ android::dataloader::StatusListenerPtr mStatusListener = nullptr;
+ android::base::unique_fd mInFd;
+ android::base::unique_fd mOutFd;
+ android::base::unique_fd mEventFd;
+ android::base::unique_fd mReadLogFd;
+ std::string mReadLog;
+ std::thread mReceiverThread;
+ std::mutex mMapsMutex;
+ std::unordered_map<android::dataloader::Inode, MetaPair> mNodeToMetaMap GUARDED_BY(mMapsMutex);
+ std::unordered_map<FileId, android::dataloader::Inode> mIdToNodeMap GUARDED_BY(mMapsMutex);
+ /** Tracks which files have been requested */
+ std::unordered_set<FileId> mRequestedFiles;
+ std::atomic<bool> mStopReceiving = false;
+};
+
+} // namespace
+
+int JNI_OnLoad(JavaVM* jvm, void* /* reserved */) {
+ android::dataloader::DataLoader::initialize(
+ [](auto) { return std::make_unique<AdbDataLoader>(); });
+ return JNI_VERSION_1_6;
+}
diff --git a/apex/sdkext/framework/tests/AndroidManifest.xml b/packages/Incremental/NativeAdbDataLoader/res/values/strings.xml
index 831f1328c006..9921ae69a7f5 100644
--- a/apex/sdkext/framework/tests/AndroidManifest.xml
+++ b/packages/Incremental/NativeAdbDataLoader/res/values/strings.xml
@@ -13,15 +13,7 @@
See the License for the specific language governing permissions and
limitations under the License.
-->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.sdkext.tests">
-
- <application>
- <uses-library android:name="android.test.runner" />
- </application>
-
- <instrumentation android:name="android.test.InstrumentationTestRunner"
- android:targetPackage="com.android.sdkext.tests" />
-
-</manifest>
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+ <!-- Name of the Data Loader Service. [CHAR LIMIT=40] -->
+ <string name="app_name">Native Adb Data Loader Service</string>
+</resources>
diff --git a/packages/Incremental/NativeAdbDataLoader/src/com/android/incremental/nativeadb/NativeAdbDataLoaderService.java b/packages/Incremental/NativeAdbDataLoader/src/com/android/incremental/nativeadb/NativeAdbDataLoaderService.java
new file mode 100644
index 000000000000..bd5b79594c19
--- /dev/null
+++ b/packages/Incremental/NativeAdbDataLoader/src/com/android/incremental/nativeadb/NativeAdbDataLoaderService.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2019 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 com.android.incremental.nativeadb;
+
+import android.service.dataloader.DataLoaderService;
+
+/** This code is used for testing only. */
+public class NativeAdbDataLoaderService extends DataLoaderService {
+ public static final String TAG = "NativeAdbDataLoaderService";
+ static {
+ System.loadLibrary("nativeadbdataloaderservice_jni");
+ }
+
+ @Override
+ public DataLoader onCreateDataLoader() {
+ return null;
+ }
+}
diff --git a/packages/SettingsLib/res/values/arrays.xml b/packages/SettingsLib/res/values/arrays.xml
index 39c55fd1925c..9b4a6d68a34a 100644
--- a/packages/SettingsLib/res/values/arrays.xml
+++ b/packages/SettingsLib/res/values/arrays.xml
@@ -140,8 +140,6 @@
<item><xliff:g id="qualcomm">Qualcomm®</xliff:g> <xliff:g id="aptx">aptX™</xliff:g> audio</item>
<item><xliff:g id="qualcomm">Qualcomm®</xliff:g> <xliff:g id="aptx_hd">aptX™ HD</xliff:g> audio</item>
<item>LDAC</item>
- <item>Enable Optional Codecs</item>
- <item>Disable Optional Codecs</item>
</string-array>
<!-- Values for Bluetooth Audio Codec selection preference. -->
@@ -152,8 +150,6 @@
<item>2</item>
<item>3</item>
<item>4</item>
- <item>5</item>
- <item>6</item>
</string-array>
<!-- Summaries for Bluetooth Audio Codec selection preference. [CHAR LIMIT=50]-->
@@ -164,8 +160,6 @@
<item><xliff:g id="qualcomm">Qualcomm®</xliff:g> <xliff:g id="aptx">aptX™</xliff:g> audio</item>
<item><xliff:g id="qualcomm">Qualcomm®</xliff:g> <xliff:g id="aptx_hd">aptX™ HD</xliff:g> audio</item>
<item>LDAC</item>
- <item>Enable Optional Codecs</item>
- <item>Disable Optional Codecs</item>
</string-array>
<!-- Titles for Bluetooth Audio Codec Sample Rate selection preference. [CHAR LIMIT=50] -->
diff --git a/packages/SettingsLib/res/values/strings.xml b/packages/SettingsLib/res/values/strings.xml
index 80240affc1c1..f40105d6dc9e 100644
--- a/packages/SettingsLib/res/values/strings.xml
+++ b/packages/SettingsLib/res/values/strings.xml
@@ -40,6 +40,8 @@
<string name="wifi_security_short_sae" translatable="false">WPA3</string>
<!-- Do not translate. Concise terminology for wifi with WPA2/WPA3 transition security -->
<string name="wifi_security_short_psk_sae" translatable="false">WPA2/WPA3</string>
+ <!-- Do not translate. Concise terminology for Wi-Fi with None/OWE transition mode security -->
+ <string name="wifi_security_short_none_owe" translatable="false">None/OWE</string>
<!-- Do not translate. Concise terminology for wifi with OWE security -->
<string name="wifi_security_short_owe" translatable="false">OWE</string>
<!-- Do not translate. Concise terminology for wifi with 802.1x EAP Suite-B-192 security -->
@@ -70,6 +72,8 @@
<string name="wifi_security_sae" translatable="false">WPA3-Personal</string>
<!-- Do not translate. Terminology for wifi with WPA2/WPA3 Transition mode security -->
<string name="wifi_security_psk_sae" translatable="false">WPA2/WPA3-Personal</string>
+ <!-- Do not translate. Terminology for Wi-Fi with None/OWE transition mode security -->
+ <string name="wifi_security_none_owe" translatable="false">None/Enhanced Open</string>
<!-- Do not translate. Terminology for wifi with OWE security -->
<string name="wifi_security_owe" translatable="false">Enhanced Open</string>
<!-- Do not translate. Concise terminology for wifi with 802.1x EAP Suite-B-192 security -->
@@ -594,6 +598,8 @@
<string name="bluetooth_show_devices_without_names">Show Bluetooth devices without names</string>
<!-- Setting Checkbox title for disabling Bluetooth absolute volume -->
<string name="bluetooth_disable_absolute_volume">Disable absolute volume</string>
+ <!-- Setting Checkbox title for enabling Bluetooth Gabeldorsche. [CHAR LIMIT=40] -->
+ <string name="bluetooth_enable_gabeldorsche">Enable Gabeldorsche</string>
<!-- UI debug setting: Select Bluetooth AVRCP Version -->
<string name="bluetooth_select_avrcp_version_string">Bluetooth AVRCP Version</string>
@@ -692,6 +698,8 @@
<string name="bluetooth_show_devices_without_names_summary">Bluetooth devices without names (MAC addresses only) will be displayed</string>
<!-- Summary of checkbox for disabling Bluetooth absolute volume -->
<string name="bluetooth_disable_absolute_volume_summary">Disables the Bluetooth absolute volume feature in case of volume issues with remote devices such as unacceptably loud volume or lack of control.</string>
+ <!-- Summary of checkbox for enabling Bluetooth Gabeldorche features [CHAR LIMIT=none] -->
+ <string name="bluetooth_enable_gabeldorsche_summary">Enables the Bluetooth Gabeldorche feature stack.</string>
<!-- Title of checkbox setting that enables the terminal app. [CHAR LIMIT=32] -->
<string name="enable_terminal_title">Local terminal</string>
@@ -957,7 +965,7 @@
<!-- Title for the accessibility preference to configure display color space correction. [CHAR LIMIT=NONE] -->
<string name="accessibility_display_daltonizer_preference_title">Color correction</string>
<!-- Subtitle for the accessibility preference to configure display color space correction. [CHAR LIMIT=NONE] -->
- <string name="accessibility_display_daltonizer_preference_subtitle">This feature is experimental and may affect performance.</string>
+ <string name="accessibility_display_daltonizer_preference_subtitle">Color correction helps people with color blindness to see more accurate colors</string>
<!-- Summary shown for color space correction preference when its value is overridden by another preference [CHAR LIMIT=35] -->
<string name="daltonizer_type_overridden">Overridden by <xliff:g id="title" example="Simulate color space">%1$s</xliff:g></string>
diff --git a/packages/SettingsLib/src/com/android/settingslib/Utils.java b/packages/SettingsLib/src/com/android/settingslib/Utils.java
index 14f233d958e6..2c001b033311 100644
--- a/packages/SettingsLib/src/com/android/settingslib/Utils.java
+++ b/packages/SettingsLib/src/com/android/settingslib/Utils.java
@@ -1,7 +1,5 @@
package com.android.settingslib;
-import static android.telephony.ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN;
-
import android.annotation.ColorInt;
import android.content.Context;
import android.content.Intent;
@@ -25,6 +23,8 @@ import android.os.UserHandle;
import android.os.UserManager;
import android.print.PrintManager;
import android.provider.Settings;
+import android.telephony.AccessNetworkConstants;
+import android.telephony.NetworkRegistrationInfo;
import android.telephony.ServiceState;
import com.android.internal.annotations.VisibleForTesting;
@@ -412,15 +412,30 @@ public class Utils {
// service" or "emergency calls only" text that indicates that voice
// is not available. Note that we ignore the IWLAN service state
// because that state indicates the use of VoWIFI and not cell service
- int state = serviceState.getState();
- int dataState = serviceState.getDataRegState();
+ final int state = serviceState.getState();
+ final int dataState = serviceState.getDataRegState();
+
if (state == ServiceState.STATE_OUT_OF_SERVICE
|| state == ServiceState.STATE_EMERGENCY_ONLY) {
- if (dataState == ServiceState.STATE_IN_SERVICE
- && serviceState.getDataNetworkType() != RIL_RADIO_TECHNOLOGY_IWLAN) {
+ if (dataState == ServiceState.STATE_IN_SERVICE && isNotInIwlan(serviceState)) {
return ServiceState.STATE_IN_SERVICE;
}
}
return state;
}
+
+ private static boolean isNotInIwlan(ServiceState serviceState) {
+ final NetworkRegistrationInfo networkRegWlan = serviceState.getNetworkRegistrationInfo(
+ NetworkRegistrationInfo.DOMAIN_PS,
+ AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
+ if (networkRegWlan == null) {
+ return true;
+ }
+
+ final boolean isInIwlan = (networkRegWlan.getRegistrationState()
+ == NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
+ || (networkRegWlan.getRegistrationState()
+ == NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING);
+ return !isInIwlan;
+ }
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/A2dpProfile.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/A2dpProfile.java
index 96aee512c090..a2bd210b67a6 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/A2dpProfile.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/A2dpProfile.java
@@ -155,8 +155,8 @@ public class A2dpProfile implements LocalBluetoothProfile {
public boolean disconnect(BluetoothDevice device) {
if (mService == null) return false;
// Downgrade priority as user is disconnecting the headset.
- if (mService.getPriority(device) > BluetoothProfile.PRIORITY_ON){
- mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
+ if (mService.getConnectionPolicy(device) > BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
}
return mService.disconnect(device);
}
@@ -179,23 +179,29 @@ public class A2dpProfile implements LocalBluetoothProfile {
}
public boolean isPreferred(BluetoothDevice device) {
- if (mService == null) return false;
- return mService.getPriority(device) > BluetoothProfile.PRIORITY_OFF;
+ if (mService == null) {
+ return false;
+ }
+ return mService.getConnectionPolicy(device) > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
}
public int getPreferred(BluetoothDevice device) {
- if (mService == null) return BluetoothProfile.PRIORITY_OFF;
- return mService.getPriority(device);
+ if (mService == null) {
+ return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+ }
+ return mService.getConnectionPolicy(device);
}
public void setPreferred(BluetoothDevice device, boolean preferred) {
- if (mService == null) return;
+ if (mService == null) {
+ return;
+ }
if (preferred) {
- if (mService.getPriority(device) < BluetoothProfile.PRIORITY_ON) {
- mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
+ if (mService.getConnectionPolicy(device) < BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
}
} else {
- mService.setPriority(device, BluetoothProfile.PRIORITY_OFF);
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
}
}
boolean isA2dpPlaying() {
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/A2dpSinkProfile.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/A2dpSinkProfile.java
index 55765dd40d36..bc03c343a909 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/A2dpSinkProfile.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/A2dpSinkProfile.java
@@ -124,8 +124,8 @@ final class A2dpSinkProfile implements LocalBluetoothProfile {
return false;
}
// Downgrade priority as user is disconnecting the headset.
- if (mService.getPriority(device) > BluetoothProfile.PRIORITY_ON) {
- mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
+ if (mService.getConnectionPolicy(device) > BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
}
return mService.disconnect(device);
}
@@ -141,14 +141,14 @@ final class A2dpSinkProfile implements LocalBluetoothProfile {
if (mService == null) {
return false;
}
- return mService.getPriority(device) > BluetoothProfile.PRIORITY_OFF;
+ return mService.getConnectionPolicy(device) > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
}
public int getPreferred(BluetoothDevice device) {
if (mService == null) {
- return BluetoothProfile.PRIORITY_OFF;
+ return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
}
- return mService.getPriority(device);
+ return mService.getConnectionPolicy(device);
}
public void setPreferred(BluetoothDevice device, boolean preferred) {
@@ -156,21 +156,21 @@ final class A2dpSinkProfile implements LocalBluetoothProfile {
return;
}
if (preferred) {
- if (mService.getPriority(device) < BluetoothProfile.PRIORITY_ON) {
- mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
+ if (mService.getConnectionPolicy(device) < BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
}
} else {
- mService.setPriority(device, BluetoothProfile.PRIORITY_OFF);
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
}
}
- boolean isA2dpPlaying() {
+ boolean isAudioPlaying() {
if (mService == null) {
return false;
}
List<BluetoothDevice> srcs = mService.getConnectedDevices();
if (!srcs.isEmpty()) {
- if (mService.isA2dpPlaying(srcs.get(0))) {
+ if (mService.isAudioPlaying(srcs.get(0))) {
return true;
}
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothUtils.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothUtils.java
index e660e43a60da..d3f9cd4f9034 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothUtils.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothUtils.java
@@ -116,7 +116,7 @@ public class BluetoothUtils {
}
return new Pair<>(
getBluetoothDrawable(context,
- com.android.internal.R.drawable.ic_settings_bluetooth),
+ com.android.internal.R.drawable.ic_settings_bluetooth).mutate(),
context.getString(R.string.bluetooth_talkback_bluetooth));
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java
index 066659677add..747ceb190a5d 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java
@@ -721,12 +721,8 @@ public class CachedBluetoothDevice implements Comparable<CachedBluetoothDevice>
refresh();
- if (bondState == BluetoothDevice.BOND_BONDED) {
- if (mDevice.isBluetoothDock()) {
- onBondingDockConnect();
- } else if (mDevice.isBondingInitiatedLocally()) {
- connect(false);
- }
+ if (bondState == BluetoothDevice.BOND_BONDED && mDevice.isBondingInitiatedLocally()) {
+ connect(false);
}
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/HeadsetProfile.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/HeadsetProfile.java
index 9f7b7181b19f..560cb3b9b5b4 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/HeadsetProfile.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/HeadsetProfile.java
@@ -120,8 +120,8 @@ public class HeadsetProfile implements LocalBluetoothProfile {
return false;
}
// Downgrade priority as user is disconnecting the headset.
- if (mService.getPriority(device) > BluetoothProfile.PRIORITY_ON) {
- mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
+ if (mService.getConnectionPolicy(device) > BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
}
return mService.disconnect(device);
}
@@ -165,14 +165,14 @@ public class HeadsetProfile implements LocalBluetoothProfile {
if (mService == null) {
return false;
}
- return mService.getPriority(device) > BluetoothProfile.PRIORITY_OFF;
+ return mService.getConnectionPolicy(device) > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
}
public int getPreferred(BluetoothDevice device) {
if (mService == null) {
- return BluetoothProfile.PRIORITY_OFF;
+ return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
}
- return mService.getPriority(device);
+ return mService.getConnectionPolicy(device);
}
public void setPreferred(BluetoothDevice device, boolean preferred) {
@@ -180,11 +180,11 @@ public class HeadsetProfile implements LocalBluetoothProfile {
return;
}
if (preferred) {
- if (mService.getPriority(device) < BluetoothProfile.PRIORITY_ON) {
- mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
+ if (mService.getConnectionPolicy(device) < BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
}
} else {
- mService.setPriority(device, BluetoothProfile.PRIORITY_OFF);
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
}
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/HearingAidProfile.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/HearingAidProfile.java
index ebaeb742b198..58655a2b930a 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/HearingAidProfile.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/HearingAidProfile.java
@@ -153,8 +153,8 @@ public class HearingAidProfile implements LocalBluetoothProfile {
public boolean disconnect(BluetoothDevice device) {
if (mService == null) return false;
// Downgrade priority as user is disconnecting the hearing aid.
- if (mService.getPriority(device) > BluetoothProfile.PRIORITY_ON){
- mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
+ if (mService.getConnectionPolicy(device) > BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
}
return mService.disconnect(device);
}
@@ -177,23 +177,29 @@ public class HearingAidProfile implements LocalBluetoothProfile {
}
public boolean isPreferred(BluetoothDevice device) {
- if (mService == null) return false;
- return mService.getPriority(device) > BluetoothProfile.PRIORITY_OFF;
+ if (mService == null) {
+ return false;
+ }
+ return mService.getConnectionPolicy(device) > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
}
public int getPreferred(BluetoothDevice device) {
- if (mService == null) return BluetoothProfile.PRIORITY_OFF;
- return mService.getPriority(device);
+ if (mService == null) {
+ return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+ }
+ return mService.getConnectionPolicy(device);
}
public void setPreferred(BluetoothDevice device, boolean preferred) {
- if (mService == null) return;
+ if (mService == null) {
+ return;
+ }
if (preferred) {
- if (mService.getPriority(device) < BluetoothProfile.PRIORITY_ON) {
- mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
+ if (mService.getConnectionPolicy(device) < BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
}
} else {
- mService.setPriority(device, BluetoothProfile.PRIORITY_OFF);
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
}
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/HfpClientProfile.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/HfpClientProfile.java
index 860b77d1ebcd..a372e23654e0 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/HfpClientProfile.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/HfpClientProfile.java
@@ -135,8 +135,8 @@ final class HfpClientProfile implements LocalBluetoothProfile {
return false;
}
// Downgrade priority as user is disconnecting the headset.
- if (mService.getPriority(device) > BluetoothProfile.PRIORITY_ON){
- mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
+ if (mService.getConnectionPolicy(device) > BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
}
return mService.disconnect(device);
}
@@ -154,15 +154,15 @@ final class HfpClientProfile implements LocalBluetoothProfile {
if (mService == null) {
return false;
}
- return mService.getPriority(device) > BluetoothProfile.PRIORITY_OFF;
+ return mService.getConnectionPolicy(device) > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
}
@Override
public int getPreferred(BluetoothDevice device) {
if (mService == null) {
- return BluetoothProfile.PRIORITY_OFF;
+ return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
}
- return mService.getPriority(device);
+ return mService.getConnectionPolicy(device);
}
@Override
@@ -171,11 +171,11 @@ final class HfpClientProfile implements LocalBluetoothProfile {
return;
}
if (preferred) {
- if (mService.getPriority(device) < BluetoothProfile.PRIORITY_ON) {
- mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
+ if (mService.getConnectionPolicy(device) < BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
}
} else {
- mService.setPriority(device, BluetoothProfile.PRIORITY_OFF);
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
}
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/HidProfile.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/HidProfile.java
index 6d874ab2be9b..975a1e67af5b 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/HidProfile.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/HidProfile.java
@@ -116,23 +116,27 @@ public class HidProfile implements LocalBluetoothProfile {
}
public boolean isPreferred(BluetoothDevice device) {
- if (mService == null) return false;
- return mService.getPriority(device) != BluetoothProfile.PRIORITY_OFF;
+ if (mService == null) {
+ return false;
+ }
+ return mService.getConnectionPolicy(device) != BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
}
public int getPreferred(BluetoothDevice device) {
- if (mService == null) return BluetoothProfile.PRIORITY_OFF;
- return mService.getPriority(device);
+ if (mService == null) {
+ return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+ }
+ return mService.getConnectionPolicy(device);
}
public void setPreferred(BluetoothDevice device, boolean preferred) {
if (mService == null) return;
if (preferred) {
- if (mService.getPriority(device) < BluetoothProfile.PRIORITY_ON) {
- mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
+ if (mService.getConnectionPolicy(device) < BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
}
} else {
- mService.setPriority(device, BluetoothProfile.PRIORITY_OFF);
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
}
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/LocalBluetoothAdapter.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/LocalBluetoothAdapter.java
index 8f40ab47fe1b..80b03a43b055 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/LocalBluetoothAdapter.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/LocalBluetoothAdapter.java
@@ -175,7 +175,7 @@ public class LocalBluetoothAdapter {
return;
}
A2dpSinkProfile a2dpSink = mProfileManager.getA2dpSinkProfile();
- if ((a2dpSink != null) && (a2dpSink.isA2dpPlaying())){
+ if ((a2dpSink != null) && (a2dpSink.isAudioPlaying())) {
return;
}
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/MapClientProfile.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/MapClientProfile.java
index d4dda329fa63..95139a1bfab9 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/MapClientProfile.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/MapClientProfile.java
@@ -123,8 +123,8 @@ public final class MapClientProfile implements LocalBluetoothProfile {
return false;
}
// Downgrade priority as user is disconnecting.
- if (mService.getPriority(device) > BluetoothProfile.PRIORITY_ON) {
- mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
+ if (mService.getConnectionPolicy(device) > BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
}
return mService.disconnect(device);
}
@@ -140,14 +140,14 @@ public final class MapClientProfile implements LocalBluetoothProfile {
if (mService == null) {
return false;
}
- return mService.getPriority(device) > BluetoothProfile.PRIORITY_OFF;
+ return mService.getConnectionPolicy(device) > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
}
public int getPreferred(BluetoothDevice device) {
if (mService == null) {
- return BluetoothProfile.PRIORITY_OFF;
+ return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
}
- return mService.getPriority(device);
+ return mService.getConnectionPolicy(device);
}
public void setPreferred(BluetoothDevice device, boolean preferred) {
@@ -155,11 +155,11 @@ public final class MapClientProfile implements LocalBluetoothProfile {
return;
}
if (preferred) {
- if (mService.getPriority(device) < BluetoothProfile.PRIORITY_ON) {
- mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
+ if (mService.getConnectionPolicy(device) < BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
}
} else {
- mService.setPriority(device, BluetoothProfile.PRIORITY_OFF);
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
}
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/MapProfile.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/MapProfile.java
index b2a9a6a28231..31a0eea56b42 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/MapProfile.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/MapProfile.java
@@ -119,8 +119,8 @@ public class MapProfile implements LocalBluetoothProfile {
if (mService == null) {
return false;
}
- if (mService.getPriority(device) > BluetoothProfile.PRIORITY_ON) {
- mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
+ if (mService.getConnectionPolicy(device) > BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
}
return mService.disconnect(device);
}
@@ -136,14 +136,14 @@ public class MapProfile implements LocalBluetoothProfile {
if (mService == null) {
return false;
}
- return mService.getPriority(device) > BluetoothProfile.PRIORITY_OFF;
+ return mService.getConnectionPolicy(device) > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
}
public int getPreferred(BluetoothDevice device) {
if (mService == null) {
- return BluetoothProfile.PRIORITY_OFF;
+ return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
}
- return mService.getPriority(device);
+ return mService.getConnectionPolicy(device);
}
public void setPreferred(BluetoothDevice device, boolean preferred) {
@@ -151,11 +151,11 @@ public class MapProfile implements LocalBluetoothProfile {
return;
}
if (preferred) {
- if (mService.getPriority(device) < BluetoothProfile.PRIORITY_ON) {
- mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
+ if (mService.getConnectionPolicy(device) < BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
}
} else {
- mService.setPriority(device, BluetoothProfile.PRIORITY_OFF);
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
}
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/OWNERS b/packages/SettingsLib/src/com/android/settingslib/bluetooth/OWNERS
index 7162121330ef..387bae130374 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/OWNERS
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/OWNERS
@@ -1,8 +1,7 @@
# Default reviewers for this and subdirectories.
-asapperstein@google.com
-asargent@google.com
-eisenbach@google.com
-jackqdyulei@google.com
siyuanh@google.com
+hughchen@google.com
+timhypeng@google.com
+robertluo@google.com
-# Emergency approvers in case the above are not available \ No newline at end of file
+# Emergency approvers in case the above are not available
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/OppProfile.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/OppProfile.java
index e1e5dbe29a1a..8e3f3edcef10 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/OppProfile.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/OppProfile.java
@@ -57,7 +57,7 @@ final class OppProfile implements LocalBluetoothProfile {
}
public int getPreferred(BluetoothDevice device) {
- return BluetoothProfile.PRIORITY_OFF; // Settings app doesn't handle OPP
+ return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; // Settings app doesn't handle OPP
}
public void setPreferred(BluetoothDevice device, boolean preferred) {
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/PbapClientProfile.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/PbapClientProfile.java
index a2da4fb30e39..4ea0df621bea 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/PbapClientProfile.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/PbapClientProfile.java
@@ -151,14 +151,14 @@ public final class PbapClientProfile implements LocalBluetoothProfile {
if (mService == null) {
return false;
}
- return mService.getPriority(device) > BluetoothProfile.PRIORITY_OFF;
+ return mService.getConnectionPolicy(device) > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
}
public int getPreferred(BluetoothDevice device) {
if (mService == null) {
- return BluetoothProfile.PRIORITY_OFF;
+ return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
}
- return mService.getPriority(device);
+ return mService.getConnectionPolicy(device);
}
public void setPreferred(BluetoothDevice device, boolean preferred) {
@@ -166,11 +166,11 @@ public final class PbapClientProfile implements LocalBluetoothProfile {
return;
}
if (preferred) {
- if (mService.getPriority(device) < BluetoothProfile.PRIORITY_ON) {
- mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
+ if (mService.getConnectionPolicy(device) < BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
}
} else {
- mService.setPriority(device, BluetoothProfile.PRIORITY_OFF);
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
}
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/PbapServerProfile.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/PbapServerProfile.java
index d91226e02878..3f920a8cf1dd 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/PbapServerProfile.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/PbapServerProfile.java
@@ -16,6 +16,7 @@
package com.android.settingslib.bluetooth;
+import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothPbap;
@@ -52,14 +53,16 @@ public class PbapServerProfile implements LocalBluetoothProfile {
// These callbacks run on the main thread.
private final class PbapServiceListener
- implements BluetoothPbap.ServiceListener {
+ implements BluetoothProfile.ServiceListener {
- public void onServiceConnected(BluetoothPbap proxy) {
+ @Override
+ public void onServiceConnected(int profile, BluetoothProfile proxy) {
mService = (BluetoothPbap) proxy;
mIsProfileReady=true;
}
- public void onServiceDisconnected() {
+ @Override
+ public void onServiceDisconnected(int profile) {
mIsProfileReady=false;
}
}
@@ -74,7 +77,8 @@ public class PbapServerProfile implements LocalBluetoothProfile {
}
PbapServerProfile(Context context) {
- BluetoothPbap pbap = new BluetoothPbap(context, new PbapServiceListener());
+ BluetoothAdapter.getDefaultAdapter().getProfileProxy(context, new PbapServiceListener(),
+ BluetoothProfile.PBAP);
}
public boolean accessProfileEnabled() {
@@ -97,13 +101,8 @@ public class PbapServerProfile implements LocalBluetoothProfile {
}
public int getConnectionStatus(BluetoothDevice device) {
- if (mService == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
- }
- if (mService.isConnected(device))
- return BluetoothProfile.STATE_CONNECTED;
- else
- return BluetoothProfile.STATE_DISCONNECTED;
+ if (mService == null) return BluetoothProfile.STATE_DISCONNECTED;
+ return mService.getConnectionState(device);
}
public boolean isPreferred(BluetoothDevice device) {
@@ -142,7 +141,8 @@ public class PbapServerProfile implements LocalBluetoothProfile {
Log.d(TAG, "finalize()");
if (mService != null) {
try {
- mService.close();
+ BluetoothAdapter.getDefaultAdapter().closeProfileProxy(BluetoothProfile.PBAP,
+ mService);
mService = null;
}catch (Throwable t) {
Log.w(TAG, "Error cleaning up PBAP proxy", t);
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/SapProfile.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/SapProfile.java
index 9b733f2e0e50..0ca4d6195a32 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/SapProfile.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/SapProfile.java
@@ -119,8 +119,8 @@ final class SapProfile implements LocalBluetoothProfile {
if (mService == null) {
return false;
}
- if (mService.getPriority(device) > BluetoothProfile.PRIORITY_ON) {
- mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
+ if (mService.getConnectionPolicy(device) > BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
}
return mService.disconnect(device);
}
@@ -136,14 +136,14 @@ final class SapProfile implements LocalBluetoothProfile {
if (mService == null) {
return false;
}
- return mService.getPriority(device) > BluetoothProfile.PRIORITY_OFF;
+ return mService.getConnectionPolicy(device) > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
}
public int getPreferred(BluetoothDevice device) {
if (mService == null) {
- return BluetoothProfile.PRIORITY_OFF;
+ return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
}
- return mService.getPriority(device);
+ return mService.getConnectionPolicy(device);
}
public void setPreferred(BluetoothDevice device, boolean preferred) {
@@ -151,11 +151,11 @@ final class SapProfile implements LocalBluetoothProfile {
return;
}
if (preferred) {
- if (mService.getPriority(device) < BluetoothProfile.PRIORITY_ON) {
- mService.setPriority(device, BluetoothProfile.PRIORITY_ON);
+ if (mService.getConnectionPolicy(device) < BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
}
} else {
- mService.setPriority(device, BluetoothProfile.PRIORITY_OFF);
+ mService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
}
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/core/instrumentation/MetricsFeatureProvider.java b/packages/SettingsLib/src/com/android/settingslib/core/instrumentation/MetricsFeatureProvider.java
index 5cf44e1f6725..a82231a597c3 100644
--- a/packages/SettingsLib/src/com/android/settingslib/core/instrumentation/MetricsFeatureProvider.java
+++ b/packages/SettingsLib/src/com/android/settingslib/core/instrumentation/MetricsFeatureProvider.java
@@ -23,6 +23,9 @@ import android.content.Intent;
import android.text.TextUtils;
import android.util.Pair;
+import androidx.annotation.NonNull;
+import androidx.preference.Preference;
+
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import java.util.ArrayList;
@@ -132,34 +135,44 @@ public class MetricsFeatureProvider {
return ((Instrumentable) object).getMetricsCategory();
}
- public void logDashboardStartIntent(Context context, Intent intent,
- int sourceMetricsCategory) {
+ /**
+ * Logs an event when the preference is clicked.
+ *
+ * @return true if the preference is loggable, otherwise false
+ */
+ public boolean logClickedPreference(@NonNull Preference preference, int sourceMetricsCategory) {
+ if (preference == null) {
+ return false;
+ }
+ return logSettingsTileClick(preference.getKey(), sourceMetricsCategory)
+ || logStartedIntent(preference.getIntent(), sourceMetricsCategory)
+ || logSettingsTileClick(preference.getFragment(), sourceMetricsCategory);
+ }
+
+ /**
+ * Logs an event when the intent is started.
+ *
+ * @return true if the intent is loggable, otherwise false
+ */
+ public boolean logStartedIntent(Intent intent, int sourceMetricsCategory) {
if (intent == null) {
- return;
+ return false;
}
final ComponentName cn = intent.getComponent();
- if (cn == null) {
- final String action = intent.getAction();
- if (TextUtils.isEmpty(action)) {
- // Not loggable
- return;
- }
- action(sourceMetricsCategory,
- MetricsEvent.ACTION_SETTINGS_TILE_CLICK,
- SettingsEnums.PAGE_UNKNOWN,
- action,
- 0);
- return;
- } else if (TextUtils.equals(cn.getPackageName(), context.getPackageName())) {
- // Going to a Setting internal page, skip click logging in favor of page's own
- // visibility logging.
- return;
+ return logSettingsTileClick(cn != null ? cn.flattenToString() : intent.getAction(),
+ sourceMetricsCategory);
+ }
+
+ private boolean logSettingsTileClick(String logKey, int sourceMetricsCategory) {
+ if (TextUtils.isEmpty(logKey)) {
+ // Not loggable
+ return false;
}
action(sourceMetricsCategory,
MetricsEvent.ACTION_SETTINGS_TILE_CLICK,
SettingsEnums.PAGE_UNKNOWN,
- cn.flattenToString(),
+ logKey,
0);
+ return true;
}
-
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/location/RecentLocationApps.java b/packages/SettingsLib/src/com/android/settingslib/location/RecentLocationApps.java
index 104cc8f9841c..d3315efa0656 100644
--- a/packages/SettingsLib/src/com/android/settingslib/location/RecentLocationApps.java
+++ b/packages/SettingsLib/src/com/android/settingslib/location/RecentLocationApps.java
@@ -235,7 +235,7 @@ public class RecentLocationApps {
public final CharSequence contentDescription;
public final long requestFinishTime;
- private Request(String packageName, UserHandle userHandle, Drawable icon,
+ public Request(String packageName, UserHandle userHandle, Drawable icon,
CharSequence label, boolean isHighBattery, CharSequence contentDescription,
long requestFinishTime) {
this.packageName = packageName;
diff --git a/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPoint.java b/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPoint.java
index 328bfb281992..b13c483fc2c2 100644
--- a/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPoint.java
+++ b/packages/SettingsLib/src/com/android/settingslib/wifi/AccessPoint.java
@@ -36,7 +36,6 @@ import android.net.ScoredNetwork;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.KeyMgmt;
-import android.net.wifi.WifiEnterpriseConfig;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiNetworkScoreCache;
@@ -181,9 +180,6 @@ public class AccessPoint implements Comparable<AccessPoint> {
static final String KEY_CONFIG = "key_config";
static final String KEY_FQDN = "key_fqdn";
static final String KEY_PROVIDER_FRIENDLY_NAME = "key_provider_friendly_name";
- static final String KEY_IS_CARRIER_AP = "key_is_carrier_ap";
- static final String KEY_CARRIER_AP_EAP_TYPE = "key_carrier_ap_eap_type";
- static final String KEY_CARRIER_NAME = "key_carrier_name";
static final String KEY_EAPTYPE = "eap_psktype";
static final String KEY_SUBSCRIPTION_EXPIRATION_TIME_IN_MILLIS =
"key_subscription_expiration_time_in_millis";
@@ -265,8 +261,6 @@ public class AccessPoint implements Comparable<AccessPoint> {
@PasspointConfigurationVersion private int mPasspointConfigurationVersion =
PasspointConfigurationVersion.INVALID;
- private boolean mIsCarrierAp = false;
-
private OsuProvider mOsuProvider;
private String mOsuStatus;
@@ -276,12 +270,6 @@ public class AccessPoint implements Comparable<AccessPoint> {
private boolean mIsPskSaeTransitionMode = false;
private boolean mIsOweTransitionMode = false;
- /**
- * The EAP type {@link WifiEnterpriseConfig.Eap} associated with this AP if it is a carrier AP.
- */
- private int mCarrierApEapType = WifiEnterpriseConfig.Eap.NONE;
- private String mCarrierName = null;
-
public AccessPoint(Context context, Bundle savedState) {
mContext = context;
@@ -330,15 +318,6 @@ public class AccessPoint implements Comparable<AccessPoint> {
if (savedState.containsKey(KEY_PROVIDER_FRIENDLY_NAME)) {
mProviderFriendlyName = savedState.getString(KEY_PROVIDER_FRIENDLY_NAME);
}
- if (savedState.containsKey(KEY_IS_CARRIER_AP)) {
- mIsCarrierAp = savedState.getBoolean(KEY_IS_CARRIER_AP);
- }
- if (savedState.containsKey(KEY_CARRIER_AP_EAP_TYPE)) {
- mCarrierApEapType = savedState.getInt(KEY_CARRIER_AP_EAP_TYPE);
- }
- if (savedState.containsKey(KEY_CARRIER_NAME)) {
- mCarrierName = savedState.getString(KEY_CARRIER_NAME);
- }
if (savedState.containsKey(KEY_SUBSCRIPTION_EXPIRATION_TIME_IN_MILLIS)) {
mSubscriptionExpirationTimeInMillis =
savedState.getLong(KEY_SUBSCRIPTION_EXPIRATION_TIME_IN_MILLIS);
@@ -966,10 +945,6 @@ public class AccessPoint implements Comparable<AccessPoint> {
mIsPskSaeTransitionMode = AccessPoint.isPskSaeTransitionMode(bestResult);
mIsOweTransitionMode = AccessPoint.isOweTransitionMode(bestResult);
-
- mIsCarrierAp = bestResult.isCarrierAp;
- mCarrierApEapType = bestResult.carrierApEapType;
- mCarrierName = bestResult.carrierName;
}
// Update the config SSID of a Passpoint network to that of the best RSSI
if (isPasspoint()) {
@@ -1004,6 +979,10 @@ public class AccessPoint implements Comparable<AccessPoint> {
return concise ? context.getString(R.string.wifi_security_short_psk_sae) :
context.getString(R.string.wifi_security_psk_sae);
}
+ if (mIsOweTransitionMode) {
+ return concise ? context.getString(R.string.wifi_security_short_none_owe) :
+ context.getString(R.string.wifi_security_none_owe);
+ }
switch(security) {
case SECURITY_EAP:
@@ -1090,18 +1069,6 @@ public class AccessPoint implements Comparable<AccessPoint> {
return null;
}
- public boolean isCarrierAp() {
- return mIsCarrierAp;
- }
-
- public int getCarrierApEapType() {
- return mCarrierApEapType;
- }
-
- public String getCarrierName() {
- return mCarrierName;
- }
-
public String getSavedNetworkSummary() {
WifiConfiguration config = mConfig;
if (config != null) {
@@ -1177,15 +1144,9 @@ public class AccessPoint implements Comparable<AccessPoint> {
summary.append(mContext.getString(R.string.tap_to_sign_up));
}
} else if (isActive()) {
- if (getDetailedState() == DetailedState.CONNECTED && mIsCarrierAp) {
- // This is the active connection on a carrier AP
- summary.append(String.format(mContext.getString(R.string.connected_via_carrier),
- mCarrierName));
- } else {
- summary.append(getSummary(mContext, /* ssid */ null, getDetailedState(),
- mInfo != null && mInfo.isEphemeral(),
- mInfo != null ? mInfo.getAppPackageName() : null));
- }
+ summary.append(getSummary(mContext, /* ssid */ null, getDetailedState(),
+ mInfo != null && mInfo.isEphemeral(),
+ mInfo != null ? mInfo.getAppPackageName() : null));
} else { // not active
if (mConfig != null && mConfig.hasNoInternetAccess()) {
int messageID = mConfig.getNetworkSelectionStatus().isNetworkPermanentlyDisabled()
@@ -1209,9 +1170,6 @@ public class AccessPoint implements Comparable<AccessPoint> {
summary.append(mContext.getString(R.string.wifi_disabled_generic));
break;
}
- } else if (mIsCarrierAp) {
- summary.append(String.format(mContext.getString(
- R.string.available_via_carrier), mCarrierName));
} else if (!isReachable()) { // Wifi out of range
summary.append(mContext.getString(R.string.wifi_not_in_range));
} else { // In range, not disabled.
@@ -1391,7 +1349,7 @@ public class AccessPoint implements Comparable<AccessPoint> {
mConfig = new WifiConfiguration();
mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
- if (security == SECURITY_NONE || !getWifiManager().isEasyConnectSupported()) {
+ if (security == SECURITY_NONE) {
mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
} else {
mConfig.allowedKeyManagement.set(KeyMgmt.OWE);
@@ -1423,9 +1381,6 @@ public class AccessPoint implements Comparable<AccessPoint> {
if (mProviderFriendlyName != null) {
savedState.putString(KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName);
}
- savedState.putBoolean(KEY_IS_CARRIER_AP, mIsCarrierAp);
- savedState.putInt(KEY_CARRIER_AP_EAP_TYPE, mCarrierApEapType);
- savedState.putString(KEY_CARRIER_NAME, mCarrierName);
savedState.putLong(KEY_SUBSCRIPTION_EXPIRATION_TIME_IN_MILLIS,
mSubscriptionExpirationTimeInMillis);
savedState.putInt(KEY_PASSPOINT_CONFIGURATION_VERSION, mPasspointConfigurationVersion);
diff --git a/packages/SettingsLib/src/com/android/settingslib/wifi/TestAccessPointBuilder.java b/packages/SettingsLib/src/com/android/settingslib/wifi/TestAccessPointBuilder.java
index 17a73acb9bda..4a4f0e66cfe8 100644
--- a/packages/SettingsLib/src/com/android/settingslib/wifi/TestAccessPointBuilder.java
+++ b/packages/SettingsLib/src/com/android/settingslib/wifi/TestAccessPointBuilder.java
@@ -56,8 +56,6 @@ public class TestAccessPointBuilder {
private int mSecurity = AccessPoint.SECURITY_NONE;
private WifiConfiguration mWifiConfig;
private WifiInfo mWifiInfo;
- private boolean mIsCarrierAp = false;
- private String mCarrierName = null;
Context mContext;
private ArrayList<ScanResult> mScanResults;
@@ -99,10 +97,6 @@ public class TestAccessPointBuilder {
}
bundle.putInt(AccessPoint.KEY_SECURITY, mSecurity);
bundle.putInt(AccessPoint.KEY_SPEED, mSpeed);
- bundle.putBoolean(AccessPoint.KEY_IS_CARRIER_AP, mIsCarrierAp);
- if (mCarrierName != null) {
- bundle.putString(AccessPoint.KEY_CARRIER_NAME, mCarrierName);
- }
AccessPoint ap = new AccessPoint(mContext, bundle);
ap.setRssi(mRssi);
@@ -241,16 +235,6 @@ public class TestAccessPointBuilder {
return this;
}
- public TestAccessPointBuilder setIsCarrierAp(boolean isCarrierAp) {
- mIsCarrierAp = isCarrierAp;
- return this;
- }
-
- public TestAccessPointBuilder setCarrierName(String carrierName) {
- mCarrierName = carrierName;
- return this;
- }
-
public TestAccessPointBuilder setScoredNetworkCache(
ArrayList<TimestampedScoredNetwork> scoredNetworkCache) {
mScoredNetworkCache = scoredNetworkCache;
diff --git a/packages/SettingsLib/src/com/android/settingslib/wifi/WifiEntryPreference.java b/packages/SettingsLib/src/com/android/settingslib/wifi/WifiEntryPreference.java
index 22f47f1c6585..440315ffe37b 100644
--- a/packages/SettingsLib/src/com/android/settingslib/wifi/WifiEntryPreference.java
+++ b/packages/SettingsLib/src/com/android/settingslib/wifi/WifiEntryPreference.java
@@ -152,6 +152,14 @@ public class WifiEntryPreference extends Preference implements WifiEntry.WifiEnt
// TODO(b/70983952): Fill this method in
}
+ /**
+ * Result of the sign-in request indecated by the WifiEntry.SIGNIN_STATUS constants
+ */
+ public void onSignInResult(int status) {
+ // TODO(b/70983952): Fill this method in
+ }
+
+
private void updateIcon(int level) {
if (level == -1) {
setIcon(null);
diff --git a/packages/SettingsLib/tests/integ/src/com/android/settingslib/wifi/AccessPointTest.java b/packages/SettingsLib/tests/integ/src/com/android/settingslib/wifi/AccessPointTest.java
index 325366ea6e40..61cbbd3eb0a4 100644
--- a/packages/SettingsLib/tests/integ/src/com/android/settingslib/wifi/AccessPointTest.java
+++ b/packages/SettingsLib/tests/integ/src/com/android/settingslib/wifi/AccessPointTest.java
@@ -28,6 +28,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
+import android.content.ContextWrapper;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
@@ -40,7 +41,6 @@ import android.net.WifiKey;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.KeyMgmt;
-import android.net.wifi.WifiEnterpriseConfig;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiNetworkScoreCache;
@@ -473,51 +473,6 @@ public class AccessPointTest {
}
@Test
- public void testSummaryString_showsAvaiableViaCarrier() {
- String carrierName = "Test Carrier";
- ScanResult result = new ScanResult();
- result.BSSID = "00:11:22:33:44:55";
- result.capabilities = "EAP";
- result.isCarrierAp = true;
- result.carrierApEapType = WifiEnterpriseConfig.Eap.SIM;
- result.carrierName = carrierName;
-
- AccessPoint ap = new AccessPoint(mContext, Collections.singletonList(result));
- assertThat(ap.getSummary()).isEqualTo(String.format(mContext.getString(
- R.string.available_via_carrier), carrierName));
- assertThat(ap.isCarrierAp()).isEqualTo(true);
- assertThat(ap.getCarrierApEapType()).isEqualTo(WifiEnterpriseConfig.Eap.SIM);
- assertThat(ap.getCarrierName()).isEqualTo(carrierName);
- }
-
- @Test
- public void testSummaryString_showsConnectedViaCarrier() {
- int networkId = 123;
- int rssi = -55;
- String carrierName = "Test Carrier";
- WifiConfiguration config = new WifiConfiguration();
- config.networkId = networkId;
- WifiInfo wifiInfo = new WifiInfo();
- wifiInfo.setNetworkId(networkId);
- wifiInfo.setRssi(rssi);
-
- NetworkInfo networkInfo =
- new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0 /* subtype */, "WIFI", "");
- networkInfo.setDetailedState(NetworkInfo.DetailedState.CONNECTED, "", "");
-
- AccessPoint ap = new TestAccessPointBuilder(mContext)
- .setNetworkInfo(networkInfo)
- .setNetworkId(networkId)
- .setRssi(rssi)
- .setWifiInfo(wifiInfo)
- .setIsCarrierAp(true)
- .setCarrierName(carrierName)
- .build();
- assertThat(ap.getSummary()).isEqualTo(String.format(mContext.getString(
- R.string.connected_via_carrier), carrierName));
- }
-
- @Test
public void testSummaryString_showsDisconnected() {
AccessPoint ap = createAccessPointWithScanResultCache();
ap.update(new WifiConfiguration());
@@ -580,31 +535,6 @@ public class AccessPointTest {
assertThat(ap.getSummary()).isEqualTo("Connected via Test App");
}
- @Test
- public void testSetScanResultWithCarrierInfo() {
- String ssid = "ssid";
- AccessPoint ap = new TestAccessPointBuilder(mContext).setSsid(ssid).build();
- assertThat(ap.isCarrierAp()).isEqualTo(false);
- assertThat(ap.getCarrierApEapType()).isEqualTo(WifiEnterpriseConfig.Eap.NONE);
- assertThat(ap.getCarrierName()).isEqualTo(null);
-
- int carrierApEapType = WifiEnterpriseConfig.Eap.SIM;
- String carrierName = "Test Carrier";
- ScanResult scanResult = new ScanResult();
- scanResult.SSID = ssid;
- scanResult.BSSID = "00:11:22:33:44:55";
- scanResult.capabilities = "";
- scanResult.isCarrierAp = true;
- scanResult.carrierApEapType = carrierApEapType;
- scanResult.carrierName = carrierName;
-
-
- ap.setScanResults(Collections.singletonList(scanResult));
- assertThat(ap.isCarrierAp()).isEqualTo(true);
- assertThat(ap.getCarrierApEapType()).isEqualTo(carrierApEapType);
- assertThat(ap.getCarrierName()).isEqualTo(carrierName);
- }
-
private ScoredNetwork buildScoredNetworkWithMockBadgeCurve() {
return buildScoredNetworkWithGivenBadgeCurve(mockBadgeCurve);
}
@@ -1435,8 +1365,15 @@ public class AccessPointTest {
*/
@Test
public void testOsuAccessPointSummary_showsProvisioningUpdates() {
- AccessPoint osuAccessPoint = new AccessPoint(mContext, createOsuProvider(),
+ OsuProvider provider = createOsuProvider();
+ Context spyContext = spy(new ContextWrapper(mContext));
+ AccessPoint osuAccessPoint = new AccessPoint(spyContext, provider,
mScanResults);
+ Map<OsuProvider, PasspointConfiguration> osuProviderConfigMap = new HashMap<>();
+ osuProviderConfigMap.put(provider, null);
+ when(spyContext.getSystemService(Context.WIFI_SERVICE)).thenReturn(mMockWifiManager);
+ when(mMockWifiManager.getMatchingPasspointConfigsForOsuProviders(
+ Collections.singleton(provider))).thenReturn(osuProviderConfigMap);
osuAccessPoint.setListener(mMockAccessPointListener);
@@ -1683,6 +1620,18 @@ public class AccessPointTest {
assertThat(pskSaeTransitionModeAp.matches(saeScanResult)).isFalse();
}
+ @Test
+ public void testGetSecurityString_oweTransitionMode_shouldReturnCorrectly() {
+ when(mMockContext.getSystemService(Context.WIFI_SERVICE)).thenReturn(mMockWifiManager);
+ when(mMockWifiManager.isEnhancedOpenSupported()).thenReturn(true);
+ AccessPoint oweTransitionModeAp = getOweTransitionModeAp();
+
+ assertThat(oweTransitionModeAp.getSecurityString(true /* concise */))
+ .isEqualTo(mContext.getString(R.string.wifi_security_short_none_owe));
+ assertThat(oweTransitionModeAp.getSecurityString(false /* concise */))
+ .isEqualTo(mContext.getString(R.string.wifi_security_none_owe));
+ }
+
private AccessPoint getPskSaeTransitionModeAp() {
ScanResult scanResult = createScanResult(AccessPoint.removeDoubleQuotes(TEST_SSID),
TEST_BSSID, DEFAULT_RSSI);
@@ -1692,4 +1641,30 @@ public class AccessPointTest {
.setScanResults(new ArrayList<ScanResult>(Arrays.asList(scanResult)))
.build();
}
+
+ private AccessPoint getOweTransitionModeAp() {
+ ScanResult scanResult = createScanResult(AccessPoint.removeDoubleQuotes(TEST_SSID),
+ TEST_BSSID, DEFAULT_RSSI);
+ scanResult.capabilities = "[OWE_TRANSITION]";
+ return new TestAccessPointBuilder(mContext)
+ .setScanResults(new ArrayList<ScanResult>(Arrays.asList(scanResult)))
+ .build();
+ }
+
+ @Test
+ public void testGenerateOpenNetworkConfig_oweNotSupported_shouldGetCorrectSecurity() {
+ when(mMockContext.getSystemService(Context.WIFI_SERVICE)).thenReturn(mMockWifiManager);
+ AccessPoint oweAccessPoint = new TestAccessPointBuilder(mMockContext)
+ .setSecurity(AccessPoint.SECURITY_OWE).build();
+ AccessPoint noneAccessPoint = new TestAccessPointBuilder(mMockContext)
+ .setSecurity(AccessPoint.SECURITY_NONE).build();
+
+ oweAccessPoint.generateOpenNetworkConfig();
+ noneAccessPoint.generateOpenNetworkConfig();
+
+ assertThat(oweAccessPoint.getConfig().allowedKeyManagement.get(KeyMgmt.NONE)).isFalse();
+ assertThat(oweAccessPoint.getConfig().allowedKeyManagement.get(KeyMgmt.OWE)).isTrue();
+ assertThat(noneAccessPoint.getConfig().allowedKeyManagement.get(KeyMgmt.NONE)).isTrue();
+ assertThat(noneAccessPoint.getConfig().allowedKeyManagement.get(KeyMgmt.OWE)).isFalse();
+ }
}
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/UtilsTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/UtilsTest.java
index fc69b1a657d4..f18ffe1ebdd4 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/UtilsTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/UtilsTest.java
@@ -34,6 +34,8 @@ import android.media.AudioManager;
import android.os.SystemProperties;
import android.os.UserHandle;
import android.provider.Settings;
+import android.telephony.AccessNetworkConstants;
+import android.telephony.NetworkRegistrationInfo;
import android.telephony.ServiceState;
import android.text.TextUtils;
@@ -69,6 +71,8 @@ public class UtilsTest {
private LocationManager mLocationManager;
@Mock
private ServiceState mServiceState;
+ @Mock
+ private NetworkRegistrationInfo mNetworkRegistrationInfo;
@Before
public void setUp() {
@@ -207,6 +211,7 @@ public class UtilsTest {
@Test
public void isInService_voiceInService_returnTrue() {
when(mServiceState.getState()).thenReturn(ServiceState.STATE_IN_SERVICE);
+
assertThat(Utils.isInService(mServiceState)).isTrue();
}
@@ -214,15 +219,23 @@ public class UtilsTest {
public void isInService_voiceOutOfServiceDataInService_returnTrue() {
when(mServiceState.getState()).thenReturn(ServiceState.STATE_OUT_OF_SERVICE);
when(mServiceState.getDataRegState()).thenReturn(ServiceState.STATE_IN_SERVICE);
+ when(mServiceState.getNetworkRegistrationInfo(NetworkRegistrationInfo.DOMAIN_PS,
+ AccessNetworkConstants.TRANSPORT_TYPE_WLAN)).thenReturn(mNetworkRegistrationInfo);
+ when(mNetworkRegistrationInfo.getRegistrationState()).thenReturn(
+ NetworkRegistrationInfo.REGISTRATION_STATE_UNKNOWN);
+
assertThat(Utils.isInService(mServiceState)).isTrue();
}
@Test
public void isInService_voiceOutOfServiceDataInServiceOnIwLan_returnFalse() {
when(mServiceState.getState()).thenReturn(ServiceState.STATE_OUT_OF_SERVICE);
- when(mServiceState.getDataNetworkType())
- .thenReturn(ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN);
+ when(mServiceState.getNetworkRegistrationInfo(NetworkRegistrationInfo.DOMAIN_PS,
+ AccessNetworkConstants.TRANSPORT_TYPE_WLAN)).thenReturn(mNetworkRegistrationInfo);
+ when(mNetworkRegistrationInfo.getRegistrationState()).thenReturn(
+ NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
when(mServiceState.getDataRegState()).thenReturn(ServiceState.STATE_IN_SERVICE);
+
assertThat(Utils.isInService(mServiceState)).isFalse();
}
@@ -230,12 +243,14 @@ public class UtilsTest {
public void isInService_voiceOutOfServiceDataOutOfService_returnFalse() {
when(mServiceState.getState()).thenReturn(ServiceState.STATE_OUT_OF_SERVICE);
when(mServiceState.getDataRegState()).thenReturn(ServiceState.STATE_OUT_OF_SERVICE);
+
assertThat(Utils.isInService(mServiceState)).isFalse();
}
@Test
public void isInService_ServiceStatePowerOff_returnFalse() {
when(mServiceState.getState()).thenReturn(ServiceState.STATE_POWER_OFF);
+
assertThat(Utils.isInService(mServiceState)).isFalse();
}
@@ -248,6 +263,7 @@ public class UtilsTest {
@Test
public void getCombinedServiceState_ServiceStatePowerOff_returnPowerOff() {
when(mServiceState.getState()).thenReturn(ServiceState.STATE_POWER_OFF);
+
assertThat(Utils.getCombinedServiceState(mServiceState)).isEqualTo(
ServiceState.STATE_POWER_OFF);
}
@@ -255,6 +271,7 @@ public class UtilsTest {
@Test
public void getCombinedServiceState_voiceInService_returnInService() {
when(mServiceState.getState()).thenReturn(ServiceState.STATE_IN_SERVICE);
+
assertThat(Utils.getCombinedServiceState(mServiceState)).isEqualTo(
ServiceState.STATE_IN_SERVICE);
}
@@ -263,14 +280,33 @@ public class UtilsTest {
public void getCombinedServiceState_voiceOutOfServiceDataInService_returnInService() {
when(mServiceState.getState()).thenReturn(ServiceState.STATE_OUT_OF_SERVICE);
when(mServiceState.getDataRegState()).thenReturn(ServiceState.STATE_IN_SERVICE);
+ when(mServiceState.getNetworkRegistrationInfo(NetworkRegistrationInfo.DOMAIN_PS,
+ AccessNetworkConstants.TRANSPORT_TYPE_WLAN)).thenReturn(mNetworkRegistrationInfo);
+ when(mNetworkRegistrationInfo.getRegistrationState()).thenReturn(
+ NetworkRegistrationInfo.REGISTRATION_STATE_UNKNOWN);
+
assertThat(Utils.getCombinedServiceState(mServiceState)).isEqualTo(
ServiceState.STATE_IN_SERVICE);
}
@Test
+ public void getCombinedServiceState_voiceOutOfServiceDataInServiceOnIwLan_returnOutOfService() {
+ when(mServiceState.getState()).thenReturn(ServiceState.STATE_OUT_OF_SERVICE);
+ when(mServiceState.getDataRegState()).thenReturn(ServiceState.STATE_IN_SERVICE);
+ when(mServiceState.getNetworkRegistrationInfo(NetworkRegistrationInfo.DOMAIN_PS,
+ AccessNetworkConstants.TRANSPORT_TYPE_WLAN)).thenReturn(mNetworkRegistrationInfo);
+ when(mNetworkRegistrationInfo.getRegistrationState()).thenReturn(
+ NetworkRegistrationInfo.REGISTRATION_STATE_HOME);
+
+ assertThat(Utils.getCombinedServiceState(mServiceState)).isEqualTo(
+ ServiceState.STATE_OUT_OF_SERVICE);
+ }
+
+ @Test
public void getCombinedServiceState_voiceOutOfServiceDataOutOfService_returnOutOfService() {
when(mServiceState.getState()).thenReturn(ServiceState.STATE_OUT_OF_SERVICE);
when(mServiceState.getDataRegState()).thenReturn(ServiceState.STATE_OUT_OF_SERVICE);
+
assertThat(Utils.getCombinedServiceState(mServiceState)).isEqualTo(
ServiceState.STATE_OUT_OF_SERVICE);
}
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/instrumentation/MetricsFeatureProviderTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/instrumentation/MetricsFeatureProviderTest.java
index 8a0ae9190a8c..ed0857ca21dc 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/instrumentation/MetricsFeatureProviderTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/instrumentation/MetricsFeatureProviderTest.java
@@ -26,6 +26,8 @@ import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
+import androidx.preference.Preference;
+
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import org.junit.Before;
@@ -60,19 +62,84 @@ public class MetricsFeatureProviderTest {
}
@Test
- public void logDashboardStartIntent_intentEmpty_shouldNotLog() {
- mProvider.logDashboardStartIntent(mContext, null /* intent */,
+ public void logClickedPreference_preferenceEmpty_shouldNotLog() {
+ final boolean loggable = mProvider.logClickedPreference(null /* preference */,
+ MetricsEvent.SETTINGS_GESTURES);
+
+ assertThat(loggable).isFalse();
+ verifyNoMoreInteractions(mLogWriter);
+ }
+
+ @Test
+ public void logClickedPreference_preferenceHasKey_shouldLog() {
+ final String key = "abc";
+ final Preference preference = new Preference(mContext);
+ preference.setKey(key);
+
+ final boolean loggable = mProvider.logClickedPreference(preference,
+ MetricsEvent.SETTINGS_GESTURES);
+
+ assertThat(loggable).isTrue();
+ verify(mLogWriter).action(
+ MetricsEvent.SETTINGS_GESTURES,
+ MetricsEvent.ACTION_SETTINGS_TILE_CLICK,
+ SettingsEnums.PAGE_UNKNOWN,
+ key,
+ 0);
+ }
+
+ @Test
+ public void logClickedPreference_preferenceHasIntent_shouldLog() {
+ final Preference preference = new Preference(mContext);
+ final Intent intent = new Intent(Intent.ACTION_ASSIST);
+ preference.setIntent(intent);
+
+ final boolean loggable = mProvider.logClickedPreference(preference,
+ MetricsEvent.SETTINGS_GESTURES);
+
+ assertThat(loggable).isTrue();
+ verify(mLogWriter).action(
+ MetricsEvent.SETTINGS_GESTURES,
+ MetricsEvent.ACTION_SETTINGS_TILE_CLICK,
+ SettingsEnums.PAGE_UNKNOWN,
+ Intent.ACTION_ASSIST,
+ 0);
+ }
+
+ @Test
+ public void logClickedPreference_preferenceHasFragment_shouldLog() {
+ final Preference preference = new Preference(mContext);
+ final String fragment = "com.android.settings.tts.TextToSpeechSettings";
+ preference.setFragment(fragment);
+
+ final boolean loggable = mProvider.logClickedPreference(preference,
+ MetricsEvent.SETTINGS_GESTURES);
+
+ assertThat(loggable).isTrue();
+ verify(mLogWriter).action(
+ MetricsEvent.SETTINGS_GESTURES,
+ MetricsEvent.ACTION_SETTINGS_TILE_CLICK,
+ SettingsEnums.PAGE_UNKNOWN,
+ fragment,
+ 0);
+ }
+
+ @Test
+ public void logStartedIntent_intentEmpty_shouldNotLog() {
+ final boolean loggable = mProvider.logStartedIntent(null /* intent */,
MetricsEvent.SETTINGS_GESTURES);
+ assertThat(loggable).isFalse();
verifyNoMoreInteractions(mLogWriter);
}
@Test
- public void logDashboardStartIntent_intentHasNoComponent_shouldLog() {
+ public void logStartedIntent_intentHasNoComponent_shouldLog() {
final Intent intent = new Intent(Intent.ACTION_ASSIST);
- mProvider.logDashboardStartIntent(mContext, intent, MetricsEvent.SETTINGS_GESTURES);
+ final boolean loggable = mProvider.logStartedIntent(intent, MetricsEvent.SETTINGS_GESTURES);
+ assertThat(loggable).isTrue();
verify(mLogWriter).action(
MetricsEvent.SETTINGS_GESTURES,
MetricsEvent.ACTION_SETTINGS_TILE_CLICK,
@@ -82,11 +149,12 @@ public class MetricsFeatureProviderTest {
}
@Test
- public void logDashboardStartIntent_intentIsExternal_shouldLog() {
+ public void logStartedIntent_intentIsExternal_shouldLog() {
final Intent intent = new Intent().setComponent(new ComponentName("pkg", "cls"));
- mProvider.logDashboardStartIntent(mContext, intent, MetricsEvent.SETTINGS_GESTURES);
+ final boolean loggable = mProvider.logStartedIntent(intent, MetricsEvent.SETTINGS_GESTURES);
+ assertThat(loggable).isTrue();
verify(mLogWriter).action(
MetricsEvent.SETTINGS_GESTURES,
MetricsEvent.ACTION_SETTINGS_TILE_CLICK,
diff --git a/packages/SettingsProvider/res/values-af/strings.xml b/packages/SettingsProvider/res/values-af/strings.xml
index 2c454843e4d2..8c2f8b32d85e 100644
--- a/packages/SettingsProvider/res/values-af/strings.xml
+++ b/packages/SettingsProvider/res/values-af/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Instellingsberging"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Veranderings aan jou warmkolinstellings"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Jou warmkolband het verander."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Hierdie toestel steun nie jou voorkeur vir net 5 GHz nie. Hierdie toestel sal pleks daarvan die 5 GHz-band gebruik wanneer dit beskikbaar is."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-am/strings.xml b/packages/SettingsProvider/res/values-am/strings.xml
index 0630560e3e46..640301a54b75 100644
--- a/packages/SettingsProvider/res/values-am/strings.xml
+++ b/packages/SettingsProvider/res/values-am/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"የቅንብሮች ማከማቻ"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"በእርስዎ ሆትስፖት ቅንብሮች ላይ ለውጦች"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"የእርስዎ ሆትስፖት ባንድ ተለውጧል።"</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"ይህ መሣሪያ የእርስዎን ምርጫ ለ5GHz ብቻ አይደግፍም። በምትኩ፣ ይህ መሣሪያ ሲገኝ 5GHz ባንድ ይጠቀማል።"</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-ar/strings.xml b/packages/SettingsProvider/res/values-ar/strings.xml
index 19306a604f40..2675839abc5f 100644
--- a/packages/SettingsProvider/res/values-ar/strings.xml
+++ b/packages/SettingsProvider/res/values-ar/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"تخزين الإعدادات"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"التغييرات التي طرأت على إعدادات نقطة الاتصال"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"تمّ تغيير نطاق نقطة الاتصال الخاصة بك."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"لا يتوافق هذا الجهاز مع إعدادك المفضّل الخاص باستخدام النطاق 5 غيغاهرتز فقط. وسيستخدم الجهاز بدلاً من ذلك النطاق 5 غيغاهرتز عندما يكون متاحًا."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-as/strings.xml b/packages/SettingsProvider/res/values-as/strings.xml
index 13b90d699664..b70146ac3157 100644
--- a/packages/SettingsProvider/res/values-as/strings.xml
+++ b/packages/SettingsProvider/res/values-as/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"ছেটিংছসমূহৰ সঞ্চয়াগাৰ"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"আপোনাৰ হটস্পট ছেটিংসমূহত হোৱা সালসলনিসমূহ"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"আপোনাৰ হটস্পটৰ বেণ্ড সলনি কৰা হৈছে।"</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"আপোনাৰ কেৱল ৫ গিগাহাৰ্টজৰ প্ৰতি অগ্ৰাধিকাৰ এই ডিভাচইচটোৱে সমৰ্থন নকৰে। ইয়াৰ পৰিৱৰ্তে, ডিভাচইচটোৱে যেতিয়া ৫ গিগাহাৰ্টজ বেণ্ড উপলব্ধ হ’ব তেতিয়া তাক ব্যৱহাৰ কৰিব।"</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-az/strings.xml b/packages/SettingsProvider/res/values-az/strings.xml
index 4737a1ee9323..8b4f75b87e81 100644
--- a/packages/SettingsProvider/res/values-az/strings.xml
+++ b/packages/SettingsProvider/res/values-az/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Ayarlar Deposu"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Hotspot ayarlarınızda dəyişiklik"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Hotspot diapazonu dəyişib."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Bu cihaz yalnız 5GHz üçün tərcihinizi dəstəkləmir. Əvəzində, əlçatan olduqda bu cihaz 5GHz diapazonundan istifadə edəcək."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-b+sr+Latn/strings.xml b/packages/SettingsProvider/res/values-b+sr+Latn/strings.xml
index 032dbc577f73..9c3a00e7966d 100644
--- a/packages/SettingsProvider/res/values-b+sr+Latn/strings.xml
+++ b/packages/SettingsProvider/res/values-b+sr+Latn/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Podešavanja skladišta"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Promene podešavanja za hotspot"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Opseg hotspota je promenjen."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Ovaj uređaj ne podržava podešavanje samo za 5 GHz. Uređaj će koristiti opseg od 5 GHz kada bude dostupan."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-be/strings.xml b/packages/SettingsProvider/res/values-be/strings.xml
index 60bdb2daa4a3..0e098e74aee9 100644
--- a/packages/SettingsProvider/res/values-be/strings.xml
+++ b/packages/SettingsProvider/res/values-be/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Сховішча налад"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Змяненні ў наладах хот-спота"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Частата хот-спота змянілася."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Прылада не можа працаваць толькі на частаце 5 ГГц. Гэта частата будзе выкарыстоўвацца, калі гэта магчыма."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-bg/strings.xml b/packages/SettingsProvider/res/values-bg/strings.xml
index c3a994b24252..30526f262230 100644
--- a/packages/SettingsProvider/res/values-bg/strings.xml
+++ b/packages/SettingsProvider/res/values-bg/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Настройки за хранилище"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Промени в настройките ви за точка за достъп"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Честотната лента на точката ви за достъп е променена."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Това устройство не поддържа предпочитанието ви за използване само на честотната лента от 5 ГХц. Вместо това то ще я ползва, когато е възможно."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-bn/strings.xml b/packages/SettingsProvider/res/values-bn/strings.xml
index 71ee99b9b06e..8fc6bbb860f2 100644
--- a/packages/SettingsProvider/res/values-bn/strings.xml
+++ b/packages/SettingsProvider/res/values-bn/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"সেটিংস স্টোরেজ"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"আপনার হটস্পট সেটিংসে করা পরিবর্তনগুলি"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"আপনার হটস্পট ব্যান্ড পরিবর্তন করা হয়েছে।"</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"এই ডিভাইসটি শুধুমাত্র 5GHz এর জন্য আপনার পছন্দ সমর্থন করে না। পরিবর্তে, এই ডিভাইসটি 5GHz ব্যান্ড ব্যবহার করবে।"</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-bs/strings.xml b/packages/SettingsProvider/res/values-bs/strings.xml
index 09d4c68ae541..ddacb327dfc0 100644
--- a/packages/SettingsProvider/res/values-bs/strings.xml
+++ b/packages/SettingsProvider/res/values-bs/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Postavke za pohranu podataka"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Promjene postavki pristupne tačke"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Opseg pristupne tačke je promijenjen."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Ovaj uređaj ne podržava vašu postavku za mreže od isključivo 5 GHz. Uređaj će koristiti opseg of 5 GHz kada bude dostupan."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-ca/strings.xml b/packages/SettingsProvider/res/values-ca/strings.xml
index ee6b51e39dd0..0c2ad73c364c 100644
--- a/packages/SettingsProvider/res/values-ca/strings.xml
+++ b/packages/SettingsProvider/res/values-ca/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Configuració de l\'emmagatzematge"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Canvis en la configuració del punt d\'accés Wi‑Fi"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Ha canviat la teva banda del punt d\'accés Wi‑Fi."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Aquest dispositiu no admet utilitzar exclusivament una banda de 5 GHz. El dispositiu utilitzarà una banda de 5 GHz quan estigui disponible."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-cs/strings.xml b/packages/SettingsProvider/res/values-cs/strings.xml
index f134e0559667..ab474b1e0ab7 100644
--- a/packages/SettingsProvider/res/values-cs/strings.xml
+++ b/packages/SettingsProvider/res/values-cs/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Paměť pro nastavení"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Změny nastavení hotspotu"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Pásmo hotspotu se změnilo."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Toto zařízení nepodporuje vaše nastavení jen 5GHz pásma. Zařízení použije pásmo 5 GHz, jen když bude dostupné."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-da/strings.xml b/packages/SettingsProvider/res/values-da/strings.xml
index 99988a58a041..719614c90e4f 100644
--- a/packages/SettingsProvider/res/values-da/strings.xml
+++ b/packages/SettingsProvider/res/values-da/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Lagring af indstillinger"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Ændringer af dine indstillinger for hotspot"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Dit hotspotbånd er ændret."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Denne enhed understøtter ikke din præference om kun 5 GHz. Denne enhed vil i stedet bruge 5 GHz-båndet, når det er muligt."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-de/strings.xml b/packages/SettingsProvider/res/values-de/strings.xml
index ddcabaa23e3c..6e253e0a306b 100644
--- a/packages/SettingsProvider/res/values-de/strings.xml
+++ b/packages/SettingsProvider/res/values-de/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Einstellungsspeicher"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Änderungen an deinen Hotspot-Einstellungen"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Dein Hotspot-Band hat sich geändert."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Dieses Gerät unterstützt die ausschließliche Nutzung von 5 GHz nicht. Es greift aber immer auf das 5-GHz-Band zurück, wenn dieses verfügbar ist."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-el/strings.xml b/packages/SettingsProvider/res/values-el/strings.xml
index 924fab5fb80b..c47fea2c77dc 100644
--- a/packages/SettingsProvider/res/values-el/strings.xml
+++ b/packages/SettingsProvider/res/values-el/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Αποθηκευτικός χώρος ρυθμίσεων"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Αλλαγές στις ρυθμίσεις σημείου πρόσβασης Wi-Fi"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Το εύρος σημείου πρόσβασης Wi-Fi άλλαξε."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Αυτή η συσκευή δεν υποστηρίζει την προτίμησή σας για αποκλειστική χρήση του εύρους 5 GHz. Αντ\' αυτού, αυτή η συσκευή θα χρησιμοποιεί το εύρος 5 GHz όταν είναι διαθέσιμο."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-en-rAU/strings.xml b/packages/SettingsProvider/res/values-en-rAU/strings.xml
index 05cd54e7cee7..fac51d83dba3 100644
--- a/packages/SettingsProvider/res/values-en-rAU/strings.xml
+++ b/packages/SettingsProvider/res/values-en-rAU/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Settings Storage"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Changes to your hotspot settings"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Your hotspot band has changed."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"This device doesn’t support your preference for 5 GHz only. Instead, this device will use the 5 GHz band when available."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-en-rCA/strings.xml b/packages/SettingsProvider/res/values-en-rCA/strings.xml
index 05cd54e7cee7..fac51d83dba3 100644
--- a/packages/SettingsProvider/res/values-en-rCA/strings.xml
+++ b/packages/SettingsProvider/res/values-en-rCA/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Settings Storage"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Changes to your hotspot settings"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Your hotspot band has changed."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"This device doesn’t support your preference for 5 GHz only. Instead, this device will use the 5 GHz band when available."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-en-rGB/strings.xml b/packages/SettingsProvider/res/values-en-rGB/strings.xml
index 05cd54e7cee7..fac51d83dba3 100644
--- a/packages/SettingsProvider/res/values-en-rGB/strings.xml
+++ b/packages/SettingsProvider/res/values-en-rGB/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Settings Storage"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Changes to your hotspot settings"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Your hotspot band has changed."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"This device doesn’t support your preference for 5 GHz only. Instead, this device will use the 5 GHz band when available."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-en-rIN/strings.xml b/packages/SettingsProvider/res/values-en-rIN/strings.xml
index 05cd54e7cee7..fac51d83dba3 100644
--- a/packages/SettingsProvider/res/values-en-rIN/strings.xml
+++ b/packages/SettingsProvider/res/values-en-rIN/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Settings Storage"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Changes to your hotspot settings"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Your hotspot band has changed."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"This device doesn’t support your preference for 5 GHz only. Instead, this device will use the 5 GHz band when available."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-es-rUS/strings.xml b/packages/SettingsProvider/res/values-es-rUS/strings.xml
index d5e6da9affc0..af9025777fd6 100644
--- a/packages/SettingsProvider/res/values-es-rUS/strings.xml
+++ b/packages/SettingsProvider/res/values-es-rUS/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Almacenamiento de configuración"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Cambios en la configuración de tu hotspot"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Cambió la banda de tu hotspot."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Si bien este dispositivo no admite la opción para conectarse exclusivamente a bandas de 5 GHz, las usará cuando estén disponibles."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-es/strings.xml b/packages/SettingsProvider/res/values-es/strings.xml
index d5e6da9affc0..ff4ee385b4b6 100644
--- a/packages/SettingsProvider/res/values-es/strings.xml
+++ b/packages/SettingsProvider/res/values-es/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Almacenamiento de configuración"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Cambios en los ajustes del punto de acceso"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"La banda de tu punto de acceso ha cambiado."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Este dispositivo no admite la opción de conectarse únicamente a bandas de 5 GHz, pero las usará cuando estén disponibles."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-et/strings.xml b/packages/SettingsProvider/res/values-et/strings.xml
index a3e4db6c8898..a0ec5939019e 100644
--- a/packages/SettingsProvider/res/values-et/strings.xml
+++ b/packages/SettingsProvider/res/values-et/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Seadete talletusruum"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Muudatused teie kuumkoha seadetes"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Teie kuumkoha sagedusriba on muutunud."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"See seade ei toeta teie eelistatud ainult 5 GHz riba. Seade kasutab 5 GHz riba ainult siis, kui see on saadaval."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-eu/strings.xml b/packages/SettingsProvider/res/values-eu/strings.xml
index 8d410de1eb3c..220b486b283b 100644
--- a/packages/SettingsProvider/res/values-eu/strings.xml
+++ b/packages/SettingsProvider/res/values-eu/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Ezarpenen biltegia"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Aldaketak egin dira sare publikoaren ezarpenetan"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Aldatu da sare publikoaren banda."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Gailuak ez du onartzen 5 GHz-ko banda soilik erabiltzeko hobespena. Horren ordez, erabilgarri dagoen bakoitzean erabiliko da 5 GHz-ko banda."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-fa/strings.xml b/packages/SettingsProvider/res/values-fa/strings.xml
index ed9d168bc54b..6819d2fd3af3 100644
--- a/packages/SettingsProvider/res/values-fa/strings.xml
+++ b/packages/SettingsProvider/res/values-fa/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"تنظیم محل ذخیره"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"تغییرات در تنظیمات نقطه اتصال"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"نوار نقطه اتصال شما تغییر کرد."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"این دستگاه از اولویت فقط ۵ گیگاهرتز شما پشتیبانی نمی‌کند. هرزمان نوار ۵ گیگاهرتزی دردسترس باشد، این دستگاه از آن استفاده خواهد کرد."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-fi/strings.xml b/packages/SettingsProvider/res/values-fi/strings.xml
index 9ff2c41936d3..9ad01eb9a183 100644
--- a/packages/SettingsProvider/res/values-fi/strings.xml
+++ b/packages/SettingsProvider/res/values-fi/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Asetuksien tallennus"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Hotspot-asetustesi muutokset"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Hotspot-taajuutesi on muuttunut."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Tämä laite ei tue asetustasi (vain 5 GHz). Sen sijaan laite käyttää 5 GHz:n taajuutta sen ollessa käytettävissä."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-fr-rCA/strings.xml b/packages/SettingsProvider/res/values-fr-rCA/strings.xml
index fdfdb1d01b2f..62951bd1d120 100644
--- a/packages/SettingsProvider/res/values-fr-rCA/strings.xml
+++ b/packages/SettingsProvider/res/values-fr-rCA/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Stockage des paramètres"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Modifications apportées à vos paramètres de point d\'accès"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"La bande de votre point d\'accès a changé."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Cet appareil ne prend pas en charge votre préférence pour la bande de 5 GHz seulement. Au lieu de cela, cet appareil utilisera la bande de 5 GHz lorsqu\'elle sera disponible."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-fr/strings.xml b/packages/SettingsProvider/res/values-fr/strings.xml
index fdfdb1d01b2f..56bc65baadcb 100644
--- a/packages/SettingsProvider/res/values-fr/strings.xml
+++ b/packages/SettingsProvider/res/values-fr/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Stockage des paramètres"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Modifications apportées à vos paramètres de point d\'accès"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"La bande utilisée par votre point d\'accès a été modifiée."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Cet appareil n\'est pas conçu pour utiliser exclusivement la bande 5 GHz, mais il l\'utilisera chaque fois que disponible."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-gl/strings.xml b/packages/SettingsProvider/res/values-gl/strings.xml
index 7b1599e0e8cd..771fade21c17 100644
--- a/packages/SettingsProvider/res/values-gl/strings.xml
+++ b/packages/SettingsProvider/res/values-gl/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Almacenamento da configuración"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Cambios na configuración da zona wifi"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Modificouse a banda da zona wifi."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Este dispositivo non admite a opción de conectarse só a bandas de 5 GHz, pero usaraas se están dispoñibles."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-gu/strings.xml b/packages/SettingsProvider/res/values-gu/strings.xml
index 00246f98ad52..a561924981fc 100644
--- a/packages/SettingsProvider/res/values-gu/strings.xml
+++ b/packages/SettingsProvider/res/values-gu/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"સેટિંગ્સ સંગ્રહ"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"તમારા હૉટસ્પૉટ સેટિંગને બદલે છે"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"તમારું હૉટસ્પૉટ બૅન્ડ બદલાઈ ગયું છે."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"આ ડિવાઇસ તમારી ફક્ત 5GHz માટેની પસંદગીને સપોર્ટ કરતું નથી. તેના બદલે, જ્યારે 5GHz બૅન્ડ ઉપલબ્ધ હશે ત્યારે આ ડિવાઇસ તેનો ઉપયોગ કરશે."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-hi/strings.xml b/packages/SettingsProvider/res/values-hi/strings.xml
index 35ed78fba729..199a546c57a4 100644
--- a/packages/SettingsProvider/res/values-hi/strings.xml
+++ b/packages/SettingsProvider/res/values-hi/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"सेटिंग मेमोरी"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"आपकी हॉटस्पॉट की सेटिंग में किए गए बदलाव"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"आपका हॉटस्पॉट का बैंड बदल दिया गया है."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"इस डिवाइस पर आप \'सिर्फ़ 5 गीगाहर्ट्ज़\' वाला विकल्प नहीं चुन सकते. इसके बजाय, 5 गीगाहर्ट्ज़ बैंड उपलब्ध होने पर यह डिवाइस उसका इस्तेमाल करेगा."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-hr/strings.xml b/packages/SettingsProvider/res/values-hr/strings.xml
index 070d0619f07d..9129a049458b 100644
--- a/packages/SettingsProvider/res/values-hr/strings.xml
+++ b/packages/SettingsProvider/res/values-hr/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Postavke pohrane"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Promjene postavki vaše žarišne točke"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Promijenila se frekvencija vaše žarišne točke."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Ovaj uređaj ne podržava vašu postavku za upotrebu samo 5 GHz. Upotrebljavat će frekvenciju od 5 GHz kada je dostupna."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-hu/strings.xml b/packages/SettingsProvider/res/values-hu/strings.xml
index 97124ae390af..a1ed494d75c6 100644
--- a/packages/SettingsProvider/res/values-hu/strings.xml
+++ b/packages/SettingsProvider/res/values-hu/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Beállítástároló"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"A hotspot beállításainak módosítása"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"A hotspot sávja megváltozott."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Ez az eszköz nem támogatja a csak 5 GHz-es sávra vonatkozó beállítást. Az eszköz akkor használ 5 GHz-es sávot, ha a sáv rendelkezésre áll."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-hy/strings.xml b/packages/SettingsProvider/res/values-hy/strings.xml
index d4940124f20f..6d716f878ce4 100644
--- a/packages/SettingsProvider/res/values-hy/strings.xml
+++ b/packages/SettingsProvider/res/values-hy/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Կարգավորումների պահուստ"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Փոփոխություններ թեժ կետի կարգավորումներում"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Ձեր թեժ կետի հաճախականությունը փոխվել է։"</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Սարքը չի կարող աշխատել միայն 5 ԳՀց հաճախականությամբ։ Այդ հաճախականությունը կօգտագործվի հնարավորության դեպքում։"</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-in/strings.xml b/packages/SettingsProvider/res/values-in/strings.xml
index 4ec8f8464969..8b1b1f4ab0ff 100644
--- a/packages/SettingsProvider/res/values-in/strings.xml
+++ b/packages/SettingsProvider/res/values-in/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Setelan Penyimpanan"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Perubahan pada setelan hotspot Anda"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Band hotspot Anda telah berubah."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Perangkat ini tidak mendukung preferensi Anda, yaitu hanya 5GHz. Sebagai gantinya, perangkat ini akan menggunakan band 5GHz jika tersedia."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-is/strings.xml b/packages/SettingsProvider/res/values-is/strings.xml
index d75abae3849c..150c0845579c 100644
--- a/packages/SettingsProvider/res/values-is/strings.xml
+++ b/packages/SettingsProvider/res/values-is/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Stillingageymsla"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Breytingar á stillingum heits reits"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Tíðnisvið heita reitsins hefur breyst."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Þetta tæki styður ekki val þitt fyrir aðeins 5 GHz. Í staðinn mun þetta tæki nota 5 GHz tíðnisvið þegar það er í boði."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-it/strings.xml b/packages/SettingsProvider/res/values-it/strings.xml
index a1e3901f1f7a..6715c3cc2a7d 100644
--- a/packages/SettingsProvider/res/values-it/strings.xml
+++ b/packages/SettingsProvider/res/values-it/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Memoria impostazioni"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Modifiche alle tue impostazioni dell\'hotspot"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"La banda dell\'hotspot è cambiata."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Questo dispositivo non supporta la tua preferenza esclusiva per 5 GHz. Utilizzerà la banda a 5 GHz solo quando è disponibile."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-iw/strings.xml b/packages/SettingsProvider/res/values-iw/strings.xml
index c14f776d26c4..dd4432984154 100644
--- a/packages/SettingsProvider/res/values-iw/strings.xml
+++ b/packages/SettingsProvider/res/values-iw/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"אחסון הגדרות"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"שינויים להגדרות של הנקודה לשיתוף אינטרנט"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"התדר של הנקודה לשיתוף אינטרנט השתנה."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"‏מכשיר זה לא תומך בהעדפות שלך ל-5GHz בלבד. במקום זאת, מכשיר זה ישתמש בתדר 5GHz כשיהיה זמין."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-ja/strings.xml b/packages/SettingsProvider/res/values-ja/strings.xml
index b11ec3b14d82..7bbcd4696e86 100644
--- a/packages/SettingsProvider/res/values-ja/strings.xml
+++ b/packages/SettingsProvider/res/values-ja/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"ストレージの設定"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"アクセス ポイントの設定の変更"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"アクセス ポイントの帯域幅が変更されました。"</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"このデバイスは 5 GHz のみという設定に対応していません。ただし、5 GHz 周波数帯が利用できるときには利用します。"</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-ka/strings.xml b/packages/SettingsProvider/res/values-ka/strings.xml
index d08e71ea592b..86db4f38d81e 100644
--- a/packages/SettingsProvider/res/values-ka/strings.xml
+++ b/packages/SettingsProvider/res/values-ka/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"პარამეტრების საცავი"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"თქვენი უსადენო ქსელის პარამეტრების ცვლილება"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"თქვენი უსადენო ქსელის დიაპაზონი შეიცვალა."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"ამ მოწყობილობას არ შეუძლია მხოლოდ 5 გჰც სიხშირეზე მუშაობა. აღნიშნული სიხშირის გამოყენება მოხდება მაშინ, როცა ეს შესაძლებელია."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-kk/strings.xml b/packages/SettingsProvider/res/values-kk/strings.xml
index c07264cb6f11..a093d08987a0 100644
--- a/packages/SettingsProvider/res/values-kk/strings.xml
+++ b/packages/SettingsProvider/res/values-kk/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Параметрлер жады"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Хотспот параметрлеріне өзгерістер енгізілді"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Хотспот жолағы өзгертілді."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Бұл құрылғы тек 5 ГГц жиілікте жұмыс істей алмайды. Бұл жиілік мүмкін болған жағдайда ғана қолданылады."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-km/strings.xml b/packages/SettingsProvider/res/values-km/strings.xml
index c880ead34f7d..f0a2712558a6 100644
--- a/packages/SettingsProvider/res/values-km/strings.xml
+++ b/packages/SettingsProvider/res/values-km/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"កំណត់​ការ​ផ្ទុក"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"ប្ដូរ​ទៅ​ការ​កំណត់​ហតស្ប៉ត​របស់អ្នក"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"កម្រិតបញ្ជូន​ហតស្ប៉ត​របស់​អ្នកបាន​ផ្លាស់ប្ដូរ។"</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"ឧបករណ៍នេះ​មិនស្គាល់​ចំណូលចិត្ត​របស់អ្នក​សម្រាប់តែ 5GHz ប៉ុណ្ណោះ។ ផ្ទុយមកវិញ ឧបករណ៍នេះ​នឹងប្រើ​កម្រិតបញ្ជូន 5GHz នៅពេល​ដែលអាច​ប្រើបាន។"</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-kn/strings.xml b/packages/SettingsProvider/res/values-kn/strings.xml
index d82332364c74..f2c1d5e4a59d 100644
--- a/packages/SettingsProvider/res/values-kn/strings.xml
+++ b/packages/SettingsProvider/res/values-kn/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"ಸೆಟ್ಟಿಂಗ್‌ಗಳ ಸಂಗ್ರಹಣೆ"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"ನಿಮ್ಮ ಹಾಟ್‌ಸ್ಪಾಟ್‌ ಸೆಟ್ಟಿಂಗ್‌ಗಳಲ್ಲಿನ ಬದಲಾವಣೆಗಳು"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"ನಿಮ್ಮ ಹಾಟ್‌ಸ್ಪಾಟ್‌ ಬ್ಯಾಂಡ್ ಬದಲಾಗಿದೆ."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"ಈ ಸಾಧನವು 5GHz ಗೆ ಮಾತ್ರ ನಿಮ್ಮ ಆದ್ಯತೆಯನ್ನು ಬೆಂಬಲಿಸುವುದಿಲ್ಲ. ಬದಲಿಗೆ, ಈ ಸಾಧನವು 5GHz ಬ್ಯಾಂಡ್ ಅನ್ನು ಲಭ್ಯವಿರುವಾಗ ಬಳಸುತ್ತದೆ."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-ko/strings.xml b/packages/SettingsProvider/res/values-ko/strings.xml
index ab8fb2be95cd..841832d83853 100644
--- a/packages/SettingsProvider/res/values-ko/strings.xml
+++ b/packages/SettingsProvider/res/values-ko/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"설정 저장소"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"핫스팟 설정 변경"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"핫스팟 대역이 변경되었습니다."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"이 기기에서는 5GHz 전용 환경설정이 지원되지 않습니다. 대신 가능할 때만 기기에서 5GHz 대역이 사용됩니다."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-ky/strings.xml b/packages/SettingsProvider/res/values-ky/strings.xml
index 566c48139506..014c66ca4186 100644
--- a/packages/SettingsProvider/res/values-ky/strings.xml
+++ b/packages/SettingsProvider/res/values-ky/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Жөндөөлөрдү сактоо"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Байланыш түйүнүңүздүн жөндөөлөрү өзгөрүлдү"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Байланыш түйүнүңүздүн жыштыгы өзгөрдү."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Бул түзмөк 5ГГцти гана колдонуу жөндөөсүн колдоого албайт. Анын ордуна, бул түзмөк 5ГГц жыштыгын ал жеткиликтүү болгондо колдонот."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-lo/strings.xml b/packages/SettingsProvider/res/values-lo/strings.xml
index 1aa5fe9a330a..9d60ba12904c 100644
--- a/packages/SettingsProvider/res/values-lo/strings.xml
+++ b/packages/SettingsProvider/res/values-lo/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"ບ່ອນເກັບຂໍ້ມູນການຕັ້ງຄ່າ"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"ການປ່ຽນແປງການຕັ້ງຄ່າຮັອດສະປອດຂອງທ່ານ"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"ຄື້ນຄວາມຖີ່ຮັອດສະປອດຂອງທ່ານປ່ຽນແປງແລ້ວ."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"ອຸປະກອນນີ້ບໍ່ຮອງຮັບການຕັ້ງຄ່າຂອງທ່ານສຳລັບ 5GHz ເທົ່ານັ້ນ. ແຕ່ວ່າອຸປະກອນນີ້ຈະໃຊ້ຄື້ນຄວາມຖີ່ 5GHz ເມື່ອສາມາດໃຊ້ໄດ້."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-lt/strings.xml b/packages/SettingsProvider/res/values-lt/strings.xml
index 47cd6b4e6838..775d3b9186d4 100644
--- a/packages/SettingsProvider/res/values-lt/strings.xml
+++ b/packages/SettingsProvider/res/values-lt/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Nustatymų saugykla"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Viešosios interneto prieigos taško nustatymų pakeitimai"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Viešosios prieigos taško dažnio juosta pasikeitė."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Šiame įrenginyje nepalaikoma tik 5 GHz nuostata. Vietoj to šiame įrenginyje bus naudojama 5 GHz dažnio juosta, kai bus pasiekiama."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-lv/strings.xml b/packages/SettingsProvider/res/values-lv/strings.xml
index d221d468c42c..f7f3117ffcb0 100644
--- a/packages/SettingsProvider/res/values-lv/strings.xml
+++ b/packages/SettingsProvider/res/values-lv/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Iestatījumu krātuve"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Izmaiņas tīklāja iestatījumos"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Ir mainīts tīklāja joslas platums."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Šajā ierīcē netiek atbalstīta jūsu preference par tikai 5 GHz joslu. 5 GHz josla ierīcē tiks izmantota, kad tā būs pieejama."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-mk/strings.xml b/packages/SettingsProvider/res/values-mk/strings.xml
index dc74c4aa732c..a245e5f441f4 100644
--- a/packages/SettingsProvider/res/values-mk/strings.xml
+++ b/packages/SettingsProvider/res/values-mk/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Поставки за меморија"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Промени на поставките за точка на пристап"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Опсегот за точка на пристап е променет."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Уредов не ги поддржува вашите поставки за само 5 GHz. Наместо тоа, ќе го користи опсегот од 5 GHz кога е достапен."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-ml/strings.xml b/packages/SettingsProvider/res/values-ml/strings.xml
index a11e23604436..b63f20e903f8 100644
--- a/packages/SettingsProvider/res/values-ml/strings.xml
+++ b/packages/SettingsProvider/res/values-ml/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"സംഭരണ ക്രമീകരണം"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"നിങ്ങളുടെ ഹോട്ട്‌സ്‌പോട്ട് ക്രമീകരണത്തിൽ വരുത്തിയ മാറ്റങ്ങൾ"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"നിങ്ങളുടെ ഹോട്ട്‌സ്‌പോട്ട് ബാൻഡ് മാറിയിരിക്കുന്നു."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"നിങ്ങളുടെ മുൻഗണനയനുസരിച്ചുള്ള, 5GHz മാത്രം എന്നത് ഈ ഉപകരണം പിന്തുണയ്ക്കുന്നില്ല. പകരം, 5GHz ബാൻഡ് ലഭ്യമാകുമ്പോൾ അത് ഉപയോഗിക്കും."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-mn/strings.xml b/packages/SettingsProvider/res/values-mn/strings.xml
index f6437c7591f3..c839177f0c4f 100644
--- a/packages/SettingsProvider/res/values-mn/strings.xml
+++ b/packages/SettingsProvider/res/values-mn/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Тохиргооны Сан"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Таны сүлжээний цэгийн тохиргооны өөрчлөлт"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Таны сүлжээний цэгийн хязгаарыг өөрчилсөн."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Энэ төхөөрөмж нь зөвхөн 5Гц гэсэн таны сонголтыг дэмждэггүй. Оронд нь энэ төхөөрөмж 5Гц-н хязгаарыг боломжтой үед нь ашиглах болно."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-mr/strings.xml b/packages/SettingsProvider/res/values-mr/strings.xml
index 78884882555f..0c7041ee6996 100644
--- a/packages/SettingsProvider/res/values-mr/strings.xml
+++ b/packages/SettingsProvider/res/values-mr/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"सेटिंग्ज संचयन"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"तुमच्या हॉटस्पॉट सेटिंग्जमधील बदल"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"तुमचा हॉटस्पॉट बँड बदलला गेला आहे."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"हे डिव्हाइस फक्त ५GHz च्या तुमच्या प्राधान्याला सपोर्ट करत नाही. त्याऐवजी, उपलब्ध असेल तेव्हा हे डिव्हाइस ५GHz बँड वापरेल."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-ms/strings.xml b/packages/SettingsProvider/res/values-ms/strings.xml
index bcde71c7614b..a1574df9c473 100644
--- a/packages/SettingsProvider/res/values-ms/strings.xml
+++ b/packages/SettingsProvider/res/values-ms/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Storan Tetapan"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Perubahan kepada tetapan tempat liputan anda"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Jalur tempat liputan anda telah berubah."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Peranti ini tidak menyokong pilihan anda untuk 5GHz sahaja. Sebaliknya, peranti ini akan menggunakan jalur 5GHz apabila tersedia."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-my/strings.xml b/packages/SettingsProvider/res/values-my/strings.xml
index b2e670e07279..48d4dbac8c1f 100644
--- a/packages/SettingsProvider/res/values-my/strings.xml
+++ b/packages/SettingsProvider/res/values-my/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"သိုလှောင်မှုဆက်တင်များ"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"သင်၏ဟော့စပေါ့ ဆက်တင်များ ပြောင်းလဲမှု"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"သင်၏ ဟော့စပေါ့လိုင်း ပြောင်းသွားပါပြီ။"</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"ဤစက်ပစ္စည်းသည် သင်၏ 5GHz သီးသန့်ရွေးချယ်မှုအတွက် ပံ့ပိုးမထားပါ။ ၎င်းအစား ဤစက်ပစ္စည်းသည် ရနိုင်သည့်အခါ 5GHz လိုင်းကို သုံးသွားပါမည်။"</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-nb/strings.xml b/packages/SettingsProvider/res/values-nb/strings.xml
index 5c60ad708abf..e0cbd7e21812 100644
--- a/packages/SettingsProvider/res/values-nb/strings.xml
+++ b/packages/SettingsProvider/res/values-nb/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Lagring av innstillinger"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Endres til innstillingene dine for Wi-Fi-soner"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Båndet ditt for Wi-Fi-sone er endret."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Denne enheten støtter ikke innstillingen din for bare 5 GHz. I stedet bruker enheten 5 GHz-båndet når det er tilgjengelig."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-ne/strings.xml b/packages/SettingsProvider/res/values-ne/strings.xml
index 8c4f8c891b0f..2fd9b00c54ca 100644
--- a/packages/SettingsProvider/res/values-ne/strings.xml
+++ b/packages/SettingsProvider/res/values-ne/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"सेटिङहरू भण्डारण"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"तपाईंका हटस्पट सेटिङहरूमा गरिएका परिवर्तनहरू"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"तपाईंको हटस्पट ब्यान्ड परिवर्तन भएको छ।"</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"यो यन्त्रले तपाईंको 5GHz मात्रको प्राथमिकतालाई समर्थन गर्दैन। बरु, उपलब्ध भएको खण्डमा यो यन्त्रले 5GHz ब्यान्ड प्रयोग गर्ने छ।"</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-nl/strings.xml b/packages/SettingsProvider/res/values-nl/strings.xml
index 7ad4588c76f2..0b843ae5f96c 100644
--- a/packages/SettingsProvider/res/values-nl/strings.xml
+++ b/packages/SettingsProvider/res/values-nl/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Opslagruimte voor instellingen"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Wijzigingen in je hotspot-instellingen"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Je hotspot-band is gewijzigd."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Dit apparaat biedt geen ondersteuning voor je voorkeur voor alleen 5 GHz. In plaats daarvan gebruikt dit apparaat de 5-GHz-band wanneer deze beschikbaar is."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-or/strings.xml b/packages/SettingsProvider/res/values-or/strings.xml
index 183721954434..53f6104d1033 100644
--- a/packages/SettingsProvider/res/values-or/strings.xml
+++ b/packages/SettingsProvider/res/values-or/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"ସେଟିଙ୍ଗ ଷ୍ଟୋରେଜ୍‌"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"ଆପଣଙ୍କର ହଟ୍‌ସ୍ପଟ୍ ସେଟିଂସ୍‌କୁ ବଦଳାଇଥାଏ"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"ଆପଣଙ୍କର ହଟ୍‌ସ୍ପଟ୍ ପରିବର୍ତ୍ତନ କରାଯାଇଛି।"</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"କେବଳ 5GHz ପାଇଁ, ଏହି ଡିଭାଇସ୍ ଆପଣଙ୍କର ପସନ୍ଦକୁ ସମର୍ଥନ କରେ ନାହିଁ। ଏହା ପରିବର୍ତ୍ତେ, ଉପଲବ୍ଧ ହେଲେ ଏହି ଡିଭାଇସ୍ 5GHz ବ୍ୟାଣ୍ଡ ବ୍ୟବହାର କରିବ।"</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-pa/strings.xml b/packages/SettingsProvider/res/values-pa/strings.xml
index 2961435e6990..9a41e36d15e1 100644
--- a/packages/SettingsProvider/res/values-pa/strings.xml
+++ b/packages/SettingsProvider/res/values-pa/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"ਸੈਟਿੰਗਾਂ ਸਟੋਰੇਜ"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"ਤੁਹਾਡੀਆਂ ਹੌਟਸਪੌਟ ਸੈਟਿੰਗਾਂ ਵਿੱਚ ਬਦਲਾਅ"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"ਤੁਹਾਡਾ ਹੌਟਸਪੌਟ ਬੈਂਡ ਬਦਲ ਗਿਆ ਹੈ।"</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"ਇਹ ਡੀਵਾਈਸ ਸਿਰਫ਼ 5GHz ਦੀ ਤੁਹਾਡੀ ਤਰਜੀਹ ਦਾ ਸਮਰਥਨ ਨਹੀਂ ਕਰਦਾ ਹੈ। ਇਸਦੀ ਬਜਾਏ, ਇਹ ਡੀਵਾਈਸ ਉਪਲਬਧ ਹੋਣ \'ਤੇ 5GHz ਬੈਂਡ ਵਰਤੇਗਾ।"</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-pl/strings.xml b/packages/SettingsProvider/res/values-pl/strings.xml
index 9963aee683f9..7fd2b136dfb8 100644
--- a/packages/SettingsProvider/res/values-pl/strings.xml
+++ b/packages/SettingsProvider/res/values-pl/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Pamięć ustawień"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Zmieniono ustawienia hotspotu"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Zmieniono pasmo hotspotu."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"To urządzenie nie może korzystać tylko z częstotliwości 5 GHz. Będzie korzystać z tego pasma, jeśli będzie ono dostępne."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-pt-rBR/strings.xml b/packages/SettingsProvider/res/values-pt-rBR/strings.xml
index e25e82e46f87..18db8f664686 100644
--- a/packages/SettingsProvider/res/values-pt-rBR/strings.xml
+++ b/packages/SettingsProvider/res/values-pt-rBR/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Armazenamento de configurações"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Mudanças nas suas configurações de ponto de acesso"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Sua banda de ponto de acesso foi modificada."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Este dispositivo não é compatível com sua preferência apenas por 5 GHz. Em vez disso, o dispositivo usará a banda de 5 GHz quando ela estiver disponível."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-pt-rPT/strings.xml b/packages/SettingsProvider/res/values-pt-rPT/strings.xml
index 3b95a31c6cf5..be88cceb72f4 100644
--- a/packages/SettingsProvider/res/values-pt-rPT/strings.xml
+++ b/packages/SettingsProvider/res/values-pt-rPT/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Armazenamento de definições"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Alterações às definições de zona Wi-Fi"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"A banda da sua zona Wi-Fi foi alterada."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Este dispositivo não suporta a sua preferência apenas para 5 GHz. Em alternativa, este dispositivo vai utilizar a banda de 5 GHz quando estiver disponível."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-pt/strings.xml b/packages/SettingsProvider/res/values-pt/strings.xml
index e25e82e46f87..18db8f664686 100644
--- a/packages/SettingsProvider/res/values-pt/strings.xml
+++ b/packages/SettingsProvider/res/values-pt/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Armazenamento de configurações"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Mudanças nas suas configurações de ponto de acesso"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Sua banda de ponto de acesso foi modificada."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Este dispositivo não é compatível com sua preferência apenas por 5 GHz. Em vez disso, o dispositivo usará a banda de 5 GHz quando ela estiver disponível."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-ro/strings.xml b/packages/SettingsProvider/res/values-ro/strings.xml
index 5a5ac6de32c1..3a234e19faa2 100644
--- a/packages/SettingsProvider/res/values-ro/strings.xml
+++ b/packages/SettingsProvider/res/values-ro/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Stocare setări"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Modificări aduse setărilor pentru hotspot"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"S-a schimbat banda de frecvență a hotspotului."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Dispozitivul nu acceptă doar preferința pentru 5 GHz. Dispozitivul va folosi banda de 5 GHz când este disponibilă."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-ru/strings.xml b/packages/SettingsProvider/res/values-ru/strings.xml
index 15ca313a1538..184afdde3e6d 100644
--- a/packages/SettingsProvider/res/values-ru/strings.xml
+++ b/packages/SettingsProvider/res/values-ru/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Хранилище настроек"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Изменения в настройках точки доступа"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Частота точки доступа изменена."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Устройство не может работать только на частоте 5 ГГц. Эта частота будет использоваться, когда это возможно."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-si/strings.xml b/packages/SettingsProvider/res/values-si/strings.xml
index feff43c5bc1b..69e04f1749e6 100644
--- a/packages/SettingsProvider/res/values-si/strings.xml
+++ b/packages/SettingsProvider/res/values-si/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"සැකසීම් ගබඩාව"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"ඔබගේ හොට්ස්පොට් සැකසීම්වලට වෙනස් කිරීම්"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"ඔබගේ හොට්ස්පොට් කලාපය වෙනස් වී ඇත."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"මෙම උපාංගය 5GHz සඳහා ඔබේ මනාපවලට සහාය නොදක්වයි. ඒ වෙනුවට, මෙම උපාංගය ලබා ගත හැකි විට 5GHz කලාපය භාවිතා කරනු ඇත."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-sk/strings.xml b/packages/SettingsProvider/res/values-sk/strings.xml
index 1207a940eaec..a53178daf0a0 100644
--- a/packages/SettingsProvider/res/values-sk/strings.xml
+++ b/packages/SettingsProvider/res/values-sk/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Ukladací priestor nastavení"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Zmeny nastavení hotspotu"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Pásmo vášho hotspotu sa zmenilo."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Toto zariadenie nepodporuje vašu predvoľbu používať iba 5 GHz. Namiesto toho bude pásmo 5 GHz používať vtedy, keď bude k dispozícii."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-sl/strings.xml b/packages/SettingsProvider/res/values-sl/strings.xml
index 28a99375dc40..ea697fe4d1d3 100644
--- a/packages/SettingsProvider/res/values-sl/strings.xml
+++ b/packages/SettingsProvider/res/values-sl/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Shramba nastavitev"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Spremembe nastavitev dostopne točke"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Pas dostopne točke je spremenjen."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Ta naprava ne podpira prednostne nastavitve samo za 5-GHz pas. Namesto tega bo ta naprava uporabljala 5-GHz pas, ko bo na voljo."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-sq/strings.xml b/packages/SettingsProvider/res/values-sq/strings.xml
index 977fe02dbc7b..a111576d8e6a 100644
--- a/packages/SettingsProvider/res/values-sq/strings.xml
+++ b/packages/SettingsProvider/res/values-sq/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Hapësira ruajtëse e \"Cilësimeve\""</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Ndryshimet në cilësimet e zonës së qasjes për internet"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Brezi yt i zonës së qasjes për internet ka ndryshuar."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Kjo pajisje nuk e mbështet preferencën për vetëm 5 GHz. Përkundrazi, pajisja do të përdorë brezin 5 GHz nëse ka."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-sr/strings.xml b/packages/SettingsProvider/res/values-sr/strings.xml
index 74b9dde0a4f0..d4731022f8ad 100644
--- a/packages/SettingsProvider/res/values-sr/strings.xml
+++ b/packages/SettingsProvider/res/values-sr/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Подешавања складишта"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Промене подешавања за хотспот"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Опсег хотспота је промењен."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Овај уређај не подржава подешавање само за 5 GHz. Уређај ће користити опсег од 5 GHz када буде доступан."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-sv/strings.xml b/packages/SettingsProvider/res/values-sv/strings.xml
index 1444626865c0..fea3e5eb2b18 100644
--- a/packages/SettingsProvider/res/values-sv/strings.xml
+++ b/packages/SettingsProvider/res/values-sv/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Lagring av inställningar"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Ändringar i inställningarna för surfzon"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Frekvensbandet för surfzonen har ändrats."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Den här enheten har inte stöd för inställningen för att endast använda 5 GHz. I stället används 5 GHz när det är möjligt."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-sw/strings.xml b/packages/SettingsProvider/res/values-sw/strings.xml
index c244d8849ba6..4d05817ab9c1 100644
--- a/packages/SettingsProvider/res/values-sw/strings.xml
+++ b/packages/SettingsProvider/res/values-sw/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Hifadhi ya Mipangilio"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Mabadiliko kwenye mipangilio ya mtandaopepe"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Bendi ya mtandaopepe wako imebadilika."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Kifaa hiki hakitumii mapendeleo yako ya GHz 5 pekee. Badala yake, kifaa hiki kitatumia bendi ya GHz 5 itakapopatikana."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-ta/strings.xml b/packages/SettingsProvider/res/values-ta/strings.xml
index b26c875747df..f518a78a470e 100644
--- a/packages/SettingsProvider/res/values-ta/strings.xml
+++ b/packages/SettingsProvider/res/values-ta/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"அமைப்புகளின் சேமிப்பிடம்"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"உங்கள் ஹாட்ஸ்பாட் அமைப்புகளில் செய்யப்பட்டுள்ள மாற்றங்கள்"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"உங்கள் ஹாட்ஸ்பாட்டின் அலைவரிசை வரம்பு மாறிவிட்டது."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"இந்தச் சாதனத்தில், ’5GHz மட்டும்’ எனும் முன்னுரிமைத் தேர்வு ஆதரிக்கப்படவில்லை. எனினும் 5GHz அலைவரிசை வரம்பிற்குள் இருக்கும்போது சாதனம் அதைப் பயன்படுத்திக்கொள்ளும்."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-te/strings.xml b/packages/SettingsProvider/res/values-te/strings.xml
index 2a4971acd340..6c5922352ae9 100644
--- a/packages/SettingsProvider/res/values-te/strings.xml
+++ b/packages/SettingsProvider/res/values-te/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"సెట్టింగ్‌ల నిల్వ"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"మీ హాట్‌స్పాట్ సెట్టింగ్‌లకు మార్పులు"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"మీ హాట్‌స్పాట్ బ్యాండ్ మార్చబడింది."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"ఈ పరికరం 5GHz కోసం మాత్రమే మీ ప్రాధాన్యతకు మద్దతు ఇవ్వదు. బదులుగా, ఈ పరికరం అందుబాటులో ఉన్నప్పుడు 5GHz బ్యాండ్‌ను ఉపయోగిస్తుంది."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-th/strings.xml b/packages/SettingsProvider/res/values-th/strings.xml
index db47654cad86..4bf148f253be 100644
--- a/packages/SettingsProvider/res/values-th/strings.xml
+++ b/packages/SettingsProvider/res/values-th/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"ที่เก็บข้อมูลการตั้งค่า"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"มีการเปลี่ยนแปลงการตั้งค่าฮอตสปอต"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"ย่านความถี่ฮอตสปอตมีการเปลี่ยนแปลง"</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"อุปกรณ์นี้ไม่รองรับค่ากำหนดของคุณเฉพาะสำหรับ 5 GHz เท่านั้น และจะใช้ย่านความถี่ 5 GHz แทน เมื่อใช้ได้"</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-tl/strings.xml b/packages/SettingsProvider/res/values-tl/strings.xml
index 71c6266b98ca..2a36d5819600 100644
--- a/packages/SettingsProvider/res/values-tl/strings.xml
+++ b/packages/SettingsProvider/res/values-tl/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Storage ng Mga Setting"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Mga pagbabago sa mga setting ng iyong hotspot"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Nagbago ang band ng iyong hotspot."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Hindi sinusuportahan ng device na ito ang kagustuhan mong gumamit lang ng 5GHz. Sa halip, gagamitin ng device na ito ang 5GHz na band kapag available."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-tr/strings.xml b/packages/SettingsProvider/res/values-tr/strings.xml
index 4737a1ee9323..add1fdb098be 100644
--- a/packages/SettingsProvider/res/values-tr/strings.xml
+++ b/packages/SettingsProvider/res/values-tr/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Ayarlar Deposu"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Hotspot ayarlarınız değişti"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Hotspot bandınız değişti."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Bu cihaz yalnızca 5 GHz bandının kullanılmasına yönelik tercihinizi desteklemiyor. Bunun yerine, bu cihaz 5 GHz bandını mevcut olduğunda kullanacak."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-uk/strings.xml b/packages/SettingsProvider/res/values-uk/strings.xml
index 2c77c6a61d77..cd678bc41a14 100644
--- a/packages/SettingsProvider/res/values-uk/strings.xml
+++ b/packages/SettingsProvider/res/values-uk/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Сховище налаштувань"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Зміни в налаштуваннях точки доступу"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Діапазон частот точки доступу змінено."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"На цьому пристрої не підтримується налаштування \"Лише 5 ГГц\". Натомість буде використано діапазон частот 5 ГГц (якщо доступно)."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-ur/strings.xml b/packages/SettingsProvider/res/values-ur/strings.xml
index 31694e0ac3bc..2241ce9d12a4 100644
--- a/packages/SettingsProvider/res/values-ur/strings.xml
+++ b/packages/SettingsProvider/res/values-ur/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"ترتیبات کا اسٹوریج"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"اپنے ہاٹ اسپاٹ کی ترتیبات میں تبدیلیاں"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"آپ کا ہاٹ اسپات بینڈ تبدیل ہو گیا ہے۔"</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"‏یہ آلہ صرف 5GHz کے لیے آپ کی ترجیح کو سپورٹ نہیں کرے گا۔ بلکہ 5GHz بینڈ کے دستیاب ہونے پر اس کا استعمال کرے گا۔"</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-uz/strings.xml b/packages/SettingsProvider/res/values-uz/strings.xml
index 86a980ece898..a266bf0379f2 100644
--- a/packages/SettingsProvider/res/values-uz/strings.xml
+++ b/packages/SettingsProvider/res/values-uz/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Sozlamalar xotirasi"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Hotspot sozlamalari o‘zgartirildi"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Hotspot chastotasi oʻzgartirildi."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Qurilma faqat 5 GGs chastotada ishlay olmaydi. Bu chastotadan imkoniyatga qarab foydalaniladi."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-vi/strings.xml b/packages/SettingsProvider/res/values-vi/strings.xml
index 6476927bf320..74f93b28a60d 100644
--- a/packages/SettingsProvider/res/values-vi/strings.xml
+++ b/packages/SettingsProvider/res/values-vi/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Lưu trữ bộ nhớ"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Những thay đổi trong mục cài đặt điểm phát sóng của bạn"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Bằng tần của điểm phát sóng đã thay đổi."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Thiết bị này không hỗ trợ tùy chọn chỉ sử dụng băng tần 5 GHz. Thay vào đó, thiết bị này sẽ sử dụng băng tần 5 GHz khi có thể."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-zh-rCN/strings.xml b/packages/SettingsProvider/res/values-zh-rCN/strings.xml
index 13959127a772..95b15e0778bc 100644
--- a/packages/SettingsProvider/res/values-zh-rCN/strings.xml
+++ b/packages/SettingsProvider/res/values-zh-rCN/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"设置存储"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"您的热点设置已变更"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"您的热点频段已变更。"</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"此设备不支持您的偏好设置(仅限 5GHz),而且会在 5GHz 频段可用时使用该频段。"</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-zh-rHK/strings.xml b/packages/SettingsProvider/res/values-zh-rHK/strings.xml
index 284526402466..41ebe27bf52a 100644
--- a/packages/SettingsProvider/res/values-zh-rHK/strings.xml
+++ b/packages/SettingsProvider/res/values-zh-rHK/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"設定儲存空間"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"您的熱點設定變更"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"您的熱點頻段已變更。"</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"此裝置不支援只限 5 GHz 的偏好設定,但會在 5 GHz 頻段可用時採用。"</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-zh-rTW/strings.xml b/packages/SettingsProvider/res/values-zh-rTW/strings.xml
index 284526402466..d0a30f516862 100644
--- a/packages/SettingsProvider/res/values-zh-rTW/strings.xml
+++ b/packages/SettingsProvider/res/values-zh-rTW/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"設定儲存空間"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"無線基地台設定變更"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"你的無線基地台頻帶已變更。"</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"這部裝置不支援你的偏好設定 (僅限 5GHz),而是會在 5GHz 可用時使用該頻帶。"</string>
</resources>
diff --git a/packages/SettingsProvider/res/values-zu/strings.xml b/packages/SettingsProvider/res/values-zu/strings.xml
index 8c1d9e024099..0440b3b90533 100644
--- a/packages/SettingsProvider/res/values-zu/strings.xml
+++ b/packages/SettingsProvider/res/values-zu/strings.xml
@@ -20,10 +20,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"Izilungiselelo zesitoreji"</string>
- <!-- no translation found for wifi_softap_config_change (5338670993556993667) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (7600005249167787750) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_detailed (2504664754843959730) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5338670993556993667">"Ushintsho kuzilungiselelo zakho ze-hotspot"</string>
+ <string name="wifi_softap_config_change_summary" msgid="7600005249167787750">"Ibhendi yakho ye-hotspot ishintshile."</string>
+ <string name="wifi_softap_config_change_detailed" msgid="2504664754843959730">"Le divayisi ayisekeli okuncamelayo kwe-5GHz kuphela. Kunalokho, le divayisi izosebenzisa ibhendi ye-5GHz uma itholakala."</string>
</resources>
diff --git a/packages/SettingsProvider/res/values/defaults.xml b/packages/SettingsProvider/res/values/defaults.xml
index 21b3ba3d2548..c9e1944bd6f2 100644
--- a/packages/SettingsProvider/res/values/defaults.xml
+++ b/packages/SettingsProvider/res/values/defaults.xml
@@ -224,7 +224,7 @@
<bool name="def_charging_sounds_enabled">true</bool>
<!-- Default for Settings.Secure.NOTIFICATION_BUBBLES -->
- <bool name="def_notification_bubbles">false</bool>
+ <bool name="def_notification_bubbles">true</bool>
<!-- Default for Settings.Secure.AWARE_ENABLED -->
<bool name="def_aware_enabled">false</bool>
diff --git a/packages/SettingsProvider/src/android/provider/settings/backup/GlobalSettings.java b/packages/SettingsProvider/src/android/provider/settings/backup/GlobalSettings.java
index 1f687420a377..987e82ed0b2f 100644
--- a/packages/SettingsProvider/src/android/provider/settings/backup/GlobalSettings.java
+++ b/packages/SettingsProvider/src/android/provider/settings/backup/GlobalSettings.java
@@ -72,5 +72,6 @@ public class GlobalSettings {
Settings.Global.NOTIFICATION_BUBBLES,
Settings.Global.CUSTOM_BUGREPORT_HANDLER_APP,
Settings.Global.CUSTOM_BUGREPORT_HANDLER_USER,
+ Settings.Global.DEVELOPMENT_SETTINGS_ENABLED
};
}
diff --git a/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java b/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java
index 3b929b901e49..22d843b1dc90 100644
--- a/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java
+++ b/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java
@@ -142,6 +142,8 @@ public class SecureSettings {
Settings.Secure.LOCK_SCREEN_WHEN_TRUST_LOST,
Settings.Secure.SKIP_DIRECTION,
Settings.Secure.THEME_CUSTOMIZATION_OVERLAY_PACKAGES,
+ Settings.Secure.BACK_GESTURE_INSET_SCALE_LEFT,
+ Settings.Secure.BACK_GESTURE_INSET_SCALE_RIGHT,
Settings.Secure.NAVIGATION_MODE,
Settings.Secure.SKIP_GESTURE_COUNT,
Settings.Secure.SKIP_TOUCH_COUNT,
@@ -155,6 +157,7 @@ public class SecureSettings {
Settings.Secure.GLOBAL_ACTIONS_PANEL_ENABLED,
Settings.Secure.AWARE_LOCK_ENABLED,
Settings.Secure.AWARE_TAP_PAUSE_GESTURE_COUNT,
- Settings.Secure.AWARE_TAP_PAUSE_TOUCH_COUNT
+ Settings.Secure.AWARE_TAP_PAUSE_TOUCH_COUNT,
+ Settings.Secure.PEOPLE_STRIP,
};
}
diff --git a/packages/SettingsProvider/src/android/provider/settings/validators/GlobalSettingsValidators.java b/packages/SettingsProvider/src/android/provider/settings/validators/GlobalSettingsValidators.java
index 3d278db800a6..72923a3554ab 100644
--- a/packages/SettingsProvider/src/android/provider/settings/validators/GlobalSettingsValidators.java
+++ b/packages/SettingsProvider/src/android/provider/settings/validators/GlobalSettingsValidators.java
@@ -151,5 +151,6 @@ public class GlobalSettingsValidators {
VALIDATORS.put(Global.NOTIFICATION_BUBBLES, BOOLEAN_VALIDATOR);
VALIDATORS.put(Global.CUSTOM_BUGREPORT_HANDLER_APP, ANY_STRING_VALIDATOR);
VALIDATORS.put(Global.CUSTOM_BUGREPORT_HANDLER_USER, ANY_INTEGER_VALIDATOR);
+ VALIDATORS.put(Global.DEVELOPMENT_SETTINGS_ENABLED, BOOLEAN_VALIDATOR);
}
}
diff --git a/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java b/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java
index 090af9837db8..4b10557e34d9 100644
--- a/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java
+++ b/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java
@@ -216,6 +216,10 @@ public class SecureSettingsValidators {
VALIDATORS.put(Secure.THEME_CUSTOMIZATION_OVERLAY_PACKAGES, JSON_OBJECT_VALIDATOR);
VALIDATORS.put(
Secure.NAVIGATION_MODE, new DiscreteValueValidator(new String[] {"0", "1", "2"}));
+ VALIDATORS.put(Secure.BACK_GESTURE_INSET_SCALE_LEFT,
+ new InclusiveFloatRangeValidator(0.0f, Float.MAX_VALUE));
+ VALIDATORS.put(Secure.BACK_GESTURE_INSET_SCALE_RIGHT,
+ new InclusiveFloatRangeValidator(0.0f, Float.MAX_VALUE));
VALIDATORS.put(Secure.AWARE_ENABLED, BOOLEAN_VALIDATOR);
VALIDATORS.put(Secure.SKIP_GESTURE_COUNT, NON_NEGATIVE_INTEGER_VALIDATOR);
VALIDATORS.put(Secure.SKIP_TOUCH_COUNT, NON_NEGATIVE_INTEGER_VALIDATOR);
@@ -234,5 +238,6 @@ public class SecureSettingsValidators {
VALIDATORS.put(Secure.AWARE_LOCK_ENABLED, BOOLEAN_VALIDATOR);
VALIDATORS.put(Secure.DISPLAY_DENSITY_FORCED, NON_NEGATIVE_INTEGER_VALIDATOR);
VALIDATORS.put(Secure.TAP_GESTURE, BOOLEAN_VALIDATOR);
+ VALIDATORS.put(Secure.PEOPLE_STRIP, BOOLEAN_VALIDATOR);
}
}
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
index 202734566903..375a65044683 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
@@ -951,8 +951,7 @@ class DatabaseHelper extends SQLiteOpenHelper {
(1 << AudioManager.STREAM_NOTIFICATION) |
(1 << AudioManager.STREAM_SYSTEM) |
(1 << AudioManager.STREAM_SYSTEM_ENFORCED);
- if (!mContext.getResources().getBoolean(
- com.android.internal.R.bool.config_voice_capable)) {
+ if (!getTelephonyManager().isVoiceCapable()) {
ringerModeAffectedStreams |= (1 << AudioManager.STREAM_MUSIC);
}
db.execSQL("DELETE FROM system WHERE name='"
@@ -2548,7 +2547,7 @@ class DatabaseHelper extends SQLiteOpenHelper {
StringBuilder val = new StringBuilder();
List<Integer> defaultNetworks = TelephonyProperties.default_network();
int phoneCount = 1;
- TelephonyManager telephonyManager = mContext.getSystemService(TelephonyManager.class);
+ TelephonyManager telephonyManager = getTelephonyManager();
if (telephonyManager != null) {
phoneCount = telephonyManager.getSupportedModemCount();
}
@@ -2663,4 +2662,8 @@ class DatabaseHelper extends SQLiteOpenHelper {
private String getDefaultDeviceName() {
return mContext.getResources().getString(R.string.def_device_name_simple, Build.MODEL);
}
+
+ private TelephonyManager getTelephonyManager() {
+ return (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
+ }
}
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java
index 443288cfe492..c19a340498e7 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java
@@ -28,7 +28,7 @@ import android.database.Cursor;
import android.net.NetworkPolicy;
import android.net.NetworkPolicyManager;
import android.net.Uri;
-import android.net.wifi.WifiConfiguration;
+import android.net.wifi.SoftApConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.ParcelFileDescriptor;
@@ -875,32 +875,23 @@ public class SettingsBackupAgent extends BackupAgentHelper {
}
private byte[] getSoftAPConfiguration() {
- try {
- return mWifiManager.getWifiApConfiguration().getBytesForBackup();
- } catch (IOException ioe) {
- Log.e(TAG, "Failed to marshal SoftAPConfiguration" + ioe.getMessage());
- return new byte[0];
- }
+ return mWifiManager.retrieveSoftApBackupData();
}
private void restoreSoftApConfiguration(byte[] data) {
- try {
- WifiConfiguration config = WifiConfiguration
- .getWifiConfigFromBackup(new DataInputStream(new ByteArrayInputStream(data)));
- if (DEBUG) Log.d(TAG, "Successfully unMarshaled WifiConfiguration ");
- int originalApBand = config.apBand;
- mWifiManager.setWifiApConfiguration(config);
+ SoftApConfiguration config = mWifiManager.restoreSoftApBackupData(data);
+ if (config != null) {
+ int originalApBand = config.getBand();
+ if (DEBUG) Log.d(TAG, "Successfully unMarshaled SoftApConfiguration ");
// Depending on device hardware, we may need to notify the user of a setting change for
// the apBand preference
boolean dualMode = mWifiManager.isDualModeSupported();
- int storedApBand = mWifiManager.getWifiApConfiguration().apBand;
+ int storedApBand = mWifiManager.getSoftApConfiguration().getBand();
if (dualMode && storedApBand != originalApBand) {
Log.d(TAG, "restored ap configuration requires a conversion, notify the user");
WifiSoftApBandChangedNotifier.notifyUserOfApBandConversion(this);
}
- } catch (IOException | BackupUtils.BadVersionException e) {
- Log.e(TAG, "Failed to unMarshal SoftAPConfiguration " + e.getMessage());
}
}
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
index 0a2dd3826822..016896f52a75 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
@@ -691,6 +691,9 @@ class SettingsProtoDumpUtil {
dumpRepeatedSetting(s, p,
Settings.Global.ERROR_LOGCAT_PREFIX,
GlobalSettingsProto.ERROR_LOGCAT_LINES);
+ dumpRepeatedSetting(s, p,
+ Settings.Global.MAX_ERROR_BYTES_PREFIX,
+ GlobalSettingsProto.MAX_ERROR_BYTES);
final long euiccToken = p.start(GlobalSettingsProto.EUICC);
dumpSetting(s, p,
@@ -2188,6 +2191,14 @@ class SettingsProtoDumpUtil {
Settings.Secure.NAVIGATION_MODE,
SecureSettingsProto.NAVIGATION_MODE);
+ dumpSetting(s, p,
+ Settings.Secure.BACK_GESTURE_INSET_SCALE_LEFT,
+ SecureSettingsProto.GestureNavigation.BACK_GESTURE_INSET_SCALE_LEFT);
+
+ dumpSetting(s, p,
+ Settings.Secure.BACK_GESTURE_INSET_SCALE_RIGHT,
+ SecureSettingsProto.GestureNavigation.BACK_GESTURE_INSET_SCALE_RIGHT);
+
final long nfcPaymentToken = p.start(SecureSettingsProto.NFC_PAYMENT);
dumpSetting(s, p,
Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
index 93a140730ee2..4309c8030dbd 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
@@ -3264,7 +3264,7 @@ public class SettingsProvider extends ContentProvider {
}
private final class UpgradeController {
- private static final int SETTINGS_VERSION = 184;
+ private static final int SETTINGS_VERSION = 185;
private final int mUserId;
@@ -4446,20 +4446,15 @@ public class SettingsProvider extends ContentProvider {
}
if (currentVersion == 182) {
- // Remove secure bubble settings.
+ // Remove secure bubble settings; it's in global now.
getSecureSettingsLocked(userId).deleteSettingLocked("notification_bubbles");
- // Add global bubble settings.
- getGlobalSettingsLocked().insertSettingLocked(Global.NOTIFICATION_BUBBLES,
- getContext().getResources().getBoolean(
- R.bool.def_notification_bubbles) ? "1" : "0", null /* tag */,
- true /* makeDefault */, SettingsState.SYSTEM_PACKAGE_NAME);
-
+ // Removed. Updated NOTIFICATION_BUBBLES to be true by default, see 184.
currentVersion = 183;
}
if (currentVersion == 183) {
- // Version 184: Set default values for WIRELESS_CHARGING_STARTED_SOUND
+ // Version 183: Set default values for WIRELESS_CHARGING_STARTED_SOUND
// and CHARGING_STARTED_SOUND
final SettingsState globalSettings = getGlobalSettingsLocked();
@@ -4500,6 +4495,18 @@ public class SettingsProvider extends ContentProvider {
currentVersion = 184;
}
+ if (currentVersion == 184) {
+ // Version 184: Reset the default for Global Settings: NOTIFICATION_BUBBLES
+ // This is originally set in version 182, however, the default value changed
+ // so this step is to ensure the value is updated to the correct default.
+ getGlobalSettingsLocked().insertSettingLocked(Global.NOTIFICATION_BUBBLES,
+ getContext().getResources().getBoolean(
+ R.bool.def_notification_bubbles) ? "1" : "0", null /* tag */,
+ true /* makeDefault */, SettingsState.SYSTEM_PACKAGE_NAME);
+
+ currentVersion = 185;
+ }
+
// vXXX: Add new settings above this point.
if (currentVersion != newVersion) {
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java
index 4731e6894baf..086b20facb46 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java
@@ -62,6 +62,8 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -766,6 +768,23 @@ final class SettingsState {
}
} catch (Throwable t) {
Slog.wtf(LOG_TAG, "Failed to write settings, restoring backup", t);
+ if (t instanceof IOException) {
+ // we failed to create a directory, so log the permissions and existence
+ // state for the settings file and directory
+ logSettingsDirectoryInformation(destination.getBaseFile());
+ if (t.getMessage().contains("Couldn't create directory")) {
+ // attempt to create the directory with Files.createDirectories, which
+ // throws more informative errors than File.mkdirs.
+ Path parentPath = destination.getBaseFile().getParentFile().toPath();
+ try {
+ Files.createDirectories(parentPath);
+ Slog.i(LOG_TAG, "Successfully created " + parentPath);
+ } catch (Throwable t2) {
+ Slog.e(LOG_TAG, "Failed to write " + parentPath
+ + " with Files.writeDirectories", t2);
+ }
+ }
+ }
destination.failWrite(out);
} finally {
IoUtils.closeQuietly(out);
@@ -779,6 +798,33 @@ final class SettingsState {
}
}
+ private static void logSettingsDirectoryInformation(File settingsFile) {
+ File parent = settingsFile.getParentFile();
+ Slog.i(LOG_TAG, "directory info for directory/file " + settingsFile
+ + " with stacktrace ", new Exception());
+ File ancestorDir = parent;
+ while (ancestorDir != null) {
+ if (!ancestorDir.exists()) {
+ Slog.i(LOG_TAG, "ancestor directory " + ancestorDir
+ + " does not exist");
+ ancestorDir = ancestorDir.getParentFile();
+ } else {
+ Slog.i(LOG_TAG, "ancestor directory " + ancestorDir
+ + " exists");
+ Slog.i(LOG_TAG, "ancestor directory " + ancestorDir
+ + " permissions: r: " + ancestorDir.canRead() + " w: "
+ + ancestorDir.canWrite() + " x: " + ancestorDir.canExecute());
+ File ancestorParent = ancestorDir.getParentFile();
+ if (ancestorParent != null) {
+ Slog.i(LOG_TAG, "ancestor's parent directory " + ancestorParent
+ + " permissions: r: " + ancestorParent.canRead() + " w: "
+ + ancestorParent.canWrite() + " x: " + ancestorParent.canExecute());
+ }
+ break;
+ }
+ }
+ }
+
static void writeSingleSetting(int version, XmlSerializer serializer, String id,
String name, String value, String defaultValue, String packageName,
String tag, boolean defaultSysSet) throws IOException {
@@ -853,6 +899,7 @@ final class SettingsState {
in = new AtomicFile(mStatePersistFile).openRead();
} catch (FileNotFoundException fnfe) {
Slog.i(LOG_TAG, "No settings state " + mStatePersistFile);
+ logSettingsDirectoryInformation(mStatePersistFile);
addHistoricalOperationLocked(HISTORICAL_OPERATION_INITIALIZE, null);
return;
}
diff --git a/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java b/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java
index c23a494d3312..19ff2444e6ca 100644
--- a/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java
+++ b/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java
@@ -215,7 +215,6 @@ public class SettingsBackupTest {
Settings.Global.DEFAULT_DNS_SERVER,
Settings.Global.DEFAULT_INSTALL_LOCATION,
Settings.Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
- Settings.Global.DEFAULT_USER_ID_TO_BOOT_INTO,
Settings.Global.DESK_DOCK_SOUND,
Settings.Global.DESK_UNDOCK_SOUND,
Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT,
@@ -223,7 +222,6 @@ public class SettingsBackupTest {
Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES,
Settings.Global.DEVELOPMENT_FORCE_RTL,
Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM,
- Settings.Global.DEVELOPMENT_SETTINGS_ENABLED,
Settings.Global.DEVICE_DEMO_MODE,
Settings.Global.DEVICE_IDLE_CONSTANTS,
Settings.Global.BATTERY_SAVER_ADAPTIVE_CONSTANTS,
@@ -324,6 +322,7 @@ public class SettingsBackupTest {
Settings.Global.LOW_POWER_MODE_SUGGESTION_PARAMS,
Settings.Global.LTE_SERVICE_FORCED,
Settings.Global.LID_BEHAVIOR,
+ Settings.Global.MAX_ERROR_BYTES_PREFIX,
Settings.Global.MAX_NOTIFICATION_ENQUEUE_RATE,
Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
Settings.Global.MDC_INITIAL_MAX_RETRY,
@@ -734,7 +733,8 @@ public class SettingsBackupTest {
Settings.Secure.DOZE_WAKE_LOCK_SCREEN_GESTURE,
Settings.Secure.DOZE_WAKE_DISPLAY_GESTURE,
Settings.Secure.FACE_UNLOCK_RE_ENROLL,
- Settings.Secure.TAP_GESTURE);
+ Settings.Secure.TAP_GESTURE,
+ Settings.Secure.WINDOW_MAGNIFICATION);
@Test
public void systemSettingsBackedUpOrBlacklisted() {
diff --git a/packages/Shell/AndroidManifest.xml b/packages/Shell/AndroidManifest.xml
index b89f1412c6a6..aefdce48d989 100644
--- a/packages/Shell/AndroidManifest.xml
+++ b/packages/Shell/AndroidManifest.xml
@@ -224,6 +224,12 @@
<!-- Permission requried for CTS test - CellBroadcastIntentsTest -->
<uses-permission android:name="android.permission.GRANT_RUNTIME_PERMISSIONS_TO_TELEPHONY_DEFAULTS"/>
+ <!-- Permission required for CTS test - TetheringManagerTest -->
+ <uses-permission android:name="android.permission.TETHER_PRIVILEGED"/>
+
+ <!-- Permission required for CTS test - CtsOsTestCases -->
+ <uses-permission android:name="android.permission.MANAGE_CRATES"/>
+
<application android:label="@string/app_label"
android:theme="@android:style/Theme.DeviceDefault.DayNight"
android:defaultToDeviceProtectedStorage="true"
diff --git a/packages/SoundPicker/src/com/android/soundpicker/RingtoneOverlayService.java b/packages/SoundPicker/src/com/android/soundpicker/RingtoneOverlayService.java
index 2d37b4c9c342..15fd1f7f4957 100644
--- a/packages/SoundPicker/src/com/android/soundpicker/RingtoneOverlayService.java
+++ b/packages/SoundPicker/src/com/android/soundpicker/RingtoneOverlayService.java
@@ -101,7 +101,7 @@ public class RingtoneOverlayService extends Service {
}
private Uri scanFile(@NonNull final File file) {
- return MediaStore.scanFile(this, file);
+ return MediaStore.scanFile(getContentResolver(), file);
}
private void set(@NonNull final String name, @NonNull final Uri uri) {
diff --git a/packages/SystemUI/Android.bp b/packages/SystemUI/Android.bp
index 2a5bdc75361d..4fb3be2d588f 100644
--- a/packages/SystemUI/Android.bp
+++ b/packages/SystemUI/Android.bp
@@ -80,7 +80,7 @@ android_library {
filegroup {
name: "SystemUI-tests-utils",
srcs: [
- "tests/src/com/android/systemui/statusbar/NotificationEntryBuilder.java",
+ "tests/src/com/android/systemui/statusbar/notification/collection/NotificationEntryBuilder.java",
"tests/src/com/android/systemui/statusbar/RankingBuilder.java",
"tests/src/com/android/systemui/statusbar/SbnBuilder.java",
],
@@ -127,7 +127,7 @@ android_library {
"SystemUI-proto",
"metrics-helper-lib",
"androidx.test.rules", "hamcrest-library",
- "mockito-target-inline-minus-junit4",
+ "mockito-target-extended-minus-junit4",
"testables",
"truth-prebuilt",
"dagger2-2.19",
@@ -154,7 +154,7 @@ android_app {
resource_dirs: [],
platform_apis: true,
- product_specific: true,
+ system_ext_specific: true,
certificate: "platform",
privileged: true,
diff --git a/packages/SystemUI/AndroidManifest.xml b/packages/SystemUI/AndroidManifest.xml
index 6f6803817138..2a1e74e18fb7 100644
--- a/packages/SystemUI/AndroidManifest.xml
+++ b/packages/SystemUI/AndroidManifest.xml
@@ -28,11 +28,6 @@
android:glEsVersion="0x00020000"
android:required="true" />
- <!-- SysUI must be the one to define this permission; its name is
- referenced by the core OS. -->
- <permission android:name="android.permission.systemui.IDENTITY"
- android:protectionLevel="signature" />
-
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- Used to read wallpaper -->
@@ -179,6 +174,9 @@
<!-- Adding Quick Settings tiles -->
<uses-permission android:name="android.permission.BIND_QUICK_SETTINGS_TILE" />
+ <!-- Adding Controls to SystemUI -->
+ <uses-permission android:name="android.permission.BIND_CONTROLS" />
+
<!-- Quick Settings tile: Night Mode / Dark Theme -->
<uses-permission android:name="android.permission.MODIFY_DAY_NIGHT_MODE" />
@@ -325,6 +323,14 @@
android:permission="android.permission.BIND_WALLPAPER"
android:exported="true" />
+ <activity
+ android:name=".bubbles.BubbleOverflowActivity"
+ android:theme="@style/BubbleOverflow"
+ android:excludeFromRecents="true"
+ android:documentLaunchMode="always"
+ android:resizeableActivity="true">
+ </activity>
+
<activity android:name=".tuner.TunerActivity"
android:enabled="false"
android:icon="@drawable/tuner"
diff --git a/packages/SystemUI/CleanSpec.mk b/packages/SystemUI/CleanSpec.mk
new file mode 100644
index 000000000000..2a2e4e44e834
--- /dev/null
+++ b/packages/SystemUI/CleanSpec.mk
@@ -0,0 +1,50 @@
+# Copyright (C) 2019 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.
+#
+
+# If you don't need to do a full clean build but would like to touch
+# a file or delete some intermediate files, add a clean step to the end
+# of the list. These steps will only be run once, if they haven't been
+# run before.
+#
+# E.g.:
+# $(call add-clean-step, touch -c external/sqlite/sqlite3.h)
+# $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/STATIC_LIBRARIES/libz_intermediates)
+#
+# Always use "touch -c" and "rm -f" or "rm -rf" to gracefully deal with
+# files that are missing or have been moved.
+#
+# Use $(PRODUCT_OUT) to get to the "out/target/product/blah/" directory.
+# Use $(OUT_DIR) to refer to the "out" directory.
+#
+# If you need to re-do something that's already mentioned, just copy
+# the command and add it to the bottom of the list. E.g., if a change
+# that you made last week required touching a file and a change you
+# made today requires touching the same file, just copy the old
+# touch step and add it to the end of the list.
+#
+# *****************************************************************
+# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST ABOVE THE BANNER
+# *****************************************************************
+
+# For example:
+#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/AndroidTests_intermediates)
+#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/core_intermediates)
+#$(call add-clean-step, find $(OUT_DIR) -type f -name "IGTalkSession*" -print0 | xargs -0 rm -f)
+#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/data/*)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/product/priv-app/SystemUI)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/product/priv-app/SystemUI)
+# ******************************************************************
+# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST ABOVE THIS BANNER
+# ******************************************************************
diff --git a/packages/SystemUI/plugin_core/Android.bp b/packages/SystemUI/plugin_core/Android.bp
index 42d67620b81d..581fef721acc 100644
--- a/packages/SystemUI/plugin_core/Android.bp
+++ b/packages/SystemUI/plugin_core/Android.bp
@@ -16,4 +16,8 @@ java_library {
sdk_version: "current",
name: "PluginCoreLib",
srcs: ["src/**/*.java"],
+
+ // Enforce that the library is built against java 8 so that there are
+ // no compatibility issues with launcher
+ java_version: "1.8",
}
diff --git a/packages/SystemUI/res/drawable-xhdpi/tv_card_gradient_protection.png b/packages/SystemUI/res/drawable-xhdpi/tv_card_gradient_protection.png
deleted file mode 100644
index 135dabb63069..000000000000
--- a/packages/SystemUI/res/drawable-xhdpi/tv_card_gradient_protection.png
+++ /dev/null
Binary files differ
diff --git a/packages/SystemUI/res/drawable/ic_control_magnification_grey.xml b/packages/SystemUI/res/drawable/ic_control_magnification_grey.xml
new file mode 100644
index 000000000000..80ce8c110041
--- /dev/null
+++ b/packages/SystemUI/res/drawable/ic_control_magnification_grey.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ Copyright (C) 2019 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.
+-->
+
+<vector android:height="96dp" android:viewportHeight="24"
+ android:viewportWidth="24" android:width="96dp" xmlns:android="http://schemas.android.com/apk/res/android">
+ <path android:fillColor="#757575" android:pathData="M15.54,5.54L13.77,7.3 12,5.54 10.23,7.3 8.46,5.54 12,2zM18.46,15.54l-1.76,-1.77L18.46,12l-1.76,-1.77 1.76,-1.77L22,12zM8.46,18.46l1.77,-1.76L12,18.46l1.77,-1.76 1.77,1.76L12,22zM5.54,8.46l1.76,1.77L5.54,12l1.76,1.77 -1.76,1.77L2,12z"/>
+ <path android:fillColor="#757575" android:pathData="M12,12m-3,0a3,3 0,1 1,6 0a3,3 0,1 1,-6 0"/>
+</vector>
diff --git a/packages/SystemUI/res/drawable/tv_bg_item_app_info.xml b/packages/SystemUI/res/drawable/tv_circle_dark.xml
index 1bbb8c3e8ef0..d1ba8e71ec31 100644
--- a/packages/SystemUI/res/drawable/tv_bg_item_app_info.xml
+++ b/packages/SystemUI/res/drawable/tv_circle_dark.xml
@@ -16,7 +16,9 @@
-->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
- android:shape="rectangle">
- <corners android:radius="24dp"/>
- <solid android:color="@color/tv_audio_recording_bar_chip_background"/>
-</shape>
+ android:shape="oval">
+
+ <solid
+ android:color="@color/tv_audio_recording_indicator_background" />
+
+</shape> \ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/circle_red.xml b/packages/SystemUI/res/drawable/tv_circle_white_translucent.xml
index fd3c125e5ab8..55d21de00ca3 100644
--- a/packages/SystemUI/res/drawable/circle_red.xml
+++ b/packages/SystemUI/res/drawable/tv_circle_white_translucent.xml
@@ -16,6 +16,9 @@
-->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
- android:shape="oval">
- <solid android:color="@color/red"/>
+ android:shape="oval">
+
+ <solid
+ android:color="@color/tv_audio_recording_indicator_pulse" />
+
</shape> \ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/tv_ic_mic_white.xml b/packages/SystemUI/res/drawable/tv_ic_mic_white.xml
index 1bea8a19c8b9..d887113c7717 100644
--- a/packages/SystemUI/res/drawable/tv_ic_mic_white.xml
+++ b/packages/SystemUI/res/drawable/tv_ic_mic_white.xml
@@ -1,25 +1,27 @@
-<?xml version="1.0" encoding="utf-8"?>
<!--
- ~ Copyright (C) 2019 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
- -->
+Copyright (C) 2019 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.
+-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
- android:viewportWidth="44"
- android:viewportHeight="44"
- android:width="44dp"
- android:height="44dp">
- <path
- android:pathData="M22 25.6666667C25.0433333 25.6666667 27.4816667 23.21 27.4816667 20.1666667L27.5 9.16666667C27.5 6.12333333 25.0433333 3.66666667 22 3.66666667C18.9566667 3.66666667 16.5 6.12333333 16.5 9.16666667L16.5 20.1666667C16.5 23.21 18.9566667 25.6666667 22 25.6666667ZM31.7166667 20.1666667C31.7166667 25.6666667 27.06 29.5166667 22 29.5166667C16.94 29.5166667 12.2833333 25.6666667 12.2833333 20.1666667L9.16666667 20.1666667C9.16666667 26.4183333 14.1533333 31.5883333 20.1666667 32.4866667L20.1666667 38.5L23.8333333 38.5L23.8333333 32.4866667C29.8466667 31.6066667 34.8333333 26.4366667 34.8333333 20.1666667L31.7166667 20.1666667Z"
- android:fillColor="@android:color/white" />
+ android:width="32dp"
+ android:height="32dp"
+ android:viewportWidth="24.0"
+ android:viewportHeight="24.0">
+ <path
+ android:fillColor="#FFFFFFFF"
+ android:pathData="M12,14c1.66,0 3,-1.34 3,-3V5c0,-1.66 -1.34,-3 -3,-3S9,3.34 9,5v6C9,12.66 10.34,14 12,14zM11,5c0,-0.55 0.45,-1 1,-1s1,0.45 1,1v6c0,0.55 -0.45,1 -1,1s-1,-0.45 -1,-1V5z"/>
+ <path
+ android:fillColor="#FFFFFFFF"
+ android:pathData="M17,11c0,2.76 -2.24,5 -5,5s-5,-2.24 -5,-5H5c0,3.53 2.61,6.43 6,6.92V21h2v-3.08c3.39,-0.49 6,-3.39 6,-6.92H17z"/>
</vector> \ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/tv_rect_dark_left_rounded.xml b/packages/SystemUI/res/drawable/tv_rect_dark_left_rounded.xml
new file mode 100644
index 000000000000..9b48a70d9439
--- /dev/null
+++ b/packages/SystemUI/res/drawable/tv_rect_dark_left_rounded.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2019 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.
+ -->
+
+<shape xmlns:android="http://schemas.android.com/apk/res/android"
+ android:shape="rectangle">
+
+ <corners
+ android:bottomLeftRadius="8dp"
+ android:topLeftRadius="8dp" />
+ <solid android:color="@color/tv_audio_recording_indicator_background" />
+
+</shape> \ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/tv_rect_dark_right_rounded.xml b/packages/SystemUI/res/drawable/tv_rect_dark_right_rounded.xml
new file mode 100644
index 000000000000..03348756231b
--- /dev/null
+++ b/packages/SystemUI/res/drawable/tv_rect_dark_right_rounded.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2019 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.
+ -->
+
+<shape xmlns:android="http://schemas.android.com/apk/res/android"
+ android:shape="rectangle">
+
+ <corners
+ android:bottomRightRadius="8dp"
+ android:topRightRadius="8dp" />
+ <solid android:color="@color/tv_audio_recording_indicator_background" />
+
+</shape> \ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/tv_gradient_protection.xml b/packages/SystemUI/res/drawable/tv_ring_white.xml
index ee5cbc7e6ba0..0f7cc1082f71 100644
--- a/packages/SystemUI/res/drawable/tv_gradient_protection.xml
+++ b/packages/SystemUI/res/drawable/tv_ring_white.xml
@@ -15,8 +15,11 @@
~ limitations under the License.
-->
-<!-- gradient protection for cards -->
-<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
- android:src="@drawable/tv_card_gradient_protection"
- android:tileMode="repeat"
-/>
+<shape xmlns:android="http://schemas.android.com/apk/res/android"
+ android:shape="oval">
+
+ <stroke
+ android:width="1dp"
+ android:color="@android:color/white" />
+
+</shape> \ No newline at end of file
diff --git a/packages/SystemUI/res/layout/bubble_overflow_activity.xml b/packages/SystemUI/res/layout/bubble_overflow_activity.xml
new file mode 100644
index 000000000000..4cee74615bd2
--- /dev/null
+++ b/packages/SystemUI/res/layout/bubble_overflow_activity.xml
@@ -0,0 +1,20 @@
+<!--
+ ~ Copyright (C) 2019 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
+ -->
+<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/bubble_overflow_recycler"
+ android:scrollbars="vertical"
+ android:layout_width="wrap_content"
+ android:layout_height="match_parent"/>
diff --git a/packages/SystemUI/res/layout/magnifier_controllers.xml b/packages/SystemUI/res/layout/magnifier_controllers.xml
new file mode 100644
index 000000000000..0203cd4f506b
--- /dev/null
+++ b/packages/SystemUI/res/layout/magnifier_controllers.xml
@@ -0,0 +1,65 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2019 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.
+ -->
+
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="@dimen/magnification_controls_size"
+ android:layout_alignParentBottom="true"
+ android:layout_alignParentEnd="true"
+ android:layout_height="@dimen/magnification_controls_size"
+ android:gravity="center">
+
+ <RelativeLayout
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content">
+
+ <ImageView
+ android:focusable="true"
+ android:id="@+id/controller"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:src="@drawable/ic_control_magnification_grey" />
+
+ <View
+ android:id="@+id/left_control"
+ android:layout_width="@dimen/magnifier_left_right_controls_width"
+ android:layout_height="@dimen/magnifier_left_right_controls_height"
+ android:layout_alignLeft="@+id/controller"
+ android:layout_centerVertical="true" />
+
+ <View
+ android:id="@+id/up_control"
+ android:layout_width="@dimen/magnifier_up_down_controls_width"
+ android:layout_height="@dimen/magnifier_up_down_controls_height"
+ android:layout_alignTop="@+id/controller"
+ android:layout_centerHorizontal="true" />
+
+ <View
+ android:id="@+id/right_control"
+ android:layout_width="@dimen/magnifier_left_right_controls_width"
+ android:layout_height="@dimen/magnifier_left_right_controls_height"
+ android:layout_alignRight="@+id/controller"
+ android:layout_centerVertical="true" />
+
+ <View
+ android:id="@+id/down_control"
+ android:layout_width="@dimen/magnifier_up_down_controls_width"
+ android:layout_height="@dimen/magnifier_up_down_controls_height"
+ android:layout_alignBottom="@+id/controller"
+ android:layout_centerHorizontal="true" />
+ </RelativeLayout>
+
+</FrameLayout>
diff --git a/packages/SystemUI/res/layout/tv_audio_recording_indicator.xml b/packages/SystemUI/res/layout/tv_audio_recording_indicator.xml
new file mode 100644
index 000000000000..f04226e7ceaf
--- /dev/null
+++ b/packages/SystemUI/res/layout/tv_audio_recording_indicator.xml
@@ -0,0 +1,121 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2019 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.
+ -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal"
+ android:padding="32dp">
+
+ <FrameLayout
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content">
+
+ <LinearLayout
+ android:id="@+id/icon_texts_container"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal">
+
+ <FrameLayout
+ android:layout_width="90dp"
+ android:layout_height="94dp">
+
+ <View
+ android:id="@+id/icon_container_bg"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:background="@drawable/tv_rect_dark_left_rounded"/>
+
+ <FrameLayout
+ android:id="@+id/icon_mic"
+ android:layout_width="70dp"
+ android:layout_height="70dp"
+ android:layout_marginLeft="12dp"
+ android:layout_marginTop="12dp"
+ android:layout_marginRight="8dp"
+ android:layout_marginBottom="12dp">
+
+ <View
+ android:layout_width="54dp"
+ android:layout_height="54dp"
+ android:layout_gravity="center"
+ android:background="@drawable/tv_circle_dark"/>
+
+ <ImageView
+ android:id="@+id/pulsating_circle"
+ android:layout_width="54dp"
+ android:layout_height="54dp"
+ android:layout_gravity="center"
+ android:background="@drawable/tv_circle_white_translucent"/>
+
+ <ImageView
+ android:layout_width="54dp"
+ android:layout_height="54dp"
+ android:layout_gravity="center"
+ android:src="@drawable/tv_ring_white"/>
+
+ <ImageView
+ android:layout_width="32dp"
+ android:layout_height="32dp"
+ android:layout_gravity="center"
+ android:background="@drawable/tv_ic_mic_white"/>
+ </FrameLayout>
+
+ </FrameLayout>
+
+ <LinearLayout
+ android:id="@+id/texts_container"
+ android:layout_width="wrap_content"
+ android:layout_height="94dp"
+ android:background="@color/tv_audio_recording_indicator_background"
+ android:gravity="center_vertical"
+ android:orientation="vertical"
+ android:visibility="visible">
+
+ <TextView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="@string/mic_active"
+ android:textColor="@android:color/white"
+ android:fontFamily="sans-serif"
+ android:textSize="20dp"/>
+
+ <TextView
+ android:id="@+id/text"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:singleLine="true"
+ android:text="SomeApplication accessed your microphone"
+ android:textColor="@android:color/white"
+ android:fontFamily="sans-serif"
+ android:textSize="16dp"/>
+
+ </LinearLayout>
+
+ </LinearLayout>
+
+ </FrameLayout>
+
+ <View
+ android:id="@+id/bg_right"
+ android:layout_width="24dp"
+ android:layout_height="94dp"
+ android:background="@drawable/tv_rect_dark_right_rounded"
+ android:visibility="visible"/>
+
+</LinearLayout>
diff --git a/packages/SystemUI/res/layout/tv_item_app_info.xml b/packages/SystemUI/res/layout/tv_item_app_info.xml
deleted file mode 100644
index b40589ec80c6..000000000000
--- a/packages/SystemUI/res/layout/tv_item_app_info.xml
+++ /dev/null
@@ -1,41 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- ~ Copyright (C) 2019 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.
- -->
-
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="horizontal"
- android:layout_width="wrap_content"
- android:layout_height="48dp"
- android:layout_marginLeft="8dp"
- android:paddingHorizontal="12dp"
- android:gravity="center_vertical"
- android:background="@drawable/tv_bg_item_app_info">
-
- <ImageView
- android:id="@+id/icon"
- android:layout_width="24dp"
- android:layout_height="24dp"
- android:layout_marginRight="8dp"/>
-
- <TextView
- android:id="@+id/title"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textColor="@color/tv_audio_recording_bar_text"
- android:fontFamily="sans-serif"
- android:textSize="14sp"/>
-
-</LinearLayout>
diff --git a/packages/SystemUI/res/layout/tv_status_bar_audio_recording.xml b/packages/SystemUI/res/layout/tv_status_bar_audio_recording.xml
deleted file mode 100644
index b9dffbb4de20..000000000000
--- a/packages/SystemUI/res/layout/tv_status_bar_audio_recording.xml
+++ /dev/null
@@ -1,63 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- ~ Copyright (C) 2019 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.
- -->
-
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_gravity="bottom"
- android:orientation="vertical">
-
- <!-- Gradient Protector -->
- <View
- android:layout_width="match_parent"
- android:layout_height="102.5dp"
- android:background="@drawable/tv_gradient_protection"/>
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="72dp"
- android:background="@color/tv_audio_recording_bar_background"
- android:gravity="center_vertical"
- android:orientation="horizontal">
-
- <ImageView
- android:layout_width="48dp"
- android:layout_height="48dp"
- android:layout_marginLeft="42dp"
- android:layout_marginVertical="12dp"
- android:padding="8dp"
- android:background="@drawable/circle_red"
- android:scaleType="centerInside"
- android:src="@drawable/tv_ic_mic_white"/>
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginLeft="24dp"
- android:text="Audio recording by"
- android:textColor="@color/tv_audio_recording_bar_text"
- android:fontFamily="sans-serif"
- android:textSize="14sp"/>
-
- <LinearLayout
- android:id="@+id/container"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"/>
-
- </LinearLayout>
-
-</LinearLayout>
diff --git a/packages/SystemUI/res/layout/window_magnifier_view.xml b/packages/SystemUI/res/layout/window_magnifier_view.xml
new file mode 100644
index 000000000000..f8186129f111
--- /dev/null
+++ b/packages/SystemUI/res/layout/window_magnifier_view.xml
@@ -0,0 +1,71 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2019 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.
+ -->
+
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content">
+
+ <SurfaceView
+ android:layout_marginStart="@dimen/magnification_border_size"
+ android:layout_marginTop="@dimen/magnification_border_size"
+ android:id="@+id/surface_view"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent" />
+
+ <RelativeLayout
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="vertical">
+
+ <View
+ android:id="@+id/left_handle"
+ android:layout_width="@dimen/magnification_border_size"
+ android:layout_height="match_parent"
+ android:layout_above="@+id/drag_handle"
+ android:background="@color/magnification_border_color" />
+
+ <View
+ android:id="@+id/top_handle"
+ android:layout_width="match_parent"
+ android:layout_height="@dimen/magnification_border_size"
+ android:background="@color/magnification_border_color" />
+
+ <View
+ android:id="@+id/right_handle"
+ android:layout_width="@dimen/magnification_border_size"
+ android:layout_height="match_parent"
+ android:layout_above="@+id/drag_handle"
+ android:layout_alignParentEnd="true"
+ android:background="@color/magnification_border_color" />
+
+ <View
+ android:id="@+id/bottom_handle"
+ android:layout_width="match_parent"
+ android:layout_height="@dimen/magnification_border_size"
+ android:layout_above="@+id/drag_handle"
+ android:background="@color/magnification_border_color" />
+
+ <View
+ android:id="@+id/drag_handle"
+ android:layout_width="@dimen/magnification_drag_view_width"
+ android:layout_height="@dimen/magnification_drag_view_height"
+ android:layout_alignParentBottom="true"
+ android:layout_centerHorizontal="true"
+ android:background="@color/magnification_border_color" />
+
+ </RelativeLayout>
+</FrameLayout> \ No newline at end of file
diff --git a/packages/SystemUI/res/values/attrs.xml b/packages/SystemUI/res/values/attrs.xml
index 6becd21984b9..79629e4c6d7e 100644
--- a/packages/SystemUI/res/values/attrs.xml
+++ b/packages/SystemUI/res/values/attrs.xml
@@ -154,12 +154,5 @@
<declare-styleable name="CaptionsToggleImageButton">
<attr name="optedOut" format="boolean" />
</declare-styleable>
-
- <!-- Theme attributes used to style the appearance of expanded Bubbles -->
- <declare-styleable name="BubbleExpandedView">
- <attr name="android:colorBackgroundFloating" />
- <attr name="android:dialogCornerRadius" />
- </declare-styleable>
-
</resources>
diff --git a/packages/SystemUI/res/values/colors.xml b/packages/SystemUI/res/values/colors.xml
index 92c74770a3c4..c1424657cf4f 100644
--- a/packages/SystemUI/res/values/colors.xml
+++ b/packages/SystemUI/res/values/colors.xml
@@ -211,4 +211,5 @@
<color name="GM2_green_500">#FF34A853</color>
<color name="GM2_blue_500">#FF4285F4</color>
+ <color name="magnification_border_color">#FF9900</color>
</resources>
diff --git a/packages/SystemUI/res/values/colors_tv.xml b/packages/SystemUI/res/values/colors_tv.xml
index db225428a348..53cd9716c98e 100644
--- a/packages/SystemUI/res/values/colors_tv.xml
+++ b/packages/SystemUI/res/values/colors_tv.xml
@@ -22,13 +22,9 @@
<color name="recents_tv_dismiss_text_color">#7FEEEEEE</color>
<color name="recents_tv_text_shadow_color">#7F000000</color>
-
- <!-- Text color used in audio recording bar: G50 -->
- <color name="tv_audio_recording_bar_text">#FFF8F9FA</color>
- <!-- Background color for a chip in audio recording bar: G800 -->
- <color name="tv_audio_recording_bar_chip_background">#FF3C4043</color>
- <!-- Audio recording bar background color: G900 -->
- <color name="tv_audio_recording_bar_background">#FF202124</color>
+ <!-- Background color for audio recording indicator (G800) -->
+ <color name="tv_audio_recording_indicator_background">#FF3C4043</color>
+ <color name="tv_audio_recording_indicator_pulse">#4DFFFFFF</color>
<color name="red">#FFCC0000</color>
</resources>
diff --git a/packages/SystemUI/res/values/config.xml b/packages/SystemUI/res/values/config.xml
index e896c162af7d..640f31bc9fe8 100644
--- a/packages/SystemUI/res/values/config.xml
+++ b/packages/SystemUI/res/values/config.xml
@@ -295,6 +295,7 @@
<item>com.android.systemui.SizeCompatModeActivityController</item>
<item>com.android.systemui.statusbar.notification.InstantAppNotifier</item>
<item>com.android.systemui.theme.ThemeOverlayController</item>
+ <item>com.android.systemui.accessibility.WindowMagnification</item>
</string-array>
<!-- SystemUI vender service, used in config_systemUIServiceComponents. -->
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index c9481164c202..da0323ac7357 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -1139,4 +1139,16 @@
<dimen name="qs_media_width">350dp</dimen>
<dimen name="qs_media_padding">8dp</dimen>
<dimen name="qs_media_corner_radius">10dp</dimen>
+
+ <dimen name="magnification_border_size">5dp</dimen>
+ <dimen name="magnification_frame_move_short">5dp</dimen>
+ <dimen name="magnification_frame_move_long">25dp</dimen>
+ <dimen name="magnification_drag_view_width">100dp</dimen>
+ <dimen name="magnification_drag_view_height">35dp</dimen>
+ <dimen name="magnification_controls_size">90dp</dimen>
+ <dimen name="magnifier_left_right_controls_width">35dp</dimen>
+ <dimen name="magnifier_left_right_controls_height">45dp</dimen>
+ <dimen name="magnifier_up_down_controls_width">45dp</dimen>
+ <dimen name="magnifier_up_down_controls_height">40dp</dimen>
+
</resources>
diff --git a/packages/SystemUI/res/values/integers.xml b/packages/SystemUI/res/values/integers.xml
index deae7e2c181c..c1cf7b420078 100644
--- a/packages/SystemUI/res/values/integers.xml
+++ b/packages/SystemUI/res/values/integers.xml
@@ -32,4 +32,6 @@
<!-- Ratio of "right" end of status bar that will swipe to QS. -->
<integer name="qs_split_fraction">2</integer>
+ <integer name="magnification_default_scale">2</integer>
+
</resources> \ No newline at end of file
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index 1053750a5538..380dcfd63585 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -914,8 +914,8 @@
<string name="quick_settings_secondary_label_until">Until <xliff:g id="time" example="7 am">%s</xliff:g></string>
<!-- QuickSettings: Label for the toggle to activate dark theme (A.K.A Dark Mode). [CHAR LIMIT=20] -->
<string name="quick_settings_ui_mode_night_label">Dark theme</string>
- <!-- QuickSettings: Label for the dark theme tile when enabled by battery saver. [CHAR LIMIT=40] -->
- <string name="quick_settings_ui_mode_night_label_battery_saver">Dark theme\nBattery saver</string>
+ <!-- QuickSettings: Secondary text for the dark theme tile when enabled by battery saver. [CHAR LIMIT=20] -->
+ <string name="quick_settings_dark_mode_secondary_label_battery_saver">Battery Saver</string>
<!-- QuickSettings: Secondary text for when the Dark Mode will be enabled at sunset. [CHAR LIMIT=20] -->
<string name="quick_settings_dark_mode_secondary_label_on_at_sunset">On at sunset</string>
<!-- QuickSettings: Secondary text for when the Dark Mode will be on until sunrise. [CHAR LIMIT=20] -->
@@ -1140,13 +1140,16 @@
<string name="battery_saver_notification_action_text">Turn off Battery Saver</string>
<!-- Media projection permission dialog warning text. [CHAR LIMIT=NONE] -->
- <string name="media_projection_dialog_text">While recording or casting, <xliff:g id="app_seeking_permission" example="Hangouts">%s</xliff:g> can capture any sensitive information that is displayed on your screen or played from your device, including sensitive information such as audio, passwords, payment info, photos and messages.</string>
+ <string name="media_projection_dialog_text"><xliff:g id="app_seeking_permission" example="Hangouts">%s</xliff:g> will have access to all of the information that is visible on your screen or played from your device while recording or casting. This includes information such as passwords, payment details, photos, messages, and audio that you play.</string>
<!-- Media projection permission dialog warning text for system services. [CHAR LIMIT=NONE] -->
- <string name="media_projection_dialog_service_text">While recording or casting, the service providing this function can capture any sensitive information that is displayed on your screen or played from your device, including sensitive information such as audio, passwords, payment info, photos and messages.</string>
+ <string name="media_projection_dialog_service_text">The service providing this function will have access to all of the information that is visible on your screen or played from your device while recording or casting. This includes information such as passwords, payment details, photos, messages, and audio that you play.</string>
+
+ <!-- Media projection permission dialog warning title for system services. [CHAR LIMIT=NONE] -->
+ <string name="media_projection_dialog_service_title">Start recording or casting ?</string>
<!-- Media projection permission dialog warning title. [CHAR LIMIT=NONE] -->
- <string name="media_projection_dialog_title">Exposing sensitive info during casting/recording </string>
+ <string name="media_projection_dialog_title">Start recording or casting with <xliff:g id="app_seeking_permission" example="Hangouts">%s</xliff:g>?</string>
<!-- Media projection permission dialog permanent grant check box. [CHAR LIMIT=NONE] -->
<string name="media_projection_remember_text">Don\'t show again</string>
@@ -2492,4 +2495,12 @@
<!-- Title of the overlay warning the user to interact with the device or it will go to sleep. [CHAR LIMIT=25] -->
<string name="inattentive_sleep_warning_title">Standby</string>
+
+ <!-- Window Magnification strings -->
+ <!-- Title for Magnification Overlay Window [CHAR LIMIT=NONE] -->
+ <string name="magnification_overlay_title">Magnification Overlay Window</string>
+ <!-- Title for Magnification Window [CHAR LIMIT=NONE] -->
+ <string name="magnification_window_title">Magnification Window</string>
+ <!-- Title for Magnification Controls Window [CHAR LIMIT=NONE] -->
+ <string name="magnification_controls_title">Magnification Window Controls</string>
</resources>
diff --git a/packages/SystemUI/res/values/strings_tv.xml b/packages/SystemUI/res/values/strings_tv.xml
index a9bdb71de039..6d61ff989cb1 100644
--- a/packages/SystemUI/res/values/strings_tv.xml
+++ b/packages/SystemUI/res/values/strings_tv.xml
@@ -31,4 +31,8 @@
<string name="pip_close">Close PIP</string>
<!-- Button to move picture-in-picture (PIP) screen to the fullscreen in PIP menu [CHAR LIMIT=30] -->
<string name="pip_fullscreen">Full screen</string>
+
+ <!-- Title and subtitle for AudioRecordingIndicator -->
+ <string name="mic_active">Microphone Active</string>
+ <string name="app_accessed_mic">%1$s accessed your microphone</string>
</resources>
diff --git a/packages/SystemUI/res/values/styles.xml b/packages/SystemUI/res/values/styles.xml
index 926d01685075..3ff824374aac 100644
--- a/packages/SystemUI/res/values/styles.xml
+++ b/packages/SystemUI/res/values/styles.xml
@@ -15,6 +15,7 @@
-->
<resources xmlns:android="http://schemas.android.com/apk/res/android">
+ <style name="BubbleOverflow" parent="@android:style/Theme.NoTitleBar"></style>
<style name="ClearAllButtonDefaultMargins">
<item name="android:layout_marginStart">0dp</item>
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/ActivityManagerWrapper.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/ActivityManagerWrapper.java
index 70f8e15eb83d..deaafca7a98c 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/ActivityManagerWrapper.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/ActivityManagerWrapper.java
@@ -28,6 +28,7 @@ import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECOND
import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
import android.annotation.NonNull;
+import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RecentTaskInfo;
import android.app.ActivityManager.RunningTaskInfo;
@@ -161,6 +162,23 @@ public class ActivityManagerWrapper {
}
/**
+ * Removes the outdated snapshot of home task.
+ */
+ public void invalidateHomeTaskSnapshot(final Activity homeActivity) {
+ mBackgroundExecutor.submit(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ ActivityTaskManager.getService().invalidateHomeTaskSnapshot(
+ homeActivity.getActivityToken());
+ } catch (RemoteException e) {
+ Log.w(TAG, "Failed to invalidate home snapshot", e);
+ }
+ }
+ });
+ }
+
+ /**
* @return the activity label, badging if necessary.
*/
public String getBadgedActivityLabel(ActivityInfo info, int userId) {
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskDescriptionCompat.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskDescriptionCompat.java
index eaf8d9b57398..35952f55ec1e 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskDescriptionCompat.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskDescriptionCompat.java
@@ -17,6 +17,7 @@
package com.android.systemui.shared.system;
import android.app.ActivityManager;
+import android.graphics.Bitmap;
public class TaskDescriptionCompat {
@@ -37,4 +38,12 @@ public class TaskDescriptionCompat {
? mTaskDescription.getBackgroundColor()
: 0;
}
+
+ public static Bitmap getIcon(ActivityManager.TaskDescription desc, int userId) {
+ if (desc.getInMemoryIcon() != null) {
+ return desc.getInMemoryIcon();
+ }
+ return ActivityManager.TaskDescription.loadTaskDescriptionIcon(
+ desc.getIconFilename(), userId);
+ }
}
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/WindowManagerWrapper.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/WindowManagerWrapper.java
index 22d1675cf17e..9f13718ec236 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/WindowManagerWrapper.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/WindowManagerWrapper.java
@@ -27,6 +27,7 @@ import android.graphics.Rect;
import android.os.Handler;
import android.os.RemoteException;
import android.util.Log;
+import android.view.SurfaceControl;
import android.view.WindowManager;
import android.view.WindowManagerGlobal;
@@ -215,4 +216,23 @@ public class WindowManagerWrapper {
public void removePinnedStackListener(PinnedStackListener listener) {
mPinnedStackListenerForwarder.removeListener(listener);
}
+
+ /**
+ * Mirrors a specified display. The SurfaceControl returned is the root of the mirrored
+ * hierarchy.
+ *
+ * @param displayId The id of the display to mirror
+ * @return The SurfaceControl for the root of the mirrored hierarchy.
+ */
+ public SurfaceControl mirrorDisplay(final int displayId) {
+ try {
+ SurfaceControl outSurfaceControl = new SurfaceControl();
+ WindowManagerGlobal.getWindowManagerService().mirrorDisplay(displayId,
+ outSurfaceControl);
+ return outSurfaceControl;
+ } catch (RemoteException e) {
+ Log.e(TAG, "Unable to reach window manager", e);
+ }
+ return null;
+ }
}
diff --git a/packages/SystemUI/src/com/android/keyguard/CarrierTextController.java b/packages/SystemUI/src/com/android/keyguard/CarrierTextController.java
index d66a53cd9012..caf5ee02df06 100644
--- a/packages/SystemUI/src/com/android/keyguard/CarrierTextController.java
+++ b/packages/SystemUI/src/com/android/keyguard/CarrierTextController.java
@@ -163,8 +163,7 @@ public class CarrierTextController {
public CarrierTextController(Context context, CharSequence separator, boolean showAirplaneMode,
boolean showMissingSim) {
mContext = context;
- mIsEmergencyCallCapable = context.getResources().getBoolean(
- com.android.internal.R.bool.config_voice_capable);
+ mIsEmergencyCallCapable = getTelephonyManager().isVoiceCapable();
mShowAirplaneMode = showAirplaneMode;
mShowMissingSim = showMissingSim;
diff --git a/packages/SystemUI/src/com/android/keyguard/EmergencyButton.java b/packages/SystemUI/src/com/android/keyguard/EmergencyButton.java
index 867014b6b5e1..c2cedad0dc48 100644
--- a/packages/SystemUI/src/com/android/keyguard/EmergencyButton.java
+++ b/packages/SystemUI/src/com/android/keyguard/EmergencyButton.java
@@ -28,7 +28,9 @@ import android.os.RemoteException;
import android.os.SystemClock;
import android.os.UserHandle;
import android.telecom.TelecomManager;
+import android.telephony.TelephonyManager;
import android.util.AttributeSet;
+import android.util.Log;
import android.util.Slog;
import android.view.MotionEvent;
import android.view.View;
@@ -86,13 +88,16 @@ public class EmergencyButton extends Button {
public EmergencyButton(Context context, AttributeSet attrs) {
super(context, attrs);
- mIsVoiceCapable = context.getResources().getBoolean(
- com.android.internal.R.bool.config_voice_capable);
+ mIsVoiceCapable = getTelephonyManager().isVoiceCapable();
mEnableEmergencyCallWhileSimLocked = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_enable_emergency_call_while_sim_locked);
mEmergencyAffordanceManager = new EmergencyAffordanceManager(context);
}
+ private TelephonyManager getTelephonyManager() {
+ return (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
+ }
+
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
@@ -110,11 +115,7 @@ public class EmergencyButton extends Button {
super.onFinishInflate();
mLockPatternUtils = new LockPatternUtils(mContext);
mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
- setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- takeEmergencyCallAction();
- }
- });
+ setOnClickListener(v -> takeEmergencyCallAction());
setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
@@ -164,9 +165,9 @@ public class EmergencyButton extends Button {
*/
public void takeEmergencyCallAction() {
MetricsLogger.action(mContext, MetricsEvent.ACTION_EMERGENCY_CALL);
- // TODO: implement a shorter timeout once new PowerManager API is ready.
- // should be the equivalent to the old userActivity(EMERGENCY_CALL_TIMEOUT)
- mPowerManager.userActivity(SystemClock.uptimeMillis(), true);
+ if (mPowerManager != null) {
+ mPowerManager.userActivity(SystemClock.uptimeMillis(), true);
+ }
try {
ActivityTaskManager.getService().stopSystemLockTaskMode();
} catch (RemoteException e) {
@@ -178,10 +179,19 @@ public class EmergencyButton extends Button {
mEmergencyButtonCallback.onEmergencyButtonClickedWhenInCall();
}
} else {
- Dependency.get(KeyguardUpdateMonitor.class).reportEmergencyCallAction(
- true /* bypassHandler */);
+ KeyguardUpdateMonitor updateMonitor = Dependency.get(KeyguardUpdateMonitor.class);
+ if (updateMonitor != null) {
+ updateMonitor.reportEmergencyCallAction(true /* bypassHandler */);
+ } else {
+ Log.w(LOG_TAG, "KeyguardUpdateMonitor was null, launching intent anyway.");
+ }
+ TelecomManager telecomManager = getTelecommManager();
+ if (telecomManager == null) {
+ Log.wtf(LOG_TAG, "TelecomManager was null, cannot launch emergency dialer");
+ return;
+ }
Intent emergencyDialIntent =
- getTelecommManager().createLaunchEmergencyDialerIntent(null /* number*/)
+ telecomManager.createLaunchEmergencyDialerIntent(null /* number*/)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
| Intent.FLAG_ACTIVITY_CLEAR_TOP)
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardDisplayManager.java b/packages/SystemUI/src/com/android/keyguard/KeyguardDisplayManager.java
index 9380eb4b03f0..4e7956db4a2b 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardDisplayManager.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardDisplayManager.java
@@ -290,6 +290,7 @@ public class KeyguardDisplayManager {
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
+ getWindow().setFitWindowInsetsTypes(0 /* types */);
getWindow().setNavigationBarContrastEnforced(false);
getWindow().setNavigationBarColor(Color.TRANSPARENT);
diff --git a/packages/SystemUI/src/com/android/keyguard/clock/ClockInfo.java b/packages/SystemUI/src/com/android/keyguard/clock/ClockInfo.java
index 812f2156d5d9..0210e08bb24c 100644
--- a/packages/SystemUI/src/com/android/keyguard/clock/ClockInfo.java
+++ b/packages/SystemUI/src/com/android/keyguard/clock/ClockInfo.java
@@ -25,12 +25,12 @@ import java.util.function.Supplier;
final class ClockInfo {
private final String mName;
- private final String mTitle;
+ private final Supplier<String> mTitle;
private final String mId;
private final Supplier<Bitmap> mThumbnail;
private final Supplier<Bitmap> mPreview;
- private ClockInfo(String name, String title, String id,
+ private ClockInfo(String name, Supplier<String> title, String id,
Supplier<Bitmap> thumbnail, Supplier<Bitmap> preview) {
mName = name;
mTitle = title;
@@ -50,7 +50,7 @@ final class ClockInfo {
* Gets the name (title) of the clock face to be shown in the picker app.
*/
String getTitle() {
- return mTitle;
+ return mTitle.get();
}
/**
@@ -80,7 +80,7 @@ final class ClockInfo {
static class Builder {
private String mName;
- private String mTitle;
+ private Supplier<String> mTitle;
private String mId;
private Supplier<Bitmap> mThumbnail;
private Supplier<Bitmap> mPreview;
@@ -94,7 +94,7 @@ final class ClockInfo {
return this;
}
- public Builder setTitle(String title) {
+ public Builder setTitle(Supplier<String> title) {
mTitle = title;
return this;
}
diff --git a/packages/SystemUI/src/com/android/keyguard/clock/ClockManager.java b/packages/SystemUI/src/com/android/keyguard/clock/ClockManager.java
index dfabe696cf71..9cd4aec4617d 100644
--- a/packages/SystemUI/src/com/android/keyguard/clock/ClockManager.java
+++ b/packages/SystemUI/src/com/android/keyguard/clock/ClockManager.java
@@ -244,11 +244,12 @@ public final class ClockManager {
mPreviewClocks.reloadCurrentClock();
mListeners.forEach((listener, clocks) -> {
clocks.reloadCurrentClock();
- ClockPlugin clock = clocks.getCurrentClock();
- if (clock instanceof DefaultClockController) {
- listener.onClockChanged(null);
+ final ClockPlugin clock = clocks.getCurrentClock();
+ if (Looper.myLooper() == Looper.getMainLooper()) {
+ listener.onClockChanged(clock instanceof DefaultClockController ? null : clock);
} else {
- listener.onClockChanged(clock);
+ mMainHandler.post(() -> listener.onClockChanged(
+ clock instanceof DefaultClockController ? null : clock));
}
});
}
@@ -323,7 +324,7 @@ public final class ClockManager {
mClocks.put(plugin.getClass().getName(), plugin);
mClockInfo.add(ClockInfo.builder()
.setName(plugin.getName())
- .setTitle(plugin.getTitle())
+ .setTitle(plugin::getTitle)
.setId(id)
.setThumbnail(plugin::getThumbnail)
.setPreview(() -> plugin.getPreview(mWidth, mHeight))
diff --git a/packages/SystemUI/src/com/android/systemui/ActivityStarterDelegate.java b/packages/SystemUI/src/com/android/systemui/ActivityStarterDelegate.java
index 41a7bc43eaa0..47a10af7c550 100644
--- a/packages/SystemUI/src/com/android/systemui/ActivityStarterDelegate.java
+++ b/packages/SystemUI/src/com/android/systemui/ActivityStarterDelegate.java
@@ -19,117 +19,99 @@ import android.content.Intent;
import android.view.View;
import com.android.systemui.plugins.ActivityStarter;
+import com.android.systemui.statusbar.phone.StatusBar;
+
+import java.util.Optional;
import javax.inject.Inject;
import javax.inject.Singleton;
+import dagger.Lazy;
+
/**
* Single common instance of ActivityStarter that can be gotten and referenced from anywhere, but
- * delegates to an actual implementation such as StatusBar, assuming it exists.
+ * delegates to an actual implementation (StatusBar).
*/
+@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@Singleton
public class ActivityStarterDelegate implements ActivityStarter {
- private ActivityStarter mActualStarter;
+ private Optional<Lazy<StatusBar>> mActualStarter;
@Inject
- public ActivityStarterDelegate() {
+ public ActivityStarterDelegate(Optional<Lazy<StatusBar>> statusBar) {
+ mActualStarter = statusBar;
}
@Override
public void startPendingIntentDismissingKeyguard(PendingIntent intent) {
- if (mActualStarter == null) {
- return;
- }
- mActualStarter.startPendingIntentDismissingKeyguard(intent);
+ mActualStarter.ifPresent(
+ starter -> starter.get().startPendingIntentDismissingKeyguard(intent));
}
@Override
public void startPendingIntentDismissingKeyguard(PendingIntent intent,
Runnable intentSentCallback) {
- if (mActualStarter == null) {
- return;
- }
- mActualStarter.startPendingIntentDismissingKeyguard(intent, intentSentCallback);
+ mActualStarter.ifPresent(
+ starter -> starter.get().startPendingIntentDismissingKeyguard(intent,
+ intentSentCallback));
}
@Override
public void startPendingIntentDismissingKeyguard(PendingIntent intent,
Runnable intentSentCallback, View associatedView) {
- if (mActualStarter == null) {
- return;
- }
- mActualStarter.startPendingIntentDismissingKeyguard(intent, intentSentCallback,
- associatedView);
+ mActualStarter.ifPresent(
+ starter -> starter.get().startPendingIntentDismissingKeyguard(intent,
+ intentSentCallback, associatedView));
}
@Override
public void startActivity(Intent intent, boolean onlyProvisioned, boolean dismissShade,
int flags) {
- if (mActualStarter == null) {
- return;
- }
- mActualStarter.startActivity(intent, onlyProvisioned, dismissShade, flags);
+ mActualStarter.ifPresent(
+ starter -> starter.get().startActivity(intent, onlyProvisioned, dismissShade,
+ flags));
}
@Override
public void startActivity(Intent intent, boolean dismissShade) {
- if (mActualStarter == null) {
- return;
- }
- mActualStarter.startActivity(intent, dismissShade);
+ mActualStarter.ifPresent(starter -> starter.get().startActivity(intent, dismissShade));
}
@Override
public void startActivity(Intent intent, boolean onlyProvisioned, boolean dismissShade) {
- if (mActualStarter == null) {
- return;
- }
- mActualStarter.startActivity(intent, onlyProvisioned, dismissShade);
+ mActualStarter.ifPresent(
+ starter -> starter.get().startActivity(intent, onlyProvisioned, dismissShade));
}
@Override
public void startActivity(Intent intent, boolean dismissShade, Callback callback) {
- if (mActualStarter == null) {
- return;
- }
- mActualStarter.startActivity(intent, dismissShade, callback);
+ mActualStarter.ifPresent(
+ starter -> starter.get().startActivity(intent, dismissShade, callback));
}
@Override
public void postStartActivityDismissingKeyguard(Intent intent, int delay) {
- if (mActualStarter == null) {
- return;
- }
- mActualStarter.postStartActivityDismissingKeyguard(intent, delay);
+ mActualStarter.ifPresent(
+ starter -> starter.get().postStartActivityDismissingKeyguard(intent, delay));
}
@Override
public void postStartActivityDismissingKeyguard(PendingIntent intent) {
- if (mActualStarter == null) {
- return;
- }
- mActualStarter.postStartActivityDismissingKeyguard(intent);
+ mActualStarter.ifPresent(
+ starter -> starter.get().postStartActivityDismissingKeyguard(intent));
}
@Override
public void postQSRunnableDismissingKeyguard(Runnable runnable) {
- if (mActualStarter == null) {
- return;
- }
- mActualStarter.postQSRunnableDismissingKeyguard(runnable);
+ mActualStarter.ifPresent(
+ starter -> starter.get().postQSRunnableDismissingKeyguard(runnable));
}
@Override
public void dismissKeyguardThenExecute(OnDismissAction action, Runnable cancel,
boolean afterKeyguardGone) {
- if (mActualStarter == null) {
- return;
- }
- mActualStarter.dismissKeyguardThenExecute(action, cancel, afterKeyguardGone);
- }
-
- public void setActivityStarterImpl(ActivityStarter starter) {
- mActualStarter = starter;
+ mActualStarter.ifPresent(starter -> starter.get().dismissKeyguardThenExecute(action, cancel,
+ afterKeyguardGone));
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/BatteryMeterView.java b/packages/SystemUI/src/com/android/systemui/BatteryMeterView.java
index 2afcb12da730..d68fe15844c1 100644
--- a/packages/SystemUI/src/com/android/systemui/BatteryMeterView.java
+++ b/packages/SystemUI/src/com/android/systemui/BatteryMeterView.java
@@ -42,6 +42,7 @@ import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
+import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
@@ -288,6 +289,7 @@ public class BatteryMeterView extends LinearLayout implements
public void onTuningChanged(String key, String newValue) {
if (StatusBarIconController.ICON_BLACKLIST.equals(key)) {
ArraySet<String> icons = StatusBarIconController.getIconBlacklist(newValue);
+ setVisibility(icons.contains(mSlotBattery) ? View.GONE : View.VISIBLE);
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/CornerHandleView.java b/packages/SystemUI/src/com/android/systemui/CornerHandleView.java
index 8e472f9c98a3..8503396975b5 100644
--- a/packages/SystemUI/src/com/android/systemui/CornerHandleView.java
+++ b/packages/SystemUI/src/com/android/systemui/CornerHandleView.java
@@ -57,6 +57,7 @@ public class CornerHandleView extends View {
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(getStrokePx());
+ setLayerType(View.LAYER_TYPE_SOFTWARE, mPaint);
final int dualToneDarkTheme = Utils.getThemeAttr(mContext, R.attr.darkIconTheme);
final int dualToneLightTheme = Utils.getThemeAttr(mContext, R.attr.lightIconTheme);
@@ -114,10 +115,17 @@ public class CornerHandleView extends View {
* appropriately. Intention is to match the home handle color.
*/
public void updateDarkness(float darkIntensity) {
+ // Handle color is same as home handle color.
int color = (int) ArgbEvaluator.getInstance().evaluate(darkIntensity,
mLightColor, mDarkColor);
+ // Shadow color is inverse of handle color.
+ int shadowColor = (int) ArgbEvaluator.getInstance().evaluate(darkIntensity,
+ mDarkColor, mLightColor);
if (mPaint.getColor() != color) {
mPaint.setColor(color);
+ mPaint.setShadowLayer(/** radius */ getResources().getDimensionPixelSize(
+ com.android.internal.R.dimen.assist_handle_shadow_radius), /** shadowDx */ 0,
+ /** shadowDy */ 0, /** color */ shadowColor);
if (getVisibility() == VISIBLE && getAlpha() > 0) {
invalidate();
} else {
diff --git a/packages/SystemUI/src/com/android/systemui/Dependency.java b/packages/SystemUI/src/com/android/systemui/Dependency.java
index 6821265df28b..94e7c68c831d 100644
--- a/packages/SystemUI/src/com/android/systemui/Dependency.java
+++ b/packages/SystemUI/src/com/android/systemui/Dependency.java
@@ -124,6 +124,7 @@ import com.android.systemui.util.leak.LeakDetector;
import com.android.systemui.util.leak.LeakReporter;
import com.android.systemui.util.sensors.AsyncSensorManager;
import com.android.systemui.wm.DisplayWindowController;
+import com.android.systemui.wm.SystemWindows;
import java.io.FileDescriptor;
import java.io.PrintWriter;
@@ -209,7 +210,6 @@ public class Dependency {
private final ArrayMap<Object, LazyDependencyCreator> mProviders = new ArrayMap<>();
@Inject Lazy<ActivityStarter> mActivityStarter;
- @Inject Lazy<ActivityStarterDelegate> mActivityStarterDelegate;
@Inject Lazy<BroadcastDispatcher> mBroadcastDispatcher;
@Inject Lazy<AsyncSensorManager> mAsyncSensorManager;
@Inject Lazy<BluetoothController> mBluetoothController;
@@ -323,6 +323,7 @@ public class Dependency {
@Inject Lazy<Recents> mRecents;
@Inject Lazy<StatusBar> mStatusBar;
@Inject Lazy<DisplayWindowController> mDisplayWindowController;
+ @Inject Lazy<SystemWindows> mSystemWindows;
@Inject
public Dependency() {
@@ -339,7 +340,6 @@ public class Dependency {
mProviders.put(MAIN_LOOPER, mMainLooper::get);
mProviders.put(MAIN_HANDLER, mMainHandler::get);
mProviders.put(ActivityStarter.class, mActivityStarter::get);
- mProviders.put(ActivityStarterDelegate.class, mActivityStarterDelegate::get);
mProviders.put(BroadcastDispatcher.class, mBroadcastDispatcher::get);
mProviders.put(AsyncSensorManager.class, mAsyncSensorManager::get);
@@ -513,6 +513,7 @@ public class Dependency {
mProviders.put(Recents.class, mRecents::get);
mProviders.put(StatusBar.class, mStatusBar::get);
mProviders.put(DisplayWindowController.class, mDisplayWindowController::get);
+ mProviders.put(SystemWindows.class, mSystemWindows::get);
// TODO(b/118592525): to support multi-display , we start to add something which is
// per-display, while others may be global. I think it's time to add
diff --git a/packages/SystemUI/src/com/android/systemui/ExpandHelper.java b/packages/SystemUI/src/com/android/systemui/ExpandHelper.java
index ecf4c0a86bfc..e2b12daf441e 100644
--- a/packages/SystemUI/src/com/android/systemui/ExpandHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/ExpandHelper.java
@@ -179,7 +179,8 @@ public class ExpandHelper implements Gefingerpoken {
mTouchSlop = configuration.getScaledTouchSlop();
mSGD = new ScaleGestureDetector(context, mScaleGestureListener);
- mFlingAnimationUtils = new FlingAnimationUtils(context, EXPAND_DURATION);
+ mFlingAnimationUtils = new FlingAnimationUtils(mContext.getResources().getDisplayMetrics(),
+ EXPAND_DURATION);
}
@VisibleForTesting
diff --git a/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java b/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java
index ab7eec52a959..9ce277eabbe8 100644
--- a/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java
+++ b/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java
@@ -495,6 +495,7 @@ public class ScreenDecorations extends SystemUI implements Tunable {
lp.gravity = Gravity.TOP | Gravity.LEFT;
}
lp.layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
+ lp.setFitWindowInsetsTypes(0 /* types */);
if (isLandscape(mRotation)) {
lp.width = WRAP_CONTENT;
lp.height = MATCH_PARENT;
diff --git a/packages/SystemUI/src/com/android/systemui/SizeCompatModeActivityController.java b/packages/SystemUI/src/com/android/systemui/SizeCompatModeActivityController.java
index 72a403035294..4749addc7139 100644
--- a/packages/SystemUI/src/com/android/systemui/SizeCompatModeActivityController.java
+++ b/packages/SystemUI/src/com/android/systemui/SizeCompatModeActivityController.java
@@ -280,6 +280,7 @@ public class SizeCompatModeActivityController extends SystemUI implements Comman
R.layout.size_compat_mode_hint, null /* root */);
PopupWindow popupWindow = new PopupWindow(popupView,
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
+ popupWindow.setWindowLayoutType(mWinParams.type);
popupWindow.setElevation(getResources().getDimension(R.dimen.bubble_elevation));
popupWindow.setAnimationStyle(android.R.style.Animation_InputMethod);
popupWindow.setClippingEnabled(false);
diff --git a/packages/SystemUI/src/com/android/systemui/SwipeHelper.java b/packages/SystemUI/src/com/android/systemui/SwipeHelper.java
index 58c52a1fc50e..4728327d51b8 100644
--- a/packages/SystemUI/src/com/android/systemui/SwipeHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/SwipeHelper.java
@@ -93,13 +93,11 @@ public class SwipeHelper implements Gefingerpoken {
private boolean mTouchAboveFalsingThreshold;
private boolean mDisableHwLayers;
private final boolean mFadeDependingOnAmountSwiped;
- private final Context mContext;
private final ArrayMap<View, Animator> mDismissPendingMap = new ArrayMap<>();
public SwipeHelper(
int swipeDirection, Callback callback, Context context, FalsingManager falsingManager) {
- mContext = context;
mCallback = callback;
mHandler = new Handler();
mSwipeDirection = swipeDirection;
@@ -114,7 +112,8 @@ public class SwipeHelper implements Gefingerpoken {
mFalsingThreshold = res.getDimensionPixelSize(R.dimen.swipe_helper_falsing_threshold);
mFadeDependingOnAmountSwiped = res.getBoolean(R.bool.config_fadeDependingOnAmountSwiped);
mFalsingManager = falsingManager;
- mFlingAnimationUtils = new FlingAnimationUtils(context, getMaxEscapeAnimDuration() / 1000f);
+ mFlingAnimationUtils = new FlingAnimationUtils(res.getDisplayMetrics(),
+ getMaxEscapeAnimDuration() / 1000f);
}
public void setDensityScale(float densityScale) {
diff --git a/packages/SystemUI/src/com/android/systemui/accessibility/WindowMagnification.java b/packages/SystemUI/src/com/android/systemui/accessibility/WindowMagnification.java
new file mode 100644
index 000000000000..6178ff2ab2cb
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/accessibility/WindowMagnification.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.accessibility;
+
+import android.content.Context;
+import android.database.ContentObserver;
+import android.os.Handler;
+import android.provider.Settings;
+
+import com.android.systemui.SystemUI;
+import com.android.systemui.dagger.qualifiers.MainHandler;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+/**
+ * Class to handle changes to setting window_magnification value.
+ */
+@Singleton
+public class WindowMagnification extends SystemUI {
+ private WindowMagnificationController mWindowMagnificationController;
+ private final Handler mHandler;
+
+ @Inject
+ public WindowMagnification(Context context, @MainHandler Handler mainHandler) {
+ super(context);
+ mHandler = mainHandler;
+ }
+
+ @Override
+ public void start() {
+ mContext.getContentResolver().registerContentObserver(
+ Settings.Secure.getUriFor(Settings.Secure.WINDOW_MAGNIFICATION),
+ true, new ContentObserver(mHandler) {
+ @Override
+ public void onChange(boolean selfChange) {
+ updateWindowMagnification();
+ }
+ });
+ }
+
+ private void updateWindowMagnification() {
+ try {
+ boolean enable = Settings.Secure.getInt(mContext.getContentResolver(),
+ Settings.Secure.WINDOW_MAGNIFICATION) != 0;
+ if (enable) {
+ enableMagnification();
+ } else {
+ disableMagnification();
+ }
+ } catch (Settings.SettingNotFoundException e) {
+ disableMagnification();
+ }
+ }
+
+ private void enableMagnification() {
+ if (mWindowMagnificationController == null) {
+ mWindowMagnificationController = new WindowMagnificationController(mContext, mHandler);
+ }
+ mWindowMagnificationController.createWindowMagnification();
+ }
+
+ private void disableMagnification() {
+ if (mWindowMagnificationController != null) {
+ mWindowMagnificationController.deleteWindowMagnification();
+ }
+ mWindowMagnificationController = null;
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/accessibility/WindowMagnificationController.java b/packages/SystemUI/src/com/android/systemui/accessibility/WindowMagnificationController.java
new file mode 100644
index 000000000000..e3694ac532fe
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/accessibility/WindowMagnificationController.java
@@ -0,0 +1,424 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.accessibility;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.PixelFormat;
+import android.graphics.Point;
+import android.graphics.PointF;
+import android.graphics.Rect;
+import android.os.Binder;
+import android.os.Handler;
+import android.view.Display;
+import android.view.Gravity;
+import android.view.LayoutInflater;
+import android.view.MotionEvent;
+import android.view.Surface;
+import android.view.SurfaceControl;
+import android.view.SurfaceHolder;
+import android.view.SurfaceView;
+import android.view.View;
+import android.view.ViewTreeObserver;
+import android.view.WindowManager;
+
+import com.android.systemui.R;
+import com.android.systemui.shared.system.WindowManagerWrapper;
+
+/**
+ * Class to handle adding and removing a window magnification.
+ */
+public class WindowMagnificationController implements View.OnClickListener,
+ View.OnLongClickListener, View.OnTouchListener, SurfaceHolder.Callback {
+ private final int mBorderSize;
+ private final int mMoveFrameAmountShort;
+ private final int mMoveFrameAmountLong;
+
+ private final Context mContext;
+ private final Point mDisplaySize = new Point();
+ private final int mDisplayId;
+ private final Handler mHandler;
+ private final Rect mMagnificationFrame = new Rect();
+ private final SurfaceControl.Transaction mTransaction = new SurfaceControl.Transaction();
+
+ private final WindowManager mWm;
+
+ private float mScale;
+
+ private final Rect mTmpRect = new Rect();
+
+ // The root of the mirrored content
+ private SurfaceControl mMirrorSurface;
+
+ private boolean mIsPressedDown;
+
+ private View mLeftControl;
+ private View mUpControl;
+ private View mRightControl;
+ private View mBottomControl;
+
+ private View mDragView;
+ private View mLeftDrag;
+ private View mTopDrag;
+ private View mRightDrag;
+ private View mBottomDrag;
+
+ private final PointF mLastDrag = new PointF();
+ private final Point mMoveWindowOffset = new Point();
+
+ private View mMirrorView;
+ private SurfaceView mMirrorSurfaceView;
+ private View mControlsView;
+ private View mOverlayView;
+
+ private MoveMirrorRunnable mMoveMirrorRunnable = new MoveMirrorRunnable();
+
+ WindowMagnificationController(Context context, Handler handler) {
+ mContext = context;
+ mHandler = handler;
+ Display display = mContext.getDisplay();
+ display.getSize(mDisplaySize);
+ mDisplayId = mContext.getDisplayId();
+
+ mWm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
+
+ Resources r = context.getResources();
+ mBorderSize = (int) r.getDimension(R.dimen.magnification_border_size);
+ mMoveFrameAmountShort = (int) r.getDimension(R.dimen.magnification_frame_move_short);
+ mMoveFrameAmountLong = (int) r.getDimension(R.dimen.magnification_frame_move_long);
+
+ mScale = r.getInteger(R.integer.magnification_default_scale);
+ }
+
+ /**
+ * Creates a magnification window if it doesn't already exist.
+ */
+ void createWindowMagnification() {
+ if (mMirrorView != null) {
+ return;
+ }
+ createOverlayWindow();
+ }
+
+ private void createOverlayWindow() {
+ WindowManager.LayoutParams params = new WindowManager.LayoutParams(
+ WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT,
+ WindowManager.LayoutParams.TYPE_ACCESSIBILITY_MAGNIFICATION_OVERLAY,
+ WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
+ | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
+ PixelFormat.TRANSPARENT);
+ params.gravity = Gravity.TOP | Gravity.LEFT;
+ params.token = new Binder();
+ params.setTitle(mContext.getString(R.string.magnification_overlay_title));
+
+ mOverlayView = new View(mContext);
+ mOverlayView.getViewTreeObserver().addOnWindowAttachListener(
+ new ViewTreeObserver.OnWindowAttachListener() {
+ @Override
+ public void onWindowAttached() {
+ mOverlayView.getViewTreeObserver().removeOnWindowAttachListener(this);
+ createMirrorWindow();
+ createControls();
+ }
+
+ @Override
+ public void onWindowDetached() {
+
+ }
+ });
+
+ mOverlayView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
+ | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
+ | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
+ | View.SYSTEM_UI_FLAG_FULLSCREEN
+ | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
+ | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
+
+ mWm.addView(mOverlayView, params);
+ }
+
+ /**
+ * Deletes the magnification window.
+ */
+ void deleteWindowMagnification() {
+ if (mMirrorSurface != null) {
+ mTransaction.remove(mMirrorSurface).apply();
+ mMirrorSurface = null;
+ }
+
+ if (mOverlayView != null) {
+ mWm.removeView(mOverlayView);
+ mOverlayView = null;
+ }
+
+ if (mMirrorView != null) {
+ mWm.removeView(mMirrorView);
+ mMirrorView = null;
+ }
+
+ if (mControlsView != null) {
+ mWm.removeView(mControlsView);
+ mControlsView = null;
+ }
+ }
+
+ private void createMirrorWindow() {
+ setInitialStartBounds();
+
+ // The window should be the size the mirrored surface will be but also add room for the
+ // border and the drag handle.
+ int dragViewHeight = (int) mContext.getResources().getDimension(
+ R.dimen.magnification_drag_view_height);
+ int windowWidth = mMagnificationFrame.width() + 2 * mBorderSize;
+ int windowHeight = mMagnificationFrame.height() + dragViewHeight + 2 * mBorderSize;
+
+ WindowManager.LayoutParams params = new WindowManager.LayoutParams(
+ windowWidth, windowHeight,
+ WindowManager.LayoutParams.TYPE_APPLICATION_PANEL,
+ WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
+ | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
+ PixelFormat.TRANSPARENT);
+ params.gravity = Gravity.TOP | Gravity.LEFT;
+ params.token = mOverlayView.getWindowToken();
+ params.x = mMagnificationFrame.left;
+ params.y = mMagnificationFrame.top;
+ params.setTitle(mContext.getString(R.string.magnification_window_title));
+
+ mMirrorView = LayoutInflater.from(mContext).inflate(R.layout.window_magnifier_view, null);
+ mMirrorSurfaceView = mMirrorView.findViewById(R.id.surface_view);
+ // This places the SurfaceView's SurfaceControl above the ViewRootImpl's SurfaceControl to
+ // ensure the mirrored area can get touch instead of going to the window
+ mMirrorSurfaceView.setZOrderOnTop(true);
+
+ mMirrorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
+ | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
+ | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
+ | View.SYSTEM_UI_FLAG_FULLSCREEN
+ | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
+ | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
+ mWm.addView(mMirrorView, params);
+
+ SurfaceHolder holder = mMirrorSurfaceView.getHolder();
+ holder.addCallback(this);
+ holder.setFormat(PixelFormat.RGBA_8888);
+
+ addDragTouchListeners();
+ }
+
+ private void createControls() {
+ int controlsSize = (int) mContext.getResources().getDimension(
+ R.dimen.magnification_controls_size);
+
+ WindowManager.LayoutParams lp = new WindowManager.LayoutParams(controlsSize, controlsSize,
+ WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
+ WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
+ | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
+ PixelFormat.RGBA_8888);
+ lp.gravity = Gravity.BOTTOM | Gravity.RIGHT;
+ lp.token = mOverlayView.getWindowToken();
+ lp.setTitle(mContext.getString(R.string.magnification_controls_title));
+
+ mControlsView = LayoutInflater.from(mContext).inflate(R.layout.magnifier_controllers, null);
+ mWm.addView(mControlsView, lp);
+
+ mLeftControl = mControlsView.findViewById(R.id.left_control);
+ mUpControl = mControlsView.findViewById(R.id.up_control);
+ mRightControl = mControlsView.findViewById(R.id.right_control);
+ mBottomControl = mControlsView.findViewById(R.id.down_control);
+
+ mLeftControl.setOnClickListener(this);
+ mUpControl.setOnClickListener(this);
+ mRightControl.setOnClickListener(this);
+ mBottomControl.setOnClickListener(this);
+
+ mLeftControl.setOnLongClickListener(this);
+ mUpControl.setOnLongClickListener(this);
+ mRightControl.setOnLongClickListener(this);
+ mBottomControl.setOnLongClickListener(this);
+
+ mLeftControl.setOnTouchListener(this);
+ mUpControl.setOnTouchListener(this);
+ mRightControl.setOnTouchListener(this);
+ mBottomControl.setOnTouchListener(this);
+ }
+
+ private void setInitialStartBounds() {
+ // Sets the initial frame area for the mirror and places it in the center of the display.
+ int initSize = Math.min(mDisplaySize.x, mDisplaySize.y) / 2;
+ int initX = mDisplaySize.x / 2 - initSize / 2;
+ int initY = mDisplaySize.y / 2 - initSize / 2;
+ mMagnificationFrame.set(initX, initY, initX + initSize, initY + initSize);
+ }
+
+ /**
+ * This is called once the surfaceView is created so the mirrored content can be placed as a
+ * child of the surfaceView.
+ */
+ private void createMirror() {
+ mMirrorSurface = WindowManagerWrapper.getInstance().mirrorDisplay(mDisplayId);
+ if (!mMirrorSurface.isValid()) {
+ return;
+ }
+ mTransaction.show(mMirrorSurface)
+ .reparent(mMirrorSurface, mMirrorSurfaceView.getSurfaceControl());
+
+ modifyWindowMagnification(mTransaction);
+ mTransaction.apply();
+ }
+
+ private void addDragTouchListeners() {
+ mDragView = mMirrorView.findViewById(R.id.drag_handle);
+ mLeftDrag = mMirrorView.findViewById(R.id.left_handle);
+ mTopDrag = mMirrorView.findViewById(R.id.top_handle);
+ mRightDrag = mMirrorView.findViewById(R.id.right_handle);
+ mBottomDrag = mMirrorView.findViewById(R.id.bottom_handle);
+
+ mDragView.setOnTouchListener(this);
+ mLeftDrag.setOnTouchListener(this);
+ mTopDrag.setOnTouchListener(this);
+ mRightDrag.setOnTouchListener(this);
+ mBottomDrag.setOnTouchListener(this);
+ }
+
+ /**
+ * Modifies the placement of the mirrored content.
+ */
+ private void modifyWindowMagnification(SurfaceControl.Transaction t) {
+ Rect sourceBounds = getSourceBounds(mMagnificationFrame, mScale);
+ // The final destination for the magnification surface should be at 0,0 since the
+ // ViewRootImpl's position will change
+ mTmpRect.set(0, 0, mMagnificationFrame.width(), mMagnificationFrame.height());
+
+ WindowManager.LayoutParams params =
+ (WindowManager.LayoutParams) mMirrorView.getLayoutParams();
+ params.x = mMagnificationFrame.left;
+ params.y = mMagnificationFrame.top;
+ mWm.updateViewLayout(mMirrorView, params);
+
+ t.setGeometry(mMirrorSurface, sourceBounds, mTmpRect, Surface.ROTATION_0);
+ }
+
+ @Override
+ public void onClick(View v) {
+ setMoveOffset(v, mMoveFrameAmountShort);
+ moveMirrorFromControls();
+ }
+
+ @Override
+ public boolean onLongClick(View v) {
+ mIsPressedDown = true;
+ setMoveOffset(v, mMoveFrameAmountLong);
+ mHandler.post(mMoveMirrorRunnable);
+ return true;
+ }
+
+ @Override
+ public boolean onTouch(View v, MotionEvent event) {
+ if (v == mLeftControl || v == mUpControl || v == mRightControl || v == mBottomControl) {
+ return handleControlTouchEvent(event);
+ } else if (v == mDragView || v == mLeftDrag || v == mTopDrag || v == mRightDrag
+ || v == mBottomDrag) {
+ return handleDragTouchEvent(event);
+ }
+ return false;
+ }
+
+ private boolean handleControlTouchEvent(MotionEvent event) {
+ switch (event.getAction()) {
+ case MotionEvent.ACTION_UP:
+ case MotionEvent.ACTION_CANCEL:
+ mIsPressedDown = false;
+ break;
+ }
+ return false;
+ }
+
+ private boolean handleDragTouchEvent(MotionEvent event) {
+ switch (event.getAction()) {
+ case MotionEvent.ACTION_DOWN:
+ mLastDrag.set(event.getRawX(), event.getRawY());
+ return true;
+ case MotionEvent.ACTION_MOVE:
+ int xDiff = (int) (event.getRawX() - mLastDrag.x);
+ int yDiff = (int) (event.getRawY() - mLastDrag.y);
+ mMagnificationFrame.offset(xDiff, yDiff);
+ mLastDrag.set(event.getRawX(), event.getRawY());
+ modifyWindowMagnification(mTransaction);
+ mTransaction.apply();
+ return true;
+ }
+ return false;
+ }
+
+ private void setMoveOffset(View v, int moveFrameAmount) {
+ mMoveWindowOffset.set(0, 0);
+
+ if (v == mLeftControl) {
+ mMoveWindowOffset.x = -moveFrameAmount;
+ } else if (v == mUpControl) {
+ mMoveWindowOffset.y = -moveFrameAmount;
+ } else if (v == mRightControl) {
+ mMoveWindowOffset.x = moveFrameAmount;
+ } else if (v == mBottomControl) {
+ mMoveWindowOffset.y = moveFrameAmount;
+ }
+ }
+
+ private void moveMirrorFromControls() {
+ mMagnificationFrame.offset(mMoveWindowOffset.x, mMoveWindowOffset.y);
+
+ modifyWindowMagnification(mTransaction);
+ mTransaction.apply();
+ }
+
+ /**
+ * Calculates the desired source bounds. This will be the area under from the center of the
+ * displayFrame, factoring in scale.
+ */
+ private Rect getSourceBounds(Rect displayFrame, float scale) {
+ int halfWidth = displayFrame.width() / 2;
+ int halfHeight = displayFrame.height() / 2;
+ int left = displayFrame.left + (halfWidth - (int) (halfWidth / scale));
+ int right = displayFrame.right - (halfWidth - (int) (halfWidth / scale));
+ int top = displayFrame.top + (halfHeight - (int) (halfHeight / scale));
+ int bottom = displayFrame.bottom - (halfHeight - (int) (halfHeight / scale));
+ return new Rect(left, top, right, bottom);
+ }
+
+ @Override
+ public void surfaceCreated(SurfaceHolder holder) {
+ createMirror();
+ }
+
+ @Override
+ public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
+ }
+
+ @Override
+ public void surfaceDestroyed(SurfaceHolder holder) {
+ }
+
+ class MoveMirrorRunnable implements Runnable {
+ @Override
+ public void run() {
+ if (mIsPressedDown) {
+ moveMirrorFromControls();
+ mHandler.postDelayed(mMoveMirrorRunnable, 100);
+ }
+ }
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/assist/AssistDisclosure.java b/packages/SystemUI/src/com/android/systemui/assist/AssistDisclosure.java
index 79d4f8d634ce..659629b59b45 100644
--- a/packages/SystemUI/src/com/android/systemui/assist/AssistDisclosure.java
+++ b/packages/SystemUI/src/com/android/systemui/assist/AssistDisclosure.java
@@ -70,6 +70,7 @@ public class AssistDisclosure {
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED,
PixelFormat.TRANSLUCENT);
lp.setTitle("AssistDisclosure");
+ lp.setFitWindowInsetsTypes(0 /* types */);
mWm.addView(mView, lp);
mViewAdded = true;
diff --git a/packages/SystemUI/src/com/android/systemui/assist/ui/DefaultUiController.java b/packages/SystemUI/src/com/android/systemui/assist/ui/DefaultUiController.java
index 4cb1708468ea..eb615a0392fa 100644
--- a/packages/SystemUI/src/com/android/systemui/assist/ui/DefaultUiController.java
+++ b/packages/SystemUI/src/com/android/systemui/assist/ui/DefaultUiController.java
@@ -85,6 +85,7 @@ public class DefaultUiController implements AssistManager.UiController {
PixelFormat.TRANSLUCENT);
mLayoutParams.privateFlags = WindowManager.LayoutParams.PRIVATE_FLAG_NO_MOVE_ANIMATION;
mLayoutParams.gravity = Gravity.BOTTOM;
+ mLayoutParams.setFitWindowInsetsTypes(0 /* types */);
mLayoutParams.setTitle("Assist");
mInvocationLightsView = (InvocationLightsView)
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
index 3948416ff4f7..36c89fdb2441 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
@@ -35,6 +35,7 @@ import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
+import android.view.WindowInsets.Type;
import android.view.WindowManager;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;
@@ -590,6 +591,7 @@ public class AuthContainerView extends LinearLayout
lp.privateFlags |= WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS;
lp.setTitle("BiometricPrompt");
lp.token = windowToken;
+ lp.setFitWindowInsetsTypes(lp.getFitWindowInsetsTypes() & ~Type.statusBars());
return lp;
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java
index 6b0d3c807079..e0ca1ace2ac4 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java
@@ -18,6 +18,7 @@ package com.android.systemui.biometrics;
import static android.hardware.biometrics.BiometricAuthenticator.TYPE_FACE;
import static android.hardware.biometrics.BiometricAuthenticator.TYPE_FINGERPRINT;
+import static android.hardware.biometrics.BiometricManager.Authenticators;
import android.app.ActivityManager;
import android.app.ActivityTaskManager;
@@ -29,7 +30,6 @@ import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
-import android.hardware.biometrics.Authenticator;
import android.hardware.biometrics.BiometricConstants;
import android.hardware.biometrics.BiometricPrompt;
import android.hardware.biometrics.IBiometricServiceReceiverInternal;
@@ -341,6 +341,10 @@ public class AuthController extends SystemUI implements CommandQueue.Callbacks,
if (DEBUG) Log.d(TAG, "hideAuthenticationDialog");
mCurrentDialog.dismissFromSystemServer();
+
+ // BiometricService will have already sent the callback to the client in this case.
+ // This avoids a round trip to SystemUI. So, just dismiss the dialog and we're done.
+ mCurrentDialog = null;
}
private void showDialog(SomeArgs args, boolean skipAnimation, Bundle savedState) {
@@ -416,7 +420,7 @@ public class AuthController extends SystemUI implements CommandQueue.Callbacks,
// TODO: Clean this up
Bundle bundle = (Bundle) mCurrentDialogArgs.arg1;
bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED,
- Authenticator.TYPE_CREDENTIAL);
+ Authenticators.DEVICE_CREDENTIAL);
}
showDialog(mCurrentDialogArgs, true /* skipAnimation */, savedState);
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/OWNERS b/packages/SystemUI/src/com/android/systemui/biometrics/OWNERS
new file mode 100644
index 000000000000..8765c9a64b77
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/OWNERS
@@ -0,0 +1,7 @@
+set noparent
+
+kchyn@google.com
+jaggies@google.com
+curtislb@google.com
+ilyamaty@google.com
+joshmccloskey@google.com
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/Utils.java b/packages/SystemUI/src/com/android/systemui/biometrics/Utils.java
index d6f830dd2e7a..7d237c45c7b3 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/Utils.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/Utils.java
@@ -16,23 +16,21 @@
package com.android.systemui.biometrics;
+import static android.hardware.biometrics.BiometricManager.Authenticators;
import static android.view.accessibility.AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE;
import android.annotation.IntDef;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
-import android.hardware.biometrics.Authenticator;
import android.hardware.biometrics.BiometricPrompt;
import android.os.Bundle;
import android.os.UserManager;
import android.util.DisplayMetrics;
-import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import com.android.internal.widget.LockPatternUtils;
-import com.android.systemui.R;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -71,12 +69,12 @@ public class Utils {
static boolean isDeviceCredentialAllowed(Bundle biometricPromptBundle) {
final int authenticators = getAuthenticators(biometricPromptBundle);
- return (authenticators & Authenticator.TYPE_CREDENTIAL) != 0;
+ return (authenticators & Authenticators.DEVICE_CREDENTIAL) != 0;
}
static boolean isBiometricAllowed(Bundle biometricPromptBundle) {
final int authenticators = getAuthenticators(biometricPromptBundle);
- return (authenticators & Authenticator.TYPE_BIOMETRIC) != 0;
+ return (authenticators & Authenticators.BIOMETRIC_WEAK) != 0;
}
static int getAuthenticators(Bundle biometricPromptBundle) {
diff --git a/packages/SystemUI/src/com/android/systemui/broadcast/BroadcastDispatcher.kt b/packages/SystemUI/src/com/android/systemui/broadcast/BroadcastDispatcher.kt
index adb288a9ce82..5cc70bc27c2a 100644
--- a/packages/SystemUI/src/com/android/systemui/broadcast/BroadcastDispatcher.kt
+++ b/packages/SystemUI/src/com/android/systemui/broadcast/BroadcastDispatcher.kt
@@ -46,7 +46,7 @@ private const val MSG_ADD_RECEIVER = 0
private const val MSG_REMOVE_RECEIVER = 1
private const val MSG_REMOVE_RECEIVER_FOR_USER = 2
private const val TAG = "BroadcastDispatcher"
-private const val DEBUG = false
+private const val DEBUG = true
/**
* SystemUI master Broadcast Dispatcher.
@@ -147,7 +147,13 @@ open class BroadcastDispatcher @Inject constructor (
when (msg.what) {
MSG_ADD_RECEIVER -> {
val data = msg.obj as ReceiverData
- val userId = data.user.identifier
+ // If the receiver asked to be registered under the current user, we register
+ // under the actual current user.
+ val userId = if (data.user.identifier == UserHandle.USER_CURRENT) {
+ context.userId
+ } else {
+ data.user.identifier
+ }
if (userId < UserHandle.USER_ALL) {
if (DEBUG) Log.w(TAG, "Register receiver for invalid user: $userId")
return
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BadgedImageView.java b/packages/SystemUI/src/com/android/systemui/bubbles/BadgedImageView.java
index a6a3ce06324f..dc2499602125 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BadgedImageView.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BadgedImageView.java
@@ -16,22 +16,15 @@
package com.android.systemui.bubbles;
import android.annotation.Nullable;
-import android.app.Notification;
import android.content.Context;
-import android.content.pm.LauncherApps;
+import android.graphics.Bitmap;
import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.Matrix;
import android.graphics.Path;
import android.graphics.Rect;
-import android.graphics.drawable.Drawable;
-import android.graphics.drawable.Icon;
import android.util.AttributeSet;
import android.util.PathParser;
import android.widget.ImageView;
-import com.android.internal.graphics.ColorUtils;
-import com.android.launcher3.icons.BitmapInfo;
import com.android.launcher3.icons.DotRenderer;
import com.android.systemui.Interpolators;
import com.android.systemui.R;
@@ -46,9 +39,9 @@ import com.android.systemui.R;
public class BadgedImageView extends ImageView {
/** Same value as Launcher3 dot code */
- private static final float WHITE_SCRIM_ALPHA = 0.54f;
+ public static final float WHITE_SCRIM_ALPHA = 0.54f;
/** Same as value in Launcher3 IconShape */
- private static final int DEFAULT_PATH_SIZE = 100;
+ public static final int DEFAULT_PATH_SIZE = 100;
static final int DOT_STATE_DEFAULT = 0;
static final int DOT_STATE_SUPPRESSED_FOR_FLYOUT = 1;
@@ -58,7 +51,6 @@ public class BadgedImageView extends ImageView {
private int mCurrentDotState = DOT_STATE_SUPPRESSED_FOR_FLYOUT;
private Bubble mBubble;
- private BubbleIconFactory mBubbleIconFactory;
private int mIconBitmapSize;
private DotRenderer mDotRenderer;
@@ -94,6 +86,18 @@ public class BadgedImageView extends ImageView {
mDotRenderer = new DotRenderer(mIconBitmapSize, iconPath, DEFAULT_PATH_SIZE);
}
+ /**
+ * Updates the view with provided info.
+ */
+ public void update(Bubble bubble, Bitmap bubbleImage, int dotColor, Path dotPath) {
+ mBubble = bubble;
+ setImageBitmap(bubbleImage);
+ setDotState(DOT_STATE_SUPPRESSED_FOR_FLYOUT);
+ mDotColor = dotColor;
+ drawDot(dotPath);
+ animateDot();
+ }
+
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
@@ -140,14 +144,6 @@ public class BadgedImageView extends ImageView {
}
/**
- * The colour to use for the dot.
- */
- void setDotColor(int color) {
- mDotColor = ColorUtils.setAlphaComponent(color, 255 /* alpha */);
- invalidate();
- }
-
- /**
* @param iconPath The new icon path to use when calculating dot position.
*/
void drawDot(Path iconPath) {
@@ -187,25 +183,6 @@ public class BadgedImageView extends ImageView {
}
/**
- * Populates this view with a bubble.
- * <p>
- * This should only be called when a new bubble is being set on the view, updates to the
- * current bubble should use {@link #update(Bubble)}.
- *
- * @param bubble the bubble to display in this view.
- */
- public void setBubble(Bubble bubble) {
- mBubble = bubble;
- }
-
- /**
- * @param factory Factory for creating normalized bubble icons.
- */
- public void setBubbleIconFactory(BubbleIconFactory factory) {
- mBubbleIconFactory = factory;
- }
-
- /**
* The key for the {@link Bubble} associated with this view, if one exists.
*/
@Nullable
@@ -213,15 +190,6 @@ public class BadgedImageView extends ImageView {
return (mBubble != null) ? mBubble.getKey() : null;
}
- /**
- * Updates the UI based on the bubble, updates badge and animates messages as needed.
- */
- public void update(Bubble bubble) {
- mBubble = bubble;
- setDotState(DOT_STATE_SUPPRESSED_FOR_FLYOUT);
- updateViews();
- }
-
int getDotColor() {
return mDotColor;
}
@@ -277,47 +245,4 @@ public class BadgedImageView extends ImageView {
}
}).start();
}
-
- void updateViews() {
- if (mBubble == null || mBubbleIconFactory == null) {
- return;
- }
-
- Drawable bubbleDrawable = getBubbleDrawable(mContext);
- BitmapInfo badgeBitmapInfo = mBubbleIconFactory.getBadgedBitmap(mBubble);
- BitmapInfo bubbleBitmapInfo = mBubbleIconFactory.getBubbleBitmap(bubbleDrawable,
- badgeBitmapInfo);
- setImageBitmap(bubbleBitmapInfo.icon);
-
- // Update badge.
- mDotColor = ColorUtils.blendARGB(badgeBitmapInfo.color, Color.WHITE, WHITE_SCRIM_ALPHA);
- setDotColor(mDotColor);
-
- // Update dot.
- Path iconPath = PathParser.createPathFromPathData(
- getResources().getString(com.android.internal.R.string.config_icon_mask));
- Matrix matrix = new Matrix();
- float scale = mBubbleIconFactory.getNormalizer().getScale(bubbleDrawable,
- null /* outBounds */, null /* path */, null /* outMaskShape */);
- float radius = BadgedImageView.DEFAULT_PATH_SIZE / 2f;
- matrix.setScale(scale /* x scale */, scale /* y scale */, radius /* pivot x */,
- radius /* pivot y */);
- iconPath.transform(matrix);
- drawDot(iconPath);
-
- animateDot();
- }
-
- Drawable getBubbleDrawable(Context context) {
- if (mBubble.getShortcutInfo() != null && mBubble.usingShortcutInfo()) {
- LauncherApps launcherApps =
- (LauncherApps) getContext().getSystemService(Context.LAUNCHER_APPS_SERVICE);
- int density = getContext().getResources().getConfiguration().densityDpi;
- return launcherApps.getShortcutIconDrawable(mBubble.getShortcutInfo(), density);
- } else {
- Notification.BubbleMetadata metadata = mBubble.getEntry().getBubbleMetadata();
- Icon ic = metadata.getIcon();
- return ic.loadDrawable(context);
- }
- }
}
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/Bubble.java b/packages/SystemUI/src/com/android/systemui/bubbles/Bubble.java
index f3a7ca9c0a75..77c8e0b07158 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/Bubble.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/Bubble.java
@@ -16,6 +16,7 @@
package com.android.systemui.bubbles;
+import static android.os.AsyncTask.Status.FINISHED;
import static android.view.Display.INVALID_DISPLAY;
import static com.android.internal.annotations.VisibleForTesting.Visibility.PRIVATE;
@@ -26,20 +27,17 @@ import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
-import android.content.pm.ApplicationInfo;
import android.content.pm.LauncherApps;
import android.content.pm.PackageManager;
import android.content.pm.ShortcutInfo;
import android.content.res.Resources;
import android.graphics.Rect;
-import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.UserHandle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
-import android.view.LayoutInflater;
import com.android.internal.annotations.VisibleForTesting;
import com.android.systemui.R;
@@ -59,19 +57,19 @@ class Bubble {
private NotificationEntry mEntry;
private final String mKey;
private final String mGroupId;
+
+ private long mLastUpdated;
+ private long mLastAccessed;
+
+ // Items that are typically loaded later
private String mAppName;
- private Drawable mUserBadgedAppIcon;
private ShortcutInfo mShortcutInfo;
-
- private boolean mInflated;
private BadgedImageView mIconView;
private BubbleExpandedView mExpandedView;
- private BubbleIconFactory mBubbleIconFactory;
-
- private long mLastUpdated;
- private long mLastAccessed;
- private boolean mIsUserCreated;
+ private boolean mInflated;
+ private BubbleViewInfoTask mInflationTask;
+ private boolean mInflateSynchronously;
/**
* Whether this notification should be shown in the shade when it is also displayed as a bubble.
@@ -94,37 +92,11 @@ class Bubble {
/** Used in tests when no UI is required. */
@VisibleForTesting(visibility = PRIVATE)
- Bubble(Context context, NotificationEntry e) {
+ Bubble(NotificationEntry e) {
mEntry = e;
mKey = e.getKey();
mLastUpdated = e.getSbn().getPostTime();
mGroupId = groupId(e);
-
- String shortcutId = e.getSbn().getNotification().getShortcutId();
- if (BubbleExperimentConfig.useShortcutInfoToBubble(context)
- && shortcutId != null) {
- mShortcutInfo = BubbleExperimentConfig.getShortcutInfo(context,
- e.getSbn().getPackageName(),
- e.getSbn().getUser(), shortcutId);
- }
-
- PackageManager pm = context.getPackageManager();
- ApplicationInfo info;
- try {
- info = pm.getApplicationInfo(
- mEntry.getSbn().getPackageName(),
- PackageManager.MATCH_UNINSTALLED_PACKAGES
- | PackageManager.MATCH_DISABLED_COMPONENTS
- | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
- | PackageManager.MATCH_DIRECT_BOOT_AWARE);
- if (info != null) {
- mAppName = String.valueOf(pm.getApplicationLabel(info));
- }
- Drawable appIcon = pm.getApplicationIcon(mEntry.getSbn().getPackageName());
- mUserBadgedAppIcon = pm.getUserBadgedIcon(appIcon, mEntry.getSbn().getUser());
- } catch (PackageManager.NameNotFoundException unused) {
- mAppName = mEntry.getSbn().getPackageName();
- }
}
public String getKey() {
@@ -143,41 +115,22 @@ class Bubble {
return mEntry.getSbn().getPackageName();
}
+ @Nullable
public String getAppName() {
return mAppName;
}
- Drawable getUserBadgedAppIcon() {
- return mUserBadgedAppIcon;
- }
-
@Nullable
public ShortcutInfo getShortcutInfo() {
return mShortcutInfo;
}
- /**
- * Whether shortcut information should be used to populate the bubble.
- * <p>
- * To populate the activity use {@link LauncherApps#startShortcut(ShortcutInfo, Rect, Bundle)}.
- * To populate the icon use {@link LauncherApps#getShortcutIconDrawable(ShortcutInfo, int)}.
- */
- public boolean usingShortcutInfo() {
- return BubbleExperimentConfig.isShortcutIntent(getBubbleIntent());
- }
-
- void setBubbleIconFactory(BubbleIconFactory factory) {
- mBubbleIconFactory = factory;
- }
-
- boolean isInflated() {
- return mInflated;
- }
-
+ @Nullable
BadgedImageView getIconView() {
return mIconView;
}
+ @Nullable
BubbleExpandedView getExpandedView() {
return mExpandedView;
}
@@ -188,20 +141,62 @@ class Bubble {
}
}
- void inflate(LayoutInflater inflater, BubbleStackView stackView) {
- if (mInflated) {
- return;
+ /**
+ * Sets whether to perform inflation on the same thread as the caller. This method should only
+ * be used in tests, not in production.
+ */
+ @VisibleForTesting
+ void setInflateSynchronously(boolean inflateSynchronously) {
+ mInflateSynchronously = inflateSynchronously;
+ }
+
+ /**
+ * Starts a task to inflate & load any necessary information to display a bubble.
+ *
+ * @param callback the callback to notify one the bubble is ready to be displayed.
+ * @param context the context for the bubble.
+ * @param stackView the stackView the bubble is eventually added to.
+ * @param iconFactory the iconfactory use to create badged images for the bubble.
+ */
+ void inflate(BubbleViewInfoTask.Callback callback,
+ Context context,
+ BubbleStackView stackView,
+ BubbleIconFactory iconFactory) {
+ if (isBubbleLoading()) {
+ mInflationTask.cancel(true /* mayInterruptIfRunning */);
+ }
+ mInflationTask = new BubbleViewInfoTask(this,
+ context,
+ stackView,
+ iconFactory,
+ callback);
+ if (mInflateSynchronously) {
+ mInflationTask.onPostExecute(mInflationTask.doInBackground());
+ } else {
+ mInflationTask.execute();
}
- mIconView = (BadgedImageView) inflater.inflate(
- R.layout.bubble_view, stackView, false /* attachToRoot */);
- mIconView.setBubbleIconFactory(mBubbleIconFactory);
- mIconView.setBubble(this);
+ }
- mExpandedView = (BubbleExpandedView) inflater.inflate(
- R.layout.bubble_expanded_view, stackView, false /* attachToRoot */);
- mExpandedView.setBubble(this, stackView);
+ private boolean isBubbleLoading() {
+ return mInflationTask != null && mInflationTask.getStatus() != FINISHED;
+ }
- mInflated = true;
+ boolean isInflated() {
+ return mInflated;
+ }
+
+ void setViewInfo(BubbleViewInfoTask.BubbleViewInfo info) {
+ if (!isInflated()) {
+ mIconView = info.imageView;
+ mExpandedView = info.expandedView;
+ mInflated = true;
+ }
+
+ mShortcutInfo = info.shortcutInfo;
+ mAppName = info.appName;
+
+ mExpandedView.update(this);
+ mIconView.update(this, info.badgedBubbleImage, info.dotColor, info.dotPath);
}
/**
@@ -218,13 +213,12 @@ class Bubble {
}
}
- void updateEntry(NotificationEntry entry) {
+ /**
+ * Sets the entry associated with this bubble.
+ */
+ void setEntry(NotificationEntry entry) {
mEntry = entry;
mLastUpdated = entry.getSbn().getPostTime();
- if (mInflated) {
- mIconView.update(this);
- mExpandedView.update(this);
- }
}
/**
@@ -242,13 +236,6 @@ class Bubble {
}
/**
- * @return the timestamp in milliseconds when this bubble was last displayed in expanded state
- */
- long getLastAccessTime() {
- return mLastAccessed;
- }
-
- /**
* @return the display id of the virtual display on which bubble contents is drawn.
*/
int getDisplayId() {
@@ -297,7 +284,9 @@ class Bubble {
* Whether the bubble for this notification should show a dot indicating updated content.
*/
boolean showDot() {
- return mShowBubbleUpdateDot && !mEntry.shouldSuppressNotificationDot();
+ return mShowBubbleUpdateDot
+ && !mEntry.shouldSuppressNotificationDot()
+ && !shouldSuppressNotification();
}
/**
@@ -305,6 +294,7 @@ class Bubble {
*/
boolean showFlyout() {
return !mSuppressFlyout && !mEntry.shouldSuppressPeek()
+ && !shouldSuppressNotification()
&& !mEntry.shouldSuppressNotificationList();
}
@@ -349,6 +339,16 @@ class Bubble {
}
}
+ /**
+ * Whether shortcut information should be used to populate the bubble.
+ * <p>
+ * To populate the activity use {@link LauncherApps#startShortcut(ShortcutInfo, Rect, Bundle)}.
+ * To populate the icon use {@link LauncherApps#getShortcutIconDrawable(ShortcutInfo, int)}.
+ */
+ boolean usingShortcutInfo() {
+ return BubbleExperimentConfig.isShortcutIntent(getBubbleIntent());
+ }
+
@Nullable
PendingIntent getBubbleIntent() {
Notification.BubbleMetadata data = mEntry.getBubbleMetadata();
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
index 19381940543e..7cd29ea48199 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
@@ -103,14 +103,11 @@ import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.List;
import java.util.function.Consumer;
import javax.inject.Inject;
import javax.inject.Singleton;
-import dagger.Lazy;
-
/**
* Bubbles are a special type of content that can "float" on top of other apps or System UI.
* Bubbles can be expanded to show more content.
@@ -147,12 +144,13 @@ public class BubbleController implements ConfigurationController.ConfigurationLi
private BubbleExpandListener mExpandListener;
@Nullable private BubbleStackView.SurfaceSynchronizer mSurfaceSynchronizer;
private final NotificationGroupManager mNotificationGroupManager;
- private final Lazy<ShadeController> mShadeController;
+ private final ShadeController mShadeController;
private final RemoteInputUriController mRemoteInputUriController;
private Handler mHandler = new Handler() {};
private BubbleData mBubbleData;
@Nullable private BubbleStackView mStackView;
+ private BubbleIconFactory mBubbleIconFactory;
// Tracks the id of the current (foreground) user.
private int mCurrentUserId;
@@ -162,6 +160,10 @@ public class BubbleController implements ConfigurationController.ConfigurationLi
// Saves notification keys of user created "fake" bubbles so that we can allow notifications
// like these to bubble by default. Doesn't persist across reboots, not a long-term solution.
private final HashSet<String> mUserCreatedBubbles;
+ // If we're auto-bubbling bubbles via a whitelist, we need to track which notifs from that app
+ // have been "demoted" back to a notification so that we don't auto-bubbles those again.
+ // Doesn't persist across reboots, not a long-term solution.
+ private final HashSet<String> mUserBlockedBubbles;
// Bubbles get added to the status bar view
private final StatusBarWindowController mStatusBarWindowController;
@@ -182,6 +184,8 @@ public class BubbleController implements ConfigurationController.ConfigurationLi
/** Last known orientation, used to detect orientation changes in {@link #onConfigChanged}. */
private int mOrientation = Configuration.ORIENTATION_UNDEFINED;
+ private boolean mInflateSynchronously;
+
/**
* Listener to be notified when some states of the bubbles change.
*/
@@ -243,7 +247,7 @@ public class BubbleController implements ConfigurationController.ConfigurationLi
public BubbleController(Context context,
StatusBarWindowController statusBarWindowController,
StatusBarStateController statusBarStateController,
- Lazy<ShadeController> shadeController,
+ ShadeController shadeController,
BubbleData data,
ConfigurationController configurationController,
NotificationInterruptionStateProvider interruptionStateProvider,
@@ -261,7 +265,7 @@ public class BubbleController implements ConfigurationController.ConfigurationLi
public BubbleController(Context context,
StatusBarWindowController statusBarWindowController,
StatusBarStateController statusBarStateController,
- Lazy<ShadeController> shadeController,
+ ShadeController shadeController,
BubbleData data,
@Nullable BubbleStackView.SurfaceSynchronizer synchronizer,
ConfigurationController configurationController,
@@ -272,6 +276,7 @@ public class BubbleController implements ConfigurationController.ConfigurationLi
NotificationEntryManager entryManager,
RemoteInputUriController remoteInputUriController) {
mContext = context;
+ mShadeController = shadeController;
mNotificationInterruptionStateProvider = interruptionStateProvider;
mNotifUserManager = notifUserManager;
mZenModeController = zenModeController;
@@ -319,7 +324,6 @@ public class BubbleController implements ConfigurationController.ConfigurationLi
}
});
- mShadeController = shadeController;
mStatusBarWindowController = statusBarWindowController;
mStatusBarStateListener = new StatusBarStateListener();
statusBarStateController.addCallback(mStatusBarStateListener);
@@ -348,8 +352,19 @@ public class BubbleController implements ConfigurationController.ConfigurationLi
});
mUserCreatedBubbles = new HashSet<>();
+ mUserBlockedBubbles = new HashSet<>();
mScreenshotHelper = new ScreenshotHelper(context);
+ mBubbleIconFactory = new BubbleIconFactory(context);
+ }
+
+ /**
+ * Sets whether to perform inflation on the same thread as the caller. This method should only
+ * be used in tests, not in production.
+ */
+ @VisibleForTesting
+ void setInflateSynchronously(boolean inflateSynchronously) {
+ mInflateSynchronously = inflateSynchronously;
}
/**
@@ -413,16 +428,23 @@ public class BubbleController implements ConfigurationController.ConfigurationLi
@Override
public void onUiModeChanged() {
- if (mStackView != null) {
- mStackView.onThemeChanged();
- }
+ updateForThemeChanges();
}
@Override
public void onOverlayChanged() {
+ updateForThemeChanges();
+ }
+
+ private void updateForThemeChanges() {
if (mStackView != null) {
mStackView.onThemeChanged();
}
+ mBubbleIconFactory = new BubbleIconFactory(mContext);
+ for (Bubble b: mBubbleData.getBubbles()) {
+ // Reload each bubble
+ b.inflate(null /* callback */, mContext, mStackView, mBubbleIconFactory);
+ }
}
@Override
@@ -506,14 +528,10 @@ public class BubbleController implements ConfigurationController.ConfigurationLi
return (isSummary && isSuppressedSummary) || isBubbleAndSuppressed;
}
- void selectBubble(Bubble bubble) {
- mBubbleData.setSelectedBubble(bubble);
- }
-
@VisibleForTesting
void selectBubble(String key) {
Bubble bubble = mBubbleData.getBubbleWithKey(key);
- selectBubble(bubble);
+ mBubbleData.setSelectedBubble(bubble);
}
/**
@@ -560,11 +578,19 @@ public class BubbleController implements ConfigurationController.ConfigurationLi
}
void updateBubble(NotificationEntry notif, boolean suppressFlyout, boolean showInShade) {
+ if (mStackView == null) {
+ // Lazy init stack view when a bubble is created
+ ensureStackViewCreated();
+ }
// If this is an interruptive notif, mark that it's interrupted
if (notif.getImportance() >= NotificationManager.IMPORTANCE_HIGH) {
notif.setInterruption();
}
- mBubbleData.notificationEntryUpdated(notif, suppressFlyout, showInShade);
+ Bubble bubble = mBubbleData.getOrCreateBubble(notif);
+ bubble.setInflateSynchronously(mInflateSynchronously);
+ bubble.inflate(
+ b -> mBubbleData.notificationEntryUpdated(b, suppressFlyout, showInShade),
+ mContext, mStackView, mBubbleIconFactory);
}
/**
@@ -579,10 +605,11 @@ public class BubbleController implements ConfigurationController.ConfigurationLi
if (DEBUG_EXPERIMENTS || DEBUG_BUBBLE_CONTROLLER) {
Log.d(TAG, "onUserCreatedBubble: " + entry.getKey());
}
- mShadeController.get().collapsePanel(true);
+ mShadeController.collapsePanel(true);
entry.setFlagBubble(true);
updateBubble(entry, true /* suppressFlyout */, false /* showInShade */);
mUserCreatedBubbles.add(entry.getKey());
+ mUserBlockedBubbles.remove(entry.getKey());
}
/**
@@ -598,6 +625,12 @@ public class BubbleController implements ConfigurationController.ConfigurationLi
entry.setFlagBubble(false);
removeBubble(entry.getKey(), DISMISS_BLOCKED);
mUserCreatedBubbles.remove(entry.getKey());
+ if (BubbleExperimentConfig.isPackageWhitelistedToAutoBubble(
+ mContext, entry.getSbn().getPackageName())) {
+ // This package is whitelist but user demoted the bubble, let's save it so we don't
+ // auto-bubble for the whitelist again.
+ mUserBlockedBubbles.add(entry.getKey());
+ }
}
/**
@@ -725,10 +758,11 @@ public class BubbleController implements ConfigurationController.ConfigurationLi
@SuppressWarnings("FieldCanBeLocal")
private final NotificationEntryListener mEntryListener = new NotificationEntryListener() {
@Override
- public void onPendingEntryAdded(NotificationEntry entry) {
+ public void onNotificationAdded(NotificationEntry entry) {
boolean previouslyUserCreated = mUserCreatedBubbles.contains(entry.getKey());
+ boolean userBlocked = mUserBlockedBubbles.contains(entry.getKey());
boolean wasAdjusted = BubbleExperimentConfig.adjustForExperiments(
- mContext, entry, previouslyUserCreated);
+ mContext, entry, previouslyUserCreated, userBlocked);
if (mNotificationInterruptionStateProvider.shouldBubbleUp(entry)
&& (canLaunchInActivityView(mContext, entry) || wasAdjusted)) {
@@ -743,8 +777,9 @@ public class BubbleController implements ConfigurationController.ConfigurationLi
@Override
public void onPreEntryUpdated(NotificationEntry entry) {
boolean previouslyUserCreated = mUserCreatedBubbles.contains(entry.getKey());
+ boolean userBlocked = mUserBlockedBubbles.contains(entry.getKey());
boolean wasAdjusted = BubbleExperimentConfig.adjustForExperiments(
- mContext, entry, previouslyUserCreated);
+ mContext, entry, previouslyUserCreated, userBlocked);
boolean shouldBubble = mNotificationInterruptionStateProvider.shouldBubbleUp(entry)
&& (canLaunchInActivityView(mContext, entry) || wasAdjusted);
@@ -772,16 +807,6 @@ public class BubbleController implements ConfigurationController.ConfigurationLi
@Override
public void applyUpdate(BubbleData.Update update) {
- if (mStackView == null && update.addedBubble != null) {
- // Lazy init stack view when the first bubble is added.
- ensureStackViewCreated();
- }
-
- // If not yet initialized, ignore all other changes.
- if (mStackView == null) {
- return;
- }
-
if (update.addedBubble != null) {
mStackView.addBubble(update.addedBubble);
}
@@ -878,12 +903,12 @@ public class BubbleController implements ConfigurationController.ConfigurationLi
if (DEBUG_BUBBLE_CONTROLLER) {
Log.d(TAG, "[BubbleData]");
- Log.d(TAG, formatBubblesString(mBubbleData.getBubbles(),
+ Log.d(TAG, BubbleDebugConfig.formatBubblesString(mBubbleData.getBubbles(),
mBubbleData.getSelectedBubble()));
if (mStackView != null) {
Log.d(TAG, "[BubbleStackView]");
- Log.d(TAG, formatBubblesString(mStackView.getBubblesOnScreen(),
+ Log.d(TAG, BubbleDebugConfig.formatBubblesString(mStackView.getBubblesOnScreen(),
mStackView.getExpandedBubble()));
}
}
@@ -972,23 +997,6 @@ public class BubbleController implements ConfigurationController.ConfigurationLi
pw.println();
}
- static String formatBubblesString(List<Bubble> bubbles, Bubble selected) {
- StringBuilder sb = new StringBuilder();
- for (Bubble bubble : bubbles) {
- if (bubble == null) {
- sb.append(" <null> !!!!!\n");
- } else {
- boolean isSelected = (bubble == selected);
- sb.append(String.format("%s Bubble{act=%12d, ongoing=%d, key=%s}\n",
- ((isSelected) ? "->" : " "),
- bubble.getLastActivity(),
- (bubble.isOngoing() ? 1 : 0),
- bubble.getKey()));
- }
- }
- return sb.toString();
- }
-
/**
* This task stack listener is responsible for responding to tasks moved to the front
* which are on the default (main) display. When this happens, expanded bubbles must be
@@ -1124,36 +1132,33 @@ public class BubbleController implements ConfigurationController.ConfigurationLi
}
private void sendScreenshotToBubble(Bubble bubble) {
- // delay allows the bubble menu to disappear before the screenshot
- // done here because we already have a Handler to delay with.
- // TODO: Hide bubble + menu UI from screenshots entirely instead of just delaying.
- mHandler.postDelayed(new Runnable() {
- @Override
- public void run() {
- mScreenshotHelper.takeScreenshot(
- android.view.WindowManager.TAKE_SCREENSHOT_FULLSCREEN,
- true /* hasStatus */,
- true /* hasNav */,
- mHandler,
- new Consumer<Uri>() {
- @Override
- public void accept(Uri uri) {
- if (uri != null) {
- NotificationEntry entry = bubble.getEntry();
- Pair<RemoteInput, Notification.Action> pair = entry.getSbn()
- .getNotification().findRemoteInputActionPair(false);
- RemoteInput remoteInput = pair.first;
- Notification.Action action = pair.second;
- Intent dataIntent = prepareRemoteInputFromData("image/png", uri,
- remoteInput, entry);
- sendRemoteInput(dataIntent, entry, action.actionIntent);
- mBubbleData.setSelectedBubble(bubble);
- mBubbleData.setExpanded(true);
- }
+ mScreenshotHelper.takeScreenshot(
+ android.view.WindowManager.TAKE_SCREENSHOT_FULLSCREEN,
+ true /* hasStatus */,
+ true /* hasNav */,
+ mHandler,
+ new Consumer<Uri>() {
+ @Override
+ public void accept(Uri uri) {
+ if (uri != null) {
+ NotificationEntry entry = bubble.getEntry();
+ Pair<RemoteInput, Notification.Action> pair = entry.getSbn()
+ .getNotification().findRemoteInputActionPair(false);
+ if (pair != null) {
+ RemoteInput remoteInput = pair.first;
+ Notification.Action action = pair.second;
+ Intent dataIntent = prepareRemoteInputFromData("image/png", uri,
+ remoteInput, entry);
+ sendRemoteInput(dataIntent, entry, action.actionIntent);
+ mBubbleData.setSelectedBubble(bubble);
+ mBubbleData.setExpanded(true);
+ } else {
+ Log.w(TAG, "No RemoteInput found for notification: "
+ + entry.getSbn().getKey());
}
- });
- }
- }, 200);
+ }
+ }
+ });
}
private final BubbleScreenshotListener mBubbleScreenshotListener =
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleData.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleData.java
index 034bff345d71..97224f1234dd 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleData.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleData.java
@@ -33,6 +33,7 @@ import android.util.Pair;
import androidx.annotation.Nullable;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.systemui.R;
import com.android.systemui.bubbles.BubbleController.DismissReason;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
@@ -57,8 +58,6 @@ public class BubbleData {
private static final String TAG = TAG_WITH_CLASS_NAME ? "BubbleData" : TAG_BUBBLES;
- private static final int MAX_BUBBLES = 5;
-
private static final Comparator<Bubble> BUBBLES_BY_SORT_KEY_DESCENDING =
Comparator.comparing(BubbleData::sortKey).reversed();
@@ -115,6 +114,7 @@ public class BubbleData {
private final List<Bubble> mBubbles;
private Bubble mSelectedBubble;
private boolean mExpanded;
+ private final int mMaxBubbles;
// State tracked during an operation -- keeps track of what listener events to dispatch.
private Update mStateChange;
@@ -144,6 +144,7 @@ public class BubbleData {
mContext = context;
mBubbles = new ArrayList<>();
mStateChange = new Update(mBubbles);
+ mMaxBubbles = mContext.getResources().getInteger(R.integer.bubbles_max_rendered);
}
public boolean hasBubbles() {
@@ -179,28 +180,44 @@ public class BubbleData {
dispatchPendingChanges();
}
- void notificationEntryUpdated(NotificationEntry entry, boolean suppressFlyout,
- boolean showInShade) {
+ /**
+ * Constructs a new bubble or returns an existing one. Does not add new bubbles to
+ * bubble data, must go through {@link #notificationEntryUpdated(Bubble, boolean, boolean)}
+ * for that.
+ */
+ Bubble getOrCreateBubble(NotificationEntry entry) {
+ Bubble bubble = getBubbleWithKey(entry.getKey());
+ if (bubble == null) {
+ bubble = new Bubble(entry);
+ } else {
+ bubble.setEntry(entry);
+ }
+ return bubble;
+ }
+
+ /**
+ * When this method is called it is expected that all info in the bubble has completed loading.
+ * @see Bubble#inflate(BubbleViewInfoTask.Callback, Context,
+ * BubbleStackView, BubbleIconFactory).
+ */
+ void notificationEntryUpdated(Bubble bubble, boolean suppressFlyout, boolean showInShade) {
if (DEBUG_BUBBLE_DATA) {
- Log.d(TAG, "notificationEntryUpdated: " + entry);
+ Log.d(TAG, "notificationEntryUpdated: " + bubble);
}
- Bubble bubble = getBubbleWithKey(entry.getKey());
- suppressFlyout |= !shouldShowFlyout(entry);
+ Bubble prevBubble = getBubbleWithKey(bubble.getKey());
+ suppressFlyout |= !shouldShowFlyout(bubble.getEntry());
- if (bubble == null) {
+ if (prevBubble == null) {
// Create a new bubble
- bubble = new Bubble(mContext, entry);
bubble.setSuppressFlyout(suppressFlyout);
doAdd(bubble);
trim();
} else {
// Updates an existing bubble
- bubble.updateEntry(entry);
bubble.setSuppressFlyout(suppressFlyout);
doUpdate(bubble);
}
-
if (bubble.shouldAutoExpand()) {
setSelectedBubbleInternal(bubble);
if (!mExpanded) {
@@ -213,6 +230,7 @@ public class BubbleData {
bubble.setShowInShade(!isBubbleExpandedAndSelected && showInShade);
bubble.setShowDot(!isBubbleExpandedAndSelected /* show */, true /* animate */);
dispatchPendingChanges();
+
}
public void notificationEntryRemoved(NotificationEntry entry, @DismissReason int reason) {
@@ -329,7 +347,7 @@ public class BubbleData {
}
private void trim() {
- if (mBubbles.size() > MAX_BUBBLES) {
+ if (mBubbles.size() > mMaxBubbles) {
mBubbles.stream()
// sort oldest first (ascending lastActivity)
.sorted(Comparator.comparingLong(Bubble::getLastActivity))
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleDebugConfig.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleDebugConfig.java
index a912eccd4d5e..319066221600 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleDebugConfig.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleDebugConfig.java
@@ -16,6 +16,8 @@
package com.android.systemui.bubbles;
+import java.util.List;
+
/**
* Common class for the various debug {@link android.util.Log} output configuration in the Bubbles
* package.
@@ -38,5 +40,23 @@ public class BubbleDebugConfig {
static final boolean DEBUG_BUBBLE_STACK_VIEW = false;
static final boolean DEBUG_BUBBLE_EXPANDED_VIEW = false;
static final boolean DEBUG_EXPERIMENTS = true;
+ static final boolean DEBUG_OVERFLOW = false;
+ static String formatBubblesString(List<Bubble> bubbles, Bubble selected) {
+ StringBuilder sb = new StringBuilder();
+ for (Bubble bubble : bubbles) {
+ if (bubble == null) {
+ sb.append(" <null> !!!!!\n");
+ } else {
+ boolean isSelected = (selected != null && bubble == selected);
+ String arrow = isSelected ? "=>" : " ";
+ sb.append(String.format("%s Bubble{act=%12d, ongoing=%d, key=%s}\n",
+ arrow,
+ bubble.getLastActivity(),
+ (bubble.isOngoing() ? 1 : 0),
+ bubble.getKey()));
+ }
+ }
+ return sb.toString();
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExpandedView.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExpandedView.java
index efc955d9bca4..c1705dbb4e4b 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExpandedView.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExpandedView.java
@@ -99,7 +99,6 @@ public class BubbleExpandedView extends LinearLayout implements View.OnClickList
private int mExpandedViewTouchSlop;
private Bubble mBubble;
- private String mAppName;
private BubbleController mBubbleController = Dependency.get(BubbleController.class);
private WindowManager mWindowManager;
@@ -275,17 +274,15 @@ public class BubbleExpandedView extends LinearLayout implements View.OnClickList
}
void applyThemeAttrs() {
- TypedArray ta = getContext().obtainStyledAttributes(R.styleable.BubbleExpandedView);
- int bgColor = ta.getColor(
- R.styleable.BubbleExpandedView_android_colorBackgroundFloating, Color.WHITE);
- float cornerRadius = ta.getDimension(
- R.styleable.BubbleExpandedView_android_dialogCornerRadius, 0);
+ final TypedArray ta = mContext.obtainStyledAttributes(
+ new int[] {
+ android.R.attr.colorBackgroundFloating,
+ android.R.attr.dialogCornerRadius});
+ int bgColor = ta.getColor(0, Color.WHITE);
+ float cornerRadius = ta.getDimensionPixelSize(1, 0);
ta.recycle();
- // Update triangle color.
mPointerDrawable.setTint(bgColor);
-
- // Update ActivityView cornerRadius
if (ScreenDecorationsUtils.supportsRoundedCornersOnWindows(mContext.getResources())) {
mActivityView.setCornerRadius(cornerRadius);
}
@@ -341,68 +338,51 @@ public class BubbleExpandedView extends LinearLayout implements View.OnClickList
}
}
- /**
- * Sets the bubble used to populate this view.
- */
- public void setBubble(Bubble bubble, BubbleStackView stackView) {
- if (DEBUG_BUBBLE_EXPANDED_VIEW) {
- Log.d(TAG, "setBubble: bubble=" + (bubble != null ? bubble.getKey() : "null"));
- }
+ void setStackView(BubbleStackView stackView) {
mStackView = stackView;
- mBubble = bubble;
- mAppName = bubble.getAppName();
-
- applyThemeAttrs();
- showSettingsIcon();
- updateExpandedView();
}
/**
- * Lets activity view know it should be shown / populated.
- */
- public void populateExpandedView() {
- if (DEBUG_BUBBLE_EXPANDED_VIEW) {
- Log.d(TAG, "populateExpandedView: "
- + "bubble=" + getBubbleKey());
- }
-
- if (usingActivityView()) {
- mActivityView.setCallback(mStateCallback);
- } else {
- Log.e(TAG, "Cannot populate expanded view.");
- }
- }
-
- /**
- * Updates the bubble backing this view. This will not re-populate ActivityView, it will
- * only update the deep-links in the title, and the height of the view.
+ * Sets the bubble used to populate this view.
*/
- public void update(Bubble bubble) {
+ void update(Bubble bubble) {
if (DEBUG_BUBBLE_EXPANDED_VIEW) {
Log.d(TAG, "update: bubble=" + (bubble != null ? bubble.getKey() : "null"));
}
- if (bubble.getKey().equals(mBubble.getKey())) {
+ boolean isNew = mBubble == null;
+ if (isNew || bubble.getKey().equals(mBubble.getKey())) {
mBubble = bubble;
- updateSettingsContentDescription();
- updateHeight();
+ mSettingsIcon.setContentDescription(getResources().getString(
+ R.string.bubbles_settings_button_description, bubble.getAppName()));
+
+ if (isNew) {
+ mBubbleIntent = mBubble.getBubbleIntent();
+ if (mBubbleIntent != null) {
+ setContentVisibility(false);
+ mActivityView.setVisibility(VISIBLE);
+ }
+ }
+ applyThemeAttrs();
} else {
Log.w(TAG, "Trying to update entry with different key, new bubble: "
+ bubble.getKey() + " old bubble: " + bubble.getKey());
}
}
- private void updateExpandedView() {
+ /**
+ * Lets activity view know it should be shown / populated with activity content.
+ */
+ void populateExpandedView() {
if (DEBUG_BUBBLE_EXPANDED_VIEW) {
- Log.d(TAG, "updateExpandedView: bubble="
- + getBubbleKey());
+ Log.d(TAG, "populateExpandedView: "
+ + "bubble=" + getBubbleKey());
}
- mBubbleIntent = mBubble.getBubbleIntent();
- if (mBubbleIntent != null) {
- setContentVisibility(false);
- mActivityView.setVisibility(VISIBLE);
+ if (usingActivityView()) {
+ mActivityView.setCallback(mStateCallback);
+ } else {
+ Log.e(TAG, "Cannot populate expanded view.");
}
- updateView();
}
boolean performBackPressIfNeeded() {
@@ -492,16 +472,6 @@ public class BubbleExpandedView extends LinearLayout implements View.OnClickList
}
}
- private void updateSettingsContentDescription() {
- mSettingsIcon.setContentDescription(getResources().getString(
- R.string.bubbles_settings_button_description, mAppName));
- }
-
- void showSettingsIcon() {
- updateSettingsContentDescription();
- mSettingsIcon.setVisibility(VISIBLE);
- }
-
/**
* Update appearance of the expanded view being displayed.
*/
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExperimentConfig.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExperimentConfig.java
index 8299f2261b8e..4c1cf49ecf9e 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExperimentConfig.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExperimentConfig.java
@@ -32,6 +32,9 @@ import android.content.Context;
import android.content.Intent;
import android.content.pm.LauncherApps;
import android.content.pm.ShortcutInfo;
+import android.graphics.Color;
+import android.graphics.drawable.BitmapDrawable;
+import android.graphics.drawable.Drawable;
import android.graphics.drawable.Icon;
import android.os.Bundle;
import android.os.Parcelable;
@@ -39,8 +42,11 @@ import android.os.UserHandle;
import android.provider.Settings;
import android.util.Log;
+import com.android.internal.graphics.ColorUtils;
import com.android.internal.util.ArrayUtils;
+import com.android.internal.util.ContrastColorUtil;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.people.PeopleHubNotificationListenerKt;
import java.util.ArrayList;
import java.util.Arrays;
@@ -143,7 +149,7 @@ public class BubbleExperimentConfig {
* @return whether an adjustment was made.
*/
static boolean adjustForExperiments(Context context, NotificationEntry entry,
- boolean previouslyUserCreated) {
+ boolean previouslyUserCreated, boolean userBlocked) {
Notification.BubbleMetadata metadata = null;
boolean addedMetadata = false;
boolean whiteListedToAutoBubble =
@@ -205,7 +211,9 @@ public class BubbleExperimentConfig {
}
}
- boolean bubbleForWhitelist = whiteListedToAutoBubble && (addedMetadata || hasMetadata);
+ boolean bubbleForWhitelist = !userBlocked
+ && whiteListedToAutoBubble
+ && (addedMetadata || hasMetadata);
if ((previouslyUserCreated && addedMetadata) || bubbleForWhitelist) {
// Update to a previous bubble (or new autobubble), set its flag now.
if (DEBUG_EXPERIMENTS) {
@@ -224,12 +232,30 @@ public class BubbleExperimentConfig {
// Use the icon of the person if available
List<Person> personList = getPeopleFromNotification(entry);
if (personList.size() > 0) {
- icon = personList.get(0).getIcon();
+ final Person person = personList.get(0);
+ if (person != null) {
+ icon = person.getIcon();
+ if (icon == null) {
+ // Lets try and grab the icon constructed by the layout
+ Drawable d = PeopleHubNotificationListenerKt.extractAvatarFromRow(entry);
+ if (d instanceof BitmapDrawable) {
+ icon = Icon.createWithBitmap(((BitmapDrawable) d).getBitmap());
+ }
+ }
+ }
}
if (icon == null) {
- icon = notification.getLargeIcon() != null
- ? notification.getLargeIcon()
- : notification.getSmallIcon();
+ boolean shouldTint = notification.getLargeIcon() == null;
+ icon = shouldTint
+ ? notification.getSmallIcon()
+ : notification.getLargeIcon();
+ if (shouldTint) {
+ int notifColor = entry.getSbn().getNotification().color;
+ notifColor = ColorUtils.setAlphaComponent(notifColor, 255);
+ notifColor = ContrastColorUtil.findContrastColor(notifColor, Color.WHITE,
+ true /* findFg */, 3f);
+ icon.setTint(notifColor);
+ }
}
if (intent != null) {
return new Notification.BubbleMetadata.Builder()
@@ -279,7 +305,7 @@ public class BubbleExperimentConfig {
}
static boolean isShortcutIntent(PendingIntent intent) {
- return intent.equals(sDummyShortcutIntent);
+ return intent != null && intent.equals(sDummyShortcutIntent);
}
static List<Person> getPeopleFromNotification(NotificationEntry entry) {
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleIconFactory.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleIconFactory.java
index 9ff033cb3411..b32dbb724258 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleIconFactory.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleIconFactory.java
@@ -15,11 +15,14 @@
*/
package com.android.systemui.bubbles;
+import android.app.Notification;
import android.content.Context;
+import android.content.pm.LauncherApps;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
+import android.graphics.drawable.Icon;
import com.android.launcher3.icons.BaseIconFactory;
import com.android.launcher3.icons.BitmapInfo;
@@ -42,19 +45,40 @@ public class BubbleIconFactory extends BaseIconFactory {
return mContext.getResources().getDimensionPixelSize(
com.android.launcher3.icons.R.dimen.profile_badge_size);
}
+ /**
+ * Returns the drawable that the developer has provided to display in the bubble.
+ */
+ Drawable getBubbleDrawable(Bubble b, Context context) {
+ if (b.getShortcutInfo() != null && b.usingShortcutInfo()) {
+ LauncherApps launcherApps =
+ (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE);
+ int density = context.getResources().getConfiguration().densityDpi;
+ return launcherApps.getShortcutIconDrawable(b.getShortcutInfo(), density);
+ } else {
+ Notification.BubbleMetadata metadata = b.getEntry().getBubbleMetadata();
+ Icon ic = metadata.getIcon();
+ return ic.loadDrawable(context);
+ }
+ }
- BitmapInfo getBadgedBitmap(Bubble b) {
+ /**
+ * Returns a {@link BitmapInfo} for the app-badge that is shown on top of each bubble. This
+ * will include the workprofile indicator on the badge if appropriate.
+ */
+ BitmapInfo getBadgeBitmap(Drawable userBadgedAppIcon) {
Bitmap userBadgedBitmap = createIconBitmap(
- b.getUserBadgedAppIcon(), 1f, getBadgeSize());
+ userBadgedAppIcon, 1f, getBadgeSize());
Canvas c = new Canvas();
ShadowGenerator shadowGenerator = new ShadowGenerator(getBadgeSize());
c.setBitmap(userBadgedBitmap);
shadowGenerator.recreateIcon(Bitmap.createBitmap(userBadgedBitmap), c);
- BitmapInfo bitmapInfo = createIconBitmap(userBadgedBitmap);
- return bitmapInfo;
+ return createIconBitmap(userBadgedBitmap);
}
+ /**
+ * Returns a {@link BitmapInfo} for the entire bubble icon including the badge.
+ */
BitmapInfo getBubbleBitmap(Drawable bubble, BitmapInfo badge) {
BitmapInfo bubbleIconInfo = createBadgedIconBitmap(bubble,
null /* user */,
@@ -64,5 +88,4 @@ public class BubbleIconFactory extends BaseIconFactory {
new BitmapDrawable(mContext.getResources(), badge.icon));
return bubbleIconInfo;
}
-
}
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleMenuView.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleMenuView.java
index e8eb72e8392f..bf8306561f1b 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleMenuView.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleMenuView.java
@@ -31,6 +31,9 @@ public class BubbleMenuView extends FrameLayout {
private FrameLayout mMenu;
private boolean mShowing = false;
+ /** Delay before taking a screenshot once the button is tapped to allow the menu time to hide.*/
+ public static final long SCREENSHOT_DELAY = 200;
+
public BubbleMenuView(Context context, AttributeSet attrs) {
super(context, attrs);
}
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleOverflowActivity.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleOverflowActivity.java
new file mode 100644
index 000000000000..018b6318575a
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleOverflowActivity.java
@@ -0,0 +1,69 @@
+package com.android.systemui.bubbles;
+
+import android.app.Activity;
+import android.content.res.TypedArray;
+import android.graphics.Color;
+import android.os.Bundle;
+
+import androidx.recyclerview.widget.GridLayoutManager;
+import androidx.recyclerview.widget.RecyclerView;
+
+import com.android.systemui.R;
+
+/**
+ * Activity for showing aged out bubbles.
+ * Must be public to be accessible to androidx...AppComponentFactory
+ */
+public class BubbleOverflowActivity extends Activity {
+ private RecyclerView mRecyclerView;
+ private int mMaxBubbles;
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.bubble_overflow_activity);
+ setBackgroundColor();
+
+ mMaxBubbles = getResources().getInteger(R.integer.bubbles_max_rendered);
+ mRecyclerView = findViewById(R.id.bubble_overflow_recycler);
+ mRecyclerView.setLayoutManager(
+ new GridLayoutManager(getApplicationContext(), /* numberOfColumns */ mMaxBubbles));
+ }
+
+ void setBackgroundColor() {
+ final TypedArray ta = getApplicationContext().obtainStyledAttributes(
+ new int[] {android.R.attr.colorBackgroundFloating});
+ int bgColor = ta.getColor(0, Color.WHITE);
+ ta.recycle();
+ findViewById(android.R.id.content).setBackgroundColor(bgColor);
+ }
+
+ @Override
+ public void onStart() {
+ super.onStart();
+ }
+
+ @Override
+ public void onRestart() {
+ super.onRestart();
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ }
+
+ @Override
+ public void onPause() {
+ super.onPause();
+ }
+
+ @Override
+ public void onStop() {
+ super.onStop();
+ }
+
+ public void onDestroy() {
+ super.onStop();
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
index 29a4bb1fca84..898768311031 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
@@ -516,14 +516,7 @@ public class BubbleStackView extends FrameLayout {
* Handle theme changes.
*/
public void onThemeChanged() {
- // Recreate icon factory to update default adaptive icon scale.
- mBubbleIconFactory = new BubbleIconFactory(mContext);
setUpFlyout();
- for (Bubble b: mBubbleData.getBubbles()) {
- b.getIconView().setBubbleIconFactory(mBubbleIconFactory);
- b.getIconView().updateViews();
- b.getExpandedView().applyThemeAttrs();
- }
}
/** Respond to the phone being rotated by repositioning the stack and hiding any flyouts. */
@@ -749,10 +742,6 @@ public class BubbleStackView extends FrameLayout {
mStackOnLeftOrWillBe = mStackAnimationController.isStackOnLeftSide();
}
- bubble.setBubbleIconFactory(mBubbleIconFactory);
- bubble.inflate(mInflater, this);
- bubble.getIconView().updateViews();
-
// Set the dot position to the opposite of the side the stack is resting on, since the stack
// resting slightly off-screen would result in the dot also being off-screen.
bubble.getIconView().setDotPosition(
@@ -1567,9 +1556,6 @@ public class BubbleStackView extends FrameLayout {
mExpandedViewContainer.setVisibility(mIsExpanded ? VISIBLE : GONE);
if (mIsExpanded) {
- // First update the view so that it calculates a new height (ensuring the y position
- // calculation is correct)
- mExpandedBubble.getExpandedView().updateView();
final float y = getExpandedViewY();
if (!mExpandedViewYAnim.isRunning()) {
// We're not animating so set the value
@@ -1731,17 +1717,18 @@ public class BubbleStackView extends FrameLayout {
*/
public void showBubbleMenu() {
PointF currentPos = mStackAnimationController.getStackPosition();
- float yPos = currentPos.y;
- float xPos = currentPos.x;
- if (mStackAnimationController.isStackOnLeftSide()) {
- xPos += mBubbleSize;
- } else {
- //TODO: Use the width of the menu instead of this fixed offset. Offset used for now
- // because menu width isn't correct the first time the menu is shown.
- xPos -= mBubbleMenuOffset;
- }
+ mBubbleMenuView.setVisibility(View.INVISIBLE);
+ post(() -> {
+ float yPos = currentPos.y;
+ float xPos = currentPos.x;
+ if (mStackAnimationController.isStackOnLeftSide()) {
+ xPos += mBubbleSize;
+ } else {
+ xPos -= mBubbleMenuView.getMenuView().getWidth();
+ }
- mBubbleMenuView.show(xPos, yPos);
+ mBubbleMenuView.show(xPos, yPos);
+ });
}
/**
@@ -1762,6 +1749,12 @@ public class BubbleStackView extends FrameLayout {
* Take a screenshot and send it to the specified bubble.
*/
public void sendScreenshotToBubble(Bubble bubble) {
- mBubbleScreenshotListener.onBubbleScreenshot(bubble);
+ hideBubbleMenu();
+ // delay allows the bubble menu to disappear before the screenshot
+ // done here because we already have a Handler to delay with.
+ // TODO: Hide bubble + menu UI from screenshots entirely instead of just delaying.
+ postDelayed(() -> {
+ mBubbleScreenshotListener.onBubbleScreenshot(bubble);
+ }, BubbleMenuView.SCREENSHOT_DELAY);
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleTouchHandler.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleTouchHandler.java
index b1d205c79c99..995b35f2b5b3 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleTouchHandler.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleTouchHandler.java
@@ -64,6 +64,7 @@ class BubbleTouchHandler implements View.OnTouchListener {
private boolean mMovedEnough;
private int mTouchSlopSquared;
private VelocityTracker mVelocityTracker;
+ private Runnable mShowBubbleMenuRunnable;
/** View that was initially touched, when we received the first ACTION_DOWN event. */
private View mTouchedView;
@@ -133,6 +134,11 @@ class BubbleTouchHandler implements View.OnTouchListener {
if (isStack) {
mViewPositionOnTouchDown.set(mStack.getStackPosition());
mStack.onDragStart();
+ if (!mStack.isShowingBubbleMenu() && !mStack.isExpanded()) {
+ mShowBubbleMenuRunnable = mStack::showBubbleMenu;
+ mStack.postDelayed(mShowBubbleMenuRunnable,
+ ViewConfiguration.getLongPressTimeout());
+ }
} else if (isFlyout) {
mStack.onFlyoutDragStart();
} else {
@@ -156,6 +162,7 @@ class BubbleTouchHandler implements View.OnTouchListener {
}
if (mMovedEnough) {
+ mStack.removeCallbacks(mShowBubbleMenuRunnable);
if (isStack) {
mStack.onDragged(viewX, viewY);
} else if (isFlyout) {
@@ -163,13 +170,6 @@ class BubbleTouchHandler implements View.OnTouchListener {
} else {
mStack.onBubbleDragged(mTouchedView, viewX, viewY);
}
- } else {
- float touchTime = event.getEventTime() - event.getDownTime();
- if (touchTime > ViewConfiguration.getLongPressTimeout() && !mStack.isExpanded()
- && BubbleExperimentConfig.allowBubbleScreenshotMenu(mContext)) {
- mStack.showBubbleMenu();
- return true;
- }
}
final boolean currentlyInDismissTarget = mStack.isInDismissTarget(event);
@@ -196,6 +196,8 @@ class BubbleTouchHandler implements View.OnTouchListener {
if (mStack.isShowingBubbleMenu()) {
resetForNextGesture();
return true;
+ } else {
+ mStack.removeCallbacks(mShowBubbleMenuRunnable);
}
trackMovement(event);
mVelocityTracker.computeCurrentVelocity(/* maxVelocity */ 1000);
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleViewInfoTask.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleViewInfoTask.java
new file mode 100644
index 000000000000..41f5028ed5c7
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleViewInfoTask.java
@@ -0,0 +1,182 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.bubbles;
+
+import static com.android.systemui.bubbles.BadgedImageView.DEFAULT_PATH_SIZE;
+import static com.android.systemui.bubbles.BadgedImageView.WHITE_SCRIM_ALPHA;
+import static com.android.systemui.bubbles.BubbleDebugConfig.TAG_BUBBLES;
+import static com.android.systemui.bubbles.BubbleDebugConfig.TAG_WITH_CLASS_NAME;
+
+import android.content.Context;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.ShortcutInfo;
+import android.graphics.Bitmap;
+import android.graphics.Color;
+import android.graphics.Matrix;
+import android.graphics.Path;
+import android.graphics.drawable.Drawable;
+import android.os.AsyncTask;
+import android.service.notification.StatusBarNotification;
+import android.util.Log;
+import android.util.PathParser;
+import android.view.LayoutInflater;
+
+import androidx.annotation.Nullable;
+
+import com.android.internal.graphics.ColorUtils;
+import com.android.launcher3.icons.BitmapInfo;
+import com.android.systemui.R;
+
+import java.lang.ref.WeakReference;
+
+/**
+ * Simple task to inflate views & load necessary info to display a bubble.
+ */
+public class BubbleViewInfoTask extends AsyncTask<Void, Void, BubbleViewInfoTask.BubbleViewInfo> {
+ private static final String TAG = TAG_WITH_CLASS_NAME ? "BubbleViewInfoTask" : TAG_BUBBLES;
+
+
+ /**
+ * Callback to find out when the bubble has been inflated & necessary data loaded.
+ */
+ public interface Callback {
+ /**
+ * Called when data has been loaded for the bubble.
+ */
+ void onBubbleViewsReady(Bubble bubble);
+ }
+
+ private Bubble mBubble;
+ private WeakReference<Context> mContext;
+ private WeakReference<BubbleStackView> mStackView;
+ private BubbleIconFactory mIconFactory;
+ private Callback mCallback;
+
+ /**
+ * Creates a task to load information for the provided {@link Bubble}. Once all info
+ * is loaded, {@link Callback} is notified.
+ */
+ BubbleViewInfoTask(Bubble b,
+ Context context,
+ BubbleStackView stackView,
+ BubbleIconFactory factory,
+ Callback c) {
+ mBubble = b;
+ mContext = new WeakReference<>(context);
+ mStackView = new WeakReference<>(stackView);
+ mIconFactory = factory;
+ mCallback = c;
+ }
+
+ @Override
+ protected BubbleViewInfo doInBackground(Void... voids) {
+ return BubbleViewInfo.populate(mContext.get(), mStackView.get(), mIconFactory, mBubble);
+ }
+
+ @Override
+ protected void onPostExecute(BubbleViewInfo viewInfo) {
+ if (viewInfo != null) {
+ mBubble.setViewInfo(viewInfo);
+ if (mCallback != null && !isCancelled()) {
+ mCallback.onBubbleViewsReady(mBubble);
+ }
+ }
+ }
+
+ static class BubbleViewInfo {
+ BadgedImageView imageView;
+ BubbleExpandedView expandedView;
+ ShortcutInfo shortcutInfo;
+ String appName;
+ Bitmap badgedBubbleImage;
+ int dotColor;
+ Path dotPath;
+
+ @Nullable
+ static BubbleViewInfo populate(Context c, BubbleStackView stackView,
+ BubbleIconFactory iconFactory, Bubble b) {
+ BubbleViewInfo info = new BubbleViewInfo();
+
+ // View inflation: only should do this once per bubble
+ if (!b.isInflated()) {
+ LayoutInflater inflater = LayoutInflater.from(c);
+ info.imageView = (BadgedImageView) inflater.inflate(
+ R.layout.bubble_view, stackView, false /* attachToRoot */);
+
+ info.expandedView = (BubbleExpandedView) inflater.inflate(
+ R.layout.bubble_expanded_view, stackView, false /* attachToRoot */);
+ info.expandedView.setStackView(stackView);
+ }
+
+ StatusBarNotification sbn = b.getEntry().getSbn();
+ String packageName = sbn.getPackageName();
+
+ // Shortcut info for this bubble
+ String shortcutId = sbn.getNotification().getShortcutId();
+ if (BubbleExperimentConfig.useShortcutInfoToBubble(c)
+ && shortcutId != null) {
+ info.shortcutInfo = BubbleExperimentConfig.getShortcutInfo(c,
+ packageName,
+ sbn.getUser(), shortcutId);
+ }
+
+ // App name & app icon
+ PackageManager pm = c.getPackageManager();
+ ApplicationInfo appInfo;
+ Drawable badgedIcon;
+ try {
+ appInfo = pm.getApplicationInfo(
+ packageName,
+ PackageManager.MATCH_UNINSTALLED_PACKAGES
+ | PackageManager.MATCH_DISABLED_COMPONENTS
+ | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
+ | PackageManager.MATCH_DIRECT_BOOT_AWARE);
+ if (appInfo != null) {
+ info.appName = String.valueOf(pm.getApplicationLabel(appInfo));
+ }
+ Drawable appIcon = pm.getApplicationIcon(packageName);
+ badgedIcon = pm.getUserBadgedIcon(appIcon, sbn.getUser());
+ } catch (PackageManager.NameNotFoundException exception) {
+ // If we can't find package... don't think we should show the bubble.
+ Log.w(TAG, "Unable to find package: " + packageName);
+ return null;
+ }
+
+ // Badged bubble image
+ Drawable bubbleDrawable = iconFactory.getBubbleDrawable(b, c);
+ BitmapInfo badgeBitmapInfo = iconFactory.getBadgeBitmap(badgedIcon);
+ info.badgedBubbleImage = iconFactory.getBubbleBitmap(bubbleDrawable,
+ badgeBitmapInfo).icon;
+
+ // Dot color & placement
+ Path iconPath = PathParser.createPathFromPathData(
+ c.getResources().getString(com.android.internal.R.string.config_icon_mask));
+ Matrix matrix = new Matrix();
+ float scale = iconFactory.getNormalizer().getScale(bubbleDrawable,
+ null /* outBounds */, null /* path */, null /* outMaskShape */);
+ float radius = DEFAULT_PATH_SIZE / 2f;
+ matrix.setScale(scale /* x scale */, scale /* y scale */, radius /* pivot x */,
+ radius /* pivot y */);
+ iconPath.transform(matrix);
+ info.dotPath = iconPath;
+ info.dotColor = ColorUtils.blendARGB(badgeBitmapInfo.color,
+ Color.WHITE, WHITE_SCRIM_ALPHA);
+ return info;
+ }
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/DefaultActivityBinder.java b/packages/SystemUI/src/com/android/systemui/dagger/DefaultActivityBinder.java
index 4593164869fd..df793109ae18 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/DefaultActivityBinder.java
+++ b/packages/SystemUI/src/com/android/systemui/dagger/DefaultActivityBinder.java
@@ -22,8 +22,6 @@ import com.android.systemui.ForegroundServicesDialog;
import com.android.systemui.keyguard.WorkLockActivity;
import com.android.systemui.settings.BrightnessDialog;
import com.android.systemui.tuner.TunerActivity;
-import com.android.systemui.usb.UsbDebuggingActivity;
-import com.android.systemui.usb.UsbDebuggingSecondaryUserActivity;
import dagger.Binds;
import dagger.Module;
@@ -58,17 +56,4 @@ public abstract class DefaultActivityBinder {
@IntoMap
@ClassKey(BrightnessDialog.class)
public abstract Activity bindBrightnessDialog(BrightnessDialog activity);
-
- /** Inject into UsbDebuggingActivity. */
- @Binds
- @IntoMap
- @ClassKey(UsbDebuggingActivity.class)
- public abstract Activity bindUsbDebuggingActivity(UsbDebuggingActivity activity);
-
- /** Inject into UsbDebuggingSecondaryUserActivity. */
- @Binds
- @IntoMap
- @ClassKey(UsbDebuggingSecondaryUserActivity.class)
- public abstract Activity bindUsbDebuggingSecondaryUserActivity(
- UsbDebuggingSecondaryUserActivity activity);
}
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/DependencyProvider.java b/packages/SystemUI/src/com/android/systemui/dagger/DependencyProvider.java
index 606605ad0292..0d161ceeecd5 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/DependencyProvider.java
+++ b/packages/SystemUI/src/com/android/systemui/dagger/DependencyProvider.java
@@ -20,6 +20,7 @@ import static com.android.systemui.Dependency.TIME_TICK_HANDLER_NAME;
import android.app.INotificationManager;
import android.content.Context;
+import android.content.pm.IPackageManager;
import android.hardware.display.AmbientDisplayConfiguration;
import android.hardware.display.NightDisplayListener;
import android.os.Handler;
@@ -34,7 +35,6 @@ import android.view.LayoutInflater;
import com.android.internal.logging.MetricsLogger;
import com.android.internal.widget.LockPatternUtils;
import com.android.keyguard.ViewMediatorCallback;
-import com.android.systemui.broadcast.BroadcastDispatcher;
import com.android.systemui.dagger.qualifiers.BgHandler;
import com.android.systemui.dagger.qualifiers.BgLooper;
import com.android.systemui.dagger.qualifiers.MainHandler;
@@ -53,8 +53,6 @@ import com.android.systemui.statusbar.phone.AutoHideController;
import com.android.systemui.statusbar.phone.ConfigurationControllerImpl;
import com.android.systemui.statusbar.policy.ConfigurationController;
import com.android.systemui.statusbar.policy.DataSaverController;
-import com.android.systemui.statusbar.policy.DeviceProvisionedController;
-import com.android.systemui.statusbar.policy.DeviceProvisionedControllerImpl;
import com.android.systemui.statusbar.policy.NetworkController;
import com.android.systemui.util.leak.LeakDetector;
@@ -150,6 +148,13 @@ public class DependencyProvider {
/** */
@Singleton
@Provides
+ public IPackageManager provideIPackageManager() {
+ return IPackageManager.Stub.asInterface(ServiceManager.getService("package"));
+ }
+
+ /** */
+ @Singleton
+ @Provides
public LayoutInflater providerLayoutInflater(Context context) {
return LayoutInflater.from(context);
}
@@ -215,13 +220,6 @@ public class DependencyProvider {
return DevicePolicyManagerWrapper.getInstance();
}
- @Singleton
- @Provides
- public DeviceProvisionedController provideDeviceProvisionedController(Context context,
- @MainHandler Handler mainHandler, BroadcastDispatcher broadcastDispatcher) {
- return new DeviceProvisionedControllerImpl(context, mainHandler, broadcastDispatcher);
- }
-
/** */
@Provides
public LockPatternUtils provideLockPatternUtils(Context context) {
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/SystemServicesModule.java b/packages/SystemUI/src/com/android/systemui/dagger/SystemServicesModule.java
index f032a33c45a9..534f350e4898 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/SystemServicesModule.java
+++ b/packages/SystemUI/src/com/android/systemui/dagger/SystemServicesModule.java
@@ -23,6 +23,7 @@ import android.app.AlarmManager;
import android.app.IActivityManager;
import android.app.IWallpaperManager;
import android.app.KeyguardManager;
+import android.app.NotificationManager;
import android.app.WallpaperManager;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
@@ -131,6 +132,12 @@ public class SystemServicesModule {
@Singleton
@Provides
+ static NotificationManager provideNotificationManager(Context context) {
+ return context.getSystemService(NotificationManager.class);
+ }
+
+ @Singleton
+ @Provides
static PackageManagerWrapper providePackageManagerWrapper() {
return PackageManagerWrapper.getInstance();
}
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIBinder.java b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIBinder.java
index 3cf14d65e5b8..99dd5e2356d6 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIBinder.java
+++ b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIBinder.java
@@ -21,6 +21,7 @@ import com.android.systemui.ScreenDecorations;
import com.android.systemui.SizeCompatModeActivityController;
import com.android.systemui.SliceBroadcastRelayHandler;
import com.android.systemui.SystemUI;
+import com.android.systemui.accessibility.WindowMagnification;
import com.android.systemui.biometrics.AuthController;
import com.android.systemui.globalactions.GlobalActionsComponent;
import com.android.systemui.keyguard.KeyguardViewMediator;
@@ -156,4 +157,10 @@ public abstract class SystemUIBinder {
@IntoMap
@ClassKey(VolumeUI.class)
public abstract SystemUI bindVolumeUI(VolumeUI sysui);
+
+ /** Inject into WindowMagnification. */
+ @Binds
+ @IntoMap
+ @ClassKey(WindowMagnification.class)
+ public abstract SystemUI bindWindowMagnification(WindowMagnification sysui);
}
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIDefaultModule.java b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIDefaultModule.java
index f44eae76ec50..5fc789c21f2a 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIDefaultModule.java
+++ b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIDefaultModule.java
@@ -39,7 +39,9 @@ import com.android.systemui.statusbar.phone.HeadsUpManagerPhone;
import com.android.systemui.statusbar.phone.KeyguardBypassController;
import com.android.systemui.statusbar.phone.KeyguardEnvironmentImpl;
import com.android.systemui.statusbar.phone.ShadeController;
-import com.android.systemui.statusbar.phone.StatusBar;
+import com.android.systemui.statusbar.phone.ShadeControllerImpl;
+import com.android.systemui.statusbar.policy.DeviceProvisionedController;
+import com.android.systemui.statusbar.policy.DeviceProvisionedControllerImpl;
import com.android.systemui.statusbar.policy.HeadsUpManager;
import java.util.Optional;
@@ -82,7 +84,7 @@ abstract class SystemUIDefaultModule {
KeyguardEnvironmentImpl keyguardEnvironment);
@Binds
- abstract ShadeController provideShadeController(StatusBar statusBar);
+ abstract ShadeController provideShadeController(ShadeControllerImpl shadeController);
@Singleton
@Provides
@@ -114,4 +116,8 @@ abstract class SystemUIDefaultModule {
CommandQueue commandQueue) {
return new Recents(context, recentsImplementation, commandQueue);
}
+
+ @Binds
+ abstract DeviceProvisionedController bindDeviceProvisionedController(
+ DeviceProvisionedControllerImpl deviceProvisionedController);
}
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeEvent.java b/packages/SystemUI/src/com/android/systemui/doze/DozeEvent.java
index ea1def07a309..d2fe39424875 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeEvent.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeEvent.java
@@ -28,10 +28,12 @@ import java.lang.annotation.RetentionPolicy;
* and triaging purposes.
*/
public class DozeEvent extends RichEvent {
- public static final int TOTAL_EVENT_TYPES = 19;
-
- public DozeEvent(int logLevel, int type, String reason) {
- super(logLevel, type, reason);
+ /**
+ * Initializes a doze event
+ */
+ public DozeEvent init(@EventType int type, String reason) {
+ super.init(DEBUG, type, reason);
+ return this;
}
/**
@@ -89,21 +91,6 @@ public class DozeEvent extends RichEvent {
}
}
- /**
- * Builds a DozeEvent.
- */
- public static class DozeEventBuilder extends RichEvent.Builder<DozeEventBuilder> {
- @Override
- public DozeEventBuilder getBuilder() {
- return this;
- }
-
- @Override
- public RichEvent build() {
- return new DozeEvent(mLogLevel, mType, mReason);
- }
- }
-
@IntDef({PICKUP_WAKEUP, PULSE_START, PULSE_FINISH, NOTIFICATION_PULSE, DOZING, FLING,
EMERGENCY_CALL, KEYGUARD_BOUNCER_CHANGED, SCREEN_ON, SCREEN_OFF, MISSED_TICK,
TIME_TICK_SCHEDULED, KEYGUARD_VISIBILITY_CHANGE, DOZE_STATE_CHANGED, WAKE_DISPLAY,
@@ -132,6 +119,7 @@ public class DozeEvent extends RichEvent {
public static final int PULSE_DROPPED = 16;
public static final int PULSE_DISABLED_BY_PROX = 17;
public static final int SENSOR_TRIGGERED = 18;
+ public static final int TOTAL_EVENT_TYPES = 19;
public static final int TOTAL_REASONS = 10;
@IntDef({PULSE_REASON_NONE, PULSE_REASON_INTENT, PULSE_REASON_NOTIFICATION,
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeLog.java b/packages/SystemUI/src/com/android/systemui/doze/DozeLog.java
index 2e4466d47927..fe504216b166 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeLog.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeLog.java
@@ -35,9 +35,11 @@ import javax.inject.Singleton;
* dependency DumpController DozeLog
*/
@Singleton
-public class DozeLog extends SysuiLog {
+public class DozeLog extends SysuiLog<DozeEvent> {
private static final String TAG = "DozeLog";
+ private DozeEvent mRecycledEvent;
+
private boolean mPulsing;
private long mSince;
private SummaryStats mPickupPulseNearVibrationStats;
@@ -73,8 +75,8 @@ public class DozeLog extends SysuiLog {
* Appends pickup wakeup event to the logs
*/
public void tracePickupWakeUp(boolean withinVibrationThreshold) {
- if (log(DozeEvent.PICKUP_WAKEUP,
- "withinVibrationThreshold=" + withinVibrationThreshold)) {
+ log(DozeEvent.PICKUP_WAKEUP, "withinVibrationThreshold=" + withinVibrationThreshold);
+ if (mEnabled) {
(withinVibrationThreshold ? mPickupPulseNearVibrationStats
: mPickupPulseNotNearVibrationStats).append();
}
@@ -85,27 +87,24 @@ public class DozeLog extends SysuiLog {
* @param reason why the pulse started
*/
public void tracePulseStart(@DozeEvent.Reason int reason) {
- if (log(DozeEvent.PULSE_START, DozeEvent.reasonToString(reason))) {
- mPulsing = true;
- }
+ log(DozeEvent.PULSE_START, DozeEvent.reasonToString(reason));
+ if (mEnabled) mPulsing = true;
}
/**
* Appends pulse finished event to the logs
*/
public void tracePulseFinish() {
- if (log(DozeEvent.PULSE_FINISH)) {
- mPulsing = false;
- }
+ log(DozeEvent.PULSE_FINISH);
+ if (mEnabled) mPulsing = false;
}
/**
* Appends pulse event to the logs
*/
public void traceNotificationPulse() {
- if (log(DozeEvent.NOTIFICATION_PULSE)) {
- mNotificationPulseStats.append();
- }
+ log(DozeEvent.NOTIFICATION_PULSE);
+ if (mEnabled) mNotificationPulseStats.append();
}
/**
@@ -113,9 +112,8 @@ public class DozeLog extends SysuiLog {
* @param dozing true if dozing, else false
*/
public void traceDozing(boolean dozing) {
- if (log(DozeEvent.DOZING, "dozing=" + dozing)) {
- mPulsing = false;
- }
+ log(DozeEvent.DOZING, "dozing=" + dozing);
+ if (mEnabled) mPulsing = false;
}
/**
@@ -133,9 +131,8 @@ public class DozeLog extends SysuiLog {
* Appends emergency call event to the logs
*/
public void traceEmergencyCall() {
- if (log(DozeEvent.EMERGENCY_CALL)) {
- mEmergencyCallStats.append();
- }
+ log(DozeEvent.EMERGENCY_CALL);
+ if (mEnabled) mEmergencyCallStats.append();
}
/**
@@ -150,7 +147,8 @@ public class DozeLog extends SysuiLog {
* Appends screen-on event to the logs
*/
public void traceScreenOn() {
- if (log(DozeEvent.SCREEN_ON, "pulsing=" + mPulsing)) {
+ log(DozeEvent.SCREEN_ON, "pulsing=" + mPulsing);
+ if (mEnabled) {
(mPulsing ? mScreenOnPulsingStats : mScreenOnNotPulsingStats).append();
mPulsing = false;
}
@@ -188,10 +186,8 @@ public class DozeLog extends SysuiLog {
* @param showing whether the keyguard is now showing
*/
public void traceKeyguard(boolean showing) {
- if (log(DozeEvent.KEYGUARD_VISIBILITY_CHANGE, "showing=" + showing)
- && !showing) {
- mPulsing = false;
- }
+ log(DozeEvent.KEYGUARD_VISIBILITY_CHANGE, "showing=" + showing);
+ if (mEnabled && !showing) mPulsing = false;
}
/**
@@ -217,12 +213,11 @@ public class DozeLog extends SysuiLog {
* @param reason why proximity result was triggered
*/
public void traceProximityResult(boolean near, long millis, @DozeEvent.Reason int reason) {
- if (log(DozeEvent.PROXIMITY_RESULT,
+ log(DozeEvent.PROXIMITY_RESULT,
" reason=" + DozeEvent.reasonToString(reason)
- + " near=" + near
- + " millis=" + millis)) {
- mProxStats[reason][near ? 0 : 1].append();
- }
+ + " near=" + near
+ + " millis=" + millis);
+ if (mEnabled) mProxStats[reason][near ? 0 : 1].append();
}
/**
@@ -250,15 +245,16 @@ public class DozeLog extends SysuiLog {
}
}
- private boolean log(@DozeEvent.EventType int eventType) {
- return log(eventType, "");
+ private void log(@DozeEvent.EventType int eventType) {
+ log(eventType, "");
}
- private boolean log(@DozeEvent.EventType int eventType, String msg) {
- return super.log(new DozeEvent.DozeEventBuilder()
- .setType(eventType)
- .setReason(msg)
- .build());
+ private void log(@DozeEvent.EventType int eventType, String msg) {
+ if (mRecycledEvent != null) {
+ mRecycledEvent = log(mRecycledEvent.init(eventType, msg));
+ } else {
+ mRecycledEvent = log(new DozeEvent().init(eventType, msg));
+ }
}
/**
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java b/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java
index 05a234f1e431..d008e665d171 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java
@@ -80,8 +80,7 @@ public class DozeSensors {
public DozeSensors(Context context, AlarmManager alarmManager, AsyncSensorManager sensorManager,
DozeParameters dozeParameters, AmbientDisplayConfiguration config, WakeLock wakeLock,
- Callback callback, Consumer<Boolean> proxCallback, AlwaysOnDisplayPolicy policy,
- DozeLog dozeLog) {
+ Callback callback, Consumer<Boolean> proxCallback, DozeLog dozeLog) {
mContext = context;
mAlarmManager = alarmManager;
mSensorManager = sensorManager;
@@ -154,7 +153,7 @@ public class DozeSensors {
};
mProximitySensor = new ProximitySensor(context.getResources(), sensorManager);
-
+ setProxListening(false); // Don't immediately start listening when we register.
mProximitySensor.register(
proximityEvent -> {
if (proximityEvent != null) {
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java b/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java
index 2d6b946fc67e..722dc038f853 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java
@@ -103,8 +103,7 @@ public class DozeTriggers implements DozeMachine.Part {
mWakeLock = wakeLock;
mAllowPulseTriggers = allowPulseTriggers;
mDozeSensors = new DozeSensors(context, alarmManager, mSensorManager, dozeParameters,
- config, wakeLock, this::onSensor, this::onProximityFar,
- dozeParameters.getPolicy(), dozeLog);
+ config, wakeLock, this::onSensor, this::onProximityFar, dozeLog);
mUiModeManager = mContext.getSystemService(UiModeManager.class);
mDockManager = dockManager;
mProxCheck = new ProximitySensor.ProximityCheck(proximitySensor, handler);
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeWallpaperState.java b/packages/SystemUI/src/com/android/systemui/doze/DozeWallpaperState.java
index 7f1b35678867..7aeb7851bbd1 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeWallpaperState.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeWallpaperState.java
@@ -16,6 +16,7 @@
package com.android.systemui.doze;
+import android.annotation.Nullable;
import android.app.IWallpaperManager;
import android.os.RemoteException;
import android.util.Log;
@@ -34,6 +35,7 @@ public class DozeWallpaperState implements DozeMachine.Part {
private static final String TAG = "DozeWallpaperState";
private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
+ @Nullable
private final IWallpaperManager mWallpaperManagerService;
private final DozeParameters mDozeParameters;
private final BiometricUnlockController mBiometricUnlockController;
@@ -79,16 +81,18 @@ public class DozeWallpaperState implements DozeMachine.Part {
if (isAmbientMode != mIsAmbientMode) {
mIsAmbientMode = isAmbientMode;
- try {
- long duration = animated ? StackStateAnimator.ANIMATION_DURATION_WAKEUP : 0L;
- if (DEBUG) {
- Log.i(TAG, "AOD wallpaper state changed to: " + mIsAmbientMode
+ if (mWallpaperManagerService != null) {
+ try {
+ long duration = animated ? StackStateAnimator.ANIMATION_DURATION_WAKEUP : 0L;
+ if (DEBUG) {
+ Log.i(TAG, "AOD wallpaper state changed to: " + mIsAmbientMode
+ ", animationDuration: " + duration);
+ }
+ mWallpaperManagerService.setInAmbientMode(mIsAmbientMode, duration);
+ } catch (RemoteException e) {
+ // Cannot notify wallpaper manager service, but it's fine, let's just skip it.
+ Log.w(TAG, "Cannot notify state to WallpaperManagerService: " + mIsAmbientMode);
}
- mWallpaperManagerService.setInAmbientMode(mIsAmbientMode, duration);
- } catch (RemoteException e) {
- // Cannot notify wallpaper manager service, but it's fine, let's just skip it.
- Log.w(TAG, "Cannot notify state to WallpaperManagerService: " + mIsAmbientMode);
}
}
}
@@ -97,5 +101,6 @@ public class DozeWallpaperState implements DozeMachine.Part {
public void dump(PrintWriter pw) {
pw.println("DozeWallpaperState:");
pw.println(" isAmbientMode: " + mIsAmbientMode);
+ pw.println(" hasWallpaperService: " + (mWallpaperManagerService != null));
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialog.java b/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialog.java
index 63a777154254..ef853e65c4a2 100644
--- a/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialog.java
+++ b/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialog.java
@@ -1562,6 +1562,7 @@ public class GlobalActionsDialog implements DialogInterface.OnDismissListener,
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
| WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
window.setType(WindowManager.LayoutParams.TYPE_VOLUME_OVERLAY);
+ window.setFitWindowInsetsTypes(0 /* types */);
setTitle(R.string.global_actions);
mPanelController = plugin;
diff --git a/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsImpl.java b/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsImpl.java
index 53053fc27216..d385123117d3 100644
--- a/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsImpl.java
@@ -120,6 +120,7 @@ public class GlobalActionsImpl implements GlobalActions, CommandQueue.Callbacks,
window.getAttributes().height = ViewGroup.LayoutParams.MATCH_PARENT;
window.getAttributes().layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
window.setType(WindowManager.LayoutParams.TYPE_VOLUME_OVERLAY);
+ window.setFitWindowInsetsTypes(0 /* types */);
window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
window.addFlags(
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
index 8d08b285134c..beba203b9702 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
@@ -210,8 +210,7 @@ public class KeyguardViewMediator extends SystemUI {
private AlarmManager mAlarmManager;
private AudioManager mAudioManager;
private StatusBarManager mStatusBarManager;
- private final StatusBarWindowController mStatusBarWindowController =
- Dependency.get(StatusBarWindowController.class);
+ private final StatusBarWindowController mStatusBarWindowController;
private final UiOffloadThread mUiOffloadThread = Dependency.get(UiOffloadThread.class);
private boolean mSystemReady;
@@ -688,12 +687,14 @@ public class KeyguardViewMediator extends SystemUI {
FalsingManager falsingManager,
LockPatternUtils lockPatternUtils,
BroadcastDispatcher broadcastDispatcher,
+ StatusBarWindowController statusBarWindowController,
Lazy<StatusBarKeyguardViewManager> statusBarKeyguardViewManagerLazy,
DismissCallbackRegistry dismissCallbackRegistry) {
super(context);
mFalsingManager = falsingManager;
mLockPatternUtils = lockPatternUtils;
mBroadcastDispatcher = broadcastDispatcher;
+ mStatusBarWindowController = statusBarWindowController;
mStatusBarKeyguardViewManagerLazy = statusBarKeyguardViewManagerLazy;
mDismissCallbackRegistry = dismissCallbackRegistry;
}
diff --git a/packages/SystemUI/src/com/android/systemui/log/Event.java b/packages/SystemUI/src/com/android/systemui/log/Event.java
index 92862a2bc74c..7bc1abfbb0d8 100644
--- a/packages/SystemUI/src/com/android/systemui/log/Event.java
+++ b/packages/SystemUI/src/com/android/systemui/log/Event.java
@@ -37,20 +37,28 @@ public class Event {
public static final int INFO = 4;
public static final int WARN = 5;
public static final int ERROR = 6;
+ public static final @Level int DEFAULT_LOG_LEVEL = DEBUG;
private long mTimestamp;
- private @Level int mLogLevel = DEBUG;
- protected String mMessage;
+ private @Level int mLogLevel = DEFAULT_LOG_LEVEL;
+ private String mMessage = "";
- public Event(String message) {
- mTimestamp = System.currentTimeMillis();
- mMessage = message;
+ /**
+ * initialize an event with a message
+ */
+ public Event init(String message) {
+ init(DEFAULT_LOG_LEVEL, message);
+ return this;
}
- public Event(@Level int logLevel, String message) {
+ /**
+ * initialize an event with a logLevel and message
+ */
+ public Event init(@Level int logLevel, String message) {
mTimestamp = System.currentTimeMillis();
mLogLevel = logLevel;
mMessage = message;
+ return this;
}
public String getMessage() {
@@ -64,4 +72,13 @@ public class Event {
public @Level int getLogLevel() {
return mLogLevel;
}
+
+ /**
+ * Recycle this event
+ */
+ void recycle() {
+ mTimestamp = -1;
+ mLogLevel = DEFAULT_LOG_LEVEL;
+ mMessage = "";
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/log/RichEvent.java b/packages/SystemUI/src/com/android/systemui/log/RichEvent.java
index acf761ed3936..470f2b0d1b98 100644
--- a/packages/SystemUI/src/com/android/systemui/log/RichEvent.java
+++ b/packages/SystemUI/src/com/android/systemui/log/RichEvent.java
@@ -23,23 +23,21 @@ package com.android.systemui.log;
* Events are stored in {@link SysuiLog} and can be printed in a dumpsys.
*/
public abstract class RichEvent extends Event {
- private final int mType;
- private final String mReason;
+ private int mType;
/**
- * Create a rich event that includes an event type that matches with an index in the array
+ * Initializes a rich event that includes an event type that matches with an index in the array
* getEventLabels().
*/
- public RichEvent(@Event.Level int logLevel, int type, String reason) {
- super(logLevel, null);
+ public RichEvent init(@Event.Level int logLevel, int type, String reason) {
final int numEvents = getEventLabels().length;
if (type < 0 || type >= numEvents) {
throw new IllegalArgumentException("Unsupported event type. Events only supported"
+ " from 0 to " + (numEvents - 1) + ", but given type=" + type);
}
mType = type;
- mReason = reason;
- mMessage = getEventLabels()[mType] + " " + mReason;
+ super.init(logLevel, getEventLabels()[mType] + " " + reason);
+ return this;
}
/**
@@ -49,25 +47,43 @@ public abstract class RichEvent extends Event {
*/
public abstract String[] getEventLabels();
- public int getType() {
- return mType;
+ @Override
+ public void recycle() {
+ super.recycle();
+ mType = -1;
}
- public String getReason() {
- return mReason;
+ public int getType() {
+ return mType;
}
/**
* Builder to build a RichEvent.
* @param <B> Log specific builder that is extending this builder
+ * @param <E> Type of event we'll be building
*/
- public abstract static class Builder<B extends Builder<B>> {
+ public abstract static class Builder<B extends Builder<B, E>, E extends RichEvent> {
public static final int UNINITIALIZED = -1;
+ public final SysuiLog mLog;
private B mBuilder = getBuilder();
- protected int mType = UNINITIALIZED;
+ protected int mType;
protected String mReason;
- protected @Level int mLogLevel = VERBOSE;
+ protected @Level int mLogLevel;
+
+ public Builder(SysuiLog sysuiLog) {
+ mLog = sysuiLog;
+ reset();
+ }
+
+ /**
+ * Reset this builder's parameters so it can be reused to build another RichEvent.
+ */
+ public void reset() {
+ mType = UNINITIALIZED;
+ mReason = null;
+ mLogLevel = VERBOSE;
+ }
/**
* Get the log-specific builder.
@@ -75,9 +91,9 @@ public abstract class RichEvent extends Event {
public abstract B getBuilder();
/**
- * Build the log-specific event.
+ * Build the log-specific event given an event to populate.
*/
- public abstract RichEvent build();
+ public abstract E build(E e);
/**
* Optional - set the log level. Defaults to DEBUG.
diff --git a/packages/SystemUI/src/com/android/systemui/log/SysuiLog.java b/packages/SystemUI/src/com/android/systemui/log/SysuiLog.java
index f094cb909cf2..4e15668f6a34 100644
--- a/packages/SystemUI/src/com/android/systemui/log/SysuiLog.java
+++ b/packages/SystemUI/src/com/android/systemui/log/SysuiLog.java
@@ -20,6 +20,7 @@ import android.os.Build;
import android.os.SystemProperties;
import android.util.Log;
+import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
import com.android.systemui.DumpController;
import com.android.systemui.Dumpable;
@@ -39,22 +40,26 @@ import java.util.Locale;
* To manually view the logs via adb:
* adb shell dumpsys activity service com.android.systemui/.SystemUIService \
* dependency DumpController <SysuiLogId>
+ *
+ * Logs can be disabled by setting the following SystemProperty and then restarting the device:
+ * adb shell setprop persist.sysui.log.enabled.<id> true/false && adb reboot
+ *
+ * @param <E> Type of event we'll be logging
*/
-public class SysuiLog implements Dumpable {
+public class SysuiLog<E extends Event> implements Dumpable {
public static final SimpleDateFormat DATE_FORMAT =
new SimpleDateFormat("MM-dd HH:mm:ss", Locale.US);
- private final Object mDataLock = new Object();
+ protected final Object mDataLock = new Object();
private final String mId;
private final int mMaxLogs;
- private boolean mEnabled;
+ protected boolean mEnabled;
+ protected boolean mLogToLogcatEnabled;
- @VisibleForTesting protected ArrayDeque<Event> mTimeline;
+ @VisibleForTesting protected ArrayDeque<E> mTimeline;
/**
* Creates a SysuiLog
- * To enable or disable logs, set the system property and then restart the device:
- * adb shell setprop sysui.log.enabled.<id> true/false && adb reboot
* @param dumpController where to register this logger's dumpsys
* @param id user-readable tag for this logger
* @param maxDebugLogs maximum number of logs to retain when {@link sDebuggable} is true
@@ -62,41 +67,42 @@ public class SysuiLog implements Dumpable {
*/
public SysuiLog(DumpController dumpController, String id, int maxDebugLogs, int maxLogs) {
this(dumpController, id, sDebuggable ? maxDebugLogs : maxLogs,
- SystemProperties.getBoolean(SYSPROP_ENABLED_PREFIX + id, DEFAULT_ENABLED));
+ SystemProperties.getBoolean(SYSPROP_ENABLED_PREFIX + id, DEFAULT_ENABLED),
+ SystemProperties.getBoolean(SYSPROP_LOGCAT_ENABLED_PREFIX + id,
+ DEFAULT_LOGCAT_ENABLED));
}
@VisibleForTesting
- protected SysuiLog(DumpController dumpController, String id, int maxLogs, boolean enabled) {
+ protected SysuiLog(DumpController dumpController, String id, int maxLogs, boolean enabled,
+ boolean logcatEnabled) {
mId = id;
mMaxLogs = maxLogs;
mEnabled = enabled;
+ mLogToLogcatEnabled = logcatEnabled;
mTimeline = mEnabled ? new ArrayDeque<>(mMaxLogs) : null;
dumpController.registerDumpable(mId, this);
}
- public SysuiLog(DumpController dumpController, String id) {
- this(dumpController, id, DEFAULT_MAX_DEBUG_LOGS, DEFAULT_MAX_LOGS);
- }
-
/**
* Logs an event to the timeline which can be printed by the dumpsys.
* May also log to logcat if enabled.
- * @return true if event was logged, else false
+ * @return the last event that was discarded from the Timeline (can be recycled)
*/
- public boolean log(Event event) {
+ public E log(E event) {
if (!mEnabled) {
- return false;
+ return null;
}
+ E recycledEvent = null;
synchronized (mDataLock) {
if (mTimeline.size() >= mMaxLogs) {
- mTimeline.removeFirst();
+ recycledEvent = mTimeline.removeFirst();
}
mTimeline.add(event);
}
- if (LOG_TO_LOGCAT_ENABLED) {
+ if (mLogToLogcatEnabled) {
final String strEvent = eventToString(event);
switch (event.getLogLevel()) {
case Event.VERBOSE:
@@ -116,13 +122,18 @@ public class SysuiLog implements Dumpable {
break;
}
}
- return true;
+
+ if (recycledEvent != null) {
+ recycledEvent.recycle();
+ }
+
+ return recycledEvent;
}
/**
* @return user-readable string of the given event with timestamp
*/
- public String eventToTimestampedString(Event event) {
+ private String eventToTimestampedString(Event event) {
StringBuilder sb = new StringBuilder();
sb.append(SysuiLog.DATE_FORMAT.format(event.getTimestamp()));
sb.append(" ");
@@ -137,9 +148,7 @@ public class SysuiLog implements Dumpable {
return event.getMessage();
}
- /**
- * only call on this method if you have the mDataLock
- */
+ @GuardedBy("mDataLock")
private void dumpTimelineLocked(PrintWriter pw) {
pw.println("\tTimeline:");
@@ -162,9 +171,10 @@ public class SysuiLog implements Dumpable {
}
private static boolean sDebuggable = Build.IS_DEBUGGABLE;
- private static final String SYSPROP_ENABLED_PREFIX = "sysui.log.enabled.";
- private static final boolean LOG_TO_LOGCAT_ENABLED = sDebuggable;
+ private static final String SYSPROP_ENABLED_PREFIX = "persist.sysui.log.enabled.";
+ private static final String SYSPROP_LOGCAT_ENABLED_PREFIX = "persist.sysui.log.enabled.logcat.";
private static final boolean DEFAULT_ENABLED = sDebuggable;
+ private static final boolean DEFAULT_LOGCAT_ENABLED = false;
private static final int DEFAULT_MAX_DEBUG_LOGS = 100;
private static final int DEFAULT_MAX_LOGS = 50;
}
diff --git a/packages/SystemUI/src/com/android/systemui/media/MediaProjectionPermissionActivity.java b/packages/SystemUI/src/com/android/systemui/media/MediaProjectionPermissionActivity.java
index f78429316e5a..66c51d278dab 100644
--- a/packages/SystemUI/src/com/android/systemui/media/MediaProjectionPermissionActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/media/MediaProjectionPermissionActivity.java
@@ -98,8 +98,10 @@ public class MediaProjectionPermissionActivity extends Activity
paint.setTextSize(42);
CharSequence dialogText = null;
+ CharSequence dialogTitle = null;
if (Utils.isHeadlessRemoteDisplayProvider(packageManager, mPackageName)) {
dialogText = getString(R.string.media_projection_dialog_service_text);
+ dialogTitle = getString(R.string.media_projection_dialog_service_title);
} else {
String label = aInfo.loadLabel(packageManager).toString();
@@ -138,10 +140,9 @@ public class MediaProjectionPermissionActivity extends Activity
appNameIndex, appNameIndex + appName.length(), 0);
}
dialogText = message;
+ dialogTitle = getString(R.string.media_projection_dialog_title, appName);
}
- String dialogTitle = getString(R.string.media_projection_dialog_title);
-
View dialogTitleView = View.inflate(this, R.layout.media_projection_dialog_title, null);
TextView titleText = (TextView) dialogTitleView.findViewById(R.id.dialog_title);
titleText.setText(dialogTitle);
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipDismissViewController.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipDismissViewController.java
index 3f15966c7fbb..750cc607abe3 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/phone/PipDismissViewController.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipDismissViewController.java
@@ -109,6 +109,7 @@ public class PipDismissViewController {
lp.setTitle("pip-dismiss-overlay");
lp.privateFlags |= WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS;
lp.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
+ lp.setFitWindowInsetsTypes(0 /* types */);
mWindowManager.addView(mDismissView, lp);
}
mDismissView.animate().cancel();
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java
index 2e90a3e28841..2347a476d145 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java
@@ -194,7 +194,8 @@ public class PipTouchHandler {
mMenuController.addListener(mMenuListener);
mDismissViewController = new PipDismissViewController(context);
mSnapAlgorithm = new PipSnapAlgorithm(mContext);
- mFlingAnimationUtils = new FlingAnimationUtils(context, 2.5f);
+ mFlingAnimationUtils = new FlingAnimationUtils(context.getResources().getDisplayMetrics(),
+ 2.5f);
mGestures = new PipTouchGesture[] {
mDefaultMovementGesture
};
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QuickQSMediaPlayer.java b/packages/SystemUI/src/com/android/systemui/qs/QuickQSMediaPlayer.java
index 5bb882e2355f..d40e25064352 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QuickQSMediaPlayer.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QuickQSMediaPlayer.java
@@ -250,6 +250,14 @@ public class QuickQSMediaPlayer {
return (state.getState() == PlaybackState.STATE_PLAYING);
}
+ /**
+ * Check whether this player has an attached media session.
+ * @return whether there is a controller with a current media session.
+ */
+ public boolean hasMediaSession() {
+ return mController != null && mController.getPlaybackState() != null;
+ }
+
private void addAlbumArtBackground(MediaMetadata metadata, int bgColor) {
Bitmap albumArt = metadata.getBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART);
float radius = mContext.getResources().getDimension(R.dimen.qs_media_corner_radius);
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java b/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java
index d377f1c793a9..db52e7d37a92 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java
@@ -57,6 +57,12 @@ public class QuickQSPanel extends QSPanel {
private int mMaxTiles;
protected QSPanel mFullPanel;
private QuickQSMediaPlayer mMediaPlayer;
+ private boolean mUsingMediaPlayer;
+ private LinearLayout mHorizontalLinearLayout;
+
+ // Only used with media
+ private QSTileLayout mMediaTileLayout;
+ private QSTileLayout mRegularTileLayout;
@Inject
public QuickQSPanel(@Named(VIEW_CONTEXT) Context context, AttributeSet attrs,
@@ -72,8 +78,9 @@ public class QuickQSPanel extends QSPanel {
removeView((View) mTileLayout);
}
- if (Utils.useQsMediaPlayer(context)) {
- LinearLayout mHorizontalLinearLayout = new LinearLayout(mContext);
+ mUsingMediaPlayer = Utils.useQsMediaPlayer(context);
+ if (mUsingMediaPlayer) {
+ mHorizontalLinearLayout = new LinearLayout(mContext);
mHorizontalLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
mHorizontalLinearLayout.setClipChildren(false);
mHorizontalLinearLayout.setClipToPadding(false);
@@ -81,6 +88,8 @@ public class QuickQSPanel extends QSPanel {
LayoutParams lp = new LayoutParams(0, LayoutParams.MATCH_PARENT, 1);
mTileLayout = new DoubleLineTileLayout(context);
+ mMediaTileLayout = mTileLayout;
+ mRegularTileLayout = new HeaderTileLayout(context);
lp.setMarginEnd(10);
lp.setMarginStart(0);
mHorizontalLinearLayout.addView((View) mTileLayout, lp);
@@ -95,6 +104,8 @@ public class QuickQSPanel extends QSPanel {
mTileLayout.setListening(mListening);
addView(mHorizontalLinearLayout, 0 /* Between brightness and footer */);
+ ((View) mRegularTileLayout).setVisibility(View.GONE);
+ addView((View) mRegularTileLayout, 0);
super.setPadding(0, 0, 0, 0);
} else {
sDefaultMaxTiles = getResources().getInteger(R.integer.quick_qs_panel_max_columns);
@@ -130,6 +141,8 @@ public class QuickQSPanel extends QSPanel {
Dependency.get(TunerService.class).removeTunable(mNumTiles);
}
+
+
@Override
protected String getDumpableTag() {
return TAG;
@@ -152,6 +165,42 @@ public class QuickQSPanel extends QSPanel {
super.drawTile(r, state);
}
+ boolean switchTileLayout() {
+ if (!mUsingMediaPlayer) return false;
+ if (mMediaPlayer.hasMediaSession()
+ && mHorizontalLinearLayout.getVisibility() == View.GONE) {
+ mHorizontalLinearLayout.setVisibility(View.VISIBLE);
+ ((View) mRegularTileLayout).setVisibility(View.GONE);
+ mTileLayout.setListening(false);
+ for (TileRecord record : mRecords) {
+ mTileLayout.removeTile(record);
+ record.tile.removeCallback(record.callback);
+ }
+ mTileLayout = mMediaTileLayout;
+ if (mHost != null) setTiles(mHost.getTiles());
+ mTileLayout.setListening(mListening);
+ return true;
+ } else if (!mMediaPlayer.hasMediaSession()
+ && mHorizontalLinearLayout.getVisibility() == View.VISIBLE) {
+ mHorizontalLinearLayout.setVisibility(View.GONE);
+ ((View) mRegularTileLayout).setVisibility(View.VISIBLE);
+ mTileLayout.setListening(false);
+ for (TileRecord record : mRecords) {
+ mTileLayout.removeTile(record);
+ record.tile.removeCallback(record.callback);
+ }
+ mTileLayout = mRegularTileLayout;
+ if (mHost != null) setTiles(mHost.getTiles());
+ mTileLayout.setListening(mListening);
+ return true;
+ }
+ return false;
+ }
+
+ public boolean hasMediaPlayerSession() {
+ return mMediaPlayer.hasMediaSession();
+ }
+
@Override
public void setHost(QSTileHost host, QSCustomizer customizer) {
super.setHost(host, customizer);
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java b/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java
index e5cec878b63d..d4af1548af41 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java
@@ -339,7 +339,7 @@ public class QuickStatusBarHeader extends RelativeLayout implements
if (mQsDisabled) {
lp.height = resources.getDimensionPixelSize(
com.android.internal.R.dimen.quick_qs_offset_height);
- } else if (useQsMediaPlayer(mContext)) {
+ } else if (useQsMediaPlayer(mContext) && mHeaderQsPanel.hasMediaPlayerSession()) {
lp.height = Math.max(getMinimumHeight(),
resources.getDimensionPixelSize(
com.android.internal.R.dimen.quick_qs_total_height_with_media));
@@ -405,6 +405,11 @@ public class QuickStatusBarHeader extends RelativeLayout implements
mHeaderTextContainerView.setVisibility(INVISIBLE);
}
}
+ if (expansionFraction < 1 && expansionFraction > 0.99) {
+ if (mHeaderQsPanel.switchTileLayout()) {
+ updateResources();
+ }
+ }
}
public void disable(int state1, int state2, boolean animate) {
@@ -453,6 +458,9 @@ public class QuickStatusBarHeader extends RelativeLayout implements
return;
}
mHeaderQsPanel.setListening(listening);
+ if (mHeaderQsPanel.switchTileLayout()) {
+ updateResources();
+ }
mListening = listening;
if (listening) {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tileimpl/QSTileImpl.java b/packages/SystemUI/src/com/android/systemui/qs/tileimpl/QSTileImpl.java
index e0f26cd1a267..1d379110325a 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tileimpl/QSTileImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tileimpl/QSTileImpl.java
@@ -413,6 +413,7 @@ public abstract class QSTileImpl<TState extends State> implements QSTile, Lifecy
handleSetListening(false);
}
mCallbacks.clear();
+ mHandler.removeCallbacksAndMessages(null);
}
protected void checkIfRestrictionEnforcedByAdminOnly(State state, String userRestriction) {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/UiModeNightTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/UiModeNightTile.java
index 9fe9703e4181..7bc2a0d5c97d 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/UiModeNightTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/UiModeNightTile.java
@@ -92,7 +92,10 @@ public class UiModeNightTile extends QSTileImpl<QSTile.BooleanState> implements
boolean nightMode = (mContext.getResources().getConfiguration().uiMode
& Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES;
- if (isAuto) {
+ if (powerSave) {
+ state.secondaryLabel = mContext.getResources().getString(
+ R.string.quick_settings_dark_mode_secondary_label_battery_saver);
+ } else if (isAuto) {
state.secondaryLabel = mContext.getResources().getString(nightMode
? R.string.quick_settings_dark_mode_secondary_label_until_sunrise
: R.string.quick_settings_dark_mode_secondary_label_on_at_sunset);
@@ -100,9 +103,7 @@ public class UiModeNightTile extends QSTileImpl<QSTile.BooleanState> implements
state.secondaryLabel = null;
}
state.value = nightMode;
- state.label = mContext.getString(powerSave
- ? R.string.quick_settings_ui_mode_night_label_battery_saver
- : R.string.quick_settings_ui_mode_night_label);
+ state.label = mContext.getString(R.string.quick_settings_ui_mode_night_label);
state.icon = mIcon;
state.contentDescription = TextUtils.isEmpty(state.secondaryLabel)
? state.label
@@ -123,7 +124,7 @@ public class UiModeNightTile extends QSTileImpl<QSTile.BooleanState> implements
@Override
public Intent getLongClickIntent() {
- return new Intent(Settings.ACTION_DISPLAY_SETTINGS);
+ return new Intent(Settings.ACTION_DARK_THEME_SETTINGS);
}
@Override
diff --git a/packages/SystemUI/src/com/android/systemui/recents/ScreenPinningRequest.java b/packages/SystemUI/src/com/android/systemui/recents/ScreenPinningRequest.java
index d819b8eb5bec..1d649eee4d57 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/ScreenPinningRequest.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/ScreenPinningRequest.java
@@ -138,6 +138,7 @@ public class ScreenPinningRequest implements View.OnClickListener,
lp.privateFlags |= WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS;
lp.setTitle("ScreenPinningConfirmation");
lp.gravity = Gravity.FILL;
+ lp.setFitWindowInsetsTypes(0 /* types */);
return lp;
}
diff --git a/packages/SystemUI/src/com/android/systemui/screenrecord/RecordingService.java b/packages/SystemUI/src/com/android/systemui/screenrecord/RecordingService.java
index 0383dee4f9c3..d3ccbeb0afb1 100644
--- a/packages/SystemUI/src/com/android/systemui/screenrecord/RecordingService.java
+++ b/packages/SystemUI/src/com/android/systemui/screenrecord/RecordingService.java
@@ -371,7 +371,8 @@ public class RecordingService extends Service {
Bitmap thumbnailBitmap = null;
try {
ContentResolver resolver = getContentResolver();
- Size size = Point.convert(MediaStore.ThumbnailConstants.MINI_SIZE);
+ DisplayMetrics metrics = getResources().getDisplayMetrics();
+ Size size = new Size(metrics.widthPixels, metrics.heightPixels / 2);
thumbnailBitmap = resolver.loadThumbnail(uri, size, null);
} catch (IOException e) {
Log.e(TAG, "Error creating thumbnail: " + e.getMessage());
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/GlobalScreenshot.java b/packages/SystemUI/src/com/android/systemui/screenshot/GlobalScreenshot.java
index 50413548dbba..00220cef5d7c 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/GlobalScreenshot.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/GlobalScreenshot.java
@@ -258,6 +258,7 @@ public class GlobalScreenshot {
PixelFormat.TRANSLUCENT);
mWindowLayoutParams.setTitle("ScreenshotAnimation");
mWindowLayoutParams.layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
+ mWindowLayoutParams.setFitWindowInsetsTypes(0 /* types */);
mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
mNotificationManager =
(NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/SaveImageInBackgroundTask.java b/packages/SystemUI/src/com/android/systemui/screenshot/SaveImageInBackgroundTask.java
index 76925b43cfb8..2f401e5271d8 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/SaveImageInBackgroundTask.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/SaveImageInBackgroundTask.java
@@ -23,6 +23,8 @@ import android.app.PendingIntent;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ComponentName;
+import android.content.ContentResolver;
+import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.UserInfo;
@@ -48,7 +50,9 @@ import android.os.UserHandle;
import android.os.UserManager;
import android.provider.DeviceConfig;
import android.provider.MediaStore;
+import android.provider.MediaStore.MediaColumns;
import android.text.TextUtils;
+import android.text.format.DateUtils;
import android.util.Slog;
import com.android.internal.annotations.VisibleForTesting;
@@ -275,6 +279,7 @@ class SaveImageInBackgroundTask extends AsyncTask<Void, Void, Void> {
Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Context context = mParams.context;
+ ContentResolver resolver = context.getContentResolver();
Bitmap image = mParams.image;
Resources r = context.getResources();
@@ -284,23 +289,27 @@ class SaveImageInBackgroundTask extends AsyncTask<Void, Void, Void> {
mSmartActionsProvider, mSmartActionsEnabled, isManagedProfile(context));
// Save the screenshot to the MediaStore
- final MediaStore.PendingParams params = new MediaStore.PendingParams(
- MediaStore.Images.Media.EXTERNAL_CONTENT_URI, mImageFileName, "image/png");
- params.setRelativePath(Environment.DIRECTORY_PICTURES + File.separator
- + Environment.DIRECTORY_SCREENSHOTS);
-
- final Uri uri = MediaStore.createPending(context, params);
- final MediaStore.PendingSession session = MediaStore.openPending(context, uri);
+ final ContentValues values = new ContentValues();
+ values.put(MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES
+ + File.separator + Environment.DIRECTORY_SCREENSHOTS);
+ values.put(MediaColumns.DISPLAY_NAME, mImageFileName);
+ values.put(MediaColumns.MIME_TYPE, "image/png");
+ values.put(MediaColumns.DATE_ADDED, mImageTime / 1000);
+ values.put(MediaColumns.DATE_MODIFIED, mImageTime / 1000);
+ values.put(MediaColumns.DATE_EXPIRES, (mImageTime + DateUtils.DAY_IN_MILLIS) / 1000);
+ values.put(MediaColumns.IS_PENDING, 1);
+
+ final Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
try {
// First, write the actual data for our screenshot
- try (OutputStream out = session.openOutputStream()) {
+ try (OutputStream out = resolver.openOutputStream(uri)) {
if (!image.compress(Bitmap.CompressFormat.PNG, 100, out)) {
throw new IOException("Failed to compress");
}
}
// Next, write metadata to help index the screenshot
- try (ParcelFileDescriptor pfd = session.open()) {
+ try (ParcelFileDescriptor pfd = resolver.openFile(uri, "rw", null)) {
final ExifInterface exif = new ExifInterface(pfd.getFileDescriptor());
exif.setAttribute(ExifInterface.TAG_SOFTWARE,
@@ -327,12 +336,15 @@ class SaveImageInBackgroundTask extends AsyncTask<Void, Void, Void> {
exif.saveAttributes();
}
- session.publish();
+
+ // Everything went well above, publish it!
+ values.clear();
+ values.put(MediaColumns.IS_PENDING, 0);
+ values.putNull(MediaColumns.DATE_EXPIRES);
+ resolver.update(uri, values, null, null);
} catch (Exception e) {
- session.abandon();
+ resolver.delete(uri, null);
throw e;
- } finally {
- IoUtils.closeQuietly(session);
}
populateNotificationActions(context, r, uri, smartActionsFuture, mNotificationBuilder);
diff --git a/packages/SystemUI/src/com/android/systemui/settings/CurrentUserTracker.java b/packages/SystemUI/src/com/android/systemui/settings/CurrentUserTracker.java
index 9f79785be56e..077d2602e43f 100644
--- a/packages/SystemUI/src/com/android/systemui/settings/CurrentUserTracker.java
+++ b/packages/SystemUI/src/com/android/systemui/settings/CurrentUserTracker.java
@@ -21,6 +21,7 @@ import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
+import android.os.UserHandle;
import com.android.internal.annotations.VisibleForTesting;
import com.android.systemui.broadcast.BroadcastDispatcher;
@@ -97,7 +98,7 @@ public abstract class CurrentUserTracker {
if (!mReceiverRegistered) {
mCurrentUserId = ActivityManager.getCurrentUser();
IntentFilter filter = new IntentFilter(Intent.ACTION_USER_SWITCHED);
- mBroadcastDispatcher.registerReceiver(this, filter);
+ mBroadcastDispatcher.registerReceiver(this, filter, null, UserHandle.ALL);
mReceiverRegistered = true;
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java b/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java
index bb34a878a0d8..325af2424b2f 100644
--- a/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java
+++ b/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java
@@ -23,6 +23,7 @@ import static android.view.PointerIcon.TYPE_HORIZONTAL_DOUBLE_ARROW;
import static android.view.PointerIcon.TYPE_VERTICAL_DOUBLE_ARROW;
import static android.view.WindowManager.DOCKED_LEFT;
import static android.view.WindowManager.DOCKED_RIGHT;
+import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
@@ -40,12 +41,14 @@ import android.util.AttributeSet;
import android.view.Choreographer;
import android.view.Display;
import android.view.DisplayInfo;
+import android.view.InsetsState;
import android.view.MotionEvent;
import android.view.PointerIcon;
import android.view.VelocityTracker;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
+import android.view.ViewRootImpl;
import android.view.ViewTreeObserver.InternalInsetsInfo;
import android.view.ViewTreeObserver.OnComputeInternalInsetsListener;
import android.view.WindowInsets;
@@ -292,7 +295,7 @@ public class DividerView extends FrameLayout implements OnTouchListener,
R.integer.long_press_dock_anim_duration);
mGrowRecents = getResources().getBoolean(R.bool.recents_grow_in_multiwindow);
mTouchSlop = ViewConfiguration.get(mContext).getScaledTouchSlop();
- mFlingAnimationUtils = new FlingAnimationUtils(getContext(), 0.3f);
+ mFlingAnimationUtils = new FlingAnimationUtils(getResources().getDisplayMetrics(), 0.3f);
updateDisplayInfo();
boolean landscape = getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE;
@@ -321,6 +324,16 @@ public class DividerView extends FrameLayout implements OnTouchListener,
@Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
+ if (isAttachedToWindow()
+ && ViewRootImpl.sNewInsetsMode == ViewRootImpl.NEW_INSETS_MODE_FULL) {
+ // Our window doesn't cover entire display, so we use the display frame to re-calculate
+ // the insets.
+ final InsetsState state = getWindowInsetsController().getState();
+ insets = state.calculateInsets(state.getDisplayFrame(), insets.isRound(),
+ insets.shouldAlwaysConsumeSystemBars(), insets.getDisplayCutout(),
+ null /* legacyContentInsets */, null /* legacyStableInsets */,
+ SOFT_INPUT_ADJUST_NOTHING, null /* typeSideMap */);
+ }
if (mStableInsets.left != insets.getStableInsetLeft()
|| mStableInsets.top != insets.getStableInsetTop()
|| mStableInsets.right != insets.getStableInsetRight()
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/FlingAnimationUtils.java b/packages/SystemUI/src/com/android/systemui/statusbar/FlingAnimationUtils.java
index d4272605924f..525b5b795a03 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/FlingAnimationUtils.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/FlingAnimationUtils.java
@@ -17,7 +17,7 @@
package com.android.systemui.statusbar;
import android.animation.Animator;
-import android.content.Context;
+import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ViewPropertyAnimator;
import android.view.animation.Interpolator;
@@ -25,7 +25,8 @@ import android.view.animation.PathInterpolator;
import com.android.systemui.Interpolators;
import com.android.systemui.statusbar.notification.NotificationUtils;
-import com.android.systemui.statusbar.phone.StatusBar;
+
+import javax.inject.Inject;
/**
* Utility class to calculate general fling animation when the finger is released.
@@ -56,8 +57,8 @@ public class FlingAnimationUtils {
private float mCachedStartGradient = -1;
private float mCachedVelocityFactor = -1;
- public FlingAnimationUtils(Context ctx, float maxLengthSeconds) {
- this(ctx, maxLengthSeconds, 0.0f);
+ public FlingAnimationUtils(DisplayMetrics displayMetrics, float maxLengthSeconds) {
+ this(displayMetrics, maxLengthSeconds, 0.0f);
}
/**
@@ -66,8 +67,9 @@ public class FlingAnimationUtils {
* the end of the animation. 0 means it's at the beginning and no
* acceleration will take place.
*/
- public FlingAnimationUtils(Context ctx, float maxLengthSeconds, float speedUpFactor) {
- this(ctx, maxLengthSeconds, speedUpFactor, -1.0f, 1.0f);
+ public FlingAnimationUtils(DisplayMetrics displayMetrics, float maxLengthSeconds,
+ float speedUpFactor) {
+ this(displayMetrics, maxLengthSeconds, speedUpFactor, -1.0f, 1.0f);
}
/**
@@ -79,8 +81,8 @@ public class FlingAnimationUtils {
* is provided, the value is automatically calculated.
* @param y2 the y value to take for the second point of the bezier spline
*/
- public FlingAnimationUtils(Context ctx, float maxLengthSeconds, float speedUpFactor, float x2,
- float y2) {
+ public FlingAnimationUtils(DisplayMetrics displayMetrics, float maxLengthSeconds,
+ float speedUpFactor, float x2, float y2) {
mMaxLengthSeconds = maxLengthSeconds;
mSpeedUpFactor = speedUpFactor;
if (x2 < 0) {
@@ -92,10 +94,8 @@ public class FlingAnimationUtils {
}
mY2 = y2;
- mMinVelocityPxPerSecond
- = MIN_VELOCITY_DP_PER_SECOND * ctx.getResources().getDisplayMetrics().density;
- mHighVelocityPxPerSecond
- = HIGH_VELOCITY_DP_PER_SECOND * ctx.getResources().getDisplayMetrics().density;
+ mMinVelocityPxPerSecond = MIN_VELOCITY_DP_PER_SECOND * displayMetrics.density;
+ mHighVelocityPxPerSecond = HIGH_VELOCITY_DP_PER_SECOND * displayMetrics.density;
}
/**
@@ -365,4 +365,41 @@ public class FlingAnimationUtils {
long duration;
}
+ public static class Builder {
+ private final DisplayMetrics mDisplayMetrics;
+ float mMaxLengthSeconds;
+ float mSpeedUpFactor = 0.0f;
+ float mX2 = -1.0f;
+ float mY2 = 1.0f;
+
+ @Inject
+ public Builder(DisplayMetrics displayMetrics) {
+ mDisplayMetrics = displayMetrics;
+ }
+
+ public Builder setMaxLengthSeconds(float maxLengthSeconds) {
+ mMaxLengthSeconds = maxLengthSeconds;
+ return this;
+ }
+
+ public Builder setSpeedUpFactor(float speedUpFactor) {
+ mSpeedUpFactor = speedUpFactor;
+ return this;
+ }
+
+ public Builder setX2(float x2) {
+ mX2 = x2;
+ return this;
+ }
+
+ public Builder setY2(float y2) {
+ mY2 = y2;
+ return this;
+ }
+
+ public FlingAnimationUtils build() {
+ return new FlingAnimationUtils(mDisplayMetrics, mMaxLengthSeconds, mSpeedUpFactor,
+ mX2, mY2);
+ }
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardAffordanceView.java b/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardAffordanceView.java
index 6adaa0ddbfd2..2c296353bd14 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardAffordanceView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardAffordanceView.java
@@ -138,7 +138,8 @@ public class KeyguardAffordanceView extends ImageView {
mMinBackgroundRadius = mContext.getResources().getDimensionPixelSize(
R.dimen.keyguard_affordance_min_background_radius);
mColorInterpolator = new ArgbEvaluator();
- mFlingAnimationUtils = new FlingAnimationUtils(mContext, 0.3f);
+ mFlingAnimationUtils = new FlingAnimationUtils(mContext.getResources().getDisplayMetrics(),
+ 0.3f);
a.recycle();
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java
index 9dcfb6a8a4c6..97dd3daae341 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java
@@ -19,9 +19,7 @@ package com.android.systemui.statusbar;
import static com.android.systemui.statusbar.RemoteInputController.processForRemoteInput;
import static com.android.systemui.statusbar.notification.NotificationEntryManager.UNDEFINED_DISMISS_REASON;
import static com.android.systemui.statusbar.phone.StatusBar.DEBUG;
-import static com.android.systemui.statusbar.phone.StatusBar.ENABLE_CHILD_NOTIFICATIONS;
-import android.annotation.Nullable;
import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.content.ComponentName;
@@ -33,11 +31,10 @@ import android.service.notification.StatusBarNotification;
import android.util.Log;
import com.android.systemui.dagger.qualifiers.MainHandler;
-import com.android.systemui.statusbar.notification.NotificationEntryManager;
-import com.android.systemui.statusbar.phone.NotificationGroupManager;
import com.android.systemui.statusbar.phone.NotificationListenerWithPlugins;
import java.util.ArrayList;
+import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
@@ -51,31 +48,33 @@ import javax.inject.Singleton;
public class NotificationListener extends NotificationListenerWithPlugins {
private static final String TAG = "NotificationListener";
- // Dependencies:
- private final NotificationEntryManager mEntryManager;
- private final NotificationGroupManager mGroupManager;
-
private final Context mContext;
+ private final NotificationManager mNotificationManager;
private final Handler mMainHandler;
+ private final List<NotifServiceListener> mNotificationListeners = new ArrayList<>();
private final ArrayList<NotificationSettingsListener> mSettingsListeners = new ArrayList<>();
- @Nullable private NotifServiceListener mDownstreamListener;
@Inject
- public NotificationListener(Context context, @MainHandler Handler mainHandler,
- NotificationEntryManager notificationEntryManager,
- NotificationGroupManager notificationGroupManager) {
+ public NotificationListener(
+ Context context,
+ NotificationManager notificationManager,
+ @MainHandler Handler mainHandler) {
mContext = context;
+ mNotificationManager = notificationManager;
mMainHandler = mainHandler;
- mEntryManager = notificationEntryManager;
- mGroupManager = notificationGroupManager;
}
- public void addNotificationSettingsListener(NotificationSettingsListener listener) {
- mSettingsListeners.add(listener);
+ /** Registers a listener that's notified when notifications are added/removed/etc. */
+ public void addNotificationListener(NotifServiceListener listener) {
+ if (mNotificationListeners.contains(listener)) {
+ throw new IllegalArgumentException("Listener is already added");
+ }
+ mNotificationListeners.add(listener);
}
- public void setDownstreamListener(NotifServiceListener downstreamListener) {
- mDownstreamListener = downstreamListener;
+ /** Registers a listener that's notified when any notification-related settings change. */
+ public void addNotificationSettingsListener(NotificationSettingsListener listener) {
+ mSettingsListeners.add(listener);
}
@Override
@@ -89,15 +88,25 @@ public class NotificationListener extends NotificationListenerWithPlugins {
}
final RankingMap currentRanking = getCurrentRanking();
mMainHandler.post(() -> {
+ // There's currently a race condition between the calls to getActiveNotifications() and
+ // getCurrentRanking(). It's possible for the ranking that we store here to not contain
+ // entries for every notification in getActiveNotifications(). To prevent downstream
+ // crashes, we temporarily fill in these missing rankings with stubs.
+ // See b/146011844 for long-term fix
+ final List<Ranking> newRankings = new ArrayList<>();
for (StatusBarNotification sbn : notifications) {
- if (mDownstreamListener != null) {
- mDownstreamListener.onNotificationPosted(sbn, currentRanking);
+ newRankings.add(getRankingOrTemporaryStandIn(currentRanking, sbn.getKey()));
+ }
+ final RankingMap completeMap = new RankingMap(newRankings.toArray(new Ranking[0]));
+
+ for (StatusBarNotification sbn : notifications) {
+ for (NotifServiceListener listener : mNotificationListeners) {
+ listener.onNotificationPosted(sbn, completeMap);
}
- mEntryManager.addNotification(sbn, currentRanking);
}
});
- NotificationManager noMan = mContext.getSystemService(NotificationManager.class);
- onSilentStatusBarIconsVisibilityChanged(noMan.shouldHideSilentStatusBarIcons());
+ onSilentStatusBarIconsVisibilityChanged(
+ mNotificationManager.shouldHideSilentStatusBarIcons());
}
@Override
@@ -108,34 +117,8 @@ public class NotificationListener extends NotificationListenerWithPlugins {
mMainHandler.post(() -> {
processForRemoteInput(sbn.getNotification(), mContext);
- if (mDownstreamListener != null) {
- mDownstreamListener.onNotificationPosted(sbn, rankingMap);
- }
-
- String key = sbn.getKey();
- boolean isUpdate = mEntryManager.getActiveNotificationUnfiltered(key) != null;
- // In case we don't allow child notifications, we ignore children of
- // notifications that have a summary, since` we're not going to show them
- // anyway. This is true also when the summary is canceled,
- // because children are automatically canceled by NoMan in that case.
- if (!ENABLE_CHILD_NOTIFICATIONS
- && mGroupManager.isChildInGroupWithSummary(sbn)) {
- if (DEBUG) {
- Log.d(TAG, "Ignoring group child due to existing summary: " + sbn);
- }
-
- // Remove existing notification to avoid stale data.
- if (isUpdate) {
- mEntryManager.removeNotification(key, rankingMap, UNDEFINED_DISMISS_REASON);
- } else {
- mEntryManager.updateRanking(rankingMap, "onNotificationPosted");
- }
- return;
- }
- if (isUpdate) {
- mEntryManager.updateNotification(sbn, rankingMap);
- } else {
- mEntryManager.addNotification(sbn, rankingMap);
+ for (NotifServiceListener listener : mNotificationListeners) {
+ listener.onNotificationPosted(sbn, rankingMap);
}
});
}
@@ -146,12 +129,10 @@ public class NotificationListener extends NotificationListenerWithPlugins {
int reason) {
if (DEBUG) Log.d(TAG, "onNotificationRemoved: " + sbn + " reason: " + reason);
if (sbn != null && !onPluginNotificationRemoved(sbn, rankingMap)) {
- final String key = sbn.getKey();
mMainHandler.post(() -> {
- if (mDownstreamListener != null) {
- mDownstreamListener.onNotificationRemoved(sbn, rankingMap, reason);
+ for (NotifServiceListener listener : mNotificationListeners) {
+ listener.onNotificationRemoved(sbn, rankingMap, reason);
}
- mEntryManager.removeNotification(key, rankingMap, reason);
});
}
}
@@ -167,10 +148,9 @@ public class NotificationListener extends NotificationListenerWithPlugins {
if (rankingMap != null) {
RankingMap r = onPluginRankingUpdate(rankingMap);
mMainHandler.post(() -> {
- if (mDownstreamListener != null) {
- mDownstreamListener.onNotificationRankingUpdate(rankingMap);
+ for (NotifServiceListener listener : mNotificationListeners) {
+ listener.onNotificationRankingUpdate(r);
}
- mEntryManager.updateNotificationRanking(r);
});
}
}
@@ -192,6 +172,35 @@ public class NotificationListener extends NotificationListenerWithPlugins {
}
}
+ private static Ranking getRankingOrTemporaryStandIn(RankingMap rankingMap, String key) {
+ Ranking ranking = new Ranking();
+ if (!rankingMap.getRanking(key, ranking)) {
+ ranking.populate(
+ key,
+ 0,
+ false,
+ 0,
+ 0,
+ 0,
+ null,
+ null,
+ null,
+ new ArrayList<>(),
+ new ArrayList<>(),
+ false,
+ 0,
+ false,
+ 0,
+ false,
+ new ArrayList<>(),
+ new ArrayList<>(),
+ false,
+ false
+ );
+ }
+ return ranking;
+ }
+
public interface NotificationSettingsListener {
default void onStatusBarIconsBehaviorChanged(boolean hideSilentStatusIcons) { }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationUpdateHandler.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationUpdateHandler.java
deleted file mode 100644
index 1ac81982505e..000000000000
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationUpdateHandler.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2017 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 com.android.systemui.statusbar;
-
-import android.service.notification.NotificationListenerService;
-import android.service.notification.StatusBarNotification;
-
-/**
- * Interface for accepting notification updates from {@link NotificationListener}.
- */
-public interface NotificationUpdateHandler {
- /**
- * Add a new notification and update the current notification ranking map.
- *
- * @param notification Notification to add
- * @param ranking RankingMap to update with
- */
- void addNotification(StatusBarNotification notification,
- NotificationListenerService.RankingMap ranking);
-
- /**
- * Remove a notification and update the current notification ranking map.
- *
- * @param key Key identifying the notification to remove
- * @param ranking RankingMap to update with
- * @param reason why the notification is being removed, e.g.
- * {@link NotificationListenerService#REASON_CANCEL}.
- */
- void removeNotification(String key, NotificationListenerService.RankingMap ranking, int reason);
-
- /**
- * Update a given notification and the current notification ranking map.
- *
- * @param notification Updated notification
- * @param ranking RankingMap to update with
- */
- void updateNotification(StatusBarNotification notification,
- NotificationListenerService.RankingMap ranking);
-
- /**
- * Update with a new notification ranking map.
- *
- * @param ranking RankingMap to update with
- */
- void updateNotificationRanking(NotificationListenerService.RankingMap ranking);
-}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationViewHierarchyManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationViewHierarchyManager.java
index 4204f684a632..1648196ec0ea 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationViewHierarchyManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationViewHierarchyManager.java
@@ -37,7 +37,6 @@ import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow
import com.android.systemui.statusbar.notification.stack.NotificationListContainer;
import com.android.systemui.statusbar.phone.KeyguardBypassController;
import com.android.systemui.statusbar.phone.NotificationGroupManager;
-import com.android.systemui.statusbar.phone.ShadeController;
import com.android.systemui.util.Assert;
import com.android.systemui.util.Utils;
@@ -49,8 +48,6 @@ import java.util.Stack;
import javax.inject.Inject;
import javax.inject.Singleton;
-import dagger.Lazy;
-
/**
* NotificationViewHierarchyManager manages updating the view hierarchy of notification views based
* on their group structure. For example, if a notification becomes bundled with another,
@@ -75,9 +72,6 @@ public class NotificationViewHierarchyManager implements DynamicPrivacyControlle
private final SysuiStatusBarStateController mStatusBarStateController;
private final NotificationEntryManager mEntryManager;
- // Lazy
- private final Lazy<ShadeController> mShadeController;
-
/**
* {@code true} if notifications not part of a group should by default be rendered in their
* expanded state. If {@code false}, then only the first notification will be expanded if
@@ -105,7 +99,6 @@ public class NotificationViewHierarchyManager implements DynamicPrivacyControlle
VisualStabilityManager visualStabilityManager,
StatusBarStateController statusBarStateController,
NotificationEntryManager notificationEntryManager,
- Lazy<ShadeController> shadeController,
KeyguardBypassController bypassController,
BubbleController bubbleController,
DynamicPrivacyController privacyController) {
@@ -117,7 +110,6 @@ public class NotificationViewHierarchyManager implements DynamicPrivacyControlle
mVisualStabilityManager = visualStabilityManager;
mStatusBarStateController = (SysuiStatusBarStateController) statusBarStateController;
mEntryManager = notificationEntryManager;
- mShadeController = shadeController;
Resources res = context.getResources();
mAlwaysExpandNonGroupedNotification =
res.getBoolean(R.bool.config_alwaysExpandNonGroupedNotifications);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationClicker.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationClicker.java
index 8ecf2b8421f0..c8b34f1f5b27 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationClicker.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationClicker.java
@@ -26,6 +26,8 @@ import com.android.systemui.bubbles.BubbleController;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.systemui.statusbar.phone.StatusBar;
+import java.util.Optional;
+
/**
* Click handler for generic clicks on notifications. Clicks on specific areas (expansion caret,
* app ops icon, etc) are handled elsewhere.
@@ -33,11 +35,11 @@ import com.android.systemui.statusbar.phone.StatusBar;
public final class NotificationClicker implements View.OnClickListener {
private static final String TAG = "NotificationClicker";
- private final StatusBar mStatusBar;
+ private final Optional<StatusBar> mStatusBar;
private final BubbleController mBubbleController;
private final NotificationActivityStarter mNotificationActivityStarter;
- public NotificationClicker(StatusBar statusBar,
+ public NotificationClicker(Optional<StatusBar> statusBar,
BubbleController bubbleController,
NotificationActivityStarter notificationActivityStarter) {
mStatusBar = statusBar;
@@ -52,7 +54,8 @@ public final class NotificationClicker implements View.OnClickListener {
return;
}
- mStatusBar.wakeUpIfDozing(SystemClock.uptimeMillis(), v, "NOTIFICATION_CLICK");
+ mStatusBar.ifPresent(statusBar -> statusBar.wakeUpIfDozing(
+ SystemClock.uptimeMillis(), v, "NOTIFICATION_CLICK"));
final ExpandableNotificationRow row = (ExpandableNotificationRow) v;
final StatusBarNotification sbn = row.getEntry().getSbn();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
index 7a58097f3ec1..43b9fbc909dc 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
@@ -33,11 +33,12 @@ import com.android.internal.statusbar.NotificationVisibility;
import com.android.systemui.Dependency;
import com.android.systemui.Dumpable;
import com.android.systemui.statusbar.NotificationLifetimeExtender;
+import com.android.systemui.statusbar.NotificationListener;
+import com.android.systemui.statusbar.NotificationListener.NotifServiceListener;
import com.android.systemui.statusbar.NotificationPresenter;
import com.android.systemui.statusbar.NotificationRemoteInputManager;
import com.android.systemui.statusbar.NotificationRemoveInterceptor;
import com.android.systemui.statusbar.NotificationUiAdjustment;
-import com.android.systemui.statusbar.NotificationUpdateHandler;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.NotificationRankingManager;
import com.android.systemui.statusbar.notification.collection.NotificationRowBinder;
@@ -94,7 +95,6 @@ import javax.inject.Singleton;
public class NotificationEntryManager implements
Dumpable,
NotificationContentInflater.InflationCallback,
- NotificationUpdateHandler,
VisualStabilityManager.Callback {
private static final String TAG = "NotificationEntryMgr";
private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
@@ -176,6 +176,11 @@ public class NotificationEntryManager implements
mKeyguardEnvironment = keyguardEnvironment;
}
+ /** Once called, the NEM will start processing notification events from system server. */
+ public void attach(NotificationListener notificationListener) {
+ notificationListener.addNotificationListener(mNotifListener);
+ }
+
/** Adds a {@link NotificationEntryListener}. */
public void addNotificationEntryListener(NotificationEntryListener listener) {
mNotificationEntryListeners.add(listener);
@@ -267,14 +272,13 @@ public class NotificationEntryManager implements
NotificationEntry entry = mPendingNotifications.get(key);
entry.abortTask();
mPendingNotifications.remove(key);
- mNotifLog.log(NotifEvent.INFLATION_ABORTED, entry.getSbn(), null,
- "PendingNotification aborted. " + reason);
+ mNotifLog.log(NotifEvent.INFLATION_ABORTED, entry, "PendingNotification aborted"
+ + " reason=" + reason);
}
NotificationEntry addedEntry = getActiveNotificationUnfiltered(key);
if (addedEntry != null) {
addedEntry.abortTask();
- mNotifLog.log(NotifEvent.INFLATION_ABORTED, addedEntry.getSbn(),
- null, reason);
+ mNotifLog.log(NotifEvent.INFLATION_ABORTED, addedEntry.getKey() + " " + reason);
}
}
@@ -321,6 +325,36 @@ public class NotificationEntryManager implements
}
}
+ private final NotifServiceListener mNotifListener = new NotifServiceListener() {
+ @Override
+ public void onNotificationPosted(StatusBarNotification sbn, RankingMap rankingMap) {
+ final boolean isUpdate = mActiveNotifications.containsKey(sbn.getKey());
+ if (isUpdate) {
+ updateNotification(sbn, rankingMap);
+ } else {
+ addNotification(sbn, rankingMap);
+ }
+ }
+
+ @Override
+ public void onNotificationRemoved(StatusBarNotification sbn, RankingMap rankingMap) {
+ removeNotification(sbn.getKey(), rankingMap, UNDEFINED_DISMISS_REASON);
+ }
+
+ @Override
+ public void onNotificationRemoved(
+ StatusBarNotification sbn,
+ RankingMap rankingMap,
+ int reason) {
+ removeNotification(sbn.getKey(), rankingMap, reason);
+ }
+
+ @Override
+ public void onNotificationRankingUpdate(RankingMap rankingMap) {
+ updateNotificationRanking(rankingMap);
+ }
+ };
+
/**
* Equivalent to the old NotificationData#add
* @param entry - an entry which is prepared for display
@@ -347,7 +381,6 @@ public class NotificationEntryManager implements
}
- @Override
public void removeNotification(String key, RankingMap ranking,
int reason) {
removeNotificationInternal(key, ranking, obtainVisibility(key), false /* forceRemove */,
@@ -501,13 +534,12 @@ public class NotificationEntryManager implements
abortExistingInflation(key, "addNotification");
mPendingNotifications.put(key, entry);
- mNotifLog.log(NotifEvent.NOTIF_ADDED, entry.getSbn());
+ mNotifLog.log(NotifEvent.NOTIF_ADDED, entry);
for (NotificationEntryListener listener : mNotificationEntryListeners) {
listener.onPendingEntryAdded(entry);
}
}
- @Override
public void addNotification(StatusBarNotification notification, RankingMap ranking) {
try {
addNotificationInternal(notification, ranking);
@@ -536,7 +568,7 @@ public class NotificationEntryManager implements
entry.setSbn(notification);
mGroupManager.onEntryUpdated(entry, oldSbn);
- mNotifLog.log(NotifEvent.NOTIF_UPDATED, entry.getSbn(), entry.getRanking());
+ mNotifLog.log(NotifEvent.NOTIF_UPDATED, entry);
for (NotificationEntryListener listener : mNotificationEntryListeners) {
listener.onPreEntryUpdated(entry);
}
@@ -557,7 +589,6 @@ public class NotificationEntryManager implements
}
}
- @Override
public void updateNotification(StatusBarNotification notification, RankingMap ranking) {
try {
updateNotificationInternal(notification, ranking);
@@ -577,7 +608,6 @@ public class NotificationEntryManager implements
}
}
- @Override
public void updateNotificationRanking(RankingMap rankingMap) {
List<NotificationEntry> entries = new ArrayList<>();
entries.addAll(getVisibleNotifications());
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationFilter.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationFilter.java
index 6c61923332ea..3afd6235b287 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationFilter.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationFilter.java
@@ -32,7 +32,6 @@ import com.android.systemui.statusbar.NotificationLockscreenUserManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.phone.NotificationGroupManager;
import com.android.systemui.statusbar.phone.ShadeController;
-import com.android.systemui.statusbar.phone.StatusBar;
import javax.inject.Inject;
import javax.inject.Singleton;
@@ -120,11 +119,6 @@ public class NotificationFilter {
return true;
}
- if (!StatusBar.ENABLE_CHILD_NOTIFICATIONS
- && mGroupManager.isChildInGroupWithSummary(sbn)) {
- return true;
- }
-
if (getFsc().isDisclosureNotification(sbn)
&& !getFsc().isDisclosureNeededForUser(sbn.getUserId())) {
// this is a foreground-service disclosure for a user that does not need to show one
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/GroupEntry.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/GroupEntry.java
index 9ae3882e8e82..ec1efa58868e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/GroupEntry.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/GroupEntry.java
@@ -24,6 +24,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
+import java.util.Objects;
/**
* Represents a set of grouped notifications. The final notification list is usually a mix of
@@ -57,15 +58,22 @@ public class GroupEntry extends ListEntry {
@VisibleForTesting
public void setSummary(@Nullable NotificationEntry summary) {
- mSummary = summary;
+ if (!Objects.equals(mSummary, summary)) {
+ mSummary = summary;
+ onGroupingUpdated();
+ }
}
void clearChildren() {
- mChildren.clear();
+ if (mChildren.size() != 0) {
+ mChildren.clear();
+ onGroupingUpdated();
+ }
}
void addChild(NotificationEntry child) {
mChildren.add(child);
+ onGroupingUpdated();
}
void sortChildren(Comparator<? super NotificationEntry> c) {
@@ -77,4 +85,5 @@ public class GroupEntry extends ListEntry {
}
public static final GroupEntry ROOT_ENTRY = new GroupEntry("<root>");
+
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ListEntry.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ListEntry.java
index 6ce7fd96e6a0..601b3e053e8e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ListEntry.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ListEntry.java
@@ -18,7 +18,14 @@ package com.android.systemui.statusbar.notification.collection;
import android.annotation.Nullable;
-import com.android.internal.annotations.VisibleForTesting;
+import com.android.systemui.Dependency;
+import com.android.systemui.statusbar.notification.collection.provider.DerivedMember;
+import com.android.systemui.statusbar.notification.collection.provider.IsHighPriorityProvider;
+import com.android.systemui.statusbar.phone.NotificationGroupManager;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
/**
* Abstract superclass for top-level entries, i.e. things that can appear in the final notification
@@ -26,14 +33,23 @@ import com.android.internal.annotations.VisibleForTesting;
*/
public abstract class ListEntry {
private final String mKey;
+ private final IsHighPriorityProvider mIsHighPriorityProvider = new IsHighPriorityProvider();
+ private final List<DerivedMember> mDerivedMemberList = Arrays.asList(mIsHighPriorityProvider);
@Nullable private GroupEntry mParent;
@Nullable private GroupEntry mPreviousParent;
private int mSection;
int mFirstAddedIteration = -1;
+ // TODO: (b/145659174) remove groupManager when moving to NewNotifPipeline. Logic
+ // replaced in GroupEntry and NotifListBuilderImpl
+ private final NotificationGroupManager mGroupManager;
+
ListEntry(String key) {
mKey = key;
+
+ // TODO: (b/145659174) remove
+ mGroupManager = Dependency.get(NotificationGroupManager.class);
}
public String getKey() {
@@ -51,9 +67,12 @@ public abstract class ListEntry {
return mParent;
}
- @VisibleForTesting
- public void setParent(@Nullable GroupEntry parent) {
- mParent = parent;
+ void setParent(@Nullable GroupEntry parent) {
+ if (!Objects.equals(mParent, parent)) {
+ invalidateParent();
+ mParent = parent;
+ onGroupingUpdated();
+ }
}
@Nullable public GroupEntry getPreviousParent() {
@@ -72,4 +91,58 @@ public abstract class ListEntry {
void setSection(int section) {
mSection = section;
}
+
+ /**
+ * Resets the cached values of DerivedMembers.
+ */
+ void invalidateDerivedMembers() {
+ for (int i = 0; i < mDerivedMemberList.size(); i++) {
+ mDerivedMemberList.get(i).invalidate();
+ }
+ }
+
+ /**
+ * Whether this notification is shown to the user as a high priority notification: visible on
+ * the lock screen/status bar and in the top section in the shade.
+ */
+ public boolean isHighPriority() {
+ return mIsHighPriorityProvider.get(this);
+ }
+
+ private void invalidateParent() {
+ // invalidate our parent (GroupEntry) since DerivedMembers may be dependent on children
+ if (getParent() != null) {
+ getParent().invalidateDerivedMembers();
+ }
+
+ // TODO: (b/145659174) remove
+ final NotificationEntry notifEntry = getRepresentativeEntry();
+ if (notifEntry != null && mGroupManager.isGroupChild(notifEntry.getSbn())) {
+ NotificationEntry summary = mGroupManager.getLogicalGroupSummary(notifEntry.getSbn());
+ if (summary != null) {
+ summary.invalidateDerivedMembers();
+ }
+ }
+ }
+
+ void onGroupingUpdated() {
+ for (int i = 0; i < mDerivedMemberList.size(); i++) {
+ mDerivedMemberList.get(i).onGroupingUpdated();
+ }
+ invalidateParent();
+ }
+
+ void onSbnUpdated() {
+ for (int i = 0; i < mDerivedMemberList.size(); i++) {
+ mDerivedMemberList.get(i).onSbnUpdated();
+ }
+ invalidateParent();
+ }
+
+ void onRankingUpdated() {
+ for (int i = 0; i < mDerivedMemberList.size(); i++) {
+ mDerivedMemberList.get(i).onRankingUpdated();
+ }
+ invalidateParent();
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifCollection.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifCollection.java
index 6f085c0ce7c0..7f85c88865f6 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifCollection.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifCollection.java
@@ -116,7 +116,7 @@ public class NotifCollection {
}
mAttached = true;
- listenerService.setDownstreamListener(mNotifServiceListener);
+ listenerService.addNotificationListener(mNotifServiceListener);
}
/**
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifListBuilderImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifListBuilderImpl.java
index 21a4b4f895e5..f0a003f2ff5e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifListBuilderImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifListBuilderImpl.java
@@ -20,16 +20,18 @@ import static com.android.systemui.statusbar.notification.collection.GroupEntry.
import static com.android.systemui.statusbar.notification.collection.ListDumper.dumpList;
import static com.android.systemui.statusbar.notification.collection.listbuilder.PipelineState.STATE_BUILD_PENDING;
import static com.android.systemui.statusbar.notification.collection.listbuilder.PipelineState.STATE_BUILD_STARTED;
-import static com.android.systemui.statusbar.notification.collection.listbuilder.PipelineState.STATE_FILTERING;
import static com.android.systemui.statusbar.notification.collection.listbuilder.PipelineState.STATE_FINALIZING;
+import static com.android.systemui.statusbar.notification.collection.listbuilder.PipelineState.STATE_GROUPING;
import static com.android.systemui.statusbar.notification.collection.listbuilder.PipelineState.STATE_IDLE;
+import static com.android.systemui.statusbar.notification.collection.listbuilder.PipelineState.STATE_PRE_GROUP_FILTERING;
+import static com.android.systemui.statusbar.notification.collection.listbuilder.PipelineState.STATE_PRE_RENDER_FILTERING;
+import static com.android.systemui.statusbar.notification.collection.listbuilder.PipelineState.STATE_RESETTING;
import static com.android.systemui.statusbar.notification.collection.listbuilder.PipelineState.STATE_SORTING;
import static com.android.systemui.statusbar.notification.collection.listbuilder.PipelineState.STATE_TRANSFORMING;
import android.annotation.MainThread;
import android.annotation.Nullable;
import android.util.ArrayMap;
-import android.util.Log;
import com.android.systemui.statusbar.notification.collection.listbuilder.NotifListBuilder;
import com.android.systemui.statusbar.notification.collection.listbuilder.OnBeforeRenderListListener;
@@ -40,6 +42,8 @@ import com.android.systemui.statusbar.notification.collection.listbuilder.plugga
import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.NotifFilter;
import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.NotifPromoter;
import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.SectionsProvider;
+import com.android.systemui.statusbar.notification.logging.NotifEvent;
+import com.android.systemui.statusbar.notification.logging.NotifLog;
import com.android.systemui.util.Assert;
import com.android.systemui.util.time.SystemClock;
@@ -59,19 +63,20 @@ import javax.inject.Singleton;
@MainThread
@Singleton
public class NotifListBuilderImpl implements NotifListBuilder {
-
private final SystemClock mSystemClock;
+ private final NotifLog mNotifLog;
- private final List<ListEntry> mNotifList = new ArrayList<>();
+ private List<ListEntry> mNotifList = new ArrayList<>();
+ private List<ListEntry> mNewNotifList = new ArrayList<>();
private final PipelineState mPipelineState = new PipelineState();
private final Map<String, GroupEntry> mGroups = new ArrayMap<>();
private Collection<NotificationEntry> mAllEntries = Collections.emptyList();
- private final List<ListEntry> mNewEntries = new ArrayList<>();
private int mIterationCount = 0;
- private final List<NotifFilter> mNotifFilters = new ArrayList<>();
+ private final List<NotifFilter> mNotifPreGroupFilters = new ArrayList<>();
private final List<NotifPromoter> mNotifPromoters = new ArrayList<>();
+ private final List<NotifFilter> mNotifPreRenderFilters = new ArrayList<>();
private final List<NotifComparator> mNotifComparators = new ArrayList<>();
private SectionsProvider mSectionsProvider = new DefaultSectionsProvider();
@@ -86,9 +91,10 @@ public class NotifListBuilderImpl implements NotifListBuilder {
private final List<ListEntry> mReadOnlyNotifList = Collections.unmodifiableList(mNotifList);
@Inject
- public NotifListBuilderImpl(SystemClock systemClock) {
+ public NotifListBuilderImpl(SystemClock systemClock, NotifLog notifLog) {
Assert.isMainThread();
mSystemClock = systemClock;
+ mNotifLog = notifLog;
}
/**
@@ -136,12 +142,21 @@ public class NotifListBuilderImpl implements NotifListBuilder {
}
@Override
- public void addFilter(NotifFilter filter) {
+ public void addPreGroupFilter(NotifFilter filter) {
+ Assert.isMainThread();
+ mPipelineState.requireState(STATE_IDLE);
+
+ mNotifPreGroupFilters.add(filter);
+ filter.setInvalidationListener(this::onPreGroupFilterInvalidated);
+ }
+
+ @Override
+ public void addPreRenderFilter(NotifFilter filter) {
Assert.isMainThread();
mPipelineState.requireState(STATE_IDLE);
- mNotifFilters.add(filter);
- filter.setInvalidationListener(this::onFilterInvalidated);
+ mNotifPreRenderFilters.add(filter);
+ filter.setInvalidationListener(this::onPreRenderFilterInvalidated);
}
@Override
@@ -193,28 +208,28 @@ public class NotifListBuilderImpl implements NotifListBuilder {
Assert.isMainThread();
mPipelineState.requireIsBefore(STATE_BUILD_STARTED);
- Log.i(TAG, "Build request received from NotifCollection");
+ mNotifLog.log(NotifEvent.ON_BUILD_LIST, "Request received from "
+ + "NotifCollection");
mAllEntries = entries;
buildList();
}
};
- private void onFilterInvalidated(NotifFilter filter) {
+ private void onPreGroupFilterInvalidated(NotifFilter filter) {
Assert.isMainThread();
- // TODO: Convert these log statements (here and elsewhere) into timeline logging
- Log.i(TAG, String.format(
+ mNotifLog.log(NotifEvent.PRE_GROUP_FILTER_INVALIDATED, String.format(
"Filter \"%s\" invalidated; pipeline state is %d",
filter.getName(),
mPipelineState.getState()));
- rebuildListIfBefore(STATE_FILTERING);
+ rebuildListIfBefore(STATE_PRE_GROUP_FILTERING);
}
private void onPromoterInvalidated(NotifPromoter filter) {
Assert.isMainThread();
- Log.i(TAG, String.format(
+ mNotifLog.log(NotifEvent.PROMOTER_INVALIDATED, String.format(
"NotifPromoter \"%s\" invalidated; pipeline state is %d",
filter.getName(),
mPipelineState.getState()));
@@ -225,7 +240,7 @@ public class NotifListBuilderImpl implements NotifListBuilder {
private void onSectionsProviderInvalidated(SectionsProvider provider) {
Assert.isMainThread();
- Log.i(TAG, String.format(
+ mNotifLog.log(NotifEvent.SECTIONS_PROVIDER_INVALIDATED, String.format(
"Sections provider \"%s\" invalidated; pipeline state is %d",
provider.getName(),
mPipelineState.getState()));
@@ -233,10 +248,21 @@ public class NotifListBuilderImpl implements NotifListBuilder {
rebuildListIfBefore(STATE_SORTING);
}
+ private void onPreRenderFilterInvalidated(NotifFilter filter) {
+ Assert.isMainThread();
+
+ mNotifLog.log(NotifEvent.PRE_RENDER_FILTER_INVALIDATED, String.format(
+ "Filter \"%s\" invalidated; pipeline state is %d",
+ filter.getName(),
+ mPipelineState.getState()));
+
+ rebuildListIfBefore(STATE_PRE_RENDER_FILTERING);
+ }
+
private void onNotifComparatorInvalidated(NotifComparator comparator) {
Assert.isMainThread();
- Log.i(TAG, String.format(
+ mNotifLog.log(NotifEvent.COMPARATOR_INVALIDATED, String.format(
"Comparator \"%s\" invalidated; pipeline state is %d",
comparator.getName(),
mPipelineState.getState()));
@@ -245,6 +271,17 @@ public class NotifListBuilderImpl implements NotifListBuilder {
}
/**
+ * Points mNotifList to the list stored in mNewNotifList.
+ * Reuses the (emptied) mNotifList as mNewNotifList.
+ */
+ private void applyNewNotifList() {
+ mNotifList.clear();
+ List<ListEntry> emptyList = mNotifList;
+ mNotifList = mNewNotifList;
+ mNewNotifList = emptyList;
+ }
+
+ /**
* The core algorithm of the pipeline. See the top comment in {@link NotifListBuilder} for
* details on our contracts with other code.
*
@@ -254,60 +291,67 @@ public class NotifListBuilderImpl implements NotifListBuilder {
* if we detect that behavior, we should crash instantly.
*/
private void buildList() {
- Log.i(TAG, "Starting notif list build #" + mIterationCount + "...");
+ mNotifLog.log(NotifEvent.START_BUILD_LIST, "Run #" + mIterationCount + "...");
mPipelineState.requireIsBefore(STATE_BUILD_STARTED);
mPipelineState.setState(STATE_BUILD_STARTED);
- // Step 1: Filtering and initial grouping
- // Filter out any notifs that shouldn't be shown right now and cluster any that are part of
- // a group
- mPipelineState.incrementTo(STATE_FILTERING);
- mNotifList.clear();
- mNewEntries.clear();
- filterAndGroup(mAllEntries, mNotifList, mNewEntries);
- pruneIncompleteGroups(mNotifList, mNewEntries);
+ // Step 1: Reset notification states
+ mPipelineState.incrementTo(STATE_RESETTING);
+ resetNotifs();
+
+ // Step 2: Filter out any notifications that shouldn't be shown right now
+ mPipelineState.incrementTo(STATE_PRE_GROUP_FILTERING);
+ filterNotifs(mAllEntries, mNotifList, mNotifPreGroupFilters);
- // Step 2: Group transforming
+ // Step 3: Group notifications with the same group key and set summaries
+ mPipelineState.incrementTo(STATE_GROUPING);
+ groupNotifs(mNotifList, mNewNotifList);
+ applyNewNotifList();
+ pruneIncompleteGroups(mNotifList);
+
+ // Step 4: Group transforming
// Move some notifs out of their groups and up to top-level (mostly used for heads-upping)
- dispatchOnBeforeTransformGroups(mReadOnlyNotifList, mNewEntries);
+ dispatchOnBeforeTransformGroups(mReadOnlyNotifList);
mPipelineState.incrementTo(STATE_TRANSFORMING);
promoteNotifs(mNotifList);
- pruneIncompleteGroups(mNotifList, mNewEntries);
+ pruneIncompleteGroups(mNotifList);
- // Step 3: Sort
+ // Step 5: Sort
// Assign each top-level entry a section, then sort the list by section and then within
// section by our list of custom comparators
dispatchOnBeforeSort(mReadOnlyNotifList);
mPipelineState.incrementTo(STATE_SORTING);
sortList();
- // Step 4: Lock in our group structure and log anything that's changed since the last run
+ // Step 6: Filter out entries after pre-group filtering, grouping, promoting and sorting
+ // Now filters can see grouping information to determine whether to filter or not
+ mPipelineState.incrementTo(STATE_PRE_RENDER_FILTERING);
+ filterNotifs(mNotifList, mNewNotifList, mNotifPreRenderFilters);
+ applyNewNotifList();
+ pruneIncompleteGroups(mNotifList);
+
+ // Step 7: Lock in our group structure and log anything that's changed since the last run
mPipelineState.incrementTo(STATE_FINALIZING);
logParentingChanges();
freeEmptyGroups();
- // Step 5: Dispatch the new list, first to any listeners and then to the view layer
- Log.i(TAG, "List finalized, is:\n" + dumpList(mNotifList));
- Log.i(TAG, "Dispatching final list to listeners...");
+ // Step 6: Dispatch the new list, first to any listeners and then to the view layer
+ mNotifLog.log(NotifEvent.DISPATCH_FINAL_LIST, "List finalized, is:\n"
+ + dumpList(mNotifList));
dispatchOnBeforeRenderList(mReadOnlyNotifList);
if (mOnRenderListListener != null) {
mOnRenderListListener.onRenderList(mReadOnlyNotifList);
}
- // Step 6: We're done!
- Log.i(TAG, "Notif list build #" + mIterationCount + " completed");
+ // Step 7: We're done!
+ mNotifLog.log(NotifEvent.LIST_BUILD_COMPLETE,
+ "Notif list build #" + mIterationCount + " completed");
mPipelineState.setState(STATE_IDLE);
mIterationCount++;
}
- private void filterAndGroup(
- Collection<NotificationEntry> entries,
- List<ListEntry> out,
- List<ListEntry> newlyVisibleEntries) {
-
- long now = mSystemClock.uptimeMillis();
-
+ private void resetNotifs() {
for (GroupEntry group : mGroups.values()) {
group.setPreviousParent(group.getParent());
group.setParent(null);
@@ -315,22 +359,57 @@ public class NotifListBuilderImpl implements NotifListBuilder {
group.setSummary(null);
}
- for (NotificationEntry entry : entries) {
+ for (NotificationEntry entry : mAllEntries) {
entry.setPreviousParent(entry.getParent());
entry.setParent(null);
- // See if we should filter out this notification
- boolean shouldFilterOut = applyFilters(entry, now);
- if (shouldFilterOut) {
- continue;
- }
-
if (entry.mFirstAddedIteration == -1) {
entry.mFirstAddedIteration = mIterationCount;
- newlyVisibleEntries.add(entry);
}
+ }
+
+ mNotifList.clear();
+ }
+
+ private void filterNotifs(Collection<? extends ListEntry> entries,
+ List<ListEntry> out, List<NotifFilter> filters) {
+ final long now = mSystemClock.uptimeMillis();
+ for (ListEntry entry : entries) {
+ if (entry instanceof GroupEntry) {
+ final GroupEntry groupEntry = (GroupEntry) entry;
+
+ // apply filter on its summary
+ final NotificationEntry summary = groupEntry.getRepresentativeEntry();
+ if (applyFilters(summary, now, filters)) {
+ groupEntry.setSummary(null);
+ annulAddition(summary);
+ }
+
+ // apply filter on its children
+ final List<NotificationEntry> children = groupEntry.getRawChildren();
+ for (int j = children.size() - 1; j >= 0; j--) {
+ final NotificationEntry child = children.get(j);
+ if (applyFilters(child, now, filters)) {
+ children.remove(child);
+ annulAddition(child);
+ }
+ }
+
+ out.add(groupEntry);
+ } else {
+ if (applyFilters((NotificationEntry) entry, now, filters)) {
+ annulAddition(entry);
+ } else {
+ out.add(entry);
+ }
+ }
+ }
+ }
- // Otherwise, group it
+ private void groupNotifs(List<ListEntry> entries, List<ListEntry> out) {
+ for (ListEntry listEntry : entries) {
+ // since grouping hasn't happened yet, all notifs are NotificationEntries
+ NotificationEntry entry = (NotificationEntry) listEntry;
if (entry.getSbn().isGroup()) {
final String topLevelKey = entry.getSbn().getGroupKey();
@@ -338,7 +417,6 @@ public class NotifListBuilderImpl implements NotifListBuilder {
if (group == null) {
group = new GroupEntry(topLevelKey);
group.mFirstAddedIteration = mIterationCount;
- newlyVisibleEntries.add(group);
mGroups.put(topLevelKey, group);
}
if (group.getParent() == null) {
@@ -354,7 +432,7 @@ public class NotifListBuilderImpl implements NotifListBuilder {
if (existingSummary == null) {
group.setSummary(entry);
} else {
- Log.w(TAG, String.format(
+ mNotifLog.log(NotifEvent.WARN, String.format(
"Duplicate summary for group '%s': '%s' vs. '%s'",
group.getKey(),
existingSummary.getKey(),
@@ -364,9 +442,9 @@ public class NotifListBuilderImpl implements NotifListBuilder {
if (entry.getSbn().getPostTime()
> existingSummary.getSbn().getPostTime()) {
group.setSummary(entry);
- annulAddition(existingSummary, out, newlyVisibleEntries);
+ annulAddition(existingSummary, out);
} else {
- annulAddition(entry, out, newlyVisibleEntries);
+ annulAddition(entry, out);
}
}
} else {
@@ -377,7 +455,8 @@ public class NotifListBuilderImpl implements NotifListBuilder {
final String topLevelKey = entry.getKey();
if (mGroups.containsKey(topLevelKey)) {
- Log.wtf(TAG, "Duplicate non-group top-level key: " + topLevelKey);
+ mNotifLog.log(NotifEvent.WARN,
+ "Duplicate non-group top-level key: " + topLevelKey);
} else {
entry.setParent(ROOT_ENTRY);
out.add(entry);
@@ -407,10 +486,7 @@ public class NotifListBuilderImpl implements NotifListBuilder {
}
}
- private void pruneIncompleteGroups(
- List<ListEntry> shadeList,
- List<ListEntry> newlyVisibleEntries) {
-
+ private void pruneIncompleteGroups(List<ListEntry> shadeList) {
for (int i = 0; i < shadeList.size(); i++) {
final ListEntry tle = shadeList.get(i);
@@ -427,7 +503,7 @@ public class NotifListBuilderImpl implements NotifListBuilder {
shadeList.add(summary);
group.setSummary(null);
- annulAddition(group, shadeList, newlyVisibleEntries);
+ annulAddition(group, shadeList);
} else if (group.getSummary() == null
|| children.size() < MIN_CHILDREN_FOR_GROUP) {
@@ -440,7 +516,7 @@ public class NotifListBuilderImpl implements NotifListBuilder {
if (group.getSummary() != null) {
final NotificationEntry summary = group.getSummary();
group.setSummary(null);
- annulAddition(summary, shadeList, newlyVisibleEntries);
+ annulAddition(summary, shadeList);
}
for (int j = 0; j < children.size(); j++) {
@@ -450,7 +526,7 @@ public class NotifListBuilderImpl implements NotifListBuilder {
}
children.clear();
- annulAddition(group, shadeList, newlyVisibleEntries);
+ annulAddition(group, shadeList);
}
}
}
@@ -464,10 +540,7 @@ public class NotifListBuilderImpl implements NotifListBuilder {
* Before calling this method, the entry must already have been removed from its parent. If
* it's a group, its summary must be null and its children must be empty.
*/
- private void annulAddition(
- ListEntry entry,
- List<ListEntry> shadeList,
- List<ListEntry> newlyVisibleEntries) {
+ private void annulAddition(ListEntry entry, List<ListEntry> shadeList) {
// This function does very little, but if any of its assumptions are violated (and it has a
// lot of them), it will put the system into an inconsistent state. So we check all of them
@@ -504,13 +577,18 @@ public class NotifListBuilderImpl implements NotifListBuilder {
}
}
+ annulAddition(entry);
+
+ }
+
+ /**
+ * Erases bookkeeping traces stored on an entry when it is removed from the notif list.
+ * This can happen if the entry is removed from a group that was broken up or if the entry was
+ * filtered out during any of the filtering steps.
+ */
+ private void annulAddition(ListEntry entry) {
entry.setParent(null);
if (entry.mFirstAddedIteration == mIterationCount) {
- if (!newlyVisibleEntries.remove(entry)) {
- throw new IllegalStateException("Cannot late-filter entry " + entry.getKey() + " "
- + entry + " from " + newlyVisibleEntries + " "
- + entry.mFirstAddedIteration);
- }
entry.mFirstAddedIteration = -1;
}
}
@@ -539,7 +617,7 @@ public class NotifListBuilderImpl implements NotifListBuilder {
private void logParentingChanges() {
for (NotificationEntry entry : mAllEntries) {
if (entry.getParent() != entry.getPreviousParent()) {
- Log.i(TAG, String.format(
+ mNotifLog.log(NotifEvent.PARENT_CHANGED, String.format(
"%s: parent changed from %s to %s",
entry.getKey(),
entry.getPreviousParent() == null
@@ -550,7 +628,7 @@ public class NotifListBuilderImpl implements NotifListBuilder {
}
for (GroupEntry group : mGroups.values()) {
if (group.getParent() != group.getPreviousParent()) {
- Log.i(TAG, String.format(
+ mNotifLog.log(NotifEvent.PARENT_CHANGED, String.format(
"%s: parent changed from %s to %s",
group.getKey(),
group.getPreviousParent() == null
@@ -602,22 +680,22 @@ public class NotifListBuilderImpl implements NotifListBuilder {
return cmp;
};
- private boolean applyFilters(NotificationEntry entry, long now) {
- NotifFilter filter = findRejectingFilter(entry, now);
+ private boolean applyFilters(NotificationEntry entry, long now, List<NotifFilter> filters) {
+ NotifFilter filter = findRejectingFilter(entry, now, filters);
if (filter != entry.mExcludingFilter) {
if (entry.mExcludingFilter == null) {
- Log.i(TAG, String.format(
+ mNotifLog.log(NotifEvent.FILTER_CHANGED, String.format(
"%s: filtered out by '%s'",
entry.getKey(),
filter.getName()));
} else if (filter == null) {
- Log.i(TAG, String.format(
+ mNotifLog.log(NotifEvent.FILTER_CHANGED, String.format(
"%s: no longer filtered out (previous filter was '%s')",
entry.getKey(),
entry.mExcludingFilter.getName()));
} else {
- Log.i(TAG, String.format(
+ mNotifLog.log(NotifEvent.FILTER_CHANGED, String.format(
"%s: filter changed: '%s' -> '%s'",
entry.getKey(),
entry.mExcludingFilter,
@@ -633,9 +711,12 @@ public class NotifListBuilderImpl implements NotifListBuilder {
return filter != null;
}
- @Nullable private NotifFilter findRejectingFilter(NotificationEntry entry, long now) {
- for (int i = 0; i < mNotifFilters.size(); i++) {
- NotifFilter filter = mNotifFilters.get(i);
+ @Nullable private static NotifFilter findRejectingFilter(NotificationEntry entry, long now,
+ List<NotifFilter> filters) {
+ final int size = filters.size();
+
+ for (int i = 0; i < size; i++) {
+ NotifFilter filter = filters.get(i);
if (filter.shouldFilterOut(entry, now)) {
return filter;
}
@@ -648,23 +729,22 @@ public class NotifListBuilderImpl implements NotifListBuilder {
if (promoter != entry.mNotifPromoter) {
if (entry.mNotifPromoter == null) {
- Log.i(TAG, String.format(
+ mNotifLog.log(NotifEvent.PROMOTER_CHANGED, String.format(
"%s: Entry promoted to top level by '%s'",
entry.getKey(),
promoter.getName()));
} else if (promoter == null) {
- Log.i(TAG, String.format(
+ mNotifLog.log(NotifEvent.PROMOTER_CHANGED, String.format(
"%s: Entry is no longer promoted to top level (previous promoter was '%s')",
entry.getKey(),
entry.mNotifPromoter.getName()));
} else {
- Log.i(TAG, String.format(
+ mNotifLog.log(NotifEvent.PROMOTER_CHANGED, String.format(
"%s: Top-level promoter changed: '%s' -> '%s'",
entry.getKey(),
entry.mNotifPromoter,
promoter));
}
-
entry.mNotifPromoter = promoter;
}
@@ -688,12 +768,9 @@ public class NotifListBuilderImpl implements NotifListBuilder {
}
}
- private void dispatchOnBeforeTransformGroups(
- List<ListEntry> entries,
- List<ListEntry> newlyVisibleEntries) {
+ private void dispatchOnBeforeTransformGroups(List<ListEntry> entries) {
for (int i = 0; i < mOnBeforeTransformGroupsListeners.size(); i++) {
- mOnBeforeTransformGroupsListeners.get(i)
- .onBeforeTransformGroups(entries, newlyVisibleEntries);
+ mOnBeforeTransformGroupsListeners.get(i).onBeforeTransformGroups(entries);
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java
index 232fb6d3cf67..de16ef5a6d40 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java
@@ -21,7 +21,6 @@ import static android.app.Notification.CATEGORY_CALL;
import static android.app.Notification.CATEGORY_EVENT;
import static android.app.Notification.CATEGORY_MESSAGE;
import static android.app.Notification.CATEGORY_REMINDER;
-import static android.app.Notification.EXTRA_MESSAGES;
import static android.app.Notification.FLAG_BUBBLE;
import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_AMBIENT;
import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_BADGE;
@@ -42,7 +41,6 @@ import android.app.Person;
import android.content.Context;
import android.graphics.drawable.Icon;
import android.os.Bundle;
-import android.os.Parcelable;
import android.os.SystemClock;
import android.service.notification.NotificationListenerService.Ranking;
import android.service.notification.SnoozeCriterion;
@@ -92,7 +90,6 @@ public final class NotificationEntry extends ListEntry {
private StatusBarNotification mSbn;
private Ranking mRanking;
-
/*
* Bookkeeping members
*/
@@ -120,7 +117,6 @@ public final class NotificationEntry extends ListEntry {
public int targetSdk;
private long lastFullScreenIntentLaunchTime = NOT_LAUNCHED_YET;
public CharSequence remoteInputText;
- private final List<Person> mAssociatedPeople = new ArrayList<>();
private Notification.BubbleMetadata mBubbleMetadata;
/**
@@ -157,12 +153,6 @@ public final class NotificationEntry extends ListEntry {
*/
private boolean hasSentReply;
- /**
- * Whether this notification is shown to the user as a high priority notification: visible on
- * the lock screen/status bar and in the top section in the shade.
- */
- private boolean mHighPriority;
-
private boolean mSensitive = true;
private Runnable mOnSensitiveChangedListener;
private boolean mAutoHeadsUp;
@@ -212,9 +202,11 @@ public final class NotificationEntry extends ListEntry {
+ " doesn't match existing key " + mKey);
}
- mSbn = sbn;
- mBubbleMetadata = mSbn.getNotification().getBubbleMetadata();
- updatePeopleList();
+ if (!Objects.equals(mSbn, sbn)) {
+ mSbn = sbn;
+ mBubbleMetadata = mSbn.getNotification().getBubbleMetadata();
+ onSbnUpdated();
+ }
}
/**
@@ -239,10 +231,12 @@ public final class NotificationEntry extends ListEntry {
+ " doesn't match existing key " + mKey);
}
- mRanking = ranking;
+ if (!Objects.equals(mRanking, ranking)) {
+ mRanking = ranking;
+ onRankingUpdated();
+ }
}
-
/*
* Convenience getters for SBN and Ranking members
*/
@@ -304,49 +298,10 @@ public final class NotificationEntry extends ListEntry {
return interruption;
}
- public boolean isHighPriority() {
- return mHighPriority;
- }
-
- public void setIsHighPriority(boolean highPriority) {
- this.mHighPriority = highPriority;
- }
-
public boolean isBubble() {
return (mSbn.getNotification().flags & FLAG_BUBBLE) != 0;
}
- private void updatePeopleList() {
- mAssociatedPeople.clear();
-
- Bundle extras = mSbn.getNotification().extras;
- if (extras == null) {
- return;
- }
-
- List<Person> p = extras.getParcelableArrayList(Notification.EXTRA_PEOPLE_LIST);
-
- if (p != null) {
- mAssociatedPeople.addAll(p);
- }
-
- if (Notification.MessagingStyle.class.equals(
- mSbn.getNotification().getNotificationStyle())) {
- final Parcelable[] messages = extras.getParcelableArray(EXTRA_MESSAGES);
- if (!ArrayUtils.isEmpty(messages)) {
- for (Notification.MessagingStyle.Message message :
- Notification.MessagingStyle.Message
- .getMessagesFromBundleArray(messages)) {
- mAssociatedPeople.add(message.getSenderPerson());
- }
- }
- }
- }
-
- boolean hasAssociatedPeople() {
- return mAssociatedPeople.size() > 0;
- }
-
/**
* Returns the data needed for a bubble for this notification, if it exists.
*/
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationRankingManager.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationRankingManager.kt
index 48a4882bcf82..7010943559ba 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationRankingManager.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationRankingManager.kt
@@ -16,14 +16,11 @@
package com.android.systemui.statusbar.notification.collection
-import android.app.NotificationManager.IMPORTANCE_DEFAULT
import android.app.NotificationManager.IMPORTANCE_HIGH
-import android.app.NotificationManager.IMPORTANCE_LOW
import android.app.NotificationManager.IMPORTANCE_MIN
import android.service.notification.NotificationListenerService.Ranking
import android.service.notification.NotificationListenerService.RankingMap
import android.service.notification.StatusBarNotification
-import com.android.internal.annotations.VisibleForTesting
import com.android.systemui.statusbar.NotificationMediaManager
import com.android.systemui.statusbar.notification.NotificationFilter
import com.android.systemui.statusbar.notification.NotificationSectionsFeatureManager
@@ -105,44 +102,6 @@ open class NotificationRankingManager @Inject constructor(
return entry.key == mediaManager.mediaNotificationKey && importance > IMPORTANCE_MIN
}
- @VisibleForTesting
- protected fun isHighPriority(entry: NotificationEntry): Boolean {
- if (entry.importance >= IMPORTANCE_DEFAULT ||
- hasHighPriorityCharacteristics(entry)) {
- return true
- }
-
- if (groupManager.isSummaryOfGroup(entry.sbn)) {
- val logicalChildren = groupManager.getLogicalChildren(entry.sbn)
- for (child in logicalChildren) {
- if (isHighPriority(child)) {
- return true
- }
- }
- }
-
- return false
- }
-
- private fun hasHighPriorityCharacteristics(entry: NotificationEntry): Boolean {
- val c = entry.channel
- val n = entry.sbn.notification
-
- if ((n.isForegroundService && entry.ranking.importance >= IMPORTANCE_LOW) ||
- n.hasMediaSession() ||
- entry.isPeopleNotification()) {
- // Users who have long pressed and demoted to silent should not see the notification
- // in the top section
- if (c != null && c.hasUserSetImportance()) {
- return false
- }
-
- return true
- }
-
- return false
- }
-
fun updateRanking(
newRankingMap: RankingMap?,
entries: Collection<NotificationEntry>,
@@ -219,7 +178,10 @@ open class NotificationRankingManager @Inject constructor(
// TODO: notify group manager here?
groupManager.onEntryUpdated(entry, oldSbn)
}
- entry.setIsHighPriority(isHighPriority(entry))
+
+ // TODO: (b/145659174) remove after moving to new NotifPipeline
+ // (should be able to remove all groupManager code post-migration)
+ entry.invalidateDerivedMembers()
}
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/DeviceProvisionedCoordinator.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/DeviceProvisionedCoordinator.java
index 511aafc2d12a..5e7dd98fa9da 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/DeviceProvisionedCoordinator.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/DeviceProvisionedCoordinator.java
@@ -17,7 +17,6 @@
package com.android.systemui.statusbar.notification.collection.coordinator;
import android.Manifest;
-import android.app.AppGlobals;
import android.app.Notification;
import android.content.pm.IPackageManager;
import android.content.pm.PackageManager;
@@ -43,20 +42,23 @@ public class DeviceProvisionedCoordinator implements Coordinator {
private static final String TAG = "DeviceProvisionedCoordinator";
private final DeviceProvisionedController mDeviceProvisionedController;
+ private final IPackageManager mIPackageManager;
@Inject
- public DeviceProvisionedCoordinator(DeviceProvisionedController deviceProvisionedController) {
+ public DeviceProvisionedCoordinator(DeviceProvisionedController deviceProvisionedController,
+ IPackageManager packageManager) {
mDeviceProvisionedController = deviceProvisionedController;
+ mIPackageManager = packageManager;
}
@Override
public void attach(NotifCollection notifCollection, NotifListBuilder notifListBuilder) {
mDeviceProvisionedController.addCallback(mDeviceProvisionedListener);
- notifListBuilder.addFilter(mNotifFilter);
+ notifListBuilder.addPreGroupFilter(mNotifFilter);
}
- protected final NotifFilter mNotifFilter = new NotifFilter(TAG) {
+ private final NotifFilter mNotifFilter = new NotifFilter(TAG) {
@Override
public boolean shouldFilterOut(NotificationEntry entry, long now) {
return !mDeviceProvisionedController.isDeviceProvisioned()
@@ -70,17 +72,16 @@ public class DeviceProvisionedCoordinator implements Coordinator {
* marking them as relevant for setup are allowed to show when device is unprovisioned
*/
private boolean showNotificationEvenIfUnprovisioned(StatusBarNotification sbn) {
- final boolean hasPermission = checkUidPermission(AppGlobals.getPackageManager(),
+ final boolean hasPermission = checkUidPermission(
Manifest.permission.NOTIFICATION_DURING_SETUP,
sbn.getUid()) == PackageManager.PERMISSION_GRANTED;
return hasPermission
&& sbn.getNotification().extras.getBoolean(Notification.EXTRA_ALLOW_DURING_SETUP);
}
- private static int checkUidPermission(IPackageManager packageManager, String permission,
- int uid) {
+ private int checkUidPermission(String permission, int uid) {
try {
- return packageManager.checkUidPermission(permission, uid);
+ return mIPackageManager.checkUidPermission(permission, uid);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/ForegroundCoordinator.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/ForegroundCoordinator.java
index 4803cf478327..ee841c2b4e14 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/ForegroundCoordinator.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/ForegroundCoordinator.java
@@ -24,7 +24,6 @@ import android.util.ArraySet;
import com.android.systemui.ForegroundServiceController;
import com.android.systemui.appops.AppOpsController;
-import com.android.systemui.dagger.qualifiers.BgHandler;
import com.android.systemui.dagger.qualifiers.MainHandler;
import com.android.systemui.statusbar.notification.collection.NotifCollection;
import com.android.systemui.statusbar.notification.collection.NotifCollectionListener;
@@ -52,12 +51,11 @@ import javax.inject.Singleton;
*/
@Singleton
public class ForegroundCoordinator implements Coordinator {
- private static final String TAG = "ForegroundNotificationCoordinator";
+ private static final String TAG = "ForegroundCoordinator";
private final ForegroundServiceController mForegroundServiceController;
private final AppOpsController mAppOpsController;
private final Handler mMainHandler;
- private final Handler mBgHandler;
private NotifCollection mNotifCollection;
@@ -65,12 +63,10 @@ public class ForegroundCoordinator implements Coordinator {
public ForegroundCoordinator(
ForegroundServiceController foregroundServiceController,
AppOpsController appOpsController,
- @MainHandler Handler mainHandler,
- @BgHandler Handler bgHandler) {
+ @MainHandler Handler mainHandler) {
mForegroundServiceController = foregroundServiceController;
mAppOpsController = appOpsController;
mMainHandler = mainHandler;
- mBgHandler = bgHandler;
}
@Override
@@ -87,13 +83,13 @@ public class ForegroundCoordinator implements Coordinator {
mAppOpsController.addCallback(ForegroundServiceController.APP_OPS, this::onAppOpsChanged);
// filter out foreground service notifications that aren't necessary anymore
- notifListBuilder.addFilter(mNotifFilter);
+ notifListBuilder.addPreGroupFilter(mNotifFilter);
}
/**
* Filters out notifications that represent foreground services that are no longer running.
*/
- protected final NotifFilter mNotifFilter = new NotifFilter(TAG) {
+ private final NotifFilter mNotifFilter = new NotifFilter(TAG) {
@Override
public boolean shouldFilterOut(NotificationEntry entry, long now) {
StatusBarNotification sbn = entry.getSbn();
@@ -120,7 +116,8 @@ public class ForegroundCoordinator implements Coordinator {
* Extends the lifetime of foreground notification services such that they show for at least
* five seconds
*/
- private final NotifLifetimeExtender mForegroundLifetimeExtender = new NotifLifetimeExtender() {
+ private final NotifLifetimeExtender mForegroundLifetimeExtender =
+ new NotifLifetimeExtender() {
private static final int MIN_FGS_TIME_MS = 5000;
private OnEndLifetimeExtensionCallback mEndCallback;
private Map<String, Runnable> mEndRunnables = new HashMap<>();
@@ -154,8 +151,8 @@ public class ForegroundCoordinator implements Coordinator {
}
};
mEndRunnables.put(entry.getKey(), runnable);
- mBgHandler.postDelayed(runnable, MIN_FGS_TIME_MS
- - (currTime - entry.getSbn().getPostTime()));
+ mMainHandler.postDelayed(runnable,
+ MIN_FGS_TIME_MS - (currTime - entry.getSbn().getPostTime()));
}
}
@@ -166,7 +163,7 @@ public class ForegroundCoordinator implements Coordinator {
public void cancelLifetimeExtension(NotificationEntry entry) {
if (mEndRunnables.containsKey(entry.getKey())) {
Runnable endRunnable = mEndRunnables.remove(entry.getKey());
- mBgHandler.removeCallbacks(endRunnable);
+ mMainHandler.removeCallbacks(endRunnable);
}
}
};
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/KeyguardCoordinator.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/KeyguardCoordinator.java
index 6daf3fc50b30..9312c2260d46 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/KeyguardCoordinator.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/KeyguardCoordinator.java
@@ -37,6 +37,8 @@ import com.android.systemui.broadcast.BroadcastDispatcher;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.NotificationLockscreenUserManager;
import com.android.systemui.statusbar.notification.NotificationUtils;
+import com.android.systemui.statusbar.notification.collection.GroupEntry;
+import com.android.systemui.statusbar.notification.collection.ListEntry;
import com.android.systemui.statusbar.notification.collection.NotifCollection;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.listbuilder.NotifListBuilder;
@@ -51,7 +53,7 @@ import javax.inject.Singleton;
*/
@Singleton
public class KeyguardCoordinator implements Coordinator {
- private static final String TAG = "KeyguardNotificationCoordinator";
+ private static final String TAG = "KeyguardCoordinator";
private final Context mContext;
private final Handler mMainHandler;
@@ -83,10 +85,10 @@ public class KeyguardCoordinator implements Coordinator {
@Override
public void attach(NotifCollection notifCollection, NotifListBuilder notifListBuilder) {
setupInvalidateNotifListCallbacks();
- notifListBuilder.addFilter(mNotifFilter);
+ notifListBuilder.addPreRenderFilter(mNotifFilter);
}
- protected final NotifFilter mNotifFilter = new NotifFilter(TAG) {
+ private final NotifFilter mNotifFilter = new NotifFilter(TAG) {
@Override
public boolean shouldFilterOut(NotificationEntry entry, long now) {
final StatusBarNotification sbn = entry.getSbn();
@@ -129,12 +131,11 @@ public class KeyguardCoordinator implements Coordinator {
}
}
- // ... neither this notification nor its summary have high enough priority
+ // ... neither this notification nor its group have high enough priority
// to be shown on the lockscreen
- // TODO: grouping hasn't happened yet (b/145134683)
if (entry.getParent() != null) {
- final NotificationEntry summary = entry.getParent().getRepresentativeEntry();
- if (priorityExceedsLockscreenShowingThreshold(summary)) {
+ final GroupEntry parent = entry.getParent();
+ if (priorityExceedsLockscreenShowingThreshold(parent)) {
return false;
}
}
@@ -144,17 +145,16 @@ public class KeyguardCoordinator implements Coordinator {
}
};
- private boolean priorityExceedsLockscreenShowingThreshold(NotificationEntry entry) {
+ private boolean priorityExceedsLockscreenShowingThreshold(ListEntry entry) {
if (entry == null) {
return false;
}
if (NotificationUtils.useNewInterruptionModel(mContext)
&& hideSilentNotificationsOnLockscreen()) {
- // TODO: make sure in the NewNotifPipeline that entry.isHighPriority() has been
- // correctly updated before reaching this point (b/145134683)
return entry.isHighPriority();
} else {
- return !entry.getRanking().isAmbient();
+ return entry.getRepresentativeEntry() != null
+ && !entry.getRepresentativeEntry().getRanking().isAmbient();
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinator.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinator.java
index c390f96f004d..0751aa814215 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinator.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinator.java
@@ -26,7 +26,10 @@ import javax.inject.Inject;
import javax.inject.Singleton;
/**
- * Filters out NotificationEntries based on its Ranking.
+ * Filters out NotificationEntries based on its Ranking and dozing state.
+ * We check the NotificationEntry's Ranking for:
+ * - whether the notification's app is suspended or hiding its notifications
+ * - whether DND settings are hiding notifications from ambient display or the notification list
*/
@Singleton
public class RankingCoordinator implements Coordinator {
@@ -43,7 +46,7 @@ public class RankingCoordinator implements Coordinator {
public void attach(NotifCollection notifCollection, NotifListBuilder notifListBuilder) {
mStatusBarStateController.addCallback(mStatusBarStateCallback);
- notifListBuilder.addFilter(mNotifFilter);
+ notifListBuilder.addPreGroupFilter(mNotifFilter);
}
/**
@@ -51,7 +54,7 @@ public class RankingCoordinator implements Coordinator {
* NotifListBuilder invalidates the notification list each time the ranking is updated,
* so we don't need to explicitly invalidate this filter on ranking update.
*/
- protected final NotifFilter mNotifFilter = new NotifFilter(TAG) {
+ private final NotifFilter mNotifFilter = new NotifFilter(TAG) {
@Override
public boolean shouldFilterOut(NotificationEntry entry, long now) {
// App suspended from Ranking
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/NotifListBuilder.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/NotifListBuilder.java
index 15d3b9222cd2..758092417ae0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/NotifListBuilder.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/NotifListBuilder.java
@@ -59,11 +59,12 @@ import java.util.List;
public interface NotifListBuilder {
/**
- * Registers a filter with the pipeline. Filters are called on each notification in the order
- * that they were registered. If any filter returns true, the notification is removed from the
- * pipeline (and no other filters are called on that notif).
+ * Registers a filter with the pipeline before grouping, promoting and sorting occurs. Filters
+ * are called on each notification in the order that they were registered. If any filter
+ * returns true, the notification is removed from the pipeline (and no other filters are
+ * called on that notif).
*/
- void addFilter(NotifFilter filter);
+ void addPreGroupFilter(NotifFilter filter);
/**
* Registers a promoter with the pipeline. Promoters are able to promote child notifications to
@@ -91,6 +92,15 @@ public interface NotifListBuilder {
void setComparators(List<NotifComparator> comparators);
/**
+ * Registers a filter with the pipeline to filter right before rendering the list (after
+ * pre-group filtering, grouping, promoting and sorting occurs). Filters are
+ * called on each notification in the order that they were registered. If any filter returns
+ * true, the notification is removed from the pipeline (and no other filters are called on that
+ * notif).
+ */
+ void addPreRenderFilter(NotifFilter filter);
+
+ /**
* Called after notifications have been filtered and after the initial grouping has been
* performed but before NotifPromoters have had a chance to promote children out of groups.
*/
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/OnBeforeTransformGroupsListener.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/OnBeforeTransformGroupsListener.java
index 170ff48ad7f1..d7a081510655 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/OnBeforeTransformGroupsListener.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/OnBeforeTransformGroupsListener.java
@@ -33,8 +33,6 @@ public interface OnBeforeTransformGroupsListener {
* @param list The current filtered and grouped list of (top-level) entries. Note that this is
* a live view into the current notif list and will change as the list moves through
* the pipeline.
- * @param newlyVisibleEntries The list of all entries (both top-level and children) who have
- * been added to the list for the first time.
*/
- void onBeforeTransformGroups(List<ListEntry> list, List<ListEntry> newlyVisibleEntries);
+ void onBeforeTransformGroups(List<ListEntry> list);
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/PipelineState.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/PipelineState.java
index ad4bbd915787..85f828d9e3c7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/PipelineState.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/PipelineState.java
@@ -78,18 +78,24 @@ public class PipelineState {
public static final int STATE_IDLE = 0;
public static final int STATE_BUILD_PENDING = 1;
public static final int STATE_BUILD_STARTED = 2;
- public static final int STATE_FILTERING = 3;
- public static final int STATE_TRANSFORMING = 4;
- public static final int STATE_SORTING = 5;
- public static final int STATE_FINALIZING = 6;
+ public static final int STATE_RESETTING = 3;
+ public static final int STATE_PRE_GROUP_FILTERING = 4;
+ public static final int STATE_GROUPING = 5;
+ public static final int STATE_TRANSFORMING = 6;
+ public static final int STATE_SORTING = 7;
+ public static final int STATE_PRE_RENDER_FILTERING = 8;
+ public static final int STATE_FINALIZING = 9;
@IntDef(prefix = { "STATE_" }, value = {
STATE_IDLE,
STATE_BUILD_PENDING,
STATE_BUILD_STARTED,
- STATE_FILTERING,
+ STATE_RESETTING,
+ STATE_PRE_GROUP_FILTERING,
+ STATE_GROUPING,
STATE_TRANSFORMING,
STATE_SORTING,
+ STATE_PRE_RENDER_FILTERING,
STATE_FINALIZING,
})
@Retention(RetentionPolicy.SOURCE)
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/pluggable/NotifFilter.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/pluggable/NotifFilter.java
index 685eac88de34..e6189edc2f3b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/pluggable/NotifFilter.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/listbuilder/pluggable/NotifFilter.java
@@ -20,8 +20,8 @@ import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.listbuilder.NotifListBuilder;
/**
- * Pluggable for participating in notif filtering. See
- * {@link NotifListBuilder#addFilter(NotifFilter)}.
+ * Pluggable for participating in notif filtering.
+ * See {@link NotifListBuilder#addPreGroupFilter} and {@link NotifListBuilder#addPreRenderFilter}.
*/
public abstract class NotifFilter extends Pluggable<NotifFilter> {
protected NotifFilter(String name) {
@@ -34,7 +34,11 @@ public abstract class NotifFilter extends Pluggable<NotifFilter> {
* This doesn't necessarily mean that your filter will get called on every notification,
* however. If another filter returns true before yours, we'll skip straight to the next notif.
*
- * @param entry The entry in question
+ * @param entry The entry in question.
+ * If this filter is registered via {@link NotifListBuilder#addPreGroupFilter},
+ * this entry will not have any grouping nor sorting information.
+ * If this filter is registered via {@link NotifListBuilder#addPreRenderFilter},
+ * this entry will have grouping and sorting information.
* @param now A timestamp in SystemClock.uptimeMillis that represents "now" for the purposes of
* pipeline execution. This value will be the same for all pluggable calls made
* during this pipeline run, giving pluggables a stable concept of "now" to compare
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/provider/DerivedMember.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/provider/DerivedMember.java
new file mode 100644
index 000000000000..815e6f7eaa46
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/provider/DerivedMember.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.statusbar.notification.collection.provider;
+/**
+ * Caches a computed value until invalidate() is called
+ * @param <Parent> Object used to computeValue
+ * @param <Value> type of value to cache until invalidate is called
+ */
+public abstract class DerivedMember<Parent, Value> {
+ private Value mValue;
+ protected abstract Value computeValue(Parent parent);
+
+ /**
+ * Gets the last cached value, else recomputes the value.
+ */
+ public Value get(Parent parent) {
+ if (mValue == null) {
+ mValue = computeValue(parent);
+ }
+ return mValue;
+ }
+
+ /**
+ * Resets the cached value.
+ * Next time "get" is called, the value is recomputed.
+ */
+ public void invalidate() {
+ mValue = null;
+ }
+
+ /**
+ * Called when a NotificationEntry's status bar notification has updated.
+ * Derived members can invalidate here.
+ */
+ public void onSbnUpdated() {}
+
+ /**
+ * Called when a NotificationEntry's Ranking has updated.
+ * Derived members can invalidate here.
+ */
+ public void onRankingUpdated() {}
+
+ /**
+ * Called when a ListEntry's grouping information (parent or children) has changed.
+ * Derived members can invalidate here.
+ */
+ public void onGroupingUpdated() {}
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/provider/IsHighPriorityProvider.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/provider/IsHighPriorityProvider.java
new file mode 100644
index 000000000000..76e256b9be2d
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/provider/IsHighPriorityProvider.java
@@ -0,0 +1,148 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.statusbar.notification.collection.provider;
+
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.Person;
+
+import com.android.systemui.Dependency;
+import com.android.systemui.statusbar.notification.collection.GroupEntry;
+import com.android.systemui.statusbar.notification.collection.ListEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.phone.NotificationGroupManager;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Whether the ListEntry is shown to the user as a high priority notification: visible on
+ * the lock screen/status bar and in the top section in the shade.
+ *
+ * A NotificationEntry is considered high priority if it:
+ * - has importance greater than or equal to IMPORTANCE_DEFAULT
+ * OR
+ * - their importance has NOT been set to a low priority option by the user AND the notification
+ * fulfills one of the following:
+ * - has a person associated with it
+ * - has a media session associated with it
+ * - has messaging style
+ *
+ * A GroupEntry is considered high priority if its representativeEntry (summary) or children are
+ * high priority
+ */
+public class IsHighPriorityProvider extends DerivedMember<ListEntry, Boolean> {
+ // TODO: (b/145659174) remove groupManager when moving to NewNotifPipeline. Logic
+ // replaced in GroupEntry and NotifListBuilderImpl
+ private final NotificationGroupManager mGroupManager;
+
+
+ public IsHighPriorityProvider() {
+ // TODO: (b/145659174) remove
+ mGroupManager = Dependency.get(NotificationGroupManager.class);
+ }
+
+ @Override
+ protected Boolean computeValue(ListEntry entry) {
+ if (entry == null) {
+ return false;
+ }
+
+ return isHighPriority(entry);
+ }
+
+ private boolean isHighPriority(ListEntry listEntry) {
+ // requires groups have been set (AFTER PipelineState.STATE_TRANSFORMING)
+ final NotificationEntry notifEntry = listEntry.getRepresentativeEntry();
+ return notifEntry.getRanking().getImportance() >= NotificationManager.IMPORTANCE_DEFAULT
+ || hasHighPriorityCharacteristics(notifEntry)
+ || hasHighPriorityChild(listEntry);
+
+ }
+
+ private boolean hasHighPriorityChild(ListEntry entry) {
+ // TODO: (b/145659174) remove
+ if (entry instanceof NotificationEntry) {
+ NotificationEntry notifEntry = (NotificationEntry) entry;
+ if (mGroupManager.isSummaryOfGroup(notifEntry.getSbn())) {
+ List<NotificationEntry> logicalChildren =
+ mGroupManager.getLogicalChildren(notifEntry.getSbn());
+ for (NotificationEntry child : logicalChildren) {
+ if (child.isHighPriority()) {
+ return true;
+ }
+ }
+ }
+ }
+
+ if (entry instanceof GroupEntry) {
+ for (NotificationEntry child : ((GroupEntry) entry).getChildren()) {
+ if (child.isHighPriority()) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private boolean hasHighPriorityCharacteristics(NotificationEntry entry) {
+ return !hasUserSetImportance(entry)
+ && (isImportantOngoing(entry)
+ || entry.getSbn().getNotification().hasMediaSession()
+ || hasPerson(entry)
+ || isMessagingStyle(entry));
+ }
+
+ private boolean isImportantOngoing(NotificationEntry entry) {
+ return entry.getSbn().getNotification().isForegroundService()
+ && entry.getRanking().getImportance() >= NotificationManager.IMPORTANCE_LOW;
+ }
+
+ private boolean isMessagingStyle(NotificationEntry entry) {
+ return Notification.MessagingStyle.class.equals(
+ entry.getSbn().getNotification().getNotificationStyle());
+ }
+
+ private boolean hasPerson(NotificationEntry entry) {
+ // TODO: cache favorite and recent contacts to check contact affinity
+ Notification notification = entry.getSbn().getNotification();
+ ArrayList<Person> people = notification.extras != null
+ ? notification.extras.getParcelableArrayList(Notification.EXTRA_PEOPLE_LIST)
+ : new ArrayList<>();
+ return people != null && !people.isEmpty();
+ }
+
+ private boolean hasUserSetImportance(NotificationEntry entry) {
+ return entry.getRanking().getChannel() != null
+ && entry.getRanking().getChannel().hasUserSetImportance();
+ }
+
+ @Override
+ public void onSbnUpdated() {
+ invalidate();
+ }
+
+ @Override
+ public void onRankingUpdated() {
+ invalidate();
+ }
+
+ @Override
+ public void onGroupingUpdated() {
+ invalidate();
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotifEvent.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotifEvent.java
index 8ebbca26fa5b..c18af800e183 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotifEvent.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotifEvent.java
@@ -17,10 +17,12 @@
package com.android.systemui.statusbar.notification.logging;
import android.annotation.IntDef;
-import android.service.notification.NotificationListenerService.Ranking;
+import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import com.android.systemui.log.RichEvent;
+import com.android.systemui.statusbar.notification.NotificationEntryManager;
+import com.android.systemui.statusbar.notification.collection.listbuilder.NotifListBuilder;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -31,103 +33,72 @@ import java.lang.annotation.RetentionPolicy;
* here to mitigate memory usage.
*/
public class NotifEvent extends RichEvent {
- public static final int TOTAL_EVENT_TYPES = 11;
-
/**
- * Creates a NotifEvent with an event type that matches with an index in the array
- * getSupportedEvents() and {@link EventType}.
- *
- * The status bar notification and ranking objects are stored as shallow copies of the current
- * state of the event when this event occurred.
+ * Initializes a rich event that includes an event type that matches with an index in the array
+ * getEventLabels().
*/
- public NotifEvent(int logLevel, int type, String reason, StatusBarNotification sbn,
- Ranking ranking) {
- super(logLevel, type, reason);
- mMessage += getExtraInfo(sbn, ranking);
- }
-
- private String getExtraInfo(StatusBarNotification sbn, Ranking ranking) {
- StringBuilder extraInfo = new StringBuilder();
-
+ public NotifEvent init(@EventType int type, StatusBarNotification sbn,
+ NotificationListenerService.Ranking ranking, String reason) {
+ StringBuilder extraInfo = new StringBuilder(reason);
if (sbn != null) {
- extraInfo.append(" Sbn=");
- extraInfo.append(sbn);
+ extraInfo.append(" " + sbn.getKey());
}
if (ranking != null) {
extraInfo.append(" Ranking=");
- extraInfo.append(ranking);
+ extraInfo.append(ranking.getRank());
}
-
- return extraInfo.toString();
+ super.init(INFO, type, extraInfo.toString());
+ return this;
}
/**
- * Event labels for NotifEvents
- * Index corresponds to the {@link EventType}
+ * Event labels for ListBuilderEvents
+ * Index corresponds to an # in {@link EventType}
*/
@Override
public String[] getEventLabels() {
- final String[] events = new String[]{
- "NotifAdded",
- "NotifRemoved",
- "NotifUpdated",
- "Filter",
- "Sort",
- "FilterAndSort",
- "NotifVisibilityChanged",
- "LifetimeExtended",
- "RemoveIntercepted",
- "InflationAborted",
- "Inflated"
- };
-
- if (events.length != TOTAL_EVENT_TYPES) {
- throw new IllegalStateException("NotifEvents events.length should match "
- + TOTAL_EVENT_TYPES
- + " events.length=" + events.length
- + " TOTAL_EVENT_LENGTH=" + TOTAL_EVENT_TYPES);
- }
- return events;
+ assert (TOTAL_EVENT_LABELS == (TOTAL_NEM_EVENT_TYPES + TOTAL_LIST_BUILDER_EVENT_TYPES));
+ return EVENT_LABELS;
}
/**
- * Builds a NotifEvent.
+ * @return if this event occurred in {@link NotifListBuilder}
*/
- public static class NotifEventBuilder extends RichEvent.Builder<NotifEventBuilder> {
- private StatusBarNotification mSbn;
- private Ranking mRanking;
-
- @Override
- public NotifEventBuilder getBuilder() {
- return this;
- }
-
- /**
- * Stores the status bar notification object. A shallow copy is stored in the NotifEvent's
- * constructor.
- */
- public NotifEventBuilder setSbn(StatusBarNotification sbn) {
- mSbn = sbn;
- return this;
- }
+ static boolean isListBuilderEvent(@EventType int type) {
+ return isBetweenInclusive(type, 0, TOTAL_LIST_BUILDER_EVENT_TYPES);
+ }
- /**
- * Stores the ranking object. A shallow copy is stored in the NotifEvent's
- * constructor.
- */
- public NotifEventBuilder setRanking(Ranking ranking) {
- mRanking = ranking;
- return this;
- }
+ /**
+ * @return if this event occurred in {@link NotificationEntryManager}
+ */
+ static boolean isNemEvent(@EventType int type) {
+ return isBetweenInclusive(type, TOTAL_LIST_BUILDER_EVENT_TYPES,
+ TOTAL_LIST_BUILDER_EVENT_TYPES + TOTAL_NEM_EVENT_TYPES);
+ }
- @Override
- public RichEvent build() {
- return new NotifEvent(mLogLevel, mType, mReason, mSbn, mRanking);
- }
+ private static boolean isBetweenInclusive(int x, int a, int b) {
+ return x >= a && x <= b;
}
- @IntDef({NOTIF_ADDED,
+ @IntDef({
+ // NotifListBuilder events:
+ WARN,
+ ON_BUILD_LIST,
+ START_BUILD_LIST,
+ DISPATCH_FINAL_LIST,
+ LIST_BUILD_COMPLETE,
+ PRE_GROUP_FILTER_INVALIDATED,
+ PROMOTER_INVALIDATED,
+ SECTIONS_PROVIDER_INVALIDATED,
+ COMPARATOR_INVALIDATED,
+ PARENT_CHANGED,
+ FILTER_CHANGED,
+ PROMOTER_CHANGED,
+ PRE_RENDER_FILTER_INVALIDATED,
+
+ // NotificationEntryManager events:
+ NOTIF_ADDED,
NOTIF_REMOVED,
NOTIF_UPDATED,
FILTER,
@@ -139,22 +110,74 @@ public class NotifEvent extends RichEvent {
INFLATION_ABORTED,
INFLATED
})
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface EventType {}
+
+ private static final String[] EVENT_LABELS =
+ new String[]{
+ // NotifListBuilder labels:
+ "Warning",
+ "OnBuildList",
+ "StartBuildList",
+ "DispatchFinalList",
+ "ListBuildComplete",
+ "FilterInvalidated",
+ "PromoterInvalidated",
+ "SectionsProviderInvalidated",
+ "ComparatorInvalidated",
+ "ParentChanged",
+ "FilterChanged",
+ "PromoterChanged",
+ "FinalFilterInvalidated",
+
+ // NEM event labels:
+ "NotifAdded",
+ "NotifRemoved",
+ "NotifUpdated",
+ "Filter",
+ "Sort",
+ "FilterAndSort",
+ "NotifVisibilityChanged",
+ "LifetimeExtended",
+ "RemoveIntercepted",
+ "InflationAborted",
+ "Inflated"
+ };
+
+ private static final int TOTAL_EVENT_LABELS = EVENT_LABELS.length;
/**
- * Types of NotifEvents
+ * Events related to {@link NotifListBuilder}
*/
- @Retention(RetentionPolicy.SOURCE)
- public @interface EventType {}
- public static final int NOTIF_ADDED = 0;
- public static final int NOTIF_REMOVED = 1;
- public static final int NOTIF_UPDATED = 2;
- public static final int FILTER = 3;
- public static final int SORT = 4;
- public static final int FILTER_AND_SORT = 5;
- public static final int NOTIF_VISIBILITY_CHANGED = 6;
- public static final int LIFETIME_EXTENDED = 7;
+ public static final int WARN = 0;
+ public static final int ON_BUILD_LIST = 1;
+ public static final int START_BUILD_LIST = 2;
+ public static final int DISPATCH_FINAL_LIST = 3;
+ public static final int LIST_BUILD_COMPLETE = 4;
+ public static final int PRE_GROUP_FILTER_INVALIDATED = 5;
+ public static final int PROMOTER_INVALIDATED = 6;
+ public static final int SECTIONS_PROVIDER_INVALIDATED = 7;
+ public static final int COMPARATOR_INVALIDATED = 8;
+ public static final int PARENT_CHANGED = 9;
+ public static final int FILTER_CHANGED = 10;
+ public static final int PROMOTER_CHANGED = 11;
+ public static final int PRE_RENDER_FILTER_INVALIDATED = 12;
+ private static final int TOTAL_LIST_BUILDER_EVENT_TYPES = 13;
+
+ /**
+ * Events related to {@link NotificationEntryManager}
+ */
+ public static final int NOTIF_ADDED = TOTAL_LIST_BUILDER_EVENT_TYPES + 0;
+ public static final int NOTIF_REMOVED = TOTAL_LIST_BUILDER_EVENT_TYPES + 1;
+ public static final int NOTIF_UPDATED = TOTAL_LIST_BUILDER_EVENT_TYPES + 2;
+ public static final int FILTER = TOTAL_LIST_BUILDER_EVENT_TYPES + 3;
+ public static final int SORT = TOTAL_LIST_BUILDER_EVENT_TYPES + 4;
+ public static final int FILTER_AND_SORT = TOTAL_LIST_BUILDER_EVENT_TYPES + 5;
+ public static final int NOTIF_VISIBILITY_CHANGED = TOTAL_LIST_BUILDER_EVENT_TYPES + 6;
+ public static final int LIFETIME_EXTENDED = TOTAL_LIST_BUILDER_EVENT_TYPES + 7;
// unable to remove notif - removal intercepted by {@link NotificationRemoveInterceptor}
- public static final int REMOVE_INTERCEPTED = 8;
- public static final int INFLATION_ABORTED = 9;
- public static final int INFLATED = 10;
+ public static final int REMOVE_INTERCEPTED = TOTAL_LIST_BUILDER_EVENT_TYPES + 8;
+ public static final int INFLATION_ABORTED = TOTAL_LIST_BUILDER_EVENT_TYPES + 9;
+ public static final int INFLATED = TOTAL_LIST_BUILDER_EVENT_TYPES + 10;
+ private static final int TOTAL_NEM_EVENT_TYPES = 11;
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotifLog.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotifLog.java
index 129283107894..299d628d0fd2 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotifLog.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotifLog.java
@@ -16,6 +16,7 @@
package com.android.systemui.statusbar.notification.logging;
+import android.os.SystemProperties;
import android.service.notification.NotificationListenerService.Ranking;
import android.service.notification.StatusBarNotification;
@@ -33,93 +34,82 @@ import javax.inject.Singleton;
* dependency DumpController NotifLog
*/
@Singleton
-public class NotifLog extends SysuiLog {
+public class NotifLog extends SysuiLog<NotifEvent> {
private static final String TAG = "NotifLog";
+ private static final boolean SHOW_NEM_LOGS =
+ SystemProperties.getBoolean("persist.sysui.log.notif.nem", true);
+ private static final boolean SHOW_LIST_BUILDER_LOGS =
+ SystemProperties.getBoolean("persist.sysui.log.notif.listbuilder", true);
+
private static final int MAX_DOZE_DEBUG_LOGS = 400;
private static final int MAX_DOZE_LOGS = 50;
+ private NotifEvent mRecycledEvent;
+
@Inject
public NotifLog(DumpController dumpController) {
super(dumpController, TAG, MAX_DOZE_DEBUG_LOGS, MAX_DOZE_LOGS);
}
/**
- * Logs a {@link NotifEvent} with a notification, ranking and message
+ * Logs a {@link NotifEvent} with a notification, ranking and message.
+ * Uses the last recycled event if available.
* @return true if successfully logged, else false
*/
- public boolean log(@NotifEvent.EventType int eventType, StatusBarNotification sbn,
- Ranking ranking, String msg) {
- return log(new NotifEvent.NotifEventBuilder()
- .setType(eventType)
- .setSbn(sbn)
- .setRanking(ranking)
- .setReason(msg)
- .build());
- }
+ public void log(@NotifEvent.EventType int eventType,
+ StatusBarNotification sbn, Ranking ranking, String msg) {
+ if (!mEnabled
+ || (NotifEvent.isListBuilderEvent(eventType) && !SHOW_LIST_BUILDER_LOGS)
+ || (NotifEvent.isNemEvent(eventType) && !SHOW_NEM_LOGS)) {
+ return;
+ }
- /**
- * Logs a {@link NotifEvent}
- * @return true if successfully logged, else false
- */
- public boolean log(@NotifEvent.EventType int eventType) {
- return log(eventType, null, null, null);
+ if (mRecycledEvent != null) {
+ mRecycledEvent = log(mRecycledEvent.init(eventType, sbn, ranking, msg));
+ } else {
+ mRecycledEvent = log(new NotifEvent().init(eventType, sbn, ranking, msg));
+ }
}
/**
- * Logs a {@link NotifEvent} with a message
- * @return true if successfully logged, else false
+ * Logs a {@link NotifEvent} with no extra information aside from the event type
*/
- public boolean log(@NotifEvent.EventType int eventType, String msg) {
- return log(eventType, null, null, msg);
+ public void log(@NotifEvent.EventType int eventType) {
+ log(eventType, null, null, "");
}
/**
- * Logs a {@link NotifEvent} with a notification
- * @return true if successfully logged, else false
- */
- public boolean log(@NotifEvent.EventType int eventType, StatusBarNotification sbn) {
- return log(eventType, sbn, null, "");
- }
-
- /**
- * Logs a {@link NotifEvent} with a notification
- * @return true if successfully logged, else false
+ * Logs a {@link NotifEvent} with a message
*/
- public boolean log(@NotifEvent.EventType int eventType, StatusBarNotification sbn, String msg) {
- return log(eventType, sbn, null, msg);
+ public void log(@NotifEvent.EventType int eventType, String msg) {
+ log(eventType, null, null, msg);
}
/**
- * Logs a {@link NotifEvent} with a ranking
- * @return true if successfully logged, else false
+ * Logs a {@link NotifEvent} with a entry
*/
- public boolean log(@NotifEvent.EventType int eventType, Ranking ranking) {
- return log(eventType, null, ranking, "");
+ public void log(@NotifEvent.EventType int eventType, NotificationEntry entry) {
+ log(eventType, entry.getSbn(), entry.getRanking(), "");
}
/**
- * Logs a {@link NotifEvent} with a notification and ranking
- * @return true if successfully logged, else false
+ * Logs a {@link NotifEvent} with a NotificationEntry and message
*/
- public boolean log(@NotifEvent.EventType int eventType, StatusBarNotification sbn,
- Ranking ranking) {
- return log(eventType, sbn, ranking, "");
+ public void log(@NotifEvent.EventType int eventType, NotificationEntry entry, String msg) {
+ log(eventType, entry.getSbn(), entry.getRanking(), msg);
}
/**
- * Logs a {@link NotifEvent} with a notification entry
- * @return true if successfully logged, else false
+ * Logs a {@link NotifEvent} with a notification and message
*/
- public boolean log(@NotifEvent.EventType int eventType, NotificationEntry entry) {
- return log(eventType, entry.getSbn(), entry.getRanking(), "");
+ public void log(@NotifEvent.EventType int eventType, StatusBarNotification sbn, String msg) {
+ log(eventType, sbn, null, msg);
}
/**
- * Logs a {@link NotifEvent} with a notification entry
- * @return true if successfully logged, else false
+ * Logs a {@link NotifEvent} with a ranking and message
*/
- public boolean log(@NotifEvent.EventType int eventType, NotificationEntry entry,
- String msg) {
- return log(eventType, entry.getSbn(), entry.getRanking(), msg);
+ public void log(@NotifEvent.EventType int eventType, Ranking ranking, String msg) {
+ log(eventType, null, ranking, msg);
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleHubModule.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleHubModule.kt
index 4f03003402db..efcef7124035 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleHubModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleHubModule.kt
@@ -31,6 +31,11 @@ abstract class PeopleHubModule {
abstract fun peopleHubDataSource(impl: PeopleHubDataSourceImpl): DataSource<PeopleHubModel>
@Binds
+ abstract fun peopleHubSettingChangeDataSource(
+ impl: PeopleHubSettingChangeDataSourceImpl
+ ): DataSource<Boolean>
+
+ @Binds
abstract fun peopleHubViewModelFactoryDataSource(
impl: PeopleHubViewModelFactoryDataSourceImpl
): DataSource<PeopleHubViewModelFactory>
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleHubNotificationListener.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleHubNotificationListener.kt
index 987b52dbc2e8..784673e64ff8 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleHubNotificationListener.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleHubNotificationListener.kt
@@ -249,7 +249,7 @@ private fun addBadgeToDrawable(
}
}
-private fun extractAvatarFromRow(entry: NotificationEntry): Drawable? =
+fun extractAvatarFromRow(entry: NotificationEntry): Drawable? =
entry.row
?.childrenWithId(R.id.expanded)
?.mapNotNull { it as? ViewGroup }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleHubViewController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleHubViewController.kt
index 5c354089dfe9..e9d6a0fcde83 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleHubViewController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleHubViewController.kt
@@ -16,7 +16,14 @@
package com.android.systemui.statusbar.notification.people
+import android.content.Context
+import android.database.ContentObserver
+import android.net.Uri
+import android.os.Handler
+import android.os.UserHandle
+import android.provider.Settings
import android.view.View
+import com.android.systemui.dagger.qualifiers.MainHandler
import com.android.systemui.plugins.ActivityStarter
import com.android.systemui.statusbar.notification.stack.NotificationSectionsManager
import javax.inject.Inject
@@ -90,29 +97,58 @@ private class PeopleHubDataListenerImpl(
@Singleton
class PeopleHubViewModelFactoryDataSourceImpl @Inject constructor(
private val activityStarter: ActivityStarter,
- private val dataSource: DataSource<@JvmSuppressWildcards PeopleHubModel>
+ private val dataSource: DataSource<@JvmSuppressWildcards PeopleHubModel>,
+ private val settingChangeSource: DataSource<@JvmSuppressWildcards Boolean>
) : DataSource<PeopleHubViewModelFactory> {
- override fun registerListener(listener: DataListener<PeopleHubViewModelFactory>) =
- dataSource.registerListener(PeopleHubModelListenerImpl(activityStarter, listener))
-}
+ override fun registerListener(listener: DataListener<PeopleHubViewModelFactory>): Subscription {
+ var stripEnabled = false
+ var model: PeopleHubModel? = null
+
+ fun updateListener() {
+ // don't invoke listener until we've received our first model
+ model?.let { model ->
+ val factory =
+ if (stripEnabled) PeopleHubViewModelFactoryImpl(model, activityStarter)
+ else EmptyViewModelFactory
+ listener.onDataChanged(factory)
+ }
+ }
-private class PeopleHubModelListenerImpl(
- private val activityStarter: ActivityStarter,
- private val dataListener: DataListener<PeopleHubViewModelFactory>
-) : DataListener<PeopleHubModel> {
+ val settingSub = settingChangeSource.registerListener(object : DataListener<Boolean> {
+ override fun onDataChanged(data: Boolean) {
+ stripEnabled = data
+ updateListener()
+ }
+ })
+ val dataSub = dataSource.registerListener(object : DataListener<PeopleHubModel> {
+ override fun onDataChanged(data: PeopleHubModel) {
+ model = data
+ updateListener()
+ }
+ })
+ return object : Subscription {
+ override fun unsubscribe() {
+ settingSub.unsubscribe()
+ dataSub.unsubscribe()
+ }
+ }
+ }
+}
- override fun onDataChanged(data: PeopleHubModel) =
- dataListener.onDataChanged(PeopleHubViewModelFactoryImpl(data, activityStarter))
+private object EmptyViewModelFactory : PeopleHubViewModelFactory {
+ override fun createWithAssociatedClickView(view: View): PeopleHubViewModel {
+ return PeopleHubViewModel(emptySequence(), false)
+ }
}
private class PeopleHubViewModelFactoryImpl(
- private val data: PeopleHubModel,
+ private val model: PeopleHubModel,
private val activityStarter: ActivityStarter
) : PeopleHubViewModelFactory {
override fun createWithAssociatedClickView(view: View): PeopleHubViewModel {
- val personViewModels = data.people.asSequence().map { personModel ->
+ val personViewModels = model.people.asSequence().map { personModel ->
val onClick = {
activityStarter.startPendingIntentDismissingKeyguard(
personModel.clickIntent,
@@ -122,7 +158,42 @@ private class PeopleHubViewModelFactoryImpl(
}
PersonViewModel(personModel.name, personModel.avatar, onClick)
}
- return PeopleHubViewModel(personViewModels, data.people.isNotEmpty())
+ return PeopleHubViewModel(personViewModels, model.people.isNotEmpty())
+ }
+}
+
+@Singleton
+class PeopleHubSettingChangeDataSourceImpl @Inject constructor(
+ @MainHandler private val handler: Handler,
+ context: Context
+) : DataSource<Boolean> {
+
+ private val settingUri = Settings.Secure.getUriFor(Settings.Secure.PEOPLE_STRIP)
+ private val contentResolver = context.contentResolver
+
+ override fun registerListener(listener: DataListener<Boolean>): Subscription {
+ // Immediately report current value of setting
+ updateListener(listener)
+ val observer = object : ContentObserver(handler) {
+ override fun onChange(selfChange: Boolean, uri: Uri?, userId: Int) {
+ super.onChange(selfChange, uri, userId)
+ updateListener(listener)
+ }
+ }
+ contentResolver.registerContentObserver(settingUri, false, observer, UserHandle.USER_ALL)
+ return object : Subscription {
+ override fun unsubscribe() = contentResolver.unregisterContentObserver(observer)
+ }
+ }
+
+ private fun updateListener(listener: DataListener<Boolean>) {
+ val setting = Settings.Secure.getIntForUser(
+ contentResolver,
+ Settings.Secure.PEOPLE_STRIP,
+ 0,
+ UserHandle.USER_CURRENT
+ )
+ listener.onDataChanged(setting != 0)
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ChannelEditorDialogController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ChannelEditorDialogController.kt
index 782aad17345e..315ea0a49bb7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ChannelEditorDialogController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ChannelEditorDialogController.kt
@@ -34,6 +34,7 @@ import android.view.View
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.view.Window
+import android.view.WindowInsets.Type
import android.view.WindowManager
import android.widget.TextView
import com.android.internal.annotations.VisibleForTesting
@@ -287,6 +288,7 @@ class ChannelEditorDialogController @Inject constructor(
setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
addFlags(wmFlags)
setType(WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL)
+ setFitWindowInsetsTypes(getFitWindowInsetsTypes() and Type.statusBars().inv())
setWindowAnimations(com.android.internal.R.style.Animation_InputMethod)
attributes = attributes.apply {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
index 9ac5b44f8639..65423e970cf1 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
@@ -813,15 +813,14 @@ public class ExpandableNotificationRow extends ActivatableNotificationView
* @param parent the new parent notification
*/
public void setIsChildInGroup(boolean isChildInGroup, ExpandableNotificationRow parent) {
- boolean childInGroup = StatusBar.ENABLE_CHILD_NOTIFICATIONS && isChildInGroup;
if (mExpandAnimationRunning && !isChildInGroup && mNotificationParent != null) {
mNotificationParent.setChildIsExpanding(false);
mNotificationParent.setExtraWidthForClipping(0.0f);
mNotificationParent.setMinimumHeightForClipping(0);
}
- mNotificationParent = childInGroup ? parent : null;
- mPrivateLayout.setIsChildInGroup(childInGroup);
- mNotificationInflater.setIsChildInGroup(childInGroup);
+ mNotificationParent = isChildInGroup ? parent : null;
+ mPrivateLayout.setIsChildInGroup(isChildInGroup);
+ mNotificationInflater.setIsChildInGroup(isChildInGroup);
resetBackgroundAlpha();
updateBackgroundForGroupState();
updateClickAndFocus();
@@ -2354,8 +2353,8 @@ public class ExpandableNotificationRow extends ActivatableNotificationView
}
private void onChildrenCountChanged() {
- mIsSummaryWithChildren = StatusBar.ENABLE_CHILD_NOTIFICATIONS
- && mChildrenContainer != null && mChildrenContainer.getNotificationChildCount() > 0;
+ mIsSummaryWithChildren = mChildrenContainer != null
+ && mChildrenContainer.getNotificationChildCount() > 0;
if (mIsSummaryWithChildren && mChildrenContainer.getHeaderView() == null) {
mChildrenContainer.recreateNotificationHeader(mExpandClickListener
);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationSectionsManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationSectionsManager.java
index 8e9a051e7d43..2761689ec409 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationSectionsManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationSectionsManager.java
@@ -249,10 +249,8 @@ public class NotificationSectionsManager implements StackScrollAlgorithm.Section
}
}
- if (adjustPeopleHubVisibilityAndPosition(lastPersonIndex)) {
- // make room for peopleHub
- firstGentleNotifIndex++;
- }
+ // make room for peopleHub
+ firstGentleNotifIndex += adjustPeopleHubVisibilityAndPosition(lastPersonIndex);
adjustGentleHeaderVisibilityAndPosition(firstGentleNotifIndex);
@@ -296,7 +294,7 @@ public class NotificationSectionsManager implements StackScrollAlgorithm.Section
}
}
- private boolean adjustPeopleHubVisibilityAndPosition(int lastPersonIndex) {
+ private int adjustPeopleHubVisibilityAndPosition(int lastPersonIndex) {
final boolean showPeopleHeader = mPeopleHubVisible
&& mNumberOfSections > 2
&& mStatusBarStateController.getState() != StatusBarState.KEYGUARD;
@@ -307,6 +305,7 @@ public class NotificationSectionsManager implements StackScrollAlgorithm.Section
if (!showPeopleHeader) {
if (currentlyVisible) {
mParent.removeView(mPeopleHubView);
+ return -1;
}
} else {
mPeopleHubView.unDismiss();
@@ -317,7 +316,7 @@ public class NotificationSectionsManager implements StackScrollAlgorithm.Section
mPeopleHubView.setTransientContainer(null);
}
mParent.addView(mPeopleHubView, targetIndex);
- return true;
+ return 1;
} else if (currentHubIndex != targetIndex) {
if (currentHubIndex < targetIndex) {
targetIndex--;
@@ -325,7 +324,7 @@ public class NotificationSectionsManager implements StackScrollAlgorithm.Section
mParent.changeViewPosition(mPeopleHubView, targetIndex);
}
}
- return false;
+ return 0;
}
/**
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java
index 43af3aaa5b84..71342c597bfa 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java
@@ -5519,7 +5519,7 @@ public class NotificationStackScrollLayout extends ViewGroup implements ScrollAd
if (viewsToRemove.isEmpty()) {
if (closeShade) {
- mStatusBar.animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
+ mShadeController.animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
}
return;
}
@@ -5581,7 +5581,7 @@ public class NotificationStackScrollLayout extends ViewGroup implements ScrollAd
setDismissAllInProgress(false);
onAnimationComplete.run();
});
- mStatusBar.animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
+ mShadeController.animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
} else {
setDismissAllInProgress(false);
onAnimationComplete.run();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/BiometricUnlockController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/BiometricUnlockController.java
index 865d7e7a6560..250f7300ba56 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/BiometricUnlockController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/BiometricUnlockController.java
@@ -41,6 +41,7 @@ import com.android.systemui.dagger.qualifiers.MainResources;
import com.android.systemui.keyguard.KeyguardViewMediator;
import com.android.systemui.keyguard.ScreenLifecycle;
import com.android.systemui.keyguard.WakefulnessLifecycle;
+import com.android.systemui.statusbar.CommandQueue;
import com.android.systemui.statusbar.NotificationMediaManager;
import com.android.systemui.statusbar.policy.KeyguardStateController;
@@ -136,6 +137,7 @@ public class BiometricUnlockController extends KeyguardUpdateMonitorCallback imp
private final Handler mHandler;
private final KeyguardBypassController mKeyguardBypassController;
private PowerManager.WakeLock mWakeLock;
+ private final ShadeController mShadeController;
private final KeyguardUpdateMonitor mUpdateMonitor;
private final DozeParameters mDozeParameters;
private final KeyguardStateController mKeyguardStateController;
@@ -159,20 +161,23 @@ public class BiometricUnlockController extends KeyguardUpdateMonitorCallback imp
@Inject
public BiometricUnlockController(Context context, DozeScrimController dozeScrimController,
KeyguardViewMediator keyguardViewMediator, ScrimController scrimController,
- StatusBar statusBar, KeyguardStateController keyguardStateController, Handler handler,
+ StatusBar statusBar, ShadeController shadeController,
+ StatusBarWindowController statusBarWindowController,
+ KeyguardStateController keyguardStateController, Handler handler,
KeyguardUpdateMonitor keyguardUpdateMonitor,
@MainResources Resources resources,
KeyguardBypassController keyguardBypassController, DozeParameters dozeParameters,
MetricsLogger metricsLogger, DumpController dumpController) {
mContext = context;
mPowerManager = context.getSystemService(PowerManager.class);
+ mShadeController = shadeController;
mUpdateMonitor = keyguardUpdateMonitor;
mDozeParameters = dozeParameters;
mUpdateMonitor.registerCallback(this);
mMediaManager = Dependency.get(NotificationMediaManager.class);
Dependency.get(WakefulnessLifecycle.class).addObserver(mWakefulnessObserver);
Dependency.get(ScreenLifecycle.class).addObserver(mScreenObserver);
- mStatusBarWindowController = Dependency.get(StatusBarWindowController.class);
+ mStatusBarWindowController = statusBarWindowController;
mDozeScrimController = dozeScrimController;
mKeyguardViewMediator = keyguardViewMediator;
mScrimController = scrimController;
@@ -358,8 +363,8 @@ public class BiometricUnlockController extends KeyguardUpdateMonitorCallback imp
if (mMode == MODE_SHOW_BOUNCER) {
mStatusBarKeyguardViewManager.showBouncer(false);
}
- mStatusBarKeyguardViewManager.animateCollapsePanels(
- BIOMETRIC_COLLAPSE_SPEEDUP_FACTOR);
+ mShadeController.animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE, true /* force */,
+ false /* delayed */, BIOMETRIC_COLLAPSE_SPEEDUP_FACTOR);
mPendingShowBouncer = false;
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/EdgeBackGestureHandler.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/EdgeBackGestureHandler.java
index 8ee964f3f771..f25f9106af7e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/EdgeBackGestureHandler.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/EdgeBackGestureHandler.java
@@ -300,6 +300,7 @@ public class EdgeBackGestureHandler implements DisplayListener,
layoutParams.setTitle(TAG + mContext.getDisplayId());
layoutParams.accessibilityTitle = mContext.getString(R.string.nav_bar_edge_panel);
layoutParams.windowAnimations = 0;
+ layoutParams.setFitWindowInsetsTypes(0 /* types */);
return layoutParams;
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/FloatingRotationButton.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/FloatingRotationButton.java
index a7849847387d..783e7adf2a8b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/FloatingRotationButton.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/FloatingRotationButton.java
@@ -84,6 +84,7 @@ public class FloatingRotationButton implements RotationButton {
PixelFormat.TRANSLUCENT);
lp.privateFlags |= WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS;
lp.setTitle("FloatingRotationButton");
+ lp.setFitWindowInsetsTypes(0 /*types */);
switch (mWindowManager.getDefaultDisplay().getRotation()) {
case Surface.ROTATION_0:
lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardAffordanceHelper.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardAffordanceHelper.java
index 66b1dd8db123..858023dc6c62 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardAffordanceHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardAffordanceHelper.java
@@ -101,7 +101,8 @@ public class KeyguardAffordanceHelper {
R.dimen.keyguard_affordance_touch_target_size);
mHintGrowAmount =
mContext.getResources().getDimensionPixelSize(R.dimen.hint_grow_amount_sideways);
- mFlingAnimationUtils = new FlingAnimationUtils(mContext, 0.4f);
+ mFlingAnimationUtils = new FlingAnimationUtils(mContext.getResources().getDisplayMetrics(),
+ 0.4f);
}
private void initIcons() {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockscreenGestureLogger.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockscreenGestureLogger.java
index 12819535cfb6..8c3420a522ec 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockscreenGestureLogger.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockscreenGestureLogger.java
@@ -35,8 +35,6 @@ import javax.inject.Singleton;
@Singleton
public class LockscreenGestureLogger {
private ArrayMap<Integer, Integer> mLegacyMap;
- private LogMaker mLogMaker = new LogMaker(MetricsEvent.VIEW_UNKNOWN)
- .setType(MetricsEvent.TYPE_ACTION);
private final MetricsLogger mMetricsLogger = Dependency.get(MetricsLogger.class);
@Inject
@@ -48,7 +46,7 @@ public class LockscreenGestureLogger {
}
public void write(int gesture, int length, int velocity) {
- mMetricsLogger.write(mLogMaker.setCategory(gesture)
+ mMetricsLogger.write(new LogMaker(gesture)
.setType(MetricsEvent.TYPE_ACTION)
.addTaggedData(MetricsEvent.FIELD_GESTURE_LENGTH, length)
.addTaggedData(MetricsEvent.FIELD_GESTURE_VELOCITY, velocity));
@@ -64,7 +62,7 @@ public class LockscreenGestureLogger {
*/
public void writeAtFractionalPosition(
int category, int xPercent, int yPercent, int rotation) {
- mMetricsLogger.write(mLogMaker.setCategory(category)
+ mMetricsLogger.write(new LogMaker(category)
.setType(MetricsEvent.TYPE_ACTION)
.addTaggedData(MetricsEvent.FIELD_GESTURE_X_PERCENT, xPercent)
.addTaggedData(MetricsEvent.FIELD_GESTURE_Y_PERCENT, yPercent)
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockscreenWallpaper.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockscreenWallpaper.java
index f3e9b6b3d155..183adeb037d6 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockscreenWallpaper.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockscreenWallpaper.java
@@ -37,12 +37,19 @@ import android.os.RemoteException;
import android.os.UserHandle;
import android.util.Log;
+import androidx.annotation.NonNull;
+
+import com.android.internal.util.IndentingPrintWriter;
import com.android.keyguard.KeyguardUpdateMonitor;
-import com.android.systemui.Dependency;
+import com.android.systemui.DumpController;
+import com.android.systemui.Dumpable;
+import com.android.systemui.dagger.qualifiers.MainHandler;
import com.android.systemui.statusbar.NotificationMediaManager;
import libcore.io.IoUtils;
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
import java.util.Objects;
import javax.inject.Inject;
@@ -52,16 +59,15 @@ import javax.inject.Singleton;
* Manages the lockscreen wallpaper.
*/
@Singleton
-public class LockscreenWallpaper extends IWallpaperManagerCallback.Stub implements Runnable {
+public class LockscreenWallpaper extends IWallpaperManagerCallback.Stub implements Runnable,
+ Dumpable {
private static final String TAG = "LockscreenWallpaper";
- private final NotificationMediaManager mMediaManager =
- Dependency.get(NotificationMediaManager.class);
-
+ private final NotificationMediaManager mMediaManager;
private final WallpaperManager mWallpaperManager;
- private Handler mH;
private final KeyguardUpdateMonitor mUpdateMonitor;
+ private final Handler mH;
private boolean mCached;
private Bitmap mCache;
@@ -74,10 +80,16 @@ public class LockscreenWallpaper extends IWallpaperManagerCallback.Stub implemen
@Inject
public LockscreenWallpaper(WallpaperManager wallpaperManager,
@Nullable IWallpaperManager iWallpaperManager,
- KeyguardUpdateMonitor keyguardUpdateMonitor) {
+ KeyguardUpdateMonitor keyguardUpdateMonitor,
+ DumpController dumpController,
+ NotificationMediaManager mediaManager,
+ @MainHandler Handler mainHandler) {
+ dumpController.registerDumpable(getClass().getSimpleName(), this);
mWallpaperManager = wallpaperManager;
mCurrentUserId = ActivityManager.getCurrentUser();
mUpdateMonitor = keyguardUpdateMonitor;
+ mMediaManager = mediaManager;
+ mH = mainHandler;
if (iWallpaperManager != null) {
// Service is disabled on some devices like Automotive
@@ -89,14 +101,6 @@ public class LockscreenWallpaper extends IWallpaperManagerCallback.Stub implemen
}
}
- void setHandler(Handler handler) {
- if (mH != null) {
- Log.wtfStack(TAG, "Handler has already been set. Trying to double initialize?");
- return;
- }
- mH = handler;
- }
-
public Bitmap getBitmap() {
if (mCached) {
return mCache;
@@ -227,6 +231,16 @@ public class LockscreenWallpaper extends IWallpaperManagerCallback.Stub implemen
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
+ @Override
+ public void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter pw, @NonNull String[] args) {
+ pw.println(getClass().getSimpleName() + ":");
+ IndentingPrintWriter iPw = new IndentingPrintWriter(pw, " ").increaseIndent();
+ iPw.println("mCached=" + mCached);
+ iPw.println("mCache=" + mCache);
+ iPw.println("mCurrentUserId=" + mCurrentUserId);
+ iPw.println("mSelectedUser=" + mSelectedUser);
+ }
+
private static class LoaderResult {
public final boolean success;
public final Bitmap bitmap;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarFragment.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarFragment.java
index 0703d8c397c7..ebe211754b2b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarFragment.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarFragment.java
@@ -164,6 +164,7 @@ public class NavigationBarFragment extends LifecycleFragment implements Callback
private int mDisabledFlags1;
private int mDisabledFlags2;
private final Lazy<StatusBar> mStatusBarLazy;
+ private final ShadeController mShadeController;
private Recents mRecents;
private StatusBar mStatusBar;
private final Divider mDivider;
@@ -216,7 +217,7 @@ public class NavigationBarFragment extends LifecycleFragment implements Callback
mNavigationBarView.getRotationButtonController().setRotateSuggestionButtonState(false);
// Hide the notifications panel when quick step starts
- mStatusBarLazy.get().collapsePanel(true /* animate */);
+ mShadeController.collapsePanel(true /* animate */);
}
@Override
@@ -272,6 +273,7 @@ public class NavigationBarFragment extends LifecycleFragment implements Callback
BroadcastDispatcher broadcastDispatcher,
CommandQueue commandQueue, Divider divider,
Optional<Recents> recentsOptional, Lazy<StatusBar> statusBarLazy,
+ ShadeController shadeController,
@MainHandler Handler mainHandler) {
mAccessibilityManagerWrapper = accessibilityManagerWrapper;
mDeviceProvisionedController = deviceProvisionedController;
@@ -280,6 +282,7 @@ public class NavigationBarFragment extends LifecycleFragment implements Callback
mAssistManager = assistManager;
mSysUiFlagsContainer = sysUiFlagsContainer;
mStatusBarLazy = statusBarLazy;
+ mShadeController = shadeController;
mAssistantAvailable = mAssistManager.getAssistInfoForUser(UserHandle.USER_CURRENT) != null;
mOverviewProxyService = overviewProxyService;
mNavigationModeController = navigationModeController;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
index ed2fb0fdcb1a..199d52f76c93 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
@@ -609,7 +609,7 @@ public class NotificationPanelView extends PanelView implements
@Override
protected void loadDimens() {
super.loadDimens();
- mFlingAnimationUtils = new FlingAnimationUtils(getContext(), 0.4f);
+ mFlingAnimationUtils = new FlingAnimationUtils(getResources().getDisplayMetrics(), 0.4f);
mStatusBarMinHeight = getResources().getDimensionPixelSize(
com.android.internal.R.dimen.status_bar_height);
mQsPeekHeight = getResources().getDimensionPixelSize(R.dimen.qs_peek_height);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
index e8e5e1f60c51..78a5eb237297 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
@@ -26,6 +26,7 @@ import android.content.res.Resources;
import android.os.SystemClock;
import android.os.VibrationEffect;
import android.util.AttributeSet;
+import android.util.DisplayMetrics;
import android.util.Log;
import android.view.InputDevice;
import android.view.MotionEvent;
@@ -208,11 +209,12 @@ public abstract class PanelView extends FrameLayout {
super(context, attrs);
mKeyguardStateController = keyguardStateController;
mStatusBarStateController = statusBarStateController;
- mFlingAnimationUtils = new FlingAnimationUtils(context, 0.6f /* maxLengthSeconds */,
- 0.6f /* speedUpFactor */);
- mFlingAnimationUtilsClosing = new FlingAnimationUtils(context, 0.5f /* maxLengthSeconds */,
- 0.6f /* speedUpFactor */);
- mFlingAnimationUtilsDismissing = new FlingAnimationUtils(context,
+ DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
+ mFlingAnimationUtils = new FlingAnimationUtils(displayMetrics,
+ 0.6f /* maxLengthSeconds */, 0.6f /* speedUpFactor */);
+ mFlingAnimationUtilsClosing = new FlingAnimationUtils(displayMetrics,
+ 0.5f /* maxLengthSeconds */, 0.6f /* speedUpFactor */);
+ mFlingAnimationUtilsDismissing = new FlingAnimationUtils(displayMetrics,
0.5f /* maxLengthSeconds */, 0.2f /* speedUpFactor */, 0.6f /* x2 */,
0.84f /* y2 */);
mBounceInterpolator = new BounceInterpolator();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java
index 8d43c6666773..3ee5d3138fb2 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java
@@ -385,8 +385,11 @@ public class PhoneStatusBarPolicy
mContext.getString(R.string.accessibility_quick_settings_bluetooth_on);
boolean bluetoothVisible = false;
if (mBluetooth != null) {
- if (mBluetooth.isBluetoothConnected()) {
- contentDescription = mContext.getString(R.string.accessibility_bluetooth_connected);
+ if (mBluetooth.isBluetoothConnected()
+ && (mBluetooth.isBluetoothAudioActive()
+ || !mBluetooth.isBluetoothAudioProfileOnly())) {
+ contentDescription = mContext.getString(
+ R.string.accessibility_bluetooth_connected);
bluetoothVisible = mBluetooth.isBluetoothEnabled();
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
index 1454e256b75b..4c5bbce05261 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
@@ -360,7 +360,8 @@ public class ScrimController implements ViewTreeObserver.OnPreDrawListener, OnCo
return false;
}
- if (mState == ScrimState.AOD && mDozeParameters.getAlwaysOn()) {
+ if (mState == ScrimState.AOD
+ && (mDozeParameters.getAlwaysOn() || mDockManager.isDocked())) {
return true;
}
@@ -560,7 +561,7 @@ public class ScrimController implements ViewTreeObserver.OnPreDrawListener, OnCo
}
protected void scheduleUpdate() {
- if (mUpdatePending) return;
+ if (mUpdatePending || mScrimBehind == null) return;
// Make sure that a frame gets scheduled.
mScrimBehind.invalidate();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ShadeController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ShadeController.java
index deea3f17aad0..2fa6795e9df0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ShadeController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ShadeController.java
@@ -32,12 +32,24 @@ public interface ShadeController {
*/
void instantExpandNotificationsPanel();
+ /** See {@link #animateCollapsePanels(int, boolean)}. */
+ void animateCollapsePanels();
+
+ /** See {@link #animateCollapsePanels(int, boolean)}. */
+ void animateCollapsePanels(int flags);
+
/**
* Collapse the shade animated, showing the bouncer when on {@link StatusBarState#KEYGUARD} or
* dismissing {@link StatusBar} when on {@link StatusBarState#SHADE}.
*/
void animateCollapsePanels(int flags, boolean force);
+ /** See {@link #animateCollapsePanels(int, boolean)}. */
+ void animateCollapsePanels(int flags, boolean force, boolean delayed);
+
+ /** See {@link #animateCollapsePanels(int, boolean)}. */
+ void animateCollapsePanels(int flags, boolean force, boolean delayed, float speedUpFactor);
+
/**
* If the notifications panel is not fully expanded, collapse it animated.
*
@@ -61,11 +73,9 @@ public interface ShadeController {
void addPostCollapseAction(Runnable action);
/**
- * Notify the shade controller that the current user changed
- *
- * @param newUserId userId of the new user
+ * Run all of the runnables added by {@link #addPostCollapseAction}.
*/
- void setLockscreenUser(int newUserId);
+ void runPostCollapseRunnables();
/**
* If secure with redaction: Show bouncer, go to unlocked shade.
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ShadeControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ShadeControllerImpl.java
new file mode 100644
index 000000000000..57e70141bfcf
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ShadeControllerImpl.java
@@ -0,0 +1,236 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.statusbar.phone;
+
+import android.util.Log;
+import android.view.View;
+import android.view.ViewTreeObserver;
+import android.view.WindowManager;
+
+import com.android.systemui.assist.AssistManager;
+import com.android.systemui.bubbles.BubbleController;
+import com.android.systemui.plugins.statusbar.StatusBarStateController;
+import com.android.systemui.statusbar.CommandQueue;
+import com.android.systemui.statusbar.NotificationPresenter;
+import com.android.systemui.statusbar.StatusBarState;
+
+import java.util.ArrayList;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import dagger.Lazy;
+
+/** An implementation of {@link com.android.systemui.statusbar.phone.ShadeController}. */
+@Singleton
+public class ShadeControllerImpl implements ShadeController {
+
+ private static final String TAG = "ShadeControllerImpl";
+ private static final boolean SPEW = false;
+
+ private final CommandQueue mCommandQueue;
+ private final StatusBarStateController mStatusBarStateController;
+ protected final StatusBarWindowController mStatusBarWindowController;
+ private final StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
+ private final int mDisplayId;
+ protected final Lazy<StatusBar> mStatusBarLazy;
+ private final Lazy<AssistManager> mAssistManagerLazy;
+ private final Lazy<BubbleController> mBubbleControllerLazy;
+
+ private final ArrayList<Runnable> mPostCollapseRunnables = new ArrayList<>();
+
+ @Inject
+ public ShadeControllerImpl(
+ CommandQueue commandQueue,
+ StatusBarStateController statusBarStateController,
+ StatusBarWindowController statusBarWindowController,
+ StatusBarKeyguardViewManager statusBarKeyguardViewManager,
+ WindowManager windowManager,
+ Lazy<StatusBar> statusBarLazy,
+ Lazy<AssistManager> assistManagerLazy,
+ Lazy<BubbleController> bubbleControllerLazy
+ ) {
+ mCommandQueue = commandQueue;
+ mStatusBarStateController = statusBarStateController;
+ mStatusBarWindowController = statusBarWindowController;
+ mStatusBarKeyguardViewManager = statusBarKeyguardViewManager;
+ mDisplayId = windowManager.getDefaultDisplay().getDisplayId();
+ // TODO: Remove circular reference to StatusBar when possible.
+ mStatusBarLazy = statusBarLazy;
+ mAssistManagerLazy = assistManagerLazy;
+ mBubbleControllerLazy = bubbleControllerLazy;
+ }
+
+ @Override
+ public void instantExpandNotificationsPanel() {
+ // Make our window larger and the panel expanded.
+ getStatusBar().makeExpandedVisible(true /* force */);
+ getNotificationPanelView().expand(false /* animate */);
+ mCommandQueue.recomputeDisableFlags(mDisplayId, false /* animate */);
+ }
+
+ @Override
+ public void animateCollapsePanels() {
+ animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
+ }
+
+ @Override
+ public void animateCollapsePanels(int flags) {
+ animateCollapsePanels(flags, false /* force */, false /* delayed */,
+ 1.0f /* speedUpFactor */);
+ }
+
+ @Override
+ public void animateCollapsePanels(int flags, boolean force) {
+ animateCollapsePanels(flags, force, false /* delayed */, 1.0f /* speedUpFactor */);
+ }
+
+ @Override
+ public void animateCollapsePanels(int flags, boolean force, boolean delayed) {
+ animateCollapsePanels(flags, force, delayed, 1.0f /* speedUpFactor */);
+ }
+
+ @Override
+ public void animateCollapsePanels(int flags, boolean force, boolean delayed,
+ float speedUpFactor) {
+ if (!force && mStatusBarStateController.getState() != StatusBarState.SHADE) {
+ runPostCollapseRunnables();
+ return;
+ }
+ if (SPEW) {
+ Log.d(TAG, "animateCollapse():"
+ + " mExpandedVisible=" + getStatusBar().isExpandedVisible()
+ + " flags=" + flags);
+ }
+
+ if ((flags & CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL) == 0) {
+ getStatusBar().postHideRecentApps();
+ }
+
+ // TODO(b/62444020): remove when this bug is fixed
+ Log.v(TAG, "mStatusBarWindow: " + getStatusBarWindowView() + " canPanelBeCollapsed(): "
+ + getNotificationPanelView().canPanelBeCollapsed());
+ if (getStatusBarWindowView() != null && getNotificationPanelView().canPanelBeCollapsed()) {
+ // release focus immediately to kick off focus change transition
+ mStatusBarWindowController.setStatusBarFocusable(false);
+
+ getStatusBar().getStatusBarWindowViewController().cancelExpandHelper();
+ getStatusBarView().collapsePanel(true /* animate */, delayed, speedUpFactor);
+ } else {
+ mBubbleControllerLazy.get().collapseStack();
+ }
+ }
+
+
+ @Override
+ public boolean closeShadeIfOpen() {
+ if (!getNotificationPanelView().isFullyCollapsed()) {
+ mCommandQueue.animateCollapsePanels(
+ CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL, true /* force */);
+ getStatusBar().visibilityChanged(false);
+ mAssistManagerLazy.get().hideAssist();
+ }
+ return false;
+ }
+
+ @Override
+ public void postOnShadeExpanded(Runnable executable) {
+ getNotificationPanelView().getViewTreeObserver().addOnGlobalLayoutListener(
+ new ViewTreeObserver.OnGlobalLayoutListener() {
+ @Override
+ public void onGlobalLayout() {
+ if (getStatusBar().getStatusBarWindow().getHeight()
+ != getStatusBar().getStatusBarHeight()) {
+ getNotificationPanelView().getViewTreeObserver()
+ .removeOnGlobalLayoutListener(this);
+ getNotificationPanelView().post(executable);
+ }
+ }
+ });
+ }
+
+ @Override
+ public void addPostCollapseAction(Runnable action) {
+ mPostCollapseRunnables.add(action);
+ }
+
+ @Override
+ public void runPostCollapseRunnables() {
+ ArrayList<Runnable> clonedList = new ArrayList<>(mPostCollapseRunnables);
+ mPostCollapseRunnables.clear();
+ int size = clonedList.size();
+ for (int i = 0; i < size; i++) {
+ clonedList.get(i).run();
+ }
+ mStatusBarKeyguardViewManager.readyForKeyguardDone();
+ }
+
+ @Override
+ public void goToLockedShade(View startingChild) {
+ // TODO: Move this code out of StatusBar into ShadeController.
+ getStatusBar().goToLockedShade(startingChild);
+ }
+
+ @Override
+ public boolean collapsePanel() {
+ if (!getNotificationPanelView().isFullyCollapsed()) {
+ // close the shade if it was open
+ animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL,
+ true /* force */, true /* delayed */);
+ getStatusBar().visibilityChanged(false);
+
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ @Override
+ public void collapsePanel(boolean animate) {
+ if (animate) {
+ boolean willCollapse = collapsePanel();
+ if (!willCollapse) {
+ runPostCollapseRunnables();
+ }
+ } else if (!getPresenter().isPresenterFullyCollapsed()) {
+ getStatusBar().instantCollapseNotificationPanel();
+ getStatusBar().visibilityChanged(false);
+ } else {
+ runPostCollapseRunnables();
+ }
+ }
+
+ private StatusBar getStatusBar() {
+ return mStatusBarLazy.get();
+ }
+
+ private NotificationPresenter getPresenter() {
+ return getStatusBar().getPresenter();
+ }
+
+ protected StatusBarWindowView getStatusBarWindowView() {
+ return getStatusBar().getStatusBarWindow();
+ }
+
+ protected PhoneStatusBarView getStatusBarView() {
+ return (PhoneStatusBarView) getStatusBar().getStatusBarView();
+ }
+
+ private NotificationPanelView getNotificationPanelView() {
+ return getStatusBar().getPanel();
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
index 709143d7275a..312f9c181121 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
@@ -107,7 +107,6 @@ import android.view.RemoteAnimationAdapter;
import android.view.ThreadedRenderer;
import android.view.View;
import android.view.ViewGroup;
-import android.view.ViewTreeObserver;
import android.view.WindowInsetsController.Appearance;
import android.view.WindowManager;
import android.view.WindowManagerGlobal;
@@ -125,7 +124,6 @@ import com.android.keyguard.KeyguardUpdateMonitor;
import com.android.keyguard.KeyguardUpdateMonitorCallback;
import com.android.keyguard.ViewMediatorCallback;
import com.android.systemui.ActivityIntentHelper;
-import com.android.systemui.ActivityStarterDelegate;
import com.android.systemui.AutoReinflateContainer;
import com.android.systemui.DejankUtils;
import com.android.systemui.DemoMode;
@@ -232,7 +230,6 @@ import com.android.systemui.volume.VolumeComponent;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.io.StringWriter;
-import java.util.ArrayList;
import java.util.Map;
import java.util.Optional;
@@ -245,13 +242,9 @@ public class StatusBar extends SystemUI implements DemoMode,
ActivityStarter, KeyguardStateController.Callback,
OnHeadsUpChangedListener, CommandQueue.Callbacks,
ColorExtractor.OnColorsChangedListener, ConfigurationListener,
- StatusBarStateController.StateListener, ShadeController,
- ActivityLaunchAnimator.Callback {
+ StatusBarStateController.StateListener, ActivityLaunchAnimator.Callback {
public static final boolean MULTIUSER_DEBUG = false;
- public static final boolean ENABLE_CHILD_NOTIFICATIONS
- = SystemProperties.getBoolean("debug.child_notifs", true);
-
protected static final int MSG_HIDE_RECENT_APPS = 1020;
protected static final int MSG_PRELOAD_RECENT_APPS = 1022;
protected static final int MSG_CANCEL_PRELOAD_RECENT_APPS = 1023;
@@ -387,6 +380,7 @@ public class StatusBar extends SystemUI implements DemoMode,
private final Optional<Divider> mDividerOptional;
private final StatusBarNotificationActivityStarter.Builder
mStatusBarNotificationActivityStarterBuilder;
+ private final ShadeController mShadeController;
private final SuperStatusBarViewFactory mSuperStatusBarViewFactory;
private final LightsOutNotifController mLightsOutNotifController;
private final DismissCallbackRegistry mDismissCallbackRegistry;
@@ -409,7 +403,6 @@ public class StatusBar extends SystemUI implements DemoMode,
private boolean mExpandedVisible;
private final int[] mAbsPos = new int[2];
- private final ArrayList<Runnable> mPostCollapseRunnables = new ArrayList<>();
private final NotificationGutsManager mGutsManager;
private final NotificationLogger mNotificationLogger;
@@ -683,6 +676,7 @@ public class StatusBar extends SystemUI implements DemoMode,
LightsOutNotifController lightsOutNotifController,
StatusBarNotificationActivityStarter.Builder
statusBarNotificationActivityStarterBuilder,
+ ShadeController shadeController,
SuperStatusBarViewFactory superStatusBarViewFactory,
StatusBarKeyguardViewManager statusBarKeyguardViewManager,
ViewMediatorCallback viewMediatorCallback,
@@ -754,6 +748,7 @@ public class StatusBar extends SystemUI implements DemoMode,
mRemoteInputUriController = remoteInputUriController;
mDividerOptional = dividerOptional;
mStatusBarNotificationActivityStarterBuilder = statusBarNotificationActivityStarterBuilder;
+ mShadeController = shadeController;
mSuperStatusBarViewFactory = superStatusBarViewFactory;
mLightsOutNotifController = lightsOutNotifController;
mStatusBarKeyguardViewManager = statusBarKeyguardViewManager;
@@ -814,6 +809,8 @@ public class StatusBar extends SystemUI implements DemoMode,
ServiceManager.getService(Context.STATUS_BAR_SERVICE));
mKeyguardManager = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
+ mWallpaperSupported =
+ mContext.getSystemService(WallpaperManager.class).isWallpaperSupported();
// Connect in to the status bar manager service
mCommandQueue.addCallback(this);
@@ -827,9 +824,6 @@ public class StatusBar extends SystemUI implements DemoMode,
createAndAddWindows(result);
- mWallpaperSupported =
- mContext.getSystemService(WallpaperManager.class).isWallpaperSupported();
-
if (mWallpaperSupported) {
// Make sure we always have the most current wallpaper info.
IntentFilter wallpaperChangedFilter = new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED);
@@ -903,8 +897,6 @@ public class StatusBar extends SystemUI implements DemoMode,
mStatusBarWindowViewController,
mNotificationPanel, mAmbientIndicationContainer);
- Dependency.get(ActivityStarterDelegate.class).setActivityStarterImpl(this);
-
mConfigurationController.addCallback(this);
// set the initial view visibility
@@ -1062,7 +1054,6 @@ public class StatusBar extends SystemUI implements DemoMode,
if (ENABLE_LOCKSCREEN_WALLPAPER && mWallpaperSupported) {
mLockscreenWallpaper = mLockscreenWallpaperLazy.get();
- mLockscreenWallpaper.setHandler(mHandler);
}
mKeyguardIndicationController =
@@ -1240,7 +1231,7 @@ public class StatusBar extends SystemUI implements DemoMode,
mScrimController, mActivityLaunchAnimator, mDynamicPrivacyController,
mNotificationAlertingManager, rowBinder, mKeyguardStateController,
mKeyguardIndicationController,
- this /* statusBar */, mCommandQueue);
+ this /* statusBar */, mShadeController, mCommandQueue);
mNotificationListController =
new NotificationListController(
@@ -1264,7 +1255,7 @@ public class StatusBar extends SystemUI implements DemoMode,
mRemoteInputUriController.attach(mEntryManager);
rowBinder.setNotificationClicker(new NotificationClicker(
- this, mBubbleController, mNotificationActivityStarter));
+ Optional.of(this), mBubbleController, mNotificationActivityStarter));
mGroupAlertTransferHelper.bind(mEntryManager, mGroupManager);
mNotificationListController.bind();
@@ -1272,6 +1263,7 @@ public class StatusBar extends SystemUI implements DemoMode,
if (mFeatureFlags.isNewNotifPipelineEnabled()) {
mNewNotifPipeline.get().initialize(mNotificationListener);
}
+ mEntryManager.attach(mNotificationListener);
}
/**
@@ -1318,7 +1310,7 @@ public class StatusBar extends SystemUI implements DemoMode,
mRemoteInputManager.checkRemoteInputOutside(event);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (mExpandedVisible) {
- animateCollapsePanels();
+ mShadeController.animateCollapsePanels();
}
}
return mStatusBarWindow.onTouchEvent(event);
@@ -1419,6 +1411,10 @@ public class StatusBar extends SystemUI implements DemoMode,
return mStatusBarWindow;
}
+ public StatusBarWindowViewController getStatusBarWindowViewController() {
+ return mStatusBarWindowViewController;
+ }
+
protected ViewGroup getBouncerContainer() {
return mStatusBarWindow;
}
@@ -1574,7 +1570,7 @@ public class StatusBar extends SystemUI implements DemoMode,
if ((diff1 & StatusBarManager.DISABLE_EXPAND) != 0) {
if ((state1 & StatusBarManager.DISABLE_EXPAND) != 0) {
- animateCollapsePanels();
+ mShadeController.animateCollapsePanels();
}
}
@@ -1598,7 +1594,7 @@ public class StatusBar extends SystemUI implements DemoMode,
if ((diff2 & StatusBarManager.DISABLE2_NOTIFICATION_SHADE) != 0) {
updateQsExpansionEnabled();
if ((state1 & StatusBarManager.DISABLE2_NOTIFICATION_SHADE) != 0) {
- animateCollapsePanels();
+ mShadeController.animateCollapsePanels();
}
}
}
@@ -1840,7 +1836,7 @@ public class StatusBar extends SystemUI implements DemoMode,
&& !mActivityLaunchAnimator.isLaunchForActivity()) {
onClosingFinished();
} else {
- collapsePanel(true /* animate */);
+ mShadeController.collapsePanel(true /* animate */);
}
}
@@ -1888,7 +1884,7 @@ public class StatusBar extends SystemUI implements DemoMode,
animateExpandSettingsPanel((String) m.obj);
break;
case MSG_CLOSE_PANELS:
- animateCollapsePanels();
+ mShadeController.animateCollapsePanels();
break;
case MSG_LAUNCH_TRANSITION_TIMEOUT:
onLaunchTransitionTimeout();
@@ -1985,20 +1981,13 @@ public class StatusBar extends SystemUI implements DemoMode,
setInteracting(StatusBarManager.WINDOW_STATUS_BAR, true);
}
- public void animateCollapsePanels() {
- animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
- }
-
- private final Runnable mAnimateCollapsePanels = this::animateCollapsePanels;
-
public void postAnimateCollapsePanels() {
- mHandler.post(mAnimateCollapsePanels);
+ mHandler.post(mShadeController::animateCollapsePanels);
}
public void postAnimateForceCollapsePanels() {
- mHandler.post(() -> {
- animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE, true /* force */);
- });
+ mHandler.post(() -> mShadeController.animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE,
+ true /* force */));
}
public void postAnimateOpenPanels() {
@@ -2008,67 +1997,35 @@ public class StatusBar extends SystemUI implements DemoMode,
@Override
public void togglePanel() {
if (mPanelExpanded) {
- animateCollapsePanels();
+ mShadeController.animateCollapsePanels();
} else {
animateExpandNotificationsPanel();
}
}
- public void animateCollapsePanels(int flags) {
- animateCollapsePanels(flags, false /* force */, false /* delayed */,
- 1.0f /* speedUpFactor */);
- }
-
@Override
public void animateCollapsePanels(int flags, boolean force) {
- animateCollapsePanels(flags, force, false /* delayed */, 1.0f /* speedUpFactor */);
- }
-
- public void animateCollapsePanels(int flags, boolean force, boolean delayed) {
- animateCollapsePanels(flags, force, delayed, 1.0f /* speedUpFactor */);
+ mShadeController.animateCollapsePanels(flags, force, false /* delayed */,
+ 1.0f /* speedUpFactor */);
}
- public void animateCollapsePanels(int flags, boolean force, boolean delayed,
- float speedUpFactor) {
- if (!force && mState != StatusBarState.SHADE) {
- runPostCollapseRunnables();
- return;
- }
- if (SPEW) {
- Log.d(TAG, "animateCollapse():"
- + " mExpandedVisible=" + mExpandedVisible
- + " flags=" + flags);
- }
-
- if ((flags & CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL) == 0) {
- if (!mHandler.hasMessages(MSG_HIDE_RECENT_APPS)) {
- mHandler.removeMessages(MSG_HIDE_RECENT_APPS);
- mHandler.sendEmptyMessage(MSG_HIDE_RECENT_APPS);
- }
+ /**
+ * Called by {@link ShadeController} when it calls
+ * {@link ShadeController#animateCollapsePanels(int, boolean, boolean, float)}.
+ */
+ void postHideRecentApps() {
+ if (!mHandler.hasMessages(MSG_HIDE_RECENT_APPS)) {
+ mHandler.removeMessages(MSG_HIDE_RECENT_APPS);
+ mHandler.sendEmptyMessage(MSG_HIDE_RECENT_APPS);
}
+ }
- // TODO(b/62444020): remove when this bug is fixed
- Log.v(TAG, "mStatusBarWindow: " + mStatusBarWindow + " canPanelBeCollapsed(): "
- + mNotificationPanel.canPanelBeCollapsed());
- if (mStatusBarWindow != null && mNotificationPanel.canPanelBeCollapsed()) {
- // release focus immediately to kick off focus change transition
- mStatusBarWindowController.setStatusBarFocusable(false);
-
- mStatusBarWindowViewController.cancelExpandHelper();
- mStatusBarView.collapsePanel(true /* animate */, delayed, speedUpFactor);
- } else {
- mBubbleController.collapseStack();
- }
+ public boolean isExpandedVisible() {
+ return mExpandedVisible;
}
- private void runPostCollapseRunnables() {
- ArrayList<Runnable> clonedList = new ArrayList<>(mPostCollapseRunnables);
- mPostCollapseRunnables.clear();
- int size = clonedList.size();
- for (int i = 0; i < size; i++) {
- clonedList.get(i).run();
- }
- mStatusBarKeyguardViewManager.readyForKeyguardDone();
+ public boolean isPanelExpanded() {
+ return mPanelExpanded;
}
/**
@@ -2147,7 +2104,7 @@ public class StatusBar extends SystemUI implements DemoMode,
mGutsManager.closeAndSaveGuts(true /* removeLeavebehind */, true /* force */,
true /* removeControls */, -1 /* x */, -1 /* y */, true /* resetMenu */);
- runPostCollapseRunnables();
+ mShadeController.runPostCollapseRunnables();
setInteracting(StatusBarManager.WINDOW_STATUS_BAR, false);
if (!mNotificationActivityStarter.isCollapsingToShowActivityOverLockscreen()) {
showBouncerIfKeyguard();
@@ -2672,12 +2629,12 @@ public class StatusBar extends SystemUI implements DemoMode,
}
if (dismissShade) {
if (mExpandedVisible && !mBouncerShowing) {
- animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL, true /* force */,
- true /* delayed*/);
+ mShadeController.animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL,
+ true /* force */, true /* delayed*/);
} else {
// Do it after DismissAction has been processed to conserve the needed ordering.
- mHandler.post(this::runPostCollapseRunnables);
+ mHandler.post(mShadeController::runPostCollapseRunnables);
}
} else if (isInLaunchTransition() && mNotificationPanel.isLaunchTransitionFinished()) {
@@ -2709,7 +2666,7 @@ public class StatusBar extends SystemUI implements DemoMode,
if (reason != null && reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
flags |= CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL;
}
- animateCollapsePanels(flags);
+ mShadeController.animateCollapsePanels(flags);
}
}
else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
@@ -2803,7 +2760,11 @@ public class StatusBar extends SystemUI implements DemoMode,
mScreenPinningRequest.onConfigurationChanged();
}
- @Override
+ /**
+ * Notify the shade controller that the current user changed
+ *
+ * @param newUserId userId of the new user
+ */
public void setLockscreenUser(int newUserId) {
if (mLockscreenWallpaper != null) {
mLockscreenWallpaper.setCurrentUser(newUserId);
@@ -3145,7 +3106,7 @@ public class StatusBar extends SystemUI implements DemoMode,
private void updatePanelExpansionForKeyguard() {
if (mState == StatusBarState.KEYGUARD && mBiometricUnlockController.getMode()
!= BiometricUnlockController.MODE_WAKE_AND_UNLOCK && !mBouncerShowing) {
- instantExpandNotificationsPanel();
+ mShadeController.instantExpandNotificationsPanel();
} else if (mState == StatusBarState.FULLSCREEN_USER_SWITCHER) {
instantCollapseNotificationPanel();
}
@@ -3160,10 +3121,6 @@ public class StatusBar extends SystemUI implements DemoMode,
mPresenter.updateMediaMetaData(true /* metaDataChanged */, true);
}
- public void addPostCollapseAction(Runnable r) {
- mPostCollapseRunnables.add(r);
- }
-
public boolean isInLaunchTransition() {
return mNotificationPanel.isLaunchTransitionRunning()
|| mNotificationPanel.isLaunchTransitionFinished();
@@ -3396,7 +3353,7 @@ public class StatusBar extends SystemUI implements DemoMode,
public boolean onMenuPressed() {
if (shouldUnlockOnMenuPressed()) {
- animateCollapsePanels(
+ mShadeController.animateCollapsePanels(
CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL /* flags */, true /* force */);
return true;
}
@@ -3426,7 +3383,7 @@ public class StatusBar extends SystemUI implements DemoMode,
}
if (mState != StatusBarState.KEYGUARD && mState != StatusBarState.SHADE_LOCKED) {
if (mNotificationPanel.canPanelBeCollapsed()) {
- animateCollapsePanels();
+ mShadeController.animateCollapsePanels();
} else {
mBubbleController.performBackPressIfNeeded();
}
@@ -3440,7 +3397,7 @@ public class StatusBar extends SystemUI implements DemoMode,
public boolean onSpacePressed() {
if (mDeviceInteractive && mState != StatusBarState.SHADE) {
- animateCollapsePanels(
+ mShadeController.animateCollapsePanels(
CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL /* flags */, true /* force */);
return true;
}
@@ -3454,43 +3411,9 @@ public class StatusBar extends SystemUI implements DemoMode,
}
}
- @Override
- public void instantExpandNotificationsPanel() {
- // Make our window larger and the panel expanded.
- makeExpandedVisible(true);
- mNotificationPanel.expand(false /* animate */);
- mCommandQueue.recomputeDisableFlags(mDisplayId, false /* animate */);
- }
-
- @Override
- public boolean closeShadeIfOpen() {
- if (!mNotificationPanel.isFullyCollapsed()) {
- mCommandQueue.animateCollapsePanels(
- CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL, true /* force */);
- visibilityChanged(false);
- mAssistManagerLazy.get().hideAssist();
- }
- return false;
- }
-
- @Override
- public void postOnShadeExpanded(Runnable executable) {
- mNotificationPanel.getViewTreeObserver().addOnGlobalLayoutListener(
- new ViewTreeObserver.OnGlobalLayoutListener() {
- @Override
- public void onGlobalLayout() {
- if (getStatusBarWindow().getHeight() != getStatusBarHeight()) {
- mNotificationPanel.getViewTreeObserver()
- .removeOnGlobalLayoutListener(this);
- mNotificationPanel.post(executable);
- }
- }
- });
- }
-
- private void instantCollapseNotificationPanel() {
+ void instantCollapseNotificationPanel() {
mNotificationPanel.instantCollapse();
- runPostCollapseRunnables();
+ mShadeController.runPostCollapseRunnables();
}
@Override
@@ -3576,11 +3499,11 @@ public class StatusBar extends SystemUI implements DemoMode,
}
public void onTrackingStarted() {
- runPostCollapseRunnables();
+ mShadeController.runPostCollapseRunnables();
}
public void onClosingFinished() {
- runPostCollapseRunnables();
+ mShadeController.runPostCollapseRunnables();
if (!mPresenter.isPresenterFullyCollapsed()) {
// if we set it not to be focusable when collapsing, we have to undo it when we aborted
// the closing
@@ -3641,7 +3564,7 @@ public class StatusBar extends SystemUI implements DemoMode,
*
* @param expandView The view to expand after going to the shade.
*/
- public void goToLockedShade(View expandView) {
+ void goToLockedShade(View expandView) {
if ((mDisabled2 & StatusBarManager.DISABLE2_NOTIFICATION_SHADE) != 0) {
return;
}
@@ -3700,7 +3623,7 @@ public class StatusBar extends SystemUI implements DemoMode,
mStatusBarWindowViewController.cancelCurrentTouch();
}
if (mPanelExpanded && mState == StatusBarState.SHADE) {
- animateCollapsePanels();
+ mShadeController.animateCollapsePanels();
}
}
@@ -4067,7 +3990,7 @@ public class StatusBar extends SystemUI implements DemoMode,
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.SHOW_NOTE_ABOUT_NOTIFICATION_HIDING, 0);
if (BANNER_ACTION_SETUP.equals(action)) {
- animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL,
+ mShadeController.animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL,
true /* force */);
mContext.startActivity(new Intent(Settings.ACTION_APP_NOTIFICATION_REDACTION)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
@@ -4078,35 +4001,6 @@ public class StatusBar extends SystemUI implements DemoMode,
}
};
- @Override
- public void collapsePanel(boolean animate) {
- if (animate) {
- boolean willCollapse = collapsePanel();
- if (!willCollapse) {
- runPostCollapseRunnables();
- }
- } else if (!mPresenter.isPresenterFullyCollapsed()) {
- instantCollapseNotificationPanel();
- visibilityChanged(false);
- } else {
- runPostCollapseRunnables();
- }
- }
-
- @Override
- public boolean collapsePanel() {
- if (!mNotificationPanel.isFullyCollapsed()) {
- // close the shade if it was open
- animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL, true /* force */,
- true /* delayed */);
- visibilityChanged(false);
-
- return true;
- } else {
- return false;
- }
- }
-
private final NotificationListener mNotificationListener;
public void setNotificationSnoozed(StatusBarNotification sbn, SnoozeOption snoozeOption) {
@@ -4217,7 +4111,7 @@ public class StatusBar extends SystemUI implements DemoMode,
action.run();
}).start();
- return collapsePanel();
+ return mShadeController.collapsePanel();
}, afterKeyguardGone);
}
@@ -4277,7 +4171,7 @@ public class StatusBar extends SystemUI implements DemoMode,
return options.toBundle();
}
- protected void visibilityChanged(boolean visible) {
+ void visibilityChanged(boolean visible) {
if (mVisible != visible) {
mVisible = visible;
if (!visible) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
index dac4e585c1ac..f51174b55b74 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
@@ -48,7 +48,6 @@ import com.android.systemui.keyguard.DismissCallbackRegistry;
import com.android.systemui.plugins.FalsingManager;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.shared.system.QuickStepContract;
-import com.android.systemui.statusbar.CommandQueue;
import com.android.systemui.statusbar.CrossFadeHelper;
import com.android.systemui.statusbar.NotificationMediaManager;
import com.android.systemui.statusbar.RemoteInputController;
@@ -921,12 +920,6 @@ public class StatusBarKeyguardViewManager implements RemoteInputController.Callb
mStatusBar.keyguardGoingAway();
}
- public void animateCollapsePanels(float speedUpFactor) {
- mStatusBar.animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE, true /* force */,
- false /* delayed */, speedUpFactor);
- }
-
-
/**
* Called when cancel button in bouncer is pressed.
*/
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarModule.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarModule.java
index 312c85f01275..e31c53abe988 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarModule.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarModule.java
@@ -164,6 +164,7 @@ public class StatusBarModule {
LightsOutNotifController lightsOutNotifController,
StatusBarNotificationActivityStarter.Builder
statusBarNotificationActivityStarterBuilder,
+ ShadeController shadeController,
SuperStatusBarViewFactory superStatusBarViewFactory,
StatusBarKeyguardViewManager statusBarKeyguardViewManager,
ViewMediatorCallback viewMediatorCallback,
@@ -237,6 +238,7 @@ public class StatusBarModule {
dividerOptional,
lightsOutNotifController,
statusBarNotificationActivityStarterBuilder,
+ shadeController,
superStatusBarViewFactory,
statusBarKeyguardViewManager,
viewMediatorCallback,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java
index 1988b42be14f..3123f8dacada 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java
@@ -524,7 +524,7 @@ public class StatusBarNotificationActivityStarter implements NotificationActivit
private final ActivityIntentHelper mActivityIntentHelper;
private final BubbleController mBubbleController;
private final SuperStatusBarViewFactory mSuperStatusBarViewFactory;
- private ShadeController mShadeController;
+ private final ShadeController mShadeController;
private NotificationPresenter mNotificationPresenter;
private ActivityLaunchAnimator mActivityLaunchAnimator;
private StatusBar mStatusBar;
@@ -553,6 +553,7 @@ public class StatusBarNotificationActivityStarter implements NotificationActivit
@BgHandler Handler backgroundHandler,
ActivityIntentHelper activityIntentHelper,
BubbleController bubbleController,
+ ShadeController shadeController,
SuperStatusBarViewFactory superStatusBarViewFactory) {
mContext = context;
mCommandQueue = commandQueue;
@@ -577,13 +578,13 @@ public class StatusBarNotificationActivityStarter implements NotificationActivit
mBackgroundHandler = backgroundHandler;
mActivityIntentHelper = activityIntentHelper;
mBubbleController = bubbleController;
+ mShadeController = shadeController;
mSuperStatusBarViewFactory = superStatusBarViewFactory;
}
- /** Sets the status bar to use as {@link StatusBar} and {@link ShadeController}. */
+ /** Sets the status bar to use as {@link StatusBar}. */
public Builder setStatusBar(StatusBar statusBar) {
mStatusBar = statusBar;
- mShadeController = statusBar;
return this;
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java
index 2649166bfcbf..8fc624dc9096 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java
@@ -88,7 +88,6 @@ public class StatusBarNotificationPresenter implements NotificationPresenter,
private static final String TAG = "StatusBarNotificationPresenter";
- private final ShadeController mShadeController = Dependency.get(ShadeController.class);
private final ActivityStarter mActivityStarter = Dependency.get(ActivityStarter.class);
private final KeyguardStateController mKeyguardStateController;
private final NotificationViewHierarchyManager mViewHierarchyManager =
@@ -116,6 +115,7 @@ public class StatusBarNotificationPresenter implements NotificationPresenter,
private final Context mContext;
private final KeyguardIndicationController mKeyguardIndicationController;
private final StatusBar mStatusBar;
+ private final ShadeController mShadeController;
private final CommandQueue mCommandQueue;
private final AccessibilityManager mAccessibilityManager;
@@ -145,6 +145,7 @@ public class StatusBarNotificationPresenter implements NotificationPresenter,
KeyguardStateController keyguardStateController,
KeyguardIndicationController keyguardIndicationController,
StatusBar statusBar,
+ ShadeController shadeController,
CommandQueue commandQueue) {
mContext = context;
mKeyguardStateController = keyguardStateController;
@@ -154,6 +155,7 @@ public class StatusBarNotificationPresenter implements NotificationPresenter,
mKeyguardIndicationController = keyguardIndicationController;
// TODO: use KeyguardStateController#isOccluded to remove this dependency
mStatusBar = statusBar;
+ mShadeController = shadeController;
mCommandQueue = commandQueue;
mAboveShelfObserver = new AboveShelfObserver(stackScroller);
mActivityLaunchAnimator = activityLaunchAnimator;
@@ -387,7 +389,7 @@ public class StatusBarNotificationPresenter implements NotificationPresenter,
}
updateNotificationViews();
mMediaManager.clearCurrentMediaNotification();
- mShadeController.setLockscreenUser(newUserId);
+ mStatusBar.setLockscreenUser(newUserId);
updateMediaMetaData(true, false);
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java
index 2012b5703504..6193a8e9005b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java
@@ -50,8 +50,6 @@ import com.android.systemui.statusbar.policy.KeyguardStateController;
import javax.inject.Inject;
import javax.inject.Singleton;
-import dagger.Lazy;
-
/**
*/
@Singleton
@@ -62,9 +60,9 @@ public class StatusBarRemoteInputCallback implements Callback, Callbacks,
private final SysuiStatusBarStateController mStatusBarStateController;
private final NotificationLockscreenUserManager mLockscreenUserManager;
private final ActivityStarter mActivityStarter;
- private final Lazy<ShadeController> mShadeControllerLazy;
private final Context mContext;
private final StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
+ private final ShadeController mShadeController;
private final ActivityIntentHelper mActivityIntentHelper;
private final NotificationGroupManager mGroupManager;
private View mPendingWorkRemoteInputView;
@@ -83,16 +81,16 @@ public class StatusBarRemoteInputCallback implements Callback, Callbacks,
KeyguardStateController keyguardStateController,
StatusBarStateController statusBarStateController,
StatusBarKeyguardViewManager statusBarKeyguardViewManager,
- ActivityStarter activityStarter, Lazy<ShadeController> shadeControllerLazy,
+ ActivityStarter activityStarter, ShadeController shadeController,
CommandQueue commandQueue) {
mContext = context;
mStatusBarKeyguardViewManager = statusBarKeyguardViewManager;
+ mShadeController = shadeController;
mContext.registerReceiverAsUser(mChallengeReceiver, UserHandle.ALL,
new IntentFilter(ACTION_DEVICE_LOCKED_CHANGED), null, null);
mLockscreenUserManager = notificationLockscreenUserManager;
mKeyguardStateController = keyguardStateController;
mStatusBarStateController = (SysuiStatusBarStateController) statusBarStateController;
- mShadeControllerLazy = shadeControllerLazy;
mActivityStarter = activityStarter;
mStatusBarStateController.addCallback(this);
mKeyguardManager = context.getSystemService(KeyguardManager.class);
@@ -167,8 +165,8 @@ public class StatusBarRemoteInputCallback implements Callback, Callbacks,
});
}
};
- mShadeControllerLazy.get().postOnShadeExpanded(clickPendingViewRunnable);
- mShadeControllerLazy.get().instantExpandNotificationsPanel();
+ mShadeController.postOnShadeExpanded(clickPendingViewRunnable);
+ mShadeController.instantExpandNotificationsPanel();
}
}
@@ -256,7 +254,7 @@ public class StatusBarRemoteInputCallback implements Callback, Callbacks,
boolean handled = defaultHandler.handleClick();
// close the shade if it was open and maybe wait for activity start.
- return handled && mShadeControllerLazy.get().closeShadeIfOpen();
+ return handled && mShadeController.closeShadeIfOpen();
}, null, afterKeyguardGone);
return true;
} else {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowController.java
index 2ecceba2116a..f94b2eea8154 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowController.java
@@ -204,6 +204,7 @@ public class StatusBarWindowController implements Callback, Dumpable, Configurat
PixelFormat.TRANSLUCENT);
mLp.token = new Binder();
mLp.gravity = Gravity.TOP;
+ mLp.setFitWindowInsetsTypes(0 /* types */);
mLp.softInputMode = LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
mLp.setTitle("StatusBar");
mLp.packageName = mContext.getPackageName();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowViewController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowViewController.java
index f8929e01adb8..eb86bcc8a52f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowViewController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowViewController.java
@@ -57,12 +57,9 @@ import java.io.PrintWriter;
import javax.inject.Inject;
-import dagger.Lazy;
-
/**
* Controller for {@link StatusBarWindowView}.
*/
-//@Singleton
public class StatusBarWindowViewController {
private final InjectionInflationController mInjectionInflationController;
private final NotificationWakeUpCoordinator mCoordinator;
@@ -80,7 +77,7 @@ public class StatusBarWindowViewController {
private final DozeParameters mDozeParameters;
private final CommandQueue mCommandQueue;
private final StatusBarWindowView mView;
- private final Lazy<ShadeController> mShadeControllerLazy;
+ private final ShadeController mShadeController;
private GestureDetector mGestureDetector;
private View mBrightnessMirror;
@@ -114,7 +111,7 @@ public class StatusBarWindowViewController {
DozeLog dozeLog,
DozeParameters dozeParameters,
CommandQueue commandQueue,
- Lazy<ShadeController> shadeControllerLazy,
+ ShadeController shadeController,
DockManager dockManager,
StatusBarWindowView statusBarWindowView) {
mInjectionInflationController = injectionInflationController;
@@ -133,7 +130,7 @@ public class StatusBarWindowViewController {
mDozeParameters = dozeParameters;
mCommandQueue = commandQueue;
mView = statusBarWindowView;
- mShadeControllerLazy = shadeControllerLazy;
+ mShadeController = shadeController;
mDockManager = dockManager;
// This view is not part of the newly inflated expanded status bar.
@@ -153,7 +150,7 @@ public class StatusBarWindowViewController {
mBypassController,
mFalsingManager,
mPluginManager,
- mShadeControllerLazy.get(),
+ mShadeController,
mNotificationLockscreenUserManager,
mNotificationEntryManager,
mKeyguardStateController,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/SystemUIDialog.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/SystemUIDialog.java
index 44be6bc282a7..28b6c389d4df 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/SystemUIDialog.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/SystemUIDialog.java
@@ -23,6 +23,8 @@ import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.UserHandle;
+import android.view.Window;
+import android.view.WindowInsets.Type;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
@@ -102,16 +104,22 @@ public class SystemUIDialog extends AlertDialog {
public static void setWindowOnTop(Dialog dialog) {
if (Dependency.get(KeyguardStateController.class).isShowing()) {
- dialog.getWindow().setType(LayoutParams.TYPE_STATUS_BAR_PANEL);
+ final Window window = dialog.getWindow();
+ window.setType(LayoutParams.TYPE_STATUS_BAR_PANEL);
+ window.setFitWindowInsetsTypes(
+ window.getFitWindowInsetsTypes() & ~Type.statusBars());
} else {
dialog.getWindow().setType(LayoutParams.TYPE_STATUS_BAR_SUB_PANEL);
}
}
public static AlertDialog applyFlags(AlertDialog dialog) {
- dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL);
- dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
+ final Window window = dialog.getWindow();
+ window.setType(WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL);
+ window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
+ window.setFitWindowInsetsTypes(
+ window.getFitWindowInsetsTypes() & ~Type.statusBars());
return dialog;
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BluetoothController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BluetoothController.java
index 42e02d5846bc..0c5b8515071d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BluetoothController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BluetoothController.java
@@ -31,6 +31,8 @@ public interface BluetoothController extends CallbackController<Callback>, Dumpa
boolean isBluetoothConnected();
boolean isBluetoothConnecting();
+ boolean isBluetoothAudioProfileOnly();
+ boolean isBluetoothAudioActive();
String getConnectedDeviceName();
void setBluetoothEnabled(boolean enabled);
Collection<CachedBluetoothDevice> getDevices();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BluetoothControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BluetoothControllerImpl.java
index 76683b6a5e6a..6ededd2460ce 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BluetoothControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BluetoothControllerImpl.java
@@ -32,6 +32,7 @@ import android.util.Log;
import com.android.settingslib.bluetooth.BluetoothCallback;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.bluetooth.LocalBluetoothManager;
+import com.android.settingslib.bluetooth.LocalBluetoothProfile;
import com.android.settingslib.bluetooth.LocalBluetoothProfileManager;
import com.android.systemui.dagger.qualifiers.BgLooper;
import com.android.systemui.dagger.qualifiers.MainLooper;
@@ -65,6 +66,8 @@ public class BluetoothControllerImpl implements BluetoothController, BluetoothCa
private boolean mEnabled;
private int mConnectionState = BluetoothAdapter.STATE_DISCONNECTED;
+ private boolean mAudioProfileOnly;
+ private boolean mIsActive;
private final H mHandler;
private int mState;
@@ -103,6 +106,8 @@ public class BluetoothControllerImpl implements BluetoothController, BluetoothCa
}
pw.print(" mEnabled="); pw.println(mEnabled);
pw.print(" mConnectionState="); pw.println(stateToString(mConnectionState));
+ pw.print(" mAudioProfileOnly="); pw.println(mAudioProfileOnly);
+ pw.print(" mIsActive="); pw.println(mIsActive);
pw.print(" mConnectedDevices="); pw.println(mConnectedDevices);
pw.print(" mCallbacks.size="); pw.println(mHandler.mCallbacks.size());
pw.println(" Bluetooth Devices:");
@@ -176,6 +181,16 @@ public class BluetoothControllerImpl implements BluetoothController, BluetoothCa
}
@Override
+ public boolean isBluetoothAudioProfileOnly() {
+ return mAudioProfileOnly;
+ }
+
+ @Override
+ public boolean isBluetoothAudioActive() {
+ return mIsActive;
+ }
+
+ @Override
public void setBluetoothEnabled(boolean enabled) {
if (mLocalBluetoothManager != null) {
mLocalBluetoothManager.getBluetoothAdapter().setBluetoothEnabled(enabled);
@@ -239,6 +254,48 @@ public class BluetoothControllerImpl implements BluetoothController, BluetoothCa
mConnectionState = state;
mHandler.sendEmptyMessage(H.MSG_STATE_CHANGED);
}
+ updateAudioProfile();
+ }
+
+ private void updateActive() {
+ boolean isActive = false;
+
+ for (CachedBluetoothDevice device : getDevices()) {
+ isActive |= device.isActiveDevice(BluetoothProfile.HEADSET)
+ || device.isActiveDevice(BluetoothProfile.A2DP)
+ || device.isActiveDevice(BluetoothProfile.HEARING_AID);
+ }
+
+ if (mIsActive != isActive) {
+ mIsActive = isActive;
+ mHandler.sendEmptyMessage(H.MSG_STATE_CHANGED);
+ }
+ }
+
+ private void updateAudioProfile() {
+ boolean audioProfileConnected = false;
+ boolean otherProfileConnected = false;
+
+ for (CachedBluetoothDevice device : getDevices()) {
+ for (LocalBluetoothProfile profile : device.getProfiles()) {
+ int profileId = profile.getProfileId();
+ boolean isConnected = device.isConnectedProfile(profile);
+ if (profileId == BluetoothProfile.HEADSET
+ || profileId == BluetoothProfile.A2DP
+ || profileId == BluetoothProfile.HEARING_AID) {
+ audioProfileConnected |= isConnected;
+ } else {
+ otherProfileConnected |= isConnected;
+ }
+ }
+ }
+
+ boolean audioProfileOnly = (audioProfileConnected && !otherProfileConnected);
+ if (audioProfileOnly != mAudioProfileOnly) {
+ mAudioProfileOnly = audioProfileOnly;
+ mHandler.sendEmptyMessage(H.MSG_STATE_CHANGED);
+ }
+
}
@Override
@@ -306,6 +363,16 @@ public class BluetoothControllerImpl implements BluetoothController, BluetoothCa
}
@Override
+ public void onActiveDeviceChanged(CachedBluetoothDevice activeDevice, int bluetoothProfile) {
+ if (DEBUG) {
+ Log.d(TAG, "ActiveDeviceChanged=" + activeDevice.getAddress()
+ + " profileId=" + bluetoothProfile);
+ }
+ updateActive();
+ mHandler.sendEmptyMessage(H.MSG_STATE_CHANGED);
+ }
+
+ @Override
public void onAclConnectionStateChanged(CachedBluetoothDevice cachedDevice, int state) {
if (DEBUG) {
Log.d(TAG, "ACLConnectionStateChanged=" + cachedDevice.getAddress() + " "
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceProvisionedControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceProvisionedControllerImpl.java
index b6ffd58be816..f6b770cd16b9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceProvisionedControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceProvisionedControllerImpl.java
@@ -40,7 +40,7 @@ public class DeviceProvisionedControllerImpl extends CurrentUserTracker implemen
DeviceProvisionedController {
protected static final String TAG = DeviceProvisionedControllerImpl.class.getSimpleName();
- private final ArrayList<DeviceProvisionedListener> mListeners = new ArrayList<>();
+ protected final ArrayList<DeviceProvisionedListener> mListeners = new ArrayList<>();
private final ContentResolver mContentResolver;
private final Context mContext;
private final Uri mDeviceProvisionedUri;
@@ -104,7 +104,7 @@ public class DeviceProvisionedControllerImpl extends CurrentUserTracker implemen
}
}
- private void startListening(int user) {
+ protected void startListening(int user) {
mContentResolver.registerContentObserver(mDeviceProvisionedUri, true,
mSettingsObserver, 0);
mContentResolver.registerContentObserver(mUserSetupUri, true,
@@ -112,7 +112,7 @@ public class DeviceProvisionedControllerImpl extends CurrentUserTracker implemen
startTracking();
}
- private void stopListening() {
+ protected void stopListening() {
stopTracking();
mContentResolver.unregisterContentObserver(mSettingsObserver);
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java
index b0cd90c3fb76..a6108a490331 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java
@@ -91,7 +91,8 @@ public class MobileSignalController extends SignalController<
@VisibleForTesting
boolean mIsShowingIconGracefully = false;
// Some specific carriers have 5GE network which is special LTE CA network.
- private static final int NETWORK_TYPE_LTE_CA_5GE = TelephonyManager.MAX_NETWORK_TYPE + 1;
+ private static final int NETWORK_TYPE_LTE_CA_5GE =
+ TelephonyManager.getAllNetworkTypes().length + 1;
// TODO: Reduce number of vars passed in, if we have the NetworkController, probably don't
// need listener lists anymore.
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/tv/AudioRecordingDisclosureBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/tv/AudioRecordingDisclosureBar.java
index 9b685f0ad0f6..74739e19ede9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/tv/AudioRecordingDisclosureBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/tv/AudioRecordingDisclosureBar.java
@@ -16,32 +16,44 @@
package com.android.systemui.statusbar.tv;
-import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
+import android.animation.Animator;
+import android.animation.AnimatorListenerAdapter;
+import android.animation.AnimatorSet;
+import android.animation.ObjectAnimator;
+import android.animation.PropertyValuesHolder;
+import android.annotation.IntDef;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
-import android.graphics.drawable.Drawable;
+import android.util.ArraySet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
-import android.view.ViewGroup;
-import android.view.ViewPropertyAnimator;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
-import android.widget.ImageView;
import android.widget.TextView;
import com.android.systemui.R;
-import java.util.ArrayList;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
-import java.util.List;
-
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.Set;
+
+/**
+ * A component of {@link TvStatusBar} responsible for notifying the user whenever an application is
+ * recording audio.
+ *
+ * @see TvStatusBar
+ */
class AudioRecordingDisclosureBar {
private static final String TAG = "AudioRecordingDisclosureBar";
private static final boolean DEBUG = false;
@@ -50,121 +62,310 @@ class AudioRecordingDisclosureBar {
// CtsSystemUiHostTestCases:TvMicrophoneCaptureIndicatorTest
private static final String LAYOUT_PARAMS_TITLE = "MicrophoneCaptureIndicator";
- private static final int ANIM_DURATION_MS = 150;
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(prefix = {"STATE_"}, value = {
+ STATE_NOT_SHOWN,
+ STATE_APPEARING,
+ STATE_SHOWN,
+ STATE_MINIMIZING,
+ STATE_MINIMIZED,
+ STATE_MAXIMIZING,
+ STATE_DISAPPEARING
+ })
+ public @interface State {}
+
+ private static final int STATE_NOT_SHOWN = 0;
+ private static final int STATE_APPEARING = 1;
+ private static final int STATE_SHOWN = 2;
+ private static final int STATE_MINIMIZING = 3;
+ private static final int STATE_MINIMIZED = 4;
+ private static final int STATE_MAXIMIZING = 5;
+ private static final int STATE_DISAPPEARING = 6;
+
+ private static final int ANIMATION_DURATION = 600;
+ private static final int MAXIMIZED_DURATION = 3000;
+ private static final int PULSE_BIT_DURATION = 1000;
+ private static final float PULSE_SCALE = 1.25f;
private final Context mContext;
- private final List<String> mAudioRecordingApps = new ArrayList<>();
- private View mView;
- private ViewGroup mAppsInfoContainer;
+
+ private View mIndicatorView;
+ private View mIconTextsContainer;
+ private View mIconContainerBg;
+ private View mIcon;
+ private View mBgRight;
+ private View mTextsContainers;
+ private TextView mTextView;
+
+ @State private int mState = STATE_NOT_SHOWN;
+ private final Set<String> mAudioRecordingApps = new HashSet<>();
+ private final Queue<String> mPendingNotifications = new LinkedList<>();
AudioRecordingDisclosureBar(Context context) {
mContext = context;
}
void start() {
- // Inflate and add audio recording disclosure bar
- createView();
-
// Register AppOpsManager callback
final AppOpsManager appOpsManager = (AppOpsManager) mContext.getSystemService(
Context.APP_OPS_SERVICE);
appOpsManager.startWatchingActive(
- new String[]{AppOpsManager.OPSTR_RECORD_AUDIO}, mContext.getMainExecutor(),
+ new String[]{AppOpsManager.OPSTR_RECORD_AUDIO},
+ mContext.getMainExecutor(),
new OnActiveRecordingListener());
}
- private void createView() {
- //TODO(b/142228704): this is to be re-implemented once proper design is completed
- mView = View.inflate(mContext,
- R.layout.tv_status_bar_audio_recording, null);
- mAppsInfoContainer = mView.findViewById(R.id.container);
+ private void onStartedRecording(String packageName) {
+ if (!mAudioRecordingApps.add(packageName)) {
+ // This app is already known to perform recording
+ return;
+ }
+
+ switch (mState) {
+ case STATE_NOT_SHOWN:
+ show(packageName);
+ break;
+
+ case STATE_MINIMIZED:
+ expand(packageName);
+ break;
+
+ case STATE_DISAPPEARING:
+ case STATE_APPEARING:
+ case STATE_MAXIMIZING:
+ case STATE_SHOWN:
+ case STATE_MINIMIZING:
+ // Currently animating or expanded. Thus add to the pending notifications, and it
+ // will be picked up once the indicator comes to the STATE_MINIMIZED.
+ mPendingNotifications.add(packageName);
+ break;
+ }
+ }
+
+ private void onDoneRecording(String packageName) {
+ if (!mAudioRecordingApps.remove(packageName)) {
+ // Was not marked as an active recorder, do nothing
+ return;
+ }
+
+ // If not MINIMIZED, will check whether the indicator should be hidden when the indicator
+ // comes to the STATE_MINIMIZED eventually. If is in the STATE_MINIMIZED, but there are
+ // other active recorders - simply ignore.
+ if (mState == STATE_MINIMIZED && mAudioRecordingApps.isEmpty()) {
+ hide();
+ }
+ }
+
+ private void show(String packageName) {
+ // Inflate the indicator view
+ mIndicatorView = LayoutInflater.from(mContext).inflate(
+ R.layout.tv_audio_recording_indicator,
+ null);
+ mIconTextsContainer = mIndicatorView.findViewById(R.id.icon_texts_container);
+ mIconContainerBg = mIconTextsContainer.findViewById(R.id.icon_container_bg);
+ mIcon = mIconTextsContainer.findViewById(R.id.icon_mic);
+ mTextsContainers = mIconTextsContainer.findViewById(R.id.texts_container);
+ mTextView = mTextsContainers.findViewById(R.id.text);
+ mBgRight = mIndicatorView.findViewById(R.id.bg_right);
+
+ // Set up the notification text
+ final String label = getApplicationLabel(packageName);
+ mTextView.setText(mContext.getString(R.string.app_accessed_mic, label));
+
+ // Initially change the visibility to INVISIBLE, wait until and receives the size and
+ // then animate it moving from "off" the screen correctly
+ mIndicatorView.setVisibility(View.INVISIBLE);
+ mIndicatorView
+ .getViewTreeObserver()
+ .addOnGlobalLayoutListener(
+ new ViewTreeObserver.OnGlobalLayoutListener() {
+ @Override
+ public void onGlobalLayout() {
+ // Remove the observer
+ mIndicatorView.getViewTreeObserver().removeOnGlobalLayoutListener(
+ this);
+
+ // Now that the width of the indicator has been assigned, we can
+ // move it in from off the screen.
+ final int initialOffset = mIndicatorView.getWidth();
+ final AnimatorSet set = new AnimatorSet();
+ set.setDuration(ANIMATION_DURATION);
+ set.playTogether(
+ ObjectAnimator.ofFloat(mIndicatorView,
+ View.TRANSLATION_X, initialOffset, 0),
+ ObjectAnimator.ofFloat(mIndicatorView, View.ALPHA, 0f,
+ 1f));
+ set.addListener(
+ new AnimatorListenerAdapter() {
+ @Override
+ public void onAnimationStart(Animator animation,
+ boolean isReverse) {
+ // Indicator is INVISIBLE at the moment, change it.
+ mIndicatorView.setVisibility(View.VISIBLE);
+ }
+
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ startPulsatingAnimation();
+ onExpanded();
+ }
+ });
+ set.start();
+ }
+ });
final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
- MATCH_PARENT,
+ WRAP_CONTENT,
WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
- layoutParams.gravity = Gravity.BOTTOM;
+ layoutParams.gravity = Gravity.TOP | Gravity.RIGHT;
layoutParams.setTitle(LAYOUT_PARAMS_TITLE);
layoutParams.packageName = mContext.getPackageName();
-
final WindowManager windowManager = (WindowManager) mContext.getSystemService(
Context.WINDOW_SERVICE);
- windowManager.addView(mView, layoutParams);
+ windowManager.addView(mIndicatorView, layoutParams);
+
+ mState = STATE_APPEARING;
+ }
- // Set invisible first until it gains its actual size and we are able to hide it by moving
- // off the screen
- mView.setVisibility(View.INVISIBLE);
- mView.getViewTreeObserver().addOnGlobalLayoutListener(
- new ViewTreeObserver.OnGlobalLayoutListener() {
+ private void expand(String packageName) {
+ final String label = getApplicationLabel(packageName);
+ mTextView.setText(mContext.getString(R.string.app_accessed_mic, label));
+
+ final AnimatorSet set = new AnimatorSet();
+ set.playTogether(
+ ObjectAnimator.ofFloat(mIconTextsContainer, View.TRANSLATION_X, 0),
+ ObjectAnimator.ofFloat(mIconContainerBg, View.ALPHA, 1f),
+ ObjectAnimator.ofFloat(mTextsContainers, View.ALPHA, 1f),
+ ObjectAnimator.ofFloat(mBgRight, View.ALPHA, 1f));
+ set.setDuration(ANIMATION_DURATION);
+ set.addListener(
+ new AnimatorListenerAdapter() {
@Override
- public void onGlobalLayout() {
- // Now that we get the height, we can move the bar off ("below") the screen
- final int height = mView.getHeight();
- mView.setTranslationY(height);
- // Remove the observer
- mView.getViewTreeObserver()
- .removeOnGlobalLayoutListener(this);
- // Now, that the view has been measured, and the translation was set to
- // move it off the screen, we change the visibility to GONE
- mView.setVisibility(View.GONE);
+ public void onAnimationEnd(Animator animation) {
+ onExpanded();
}
});
+ set.start();
+
+ mState = STATE_MAXIMIZING;
}
- private void showAudioRecordingDisclosureBar() {
- mView.setVisibility(View.VISIBLE);
- mView.animate()
- .translationY(0f)
- .setDuration(ANIM_DURATION_MS)
- .start();
+ private void minimize() {
+ final int targetOffset = mTextsContainers.getWidth();
+ final AnimatorSet set = new AnimatorSet();
+ set.playTogether(
+ ObjectAnimator.ofFloat(mIconTextsContainer, View.TRANSLATION_X, targetOffset),
+ ObjectAnimator.ofFloat(mIconContainerBg, View.ALPHA, 0f),
+ ObjectAnimator.ofFloat(mTextsContainers, View.ALPHA, 0f),
+ ObjectAnimator.ofFloat(mBgRight, View.ALPHA, 0f));
+ set.setDuration(ANIMATION_DURATION);
+ set.addListener(
+ new AnimatorListenerAdapter() {
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ onMinimized();
+ }
+ });
+ set.start();
+
+ mState = STATE_MINIMIZING;
}
- private void addToAudioRecordingDisclosureBar(String packageName) {
- final PackageManager pm = mContext.getPackageManager();
- final ApplicationInfo appInfo;
- try {
- appInfo = pm.getApplicationInfo(packageName, 0);
- } catch (PackageManager.NameNotFoundException e) {
- return;
+ private void hide() {
+ final int targetOffset =
+ mIndicatorView.getWidth() - (int) mIconTextsContainer.getTranslationX();
+ final AnimatorSet set = new AnimatorSet();
+ set.playTogether(
+ ObjectAnimator.ofFloat(mIndicatorView, View.TRANSLATION_X, targetOffset),
+ ObjectAnimator.ofFloat(mIcon, View.ALPHA, 0f));
+ set.setDuration(ANIMATION_DURATION);
+ set.addListener(
+ new AnimatorListenerAdapter() {
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ onHidden();
+ }
+ });
+ set.start();
+
+ mState = STATE_DISAPPEARING;
+ }
+
+ private void onExpanded() {
+ mState = STATE_SHOWN;
+
+ mIndicatorView.postDelayed(this::minimize, MAXIMIZED_DURATION);
+ }
+
+ private void onMinimized() {
+ mState = STATE_MINIMIZED;
+
+ if (!mPendingNotifications.isEmpty()) {
+ // There is a new application that started recording, tell the user about it.
+ expand(mPendingNotifications.poll());
+ } else if (mAudioRecordingApps.isEmpty()) {
+ // Nobody is recording anymore, remove the indicator.
+ hide();
}
- final CharSequence label = pm.getApplicationLabel(appInfo);
- final Drawable icon = pm.getApplicationIcon(appInfo);
+ }
+
+ private void onHidden() {
+ final WindowManager windowManager = (WindowManager) mContext.getSystemService(
+ Context.WINDOW_SERVICE);
+ windowManager.removeView(mIndicatorView);
- final View view = LayoutInflater.from(mContext).inflate(R.layout.tv_item_app_info,
- mAppsInfoContainer, false);
- ((TextView) view.findViewById(R.id.title)).setText(label);
- ((ImageView) view.findViewById(R.id.icon)).setImageDrawable(icon);
+ mIndicatorView = null;
+ mIconTextsContainer = null;
+ mIconContainerBg = null;
+ mIcon = null;
+ mTextsContainers = null;
+ mTextView = null;
+ mBgRight = null;
- mAppsInfoContainer.addView(view);
+ mState = STATE_NOT_SHOWN;
}
- private void removeFromAudioRecordingDisclosureBar(int index) {
- mAppsInfoContainer.removeViewAt(index);
+ private void startPulsatingAnimation() {
+ final View pulsatingView = mIconTextsContainer.findViewById(R.id.pulsating_circle);
+ final ObjectAnimator animator =
+ ObjectAnimator.ofPropertyValuesHolder(
+ pulsatingView,
+ PropertyValuesHolder.ofFloat(View.SCALE_X, PULSE_SCALE),
+ PropertyValuesHolder.ofFloat(View.SCALE_Y, PULSE_SCALE));
+ animator.setDuration(PULSE_BIT_DURATION);
+ animator.setRepeatCount(ObjectAnimator.INFINITE);
+ animator.setRepeatMode(ObjectAnimator.REVERSE);
+ animator.start();
}
- private void hideAudioRecordingDisclosureBar() {
- final ViewPropertyAnimator animator = mView.animate();
- animator.translationY(mView.getHeight())
- .setDuration(ANIM_DURATION_MS)
- .withEndAction(() -> mView.setVisibility(View.GONE))
- .start();
+ private String getApplicationLabel(String packageName) {
+ final PackageManager pm = mContext.getPackageManager();
+ final ApplicationInfo appInfo;
+ try {
+ appInfo = pm.getApplicationInfo(packageName, 0);
+ } catch (PackageManager.NameNotFoundException e) {
+ return packageName;
+ }
+ return pm.getApplicationLabel(appInfo).toString();
}
private class OnActiveRecordingListener implements AppOpsManager.OnOpActiveChangedListener {
- private final List<String> mExemptApps;
+ private final Set<String> mExemptApps;
private OnActiveRecordingListener() {
- mExemptApps = Arrays.asList(mContext.getResources().getStringArray(
- R.array.audio_recording_disclosure_exempt_apps));
+ mExemptApps = new ArraySet<>(Arrays.asList(mContext.getResources().getStringArray(
+ R.array.audio_recording_disclosure_exempt_apps)));
}
@Override
public void onOpActiveChanged(String op, int uid, String packageName, boolean active) {
if (DEBUG) {
Log.d(TAG,
- "OP_RECORD_AUDIO active change, active=" + active + ", app=" + packageName);
+ "OP_RECORD_AUDIO active change, active=" + active + ", app="
+ + packageName);
}
if (mExemptApps.contains(packageName)) {
@@ -174,37 +375,10 @@ class AudioRecordingDisclosureBar {
return;
}
- final boolean alreadyTracking = mAudioRecordingApps.contains(packageName);
- if ((active && alreadyTracking) || (!active && !alreadyTracking)) {
- if (DEBUG) {
- Log.d(TAG, "\t- nothing changed");
- }
- return;
- }
-
if (active) {
- if (DEBUG) {
- Log.d(TAG, "\t- new recording app");
- }
-
- if (mAudioRecordingApps.isEmpty()) {
- showAudioRecordingDisclosureBar();
- }
-
- mAudioRecordingApps.add(packageName);
- addToAudioRecordingDisclosureBar(packageName);
+ onStartedRecording(packageName);
} else {
- if (DEBUG) {
- Log.d(TAG, "\t- not recording any more");
- }
-
- final int index = mAudioRecordingApps.indexOf(packageName);
- removeFromAudioRecordingDisclosureBar(index);
- mAudioRecordingApps.remove(index);
-
- if (mAudioRecordingApps.isEmpty()) {
- hideAudioRecordingDisclosureBar();
- }
+ onDoneRecording(packageName);
}
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/usb/UsbDebuggingActivity.java b/packages/SystemUI/src/com/android/systemui/usb/UsbDebuggingActivity.java
index 2f13f395d057..367d4d2bcfa0 100644
--- a/packages/SystemUI/src/com/android/systemui/usb/UsbDebuggingActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/usb/UsbDebuggingActivity.java
@@ -16,19 +16,13 @@
package com.android.systemui.usb;
-import android.app.Activity;
import android.app.AlertDialog;
-import android.content.BroadcastReceiver;
-import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
-import android.content.IntentFilter;
import android.debug.IAdbManager;
-import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.ServiceManager;
-import android.os.SystemProperties;
import android.util.EventLog;
import android.util.Log;
import android.view.LayoutInflater;
@@ -42,25 +36,14 @@ import android.widget.Toast;
import com.android.internal.app.AlertActivity;
import com.android.internal.app.AlertController;
import com.android.systemui.R;
-import com.android.systemui.broadcast.BroadcastDispatcher;
-
-import javax.inject.Inject;
public class UsbDebuggingActivity extends AlertActivity
implements DialogInterface.OnClickListener {
private static final String TAG = "UsbDebuggingActivity";
private CheckBox mAlwaysAllow;
- private UsbDisconnectedReceiver mDisconnectedReceiver;
- private final BroadcastDispatcher mBroadcastDispatcher;
private String mKey;
- @Inject
- public UsbDebuggingActivity(BroadcastDispatcher broadcastDispatcher) {
- super();
- mBroadcastDispatcher = broadcastDispatcher;
- }
-
@Override
public void onCreate(Bundle icicle) {
Window window = getWindow();
@@ -70,10 +53,6 @@ public class UsbDebuggingActivity extends AlertActivity
super.onCreate(icicle);
- if (SystemProperties.getInt("service.adb.tcp.port", 0) == 0) {
- mDisconnectedReceiver = new UsbDisconnectedReceiver(this);
- }
-
Intent intent = getIntent();
String fingerprints = intent.getStringExtra("fingerprints");
mKey = intent.getStringExtra("key");
@@ -126,40 +105,6 @@ public class UsbDebuggingActivity extends AlertActivity
super.onWindowAttributesChanged(params);
}
- private class UsbDisconnectedReceiver extends BroadcastReceiver {
- private final Activity mActivity;
- public UsbDisconnectedReceiver(Activity activity) {
- mActivity = activity;
- }
-
- @Override
- public void onReceive(Context content, Intent intent) {
- String action = intent.getAction();
- if (!UsbManager.ACTION_USB_STATE.equals(action)) {
- return;
- }
- boolean connected = intent.getBooleanExtra(UsbManager.USB_CONNECTED, false);
- if (!connected) {
- mActivity.finish();
- }
- }
- }
-
- @Override
- public void onStart() {
- super.onStart();
- IntentFilter filter = new IntentFilter(UsbManager.ACTION_USB_STATE);
- mBroadcastDispatcher.registerReceiver(mDisconnectedReceiver, filter);
- }
-
- @Override
- protected void onStop() {
- if (mDisconnectedReceiver != null) {
- mBroadcastDispatcher.unregisterReceiver(mDisconnectedReceiver);
- }
- super.onStop();
- }
-
@Override
public void onClick(DialogInterface dialog, int which) {
boolean allow = (which == AlertDialog.BUTTON_POSITIVE);
diff --git a/packages/SystemUI/src/com/android/systemui/usb/UsbDebuggingSecondaryUserActivity.java b/packages/SystemUI/src/com/android/systemui/usb/UsbDebuggingSecondaryUserActivity.java
index 032b72ebff7d..421424206370 100644
--- a/packages/SystemUI/src/com/android/systemui/usb/UsbDebuggingSecondaryUserActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/usb/UsbDebuggingSecondaryUserActivity.java
@@ -16,41 +16,19 @@
package com.android.systemui.usb;
-import android.app.Activity;
-import android.content.BroadcastReceiver;
-import android.content.Context;
import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.hardware.usb.UsbManager;
import android.os.Bundle;
-import android.os.SystemProperties;
import com.android.internal.app.AlertActivity;
import com.android.internal.app.AlertController;
import com.android.systemui.R;
-import com.android.systemui.broadcast.BroadcastDispatcher;
-
-import javax.inject.Inject;
public class UsbDebuggingSecondaryUserActivity extends AlertActivity
implements DialogInterface.OnClickListener {
- private UsbDisconnectedReceiver mDisconnectedReceiver;
- private final BroadcastDispatcher mBroadcastDispatcher;
-
- @Inject
- public UsbDebuggingSecondaryUserActivity(BroadcastDispatcher broadcastDispatcher) {
- mBroadcastDispatcher = broadcastDispatcher;
- }
-
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
- if (SystemProperties.getInt("service.adb.tcp.port", 0) == 0) {
- mDisconnectedReceiver = new UsbDisconnectedReceiver(this);
- }
-
final AlertController.AlertParams ap = mAlertParams;
ap.mTitle = getString(R.string.usb_debugging_secondary_user_title);
ap.mMessage = getString(R.string.usb_debugging_secondary_user_message);
@@ -60,40 +38,6 @@ public class UsbDebuggingSecondaryUserActivity extends AlertActivity
setupAlert();
}
- private class UsbDisconnectedReceiver extends BroadcastReceiver {
- private final Activity mActivity;
- public UsbDisconnectedReceiver(Activity activity) {
- mActivity = activity;
- }
-
- @Override
- public void onReceive(Context content, Intent intent) {
- String action = intent.getAction();
- if (UsbManager.ACTION_USB_STATE.equals(action)) {
- boolean connected = intent.getBooleanExtra(UsbManager.USB_CONNECTED, false);
- if (!connected) {
- mActivity.finish();
- }
- }
- }
- }
-
- @Override
- public void onStart() {
- super.onStart();
-
- IntentFilter filter = new IntentFilter(UsbManager.ACTION_USB_STATE);
- mBroadcastDispatcher.registerReceiver(mDisconnectedReceiver, filter);
- }
-
- @Override
- protected void onStop() {
- if (mDisconnectedReceiver != null) {
- mBroadcastDispatcher.unregisterReceiver(mDisconnectedReceiver);
- }
- super.onStop();
- }
-
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
diff --git a/packages/SystemUI/src/com/android/systemui/util/animation/PhysicsAnimator.kt b/packages/SystemUI/src/com/android/systemui/util/animation/PhysicsAnimator.kt
new file mode 100644
index 000000000000..62ae7b9d620f
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/util/animation/PhysicsAnimator.kt
@@ -0,0 +1,717 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.util.animation
+
+import android.os.Looper
+import android.util.ArrayMap
+import android.util.Log
+import android.view.View
+import androidx.dynamicanimation.animation.DynamicAnimation
+import androidx.dynamicanimation.animation.FlingAnimation
+import androidx.dynamicanimation.animation.FloatPropertyCompat
+import androidx.dynamicanimation.animation.SpringAnimation
+import androidx.dynamicanimation.animation.SpringForce
+import com.android.systemui.util.animation.PhysicsAnimator.Companion.getInstance
+import java.util.WeakHashMap
+
+/**
+ * Extension function for all objects which will return a PhysicsAnimator instance for that object.
+ */
+val <T : View> T.physicsAnimator: PhysicsAnimator<T> get() { return getInstance(this) }
+
+private const val TAG = "PhysicsAnimator"
+
+typealias EndAction = () -> Unit
+
+/** A map of Property -> AnimationUpdate, which is provided to update listeners on each frame. */
+typealias UpdateMap<T> =
+ ArrayMap<FloatPropertyCompat<in T>, PhysicsAnimator.AnimationUpdate>
+
+/**
+ * Map of the animators associated with a given object. This ensures that only one animator
+ * per object exists.
+ */
+internal val animators = WeakHashMap<Any, PhysicsAnimator<*>>()
+
+/**
+ * Default spring configuration to use for animations where stiffness and/or damping ratio
+ * were not provided.
+ */
+private val defaultSpring = PhysicsAnimator.SpringConfig(
+ SpringForce.STIFFNESS_MEDIUM,
+ SpringForce.DAMPING_RATIO_MEDIUM_BOUNCY)
+
+/** Default fling configuration to use for animations where friction was not provided. */
+private val defaultFling = PhysicsAnimator.FlingConfig(
+ friction = 1f, min = -Float.MAX_VALUE, max = Float.MAX_VALUE)
+
+/** Whether to log helpful debug information about animations. */
+private var verboseLogging = false
+
+/**
+ * Animator that uses physics-based animations to animate properties on views and objects. Physics
+ * animations use real-world physical concepts, such as momentum and mass, to realistically simulate
+ * motion. PhysicsAnimator is heavily inspired by [android.view.ViewPropertyAnimator], and
+ * also uses the builder pattern to configure and start animations.
+ *
+ * The physics animations are backed by [DynamicAnimation].
+ *
+ * @param T The type of the object being animated.
+ */
+class PhysicsAnimator<T> private constructor (val target: T) {
+
+ /** Data class for representing animation frame updates. */
+ data class AnimationUpdate(val value: Float, val velocity: Float)
+
+ /** [DynamicAnimation] instances for the given properties. */
+ private val springAnimations = ArrayMap<FloatPropertyCompat<in T>, SpringAnimation>()
+ private val flingAnimations = ArrayMap<FloatPropertyCompat<in T>, FlingAnimation>()
+
+ /**
+ * Spring and fling configurations for the properties to be animated on the target. We'll
+ * configure and start the DynamicAnimations for these properties according to the provided
+ * configurations.
+ */
+ private val springConfigs = ArrayMap<FloatPropertyCompat<in T>, SpringConfig>()
+ private val flingConfigs = ArrayMap<FloatPropertyCompat<in T>, FlingConfig>()
+
+ /**
+ * Animation listeners for the animation. These will be notified when each property animation
+ * updates or ends.
+ */
+ private val updateListeners = ArrayList<UpdateListener<T>>()
+ private val endListeners = ArrayList<EndListener<T>>()
+
+ /** End actions to run when all animations have completed. */
+ private val endActions = ArrayList<EndAction>()
+
+ /**
+ * Internal listeners that respond to DynamicAnimations updating and ending, and dispatch to
+ * the listeners provided via [addUpdateListener] and [addEndListener]. This allows us to add
+ * just one permanent update and end listener to the DynamicAnimations.
+ */
+ internal var internalListeners = ArrayList<InternalListener>()
+
+ /**
+ * Action to run when [start] is called. This can be changed by
+ * [PhysicsAnimatorTestUtils.prepareForTest] to enable animators to run under test and provide
+ * helpful test utilities.
+ */
+ internal var startAction: () -> Unit = ::startInternal
+
+ /**
+ * Springs a property to the given value, using the provided configuration settings.
+ *
+ * Springs are used when you know the exact value to which you want to animate. They can be
+ * configured with a start velocity (typically used when the spring is initiated by a touch
+ * event), but this velocity will be realistically attenuated as forces are applied to move the
+ * property towards the end value.
+ *
+ * If you find yourself repeating the same stiffness and damping ratios many times, consider
+ * storing a single [SpringConfig] instance and passing that in instead of individual values.
+ *
+ * @param property The property to spring to the given value. The property must be an instance
+ * of FloatPropertyCompat&lt;? super T&gt;. For example, if this is a
+ * PhysicsAnimator&lt;FrameLayout&gt;, you can use a FloatPropertyCompat&lt;FrameLayout&gt;, as
+ * well as a FloatPropertyCompat&lt;ViewGroup&gt;, and so on.
+ * @param toPosition The value to spring the given property to.
+ * @param startVelocity The initial velocity to use for the animation.
+ * @param stiffness The stiffness to use for the spring. Higher stiffness values result in
+ * faster animations, while lower stiffness means a slower animation. Reasonable values for
+ * low, medium, and high stiffness can be found as constants in [SpringForce].
+ * @param dampingRatio The damping ratio (bounciness) to use for the spring. Higher values
+ * result in a less 'springy' animation, while lower values allow the animation to bounce
+ * back and forth for a longer time after reaching the final position. Reasonable values for
+ * low, medium, and high damping can be found in [SpringForce].
+ */
+ fun spring(
+ property: FloatPropertyCompat<in T>,
+ toPosition: Float,
+ startVelocity: Float = 0f,
+ stiffness: Float = defaultSpring.stiffness,
+ dampingRatio: Float = defaultSpring.dampingRatio
+ ): PhysicsAnimator<T> {
+ if (verboseLogging) {
+ Log.d(TAG, "Springing ${getReadablePropertyName(property)} to $toPosition.")
+ }
+
+ springConfigs[property] =
+ SpringConfig(stiffness, dampingRatio, startVelocity, toPosition)
+ return this
+ }
+
+ /**
+ * Springs a property to a given value using the provided start velocity and configuration
+ * options.
+ *
+ * @see spring
+ */
+ fun spring(
+ property: FloatPropertyCompat<in T>,
+ toPosition: Float,
+ startVelocity: Float,
+ config: SpringConfig = defaultSpring
+ ): PhysicsAnimator<T> {
+ return spring(
+ property, toPosition, startVelocity, config.stiffness, config.dampingRatio)
+ }
+
+ /**
+ * Springs a property to a given value using the provided configuration options, and a start
+ * velocity of 0f.
+ *
+ * @see spring
+ */
+ fun spring(
+ property: FloatPropertyCompat<in T>,
+ toPosition: Float,
+ config: SpringConfig = defaultSpring
+ ): PhysicsAnimator<T> {
+ return spring(property, toPosition, 0f, config)
+ }
+
+ /**
+ * Flings a property using the given start velocity, using a [FlingAnimation] configured using
+ * the provided configuration settings.
+ *
+ * Flings are used when you have a start velocity, and want the property value to realistically
+ * decrease as friction is applied until the velocity reaches zero. Flings do not have a
+ * deterministic end value. If you are attempting to animate to a specific end value, use
+ * [spring].
+ *
+ * If you find yourself repeating the same friction/min/max values, consider storing a single
+ * [FlingConfig] and passing that in instead.
+ *
+ * @param property The property to fling using the given start velocity.
+ * @param startVelocity The start velocity (in pixels per second) with which to start the fling.
+ * @param friction Friction value applied to slow down the animation over time. Higher values
+ * will more quickly slow the animation. Typical friction values range from 1f to 10f.
+ * @param min The minimum value allowed for the animation. If this value is reached, the
+ * animation will end abruptly.
+ * @param max The maximum value allowed for the animation. If this value is reached, the
+ * animation will end abruptly.
+ */
+ fun fling(
+ property: FloatPropertyCompat<in T>,
+ startVelocity: Float,
+ friction: Float = defaultFling.friction,
+ min: Float = defaultFling.min,
+ max: Float = defaultFling.max
+ ): PhysicsAnimator<T> {
+ if (verboseLogging) {
+ Log.d(TAG, "Flinging ${getReadablePropertyName(property)} " +
+ "with velocity $startVelocity.")
+ }
+
+ flingConfigs[property] = FlingConfig(friction, min, max, startVelocity)
+ return this
+ }
+
+ /**
+ * Flings a property using the given start velocity, using a [FlingAnimation] configured using
+ * the provided configuration settings.
+ *
+ * @see fling
+ */
+ fun fling(
+ property: FloatPropertyCompat<in T>,
+ startVelocity: Float,
+ config: FlingConfig = defaultFling
+ ): PhysicsAnimator<T> {
+ return fling(property, startVelocity, config.friction, config.min, config.max)
+ }
+
+ /**
+ * Adds a listener that will be called whenever any property on the animated object is updated.
+ * This will be called on every animation frame, with the current value of the animated object
+ * and the new property values.
+ */
+ fun addUpdateListener(listener: UpdateListener<T>): PhysicsAnimator<T> {
+ updateListeners.add(listener)
+ return this
+ }
+
+ /**
+ * Adds a listener that will be called whenever a property's animation ends. This is useful if
+ * you care about a specific property ending, or want to use the end value/end velocity from a
+ * particular property's animation. If you just want to run an action when all property
+ * animations have ended, use [withEndActions].
+ */
+ fun addEndListener(listener: EndListener<T>): PhysicsAnimator<T> {
+ endListeners.add(listener)
+ return this
+ }
+
+ /**
+ * Adds end actions that will be run sequentially when animations for every property involved in
+ * this specific animation have ended (unless they were explicitly canceled). For example, if
+ * you call:
+ *
+ * animator
+ * .spring(TRANSLATION_X, ...)
+ * .spring(TRANSLATION_Y, ...)
+ * .withEndAction(action)
+ * .start()
+ *
+ * 'action' will be run when both TRANSLATION_X and TRANSLATION_Y end.
+ *
+ * Other properties may still be animating, if those animations were not started in the same
+ * call. For example:
+ *
+ * animator
+ * .spring(ALPHA, ...)
+ * .start()
+ *
+ * animator
+ * .spring(TRANSLATION_X, ...)
+ * .spring(TRANSLATION_Y, ...)
+ * .withEndAction(action)
+ * .start()
+ *
+ * 'action' will still be run as soon as TRANSLATION_X and TRANSLATION_Y end, even if ALPHA is
+ * still animating.
+ *
+ * If you want to run actions as soon as a subset of property animations have ended, you want
+ * access to the animation's end value/velocity, or you want to run these actions even if the
+ * animation is explicitly canceled, use [addEndListener]. End listeners have an allEnded param,
+ * which indicates that all relevant animations have ended.
+ */
+ fun withEndActions(vararg endActions: EndAction): PhysicsAnimator<T> {
+ this.endActions.addAll(endActions)
+ return this
+ }
+
+ /** Starts the animations! */
+ fun start() {
+ startAction()
+ }
+
+ /**
+ * Starts the animations for real! This is typically called immediately by [start] unless this
+ * animator is under test.
+ */
+ internal fun startInternal() {
+ if (!Looper.getMainLooper().isCurrentThread) {
+ Log.e(TAG, "Animations can only be started on the main thread. If you are seeing " +
+ "this message in a test, call PhysicsAnimatorTestUtils#prepareForTest in " +
+ "your test setup.")
+ }
+
+ // Add an internal listener that will dispatch animation events to the provided listeners.
+ internalListeners.add(InternalListener(
+ getAnimatedProperties(),
+ ArrayList(updateListeners),
+ ArrayList(endListeners),
+ ArrayList(endActions)))
+
+ for ((property, config) in flingConfigs) {
+ val currentValue = property.getValue(target)
+
+ // If the fling is already out of bounds, don't start it.
+ if (currentValue <= config.min || currentValue >= config.max) {
+ continue
+ }
+
+ val flingAnim = getFlingAnimation(property)
+ config.applyToAnimation(flingAnim)
+ flingAnim.start()
+ }
+
+ for ((property, config) in springConfigs) {
+ val springAnim = getSpringAnimation(property)
+ config.applyToAnimation(springAnim)
+ springAnim.start()
+ }
+
+ clearAnimator()
+ }
+
+ /** Clear the animator's builder variables. */
+ private fun clearAnimator() {
+ springConfigs.clear()
+ flingConfigs.clear()
+
+ updateListeners.clear()
+ endListeners.clear()
+ endActions.clear()
+ }
+
+ /** Retrieves a spring animation for the given property, building one if needed. */
+ private fun getSpringAnimation(property: FloatPropertyCompat<in T>): SpringAnimation {
+ return springAnimations.getOrPut(
+ property,
+ { configureDynamicAnimation(SpringAnimation(target, property), property)
+ as SpringAnimation })
+ }
+
+ /** Retrieves a fling animation for the given property, building one if needed. */
+ private fun getFlingAnimation(property: FloatPropertyCompat<in T>): FlingAnimation {
+ return flingAnimations.getOrPut(
+ property,
+ { configureDynamicAnimation(FlingAnimation(target, property), property)
+ as FlingAnimation })
+ }
+
+ /**
+ * Adds update and end listeners to the DynamicAnimation which will dispatch to the internal
+ * listeners.
+ */
+ private fun configureDynamicAnimation(
+ anim: DynamicAnimation<*>,
+ property: FloatPropertyCompat<in T>
+ ): DynamicAnimation<*> {
+ anim.addUpdateListener { _, value, velocity ->
+ for (i in 0 until internalListeners.size) {
+ internalListeners[i].onInternalAnimationUpdate(property, value, velocity)
+ }
+ }
+ anim.addEndListener { _, canceled, value, velocity ->
+ internalListeners.removeAll {
+ it.onInternalAnimationEnd(property, canceled, value, velocity) } }
+ return anim
+ }
+
+ /**
+ * Internal listener class that receives updates from DynamicAnimation listeners, and dispatches
+ * them to the appropriate update/end listeners. This class is also aware of which properties
+ * were being animated when the end listeners were passed in, so that we can provide the
+ * appropriate value for allEnded to [EndListener.onAnimationEnd].
+ */
+ internal inner class InternalListener constructor(
+ private var properties: Set<FloatPropertyCompat<in T>>,
+ private var updateListeners: List<UpdateListener<T>>,
+ private var endListeners: List<EndListener<T>>,
+ private var endActions: List<EndAction>
+ ) {
+
+ /** The number of properties whose animations haven't ended. */
+ private var numPropertiesAnimating = properties.size
+
+ /**
+ * Update values that haven't yet been dispatched because not all property animations have
+ * updated yet.
+ */
+ private val undispatchedUpdates =
+ ArrayMap<FloatPropertyCompat<in T>, AnimationUpdate>()
+
+ /** Called when a DynamicAnimation updates. */
+ internal fun onInternalAnimationUpdate(
+ property: FloatPropertyCompat<in T>,
+ value: Float,
+ velocity: Float
+ ) {
+
+ // If this property animation isn't relevant to this listener, ignore it.
+ if (!properties.contains(property)) {
+ return
+ }
+
+ undispatchedUpdates[property] = AnimationUpdate(value, velocity)
+ maybeDispatchUpdates()
+ }
+
+ /**
+ * Called when a DynamicAnimation ends.
+ *
+ * @return True if this listener should be removed from the list of internal listeners, so
+ * it no longer receives updates from DynamicAnimations.
+ */
+ internal fun onInternalAnimationEnd(
+ property: FloatPropertyCompat<in T>,
+ canceled: Boolean,
+ finalValue: Float,
+ finalVelocity: Float
+ ): Boolean {
+
+ // If this property animation isn't relevant to this listener, ignore it.
+ if (!properties.contains(property)) {
+ return false
+ }
+
+ // Dispatch updates if we have one for each property.
+ numPropertiesAnimating--
+ maybeDispatchUpdates()
+
+ // If we didn't have an update for each property, dispatch the update for the ending
+ // property. This guarantees that an update isn't sent for this property *after* we call
+ // onAnimationEnd for that property.
+ if (undispatchedUpdates.contains(property)) {
+ updateListeners.forEach { updateListener ->
+ updateListener.onAnimationUpdateForProperty(
+ target,
+ UpdateMap<T>().also { it[property] = undispatchedUpdates[property] })
+ }
+
+ undispatchedUpdates.remove(property)
+ }
+
+ val allEnded = !arePropertiesAnimating(properties)
+ endListeners.forEach {
+ it.onAnimationEnd(target, property, canceled, finalValue, finalVelocity, allEnded) }
+
+ // If all of the animations that this listener cares about have ended, run the end
+ // actions unless the animation was canceled.
+ if (allEnded && !canceled) {
+ endActions.forEach { it() }
+ }
+
+ return allEnded
+ }
+
+ /**
+ * Dispatch undispatched values if we've received an update from each of the animating
+ * properties.
+ */
+ private fun maybeDispatchUpdates() {
+ if (undispatchedUpdates.size >= numPropertiesAnimating &&
+ undispatchedUpdates.size > 0) {
+ updateListeners.forEach {
+ it.onAnimationUpdateForProperty(target, ArrayMap(undispatchedUpdates))
+ }
+
+ undispatchedUpdates.clear()
+ }
+ }
+ }
+
+ /** Return true if any animations are running on the object. */
+ fun isRunning(): Boolean {
+ return arePropertiesAnimating(springAnimations.keys.union(flingAnimations.keys))
+ }
+
+ /** Returns whether the given property is animating. */
+ fun isPropertyAnimating(property: FloatPropertyCompat<in T>): Boolean {
+ return springAnimations[property]?.isRunning ?: false
+ }
+
+ /** Returns whether any of the given properties are animating. */
+ fun arePropertiesAnimating(properties: Set<FloatPropertyCompat<in T>>): Boolean {
+ return properties.any { isPropertyAnimating(it) }
+ }
+
+ /** Return the set of properties that will begin animating upon calling [start]. */
+ internal fun getAnimatedProperties(): Set<FloatPropertyCompat<in T>> {
+ return springConfigs.keys.union(flingConfigs.keys)
+ }
+
+ /** Cancels all in progress animations on all properties. */
+ fun cancel() {
+ for (dynamicAnim in flingAnimations.values.union(springAnimations.values)) {
+ dynamicAnim.cancel()
+ }
+ }
+
+ /**
+ * Container object for spring animation configuration settings. This allows you to store
+ * default stiffness and damping ratio values in a single configuration object, which you can
+ * pass to [spring].
+ */
+ data class SpringConfig internal constructor(
+ internal var stiffness: Float,
+ internal var dampingRatio: Float,
+ internal var startVel: Float = 0f,
+ internal var finalPosition: Float = -Float.MAX_VALUE
+ ) {
+
+ constructor() :
+ this(defaultSpring.stiffness, defaultSpring.dampingRatio)
+
+ constructor(stiffness: Float, dampingRatio: Float) :
+ this(stiffness = stiffness, dampingRatio = dampingRatio, startVel = 0f)
+
+ /** Apply these configuration settings to the given SpringAnimation. */
+ internal fun applyToAnimation(anim: SpringAnimation) {
+ val springForce = anim.spring ?: SpringForce()
+ anim.spring = springForce.apply {
+ stiffness = this@SpringConfig.stiffness
+ dampingRatio = this@SpringConfig.dampingRatio
+ finalPosition = this@SpringConfig.finalPosition
+ }
+
+ if (startVel != 0f) anim.setStartVelocity(startVel)
+ }
+ }
+
+ /**
+ * Container object for fling animation configuration settings. This allows you to store default
+ * friction values (as well as optional min/max values) in a single configuration object, which
+ * you can pass to [fling] and related methods.
+ */
+ data class FlingConfig internal constructor(
+ internal var friction: Float,
+ internal var min: Float,
+ internal var max: Float,
+ internal var startVel: Float
+ ) {
+
+ constructor() : this(defaultFling.friction)
+
+ constructor(friction: Float) :
+ this(friction, defaultFling.min, defaultFling.max)
+
+ constructor(friction: Float, min: Float, max: Float) :
+ this(friction, min, max, startVel = 0f)
+
+ /** Apply these configuration settings to the given FlingAnimation. */
+ internal fun applyToAnimation(anim: FlingAnimation) {
+ anim.apply {
+ friction = this@FlingConfig.friction
+ setMinValue(min)
+ setMaxValue(max)
+ setStartVelocity(startVel)
+ }
+ }
+ }
+
+ /**
+ * Listener for receiving values from in progress animations. Used with
+ * [PhysicsAnimator.addUpdateListener].
+ *
+ * @param <T> The type of the object being animated.
+ </T> */
+ interface UpdateListener<T> {
+
+ /**
+ * Called on each animation frame with the target object, and a map of FloatPropertyCompat
+ * -> AnimationUpdate, containing the latest value and velocity for that property. When
+ * multiple properties are animating together, the map will typically contain one entry for
+ * each property. However, you should never assume that this is the case - when a property
+ * animation ends earlier than the others, you'll receive an UpdateMap containing only that
+ * property's final update. Subsequently, you'll only receive updates for the properties
+ * that are still animating.
+ *
+ * Always check that the map contains an update for the property you're interested in before
+ * accessing it.
+ *
+ * @param target The animated object itself.
+ * @param values Map of property to AnimationUpdate, which contains that property
+ * animation's latest value and velocity. You should never assume that a particular property
+ * is present in this map.
+ */
+ fun onAnimationUpdateForProperty(
+ target: T,
+ values: UpdateMap<T>
+ )
+ }
+
+ /**
+ * Listener for receiving callbacks when animations end.
+ *
+ * @param <T> The type of the object being animated.
+ </T> */
+ interface EndListener<T> {
+
+ /**
+ * Called with the final animation values as each property animation ends. This can be used
+ * to respond to specific property animations concluding (such as hiding a view when ALPHA
+ * ends, even if the corresponding TRANSLATION animations have not ended).
+ *
+ * If you just want to run an action when all of the property animations have ended, you can
+ * use [PhysicsAnimator.withEndActions].
+ *
+ * @param target The animated object itself.
+ * @param property The property whose animation has just ended.
+ * @param canceled Whether the animation was explicitly canceled before it naturally ended.
+ * @param finalValue The final value of the animated property.
+ * @param finalVelocity The final velocity (in pixels per second) of the ended animation.
+ * This is typically zero, unless this was a fling animation which ended abruptly due to
+ * reaching its configured min/max values.
+ * @param allRelevantPropertyAnimsEnded Whether all properties relevant to this end listener
+ * have ended. Relevant properties are those which were animated alongside the
+ * [addEndListener] call where this animator was passed in. For example:
+ *
+ * animator
+ * .spring(TRANSLATION_X, 100f)
+ * .spring(TRANSLATION_Y, 200f)
+ * .withEndListener(firstEndListener)
+ * .start()
+ *
+ * firstEndListener will be called first for TRANSLATION_X, with allEnded = false,
+ * because TRANSLATION_Y is still running. When TRANSLATION_Y ends, it'll be called with
+ * allEnded = true.
+ *
+ * If a subsequent call to start() is made with other properties, those properties are not
+ * considered relevant and allEnded will still equal true when only TRANSLATION_X and
+ * TRANSLATION_Y end. For example, if immediately after the prior example, while
+ * TRANSLATION_X and TRANSLATION_Y are still animating, we called:
+ *
+ * animator.
+ * .spring(SCALE_X, 2f, stiffness = 10f) // That will take awhile...
+ * .withEndListener(secondEndListener)
+ * .start()
+ *
+ * firstEndListener will still be called with allEnded = true when TRANSLATION_X/Y end, even
+ * though SCALE_X is still animating. Similarly, secondEndListener will be called with
+ * allEnded = true as soon as SCALE_X ends, even if the translation animations are still
+ * running.
+ */
+ fun onAnimationEnd(
+ target: T,
+ property: FloatPropertyCompat<in T>,
+ canceled: Boolean,
+ finalValue: Float,
+ finalVelocity: Float,
+ allRelevantPropertyAnimsEnded: Boolean
+ )
+ }
+
+ companion object {
+
+ /**
+ * Constructor to use to for new physics animator instances in [getInstance]. This is
+ * typically the default constructor, but [PhysicsAnimatorTestUtils] can change it so that
+ * all code using the physics animator is given testable instances instead.
+ */
+ internal var instanceConstructor: (Any) -> PhysicsAnimator<*> = ::PhysicsAnimator
+
+ @JvmStatic
+ fun <T : Any> getInstance(target: T): PhysicsAnimator<T> {
+ if (!animators.containsKey(target)) {
+ animators[target] = instanceConstructor(target)
+ }
+
+ return animators[target] as PhysicsAnimator<T>
+ }
+
+ /**
+ * Set whether all physics animators should log a lot of information about animations.
+ * Useful for debugging!
+ */
+ @JvmStatic
+ fun setVerboseLogging(debug: Boolean) {
+ verboseLogging = debug
+ }
+
+ @JvmStatic
+ fun getReadablePropertyName(property: FloatPropertyCompat<*>): String {
+ return when (property) {
+ DynamicAnimation.TRANSLATION_X -> "translationX"
+ DynamicAnimation.TRANSLATION_Y -> "translationY"
+ DynamicAnimation.TRANSLATION_Z -> "translationZ"
+ DynamicAnimation.SCALE_X -> "scaleX"
+ DynamicAnimation.SCALE_Y -> "scaleY"
+ DynamicAnimation.ROTATION -> "rotation"
+ DynamicAnimation.ROTATION_X -> "rotationX"
+ DynamicAnimation.ROTATION_Y -> "rotationY"
+ DynamicAnimation.SCROLL_X -> "scrollX"
+ DynamicAnimation.SCROLL_Y -> "scrollY"
+ DynamicAnimation.ALPHA -> "alpha"
+ else -> "Custom FloatPropertyCompat instance"
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/util/animation/PhysicsAnimatorTestUtils.kt b/packages/SystemUI/src/com/android/systemui/util/animation/PhysicsAnimatorTestUtils.kt
new file mode 100644
index 000000000000..a1f74eb40cad
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/util/animation/PhysicsAnimatorTestUtils.kt
@@ -0,0 +1,457 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.util.animation
+
+import android.os.Handler
+import android.os.Looper
+import android.util.ArrayMap
+import androidx.dynamicanimation.animation.FloatPropertyCompat
+import java.util.ArrayDeque
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.TimeUnit
+
+typealias UpdateMatcher = (PhysicsAnimator.AnimationUpdate) -> Boolean
+typealias UpdateFramesPerProperty<T> =
+ ArrayMap<FloatPropertyCompat<in T>, ArrayList<PhysicsAnimator.AnimationUpdate>>
+
+/**
+ * Utilities for testing code that uses [PhysicsAnimator].
+ *
+ * Start by calling [prepareForTest] at the beginning of each test - this will modify the behavior
+ * of all PhysicsAnimator instances so that they post animations to the main thread (so they don't
+ * crash). It'll also enable the use of the other static helper methods in this class, which you can
+ * use to do things like block the test until animations complete (so you can test end states), or
+ * verify keyframes.
+ */
+object PhysicsAnimatorTestUtils {
+ var timeoutMs: Long = 2000
+ private var startBlocksUntilAnimationsEnd = false
+ private val animationThreadHandler = Handler(Looper.getMainLooper())
+ private val allAnimatedObjects = HashSet<Any>()
+ private val animatorTestHelpers = HashMap<PhysicsAnimator<*>, AnimatorTestHelper<*>>()
+
+ /**
+ * Modifies the behavior of all [PhysicsAnimator] instances so that they post animations to the
+ * main thread, and report all of their
+ */
+ @JvmStatic
+ fun prepareForTest() {
+ val defaultConstructor = PhysicsAnimator.instanceConstructor
+ PhysicsAnimator.instanceConstructor = fun(target: Any): PhysicsAnimator<*> {
+ val animator = defaultConstructor(target)
+ allAnimatedObjects.add(target)
+ animatorTestHelpers[animator] = AnimatorTestHelper(animator)
+ return animator
+ }
+
+ timeoutMs = 2000
+ startBlocksUntilAnimationsEnd = false
+ allAnimatedObjects.clear()
+ }
+
+ @JvmStatic
+ fun tearDown() {
+ val latch = CountDownLatch(1)
+ animationThreadHandler.post {
+ animatorTestHelpers.keys.forEach { it.cancel() }
+ latch.countDown()
+ }
+
+ latch.await()
+
+ animatorTestHelpers.clear()
+ animators.clear()
+ allAnimatedObjects.clear()
+ }
+
+ /**
+ * Sets the maximum time (in milliseconds) to block the test thread while waiting for animations
+ * before throwing an exception.
+ */
+ @JvmStatic
+ fun setBlockTimeout(timeoutMs: Long) {
+ this.timeoutMs = timeoutMs
+ }
+
+ /**
+ * Sets whether all animations should block the test thread until they end. This is typically
+ * the desired behavior, since you can invoke code that runs an animation and then assert things
+ * about its end state.
+ */
+ @JvmStatic
+ fun setAllAnimationsBlock(block: Boolean) {
+ startBlocksUntilAnimationsEnd = block
+ }
+
+ /**
+ * Blocks the calling thread until animations of the given property on the target object end.
+ */
+ @JvmStatic
+ @Throws(InterruptedException::class)
+ fun <T : Any> blockUntilAnimationsEnd(
+ animator: PhysicsAnimator<T>,
+ vararg properties: FloatPropertyCompat<in T>
+ ) {
+ val animatingProperties = HashSet<FloatPropertyCompat<in T>>()
+ for (property in properties) {
+ if (animator.isPropertyAnimating(property)) {
+ animatingProperties.add(property)
+ }
+ }
+
+ if (animatingProperties.size > 0) {
+ val latch = CountDownLatch(animatingProperties.size)
+ getAnimationTestHelper(animator).addTestEndListener(
+ object : PhysicsAnimator.EndListener<T> {
+ override fun onAnimationEnd(
+ target: T,
+ property: FloatPropertyCompat<in T>,
+ canceled: Boolean,
+ finalValue: Float,
+ finalVelocity: Float,
+ allRelevantPropertyAnimsEnded: Boolean
+ ) {
+ if (animatingProperties.contains(property)) {
+ latch.countDown()
+ }
+ }
+ })
+
+ latch.await(timeoutMs, TimeUnit.MILLISECONDS)
+ }
+ }
+
+ /**
+ * Blocks the calling thread until all animations of the given property (on all target objects)
+ * have ended. Useful when you don't have access to the objects being animated, but still need
+ * to wait for them to end so that other testable side effects occur (such as update/end
+ * listeners).
+ */
+ @JvmStatic
+ @Throws(InterruptedException::class)
+ fun <T : Any> blockUntilAnimationsEnd(
+ properties: FloatPropertyCompat<in T>
+ ) {
+ for (target in allAnimatedObjects) {
+ try {
+ blockUntilAnimationsEnd(
+ PhysicsAnimator.getInstance(target) as PhysicsAnimator<T>, properties)
+ } catch (e: ClassCastException) {
+ // Keep checking the other objects for ones whose types match the provided
+ // properties.
+ }
+ }
+ }
+
+ /**
+ * Blocks the calling thread until the first animation frame in which predicate returns true. If
+ * the given object isn't animating, returns without blocking.
+ */
+ @JvmStatic
+ @Throws(InterruptedException::class)
+ fun <T : Any> blockUntilFirstAnimationFrameWhereTrue(
+ animator: PhysicsAnimator<T>,
+ predicate: (T) -> Boolean
+ ) {
+ if (animator.isRunning()) {
+ val latch = CountDownLatch(1)
+ getAnimationTestHelper(animator).addTestUpdateListener(object : PhysicsAnimator
+ .UpdateListener<T> {
+ override fun onAnimationUpdateForProperty(
+ target: T,
+ values: UpdateMap<T>
+ ) {
+ if (predicate(target)) {
+ latch.countDown()
+ }
+ }
+ })
+
+ latch.await(timeoutMs, TimeUnit.MILLISECONDS)
+ }
+ }
+
+ /**
+ * Verifies that the animator reported animation frame values to update listeners that satisfy
+ * the given matchers, in order. Not all frames need to satisfy a matcher - we'll run through
+ * all animation frames, and check them against the current predicate. If it returns false, we
+ * continue through the frames until it returns true, and then move on to the next matcher.
+ * Verification fails if we run out of frames while unsatisfied matchers remain.
+ *
+ * If verification is successful, all frames to this point are considered 'verified' and will be
+ * cleared. Subsequent calls to this method will start verification at the next animation frame.
+ *
+ * Example: Verify that an animation surpassed x = 50f before going negative.
+ * verifyAnimationUpdateFrames(
+ * animator, TRANSLATION_X,
+ * { u -> u.value > 50f },
+ * { u -> u.value < 0f })
+ *
+ * Example: verify that an animation went backwards at some point while still being on-screen.
+ * verifyAnimationUpdateFrames(
+ * animator, TRANSLATION_X,
+ * { u -> u.velocity < 0f && u.value >= 0f })
+ *
+ * This method is intended to help you test longer, more complicated animations where it's
+ * critical that certain values were reached. Using this method to test short animations can
+ * fail due to the animation having fewer frames than provided matchers. For example, an
+ * animation from x = 1f to x = 5f might only have two frames, at x = 3f and x = 5f. The
+ * following would then fail despite it seeming logically sound:
+ *
+ * verifyAnimationUpdateFrames(
+ * animator, TRANSLATION_X,
+ * { u -> u.value > 1f },
+ * { u -> u.value > 2f },
+ * { u -> u.value > 3f })
+ *
+ * Tests might also fail if your matchers are too granular, such as this example test after an
+ * animation from x = 0f to x = 100f. It's unlikely there was a frame specifically between 2f
+ * and 3f.
+ *
+ * verifyAnimationUpdateFrames(
+ * animator, TRANSLATION_X,
+ * { u -> u.value > 2f && u.value < 3f },
+ * { u -> u.value >= 50f })
+ *
+ * Failures will print a helpful log of all animation frames so you can see what caused the test
+ * to fail.
+ */
+ fun <T : Any> verifyAnimationUpdateFrames(
+ animator: PhysicsAnimator<T>,
+ property: FloatPropertyCompat<in T>,
+ firstUpdateMatcher: UpdateMatcher,
+ vararg additionalUpdateMatchers: UpdateMatcher
+ ) {
+ val updateFrames: UpdateFramesPerProperty<T> = getAnimationUpdateFrames(animator)
+ val matchers = ArrayDeque<UpdateMatcher>(
+ additionalUpdateMatchers.toList())
+ val frameTraceMessage = StringBuilder()
+
+ var curMatcher = firstUpdateMatcher
+
+ // Loop through the updates from the testable animator.
+ for (update in updateFrames[property]
+ ?: error("No frames for given target object and property.")) {
+
+ // Check whether this frame satisfies the current matcher.
+ if (curMatcher(update)) {
+
+ // If that was the last unsatisfied matcher, we're good here. 'Verify' all remaining
+ // frames and return without failing.
+ if (matchers.size == 0) {
+ getAnimationUpdateFrames(animator).remove(property)
+ return
+ }
+
+ frameTraceMessage.append("$update\t(satisfied matcher)\n")
+ curMatcher = matchers.pop() // Get the next matcher and keep going.
+ } else {
+ frameTraceMessage.append("${update}\n")
+ }
+ }
+
+ val readablePropertyName = PhysicsAnimator.getReadablePropertyName(property)
+ getAnimationUpdateFrames(animator).remove(property)
+
+ throw RuntimeException(
+ "Failed to verify animation frames for property $readablePropertyName: " +
+ "Provided ${additionalUpdateMatchers.size + 1} matchers, " +
+ "however ${matchers.size + 1} remained unsatisfied.\n\n" +
+ "All frames:\n$frameTraceMessage")
+ }
+
+ /**
+ * Overload of [verifyAnimationUpdateFrames] that builds matchers for you, from given float
+ * values. For example, to verify that an animations passed from 0f to 50f to 100f back to 50f:
+ *
+ * verifyAnimationUpdateFrames(animator, TRANSLATION_X, 0f, 50f, 100f, 50f)
+ *
+ * This verifies that update frames were received with values of >= 0f, >= 50f, >= 100f, and
+ * <= 50f.
+ *
+ * The same caveats apply: short animations might not have enough frames to satisfy all of the
+ * matchers, and overly specific calls (such as 0f, 1f, 2f, 3f, etc. for an animation from
+ * x = 0f to x = 100f) might fail as the animation only had frames at 0f, 25f, 50f, 75f, and
+ * 100f. As with [verifyAnimationUpdateFrames], failures will print a helpful log of all frames
+ * so you can see what caused the test to fail.
+ */
+ fun <T : Any> verifyAnimationUpdateFrames(
+ animator: PhysicsAnimator<T>,
+ property: FloatPropertyCompat<in T>,
+ startValue: Float,
+ firstTargetValue: Float,
+ vararg additionalTargetValues: Float
+ ) {
+ val matchers = ArrayList<UpdateMatcher>()
+
+ val values = ArrayList<Float>().also {
+ it.add(firstTargetValue)
+ it.addAll(additionalTargetValues.toList())
+ }
+
+ var prevVal = startValue
+ for (value in values) {
+ if (value > prevVal) {
+ matchers.add { update -> update.value >= value }
+ } else {
+ matchers.add { update -> update.value <= value }
+ }
+
+ prevVal = value
+ }
+
+ verifyAnimationUpdateFrames(
+ animator, property, matchers[0], *matchers.drop(0).toTypedArray())
+ }
+
+ /**
+ * Returns all of the values that have ever been reported to update listeners, per property.
+ */
+ fun <T : Any> getAnimationUpdateFrames(animator: PhysicsAnimator<T>):
+ UpdateFramesPerProperty<T> {
+ return animatorTestHelpers[animator]?.getUpdates() as UpdateFramesPerProperty<T>
+ }
+
+ /**
+ * Clears animation frame updates from the given animator so they aren't used the next time its
+ * passed to [verifyAnimationUpdateFrames].
+ */
+ fun <T : Any> clearAnimationUpdateFrames(animator: PhysicsAnimator<T>) {
+ animatorTestHelpers[animator]?.clearUpdates()
+ }
+
+ private fun <T> getAnimationTestHelper(animator: PhysicsAnimator<T>): AnimatorTestHelper<T> {
+ return animatorTestHelpers[animator] as AnimatorTestHelper<T>
+ }
+
+ /**
+ * Helper class for testing an animator. This replaces the animator's start action with
+ * [startForTest] and adds test listeners to enable other test utility behaviors. We build one
+ * these for each Animator and keep them around so we can access the updates.
+ */
+ class AnimatorTestHelper<T> (private val animator: PhysicsAnimator<T>) {
+
+ /** All updates received for each property animation. */
+ private val allUpdates =
+ ArrayMap<FloatPropertyCompat<in T>, ArrayList<PhysicsAnimator.AnimationUpdate>>()
+
+ private val testEndListeners = ArrayList<PhysicsAnimator.EndListener<T>>()
+ private val testUpdateListeners = ArrayList<PhysicsAnimator.UpdateListener<T>>()
+
+ init {
+ animator.startAction = ::startForTest
+ }
+
+ internal fun addTestEndListener(listener: PhysicsAnimator.EndListener<T>) {
+ testEndListeners.add(listener)
+ }
+
+ internal fun addTestUpdateListener(listener: PhysicsAnimator.UpdateListener<T>) {
+ testUpdateListeners.add(listener)
+ }
+
+ internal fun getUpdates(): UpdateFramesPerProperty<T> {
+ return allUpdates
+ }
+
+ internal fun clearUpdates() {
+ allUpdates.clear()
+ }
+
+ private fun startForTest() {
+ // The testable animator needs to block the main thread until super.start() has been
+ // called, since callers expect .start() to be synchronous but we're posting it to a
+ // handler here. We may also continue blocking until all animations end, if
+ // startBlocksUntilAnimationsEnd = true.
+ val unblockLatch = CountDownLatch(if (startBlocksUntilAnimationsEnd) 2 else 1)
+
+ animationThreadHandler.post {
+ val animatedProperties = animator.getAnimatedProperties()
+
+ // Add an update listener that dispatches to any test update listeners added by
+ // tests.
+ animator.addUpdateListener(object : PhysicsAnimator.UpdateListener<T> {
+ override fun onAnimationUpdateForProperty(
+ target: T,
+ values: ArrayMap<FloatPropertyCompat<in T>, PhysicsAnimator.AnimationUpdate>
+ ) {
+ for (listener in testUpdateListeners) {
+ listener.onAnimationUpdateForProperty(target, values)
+ }
+ }
+ })
+
+ // Add an end listener that dispatches to any test end listeners added by tests, and
+ // unblocks the main thread if required.
+ animator.addEndListener(object : PhysicsAnimator.EndListener<T> {
+ override fun onAnimationEnd(
+ target: T,
+ property: FloatPropertyCompat<in T>,
+ canceled: Boolean,
+ finalValue: Float,
+ finalVelocity: Float,
+ allRelevantPropertyAnimsEnded: Boolean
+ ) {
+ for (listener in testEndListeners) {
+ listener.onAnimationEnd(
+ target, property, canceled, finalValue, finalVelocity,
+ allRelevantPropertyAnimsEnded)
+ }
+
+ if (allRelevantPropertyAnimsEnded) {
+ testEndListeners.clear()
+ testUpdateListeners.clear()
+
+ if (startBlocksUntilAnimationsEnd) {
+ unblockLatch.countDown()
+ }
+ }
+ }
+ })
+
+ val updateListeners = ArrayList<PhysicsAnimator.UpdateListener<T>>().also {
+ it.add(object : PhysicsAnimator.UpdateListener<T> {
+ override fun onAnimationUpdateForProperty(
+ target: T,
+ values: ArrayMap<FloatPropertyCompat<in T>,
+ PhysicsAnimator.AnimationUpdate>
+ ) {
+ values.forEach { (property, value) ->
+ allUpdates.getOrPut(property, { ArrayList() }).add(value)
+ }
+ }
+ })
+ }
+
+ /**
+ * Add an internal listener at the head of the list that captures update values
+ * directly from DynamicAnimation. We use this to build a list of all updates so we
+ * can verify that InternalListener dispatches to the real listeners properly.
+ */
+ animator.internalListeners.add(0, animator.InternalListener(
+ animatedProperties,
+ updateListeners,
+ ArrayList(),
+ ArrayList()))
+
+ animator.startInternal()
+ unblockLatch.countDown()
+ }
+
+ unblockLatch.await(timeoutMs, TimeUnit.MILLISECONDS)
+ }
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/util/concurrency/ConcurrencyModule.java b/packages/SystemUI/src/com/android/systemui/util/concurrency/ConcurrencyModule.java
index 24f49ff99879..3e90581292ce 100644
--- a/packages/SystemUI/src/com/android/systemui/util/concurrency/ConcurrencyModule.java
+++ b/packages/SystemUI/src/com/android/systemui/util/concurrency/ConcurrencyModule.java
@@ -18,11 +18,12 @@ package com.android.systemui.util.concurrency;
import android.content.Context;
import android.os.Handler;
+import android.os.Looper;
import com.android.systemui.dagger.qualifiers.Background;
-import com.android.systemui.dagger.qualifiers.BgHandler;
+import com.android.systemui.dagger.qualifiers.BgLooper;
import com.android.systemui.dagger.qualifiers.Main;
-import com.android.systemui.dagger.qualifiers.MainHandler;
+import com.android.systemui.dagger.qualifiers.MainLooper;
import java.util.concurrent.Executor;
@@ -38,8 +39,8 @@ public abstract class ConcurrencyModule {
* Provide a Background-Thread Executor by default.
*/
@Provides
- public static Executor provideExecutor(@BgHandler Handler handler) {
- return new ExecutorImpl(handler);
+ public static Executor provideExecutor(@BgLooper Looper looper) {
+ return new ExecutorImpl(new Handler(looper));
}
/**
@@ -47,8 +48,8 @@ public abstract class ConcurrencyModule {
*/
@Provides
@Background
- public static Executor provideBackgroundExecutor(@BgHandler Handler handler) {
- return new ExecutorImpl(handler);
+ public static Executor provideBackgroundExecutor(@BgLooper Looper looper) {
+ return new ExecutorImpl(new Handler(looper));
}
/**
@@ -64,8 +65,8 @@ public abstract class ConcurrencyModule {
* Provide a Background-Thread Executor by default.
*/
@Provides
- public static DelayableExecutor provideDelayableExecutor(@BgHandler Handler handler) {
- return new ExecutorImpl(handler);
+ public static DelayableExecutor provideDelayableExecutor(@BgLooper Looper looper) {
+ return new ExecutorImpl(new Handler(looper));
}
/**
@@ -73,8 +74,8 @@ public abstract class ConcurrencyModule {
*/
@Provides
@Background
- public static DelayableExecutor provideBackgroundDelayableExecutor(@BgHandler Handler handler) {
- return new ExecutorImpl(handler);
+ public static DelayableExecutor provideBackgroundDelayableExecutor(@BgLooper Looper looper) {
+ return new ExecutorImpl(new Handler(looper));
}
/**
@@ -82,7 +83,7 @@ public abstract class ConcurrencyModule {
*/
@Provides
@Main
- public static DelayableExecutor provideMainDelayableExecutor(@MainHandler Handler handler) {
- return new ExecutorImpl(handler);
+ public static DelayableExecutor provideMainDelayableExecutor(@MainLooper Looper looper) {
+ return new ExecutorImpl(new Handler(looper));
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/volume/Events.java b/packages/SystemUI/src/com/android/systemui/volume/Events.java
index 5ed8b8f9e362..e1210011c7a4 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/Events.java
+++ b/packages/SystemUI/src/com/android/systemui/volume/Events.java
@@ -21,7 +21,11 @@ import android.media.AudioSystem;
import android.provider.Settings.Global;
import android.util.Log;
+import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.logging.MetricsLogger;
+import com.android.internal.logging.UiEvent;
+import com.android.internal.logging.UiEventLogger;
+import com.android.internal.logging.UiEventLoggerImpl;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.systemui.plugins.VolumeDialogController.State;
@@ -37,7 +41,7 @@ public class Events {
public static final int EVENT_DISMISS_DIALOG = 1; // (reason|int)
public static final int EVENT_ACTIVE_STREAM_CHANGED = 2; // (stream|int)
public static final int EVENT_EXPAND = 3; // (expand|bool)
- public static final int EVENT_KEY = 4;
+ public static final int EVENT_KEY = 4; // (stream|int) (lastAudibleStreamVolume)
public static final int EVENT_COLLECTION_STARTED = 5;
public static final int EVENT_COLLECTION_STOPPED = 6;
public static final int EVENT_ICON_CLICK = 7; // (stream|int) (icon_state|int)
@@ -49,7 +53,7 @@ public class Events {
public static final int EVENT_ZEN_MODE_CHANGED = 13; // (mode|int)
public static final int EVENT_SUPPRESSOR_CHANGED = 14; // (component|string) (name|string)
public static final int EVENT_MUTE_CHANGED = 15; // (stream|int) (muted|bool)
- public static final int EVENT_TOUCH_LEVEL_DONE = 16; // (stream|int) (level|bool)
+ public static final int EVENT_TOUCH_LEVEL_DONE = 16; // (stream|int) (level|int)
public static final int EVENT_ZEN_CONFIG_CHANGED = 17; // (allow/disallow|string)
public static final int EVENT_RINGER_TOGGLE = 18; // (ringer_mode)
public static final int EVENT_SHOW_USB_OVERHEAT_ALARM = 19; // (reason|int) (keyguard|bool)
@@ -122,103 +126,363 @@ public class Events {
public static final int ICON_STATE_MUTE = 2;
public static final int ICON_STATE_VIBRATE = 3;
+ @VisibleForTesting
+ public enum VolumeDialogOpenEvent implements UiEventLogger.UiEventEnum {
+ //TODO zap the lock/unlock distinction
+ INVALID(0),
+ @UiEvent(doc = "The volume dialog was shown because the volume changed")
+ VOLUME_DIALOG_SHOW_VOLUME_CHANGED(128),
+ @UiEvent(doc = "The volume dialog was shown because the volume changed remotely")
+ VOLUME_DIALOG_SHOW_REMOTE_VOLUME_CHANGED(129),
+ @UiEvent(doc = "The volume dialog was shown because the usb high temperature alarm changed")
+ VOLUME_DIALOG_SHOW_USB_TEMP_ALARM_CHANGED(130);
+
+ private final int mId;
+ VolumeDialogOpenEvent(int id) {
+ mId = id;
+ }
+ public int getId() {
+ return mId;
+ }
+ static VolumeDialogOpenEvent fromReasons(int reason) {
+ switch (reason) {
+ case SHOW_REASON_VOLUME_CHANGED:
+ return VOLUME_DIALOG_SHOW_VOLUME_CHANGED;
+ case SHOW_REASON_REMOTE_VOLUME_CHANGED:
+ return VOLUME_DIALOG_SHOW_REMOTE_VOLUME_CHANGED;
+ case SHOW_REASON_USB_OVERHEAD_ALARM_CHANGED:
+ return VOLUME_DIALOG_SHOW_USB_TEMP_ALARM_CHANGED;
+ }
+ return INVALID;
+ }
+ }
+
+ @VisibleForTesting
+ public enum VolumeDialogCloseEvent implements UiEventLogger.UiEventEnum {
+ INVALID(0),
+ @UiEvent(doc = "The volume dialog was dismissed because of a touch outside the dialog")
+ VOLUME_DIALOG_DISMISS_TOUCH_OUTSIDE(134),
+ @UiEvent(doc = "The system asked the volume dialog to close, e.g. for a navigation bar "
+ + "touch, or ActivityManager ACTION_CLOSE_SYSTEM_DIALOGS broadcast.")
+ VOLUME_DIALOG_DISMISS_SYSTEM(135),
+ @UiEvent(doc = "The volume dialog was dismissed because it timed out")
+ VOLUME_DIALOG_DISMISS_TIMEOUT(136),
+ @UiEvent(doc = "The volume dialog was dismissed because the screen turned off")
+ VOLUME_DIALOG_DISMISS_SCREEN_OFF(137),
+ @UiEvent(doc = "The volume dialog was dismissed because the settings icon was clicked")
+ VOLUME_DIALOG_DISMISS_SETTINGS(138),
+ // reserving 139 for DISMISS_REASON_DONE_CLICKED which is currently unused
+ @UiEvent(doc = "The volume dialog was dismissed because the stream no longer exists")
+ VOLUME_DIALOG_DISMISS_STREAM_GONE(140),
+ // reserving 141 for DISMISS_REASON_OUTPUT_CHOOSER which is currently unused
+ @UiEvent(doc = "The volume dialog was dismissed because the usb high temperature alarm "
+ + "changed")
+ VOLUME_DIALOG_DISMISS_USB_TEMP_ALARM_CHANGED(142);
+
+ private final int mId;
+ VolumeDialogCloseEvent(int id) {
+ mId = id;
+ }
+ public int getId() {
+ return mId;
+ }
+
+ static VolumeDialogCloseEvent fromReason(int reason) {
+ switch (reason) {
+ case DISMISS_REASON_TOUCH_OUTSIDE:
+ return VOLUME_DIALOG_DISMISS_TOUCH_OUTSIDE;
+ case DISMISS_REASON_VOLUME_CONTROLLER:
+ return VOLUME_DIALOG_DISMISS_SYSTEM;
+ case DISMISS_REASON_TIMEOUT:
+ return VOLUME_DIALOG_DISMISS_TIMEOUT;
+ case DISMISS_REASON_SCREEN_OFF:
+ return VOLUME_DIALOG_DISMISS_SCREEN_OFF;
+ case DISMISS_REASON_SETTINGS_CLICKED:
+ return VOLUME_DIALOG_DISMISS_SETTINGS;
+ case DISMISS_STREAM_GONE:
+ return VOLUME_DIALOG_DISMISS_STREAM_GONE;
+ case DISMISS_REASON_USB_OVERHEAD_ALARM_CHANGED:
+ return VOLUME_DIALOG_DISMISS_USB_TEMP_ALARM_CHANGED;
+ }
+ return INVALID;
+ }
+ }
+
+ @VisibleForTesting
+ public enum VolumeDialogEvent implements UiEventLogger.UiEventEnum {
+ INVALID(0),
+ @UiEvent(doc = "The volume dialog settings icon was clicked")
+ VOLUME_DIALOG_SETTINGS_CLICK(143),
+ @UiEvent(doc = "The volume dialog details were expanded")
+ VOLUME_DIALOG_EXPAND_DETAILS(144),
+ @UiEvent(doc = "The volume dialog details were collapsed")
+ VOLUME_DIALOG_COLLAPSE_DETAILS(145),
+ @UiEvent(doc = "The active audio stream changed")
+ VOLUME_DIALOG_ACTIVE_STREAM_CHANGED(146),
+ @UiEvent(doc = "The audio stream was muted via icon")
+ VOLUME_DIALOG_MUTE_STREAM(147),
+ @UiEvent(doc = "The audio stream was unmuted via icon")
+ VOLUME_DIALOG_UNMUTE_STREAM(148),
+ @UiEvent(doc = "The audio stream was set to vibrate via icon")
+ VOLUME_DIALOG_TO_VIBRATE_STREAM(149),
+ @UiEvent(doc = "The audio stream was set to non-silent via slider")
+ VOLUME_DIALOG_SLIDER(150),
+ @UiEvent(doc = "The audio stream was set to silent via slider")
+ VOLUME_DIALOG_SLIDER_TO_ZERO(151),
+ @UiEvent(doc = "The audio volume was adjusted to silent via key")
+ VOLUME_KEY_TO_ZERO(152),
+ @UiEvent(doc = "The audio volume was adjusted to non-silent via key")
+ VOLUME_KEY(153),
+ @UiEvent(doc = "The ringer mode was toggled to silent")
+ RINGER_MODE_SILENT(154),
+ @UiEvent(doc = "The ringer mode was toggled to vibrate")
+ RINGER_MODE_VIBRATE(155),
+ @UiEvent(doc = "The ringer mode was toggled to normal")
+ RINGER_MODE_NORMAL(156),
+ @UiEvent(doc = "USB Overheat alarm was raised")
+ USB_OVERHEAT_ALARM(160),
+ @UiEvent(doc = "USB Overheat alarm was dismissed")
+ USB_OVERHEAT_ALARM_DISMISSED(161);
+
+ private final int mId;
+
+ VolumeDialogEvent(int id) {
+ mId = id;
+ }
+
+ public int getId() {
+ return mId;
+ }
+
+ static VolumeDialogEvent fromIconState(int iconState) {
+ switch (iconState) {
+ case ICON_STATE_UNMUTE:
+ return VOLUME_DIALOG_UNMUTE_STREAM;
+ case ICON_STATE_MUTE:
+ return VOLUME_DIALOG_MUTE_STREAM;
+ case ICON_STATE_VIBRATE:
+ return VOLUME_DIALOG_TO_VIBRATE_STREAM;
+ default:
+ return INVALID;
+ }
+ }
+
+ static VolumeDialogEvent fromSliderLevel(int level) {
+ return level == 0 ? VOLUME_DIALOG_SLIDER_TO_ZERO : VOLUME_DIALOG_SLIDER;
+ }
+
+ static VolumeDialogEvent fromKeyLevel(int level) {
+ return level == 0 ? VOLUME_KEY_TO_ZERO : VOLUME_KEY;
+ }
+
+ static VolumeDialogEvent fromRingerMode(int ringerMode) {
+ switch (ringerMode) {
+ case AudioManager.RINGER_MODE_SILENT:
+ return RINGER_MODE_SILENT;
+ case AudioManager.RINGER_MODE_VIBRATE:
+ return RINGER_MODE_VIBRATE;
+ case AudioManager.RINGER_MODE_NORMAL:
+ return RINGER_MODE_NORMAL;
+ default:
+ return INVALID;
+ }
+ }
+ }
+
+ @VisibleForTesting
+ public enum ZenModeEvent implements UiEventLogger.UiEventEnum {
+ INVALID(0),
+ @UiEvent(doc = "Zen (do not disturb) mode was toggled to off")
+ ZEN_MODE_OFF(156),
+ @UiEvent(doc = "Zen (do not disturb) mode was toggled to important interruptions only")
+ ZEN_MODE_IMPORTANT_ONLY(157),
+ @UiEvent(doc = "Zen (do not disturb) mode was toggled to alarms only")
+ ZEN_MODE_ALARMS_ONLY(158),
+ @UiEvent(doc = "Zen (do not disturb) mode was toggled to block all interruptions")
+ ZEN_MODE_NO_INTERRUPTIONS(159);
+
+ private final int mId;
+ ZenModeEvent(int id) {
+ mId = id;
+ }
+ public int getId() {
+ return mId;
+ }
+
+ static ZenModeEvent fromZenMode(int zenMode) {
+ switch (zenMode) {
+ case Global.ZEN_MODE_OFF: return ZEN_MODE_OFF;
+ case Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS: return ZEN_MODE_IMPORTANT_ONLY;
+ case Global.ZEN_MODE_ALARMS: return ZEN_MODE_ALARMS_ONLY;
+ case Global.ZEN_MODE_NO_INTERRUPTIONS: return ZEN_MODE_NO_INTERRUPTIONS;
+ default: return INVALID;
+ }
+ }
+ }
+
public static Callback sCallback;
+ @VisibleForTesting
+ static MetricsLogger sLegacyLogger = new MetricsLogger();
+ @VisibleForTesting
+ static UiEventLogger sUiEventLogger = new UiEventLoggerImpl();
/**
- * Logs an event to the system log and the event log.
+ * Logs an event to the system log, to sCallback if present, and to the logEvent destinations.
* @param tag One of the EVENT_* codes above.
* @param list Any additional event-specific arguments, documented above.
*/
public static void writeEvent(int tag, Object... list) {
- MetricsLogger logger = new MetricsLogger();
final long time = System.currentTimeMillis();
+ Log.i(TAG, logEvent(tag, list));
+ if (sCallback != null) {
+ sCallback.writeEvent(time, tag, list);
+ }
+ }
+
+ /**
+ * Logs an event to the event log and UiEvent (Westworld) logging. Compare writeEvent, which
+ * adds more log destinations.
+ * @param tag One of the EVENT_* codes above.
+ * @param list Any additional event-specific arguments, documented above.
+ * @return String a readable description of the event. Begins "writeEvent <tag_description>"
+ * if the tag is valid.
+ */
+ public static String logEvent(int tag, Object... list) {
+ if (tag >= EVENT_TAGS.length) {
+ return "";
+ }
final StringBuilder sb = new StringBuilder("writeEvent ").append(EVENT_TAGS[tag]);
- if (list != null && list.length > 0) {
- sb.append(" ");
- switch (tag) {
- case EVENT_SHOW_DIALOG:
- logger.visible(MetricsEvent.VOLUME_DIALOG);
- logger.histogram("volume_from_keyguard",
- (Boolean) list[1] ? 1 : 0);
- sb.append(SHOW_REASONS[(Integer) list[0]]).append(" keyguard=").append(list[1]);
- break;
- case EVENT_EXPAND:
- logger.visibility(MetricsEvent.VOLUME_DIALOG_DETAILS,
- (Boolean) list[0]);
- sb.append(list[0]);
- break;
- case EVENT_DISMISS_DIALOG:
- logger.hidden(MetricsEvent.VOLUME_DIALOG);
- sb.append(DISMISS_REASONS[(Integer) list[0]]);
- break;
- case EVENT_ACTIVE_STREAM_CHANGED:
- logger.action(MetricsEvent.ACTION_VOLUME_STREAM,
- (Integer) list[0]);
- sb.append(AudioSystem.streamToString((Integer) list[0]));
- break;
- case EVENT_ICON_CLICK:
- logger.action(MetricsEvent.ACTION_VOLUME_ICON,
- (Integer) list[0]);
- sb.append(AudioSystem.streamToString((Integer) list[0])).append(' ')
- .append(iconStateToString((Integer) list[1]));
- break;
- case EVENT_TOUCH_LEVEL_DONE:
- logger.action(MetricsEvent.ACTION_VOLUME_SLIDER,
- (Integer) list[1]);
- // fall through
- case EVENT_TOUCH_LEVEL_CHANGED:
- case EVENT_LEVEL_CHANGED:
- case EVENT_MUTE_CHANGED:
- sb.append(AudioSystem.streamToString((Integer) list[0])).append(' ')
- .append(list[1]);
- break;
- case EVENT_KEY:
- logger.action(MetricsEvent.ACTION_VOLUME_KEY,
- (Integer) list[0]);
+ // Handle events without extra data
+ if (list == null || list.length == 0) {
+ if (tag == EVENT_SETTINGS_CLICK) {
+ sLegacyLogger.action(MetricsEvent.ACTION_VOLUME_SETTINGS);
+ sUiEventLogger.log(VolumeDialogEvent.VOLUME_DIALOG_SETTINGS_CLICK);
+ }
+ return sb.toString();
+ }
+ // Handle events with extra data. We've established list[0] exists.
+ sb.append(" ");
+ switch (tag) {
+ case EVENT_SHOW_DIALOG:
+ sLegacyLogger.visible(MetricsEvent.VOLUME_DIALOG);
+ if (list.length > 1) {
+ final Integer reason = (Integer) list[0];
+ final Boolean keyguard = (Boolean) list[1];
+ sLegacyLogger.histogram("volume_from_keyguard", keyguard ? 1 : 0);
+ sUiEventLogger.log(VolumeDialogOpenEvent.fromReasons(reason));
+ sb.append(SHOW_REASONS[reason]).append(" keyguard=").append(keyguard);
+ }
+ break;
+ case EVENT_EXPAND: {
+ final Boolean expand = (Boolean) list[0];
+ sLegacyLogger.visibility(MetricsEvent.VOLUME_DIALOG_DETAILS, expand);
+ sUiEventLogger.log(expand ? VolumeDialogEvent.VOLUME_DIALOG_EXPAND_DETAILS
+ : VolumeDialogEvent.VOLUME_DIALOG_COLLAPSE_DETAILS);
+ sb.append(expand);
+ break;
+ }
+ case EVENT_DISMISS_DIALOG: {
+ sLegacyLogger.hidden(MetricsEvent.VOLUME_DIALOG);
+ final Integer reason = (Integer) list[0];
+ sUiEventLogger.log(VolumeDialogCloseEvent.fromReason(reason));
+ sb.append(DISMISS_REASONS[reason]);
+ break;
+ }
+ case EVENT_ACTIVE_STREAM_CHANGED: {
+ final Integer stream = (Integer) list[0];
+ sLegacyLogger.action(MetricsEvent.ACTION_VOLUME_STREAM, stream);
+ sUiEventLogger.log(VolumeDialogEvent.VOLUME_DIALOG_ACTIVE_STREAM_CHANGED);
+ sb.append(AudioSystem.streamToString(stream));
+ break;
+ }
+ case EVENT_ICON_CLICK:
+ if (list.length > 1) {
+ final Integer stream = (Integer) list[0];
+ sLegacyLogger.action(MetricsEvent.ACTION_VOLUME_ICON, stream);
+ final Integer iconState = (Integer) list[1];
+ sUiEventLogger.log(VolumeDialogEvent.fromIconState(iconState));
+ sb.append(AudioSystem.streamToString(stream)).append(' ')
+ .append(iconStateToString(iconState));
+ }
+ break;
+ case EVENT_TOUCH_LEVEL_DONE: // (stream|int) (level|int)
+ if (list.length > 1) {
+ final Integer level = (Integer) list[1];
+ sLegacyLogger.action(MetricsEvent.ACTION_VOLUME_SLIDER, level);
+ sUiEventLogger.log(VolumeDialogEvent.fromSliderLevel(level));
+ }
+ // fall through
+ case EVENT_TOUCH_LEVEL_CHANGED:
+ case EVENT_LEVEL_CHANGED:
+ case EVENT_MUTE_CHANGED: // (stream|int) (level|int)
+ if (list.length > 1) {
sb.append(AudioSystem.streamToString((Integer) list[0])).append(' ')
.append(list[1]);
- break;
- case EVENT_RINGER_TOGGLE:
- logger.action(MetricsEvent.ACTION_VOLUME_RINGER_TOGGLE, (Integer) list[0]);
- break;
- case EVENT_SETTINGS_CLICK:
- logger.action(MetricsEvent.ACTION_VOLUME_SETTINGS);
- break;
- case EVENT_EXTERNAL_RINGER_MODE_CHANGED:
- logger.action(MetricsEvent.ACTION_RINGER_MODE,
- (Integer) list[0]);
- // fall through
- case EVENT_INTERNAL_RINGER_MODE_CHANGED:
- sb.append(ringerModeToString((Integer) list[0]));
- break;
- case EVENT_ZEN_MODE_CHANGED:
- sb.append(zenModeToString((Integer) list[0]));
- break;
- case EVENT_SUPPRESSOR_CHANGED:
- sb.append(list[0]).append(' ').append(list[1]);
- break;
- case EVENT_SHOW_USB_OVERHEAT_ALARM:
- logger.visible(MetricsEvent.POWER_OVERHEAT_ALARM);
- logger.histogram("show_usb_overheat_alarm",
- (Boolean) list[1] ? 1 : 0);
- sb.append(SHOW_REASONS[(Integer) list[0]]).append(" keyguard=").append(list[1]);
- break;
- case EVENT_DISMISS_USB_OVERHEAT_ALARM:
- logger.hidden(MetricsEvent.POWER_OVERHEAT_ALARM);
- logger.histogram("dismiss_usb_overheat_alarm",
- (Boolean) list[1] ? 1 : 0);
- sb.append(DISMISS_REASONS[(Integer) list[0]])
- .append(" keyguard=").append(list[1]);
- break;
- default:
- sb.append(Arrays.asList(list));
- break;
+ }
+ break;
+ case EVENT_KEY: // (stream|int) (lastAudibleStreamVolume)
+ if (list.length > 1) {
+ final Integer stream = (Integer) list[0];
+ sLegacyLogger.action(MetricsEvent.ACTION_VOLUME_KEY, stream);
+ final Integer level = (Integer) list[1];
+ sUiEventLogger.log(VolumeDialogEvent.fromKeyLevel(level));
+ sb.append(AudioSystem.streamToString(stream)).append(' ').append(level);
+ }
+ break;
+ case EVENT_RINGER_TOGGLE: {
+ final Integer ringerMode = (Integer) list[0];
+ sLegacyLogger.action(MetricsEvent.ACTION_VOLUME_RINGER_TOGGLE, ringerMode);
+ sUiEventLogger.log(VolumeDialogEvent.fromRingerMode(ringerMode));
+ sb.append(ringerModeToString(ringerMode));
+ break;
}
+ case EVENT_EXTERNAL_RINGER_MODE_CHANGED: {
+ final Integer ringerMode = (Integer) list[0];
+ sLegacyLogger.action(MetricsEvent.ACTION_RINGER_MODE, ringerMode);
+ }
+ // fall through
+ case EVENT_INTERNAL_RINGER_MODE_CHANGED: {
+ final Integer ringerMode = (Integer) list[0];
+ sb.append(ringerModeToString(ringerMode));
+ break;
+ }
+ case EVENT_ZEN_MODE_CHANGED: {
+ final Integer zenMode = (Integer) list[0];
+ sb.append(zenModeToString(zenMode));
+ sUiEventLogger.log(ZenModeEvent.fromZenMode(zenMode));
+ break;
+ }
+ case EVENT_SUPPRESSOR_CHANGED: // (component|string) (name|string)
+ if (list.length > 1) {
+ sb.append(list[0]).append(' ').append(list[1]);
+ }
+ break;
+ case EVENT_SHOW_USB_OVERHEAT_ALARM:
+ sLegacyLogger.visible(MetricsEvent.POWER_OVERHEAT_ALARM);
+ sUiEventLogger.log(VolumeDialogEvent.USB_OVERHEAT_ALARM);
+ if (list.length > 1) {
+ final Boolean keyguard = (Boolean) list[1];
+ sLegacyLogger.histogram("show_usb_overheat_alarm", keyguard ? 1 : 0);
+ final Integer reason = (Integer) list[0];
+ sb.append(SHOW_REASONS[reason]).append(" keyguard=").append(keyguard);
+ }
+ break;
+ case EVENT_DISMISS_USB_OVERHEAT_ALARM:
+ sLegacyLogger.hidden(MetricsEvent.POWER_OVERHEAT_ALARM);
+ sUiEventLogger.log(VolumeDialogEvent.USB_OVERHEAT_ALARM_DISMISSED);
+ if (list.length > 1) {
+ final Boolean keyguard = (Boolean) list[1];
+ sLegacyLogger.histogram("dismiss_usb_overheat_alarm", keyguard ? 1 : 0);
+ final Integer reason = (Integer) list[0];
+ sb.append(DISMISS_REASONS[reason])
+ .append(" keyguard=").append(keyguard);
+ }
+ break;
+ default:
+ sb.append(Arrays.asList(list));
+ break;
}
- Log.i(TAG, sb.toString());
- if (sCallback != null) {
- sCallback.writeEvent(time, tag, list);
- }
+ return sb.toString();
}
public static void writeState(long time, State state) {
diff --git a/packages/SystemUI/src/com/android/systemui/wm/DisplayLayout.java b/packages/SystemUI/src/com/android/systemui/wm/DisplayLayout.java
new file mode 100644
index 000000000000..264a683f6a3d
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/wm/DisplayLayout.java
@@ -0,0 +1,474 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.wm;
+
+import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
+import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
+import static android.content.res.Configuration.UI_MODE_TYPE_CAR;
+import static android.content.res.Configuration.UI_MODE_TYPE_MASK;
+import static android.os.Process.SYSTEM_UID;
+import static android.provider.Settings.Global.DEVELOPMENT_FORCE_DESKTOP_MODE_ON_EXTERNAL_DISPLAYS;
+import static android.view.Display.FLAG_SHOULD_SHOW_SYSTEM_DECORATIONS;
+import static android.view.Surface.ROTATION_0;
+import static android.view.Surface.ROTATION_270;
+import static android.view.Surface.ROTATION_90;
+
+import android.annotation.NonNull;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.Rect;
+import android.os.SystemProperties;
+import android.provider.Settings;
+import android.util.Size;
+import android.view.Display;
+import android.view.DisplayCutout;
+import android.view.DisplayInfo;
+import android.view.Gravity;
+import android.view.Surface;
+
+import com.android.internal.R;
+
+import java.util.List;
+
+/**
+ * Contains information about the layout-properties of a display. This refers to internal layout
+ * like insets/cutout/rotation. In general, this can be thought of as the System-UI analog to
+ * DisplayPolicy.
+ */
+public class DisplayLayout {
+ // Navigation bar position values
+ private static final int NAV_BAR_LEFT = 1 << 0;
+ private static final int NAV_BAR_RIGHT = 1 << 1;
+ private static final int NAV_BAR_BOTTOM = 1 << 2;
+
+ private int mUiMode;
+ private int mWidth;
+ private int mHeight;
+ private DisplayCutout mCutout;
+ private int mRotation;
+ private int mDensityDpi;
+ private final Rect mNonDecorInsets = new Rect();
+ private final Rect mStableInsets = new Rect();
+ private boolean mHasNavigationBar = false;
+ private boolean mHasStatusBar = false;
+
+ /**
+ * Create empty layout.
+ */
+ public DisplayLayout() {
+ }
+
+ /**
+ * Construct a custom display layout using a DisplayInfo.
+ * @param info
+ * @param res
+ */
+ public DisplayLayout(DisplayInfo info, Resources res, boolean hasNavigationBar,
+ boolean hasStatusBar) {
+ init(info, res, hasNavigationBar, hasStatusBar);
+ }
+
+ /**
+ * Construct a display layout based on a live display.
+ * @param context Used for resources.
+ */
+ public DisplayLayout(@NonNull Context context, @NonNull Display rawDisplay) {
+ final int displayId = rawDisplay.getDisplayId();
+ DisplayInfo info = new DisplayInfo();
+ rawDisplay.getDisplayInfo(info);
+ init(info, context.getResources(), hasNavigationBar(info, context, displayId),
+ hasStatusBar(displayId));
+ }
+
+ public DisplayLayout(DisplayLayout dl) {
+ set(dl);
+ }
+
+ /** sets this DisplayLayout to a copy of another on. */
+ public void set(DisplayLayout dl) {
+ mUiMode = dl.mUiMode;
+ mWidth = dl.mWidth;
+ mHeight = dl.mHeight;
+ mCutout = dl.mCutout;
+ mRotation = dl.mRotation;
+ mDensityDpi = dl.mDensityDpi;
+ mHasNavigationBar = dl.mHasNavigationBar;
+ mHasStatusBar = dl.mHasStatusBar;
+ mNonDecorInsets.set(dl.mNonDecorInsets);
+ mStableInsets.set(dl.mStableInsets);
+ }
+
+ private void init(DisplayInfo info, Resources res, boolean hasNavigationBar,
+ boolean hasStatusBar) {
+ mUiMode = res.getConfiguration().uiMode;
+ mWidth = info.logicalWidth;
+ mHeight = info.logicalHeight;
+ mRotation = info.rotation;
+ mCutout = info.displayCutout;
+ mDensityDpi = info.logicalDensityDpi;
+ mHasNavigationBar = hasNavigationBar;
+ mHasStatusBar = hasStatusBar;
+ recalcInsets(res);
+ }
+
+ private void recalcInsets(Resources res) {
+ computeNonDecorInsets(res, mRotation, mWidth, mHeight, mCutout, mUiMode, mNonDecorInsets,
+ mHasNavigationBar);
+ mStableInsets.set(mNonDecorInsets);
+ if (mHasStatusBar) {
+ convertNonDecorInsetsToStableInsets(res, mStableInsets, mWidth, mHeight, mHasStatusBar);
+ }
+ }
+
+ /**
+ * Apply a rotation to this layout and its parameters.
+ * @param res
+ * @param targetRotation
+ */
+ public void rotateTo(Resources res, @Surface.Rotation int targetRotation) {
+ final int rotationDelta = (targetRotation - mRotation + 4) % 4;
+ final boolean changeOrient = (rotationDelta % 2) != 0;
+
+ final int origWidth = mWidth;
+ final int origHeight = mHeight;
+
+ mRotation = targetRotation;
+ if (changeOrient) {
+ mWidth = origHeight;
+ mHeight = origWidth;
+ }
+
+ if (mCutout != null && !mCutout.isEmpty()) {
+ mCutout = calculateDisplayCutoutForRotation(mCutout, rotationDelta, origWidth,
+ origHeight);
+ }
+
+ recalcInsets(res);
+ }
+
+ /** Get this layout's non-decor insets. */
+ public Rect nonDecorInsets() {
+ return mNonDecorInsets;
+ }
+
+ /** Get this layout's stable insets. */
+ public Rect stableInsets() {
+ return mStableInsets;
+ }
+
+ /** Get this layout's width. */
+ public int width() {
+ return mWidth;
+ }
+
+ /** Get this layout's height. */
+ public int height() {
+ return mHeight;
+ }
+
+ /** Get this layout's display rotation. */
+ public int rotation() {
+ return mRotation;
+ }
+
+ /** Get this layout's display density. */
+ public int densityDpi() {
+ return mDensityDpi;
+ }
+
+ /** Get whether this layout is landscape. */
+ public boolean isLandscape() {
+ return mWidth > mHeight;
+ }
+
+ /** Gets the orientation of this layout */
+ public int getOrientation() {
+ return (mWidth > mHeight) ? ORIENTATION_LANDSCAPE : ORIENTATION_PORTRAIT;
+ }
+
+ /** Gets the calculated stable-bounds for this layout */
+ public void getStableBounds(Rect outBounds) {
+ outBounds.set(0, 0, mWidth, mHeight);
+ outBounds.inset(mStableInsets);
+ }
+
+ /**
+ * Rotates bounds as if parentBounds and bounds are a group. The group is rotated by `delta`
+ * 90-degree counter-clockwise increments. This assumes that parentBounds is at 0,0 and
+ * remains at 0,0 after rotation.
+ *
+ * Only 'bounds' is mutated.
+ */
+ public static void rotateBounds(Rect inOutBounds, Rect parentBounds, int delta) {
+ int rdelta = ((delta % 4) + 4) % 4;
+ int origLeft = inOutBounds.left;
+ switch (rdelta) {
+ case 0:
+ return;
+ case 1:
+ inOutBounds.left = inOutBounds.top;
+ inOutBounds.top = parentBounds.right - inOutBounds.right;
+ inOutBounds.right = inOutBounds.bottom;
+ inOutBounds.bottom = parentBounds.right - origLeft;
+ return;
+ case 2:
+ inOutBounds.left = parentBounds.right - inOutBounds.right;
+ inOutBounds.right = parentBounds.right - origLeft;
+ return;
+ case 3:
+ inOutBounds.left = parentBounds.bottom - inOutBounds.bottom;
+ inOutBounds.bottom = inOutBounds.right;
+ inOutBounds.right = parentBounds.bottom - inOutBounds.top;
+ inOutBounds.top = origLeft;
+ return;
+ }
+ }
+
+ /**
+ * Calculates the stable insets if we already have the non-decor insets.
+ */
+ private static void convertNonDecorInsetsToStableInsets(Resources res, Rect inOutInsets,
+ int displayWidth, int displayHeight, boolean hasStatusBar) {
+ if (!hasStatusBar) {
+ return;
+ }
+ int statusBarHeight = getStatusBarHeight(displayWidth > displayHeight, res);
+ inOutInsets.top = Math.max(inOutInsets.top, statusBarHeight);
+ }
+
+ /**
+ * Calculates the insets for the areas that could never be removed in Honeycomb, i.e. system
+ * bar or button bar.
+ *
+ * @param displayRotation the current display rotation
+ * @param displayWidth the current display width
+ * @param displayHeight the current display height
+ * @param displayCutout the current display cutout
+ * @param outInsets the insets to return
+ */
+ static void computeNonDecorInsets(Resources res, int displayRotation, int displayWidth,
+ int displayHeight, DisplayCutout displayCutout, int uiMode, Rect outInsets,
+ boolean hasNavigationBar) {
+ outInsets.setEmpty();
+
+ // Only navigation bar
+ if (hasNavigationBar) {
+ int position = navigationBarPosition(res, displayWidth, displayHeight, displayRotation);
+ int navBarSize =
+ getNavigationBarSize(res, position, displayWidth > displayHeight, uiMode);
+ if (position == NAV_BAR_BOTTOM) {
+ outInsets.bottom = navBarSize;
+ } else if (position == NAV_BAR_RIGHT) {
+ outInsets.right = navBarSize;
+ } else if (position == NAV_BAR_LEFT) {
+ outInsets.left = navBarSize;
+ }
+ }
+
+ if (displayCutout != null) {
+ outInsets.left += displayCutout.getSafeInsetLeft();
+ outInsets.top += displayCutout.getSafeInsetTop();
+ outInsets.right += displayCutout.getSafeInsetRight();
+ outInsets.bottom += displayCutout.getSafeInsetBottom();
+ }
+ }
+
+ /**
+ * Calculates the stable insets without running a layout.
+ *
+ * @param displayRotation the current display rotation
+ * @param displayWidth the current display width
+ * @param displayHeight the current display height
+ * @param displayCutout the current display cutout
+ * @param outInsets the insets to return
+ */
+ static void computeStableInsets(Resources res, int displayRotation, int displayWidth,
+ int displayHeight, DisplayCutout displayCutout, int uiMode, Rect outInsets,
+ boolean hasNavigationBar, boolean hasStatusBar) {
+ outInsets.setEmpty();
+
+ // Navigation bar and status bar.
+ computeNonDecorInsets(res, displayRotation, displayWidth, displayHeight, displayCutout,
+ uiMode, outInsets, hasNavigationBar);
+ convertNonDecorInsetsToStableInsets(res, outInsets, displayWidth, displayHeight,
+ hasStatusBar);
+ }
+
+ /** Retrieve the statusbar height from resources. */
+ static int getStatusBarHeight(boolean landscape, Resources res) {
+ return landscape ? res.getDimensionPixelSize(
+ com.android.internal.R.dimen.status_bar_height_landscape)
+ : res.getDimensionPixelSize(
+ com.android.internal.R.dimen.status_bar_height_portrait);
+ }
+
+ /** Calculate the DisplayCutout for a particular display size/rotation. */
+ public static DisplayCutout calculateDisplayCutoutForRotation(
+ DisplayCutout cutout, int rotation, int displayWidth, int displayHeight) {
+ if (cutout == null || cutout == DisplayCutout.NO_CUTOUT) {
+ return null;
+ }
+ if (rotation == ROTATION_0) {
+ return computeSafeInsets(
+ cutout, displayWidth, displayHeight);
+ }
+ final boolean rotated = (rotation == ROTATION_90 || rotation == ROTATION_270);
+ Rect[] cutoutRects = computeSafeInsets(cutout, displayWidth, displayHeight)
+ .getBoundingRectsAll();
+ final Rect[] newBounds = new Rect[cutoutRects.length];
+ final Rect displayBounds = new Rect(0, 0, displayWidth, displayHeight);
+ for (int i = 0; i < cutoutRects.length; ++i) {
+ newBounds[i] = new Rect(cutoutRects[i]);
+ rotateBounds(newBounds[i], displayBounds, rotation);
+ }
+ return computeSafeInsets(DisplayCutout.fromBounds(newBounds),
+ rotated ? displayHeight : displayWidth,
+ rotated ? displayWidth : displayHeight);
+ }
+
+ /** Calculate safe insets. */
+ public static DisplayCutout computeSafeInsets(DisplayCutout inner,
+ int displayWidth, int displayHeight) {
+ if (inner == DisplayCutout.NO_CUTOUT || inner.isBoundsEmpty()) {
+ return null;
+ }
+
+ final Size displaySize = new Size(displayWidth, displayHeight);
+ final Rect safeInsets = computeSafeInsets(displaySize, inner);
+ return inner.replaceSafeInsets(safeInsets);
+ }
+
+ private static Rect computeSafeInsets(Size displaySize, DisplayCutout cutout) {
+ if (displaySize.getWidth() < displaySize.getHeight()) {
+ final List<Rect> boundingRects = cutout.replaceSafeInsets(
+ new Rect(0, displaySize.getHeight() / 2, 0, displaySize.getHeight() / 2))
+ .getBoundingRects();
+ int topInset = findInsetForSide(displaySize, boundingRects, Gravity.TOP);
+ int bottomInset = findInsetForSide(displaySize, boundingRects, Gravity.BOTTOM);
+ return new Rect(0, topInset, 0, bottomInset);
+ } else if (displaySize.getWidth() > displaySize.getHeight()) {
+ final List<Rect> boundingRects = cutout.replaceSafeInsets(
+ new Rect(displaySize.getWidth() / 2, 0, displaySize.getWidth() / 2, 0))
+ .getBoundingRects();
+ int leftInset = findInsetForSide(displaySize, boundingRects, Gravity.LEFT);
+ int right = findInsetForSide(displaySize, boundingRects, Gravity.RIGHT);
+ return new Rect(leftInset, 0, right, 0);
+ } else {
+ throw new UnsupportedOperationException("not implemented: display=" + displaySize
+ + " cutout=" + cutout);
+ }
+ }
+
+ private static int findInsetForSide(Size display, List<Rect> boundingRects, int gravity) {
+ int inset = 0;
+ final int size = boundingRects.size();
+ for (int i = 0; i < size; i++) {
+ Rect boundingRect = boundingRects.get(i);
+ switch (gravity) {
+ case Gravity.TOP:
+ if (boundingRect.top == 0) {
+ inset = Math.max(inset, boundingRect.bottom);
+ }
+ break;
+ case Gravity.BOTTOM:
+ if (boundingRect.bottom == display.getHeight()) {
+ inset = Math.max(inset, display.getHeight() - boundingRect.top);
+ }
+ break;
+ case Gravity.LEFT:
+ if (boundingRect.left == 0) {
+ inset = Math.max(inset, boundingRect.right);
+ }
+ break;
+ case Gravity.RIGHT:
+ if (boundingRect.right == display.getWidth()) {
+ inset = Math.max(inset, display.getWidth() - boundingRect.left);
+ }
+ break;
+ default:
+ throw new IllegalArgumentException("unknown gravity: " + gravity);
+ }
+ }
+ return inset;
+ }
+
+ static boolean hasNavigationBar(DisplayInfo info, Context context, int displayId) {
+ if (displayId == Display.DEFAULT_DISPLAY) {
+ // Allow a system property to override this. Used by the emulator.
+ final String navBarOverride = SystemProperties.get("qemu.hw.mainkeys");
+ if ("1".equals(navBarOverride)) {
+ return false;
+ } else if ("0".equals(navBarOverride)) {
+ return true;
+ }
+ return context.getResources().getBoolean(R.bool.config_showNavigationBar);
+ } else {
+ boolean isUntrustedVirtualDisplay = info.type == Display.TYPE_VIRTUAL
+ && info.ownerUid != SYSTEM_UID;
+ final ContentResolver resolver = context.getContentResolver();
+ boolean forceDesktopOnExternal = Settings.Global.getInt(resolver,
+ DEVELOPMENT_FORCE_DESKTOP_MODE_ON_EXTERNAL_DISPLAYS, 0) != 0;
+
+ return ((info.flags & FLAG_SHOULD_SHOW_SYSTEM_DECORATIONS) != 0
+ || (forceDesktopOnExternal && !isUntrustedVirtualDisplay));
+ // TODO(b/142569966): make sure VR2D and DisplayWindowSettings are moved here somehow.
+ }
+ }
+
+ static boolean hasStatusBar(int displayId) {
+ return displayId == Display.DEFAULT_DISPLAY;
+ }
+
+ /** Retrieve navigation bar position from resources based on rotation and size. */
+ public static int navigationBarPosition(Resources res, int displayWidth, int displayHeight,
+ int rotation) {
+ boolean navBarCanMove = displayWidth != displayHeight && res.getBoolean(
+ com.android.internal.R.bool.config_navBarCanMove);
+ if (navBarCanMove && displayWidth > displayHeight) {
+ if (rotation == Surface.ROTATION_90) {
+ return NAV_BAR_RIGHT;
+ } else {
+ return NAV_BAR_LEFT;
+ }
+ }
+ return NAV_BAR_BOTTOM;
+ }
+
+ /** Retrieve navigation bar size from resources based on side/orientation/ui-mode */
+ public static int getNavigationBarSize(Resources res, int navBarSide, boolean landscape,
+ int uiMode) {
+ final boolean carMode = (uiMode & UI_MODE_TYPE_MASK) == UI_MODE_TYPE_CAR;
+ if (carMode) {
+ if (navBarSide == NAV_BAR_BOTTOM) {
+ return res.getDimensionPixelSize(landscape
+ ? R.dimen.navigation_bar_height_landscape_car_mode
+ : R.dimen.navigation_bar_height_car_mode);
+ } else {
+ return res.getDimensionPixelSize(R.dimen.navigation_bar_width_car_mode);
+ }
+ } else {
+ if (navBarSide == NAV_BAR_BOTTOM) {
+ return res.getDimensionPixelSize(landscape
+ ? R.dimen.navigation_bar_height_landscape
+ : R.dimen.navigation_bar_height);
+ } else {
+ return res.getDimensionPixelSize(R.dimen.navigation_bar_width);
+ }
+ }
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/wm/DisplayWindowController.java b/packages/SystemUI/src/com/android/systemui/wm/DisplayWindowController.java
index 19fff79671d4..ae82115ca37e 100644
--- a/packages/SystemUI/src/com/android/systemui/wm/DisplayWindowController.java
+++ b/packages/SystemUI/src/com/android/systemui/wm/DisplayWindowController.java
@@ -16,16 +16,20 @@
package com.android.systemui.wm;
+import android.annotation.Nullable;
+import android.content.Context;
import android.content.res.Configuration;
+import android.hardware.display.DisplayManager;
import android.os.Handler;
import android.os.RemoteException;
import android.util.Slog;
import android.util.SparseArray;
+import android.view.Display;
import android.view.IDisplayWindowListener;
import android.view.IDisplayWindowRotationCallback;
import android.view.IDisplayWindowRotationController;
+import android.view.IWindowManager;
import android.view.WindowContainerTransaction;
-import android.view.WindowManagerGlobal;
import com.android.systemui.dagger.qualifiers.MainHandler;
@@ -45,6 +49,8 @@ public class DisplayWindowController {
private static final String TAG = "DisplayWindowController";
private final Handler mHandler;
+ private final Context mContext;
+ private final IWindowManager mWmService;
private final ArrayList<OnDisplayWindowRotationController> mRotationControllers =
new ArrayList<>();
@@ -76,6 +82,14 @@ public class DisplayWindowController {
}
};
+ /**
+ * Get's a display by id from DisplayManager.
+ */
+ public Display getDisplay(int displayId) {
+ final DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
+ return displayManager.getDisplay(displayId);
+ }
+
private final IDisplayWindowListener mDisplayContainerListener =
new IDisplayWindowListener.Stub() {
@Override
@@ -87,6 +101,10 @@ public class DisplayWindowController {
}
DisplayRecord record = new DisplayRecord();
record.mDisplayId = displayId;
+ Display display = getDisplay(displayId);
+ record.mContext = (displayId == Display.DEFAULT_DISPLAY) ? mContext
+ : mContext.createDisplayContext(display);
+ record.mDisplayLayout = new DisplayLayout(record.mContext, display);
mDisplays.put(displayId, record);
for (int i = 0; i < mDisplayChangedListeners.size(); ++i) {
mDisplayChangedListeners.get(i).onDisplayAdded(displayId);
@@ -105,6 +123,13 @@ public class DisplayWindowController {
+ " display.");
return;
}
+ Display display = getDisplay(displayId);
+ Context perDisplayContext = mContext;
+ if (displayId != Display.DEFAULT_DISPLAY) {
+ perDisplayContext = mContext.createDisplayContext(display);
+ }
+ dr.mContext = perDisplayContext.createConfigurationContext(newConfig);
+ dr.mDisplayLayout = new DisplayLayout(dr.mContext, display);
for (int i = 0; i < mDisplayChangedListeners.size(); ++i) {
mDisplayChangedListeners.get(i).onDisplayConfigurationChanged(
displayId, newConfig);
@@ -127,19 +152,36 @@ public class DisplayWindowController {
};
@Inject
- public DisplayWindowController(@MainHandler Handler mainHandler) {
+ public DisplayWindowController(Context context, @MainHandler Handler mainHandler,
+ IWindowManager wmService) {
mHandler = mainHandler;
+ mContext = context;
+ mWmService = wmService;
try {
- WindowManagerGlobal.getWindowManagerService().registerDisplayWindowListener(
- mDisplayContainerListener);
- WindowManagerGlobal.getWindowManagerService().setDisplayWindowRotationController(
- mDisplayRotationController);
+ mWmService.registerDisplayWindowListener(mDisplayContainerListener);
+ mWmService.setDisplayWindowRotationController(mDisplayRotationController);
} catch (RemoteException e) {
throw new RuntimeException("Unable to register hierarchy listener");
}
}
/**
+ * Gets the DisplayLayout associated with a display.
+ */
+ public @Nullable DisplayLayout getDisplayLayout(int displayId) {
+ final DisplayRecord r = mDisplays.get(displayId);
+ return r != null ? r.mDisplayLayout : null;
+ }
+
+ /**
+ * Gets a display-specific context for a display.
+ */
+ public @Nullable Context getDisplayContext(int displayId) {
+ final DisplayRecord r = mDisplays.get(displayId);
+ return r != null ? r.mContext : null;
+ }
+
+ /**
* Add a display window-container listener. It will get notified whenever a display's
* configuration changes or when displays are added/removed from the WM hierarchy.
*/
@@ -184,6 +226,8 @@ public class DisplayWindowController {
private static class DisplayRecord {
int mDisplayId;
+ Context mContext;
+ DisplayLayout mDisplayLayout;
}
/**
diff --git a/packages/SystemUI/src/com/android/systemui/wm/SystemWindows.java b/packages/SystemUI/src/com/android/systemui/wm/SystemWindows.java
new file mode 100644
index 000000000000..5ec61c3313f0
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/wm/SystemWindows.java
@@ -0,0 +1,330 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.wm;
+
+import static android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
+
+import android.annotation.NonNull;
+import android.content.Context;
+import android.content.res.Configuration;
+import android.graphics.Point;
+import android.graphics.Rect;
+import android.os.Bundle;
+import android.os.ParcelFileDescriptor;
+import android.os.RemoteException;
+import android.util.MergedConfiguration;
+import android.util.Slog;
+import android.util.SparseArray;
+import android.view.Display;
+import android.view.DisplayCutout;
+import android.view.DragEvent;
+import android.view.IWindow;
+import android.view.IWindowManager;
+import android.view.IWindowSession;
+import android.view.IWindowSessionCallback;
+import android.view.InsetsSourceControl;
+import android.view.InsetsState;
+import android.view.SurfaceControl;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.WindowManager;
+import android.view.WindowlessViewRoot;
+import android.view.WindowlessWindowManager;
+
+import com.android.internal.os.IResultReceiver;
+
+import java.util.HashMap;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+/**
+ * Represents the "windowing" layer of the System-UI. This layer allows system-ui components to
+ * place and manipulate windows without talking to WindowManager.
+ */
+@Singleton
+public class SystemWindows {
+ private static final String TAG = "SystemWindows";
+
+ private final SparseArray<PerDisplay> mPerDisplay = new SparseArray<>();
+ final HashMap<View, WindowlessViewRoot> mViewRoots = new HashMap<>();
+ Context mContext;
+ IWindowSession mSession;
+ DisplayWindowController mDisplayController;
+ IWindowManager mWmService;
+
+ private final DisplayWindowController.DisplayWindowListener mDisplayListener =
+ new DisplayWindowController.DisplayWindowListener() {
+ @Override
+ public void onDisplayAdded(int displayId) { }
+
+ @Override
+ public void onDisplayConfigurationChanged(int displayId, Configuration newConfig) {
+ PerDisplay pd = mPerDisplay.get(displayId);
+ if (pd == null) {
+ return;
+ }
+ pd.updateConfiguration(newConfig);
+ }
+
+ @Override
+ public void onDisplayRemoved(int displayId) { }
+ };
+
+ @Inject
+ public SystemWindows(Context context, DisplayWindowController displayController,
+ IWindowManager wmService) {
+ mContext = context;
+ mWmService = wmService;
+ mDisplayController = displayController;
+ mDisplayController.addDisplayWindowListener(mDisplayListener);
+ try {
+ mSession = wmService.openSession(
+ new IWindowSessionCallback.Stub() {
+ @Override
+ public void onAnimatorScaleChanged(float scale) {}
+ });
+ } catch (RemoteException e) {
+ Slog.e(TAG, "Unable to create layer", e);
+ }
+ }
+
+ /**
+ * Adds a view to system-ui window management.
+ */
+ public void addView(View view, WindowManager.LayoutParams attrs, int displayId,
+ int windowType) {
+ PerDisplay pd = mPerDisplay.get(displayId);
+ if (pd == null) {
+ pd = new PerDisplay(displayId);
+ mPerDisplay.put(displayId, pd);
+ }
+ pd.addView(view, attrs, windowType);
+ }
+
+ /**
+ * Removes a view from system-ui window management.
+ * @param view
+ */
+ public void removeView(View view) {
+ WindowlessViewRoot root = mViewRoots.remove(view);
+ root.die();
+ }
+
+ /**
+ * Updates the layout params of a view.
+ */
+ public void updateViewLayout(@NonNull View view, ViewGroup.LayoutParams params) {
+ WindowlessViewRoot root = mViewRoots.get(view);
+ if (root == null || !(params instanceof WindowManager.LayoutParams)) {
+ return;
+ }
+ view.setLayoutParams(params);
+ root.relayout((WindowManager.LayoutParams) params);
+ }
+
+ /**
+ * Adds a root for system-ui window management with no views. Only useful for IME.
+ */
+ public void addRoot(int displayId, int windowType) {
+ PerDisplay pd = mPerDisplay.get(displayId);
+ if (pd == null) {
+ pd = new PerDisplay(displayId);
+ mPerDisplay.put(displayId, pd);
+ }
+ pd.addRoot(windowType);
+ }
+
+ /**
+ * Get the IWindow token for a specific root.
+ *
+ * @param windowType A window type from {@link android.view.WindowManager}.
+ */
+ IWindow getWindow(int displayId, int windowType) {
+ PerDisplay pd = mPerDisplay.get(displayId);
+ if (pd == null) {
+ return null;
+ }
+ return pd.getWindow(windowType);
+ }
+
+ private class PerDisplay {
+ final int mDisplayId;
+ private final SparseArray<SysUiWindowManager> mWwms = new SparseArray<>();
+
+ PerDisplay(int displayId) {
+ mDisplayId = displayId;
+ }
+
+ public void addView(View view, WindowManager.LayoutParams attrs, int windowType) {
+ SysUiWindowManager wwm = addRoot(windowType);
+ if (wwm == null) {
+ Slog.e(TAG, "Unable to create systemui root");
+ return;
+ }
+ final Display display = mDisplayController.getDisplay(mDisplayId);
+ WindowlessViewRoot viewRoot = new WindowlessViewRoot(mContext, display, wwm);
+ attrs.flags |= FLAG_HARDWARE_ACCELERATED;
+ viewRoot.addView(view, attrs);
+ mViewRoots.put(view, viewRoot);
+ }
+
+ SysUiWindowManager addRoot(int windowType) {
+ SysUiWindowManager wwm = mWwms.get(windowType);
+ if (wwm != null) {
+ return wwm;
+ }
+ SurfaceControl rootSurface = null;
+ ContainerWindow win = new ContainerWindow();
+ try {
+ rootSurface = mWmService.addShellRoot(mDisplayId, win, windowType);
+ } catch (RemoteException e) {
+ }
+ if (rootSurface == null) {
+ Slog.e(TAG, "Unable to get root surfacecontrol for systemui");
+ return null;
+ }
+ Context displayContext = mDisplayController.getDisplayContext(mDisplayId);
+ wwm = new SysUiWindowManager(mDisplayId, displayContext, rootSurface, win);
+ mWwms.put(windowType, wwm);
+ return wwm;
+ }
+
+ IWindow getWindow(int windowType) {
+ SysUiWindowManager wwm = mWwms.get(windowType);
+ if (wwm == null) {
+ return null;
+ }
+ return wwm.mContainerWindow;
+ }
+
+ void updateConfiguration(Configuration configuration) {
+ for (int i = 0; i < mWwms.size(); ++i) {
+ mWwms.valueAt(i).updateConfiguration(configuration);
+ }
+ }
+ }
+
+ /**
+ * A subclass of WindowlessWindowManager that provides insets to its viewroots.
+ */
+ public class SysUiWindowManager extends WindowlessWindowManager {
+ final int mDisplayId;
+ ContainerWindow mContainerWindow;
+ public SysUiWindowManager(int displayId, Context ctx, SurfaceControl rootSurface,
+ ContainerWindow container) {
+ super(ctx.getResources().getConfiguration(), rootSurface, null /* hostInputToken */);
+ mContainerWindow = container;
+ mDisplayId = displayId;
+ }
+
+ @Override
+ public int relayout(IWindow window, int seq, WindowManager.LayoutParams attrs,
+ int requestedWidth, int requestedHeight, int viewVisibility, int flags,
+ long frameNumber, Rect outFrame, Rect outOverscanInsets, Rect outContentInsets,
+ Rect outVisibleInsets, Rect outStableInsets,
+ DisplayCutout.ParcelableWrapper cutout, MergedConfiguration mergedConfiguration,
+ SurfaceControl outSurfaceControl, InsetsState outInsetsState) {
+ int res = super.relayout(window, seq, attrs, requestedWidth, requestedHeight,
+ viewVisibility, flags, frameNumber, outFrame, outOverscanInsets,
+ outContentInsets, outVisibleInsets, outStableInsets,
+ cutout, mergedConfiguration, outSurfaceControl, outInsetsState);
+ if (res != 0) {
+ return res;
+ }
+ DisplayLayout dl = mDisplayController.getDisplayLayout(mDisplayId);
+ outStableInsets.set(dl.stableInsets());
+ return 0;
+ }
+
+ void updateConfiguration(Configuration configuration) {
+ setConfiguration(configuration);
+ }
+ }
+
+ class ContainerWindow extends IWindow.Stub {
+ ContainerWindow() {}
+
+ @Override
+ public void resized(Rect frame, Rect contentInsets, Rect visibleInsets, Rect stableInsets,
+ boolean reportDraw, MergedConfiguration newMergedConfiguration, Rect backDropFrame,
+ boolean forceLayout, boolean alwaysConsumeSystemBars, int displayId,
+ DisplayCutout.ParcelableWrapper displayCutout) {}
+
+ @Override
+ public void locationInParentDisplayChanged(Point offset) {}
+
+ @Override
+ public void insetsChanged(InsetsState insetsState) {}
+
+ @Override
+ public void insetsControlChanged(InsetsState insetsState,
+ InsetsSourceControl[] activeControls) {}
+
+ @Override
+ public void showInsets(int types, boolean fromIme) {}
+
+ @Override
+ public void hideInsets(int types, boolean fromIme) {}
+
+ @Override
+ public void moved(int newX, int newY) {}
+
+ @Override
+ public void dispatchAppVisibility(boolean visible) {}
+
+ @Override
+ public void dispatchGetNewSurface() {}
+
+ @Override
+ public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {}
+
+ @Override
+ public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {}
+
+ @Override
+ public void closeSystemDialogs(String reason) {}
+
+ @Override
+ public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
+ boolean sync) {}
+
+ @Override
+ public void dispatchWallpaperCommand(String action, int x, int y,
+ int z, Bundle extras, boolean sync) {}
+
+ /* Drag/drop */
+ @Override
+ public void dispatchDragEvent(DragEvent event) {}
+
+ @Override
+ public void updatePointerIcon(float x, float y) {}
+
+ @Override
+ public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
+ int localValue, int localChanges) {}
+
+ @Override
+ public void dispatchWindowShown() {}
+
+ @Override
+ public void requestAppKeyboardShortcuts(IResultReceiver receiver, int deviceId) {}
+
+ @Override
+ public void dispatchPointerCaptureChanged(boolean hasCapture) {}
+ }
+}
diff --git a/packages/SystemUI/tests/Android.mk b/packages/SystemUI/tests/Android.mk
index 81e2c22d5c4f..e5f56d43f4d7 100644
--- a/packages/SystemUI/tests/Android.mk
+++ b/packages/SystemUI/tests/Android.mk
@@ -32,7 +32,8 @@ LOCAL_MULTILIB := both
LOCAL_JNI_SHARED_LIBRARIES := \
libdexmakerjvmtiagent \
- libmultiplejvmtiagentsinterferenceagent
+ libmultiplejvmtiagentsinterferenceagent \
+ libstaticjvmtiagent
LOCAL_JAVA_LIBRARIES := \
android.test.runner \
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/clock/ClockInfoTest.java b/packages/SystemUI/tests/src/com/android/keyguard/clock/ClockInfoTest.java
index d2b265401cc4..4c0890a73853 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/clock/ClockInfoTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/clock/ClockInfoTest.java
@@ -57,7 +57,7 @@ public final class ClockInfoTest extends SysuiTestCase {
@Test
public void testGetTitle() {
final String title = "title";
- ClockInfo info = ClockInfo.builder().setTitle(title).build();
+ ClockInfo info = ClockInfo.builder().setTitle(() -> title).build();
assertThat(info.getTitle()).isEqualTo(title);
}
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/clock/ClockOptionsProviderTest.java b/packages/SystemUI/tests/src/com/android/keyguard/clock/ClockOptionsProviderTest.java
index 0cd6f9af8ffb..d2832fb98460 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/clock/ClockOptionsProviderTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/clock/ClockOptionsProviderTest.java
@@ -117,12 +117,12 @@ public final class ClockOptionsProviderTest extends SysuiTestCase {
public void testQuery_listOptions() {
mClocks.add(ClockInfo.builder()
.setName("name_a")
- .setTitle("title_a")
+ .setTitle(() -> "title_a")
.setId("id_a")
.build());
mClocks.add(ClockInfo.builder()
.setName("name_b")
- .setTitle("title_b")
+ .setTitle(() -> "title_b")
.setId("id_b")
.build());
Cursor cursor = mProvider.query(mListOptionsUri, null, null, null);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/ForegroundServiceControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/ForegroundServiceControllerTest.java
index 4cb54728a64c..9c9a627fa6e0 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/ForegroundServiceControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/ForegroundServiceControllerTest.java
@@ -46,11 +46,11 @@ import androidx.test.filters.SmallTest;
import com.android.internal.messages.nano.SystemMessageProto;
import com.android.systemui.appops.AppOpsController;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.NotificationEntryListener;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
import com.android.systemui.statusbar.notification.collection.NotifCollection;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import junit.framework.Assert;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/ForegroundServiceNotificationListenerTest.java b/packages/SystemUI/tests/src/com/android/systemui/ForegroundServiceNotificationListenerTest.java
index 212c93dc576d..46a473bd6543 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/ForegroundServiceNotificationListenerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/ForegroundServiceNotificationListenerTest.java
@@ -27,8 +27,8 @@ import android.app.Notification;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import org.junit.Before;
import org.junit.Test;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthBiometricViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthBiometricViewTest.java
index df676376b479..25cc9a304f2a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthBiometricViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthBiometricViewTest.java
@@ -16,6 +16,8 @@
package com.android.systemui.biometrics;
+import static android.hardware.biometrics.BiometricManager.Authenticators;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -24,7 +26,6 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import android.content.Context;
-import android.hardware.biometrics.Authenticator;
import android.hardware.biometrics.BiometricPrompt;
import android.os.Bundle;
import android.test.suitebuilder.annotation.SmallTest;
@@ -292,9 +293,9 @@ public class AuthBiometricViewTest extends SysuiTestCase {
private Bundle buildBiometricPromptBundle(boolean allowDeviceCredential) {
Bundle bundle = new Bundle();
bundle.putCharSequence(BiometricPrompt.KEY_TITLE, "Title");
- int authenticators = Authenticator.TYPE_BIOMETRIC;
+ int authenticators = Authenticators.BIOMETRIC_WEAK;
if (allowDeviceCredential) {
- authenticators |= Authenticator.TYPE_CREDENTIAL;
+ authenticators |= Authenticators.DEVICE_CREDENTIAL;
} else {
bundle.putCharSequence(BiometricPrompt.KEY_NEGATIVE_TEXT, "Negative");
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.java
index 6e438e8e5772..162b16ed3728 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.java
@@ -16,6 +16,8 @@
package com.android.systemui.biometrics;
+import static android.hardware.biometrics.BiometricManager.Authenticators;
+
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@@ -26,7 +28,6 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import android.content.Context;
-import android.hardware.biometrics.Authenticator;
import android.hardware.biometrics.BiometricAuthenticator;
import android.hardware.biometrics.BiometricPrompt;
import android.os.Bundle;
@@ -64,7 +65,7 @@ public class AuthContainerViewTest extends SysuiTestCase {
@Test
public void testActionAuthenticated_sendsDismissedAuthenticated() {
- initializeContainer(Authenticator.TYPE_BIOMETRIC);
+ initializeContainer(Authenticators.BIOMETRIC_WEAK);
mAuthContainer.mBiometricCallback.onAction(
AuthBiometricView.Callback.ACTION_AUTHENTICATED);
@@ -73,7 +74,7 @@ public class AuthContainerViewTest extends SysuiTestCase {
@Test
public void testActionUserCanceled_sendsDismissedUserCanceled() {
- initializeContainer(Authenticator.TYPE_BIOMETRIC);
+ initializeContainer(Authenticators.BIOMETRIC_WEAK);
mAuthContainer.mBiometricCallback.onAction(
AuthBiometricView.Callback.ACTION_USER_CANCELED);
@@ -82,7 +83,7 @@ public class AuthContainerViewTest extends SysuiTestCase {
@Test
public void testActionButtonNegative_sendsDismissedButtonNegative() {
- initializeContainer(Authenticator.TYPE_BIOMETRIC);
+ initializeContainer(Authenticators.BIOMETRIC_WEAK);
mAuthContainer.mBiometricCallback.onAction(
AuthBiometricView.Callback.ACTION_BUTTON_NEGATIVE);
@@ -91,7 +92,7 @@ public class AuthContainerViewTest extends SysuiTestCase {
@Test
public void testActionTryAgain_sendsTryAgain() {
- initializeContainer(Authenticator.TYPE_BIOMETRIC);
+ initializeContainer(Authenticators.BIOMETRIC_WEAK);
mAuthContainer.mBiometricCallback.onAction(
AuthBiometricView.Callback.ACTION_BUTTON_TRY_AGAIN);
@@ -100,7 +101,7 @@ public class AuthContainerViewTest extends SysuiTestCase {
@Test
public void testActionError_sendsDismissedError() {
- initializeContainer(Authenticator.TYPE_BIOMETRIC);
+ initializeContainer(Authenticators.BIOMETRIC_WEAK);
mAuthContainer.mBiometricCallback.onAction(
AuthBiometricView.Callback.ACTION_ERROR);
@@ -110,7 +111,7 @@ public class AuthContainerViewTest extends SysuiTestCase {
@Test
public void testActionUseDeviceCredential_sendsOnDeviceCredentialPressed() {
initializeContainer(
- Authenticator.TYPE_BIOMETRIC | Authenticator.TYPE_CREDENTIAL);
+ Authenticators.BIOMETRIC_WEAK | Authenticators.DEVICE_CREDENTIAL);
mAuthContainer.mBiometricCallback.onAction(
AuthBiometricView.Callback.ACTION_USE_DEVICE_CREDENTIAL);
@@ -125,7 +126,7 @@ public class AuthContainerViewTest extends SysuiTestCase {
@Test
public void testAnimateToCredentialUI_invokesStartTransitionToCredentialUI() {
initializeContainer(
- Authenticator.TYPE_BIOMETRIC | Authenticator.TYPE_CREDENTIAL);
+ Authenticators.BIOMETRIC_WEAK | Authenticators.DEVICE_CREDENTIAL);
mAuthContainer.mBiometricView = mock(AuthBiometricView.class);
mAuthContainer.animateToCredentialUI();
@@ -134,7 +135,7 @@ public class AuthContainerViewTest extends SysuiTestCase {
@Test
public void testShowBiometricUI() {
- initializeContainer(Authenticator.TYPE_BIOMETRIC);
+ initializeContainer(Authenticators.BIOMETRIC_WEAK);
assertNotEquals(null, mAuthContainer.mBiometricView);
@@ -146,7 +147,7 @@ public class AuthContainerViewTest extends SysuiTestCase {
@Test
public void testShowCredentialUI_doesNotInflateBiometricUI() {
- initializeContainer(Authenticator.TYPE_CREDENTIAL);
+ initializeContainer(Authenticators.DEVICE_CREDENTIAL);
mAuthContainer.onAttachedToWindowInternal();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java
index f6375fce8b4e..c0e92e09c486 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java
@@ -16,6 +16,8 @@
package com.android.systemui.biometrics;
+import static android.hardware.biometrics.BiometricManager.Authenticators;
+
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNull;
import static junit.framework.TestCase.assertNotNull;
@@ -38,7 +40,6 @@ import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
-import android.hardware.biometrics.Authenticator;
import android.hardware.biometrics.BiometricAuthenticator;
import android.hardware.biometrics.BiometricConstants;
import android.hardware.biometrics.BiometricPrompt;
@@ -109,28 +110,28 @@ public class AuthControllerTest extends SysuiTestCase {
@Test
public void testSendsReasonUserCanceled_whenDismissedByUserCancel() throws Exception {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
mAuthController.onDismissed(AuthDialogCallback.DISMISSED_USER_CANCELED);
verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_USER_CANCEL);
}
@Test
public void testSendsReasonNegative_whenDismissedByButtonNegative() throws Exception {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
mAuthController.onDismissed(AuthDialogCallback.DISMISSED_BUTTON_NEGATIVE);
verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_NEGATIVE);
}
@Test
public void testSendsReasonConfirmed_whenDismissedByButtonPositive() throws Exception {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
mAuthController.onDismissed(AuthDialogCallback.DISMISSED_BUTTON_POSITIVE);
verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRMED);
}
@Test
public void testSendsReasonConfirmNotRequired_whenDismissedByAuthenticated() throws Exception {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
mAuthController.onDismissed(AuthDialogCallback.DISMISSED_BIOMETRIC_AUTHENTICATED);
verify(mReceiver).onDialogDismissed(
BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRM_NOT_REQUIRED);
@@ -138,14 +139,14 @@ public class AuthControllerTest extends SysuiTestCase {
@Test
public void testSendsReasonError_whenDismissedByError() throws Exception {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
mAuthController.onDismissed(AuthDialogCallback.DISMISSED_ERROR);
verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_ERROR);
}
@Test
public void testSendsReasonServerRequested_whenDismissedByServer() throws Exception {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
mAuthController.onDismissed(AuthDialogCallback.DISMISSED_BY_SYSTEM_SERVER);
verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_SERVER_REQUESTED);
}
@@ -153,7 +154,7 @@ public class AuthControllerTest extends SysuiTestCase {
@Test
public void testSendsReasonCredentialConfirmed_whenDeviceCredentialAuthenticated()
throws Exception {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
mAuthController.onDismissed(AuthDialogCallback.DISMISSED_CREDENTIAL_AUTHENTICATED);
verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_CREDENTIAL_CONFIRMED);
}
@@ -163,20 +164,20 @@ public class AuthControllerTest extends SysuiTestCase {
@Test
public void testShowInvoked_whenSystemRequested()
throws Exception {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
verify(mDialog1).show(any(), any());
}
@Test
public void testOnAuthenticationSucceededInvoked_whenSystemRequested() {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
mAuthController.onBiometricAuthenticated();
verify(mDialog1).onAuthenticationSucceeded();
}
@Test
public void testOnAuthenticationFailedInvoked_whenBiometricRejected() {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
mAuthController.onBiometricError(BiometricAuthenticator.TYPE_NONE,
BiometricConstants.BIOMETRIC_PAUSED_REJECTED,
0 /* vendorCode */);
@@ -189,7 +190,7 @@ public class AuthControllerTest extends SysuiTestCase {
@Test
public void testOnAuthenticationFailedInvoked_whenBiometricTimedOut() {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
final int error = BiometricConstants.BIOMETRIC_ERROR_TIMEOUT;
final int vendorCode = 0;
mAuthController.onBiometricError(BiometricAuthenticator.TYPE_FACE, error, vendorCode);
@@ -202,7 +203,7 @@ public class AuthControllerTest extends SysuiTestCase {
@Test
public void testOnHelpInvoked_whenSystemRequested() {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
final String helpMessage = "help";
mAuthController.onBiometricHelp(helpMessage);
@@ -214,7 +215,7 @@ public class AuthControllerTest extends SysuiTestCase {
@Test
public void testOnErrorInvoked_whenSystemRequested() throws Exception {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
final int error = 1;
final int vendorCode = 0;
mAuthController.onBiometricError(BiometricAuthenticator.TYPE_FACE, error, vendorCode);
@@ -227,7 +228,7 @@ public class AuthControllerTest extends SysuiTestCase {
@Test
public void testErrorLockout_whenCredentialAllowed_AnimatesToCredentialUI() {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
final int error = BiometricConstants.BIOMETRIC_ERROR_LOCKOUT;
final int vendorCode = 0;
@@ -240,7 +241,7 @@ public class AuthControllerTest extends SysuiTestCase {
@Test
public void testErrorLockoutPermanent_whenCredentialAllowed_AnimatesToCredentialUI() {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
final int error = BiometricConstants.BIOMETRIC_ERROR_LOCKOUT_PERMANENT;
final int vendorCode = 0;
@@ -253,7 +254,7 @@ public class AuthControllerTest extends SysuiTestCase {
@Test
public void testErrorLockout_whenCredentialNotAllowed_sendsOnError() {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
final int error = BiometricConstants.BIOMETRIC_ERROR_LOCKOUT;
final int vendorCode = 0;
@@ -266,7 +267,7 @@ public class AuthControllerTest extends SysuiTestCase {
@Test
public void testErrorLockoutPermanent_whenCredentialNotAllowed_sendsOnError() {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
final int error = BiometricConstants.BIOMETRIC_ERROR_LOCKOUT_PERMANENT;
final int vendorCode = 0;
@@ -278,30 +279,24 @@ public class AuthControllerTest extends SysuiTestCase {
}
@Test
- public void testDismissWithoutCallbackInvoked_whenSystemRequested() {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ public void testHideAuthenticationDialog_invokesDismissFromSystemServer() {
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
mAuthController.hideAuthenticationDialog();
verify(mDialog1).dismissFromSystemServer();
- }
- @Test
- public void testClientNotified_whenDismissedBySystemServer() {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
- mAuthController.hideAuthenticationDialog();
- verify(mDialog1).dismissFromSystemServer();
-
- assertNotNull(mAuthController.mCurrentDialog);
- assertNotNull(mAuthController.mReceiver);
+ // In this case, BiometricService sends the error to the client immediately, without
+ // doing a round trip to SystemUI.
+ assertNull(mAuthController.mCurrentDialog);
}
// Corner case tests
@Test
public void testShowNewDialog_beforeOldDialogDismissed_SkipsAnimations() {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
verify(mDialog1).show(any(), any());
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
// First dialog should be dismissed without animation
verify(mDialog1).dismissWithoutCallback(eq(false) /* animate */);
@@ -312,7 +307,7 @@ public class AuthControllerTest extends SysuiTestCase {
@Test
public void testConfigurationPersists_whenOnConfigurationChanged() {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
verify(mDialog1).show(any(), any());
// Return that the UI is in "showing" state
@@ -342,7 +337,7 @@ public class AuthControllerTest extends SysuiTestCase {
@Test
public void testConfigurationPersists_whenBiometricFallbackToCredential() {
- showDialog(Authenticator.TYPE_CREDENTIAL | Authenticator.TYPE_BIOMETRIC,
+ showDialog(Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_WEAK,
BiometricPrompt.TYPE_FACE);
verify(mDialog1).show(any(), any());
@@ -361,14 +356,14 @@ public class AuthControllerTest extends SysuiTestCase {
// Check that the new dialog was initialized to the credential UI.
ArgumentCaptor<Bundle> captor = ArgumentCaptor.forClass(Bundle.class);
verify(mDialog2).show(any(), captor.capture());
- assertEquals(Authenticator.TYPE_CREDENTIAL,
+ assertEquals(Authenticators.DEVICE_CREDENTIAL,
mAuthController.mLastBiometricPromptBundle
.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED));
}
@Test
public void testClientNotified_whenTaskStackChangesDuringAuthentication() throws Exception {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
List<ActivityManager.RunningTaskInfo> tasks = new ArrayList<>();
ActivityManager.RunningTaskInfo taskInfo = mock(ActivityManager.RunningTaskInfo.class);
@@ -388,21 +383,21 @@ public class AuthControllerTest extends SysuiTestCase {
@Test
public void testDoesNotCrash_whenTryAgainPressedAfterDismissal() {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
mAuthController.onDismissed(AuthDialogCallback.DISMISSED_USER_CANCELED);
mAuthController.onTryAgainPressed();
}
@Test
public void testDoesNotCrash_whenDeviceCredentialPressedAfterDismissal() {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
mAuthController.onDismissed(AuthDialogCallback.DISMISSED_USER_CANCELED);
mAuthController.onDeviceCredentialPressed();
}
@Test
public void testActionCloseSystemDialogs_dismissesDialogIfShowing() throws Exception {
- showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+ showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
mAuthController.mBroadcastReceiver.onReceive(mContext, intent);
waitForIdleSync();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/broadcast/BroadcastDispatcherTest.kt b/packages/SystemUI/tests/src/com/android/systemui/broadcast/BroadcastDispatcherTest.kt
index 2242c1adb1d4..42fbf59fef44 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/broadcast/BroadcastDispatcherTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/broadcast/BroadcastDispatcherTest.kt
@@ -93,7 +93,7 @@ class BroadcastDispatcherTest : SysuiTestCase() {
// These should be valid filters
`when`(intentFilter.countActions()).thenReturn(1)
`when`(intentFilterOther.countActions()).thenReturn(1)
- `when`(mockContext.user).thenReturn(user0)
+ setUserMock(mockContext, user0)
}
@Test
@@ -140,6 +140,18 @@ class BroadcastDispatcherTest : SysuiTestCase() {
verify(mockUBRUser1, never()).unregisterReceiver(broadcastReceiver)
}
+ @Test
+ fun testRegisterCurrentAsActualUser() {
+ setUserMock(mockContext, user1)
+ broadcastDispatcher.registerReceiver(broadcastReceiver, intentFilter, mockHandler,
+ UserHandle.CURRENT)
+
+ testableLooper.processAllMessages()
+
+ verify(mockUBRUser1).registerReceiver(capture(argumentCaptor))
+ assertSame(broadcastReceiver, argumentCaptor.value.receiver)
+ }
+
@Test(expected = IllegalArgumentException::class)
fun testFilterMustContainActions() {
val testFilter = IntentFilter()
@@ -186,6 +198,11 @@ class BroadcastDispatcherTest : SysuiTestCase() {
broadcastDispatcher.registerReceiver(broadcastReceiver, testFilter)
}
+ private fun setUserMock(mockContext: Context, user: UserHandle) {
+ `when`(mockContext.user).thenReturn(user)
+ `when`(mockContext.userId).thenReturn(user.identifier)
+ }
+
private class TestBroadcastDispatcher(
context: Context,
mainHandler: Handler,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
index ae43aa2f4118..e0b4b81c368d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
@@ -45,9 +45,7 @@ import android.app.IActivityManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
-import android.content.Intent;
import android.content.res.Resources;
-import android.graphics.drawable.Icon;
import android.hardware.face.FaceManager;
import android.service.notification.ZenModeConfig;
import android.testing.AndroidTestingRunner;
@@ -57,7 +55,6 @@ import android.view.WindowManager;
import androidx.test.filters.SmallTest;
import com.android.internal.colorextraction.ColorExtractor;
-import com.android.systemui.R;
import com.android.systemui.SystemUIFactory;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.colorextraction.SysuiColorExtractor;
@@ -94,8 +91,6 @@ import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import dagger.Lazy;
-
@SmallTest
@RunWith(AndroidTestingRunner.class)
@TestableLooper.RunWithLooper(setAsMainLooper = true)
@@ -153,7 +148,7 @@ public class BubbleControllerTest extends SysuiTestCase {
@Mock
private Resources mResources;
@Mock
- private Lazy<ShadeController> mShadeController;
+ private ShadeController mShadeController;
@Mock
private RemoteInputUriController mRemoteInputUriController;
@@ -263,7 +258,7 @@ public class BubbleControllerTest extends SysuiTestCase {
@Test
public void testRemoveBubble_withDismissedNotif() {
- mEntryListener.onPendingEntryAdded(mRow.getEntry());
+ mEntryListener.onNotificationAdded(mRow.getEntry());
mBubbleController.updateBubble(mRow.getEntry());
assertTrue(mBubbleController.hasBubbles());
@@ -306,7 +301,7 @@ public class BubbleControllerTest extends SysuiTestCase {
assertFalse(mBubbleController.isStackExpanded());
// Mark it as a bubble and add it explicitly
- mEntryListener.onPendingEntryAdded(mRow.getEntry());
+ mEntryListener.onNotificationAdded(mRow.getEntry());
mBubbleController.updateBubble(mRow.getEntry());
// We should have bubbles & their notifs should not be suppressed
@@ -336,8 +331,8 @@ public class BubbleControllerTest extends SysuiTestCase {
@Test
public void testCollapseAfterChangingExpandedBubble() {
// Mark it as a bubble and add it explicitly
- mEntryListener.onPendingEntryAdded(mRow.getEntry());
- mEntryListener.onPendingEntryAdded(mRow2.getEntry());
+ mEntryListener.onNotificationAdded(mRow.getEntry());
+ mEntryListener.onNotificationAdded(mRow2.getEntry());
mBubbleController.updateBubble(mRow.getEntry());
mBubbleController.updateBubble(mRow2.getEntry());
@@ -379,7 +374,7 @@ public class BubbleControllerTest extends SysuiTestCase {
@Test
public void testExpansionRemovesShowInShadeAndDot() {
// Mark it as a bubble and add it explicitly
- mEntryListener.onPendingEntryAdded(mRow.getEntry());
+ mEntryListener.onNotificationAdded(mRow.getEntry());
mBubbleController.updateBubble(mRow.getEntry());
// We should have bubbles & their notifs should not be suppressed
@@ -405,7 +400,7 @@ public class BubbleControllerTest extends SysuiTestCase {
@Test
public void testUpdateWhileExpanded_DoesntChangeShowInShadeAndDot() {
// Mark it as a bubble and add it explicitly
- mEntryListener.onPendingEntryAdded(mRow.getEntry());
+ mEntryListener.onNotificationAdded(mRow.getEntry());
mBubbleController.updateBubble(mRow.getEntry());
// We should have bubbles & their notifs should not be suppressed
@@ -441,8 +436,8 @@ public class BubbleControllerTest extends SysuiTestCase {
@Test
public void testRemoveLastExpandedCollapses() {
// Mark it as a bubble and add it explicitly
- mEntryListener.onPendingEntryAdded(mRow.getEntry());
- mEntryListener.onPendingEntryAdded(mRow2.getEntry());
+ mEntryListener.onNotificationAdded(mRow.getEntry());
+ mEntryListener.onNotificationAdded(mRow2.getEntry());
mBubbleController.updateBubble(mRow.getEntry());
mBubbleController.updateBubble(mRow2.getEntry());
verify(mBubbleStateChangeListener).onHasBubblesChanged(true);
@@ -479,13 +474,13 @@ public class BubbleControllerTest extends SysuiTestCase {
}
@Test
- public void testAutoExpand_FailsNotForeground() {
+ public void testAutoExpand_fails_noFlag() {
assertFalse(mBubbleController.isStackExpanded());
setMetadataFlags(mRow.getEntry(),
Notification.BubbleMetadata.FLAG_AUTO_EXPAND_BUBBLE, false /* enableFlag */);
// Add the auto expand bubble
- mEntryListener.onPendingEntryAdded(mRow.getEntry());
+ mEntryListener.onNotificationAdded(mRow.getEntry());
mBubbleController.updateBubble(mRow.getEntry());
// Expansion shouldn't change
@@ -498,12 +493,12 @@ public class BubbleControllerTest extends SysuiTestCase {
}
@Test
- public void testAutoExpand_SucceedsForeground() {
+ public void testAutoExpand_succeeds_withFlag() {
setMetadataFlags(mRow.getEntry(),
Notification.BubbleMetadata.FLAG_AUTO_EXPAND_BUBBLE, true /* enableFlag */);
// Add the auto expand bubble
- mEntryListener.onPendingEntryAdded(mRow.getEntry());
+ mEntryListener.onNotificationAdded(mRow.getEntry());
mBubbleController.updateBubble(mRow.getEntry());
// Expansion should change
@@ -516,43 +511,57 @@ public class BubbleControllerTest extends SysuiTestCase {
}
@Test
- public void testSuppressNotif_FailsNotForeground() {
+ public void testSuppressNotif_onInitialNotif() {
setMetadataFlags(mRow.getEntry(),
- Notification.BubbleMetadata.FLAG_SUPPRESS_NOTIFICATION, false /* enableFlag */);
+ Notification.BubbleMetadata.FLAG_SUPPRESS_NOTIFICATION, true /* enableFlag */);
// Add the suppress notif bubble
- mEntryListener.onPendingEntryAdded(mRow.getEntry());
+ mEntryListener.onNotificationAdded(mRow.getEntry());
mBubbleController.updateBubble(mRow.getEntry());
- // Should not be suppressed because we weren't forground
- assertFalse(mBubbleController.isBubbleNotificationSuppressedFromShade(
+ // Notif should be suppressed because we were foreground
+ assertTrue(mBubbleController.isBubbleNotificationSuppressedFromShade(
mRow.getEntry().getKey()));
+ // Dot + flyout is hidden because notif is suppressed
+ assertFalse(mBubbleData.getBubbleWithKey(mRow.getEntry().getKey()).showDot());
+ assertFalse(mBubbleData.getBubbleWithKey(mRow.getEntry().getKey()).showFlyout());
+
// # of bubbles should change
verify(mBubbleStateChangeListener).onHasBubblesChanged(true /* hasBubbles */);
}
@Test
- public void testSuppressNotif_SucceedsForeground() {
+ public void testSuppressNotif_onUpdateNotif() {
+ mBubbleController.updateBubble(mRow.getEntry());
+
+ // Should not be suppressed
+ assertFalse(mBubbleController.isBubbleNotificationSuppressedFromShade(
+ mRow.getEntry().getKey()));
+ // Should show dot
+ assertTrue(mBubbleData.getBubbleWithKey(mRow.getEntry().getKey()).showDot());
+
+ // Update to suppress notif
setMetadataFlags(mRow.getEntry(),
Notification.BubbleMetadata.FLAG_SUPPRESS_NOTIFICATION, true /* enableFlag */);
-
- // Add the suppress notif bubble
- mEntryListener.onPendingEntryAdded(mRow.getEntry());
mBubbleController.updateBubble(mRow.getEntry());
- // Notif should be suppressed because we were foreground
+ // Notif should be suppressed
assertTrue(mBubbleController.isBubbleNotificationSuppressedFromShade(
mRow.getEntry().getKey()));
+ // Dot + flyout is hidden because notif is suppressed
+ assertFalse(mBubbleData.getBubbleWithKey(mRow.getEntry().getKey()).showDot());
+ assertFalse(mBubbleData.getBubbleWithKey(mRow.getEntry().getKey()).showFlyout());
// # of bubbles should change
verify(mBubbleStateChangeListener).onHasBubblesChanged(true /* hasBubbles */);
}
+
@Test
public void testExpandStackAndSelectBubble_removedFirst() {
final String key = mRow.getEntry().getKey();
- mEntryListener.onPendingEntryAdded(mRow.getEntry());
+ mEntryListener.onNotificationAdded(mRow.getEntry());
mBubbleController.updateBubble(mRow.getEntry());
// Simulate notification cancellation.
@@ -564,7 +573,7 @@ public class BubbleControllerTest extends SysuiTestCase {
@Test
public void testMarkNewNotificationAsShowInShade() {
- mEntryListener.onPendingEntryAdded(mRow.getEntry());
+ mEntryListener.onNotificationAdded(mRow.getEntry());
assertFalse(mBubbleController.isBubbleNotificationSuppressedFromShade(
mRow.getEntry().getKey()));
@@ -574,7 +583,7 @@ public class BubbleControllerTest extends SysuiTestCase {
@Test
public void testAddNotif_notBubble() {
- mEntryListener.onPendingEntryAdded(mNonBubbleNotifRow.getEntry());
+ mEntryListener.onNotificationAdded(mNonBubbleNotifRow.getEntry());
mEntryListener.onPreEntryUpdated(mNonBubbleNotifRow.getEntry());
verify(mBubbleStateChangeListener, never()).onHasBubblesChanged(anyBoolean());
@@ -619,7 +628,7 @@ public class BubbleControllerTest extends SysuiTestCase {
@Test
public void testRemoveBubble_succeeds_appCancel() {
- mEntryListener.onPendingEntryAdded(mRow.getEntry());
+ mEntryListener.onNotificationAdded(mRow.getEntry());
mBubbleController.updateBubble(mRow.getEntry());
assertTrue(mBubbleController.hasBubbles());
@@ -634,7 +643,7 @@ public class BubbleControllerTest extends SysuiTestCase {
@Test
public void removeBubble_fails_clearAll() {
- mEntryListener.onPendingEntryAdded(mRow.getEntry());
+ mEntryListener.onNotificationAdded(mRow.getEntry());
mBubbleController.updateBubble(mRow.getEntry());
assertTrue(mBubbleController.hasBubbles());
@@ -657,7 +666,7 @@ public class BubbleControllerTest extends SysuiTestCase {
@Test
public void removeBubble_fails_userDismissNotif() {
- mEntryListener.onPendingEntryAdded(mRow.getEntry());
+ mEntryListener.onNotificationAdded(mRow.getEntry());
mBubbleController.updateBubble(mRow.getEntry());
assertTrue(mBubbleController.hasBubbles());
@@ -680,7 +689,7 @@ public class BubbleControllerTest extends SysuiTestCase {
@Test
public void removeBubble_succeeds_userDismissBubble_userDimissNotif() {
- mEntryListener.onPendingEntryAdded(mRow.getEntry());
+ mEntryListener.onNotificationAdded(mRow.getEntry());
mBubbleController.updateBubble(mRow.getEntry());
assertTrue(mBubbleController.hasBubbles());
@@ -705,7 +714,7 @@ public class BubbleControllerTest extends SysuiTestCase {
TestableBubbleController(Context context,
StatusBarWindowController statusBarWindowController,
StatusBarStateController statusBarStateController,
- Lazy<ShadeController> shadeController,
+ ShadeController shadeController,
BubbleData data,
ConfigurationController configurationController,
NotificationInterruptionStateProvider interruptionStateProvider,
@@ -719,6 +728,7 @@ public class BubbleControllerTest extends SysuiTestCase {
data, Runnable::run, configurationController, interruptionStateProvider,
zenModeController, lockscreenUserManager, groupManager, entryManager,
remoteInputUriController);
+ setInflateSynchronously(true);
}
}
@@ -734,17 +744,6 @@ public class BubbleControllerTest extends SysuiTestCase {
}
/**
- * @return basic {@link android.app.Notification.BubbleMetadata.Builder}
- */
- private Notification.BubbleMetadata.Builder getBuilder() {
- Intent target = new Intent(mContext, BubblesTestActivity.class);
- PendingIntent bubbleIntent = PendingIntent.getActivity(mContext, 0, target, 0);
- return new Notification.BubbleMetadata.Builder()
- .setIntent(bubbleIntent)
- .setIcon(Icon.createWithResource(mContext, R.drawable.android));
- }
-
- /**
* Sets the bubble metadata flags for this entry. These flags are normally set by
* NotificationManagerService when the notification is sent, however, these tests do not
* go through that path so we set them explicitly when testing.
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleDataTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleDataTest.java
index 95c7af31865b..c4ae4093b680 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleDataTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleDataTest.java
@@ -39,9 +39,10 @@ import androidx.test.filters.SmallTest;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.bubbles.BubbleData.TimeSource;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.NotificationTestHelper;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
+import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.google.common.collect.ImmutableList;
@@ -84,6 +85,8 @@ public class BubbleDataTest extends SysuiTestCase {
private Bubble mBubbleB2;
private Bubble mBubbleB3;
private Bubble mBubbleC1;
+ private Bubble mBubbleInterruptive;
+ private Bubble mBubbleDismissed;
private BubbleData mBubbleData;
@@ -118,16 +121,20 @@ public class BubbleDataTest extends SysuiTestCase {
modifyRanking(mEntryInterruptive)
.setVisuallyInterruptive(true)
.build();
+ mBubbleInterruptive = new Bubble(mEntryInterruptive);
+ ExpandableNotificationRow row = mNotificationTestHelper.createBubble();
mEntryDismissed = createBubbleEntry(1, "dismissed", "package.d");
+ mEntryDismissed.setRow(row);
+ mBubbleDismissed = new Bubble(mEntryDismissed);
- mBubbleA1 = new Bubble(mContext, mEntryA1);
- mBubbleA2 = new Bubble(mContext, mEntryA2);
- mBubbleA3 = new Bubble(mContext, mEntryA3);
- mBubbleB1 = new Bubble(mContext, mEntryB1);
- mBubbleB2 = new Bubble(mContext, mEntryB2);
- mBubbleB3 = new Bubble(mContext, mEntryB3);
- mBubbleC1 = new Bubble(mContext, mEntryC1);
+ mBubbleA1 = new Bubble(mEntryA1);
+ mBubbleA2 = new Bubble(mEntryA2);
+ mBubbleA3 = new Bubble(mEntryA3);
+ mBubbleB1 = new Bubble(mEntryB1);
+ mBubbleB2 = new Bubble(mEntryB2);
+ mBubbleB3 = new Bubble(mEntryB3);
+ mBubbleC1 = new Bubble(mEntryC1);
mBubbleData = new BubbleData(getContext());
@@ -177,7 +184,7 @@ public class BubbleDataTest extends SysuiTestCase {
mBubbleData.setListener(mListener);
// Test
- mBubbleData.notificationEntryUpdated(mEntryC1, /* suppressFlyout */ true, /* showInShade */
+ mBubbleData.notificationEntryUpdated(mBubbleC1, /* suppressFlyout */ true, /* showInShade */
true);
// Verify
@@ -192,9 +199,8 @@ public class BubbleDataTest extends SysuiTestCase {
mBubbleData.setListener(mListener);
// Test
- mBubbleData.notificationEntryUpdated(mEntryInterruptive, /* suppressFlyout */
- false, /* showInShade */
- true);
+ mBubbleData.notificationEntryUpdated(mBubbleInterruptive,
+ false /* suppressFlyout */, true /* showInShade */);
// Verify
verifyUpdateReceived();
@@ -208,12 +214,12 @@ public class BubbleDataTest extends SysuiTestCase {
mBubbleData.setListener(mListener);
// Test
- mBubbleData.notificationEntryUpdated(mEntryC1, /* suppressFlyout */ false, /* showInShade */
- true);
+ mBubbleData.notificationEntryUpdated(mBubbleC1, false /* suppressFlyout */,
+ true /* showInShade */);
verifyUpdateReceived();
- mBubbleData.notificationEntryUpdated(mEntryC1, /* suppressFlyout */ false, /* showInShade */
- true);
+ mBubbleData.notificationEntryUpdated(mBubbleC1, false /* suppressFlyout */,
+ true /* showInShade */);
verifyUpdateReceived();
// Verify
@@ -225,16 +231,18 @@ public class BubbleDataTest extends SysuiTestCase {
public void sameUpdate_NotInShade_showFlyout() {
// Setup
mBubbleData.setListener(mListener);
- setMetadataFlags(mEntryDismissed,
- Notification.BubbleMetadata.FLAG_SUPPRESS_NOTIFICATION, /* enableFlag */ true);
// Test
- mBubbleData.notificationEntryUpdated(mEntryDismissed, /* suppressFlyout */ false,
- /* showInShade */ false);
+ mBubbleData.notificationEntryUpdated(mBubbleDismissed, false /* suppressFlyout */,
+ true /* showInShade */);
verifyUpdateReceived();
- mBubbleData.notificationEntryUpdated(mEntryDismissed, /* suppressFlyout */
- false, /* showInShade */ false);
+ // Make it look like user swiped away row
+ mEntryDismissed.getRow().dismiss(false /* refocusOnDismiss */);
+ assertThat(mBubbleData.getBubbleWithKey(mBubbleDismissed.getKey()).showInShade()).isFalse();
+
+ mBubbleData.notificationEntryUpdated(mBubbleDismissed, false /* suppressFlyout */,
+ true /* showInShade */);
verifyUpdateReceived();
// Verify
@@ -936,23 +944,6 @@ public class BubbleDataTest extends SysuiTestCase {
}
/**
- * Sets the bubble metadata flags for this entry. These flags are normally set by
- * NotificationManagerService when the notification is sent, however, these tests do not
- * go through that path so we set them explicitly when testing.
- */
- private void setMetadataFlags(NotificationEntry entry, int flag, boolean enableFlag) {
- Notification.BubbleMetadata bubbleMetadata =
- entry.getSbn().getNotification().getBubbleMetadata();
- int flags = bubbleMetadata.getFlags();
- if (enableFlag) {
- flags |= flag;
- } else {
- flags &= ~flag;
- }
- bubbleMetadata.setFlags(flags);
- }
-
- /**
* No ExpandableNotificationRow is required to test BubbleData. This setup is all that is
* required for BubbleData functionality and verification. NotificationTestHelper is used only
* as a convenience to create a Notification w/BubbleMetadata.
@@ -987,7 +978,10 @@ public class BubbleDataTest extends SysuiTestCase {
private void sendUpdatedEntryAtTime(NotificationEntry entry, long postTime) {
setPostTime(entry, postTime);
- mBubbleData.notificationEntryUpdated(entry, false /* suppressFlyout*/,
+ // BubbleController calls this:
+ Bubble b = mBubbleData.getOrCreateBubble(entry);
+ // And then this
+ mBubbleData.notificationEntryUpdated(b, false /* suppressFlyout*/,
true /* showInShade */);
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleTest.java
index 57578611e3f2..3c42fd1cb48d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleTest.java
@@ -28,8 +28,8 @@ import android.testing.TestableLooper;
import androidx.test.filters.SmallTest;
import com.android.systemui.SysuiTestCase;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import org.junit.Before;
import org.junit.Test;
@@ -58,7 +58,7 @@ public class BubbleTest extends SysuiTestCase {
mEntry = new NotificationEntryBuilder()
.setNotification(mNotif)
.build();
- mBubble = new Bubble(mContext, mEntry);
+ mBubble = new Bubble(mEntry);
}
@Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeSensorsTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeSensorsTest.java
index f2665ef3c845..775acdf58c64 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeSensorsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeSensorsTest.java
@@ -33,6 +33,7 @@ import static org.mockito.Mockito.when;
import android.app.AlarmManager;
import android.database.ContentObserver;
+import android.hardware.Sensor;
import android.hardware.display.AmbientDisplayConfiguration;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
@@ -80,6 +81,8 @@ public class DozeSensorsTest extends SysuiTestCase {
private TriggerSensor mTriggerSensor;
@Mock
private DozeLog mDozeLog;
+ @Mock
+ private Sensor mProximitySensor;
private SensorManagerPlugin.SensorEventListener mWakeLockScreenListener;
private TestableLooper mTestableLooper;
private DozeSensors mDozeSensors;
@@ -90,6 +93,7 @@ public class DozeSensorsTest extends SysuiTestCase {
mTestableLooper = TestableLooper.get(this);
when(mAmbientDisplayConfiguration.getWakeLockScreenDebounce()).thenReturn(5000L);
when(mAmbientDisplayConfiguration.alwaysOnEnabled(anyInt())).thenReturn(true);
+ when(mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY)).thenReturn(mProximitySensor);
doAnswer(invocation -> {
((Runnable) invocation.getArgument(0)).run();
return null;
@@ -98,6 +102,14 @@ public class DozeSensorsTest extends SysuiTestCase {
}
@Test
+ public void testRegisterProx() {
+ // We should not register with the sensor manager initially.
+ verify(mSensorManager, never()).registerListener(any(), any(Sensor.class), anyInt());
+ mDozeSensors.setProxListening(true);
+ verify(mSensorManager).registerListener(any(), any(Sensor.class), anyInt());
+ }
+
+ @Test
public void testSensorDebounce() {
mDozeSensors.setListening(true);
@@ -116,6 +128,7 @@ public class DozeSensorsTest extends SysuiTestCase {
@Test
public void testSetListening_firstTrue_registerSettingsObserver() {
+ verify(mSensorManager, never()).registerListener(any(), any(Sensor.class), anyInt());
mDozeSensors.setListening(true);
verify(mTriggerSensor).registerSettingsObserver(any(ContentObserver.class));
@@ -123,6 +136,7 @@ public class DozeSensorsTest extends SysuiTestCase {
@Test
public void testSetListening_twiceTrue_onlyRegisterSettingsObserverOnce() {
+ verify(mSensorManager, never()).registerListener(any(), any(Sensor.class), anyInt());
mDozeSensors.setListening(true);
mDozeSensors.setListening(true);
@@ -131,6 +145,7 @@ public class DozeSensorsTest extends SysuiTestCase {
@Test
public void testSetPaused_doesntPause_sensors() {
+ verify(mSensorManager, never()).registerListener(any(), any(Sensor.class), anyInt());
mDozeSensors.setListening(true);
verify(mTriggerSensor).setListening(eq(true));
@@ -147,8 +162,7 @@ public class DozeSensorsTest extends SysuiTestCase {
TestableDozeSensors() {
super(getContext(), mAlarmManager, mSensorManager, mDozeParameters,
- mAmbientDisplayConfiguration, mWakeLock, mCallback, mProxCallback,
- mAlwaysOnDisplayPolicy, mDozeLog);
+ mAmbientDisplayConfiguration, mWakeLock, mCallback, mProxCallback, mDozeLog);
for (TriggerSensor sensor : mSensors) {
if (sensor instanceof PluginSensor
&& ((PluginSensor) sensor).mPluginSensor.getType()
diff --git a/packages/SystemUI/tests/src/com/android/systemui/glwallpaper/ImageRevealHelperTest.java b/packages/SystemUI/tests/src/com/android/systemui/glwallpaper/ImageRevealHelperTest.java
new file mode 100644
index 000000000000..c827ac7ab963
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/glwallpaper/ImageRevealHelperTest.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.glwallpaper;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.systemui.SysuiTestCase;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@SmallTest
+@RunWith(AndroidTestingRunner.class)
+@TestableLooper.RunWithLooper
+public class ImageRevealHelperTest extends SysuiTestCase {
+
+ static final int ANIMATION_DURATION = 500;
+ ImageRevealHelper mImageRevealHelper;
+ ImageRevealHelper.RevealStateListener mRevealStateListener;
+
+ @Before
+ public void setUp() throws Exception {
+ mRevealStateListener = new ImageRevealHelper.RevealStateListener() {
+ @Override
+ public void onRevealStateChanged() {
+ // no-op
+ }
+
+ @Override
+ public void onRevealStart(boolean animate) {
+ // no-op
+ }
+
+ @Override
+ public void onRevealEnd() {
+ // no-op
+ }
+ };
+ mImageRevealHelper = new ImageRevealHelper(mRevealStateListener);
+ }
+
+ @Test
+ public void testBiometricAuthUnlockAnimateImageRevealState_shouldNotBlackoutScreen() {
+ assertThat(mImageRevealHelper.getReveal()).isEqualTo(0f);
+
+ mImageRevealHelper.updateAwake(true /* awake */, ANIMATION_DURATION);
+ assertThat(mImageRevealHelper.getReveal()).isEqualTo(0f);
+
+ // When device unlock through Biometric, should not show reveal transition
+ mImageRevealHelper.updateAwake(false /* awake */, 0);
+ assertThat(mImageRevealHelper.getReveal()).isEqualTo(1f);
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardViewMediatorTest.java b/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardViewMediatorTest.java
index cbfcfddba5ab..a8a2b33215e5 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardViewMediatorTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardViewMediatorTest.java
@@ -68,15 +68,14 @@ public class KeyguardViewMediatorTest extends SysuiTestCase {
mDependency.injectTestDependency(FalsingManager.class, mFalsingManager);
mDependency.injectTestDependency(KeyguardUpdateMonitor.class, mUpdateMonitor);
- mDependency.injectTestDependency(StatusBarWindowController.class,
- mStatusBarWindowController);
when(mLockPatternUtils.getDevicePolicyManager()).thenReturn(mDevicePolicyManager);
TestableLooper.get(this).runWithLooper(() -> {
mViewMediator = new KeyguardViewMediator(
mContext, mFalsingManager, mLockPatternUtils, mBroadcastDispatcher,
- () -> mStatusBarKeyguardViewManager, mDismissCallbackRegistry);
+ mStatusBarWindowController, () -> mStatusBarKeyguardViewManager,
+ mDismissCallbackRegistry);
});
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/log/RichEventTest.java b/packages/SystemUI/tests/src/com/android/systemui/log/RichEventTest.java
index 2f90641775e8..4a90bb91ca37 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/log/RichEventTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/log/RichEventTest.java
@@ -57,7 +57,7 @@ public class RichEventTest extends SysuiTestCase {
class TestableRichEvent extends RichEvent {
TestableRichEvent(int logLevel, int type, String reason) {
- super(logLevel, type, reason);
+ init(logLevel, type, reason);
}
@Override
diff --git a/packages/SystemUI/tests/src/com/android/systemui/log/SysuiLogTest.java b/packages/SystemUI/tests/src/com/android/systemui/log/SysuiLogTest.java
index 378bba1afda3..e7b317e882ef 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/log/SysuiLogTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/log/SysuiLogTest.java
@@ -35,11 +35,12 @@ import org.mockito.MockitoAnnotations;
@RunWith(AndroidTestingRunner.class)
public class SysuiLogTest extends SysuiTestCase {
private static final String TEST_ID = "TestLogger";
+ private static final String TEST_MSG = "msg";
private static final int MAX_LOGS = 5;
@Mock
private DumpController mDumpController;
- private SysuiLog mSysuiLog;
+ private SysuiLog<Event> mSysuiLog;
@Before
public void setup() {
@@ -48,35 +49,63 @@ public class SysuiLogTest extends SysuiTestCase {
@Test
public void testLogDisabled_noLogsWritten() {
- mSysuiLog = new SysuiLog(mDumpController, TEST_ID, MAX_LOGS, false);
- assertEquals(mSysuiLog.mTimeline, null);
+ mSysuiLog = new TestSysuiLog(mDumpController, TEST_ID, MAX_LOGS, false);
+ assertEquals(null, mSysuiLog.mTimeline);
- mSysuiLog.log(new Event("msg"));
- assertEquals(mSysuiLog.mTimeline, null);
+ mSysuiLog.log(createEvent(TEST_MSG));
+ assertEquals(null, mSysuiLog.mTimeline);
}
@Test
public void testLogEnabled_logWritten() {
- mSysuiLog = new SysuiLog(mDumpController, TEST_ID, MAX_LOGS, true);
- assertEquals(mSysuiLog.mTimeline.size(), 0);
+ mSysuiLog = new TestSysuiLog(mDumpController, TEST_ID, MAX_LOGS, true);
+ assertEquals(0, mSysuiLog.mTimeline.size());
- mSysuiLog.log(new Event("msg"));
- assertEquals(mSysuiLog.mTimeline.size(), 1);
+ mSysuiLog.log(createEvent(TEST_MSG));
+ assertEquals(1, mSysuiLog.mTimeline.size());
}
@Test
public void testMaxLogs() {
- mSysuiLog = new SysuiLog(mDumpController, TEST_ID, MAX_LOGS, true);
+ mSysuiLog = new TestSysuiLog(mDumpController, TEST_ID, MAX_LOGS, true);
assertEquals(mSysuiLog.mTimeline.size(), 0);
- final String msg = "msg";
for (int i = 0; i < MAX_LOGS + 1; i++) {
- mSysuiLog.log(new Event(msg + i));
+ mSysuiLog.log(createEvent(TEST_MSG + i));
}
- assertEquals(mSysuiLog.mTimeline.size(), MAX_LOGS);
+ assertEquals(MAX_LOGS, mSysuiLog.mTimeline.size());
+
+ // check the first message (msg0) was replaced with msg1:
+ assertEquals(TEST_MSG + "1", mSysuiLog.mTimeline.getFirst().getMessage());
+ }
+
+ @Test
+ public void testRecycleLogs() {
+ // GIVEN a SysuiLog with one log
+ mSysuiLog = new TestSysuiLog(mDumpController, TEST_ID, MAX_LOGS, true);
+ Event e = createEvent(TEST_MSG); // msg
+ mSysuiLog.log(e); // Logs: [msg]
+
+ Event recycledEvent = null;
+ // WHEN we add MAX_LOGS after the first log
+ for (int i = 0; i < MAX_LOGS; i++) {
+ recycledEvent = mSysuiLog.log(createEvent(TEST_MSG + i));
+ }
+ // Logs: [msg1, msg2, msg3, msg4]
- // check the first message (msg0) is deleted:
- assertEquals(mSysuiLog.mTimeline.getFirst().getMessage(), msg + "1");
+ // THEN we see the recycledEvent is e
+ assertEquals(e, recycledEvent);
+ }
+
+ private Event createEvent(String msg) {
+ return new Event().init(msg);
+ }
+
+ public class TestSysuiLog extends SysuiLog<Event> {
+ protected TestSysuiLog(DumpController dumpController, String id, int maxLogs,
+ boolean enabled) {
+ super(dumpController, id, maxLogs, enabled, false);
+ }
}
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/QSFragmentTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/QSFragmentTest.java
index 800456228e84..b7e9f074ad9a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/QSFragmentTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/QSFragmentTest.java
@@ -31,6 +31,7 @@ import android.view.View;
import android.widget.FrameLayout;
import androidx.test.filters.SmallTest;
+import androidx.test.filters.Suppress;
import com.android.internal.logging.MetricsLogger;
import com.android.keyguard.CarrierText;
@@ -64,7 +65,7 @@ import java.util.Optional;
@RunWith(AndroidTestingRunner.class)
@RunWithLooper
@SmallTest
-@Ignore
+@Suppress
public class QSFragmentTest extends SysuiBaseFragmentTest {
private MetricsLogger mMockMetricsLogger;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/customize/TileQueryHelperTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/customize/TileQueryHelperTest.java
index 39ce8c1209ac..8a9a7a28efb7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/customize/TileQueryHelperTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/customize/TileQueryHelperTest.java
@@ -120,7 +120,6 @@ public class TileQueryHelperTest extends SysuiTestCase {
).when(mQSTileHost).createTile(anyString());
FakeSystemClock clock = new FakeSystemClock();
- clock.setAutoIncrement(false);
mMainExecutor = new FakeExecutor(clock);
mBgExecutor = new FakeExecutor(clock);
mTileQueryHelper = new TileQueryHelper(mContext, mMainExecutor, mBgExecutor);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tileimpl/QSTileImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/tileimpl/QSTileImplTest.java
index 192d8f8e8226..6bd24b954bda 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/tileimpl/QSTileImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tileimpl/QSTileImplTest.java
@@ -47,6 +47,7 @@ import androidx.test.filters.SmallTest;
import com.android.internal.logging.MetricsLogger;
import com.android.systemui.Dependency;
import com.android.systemui.SysuiTestCase;
+import com.android.systemui.plugins.ActivityStarter;
import com.android.systemui.plugins.qs.QSTile;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.qs.QSHost;
@@ -83,6 +84,7 @@ public class QSTileImplTest extends SysuiTestCase {
String spec = "spec";
mTestableLooper = TestableLooper.get(this);
mDependency.injectTestDependency(Dependency.BG_LOOPER, mTestableLooper.getLooper());
+ mDependency.injectMockDependency(ActivityStarter.class);
mMetricsLogger = mDependency.injectMockDependency(MetricsLogger.class);
mStatusBarStateController =
mDependency.injectMockDependency(StatusBarStateController.class);
@@ -188,6 +190,16 @@ public class QSTileImplTest extends SysuiTestCase {
verify(mTile).handleSetListening(eq(false));
}
+ @Test
+ public void testHandleDestroyClearsHandlerQueue() {
+ when(mTile.getStaleTimeout()).thenReturn(0L);
+ mTile.handleRefreshState(null); // this will add a delayed H.STALE message
+ mTile.handleDestroy();
+
+ mTestableLooper.processAllMessages();
+ verify(mTile, never()).handleStale();
+ }
+
private class TileLogMatcher implements ArgumentMatcher<LogMaker> {
private final int mCategory;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/AlertingNotificationManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/AlertingNotificationManagerTest.java
index c6dd23262b85..a5395e8ebe86 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/AlertingNotificationManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/AlertingNotificationManagerTest.java
@@ -40,6 +40,7 @@ import androidx.test.filters.SmallTest;
import com.android.systemui.R;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import org.junit.Before;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationInterruptionStateProviderTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationInterruptionStateProviderTest.java
index 9b860c9e0ba7..677a6fc6b46e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationInterruptionStateProviderTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationInterruptionStateProviderTest.java
@@ -52,6 +52,7 @@ import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.notification.NotificationFilter;
import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.policy.BatteryController;
import com.android.systemui.statusbar.policy.HeadsUpManager;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationListenerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationListenerTest.java
index 8e6f4d7dd793..d580234725ac 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationListenerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationListenerTest.java
@@ -27,7 +27,8 @@ import android.app.Notification;
import android.app.NotificationManager;
import android.os.Handler;
import android.os.UserHandle;
-import android.service.notification.NotificationListenerService;
+import android.service.notification.NotificationListenerService.Ranking;
+import android.service.notification.NotificationListenerService.RankingMap;
import android.service.notification.StatusBarNotification;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
@@ -35,8 +36,7 @@ import android.testing.TestableLooper;
import androidx.test.filters.SmallTest;
import com.android.systemui.SysuiTestCase;
-import com.android.systemui.statusbar.notification.NotificationEntryManager;
-import com.android.systemui.statusbar.phone.NotificationGroupManager;
+import com.android.systemui.statusbar.NotificationListener.NotifServiceListener;
import org.junit.Before;
import org.junit.Test;
@@ -51,52 +51,39 @@ public class NotificationListenerTest extends SysuiTestCase {
private static final String TEST_PACKAGE_NAME = "test";
private static final int TEST_UID = 0;
- @Mock private NotificationListenerService.RankingMap mRanking;
-
- // Dependency mocks:
- @Mock private NotificationEntryManager mEntryManager;
+ @Mock private NotifServiceListener mServiceListener;
@Mock private NotificationManager mNotificationManager;
- @Mock private NotificationGroupManager mNotificationGroupManager;
private NotificationListener mListener;
private StatusBarNotification mSbn;
+ private RankingMap mRanking = new RankingMap(new Ranking[0]);
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
- mContext.addMockSystemService(NotificationManager.class, mNotificationManager);
- mListener = new NotificationListener(mContext,
- new Handler(TestableLooper.get(this).getLooper()), mEntryManager,
- mNotificationGroupManager);
+ mListener = new NotificationListener(
+ mContext,
+ mNotificationManager,
+ new Handler(TestableLooper.get(this).getLooper()));
mSbn = new StatusBarNotification(TEST_PACKAGE_NAME, TEST_PACKAGE_NAME, 0, null, TEST_UID, 0,
new Notification(), UserHandle.CURRENT, null, 0);
- }
- @Test
- public void testNotificationAddCallsAddNotification() {
- mListener.onNotificationPosted(mSbn, mRanking);
- TestableLooper.get(this).processAllMessages();
- verify(mEntryManager).addNotification(mSbn, mRanking);
+ mListener.addNotificationListener(mServiceListener);
}
@Test
- public void testNotificationUpdateCallsUpdateNotification() {
- when(mEntryManager.getActiveNotificationUnfiltered(mSbn.getKey()))
- .thenReturn(
- new NotificationEntryBuilder()
- .setSbn(mSbn)
- .build());
+ public void testNotificationAddCallsAddNotification() {
mListener.onNotificationPosted(mSbn, mRanking);
TestableLooper.get(this).processAllMessages();
- verify(mEntryManager).updateNotification(mSbn, mRanking);
+ verify(mServiceListener).onNotificationPosted(mSbn, mRanking);
}
@Test
public void testNotificationRemovalCallsRemoveNotification() {
mListener.onNotificationRemoved(mSbn, mRanking);
TestableLooper.get(this).processAllMessages();
- verify(mEntryManager).removeNotification(eq(mSbn.getKey()), eq(mRanking), anyInt());
+ verify(mServiceListener).onNotificationRemoved(eq(mSbn), eq(mRanking), anyInt());
}
@Test
@@ -104,7 +91,7 @@ public class NotificationListenerTest extends SysuiTestCase {
mListener.onNotificationRankingUpdate(mRanking);
TestableLooper.get(this).processAllMessages();
// RankingMap may be modified by plugins.
- verify(mEntryManager).updateNotificationRanking(any());
+ verify(mServiceListener).onNotificationRankingUpdate(any());
}
@Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerTest.java
index ba7b2e2e14c3..3a6accea2b54 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerTest.java
@@ -26,12 +26,14 @@ import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.ActivityManager;
import android.app.KeyguardManager;
+import android.app.Notification;
import android.app.admin.DevicePolicyManager;
import android.content.BroadcastReceiver;
import android.content.Context;
@@ -54,6 +56,7 @@ import com.android.systemui.broadcast.BroadcastDispatcher;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.policy.DeviceProvisionedController;
import com.android.systemui.statusbar.policy.KeyguardStateController;
@@ -198,11 +201,13 @@ public class NotificationLockscreenUserManagerTest extends SysuiTestCase {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.LOCK_SCREEN_SHOW_SILENT_NOTIFICATIONS, 0);
+ final Notification notification = mock(Notification.class);
+ when(notification.isForegroundService()).thenReturn(true);
NotificationEntry entry = new NotificationEntryBuilder()
.setImportance(IMPORTANCE_LOW)
+ .setNotification(notification)
.build();
entry.setBucket(BUCKET_SILENT);
- entry.setIsHighPriority(true);
assertFalse(mLockscreenUserManager.shouldShowOnKeyguard(entry));
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationRemoteInputManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationRemoteInputManagerTest.java
index 8aac1891a5e4..64b10c816da7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationRemoteInputManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationRemoteInputManagerTest.java
@@ -29,6 +29,7 @@ import com.android.systemui.statusbar.NotificationRemoteInputManager.RemoteInput
import com.android.systemui.statusbar.NotificationRemoteInputManager.SmartReplyHistoryExtender;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.systemui.statusbar.phone.StatusBar;
import com.android.systemui.statusbar.policy.RemoteInputUriController;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationTestHelper.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationTestHelper.java
index 88546b9b31a7..c7810be5128e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationTestHelper.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationTestHelper.java
@@ -44,6 +44,7 @@ import com.android.systemui.bubbles.BubbleController;
import com.android.systemui.bubbles.BubblesTestActivity;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.systemui.statusbar.notification.row.NotificationContentInflater.InflationFlag;
import com.android.systemui.statusbar.notification.row.NotificationContentInflaterTest;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationViewHierarchyManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationViewHierarchyManagerTest.java
index 46a8dad8c382..1b05216ac6c8 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationViewHierarchyManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationViewHierarchyManagerTest.java
@@ -47,13 +47,13 @@ import com.android.systemui.statusbar.notification.DynamicPrivacyController;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
import com.android.systemui.statusbar.notification.VisualStabilityManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.logging.NotificationLogger;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.systemui.statusbar.notification.row.ExpandableView;
import com.android.systemui.statusbar.notification.stack.NotificationListContainer;
import com.android.systemui.statusbar.phone.KeyguardBypassController;
import com.android.systemui.statusbar.phone.NotificationGroupManager;
-import com.android.systemui.statusbar.phone.ShadeController;
import com.android.systemui.util.Assert;
import com.google.android.collect.Lists;
@@ -79,7 +79,6 @@ public class NotificationViewHierarchyManagerTest extends SysuiTestCase {
@Mock private NotificationLockscreenUserManager mLockscreenUserManager;
@Mock private NotificationGroupManager mGroupManager;
@Mock private VisualStabilityManager mVisualStabilityManager;
- @Mock private ShadeController mShadeController;
private TestableLooper mTestableLooper;
private Handler mHandler;
@@ -99,14 +98,12 @@ public class NotificationViewHierarchyManagerTest extends SysuiTestCase {
mLockscreenUserManager);
mDependency.injectTestDependency(NotificationGroupManager.class, mGroupManager);
mDependency.injectTestDependency(VisualStabilityManager.class, mVisualStabilityManager);
- mDependency.injectTestDependency(ShadeController.class, mShadeController);
mHelper = new NotificationTestHelper(mContext, mDependency);
mViewHierarchyManager = new NotificationViewHierarchyManager(mContext,
mHandler, mLockscreenUserManager, mGroupManager, mVisualStabilityManager,
mock(StatusBarStateControllerImpl.class), mEntryManager,
- () -> mShadeController,
mock(KeyguardBypassController.class),
mock(BubbleController.class),
mock(DynamicPrivacyController.class));
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/RankingBuilder.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/RankingBuilder.java
index d003b994f6dd..5310dd8a61f9 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/RankingBuilder.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/RankingBuilder.java
@@ -76,6 +76,7 @@ public class RankingBuilder {
mSmartActions = copyList(ranking.getSmartActions());
mSmartReplies = copyList(ranking.getSmartReplies());
mCanBubble = ranking.canBubble();
+ mIsVisuallyInterruptive = ranking.visuallyInterruptive();
}
public Ranking build() {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/SmartReplyControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/SmartReplyControllerTest.java
index 3f624128ac2c..22dc0803339c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/SmartReplyControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/SmartReplyControllerTest.java
@@ -41,6 +41,7 @@ import com.android.systemui.SysuiTestCase;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.phone.StatusBar;
import com.android.systemui.statusbar.policy.RemoteInputUriController;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java
index e0dfe7e66ad5..7f5105ee9310 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java
@@ -66,7 +66,6 @@ import com.android.systemui.InitController;
import com.android.systemui.R;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.NotificationLifetimeExtender;
import com.android.systemui.statusbar.NotificationListener;
import com.android.systemui.statusbar.NotificationLockscreenUserManager;
@@ -80,6 +79,7 @@ import com.android.systemui.statusbar.SmartReplyController;
import com.android.systemui.statusbar.StatusBarIconView;
import com.android.systemui.statusbar.notification.NotificationEntryManager.KeyguardEnvironment;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.collection.NotificationRankingManager;
import com.android.systemui.statusbar.notification.collection.NotificationRowBinder;
import com.android.systemui.statusbar.notification.collection.NotificationRowBinderImpl;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationFilterTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationFilterTest.java
index 7fabb0fee8e2..5aed61b98ad9 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationFilterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationFilterTest.java
@@ -41,11 +41,11 @@ import androidx.test.filters.SmallTest;
import com.android.systemui.ForegroundServiceController;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.NotificationLockscreenUserManager;
import com.android.systemui.statusbar.NotificationTestHelper;
import com.android.systemui.statusbar.notification.NotificationEntryManager.KeyguardEnvironment;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.systemui.statusbar.phone.NotificationGroupManager;
import com.android.systemui.statusbar.phone.ShadeController;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationListControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationListControllerTest.java
index 133d52b4f946..7343e5e9e07d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationListControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationListControllerTest.java
@@ -30,9 +30,9 @@ import androidx.test.filters.SmallTest;
import com.android.internal.statusbar.NotificationVisibility;
import com.android.systemui.R;
import com.android.systemui.SysuiTestCase;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.NotificationLockscreenUserManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.stack.NotificationListContainer;
import com.android.systemui.statusbar.policy.DeviceProvisionedController;
import com.android.systemui.statusbar.policy.DeviceProvisionedController.DeviceProvisionedListener;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/VisualStabilityManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/VisualStabilityManagerTest.java
index 6a4ddc7ec202..9079223649ff 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/VisualStabilityManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/VisualStabilityManagerTest.java
@@ -31,9 +31,9 @@ import android.testing.TestableLooper;
import androidx.test.filters.SmallTest;
import com.android.systemui.SysuiTestCase;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.NotificationPresenter;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import org.junit.Before;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/GroupEntryTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/GroupEntryTest.java
new file mode 100644
index 000000000000..a06d6c1e593b
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/GroupEntryTest.java
@@ -0,0 +1,148 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.statusbar.notification.collection;
+
+import static android.app.NotificationManager.IMPORTANCE_HIGH;
+import static android.app.NotificationManager.IMPORTANCE_MIN;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import android.testing.AndroidTestingRunner;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.systemui.SysuiTestCase;
+import com.android.systemui.statusbar.RankingBuilder;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@SmallTest
+@RunWith(AndroidTestingRunner.class)
+public class GroupEntryTest extends SysuiTestCase {
+ @Test
+ public void testIsHighPriority_addChild() {
+ // GIVEN a GroupEntry with a lowPrioritySummary and no children
+ final GroupEntry parentEntry = new GroupEntry("test_group_key");
+ final NotificationEntry lowPrioritySummary = createNotifEntry(false);
+ setSummary(parentEntry, lowPrioritySummary);
+ assertFalse(parentEntry.isHighPriority());
+
+ // WHEN we add a high priority child and invalidate derived members
+ addChild(parentEntry, createNotifEntry(true));
+ parentEntry.invalidateDerivedMembers();
+
+ // THEN the GroupEntry's priority is updated to high even though the summary is still low
+ // priority
+ assertTrue(parentEntry.isHighPriority());
+ assertFalse(lowPrioritySummary.isHighPriority());
+ }
+
+ @Test
+ public void testIsHighPriority_clearChildren() {
+ // GIVEN a GroupEntry with a lowPrioritySummary and high priority children
+ final GroupEntry parentEntry = new GroupEntry("test_group_key");
+ setSummary(parentEntry, createNotifEntry(false));
+ addChild(parentEntry, createNotifEntry(true));
+ addChild(parentEntry, createNotifEntry(true));
+ addChild(parentEntry, createNotifEntry(true));
+ assertTrue(parentEntry.isHighPriority());
+
+ // WHEN we clear the children and invalidate derived members
+ parentEntry.clearChildren();
+ parentEntry.invalidateDerivedMembers();
+
+ // THEN the parentEntry isn't high priority anymore
+ assertFalse(parentEntry.isHighPriority());
+ }
+
+ @Test
+ public void testIsHighPriority_summaryUpdated() {
+ // GIVEN a GroupEntry with a lowPrioritySummary and no children
+ final GroupEntry parentEntry = new GroupEntry("test_group_key");
+ final NotificationEntry lowPrioritySummary = createNotifEntry(false);
+ setSummary(parentEntry, lowPrioritySummary);
+ assertFalse(parentEntry.isHighPriority());
+
+ // WHEN the summary changes to high priority and invalidates its derived members
+ lowPrioritySummary.setRanking(
+ new RankingBuilder()
+ .setKey(lowPrioritySummary.getKey())
+ .setImportance(IMPORTANCE_HIGH)
+ .build());
+ lowPrioritySummary.invalidateDerivedMembers();
+ assertTrue(lowPrioritySummary.isHighPriority());
+
+ // THEN the GroupEntry's priority is updated to high
+ assertTrue(parentEntry.isHighPriority());
+ }
+
+ @Test
+ public void testIsHighPriority_checkChildrenToCalculatePriority() {
+ // GIVEN:
+ // GroupEntry = parentEntry, summary = lowPrioritySummary
+ // NotificationEntry = lowPriorityChild
+ // NotificationEntry = highPriorityChild
+ final GroupEntry parentEntry = new GroupEntry("test_group_key");
+ setSummary(parentEntry, createNotifEntry(false));
+ addChild(parentEntry, createNotifEntry(false));
+ addChild(parentEntry, createNotifEntry(true));
+
+ // THEN the GroupEntry parentEntry is high priority since it has a high priority child
+ assertTrue(parentEntry.isHighPriority());
+ }
+
+ @Test
+ public void testIsHighPriority_childEntryRankingUpdated() {
+ // GIVEN:
+ // GroupEntry = parentEntry, summary = lowPrioritySummary
+ // NotificationEntry = lowPriorityChild
+ final GroupEntry parentEntry = new GroupEntry("test_group_key");
+ final NotificationEntry lowPriorityChild = createNotifEntry(false);
+ setSummary(parentEntry, createNotifEntry(false));
+ addChild(parentEntry, lowPriorityChild);
+
+ // WHEN the child entry ranking changes to high priority and invalidates its derived members
+ lowPriorityChild.setRanking(
+ new RankingBuilder()
+ .setKey(lowPriorityChild.getKey())
+ .setImportance(IMPORTANCE_HIGH)
+ .build());
+ lowPriorityChild.invalidateDerivedMembers();
+
+ // THEN the parent entry's high priority value is updated - but not the parent's summary
+ assertTrue(parentEntry.isHighPriority());
+ assertFalse(parentEntry.getSummary().isHighPriority());
+ }
+
+ private NotificationEntry createNotifEntry(boolean highPriority) {
+ return new NotificationEntryBuilder()
+ .setImportance(highPriority ? IMPORTANCE_HIGH : IMPORTANCE_MIN)
+ .build();
+ }
+
+ private void setSummary(GroupEntry parent, NotificationEntry summary) {
+ parent.setSummary(summary);
+ summary.setParent(parent);
+ }
+
+ private void addChild(GroupEntry parent, NotificationEntry child) {
+ parent.addChild(child);
+ child.setParent(parent);
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotifCollectionTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotifCollectionTest.java
index e1beb34db6bd..0dcd25300633 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotifCollectionTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotifCollectionTest.java
@@ -48,7 +48,6 @@ import androidx.test.filters.SmallTest;
import com.android.internal.statusbar.IStatusBarService;
import com.android.internal.statusbar.NotificationVisibility;
import com.android.systemui.SysuiTestCase;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.NotificationListener;
import com.android.systemui.statusbar.NotificationListener.NotifServiceListener;
import com.android.systemui.statusbar.RankingBuilder;
@@ -99,7 +98,7 @@ public class NotifCollectionTest extends SysuiTestCase {
// Capture the listener object that the collection registers with the listener service so
// we can simulate listener service events in tests below
- verify(mListenerService).setDownstreamListener(mListenerCaptor.capture());
+ verify(mListenerService).addNotificationListener(mListenerCaptor.capture());
mServiceListener = checkNotNull(mListenerCaptor.getValue());
mNoMan = new NoManSimulator(mServiceListener);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotifListBuilderImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotifListBuilderImplTest.java
index a25af84ca28e..9f90396e08d5 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotifListBuilderImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotifListBuilderImplTest.java
@@ -28,6 +28,7 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
@@ -38,7 +39,6 @@ import android.util.ArrayMap;
import androidx.test.filters.SmallTest;
import com.android.systemui.SysuiTestCase;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.collection.NotifListBuilderImpl.OnRenderListListener;
import com.android.systemui.statusbar.notification.collection.listbuilder.OnBeforeRenderListListener;
import com.android.systemui.statusbar.notification.collection.listbuilder.OnBeforeSortListener;
@@ -47,6 +47,7 @@ import com.android.systemui.statusbar.notification.collection.listbuilder.plugga
import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.NotifFilter;
import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.NotifPromoter;
import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.SectionsProvider;
+import com.android.systemui.statusbar.notification.logging.NotifLog;
import com.android.systemui.util.Assert;
import com.android.systemui.util.time.FakeSystemClock;
@@ -76,6 +77,7 @@ public class NotifListBuilderImplTest extends SysuiTestCase {
private NotifListBuilderImpl mListBuilder;
private FakeSystemClock mSystemClock = new FakeSystemClock();
+ @Mock private NotifLog mNotifLog;
@Mock private NotifCollection mNotifCollection;
@Spy private OnBeforeTransformGroupsListener mOnBeforeTransformGroupsListener;
@Spy private OnBeforeSortListener mOnBeforeSortListener;
@@ -97,7 +99,7 @@ public class NotifListBuilderImplTest extends SysuiTestCase {
MockitoAnnotations.initMocks(this);
Assert.sMainLooper = TestableLooper.get(this).getLooper();
- mListBuilder = new NotifListBuilderImpl(mSystemClock);
+ mListBuilder = new NotifListBuilderImpl(mSystemClock, mNotifLog);
mListBuilder.setOnRenderListListener(mOnRenderListListener);
mListBuilder.attach(mNotifCollection);
@@ -334,7 +336,7 @@ public class NotifListBuilderImplTest extends SysuiTestCase {
// GIVEN a notification that is initially added to the list
PackageFilter filter = new PackageFilter(PACKAGE_2);
filter.setEnabled(false);
- mListBuilder.addFilter(filter);
+ mListBuilder.addPreGroupFilter(filter);
addNotif(0, PACKAGE_1);
addNotif(1, PACKAGE_2);
@@ -371,24 +373,54 @@ public class NotifListBuilderImplTest extends SysuiTestCase {
notif(2)
);
- // THEN the list of newly visible entries doesn't contain the summary or the group
- assertEquals(
- Arrays.asList(
- mEntrySet.get(0),
- mEntrySet.get(2)),
- listener.newlyVisibleEntries
- );
-
// THEN the summary has a null parent and an unset firstAddedIteration
assertNull(mEntrySet.get(1).getParent());
assertEquals(-1, mEntrySet.get(1).mFirstAddedIteration);
}
@Test
- public void testNotifsAreFiltered() {
+ public void testPreGroupNotifsAreFiltered() {
+ // GIVEN a PreGroupNotifFilter and PreRenderFilter that filters out the same package
+ NotifFilter preGroupFilter = spy(new PackageFilter(PACKAGE_2));
+ NotifFilter preRenderFilter = spy(new PackageFilter(PACKAGE_2));
+ mListBuilder.addPreGroupFilter(preGroupFilter);
+ mListBuilder.addPreRenderFilter(preRenderFilter);
+
+ // WHEN the pipeline is kicked off on a list of notifs
+ addNotif(0, PACKAGE_1);
+ addNotif(1, PACKAGE_2);
+ addNotif(2, PACKAGE_3);
+ addNotif(3, PACKAGE_2);
+ dispatchBuild();
+
+ // THEN the preGroupFilter is called on each notif in the original set
+ verify(preGroupFilter).shouldFilterOut(eq(mEntrySet.get(0)), anyLong());
+ verify(preGroupFilter).shouldFilterOut(eq(mEntrySet.get(1)), anyLong());
+ verify(preGroupFilter).shouldFilterOut(eq(mEntrySet.get(2)), anyLong());
+ verify(preGroupFilter).shouldFilterOut(eq(mEntrySet.get(3)), anyLong());
+
+ // THEN the preRenderFilter is only called on the notifications not already filtered out
+ verify(preRenderFilter).shouldFilterOut(eq(mEntrySet.get(0)), anyLong());
+ verify(preRenderFilter, never()).shouldFilterOut(eq(mEntrySet.get(1)), anyLong());
+ verify(preRenderFilter).shouldFilterOut(eq(mEntrySet.get(2)), anyLong());
+ verify(preRenderFilter, never()).shouldFilterOut(eq(mEntrySet.get(3)), anyLong());
+
+ // THEN the final list doesn't contain any filtered-out notifs
+ verifyBuiltList(
+ notif(0),
+ notif(2)
+ );
+
+ // THEN each filtered notif records the NotifFilter that did it
+ assertEquals(preGroupFilter, mEntrySet.get(1).mExcludingFilter);
+ assertEquals(preGroupFilter, mEntrySet.get(3).mExcludingFilter);
+ }
+
+ @Test
+ public void testPreRenderNotifsAreFiltered() {
// GIVEN a NotifFilter that filters out a specific package
NotifFilter filter1 = spy(new PackageFilter(PACKAGE_2));
- mListBuilder.addFilter(filter1);
+ mListBuilder.addPreRenderFilter(filter1);
// WHEN the pipeline is kicked off on a list of notifs
addNotif(0, PACKAGE_1);
@@ -419,8 +451,8 @@ public class NotifListBuilderImplTest extends SysuiTestCase {
// GIVEN two notif filters
NotifFilter filter1 = spy(new PackageFilter(PACKAGE_2));
NotifFilter filter2 = spy(new PackageFilter(PACKAGE_5));
- mListBuilder.addFilter(filter1);
- mListBuilder.addFilter(filter2);
+ mListBuilder.addPreGroupFilter(filter1);
+ mListBuilder.addPreGroupFilter(filter2);
// WHEN the pipeline is kicked off on a list of notifs
addNotif(0, PACKAGE_1);
@@ -520,7 +552,7 @@ public class NotifListBuilderImplTest extends SysuiTestCase {
public void testNotifsAreSectioned() {
// GIVEN a filter that removes all PACKAGE_4 notifs and a SectionsProvider that divides
// notifs based on package name
- mListBuilder.addFilter(new PackageFilter(PACKAGE_4));
+ mListBuilder.addPreGroupFilter(new PackageFilter(PACKAGE_4));
final SectionsProvider sectionsProvider = spy(new PackageSectioner());
mListBuilder.setSectionsProvider(sectionsProvider);
@@ -594,17 +626,19 @@ public class NotifListBuilderImplTest extends SysuiTestCase {
@Test
public void testListenersAndPluggablesAreFiredInOrder() {
// GIVEN a bunch of registered listeners and pluggables
- NotifFilter filter = spy(new PackageFilter(PACKAGE_1));
+ NotifFilter preGroupFilter = spy(new PackageFilter(PACKAGE_1));
NotifPromoter promoter = spy(new IdPromoter(3));
PackageSectioner sectioner = spy(new PackageSectioner());
NotifComparator comparator = spy(new HypeComparator(PACKAGE_4));
- mListBuilder.addFilter(filter);
+ NotifFilter preRenderFilter = spy(new PackageFilter(PACKAGE_5));
+ mListBuilder.addPreGroupFilter(preGroupFilter);
mListBuilder.addOnBeforeTransformGroupsListener(mOnBeforeTransformGroupsListener);
mListBuilder.addPromoter(promoter);
mListBuilder.addOnBeforeSortListener(mOnBeforeSortListener);
mListBuilder.setComparators(Collections.singletonList(comparator));
mListBuilder.setSectionsProvider(sectioner);
mListBuilder.addOnBeforeRenderListListener(mOnBeforeRenderListListener);
+ mListBuilder.addPreRenderFilter(preRenderFilter);
// WHEN a few new notifs are added
addNotif(0, PACKAGE_1);
@@ -618,25 +652,28 @@ public class NotifListBuilderImplTest extends SysuiTestCase {
// THEN the pluggables and listeners are called in order
InOrder inOrder = inOrder(
- filter,
+ preGroupFilter,
mOnBeforeTransformGroupsListener,
promoter,
mOnBeforeSortListener,
sectioner,
comparator,
+ preRenderFilter,
mOnBeforeRenderListListener,
mOnRenderListListener);
- inOrder.verify(filter, atLeastOnce())
+ inOrder.verify(preGroupFilter, atLeastOnce())
.shouldFilterOut(any(NotificationEntry.class), anyLong());
inOrder.verify(mOnBeforeTransformGroupsListener)
- .onBeforeTransformGroups(anyList(), anyList());
+ .onBeforeTransformGroups(anyList());
inOrder.verify(promoter, atLeastOnce())
.shouldPromoteToTopLevel(any(NotificationEntry.class));
inOrder.verify(mOnBeforeSortListener).onBeforeSort(anyList());
inOrder.verify(sectioner, atLeastOnce()).getSection(any(ListEntry.class));
inOrder.verify(comparator, atLeastOnce())
.compare(any(ListEntry.class), any(ListEntry.class));
+ inOrder.verify(preRenderFilter, atLeastOnce())
+ .shouldFilterOut(any(NotificationEntry.class), anyLong());
inOrder.verify(mOnBeforeRenderListListener).onBeforeRenderList(anyList());
inOrder.verify(mOnRenderListListener).onRenderList(anyList());
}
@@ -649,7 +686,7 @@ public class NotifListBuilderImplTest extends SysuiTestCase {
SectionsProvider sectionsProvider = new PackageSectioner();
NotifComparator hypeComparator = new HypeComparator(PACKAGE_2);
- mListBuilder.addFilter(packageFilter);
+ mListBuilder.addPreGroupFilter(packageFilter);
mListBuilder.addPromoter(idPromoter);
mListBuilder.setSectionsProvider(sectionsProvider);
mListBuilder.setComparators(Collections.singletonList(hypeComparator));
@@ -685,12 +722,11 @@ public class NotifListBuilderImplTest extends SysuiTestCase {
NotifFilter filter1 = spy(new PackageFilter(PACKAGE_5));
NotifFilter filter2 = spy(new PackageFilter(PACKAGE_5));
NotifFilter filter3 = spy(new PackageFilter(PACKAGE_5));
- mListBuilder.addFilter(filter1);
- mListBuilder.addFilter(filter2);
- mListBuilder.addFilter(filter3);
+ mListBuilder.addPreGroupFilter(filter1);
+ mListBuilder.addPreGroupFilter(filter2);
+ mListBuilder.addPreGroupFilter(filter3);
// GIVEN the SystemClock is set to a particular time:
- mSystemClock.setAutoIncrement(true);
mSystemClock.setUptimeMillis(47);
// WHEN the pipeline is kicked off on a list of notifs
@@ -708,13 +744,13 @@ public class NotifListBuilderImplTest extends SysuiTestCase {
}
@Test
- public void testNewlyAddedEntries() {
+ public void testGroupTransformEntries() {
// GIVEN a registered OnBeforeTransformGroupsListener
RecordingOnBeforeTransformGroupsListener listener =
spy(new RecordingOnBeforeTransformGroupsListener());
mListBuilder.addOnBeforeTransformGroupsListener(listener);
- // Given some new notifs
+ // GIVEN some new notifs
addNotif(0, PACKAGE_1);
addGroupChild(1, PACKAGE_2, GROUP_1);
addGroupSummary(2, PACKAGE_2, GROUP_1);
@@ -742,27 +778,18 @@ public class NotifListBuilderImplTest extends SysuiTestCase {
mEntrySet.get(0),
mBuiltList.get(1),
mEntrySet.get(4)
- ),
- Arrays.asList(
- mEntrySet.get(0),
- mEntrySet.get(1),
- mBuiltList.get(1),
- mEntrySet.get(2),
- mEntrySet.get(3),
- mEntrySet.get(4),
- mEntrySet.get(5)
)
);
}
@Test
- public void testNewlyAddedEntriesOnSecondRun() {
+ public void testGroupTransformEntriesOnSecondRun() {
// GIVEN a registered OnBeforeTransformGroupsListener
RecordingOnBeforeTransformGroupsListener listener =
spy(new RecordingOnBeforeTransformGroupsListener());
mListBuilder.addOnBeforeTransformGroupsListener(listener);
- // Given some notifs that have already been added (two of which are in malformed groups)
+ // GIVEN some notifs that have already been added (two of which are in malformed groups)
addNotif(0, PACKAGE_1);
addGroupChild(1, PACKAGE_2, GROUP_1);
addGroupChild(2, PACKAGE_3, GROUP_2);
@@ -798,13 +825,6 @@ public class NotifListBuilderImplTest extends SysuiTestCase {
mEntrySet.get(1),
mBuiltList.get(2),
mEntrySet.get(7)
- ),
- Arrays.asList(
- mBuiltList.get(2),
- mEntrySet.get(4),
- mEntrySet.get(5),
- mEntrySet.get(6),
- mEntrySet.get(7)
)
);
}
@@ -841,19 +861,18 @@ public class NotifListBuilderImplTest extends SysuiTestCase {
}
@Test(expected = IllegalStateException.class)
- public void testOutOfOrderFilterInvalidationThrows() {
- // GIVEN a NotifFilter that gets invalidated during the grouping stage
+ public void testOutOfOrderPreGroupFilterInvalidationThrows() {
+ // GIVEN a PreGroupNotifFilter that gets invalidated during the grouping stage
NotifFilter filter = new PackageFilter(PACKAGE_5);
- OnBeforeTransformGroupsListener listener =
- (list, newlyVisibleEntries) -> filter.invalidateList();
- mListBuilder.addFilter(filter);
+ OnBeforeTransformGroupsListener listener = (list) -> filter.invalidateList();
+ mListBuilder.addPreGroupFilter(filter);
mListBuilder.addOnBeforeTransformGroupsListener(listener);
// WHEN we try to run the pipeline and the filter is invalidated
addNotif(0, PACKAGE_1);
dispatchBuild();
- // Then an exception is thrown
+ // THEN an exception is thrown
}
@Test(expected = IllegalStateException.class)
@@ -869,7 +888,7 @@ public class NotifListBuilderImplTest extends SysuiTestCase {
addNotif(0, PACKAGE_1);
dispatchBuild();
- // Then an exception is thrown
+ // THEN an exception is thrown
}
@Test(expected = IllegalStateException.class)
@@ -885,7 +904,37 @@ public class NotifListBuilderImplTest extends SysuiTestCase {
addNotif(0, PACKAGE_1);
dispatchBuild();
- // Then an exception is thrown
+ // THEN an exception is thrown
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void testOutOfOrderPreRenderFilterInvalidationThrows() {
+ // GIVEN a PreRenderNotifFilter that gets invalidated during the finalizing stage
+ NotifFilter filter = new PackageFilter(PACKAGE_5);
+ OnBeforeRenderListListener listener = (list) -> filter.invalidateList();
+ mListBuilder.addPreRenderFilter(filter);
+ mListBuilder.addOnBeforeRenderListListener(listener);
+
+ // WHEN we try to run the pipeline and the PreRenderFilter is invalidated
+ addNotif(0, PACKAGE_1);
+ dispatchBuild();
+
+ // THEN an exception is thrown
+ }
+
+ @Test
+ public void testInOrderPreRenderFilter() {
+ // GIVEN a PreRenderFilter that gets invalidated during the grouping stage
+ NotifFilter filter = new PackageFilter(PACKAGE_5);
+ OnBeforeTransformGroupsListener listener = (list) -> filter.invalidateList();
+ mListBuilder.addPreRenderFilter(filter);
+ mListBuilder.addOnBeforeTransformGroupsListener(listener);
+
+ // WHEN we try to run the pipeline and the filter is invalidated
+ addNotif(0, PACKAGE_1);
+ dispatchBuild();
+
+ // THEN no exception thrown
}
/**
@@ -1177,13 +1226,9 @@ public class NotifListBuilderImplTest extends SysuiTestCase {
private static class RecordingOnBeforeTransformGroupsListener
implements OnBeforeTransformGroupsListener {
- public List<ListEntry> newlyVisibleEntries;
@Override
- public void onBeforeTransformGroups(List<ListEntry> list,
- List<ListEntry> newlyVisibleEntries) {
- this.newlyVisibleEntries = newlyVisibleEntries;
- }
+ public void onBeforeTransformGroups(List<ListEntry> list) { }
}
private static final String PACKAGE_1 = "com.test1";
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationEntryBuilder.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationEntryBuilder.java
index d18b16be33d6..e6a61d62a5b4 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationEntryBuilder.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationEntryBuilder.java
@@ -14,18 +14,19 @@
* limitations under the License.
*/
-package com.android.systemui.statusbar;
+package com.android.systemui.statusbar.notification.collection;
import android.annotation.Nullable;
import android.app.Notification;
import android.app.NotificationChannel;
-import android.app.NotificationManager.Importance;
+import android.app.NotificationManager;
import android.content.Context;
import android.os.UserHandle;
import android.service.notification.SnoozeCriterion;
import android.service.notification.StatusBarNotification;
-import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.RankingBuilder;
+import com.android.systemui.statusbar.SbnBuilder;
import java.util.ArrayList;
@@ -34,6 +35,8 @@ import java.util.ArrayList;
* and Ranking. Is largely a proxy for the SBN and Ranking builders, but does a little extra magic
* to make sure the keys match between the two, etc.
*
+ * Has the ability to set ListEntry properties as well.
+ *
* Only for use in tests.
*/
public class NotificationEntryBuilder {
@@ -41,10 +44,35 @@ public class NotificationEntryBuilder {
private final RankingBuilder mRankingBuilder = new RankingBuilder();
private StatusBarNotification mSbn = null;
+ /* ListEntry properties */
+ private GroupEntry mParent;
+ private int mSection;
+
public NotificationEntry build() {
StatusBarNotification sbn = mSbn != null ? mSbn : mSbnBuilder.build();
mRankingBuilder.setKey(sbn.getKey());
- return new NotificationEntry(sbn, mRankingBuilder.build());
+ final NotificationEntry entry = new NotificationEntry(sbn, mRankingBuilder.build());
+
+ /* ListEntry properties */
+ entry.setParent(mParent);
+ entry.setSection(mSection);
+ return entry;
+ }
+
+ /**
+ * Sets the parent.
+ */
+ public NotificationEntryBuilder setParent(@Nullable GroupEntry parent) {
+ mParent = parent;
+ return this;
+ }
+
+ /**
+ * Sets the section.
+ */
+ public NotificationEntryBuilder setSection(int section) {
+ mSection = section;
+ return this;
}
/**
@@ -176,7 +204,7 @@ public class NotificationEntryBuilder {
return this;
}
- public NotificationEntryBuilder setImportance(@Importance int importance) {
+ public NotificationEntryBuilder setImportance(@NotificationManager.Importance int importance) {
mRankingBuilder.setImportance(importance);
return this;
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationEntryTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationEntryTest.java
index 536aeb4d0163..39ae68a40291 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationEntryTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationEntryTest.java
@@ -21,6 +21,8 @@ import static android.app.Notification.CATEGORY_CALL;
import static android.app.Notification.CATEGORY_EVENT;
import static android.app.Notification.CATEGORY_MESSAGE;
import static android.app.Notification.CATEGORY_REMINDER;
+import static android.app.NotificationManager.IMPORTANCE_HIGH;
+import static android.app.NotificationManager.IMPORTANCE_MIN;
import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_AMBIENT;
import static com.android.systemui.statusbar.NotificationEntryHelper.modifyRanking;
@@ -50,7 +52,6 @@ import androidx.test.filters.SmallTest;
import com.android.systemui.R;
import com.android.systemui.SysuiTestCase;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.RankingBuilder;
import com.android.systemui.statusbar.SbnBuilder;
@@ -91,6 +92,44 @@ public class NotificationEntryTest extends SysuiTestCase {
}
@Test
+ public void testIsHighPriority_notificationUpdates() {
+ // GIVEN a notification with high importance
+ final NotificationEntry entryHigh = new NotificationEntryBuilder()
+ .setImportance(IMPORTANCE_HIGH)
+ .build();
+
+ // WHEN we get the value for the high priority entry, we're caching the high priority value
+ assertTrue(entryHigh.isHighPriority());
+
+ // WHEN we change the ranking and derived members (high priority) are invalidated
+ entryHigh.setRanking(
+ new RankingBuilder()
+ .setKey(entryHigh.getKey())
+ .setImportance(IMPORTANCE_MIN)
+ .build());
+ entryHigh.invalidateDerivedMembers();
+
+ // THEN the priority is recalculated and is now low
+ assertFalse(entryHigh.isHighPriority());
+
+ // WHEN the sbn is updated to have messaging style (high priority characteristic)
+ // AND the entry invalidates its derived members
+ final Notification notification =
+ new Notification.Builder(mContext, "test")
+ .setStyle(new Notification.MessagingStyle(""))
+ .build();
+ final StatusBarNotification sbn = entryHigh.getSbn();
+ entryHigh.setSbn(new StatusBarNotification(
+ sbn.getPackageName(), sbn.getPackageName(),
+ sbn.getId(), sbn.getTag(), sbn.getUid(), sbn.getInitialPid(),
+ notification, sbn.getUser(), sbn.getOverrideGroupKey(), 0));
+ entryHigh.invalidateDerivedMembers();
+
+ // THEN the priority is recalculated and is now high
+ assertTrue(entryHigh.isHighPriority());
+ }
+
+ @Test
public void testIsExemptFromDndVisualSuppression_foreground() {
mEntry.getSbn().getNotification().flags = Notification.FLAG_FOREGROUND_SERVICE;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationRankingManagerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationRankingManagerTest.kt
index cda1538e899d..10450fa82cde 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationRankingManagerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationRankingManagerTest.kt
@@ -17,19 +17,13 @@
package com.android.systemui.statusbar.notification.collection
import android.app.Notification
-import android.app.NotificationChannel
import android.app.NotificationManager.IMPORTANCE_DEFAULT
+import android.app.NotificationManager.IMPORTANCE_HIGH
import android.app.NotificationManager.IMPORTANCE_LOW
import android.service.notification.NotificationListenerService.RankingMap
-import android.service.notification.StatusBarNotification
import android.testing.AndroidTestingRunner
-
-import org.junit.runner.RunWith
-
import androidx.test.filters.SmallTest
-
import com.android.systemui.SysuiTestCase
-import com.android.systemui.statusbar.NotificationEntryBuilder
import com.android.systemui.statusbar.NotificationEntryHelper.modifyRanking
import com.android.systemui.statusbar.NotificationMediaManager
import com.android.systemui.statusbar.notification.NotificationFilter
@@ -42,12 +36,9 @@ import com.android.systemui.statusbar.phone.NotificationGroupManager
import com.android.systemui.statusbar.policy.HeadsUpManager
import dagger.Lazy
import junit.framework.Assert.assertEquals
-import junit.framework.Assert.assertFalse
-import junit.framework.Assert.assertTrue
-
import org.junit.Before
import org.junit.Test
-import org.mockito.Mockito.`when`
+import org.junit.runner.RunWith
import org.mockito.Mockito.mock
@SmallTest
@@ -76,106 +67,34 @@ class NotificationRankingManagerTest : SysuiTestCase() {
}
@Test
- fun testPeopleNotification_isHighPriority() {
- val notification = Notification.Builder(mContext, "test")
- .build()
-
- val sbn = StatusBarNotification("pkg", "pkg", 0, "tag", 0, 0,
- notification, mContext.user, "", 0)
-
- `when`(personNotificationIdentifier.isPeopleNotification(sbn)).thenReturn(true)
-
- val e = NotificationEntryBuilder()
- .setNotification(notification)
- .setSbn(sbn)
- .build()
-
- assertTrue(rankingManager.isHighPriority2(e))
- }
-
- @Test
- fun lowForegroundHighPriority() {
- val notification = mock(Notification::class.java)
- `when`(notification.isForegroundService).thenReturn(true)
-
- val sbn = StatusBarNotification("pkg", "pkg", 0, "tag", 0, 0,
- notification, mContext.user, "", 0)
-
- val e = NotificationEntryBuilder()
- .setNotification(notification)
- .setSbn(sbn)
- .build()
-
- modifyRanking(e)
- .setImportance(IMPORTANCE_LOW)
- .build()
-
- assertTrue(rankingManager.isHighPriority2(e))
- }
-
- @Test
- fun userChangeTrumpsHighPriorityCharacteristics() {
- val notification = Notification.Builder(mContext, "test")
- .setStyle(Notification.MessagingStyle(""))
- .setFlag(Notification.FLAG_FOREGROUND_SERVICE, true)
- .build()
-
- val sbn = StatusBarNotification("pkg", "pkg", 0, "tag", 0, 0,
- notification, mContext.user, "", 0)
-
- `when`(personNotificationIdentifier.isPeopleNotification(sbn)).thenReturn(true)
-
- val channel = NotificationChannel("a", "a", IMPORTANCE_LOW)
- channel.lockFields(NotificationChannel.USER_LOCKED_IMPORTANCE)
-
- val e = NotificationEntryBuilder()
- .setSbn(sbn)
- .setChannel(channel)
- .build()
-
- assertFalse(rankingManager.isHighPriority2(e))
- }
-
- @Test
fun testSort_highPriorityTrumpsNMSRank() {
// NMS rank says A and then B. But A is not high priority and B is, so B should sort in
// front
- val aN = Notification.Builder(mContext, "test")
- .setStyle(Notification.MessagingStyle(""))
- .build()
val a = NotificationEntryBuilder()
+ .setImportance(IMPORTANCE_LOW) // low priority
+ .setRank(1) // NMS says rank first
.setPkg("pkg")
.setOpPkg("pkg")
.setTag("tag")
- .setNotification(aN)
+ .setNotification(
+ Notification.Builder(mContext, "test")
+ .build())
.setUser(mContext.getUser())
.setOverrideGroupKey("")
.build()
- a.setIsHighPriority(false)
-
- modifyRanking(a)
- .setImportance(IMPORTANCE_LOW)
- .setRank(1)
- .build()
-
- val bN = Notification.Builder(mContext, "test")
- .setStyle(Notification.MessagingStyle(""))
- .build()
val b = NotificationEntryBuilder()
+ .setImportance(IMPORTANCE_HIGH) // high priority
+ .setRank(2) // NMS says rank second
.setPkg("pkg2")
.setOpPkg("pkg2")
.setTag("tag")
- .setNotification(bN)
+ .setNotification(
+ Notification.Builder(mContext, "test")
+ .build())
.setUser(mContext.getUser())
.setOverrideGroupKey("")
.build()
- b.setIsHighPriority(true)
-
- modifyRanking(b)
- .setImportance(IMPORTANCE_LOW)
- .setRank(2)
- .build()
assertEquals(
listOf(b, a),
@@ -189,6 +108,8 @@ class NotificationRankingManagerTest : SysuiTestCase() {
.setStyle(Notification.MessagingStyle(""))
.build()
val a = NotificationEntryBuilder()
+ .setRank(1)
+ .setImportance(IMPORTANCE_HIGH)
.setPkg("pkg")
.setOpPkg("pkg")
.setTag("tag")
@@ -196,17 +117,13 @@ class NotificationRankingManagerTest : SysuiTestCase() {
.setUser(mContext.getUser())
.setOverrideGroupKey("")
.build()
- a.setIsHighPriority(false)
-
- modifyRanking(a)
- .setImportance(IMPORTANCE_LOW)
- .setRank(1)
- .build()
val bN = Notification.Builder(mContext, "test")
.setStyle(Notification.MessagingStyle(""))
.build()
val b = NotificationEntryBuilder()
+ .setRank(2)
+ .setImportance(IMPORTANCE_HIGH)
.setPkg("pkg2")
.setOpPkg("pkg2")
.setTag("tag")
@@ -214,12 +131,6 @@ class NotificationRankingManagerTest : SysuiTestCase() {
.setUser(mContext.getUser())
.setOverrideGroupKey("")
.build()
- b.setIsHighPriority(false)
-
- modifyRanking(b)
- .setImportance(IMPORTANCE_LOW)
- .setRank(2)
- .build()
assertEquals(
listOf(a, b),
@@ -239,7 +150,7 @@ class NotificationRankingManagerTest : SysuiTestCase() {
.setOverrideGroupKey("")
.build()
- modifyRanking(e).setImportance(IMPORTANCE_DEFAULT) .build()
+ modifyRanking(e).setImportance(IMPORTANCE_DEFAULT).build()
rankingManager.updateRanking(RankingMap(arrayOf(e.ranking)), listOf(e), "test")
assertEquals(e.bucket, BUCKET_ALERTING)
@@ -281,11 +192,6 @@ class NotificationRankingManagerTest : SysuiTestCase() {
sectionsFeatureManager,
peopleNotificationIdentifier
) {
-
- fun isHighPriority2(e: NotificationEntry): Boolean {
- return isHighPriority(e)
- }
-
fun applyTestRankingMap(r: RankingMap) {
rankingMap = r
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/DeviceProvisionedCoordinatorTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/DeviceProvisionedCoordinatorTest.java
new file mode 100644
index 000000000000..ea6c70a6e142
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/DeviceProvisionedCoordinatorTest.java
@@ -0,0 +1,152 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.statusbar.notification.collection.coordinator;
+
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.Manifest;
+import android.app.ActivityManagerInternal;
+import android.app.Notification;
+import android.content.pm.IPackageManager;
+import android.content.pm.PackageManager;
+import android.os.Bundle;
+import android.os.RemoteException;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.systemui.SysuiTestCase;
+import com.android.systemui.statusbar.RankingBuilder;
+import com.android.systemui.statusbar.notification.collection.NotifListBuilderImpl;
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
+import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.NotifFilter;
+import com.android.systemui.statusbar.policy.DeviceProvisionedController;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.MockitoSession;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class DeviceProvisionedCoordinatorTest extends SysuiTestCase {
+ private static final int NOTIF_UID = 0;
+
+ private static final String SHOW_WHEN_UNPROVISIONED_FLAG =
+ Notification.EXTRA_ALLOW_DURING_SETUP;
+ private static final String SETUP_NOTIF_PERMISSION =
+ Manifest.permission.NOTIFICATION_DURING_SETUP;
+
+ private MockitoSession mMockitoSession;
+
+ @Mock private ActivityManagerInternal mActivityMangerInternal;
+ @Mock private IPackageManager mIPackageManager;
+ @Mock private DeviceProvisionedController mDeviceProvisionedController;
+ @Mock private NotifListBuilderImpl mNotifListBuilder;
+ private Notification mNotification;
+ private NotificationEntry mEntry;
+ private DeviceProvisionedCoordinator mDeviceProvisionedCoordinator;
+ private NotifFilter mDeviceProvisionedFilter;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ mDeviceProvisionedCoordinator = new DeviceProvisionedCoordinator(
+ mDeviceProvisionedController, mIPackageManager);
+
+ mNotification = new Notification();
+ mEntry = new NotificationEntryBuilder()
+ .setNotification(mNotification)
+ .setUid(NOTIF_UID)
+ .build();
+
+ ArgumentCaptor<NotifFilter> filterCaptor = ArgumentCaptor.forClass(NotifFilter.class);
+ mDeviceProvisionedCoordinator.attach(null, mNotifListBuilder);
+ verify(mNotifListBuilder, times(1)).addPreGroupFilter(filterCaptor.capture());
+ mDeviceProvisionedFilter = filterCaptor.getValue();
+ }
+
+ @Test
+ public void deviceProvisioned() {
+ // GIVEN device is provisioned
+ when(mDeviceProvisionedController.isDeviceProvisioned()).thenReturn(true);
+
+ // THEN don't filter out the notification
+ assertFalse(mDeviceProvisionedFilter.shouldFilterOut(mEntry, 0));
+ }
+
+ @Test
+ public void deviceUnprovisioned() {
+ // GIVEN device is unprovisioned
+ when(mDeviceProvisionedController.isDeviceProvisioned()).thenReturn(false);
+
+ // THEN filter out the notification
+ assertTrue(mDeviceProvisionedFilter.shouldFilterOut(mEntry, 0));
+ }
+
+ @Test
+ public void deviceUnprovisionedCanBypass() throws RemoteException {
+ // GIVEN device is unprovisioned
+ when(mDeviceProvisionedController.isDeviceProvisioned()).thenReturn(false);
+
+ // GIVEN notification has a flag to allow the notification during setup
+ Bundle extras = new Bundle();
+ extras.putBoolean(SHOW_WHEN_UNPROVISIONED_FLAG, true);
+ mNotification.extras = extras;
+
+ // GIVEN notification has the permission to display during setup
+ when(mIPackageManager.checkUidPermission(SETUP_NOTIF_PERMISSION, NOTIF_UID))
+ .thenReturn(PackageManager.PERMISSION_GRANTED);
+
+ // THEN don't filter out the notification
+ assertFalse(mDeviceProvisionedFilter.shouldFilterOut(mEntry, 0));
+ }
+
+ @Test
+ public void deviceUnprovisionedTryBypassWithoutPermission() throws RemoteException {
+ // GIVEN device is unprovisioned
+ when(mDeviceProvisionedController.isDeviceProvisioned()).thenReturn(false);
+
+ // GIVEN notification has a flag to allow the notification during setup
+ Bundle extras = new Bundle();
+ extras.putBoolean(SHOW_WHEN_UNPROVISIONED_FLAG, true);
+ mNotification.extras = extras;
+
+ // GIVEN notification does NOT have permission to display during setup
+ when(mIPackageManager.checkUidPermission(SETUP_NOTIF_PERMISSION, NOTIF_UID))
+ .thenReturn(PackageManager.PERMISSION_DENIED);
+
+ // THEN filter out the notification
+ assertTrue(mDeviceProvisionedFilter.shouldFilterOut(mEntry, 0));
+ }
+
+ private RankingBuilder getRankingForUnfilteredNotif() {
+ return new RankingBuilder()
+ .setKey(mEntry.getKey())
+ .setSuppressedVisualEffects(0)
+ .setSuspended(false);
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/ForegroundCoordinatorTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/ForegroundCoordinatorTest.java
new file mode 100644
index 000000000000..01bca0dc1078
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/ForegroundCoordinatorTest.java
@@ -0,0 +1,188 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.statusbar.notification.collection.coordinator;
+
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.app.Notification;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.UserHandle;
+import android.service.notification.NotificationListenerService;
+import android.service.notification.StatusBarNotification;
+import android.testing.AndroidTestingRunner;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.systemui.ForegroundServiceController;
+import com.android.systemui.SysuiTestCase;
+import com.android.systemui.appops.AppOpsController;
+import com.android.systemui.statusbar.notification.collection.NotifCollection;
+import com.android.systemui.statusbar.notification.collection.NotifLifetimeExtender;
+import com.android.systemui.statusbar.notification.collection.NotifListBuilderImpl;
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
+import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.NotifFilter;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@SmallTest
+@RunWith(AndroidTestingRunner.class)
+public class ForegroundCoordinatorTest extends SysuiTestCase {
+ private static final String TEST_PKG = "test_pkg";
+ private static final int NOTIF_USER_ID = 0;
+
+ @Mock private Handler mMainHandler;
+ @Mock private ForegroundServiceController mForegroundServiceController;
+ @Mock private AppOpsController mAppOpsController;
+ @Mock private NotifListBuilderImpl mNotifListBuilder;
+ @Mock private NotifCollection mNotifCollection;
+
+ private NotificationEntry mEntry;
+ private Notification mNotification;
+ private ForegroundCoordinator mForegroundCoordinator;
+ private NotifFilter mForegroundFilter;
+ private NotifLifetimeExtender mForegroundNotifLifetimeExtender;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ mForegroundCoordinator = new ForegroundCoordinator(
+ mForegroundServiceController, mAppOpsController, mMainHandler);
+
+ mNotification = new Notification();
+ mEntry = new NotificationEntryBuilder()
+ .setUser(new UserHandle(NOTIF_USER_ID))
+ .setNotification(mNotification)
+ .build();
+
+ ArgumentCaptor<NotifFilter> filterCaptor = ArgumentCaptor.forClass(NotifFilter.class);
+ ArgumentCaptor<NotifLifetimeExtender> lifetimeExtenderCaptor =
+ ArgumentCaptor.forClass(NotifLifetimeExtender.class);
+
+ mForegroundCoordinator.attach(mNotifCollection, mNotifListBuilder);
+ verify(mNotifListBuilder, times(1)).addPreGroupFilter(filterCaptor.capture());
+ verify(mNotifCollection, times(1)).addNotificationLifetimeExtender(
+ lifetimeExtenderCaptor.capture());
+
+ mForegroundFilter = filterCaptor.getValue();
+ mForegroundNotifLifetimeExtender = lifetimeExtenderCaptor.getValue();
+ }
+
+ @Test
+ public void filterTest_disclosureUnnecessary() {
+ StatusBarNotification sbn = mEntry.getSbn();
+
+ // GIVEN the notification is a disclosure notification
+ when(mForegroundServiceController.isDisclosureNotification(sbn)).thenReturn(true);
+
+ // GIVEN the disclosure isn't needed for this user
+ when(mForegroundServiceController.isDisclosureNeededForUser(sbn.getUserId()))
+ .thenReturn(false);
+
+ // THEN filter out the notification
+ assertTrue(mForegroundFilter.shouldFilterOut(mEntry, 0));
+ }
+
+ @Test
+ public void filterTest_systemAlertNotificationUnnecessary() {
+ StatusBarNotification sbn = mEntry.getSbn();
+
+ // GIVEN the notification is a system alert notification + not a disclosure notification
+ when(mForegroundServiceController.isSystemAlertNotification(sbn)).thenReturn(true);
+ when(mForegroundServiceController.isDisclosureNotification(sbn)).thenReturn(false);
+
+ // GIVEN the alert notification isn't needed for this user
+ final Bundle extras = new Bundle();
+ extras.putStringArray(Notification.EXTRA_FOREGROUND_APPS,
+ new String[]{TEST_PKG});
+ mNotification.extras = extras;
+ when(mForegroundServiceController.isSystemAlertWarningNeeded(sbn.getUserId(), TEST_PKG))
+ .thenReturn(false);
+
+ // THEN filter out the notification
+ assertTrue(mForegroundFilter.shouldFilterOut(mEntry, 0));
+ }
+
+ @Test
+ public void filterTest_doNotFilter() {
+ StatusBarNotification sbn = mEntry.getSbn();
+
+ // GIVEN the notification isn't a system alert notification nor a disclosure notification
+ when(mForegroundServiceController.isSystemAlertNotification(sbn)).thenReturn(false);
+ when(mForegroundServiceController.isDisclosureNotification(sbn)).thenReturn(false);
+
+ // THEN don't filter out the notification
+ assertFalse(mForegroundFilter.shouldFilterOut(mEntry, 0));
+ }
+
+ @Test
+ public void extendLifetimeText_notForeground() {
+ // GIVEN the notification doesn't represent a foreground service
+ mNotification.flags = 0;
+
+ // THEN don't extend the lifetime
+ assertFalse(mForegroundNotifLifetimeExtender
+ .shouldExtendLifetime(mEntry, NotificationListenerService.REASON_CLICK));
+ }
+
+ @Test
+ public void extendLifetimeText_foregroundNotifRecentlyPosted() {
+ // GIVEN the notification represents a foreground service that was just posted
+ mNotification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
+ mEntry = new NotificationEntryBuilder()
+ .setUser(new UserHandle(NOTIF_USER_ID))
+ .setSbn(new StatusBarNotification(TEST_PKG, TEST_PKG, NOTIF_USER_ID, "",
+ NOTIF_USER_ID, NOTIF_USER_ID, mNotification,
+ new UserHandle(NOTIF_USER_ID), "", System.currentTimeMillis()))
+ .setNotification(mNotification)
+ .build();
+
+ // THEN extend the lifetime
+ assertTrue(mForegroundNotifLifetimeExtender
+ .shouldExtendLifetime(mEntry, NotificationListenerService.REASON_CLICK));
+ }
+
+ @Test
+ public void extendLifetimeText_foregroundNotifOld() {
+ // GIVEN the notification represents a foreground service that was posted 10 seconds ago
+ mNotification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
+ mEntry = new NotificationEntryBuilder()
+ .setUser(new UserHandle(NOTIF_USER_ID))
+ .setSbn(new StatusBarNotification(TEST_PKG, TEST_PKG, NOTIF_USER_ID, "",
+ NOTIF_USER_ID, NOTIF_USER_ID, mNotification,
+ new UserHandle(NOTIF_USER_ID), "",
+ System.currentTimeMillis() - 10000))
+ .setNotification(mNotification)
+ .build();
+
+ // THEN don't extend the lifetime because the extended time exceeds
+ // ForegroundCoordinator.MIN_FGS_TIME_MS
+ assertFalse(mForegroundNotifLifetimeExtender
+ .shouldExtendLifetime(mEntry, NotificationListenerService.REASON_CLICK));
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/KeyguardCoordinatorTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/KeyguardCoordinatorTest.java
index 87b3783d1984..979b8a906ef0 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/KeyguardCoordinatorTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/KeyguardCoordinatorTest.java
@@ -24,6 +24,8 @@ import static android.app.NotificationManager.IMPORTANCE_MIN;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.os.Handler;
@@ -36,16 +38,19 @@ import com.android.keyguard.KeyguardUpdateMonitor;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.broadcast.BroadcastDispatcher;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.NotificationLockscreenUserManager;
import com.android.systemui.statusbar.RankingBuilder;
import com.android.systemui.statusbar.notification.collection.GroupEntry;
+import com.android.systemui.statusbar.notification.collection.NotifListBuilderImpl;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
+import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.NotifFilter;
import com.android.systemui.statusbar.policy.KeyguardStateController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
@@ -61,14 +66,16 @@ public class KeyguardCoordinatorTest extends SysuiTestCase {
@Mock private BroadcastDispatcher mBroadcastDispatcher;
@Mock private StatusBarStateController mStatusBarStateController;
@Mock private KeyguardUpdateMonitor mKeyguardUpdateMonitor;
+ @Mock private NotifListBuilderImpl mNotifListBuilder;
private NotificationEntry mEntry;
- private KeyguardCoordinator mKeyguardNotificationCoordinator;
+ private KeyguardCoordinator mKeyguardCoordinator;
+ private NotifFilter mKeyguardFilter;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
- mKeyguardNotificationCoordinator = new KeyguardCoordinator(
+ mKeyguardCoordinator = new KeyguardCoordinator(
mContext, mMainHandler, mKeyguardStateController, mLockscreenUserManager,
mBroadcastDispatcher, mStatusBarStateController,
mKeyguardUpdateMonitor);
@@ -76,65 +83,70 @@ public class KeyguardCoordinatorTest extends SysuiTestCase {
mEntry = new NotificationEntryBuilder()
.setUser(new UserHandle(NOTIF_USER_ID))
.build();
+
+ ArgumentCaptor<NotifFilter> filterCaptor = ArgumentCaptor.forClass(NotifFilter.class);
+ mKeyguardCoordinator.attach(null, mNotifListBuilder);
+ verify(mNotifListBuilder, times(1)).addPreRenderFilter(filterCaptor.capture());
+ mKeyguardFilter = filterCaptor.getValue();
}
@Test
public void unfilteredState() {
// GIVEN an 'unfiltered-keyguard-showing' state
- setupUnfilteredState();
+ setupUnfilteredState(mEntry);
// THEN don't filter out the entry
- assertFalse(mKeyguardNotificationCoordinator.mNotifFilter.shouldFilterOut(mEntry, 0));
+ assertFalse(mKeyguardFilter.shouldFilterOut(mEntry, 0));
}
@Test
public void notificationNotForCurrentProfile() {
// GIVEN the notification isn't for the given user
- setupUnfilteredState();
+ setupUnfilteredState(mEntry);
when(mLockscreenUserManager.isCurrentProfile(NOTIF_USER_ID)).thenReturn(false);
// THEN filter out the entry
- assertTrue(mKeyguardNotificationCoordinator.mNotifFilter.shouldFilterOut(mEntry, 0));
+ assertTrue(mKeyguardFilter.shouldFilterOut(mEntry, 0));
}
@Test
public void keyguardNotShowing() {
// GIVEN the lockscreen isn't showing
- setupUnfilteredState();
+ setupUnfilteredState(mEntry);
when(mKeyguardStateController.isShowing()).thenReturn(false);
// THEN don't filter out the entry
- assertFalse(mKeyguardNotificationCoordinator.mNotifFilter.shouldFilterOut(mEntry, 0));
+ assertFalse(mKeyguardFilter.shouldFilterOut(mEntry, 0));
}
@Test
public void doNotShowLockscreenNotifications() {
// GIVEN an 'unfiltered-keyguard-showing' state
- setupUnfilteredState();
+ setupUnfilteredState(mEntry);
// WHEN we shouldn't show any lockscreen notifications
when(mLockscreenUserManager.shouldShowLockscreenNotifications()).thenReturn(false);
// THEN filter out the entry
- assertTrue(mKeyguardNotificationCoordinator.mNotifFilter.shouldFilterOut(mEntry, 0));
+ assertTrue(mKeyguardFilter.shouldFilterOut(mEntry, 0));
}
@Test
public void lockdown() {
// GIVEN an 'unfiltered-keyguard-showing' state
- setupUnfilteredState();
+ setupUnfilteredState(mEntry);
// WHEN the notification's user is in lockdown:
when(mKeyguardUpdateMonitor.isUserInLockdown(NOTIF_USER_ID)).thenReturn(true);
// THEN filter out the entry
- assertTrue(mKeyguardNotificationCoordinator.mNotifFilter.shouldFilterOut(mEntry, 0));
+ assertTrue(mKeyguardFilter.shouldFilterOut(mEntry, 0));
}
@Test
public void publicMode_settingsDisallow() {
// GIVEN an 'unfiltered-keyguard-showing' state
- setupUnfilteredState();
+ setupUnfilteredState(mEntry);
// WHEN the notification's user is in public mode and settings are configured to disallow
// notifications in public mode
@@ -143,13 +155,13 @@ public class KeyguardCoordinatorTest extends SysuiTestCase {
.thenReturn(false);
// THEN filter out the entry
- assertTrue(mKeyguardNotificationCoordinator.mNotifFilter.shouldFilterOut(mEntry, 0));
+ assertTrue(mKeyguardFilter.shouldFilterOut(mEntry, 0));
}
@Test
public void publicMode_notifDisallowed() {
// GIVEN an 'unfiltered-keyguard-showing' state
- setupUnfilteredState();
+ setupUnfilteredState(mEntry);
// WHEN the notification's user is in public mode and settings are configured to disallow
// notifications in public mode
@@ -159,13 +171,13 @@ public class KeyguardCoordinatorTest extends SysuiTestCase {
.setVisibilityOverride(VISIBILITY_SECRET).build());
// THEN filter out the entry
- assertTrue(mKeyguardNotificationCoordinator.mNotifFilter.shouldFilterOut(mEntry, 0));
+ assertTrue(mKeyguardFilter.shouldFilterOut(mEntry, 0));
}
@Test
public void doesNotExceedThresholdToShow() {
// GIVEN an 'unfiltered-keyguard-showing' state
- setupUnfilteredState();
+ setupUnfilteredState(mEntry);
// WHEN the notification doesn't exceed the threshold to show on the lockscreen
mEntry.setRanking(new RankingBuilder()
@@ -174,39 +186,47 @@ public class KeyguardCoordinatorTest extends SysuiTestCase {
.build());
// THEN filter out the entry
- assertTrue(mKeyguardNotificationCoordinator.mNotifFilter.shouldFilterOut(mEntry, 0));
+ assertTrue(mKeyguardFilter.shouldFilterOut(mEntry, 0));
}
@Test
public void summaryExceedsThresholdToShow() {
- // GIVEN an 'unfiltered-keyguard-showing' state
- setupUnfilteredState();
+ // GIVEN the notification doesn't exceed the threshold to show on the lockscreen
+ // but it's part of a group (has a parent)
+ final GroupEntry parent = new GroupEntry("test_group_key");
+ final NotificationEntry entryWithParent = new NotificationEntryBuilder()
+ .setParent(parent)
+ .setUser(new UserHandle(NOTIF_USER_ID))
+ .build();
- // WHEN the notification doesn't exceed the threshold to show on the lockscreen
- // but its summary does
- mEntry.setRanking(new RankingBuilder()
- .setKey(mEntry.getKey())
+ setupUnfilteredState(entryWithParent);
+ entryWithParent.setRanking(new RankingBuilder()
+ .setKey(entryWithParent.getKey())
.setImportance(IMPORTANCE_MIN)
.build());
- final NotificationEntry summary = new NotificationEntryBuilder().build();
- summary.setRanking(new RankingBuilder()
- .setKey(summary.getKey())
+ // WHEN its parent has a summary that exceeds threshold to show on lockscreen
+ parent.setSummary(new NotificationEntryBuilder()
.setImportance(IMPORTANCE_HIGH)
.build());
- final GroupEntry group = new GroupEntry(mEntry.getSbn().getGroupKey());
- group.setSummary(summary);
- mEntry.setParent(group);
// THEN don't filter out the entry
- assertFalse(mKeyguardNotificationCoordinator.mNotifFilter.shouldFilterOut(mEntry, 0));
+ assertFalse(mKeyguardFilter.shouldFilterOut(entryWithParent, 0));
+
+ // WHEN its parent has a summary that doesn't exceed threshold to show on lockscreen
+ parent.setSummary(new NotificationEntryBuilder()
+ .setImportance(IMPORTANCE_MIN)
+ .build());
+
+ // THEN filter out the entry
+ assertTrue(mKeyguardFilter.shouldFilterOut(entryWithParent, 0));
}
/**
* setup a state where the notification will not be filtered by the
* KeyguardNotificationCoordinator when the keyguard is showing.
*/
- private void setupUnfilteredState() {
+ private void setupUnfilteredState(NotificationEntry entry) {
// notification is for current profile
when(mLockscreenUserManager.isCurrentProfile(NOTIF_USER_ID)).thenReturn(true);
@@ -227,7 +247,7 @@ public class KeyguardCoordinatorTest extends SysuiTestCase {
// entry's ranking - should show on all lockscreens
// + priority of the notification exceeds the threshold to be shown on the lockscreen
- mEntry.setRanking(new RankingBuilder()
+ entry.setRanking(new RankingBuilder()
.setKey(mEntry.getKey())
.setVisibilityOverride(VISIBILITY_PUBLIC)
.setImportance(IMPORTANCE_HIGH)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinatorTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinatorTest.java
new file mode 100644
index 000000000000..d3b16c319692
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinatorTest.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.statusbar.notification.collection.coordinator;
+
+import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_AMBIENT;
+import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_NOTIFICATION_LIST;
+
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.testing.AndroidTestingRunner;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.systemui.SysuiTestCase;
+import com.android.systemui.plugins.statusbar.StatusBarStateController;
+import com.android.systemui.statusbar.RankingBuilder;
+import com.android.systemui.statusbar.notification.collection.NotifListBuilderImpl;
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
+import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.NotifFilter;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@SmallTest
+@RunWith(AndroidTestingRunner.class)
+public class RankingCoordinatorTest extends SysuiTestCase {
+
+ @Mock private StatusBarStateController mStatusBarStateController;
+ @Mock private NotifListBuilderImpl mNotifListBuilder;
+ private NotificationEntry mEntry;
+ private RankingCoordinator mRankingCoordinator;
+ private NotifFilter mRankingFilter;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ mRankingCoordinator = new RankingCoordinator(mStatusBarStateController);
+ mEntry = new NotificationEntryBuilder().build();
+
+ ArgumentCaptor<NotifFilter> filterCaptor = ArgumentCaptor.forClass(NotifFilter.class);
+ mRankingCoordinator.attach(null, mNotifListBuilder);
+ verify(mNotifListBuilder, times(1)).addPreGroupFilter(filterCaptor.capture());
+ mRankingFilter = filterCaptor.getValue();
+ }
+
+ @Test
+ public void testUnfilteredState() {
+ // GIVEN no suppressed visual effects + app not suspended
+ mEntry.setRanking(getRankingForUnfilteredNotif().build());
+
+ // THEN don't filter out the notification
+ assertFalse(mRankingFilter.shouldFilterOut(mEntry, 0));
+ }
+
+ @Test
+ public void filterSuspended() {
+ // GIVEN the notification's app is suspended
+ mEntry.setRanking(getRankingForUnfilteredNotif()
+ .setSuspended(true)
+ .build());
+
+ // THEN filter out the notification
+ assertTrue(mRankingFilter.shouldFilterOut(mEntry, 0));
+ }
+
+ @Test
+ public void filterDozingSuppressAmbient() {
+ // GIVEN should suppress ambient
+ mEntry.setRanking(getRankingForUnfilteredNotif()
+ .setSuppressedVisualEffects(SUPPRESSED_EFFECT_AMBIENT)
+ .build());
+
+ // WHEN it's dozing (on ambient display)
+ when(mStatusBarStateController.isDozing()).thenReturn(true);
+
+ // THEN filter out the notification
+ assertTrue(mRankingFilter.shouldFilterOut(mEntry, 0));
+
+ // WHEN it's not dozing (showing the notification list)
+ when(mStatusBarStateController.isDozing()).thenReturn(false);
+
+ // THEN don't filter out the notification
+ assertFalse(mRankingFilter.shouldFilterOut(mEntry, 0));
+ }
+
+ @Test
+ public void filterDozingSuppressNotificationList() {
+ // GIVEN should suppress from the notification list
+ mEntry.setRanking(getRankingForUnfilteredNotif()
+ .setSuppressedVisualEffects(SUPPRESSED_EFFECT_NOTIFICATION_LIST)
+ .build());
+
+ // WHEN it's dozing (on ambient display)
+ when(mStatusBarStateController.isDozing()).thenReturn(true);
+
+ // THEN don't filter out the notification
+ assertFalse(mRankingFilter.shouldFilterOut(mEntry, 0));
+
+ // WHEN it's not dozing (showing the notification list)
+ when(mStatusBarStateController.isDozing()).thenReturn(false);
+
+ // THEN filter out the notification
+ assertTrue(mRankingFilter.shouldFilterOut(mEntry, 0));
+ }
+
+ private RankingBuilder getRankingForUnfilteredNotif() {
+ return new RankingBuilder()
+ .setKey(mEntry.getKey())
+ .setSuppressedVisualEffects(0)
+ .setSuspended(false);
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/provider/IsHighPriorityProviderTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/provider/IsHighPriorityProviderTest.java
new file mode 100644
index 000000000000..6fa1a89515c3
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/provider/IsHighPriorityProviderTest.java
@@ -0,0 +1,184 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.statusbar.notification.collection.provider;
+
+import static android.app.NotificationManager.IMPORTANCE_HIGH;
+import static android.app.NotificationManager.IMPORTANCE_LOW;
+import static android.app.NotificationManager.IMPORTANCE_MIN;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import android.app.Notification;
+import android.app.NotificationChannel;
+import android.app.Person;
+import android.testing.AndroidTestingRunner;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.systemui.SysuiTestCase;
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@SmallTest
+@RunWith(AndroidTestingRunner.class)
+public class IsHighPriorityProviderTest extends SysuiTestCase {
+ private IsHighPriorityProvider mIsHighPriorityProvider;
+
+ @Before
+ public void setup() {
+ mIsHighPriorityProvider = new IsHighPriorityProvider();
+ }
+
+ @Test
+ public void testCache() {
+ // GIVEN a notification with high importance
+ final NotificationEntry entryHigh = new NotificationEntryBuilder()
+ .setImportance(IMPORTANCE_HIGH)
+ .build();
+
+ // GIVEN notification with min importance
+ final NotificationEntry entryMin = new NotificationEntryBuilder()
+ .setImportance(IMPORTANCE_MIN)
+ .build();
+
+ // WHEN we get the value for the high priority entry
+ assertTrue(mIsHighPriorityProvider.get(entryHigh));
+
+ // THEN the value is cached, so even when passed an entryMin, we still get high priority
+ assertTrue(mIsHighPriorityProvider.get(entryMin));
+
+ // UNTIL the provider is invalidated
+ mIsHighPriorityProvider.invalidate();
+
+ // THEN the priority is recalculated
+ assertFalse(mIsHighPriorityProvider.get(entryMin));
+ }
+
+ @Test
+ public void highImportance() {
+ // GIVEN notification has high importance
+ final NotificationEntry entry = new NotificationEntryBuilder()
+ .setImportance(IMPORTANCE_HIGH)
+ .build();
+
+ // THEN it has high priority
+ assertTrue(mIsHighPriorityProvider.get(entry));
+ }
+
+ @Test
+ public void peopleNotification() {
+ // GIVEN notification is low importance but has a person associated with it
+ final Notification notification = new Notification.Builder(mContext, "test")
+ .addPerson(
+ new Person.Builder()
+ .setName("name")
+ .setKey("abc")
+ .setUri("uri")
+ .setBot(true)
+ .build())
+ .build();
+
+ final NotificationEntry entry = new NotificationEntryBuilder()
+ .setNotification(notification)
+ .setImportance(IMPORTANCE_LOW)
+ .build();
+
+ // THEN it has high priority
+ assertTrue(mIsHighPriorityProvider.get(entry));
+ }
+
+ @Test
+ public void messagingStyle() {
+ // GIVEN notification is low importance but has messaging style
+ final Notification notification = new Notification.Builder(mContext, "test")
+ .setStyle(new Notification.MessagingStyle(""))
+ .build();
+
+ final NotificationEntry entry = new NotificationEntryBuilder()
+ .setNotification(notification)
+ .build();
+
+ // THEN it has high priority
+ assertTrue(mIsHighPriorityProvider.get(entry));
+ }
+
+ @Test
+ public void lowImportanceForeground() {
+ // GIVEN notification is low importance and is associated with a foreground service
+ final Notification notification = mock(Notification.class);
+ when(notification.isForegroundService()).thenReturn(true);
+
+ final NotificationEntry entry = new NotificationEntryBuilder()
+ .setNotification(notification)
+ .setImportance(IMPORTANCE_LOW)
+ .build();
+
+ // THEN it has high priority
+ assertTrue(mIsHighPriorityProvider.get(entry));
+ }
+
+ @Test
+ public void minImportanceForeground() {
+ // GIVEN notification is low importance and is associated with a foreground service
+ final Notification notification = mock(Notification.class);
+ when(notification.isForegroundService()).thenReturn(true);
+
+ final NotificationEntry entry = new NotificationEntryBuilder()
+ .setNotification(notification)
+ .setImportance(IMPORTANCE_MIN)
+ .build();
+
+ // THEN it does NOT have high priority
+ assertFalse(mIsHighPriorityProvider.get(entry));
+ }
+
+ @Test
+ public void userChangeTrumpsHighPriorityCharacteristics() {
+ // GIVEN notification has high priority characteristics but the user changed the importance
+ // to less than IMPORTANCE_DEFAULT (ie: IMPORTANCE_LOW or IMPORTANCE_MIN)
+ final Notification notification = new Notification.Builder(mContext, "test")
+ .addPerson(
+ new Person.Builder()
+ .setName("name")
+ .setKey("abc")
+ .setUri("uri")
+ .setBot(true)
+ .build())
+ .setStyle(new Notification.MessagingStyle(""))
+ .setFlag(Notification.FLAG_FOREGROUND_SERVICE, true)
+ .build();
+
+ final NotificationChannel channel = new NotificationChannel("a", "a",
+ IMPORTANCE_LOW);
+ channel.lockFields(NotificationChannel.USER_LOCKED_IMPORTANCE);
+
+ final NotificationEntry entry = new NotificationEntryBuilder()
+ .setNotification(notification)
+ .setChannel(channel)
+ .build();
+
+ // THEN it does NOT have high priority
+ assertFalse(mIsHighPriorityProvider.get(entry));
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/NotificationLoggerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/NotificationLoggerTest.java
index d1398667f497..e23d0ae89a09 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/NotificationLoggerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/NotificationLoggerTest.java
@@ -39,12 +39,12 @@ import com.android.internal.statusbar.NotificationVisibility;
import com.android.systemui.Dependency;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.UiOffloadThread;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.NotificationListener;
import com.android.systemui.statusbar.StatusBarStateControllerImpl;
import com.android.systemui.statusbar.notification.NotificationEntryListener;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.systemui.statusbar.notification.stack.NotificationListContainer;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/people/PeopleHubViewControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/people/PeopleHubViewControllerTest.kt
index f5d6f223b86c..0764d0cd4b88 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/people/PeopleHubViewControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/people/PeopleHubViewControllerTest.kt
@@ -89,8 +89,17 @@ class PeopleHubViewControllerTest : SysuiTestCase() {
return mockSubscription
}
}
+ val fakeSettingDataSource = object : DataSource<Boolean> {
+ override fun registerListener(listener: DataListener<Boolean>): Subscription {
+ listener.onDataChanged(true)
+ return mockSubscription
+ }
+ }
val factoryDataSource = PeopleHubViewModelFactoryDataSourceImpl(
- mockActivityStarter, fakeModelDataSource)
+ mockActivityStarter,
+ fakeModelDataSource,
+ fakeSettingDataSource
+ )
val fakeListener = FakeDataListener<PeopleHubViewModelFactory>()
val mockClickView = mock(View::class.java)
@@ -112,6 +121,41 @@ class PeopleHubViewControllerTest : SysuiTestCase() {
same(mockClickView)
)
}
+
+ @Test
+ fun testViewModelDataSource_notVisibleIfSettingDisabled() {
+ val fakeClickIntent = PendingIntent.getActivity(context, 0, Intent("action"), 0)
+ val fakePerson = fakePersonModel("id", "name", fakeClickIntent)
+ val fakeModel = PeopleHubModel(listOf(fakePerson))
+ val mockSubscription = mock(Subscription::class.java)
+ val fakeModelDataSource = object : DataSource<PeopleHubModel> {
+ override fun registerListener(listener: DataListener<PeopleHubModel>): Subscription {
+ listener.onDataChanged(fakeModel)
+ return mockSubscription
+ }
+ }
+ val fakeSettingDataSource = object : DataSource<Boolean> {
+ override fun registerListener(listener: DataListener<Boolean>): Subscription {
+ listener.onDataChanged(false)
+ return mockSubscription
+ }
+ }
+ val factoryDataSource = PeopleHubViewModelFactoryDataSourceImpl(
+ mockActivityStarter,
+ fakeModelDataSource,
+ fakeSettingDataSource
+ )
+ val fakeListener = FakeDataListener<PeopleHubViewModelFactory>()
+ val mockClickView = mock(View::class.java)
+
+ factoryDataSource.registerListener(fakeListener)
+
+ val viewModel = (fakeListener.lastSeen as Maybe.Just).value
+ .createWithAssociatedClickView(mockClickView)
+ assertThat(viewModel.isVisible).isFalse()
+ val people = viewModel.people.toList()
+ assertThat(people.size).isEqualTo(0)
+ }
}
/** Works around Mockito matchers returning `null` and breaking non-nullable Kotlin code. */
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentInflaterTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentInflaterTest.java
index 27e3a6699571..c7e59ef6bd3f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentInflaterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationContentInflaterTest.java
@@ -42,6 +42,7 @@ import android.view.ViewGroup;
import android.widget.RemoteViews;
import androidx.test.filters.SmallTest;
+import androidx.test.filters.Suppress;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.statusbar.InflationTask;
@@ -64,7 +65,7 @@ import java.util.concurrent.TimeUnit;
@SmallTest
@RunWith(AndroidTestingRunner.class)
@RunWithLooper(setAsMainLooper = true)
-@Ignore
+@Suppress
public class NotificationContentInflaterTest extends SysuiTestCase {
private NotificationContentInflater mNotificationInflater;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationGutsManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationGutsManagerTest.java
index 43d39a2f9511..ccc9496368e9 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationGutsManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationGutsManagerTest.java
@@ -20,6 +20,7 @@ import static android.app.AppOpsManager.OP_CAMERA;
import static android.app.AppOpsManager.OP_RECORD_AUDIO;
import static android.app.AppOpsManager.OP_SYSTEM_ALERT_WINDOW;
import static android.app.NotificationManager.IMPORTANCE_DEFAULT;
+import static android.app.NotificationManager.IMPORTANCE_HIGH;
import static android.service.notification.NotificationListenerService.Ranking.USER_SENTIMENT_NEGATIVE;
import static com.android.systemui.statusbar.NotificationEntryHelper.modifyRanking;
@@ -383,15 +384,14 @@ public class NotificationGutsManagerTest extends SysuiTestCase {
NotificationInfo notificationInfoView = mock(NotificationInfo.class);
ExpandableNotificationRow row = spy(mHelper.createRow());
row.setBlockingHelperShowing(true);
- modifyRanking(row.getEntry())
+ final NotificationEntry entry = row.getEntry();
+ modifyRanking(entry)
.setUserSentiment(USER_SENTIMENT_NEGATIVE)
- .setImportance(IMPORTANCE_DEFAULT)
+ .setImportance(IMPORTANCE_HIGH)
.build();
- row.getEntry().setIsHighPriority(true);
- when(row.getIsNonblockable()).thenReturn(false);
- StatusBarNotification statusBarNotification = row.getEntry().getSbn();
- NotificationEntry entry = row.getEntry();
+ when(row.getIsNonblockable()).thenReturn(false);
+ StatusBarNotification statusBarNotification = entry.getSbn();
mGutsManager.initializeNotificationInfo(row, notificationInfoView);
verify(notificationInfoView).bindNotification(
@@ -408,7 +408,7 @@ public class NotificationGutsManagerTest extends SysuiTestCase {
eq(false),
eq(false),
eq(true) /* isForBlockingHelper */,
- eq(IMPORTANCE_DEFAULT),
+ eq(IMPORTANCE_HIGH),
eq(true) /* wasShownHighPriority */);
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationInfoTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationInfoTest.java
index bdca7efeb608..f513c2d1513b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationInfoTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationInfoTest.java
@@ -78,10 +78,10 @@ import com.android.systemui.R;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.bubbles.BubbleController;
import com.android.systemui.bubbles.BubblesTestActivity;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.SbnBuilder;
import com.android.systemui.statusbar.notification.VisualStabilityManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import org.junit.After;
import org.junit.Before;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationMenuRowTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationMenuRowTest.java
index 9eba4ebeb994..f48c40c3b941 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationMenuRowTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationMenuRowTest.java
@@ -38,8 +38,8 @@ import android.view.ViewGroup;
import androidx.test.filters.SmallTest;
import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.utils.leaks.LeakCheckedTest;
import org.junit.After;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java
index d2b4a20ca3a9..deca51fe0033 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java
@@ -55,7 +55,6 @@ import com.android.systemui.SysuiTestCase;
import com.android.systemui.classifier.FalsingManagerFake;
import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin;
import com.android.systemui.statusbar.EmptyShadeView;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.NotificationLockscreenUserManager;
import com.android.systemui.statusbar.NotificationMediaManager;
import com.android.systemui.statusbar.NotificationPresenter;
@@ -71,6 +70,7 @@ import com.android.systemui.statusbar.notification.NotificationSectionsFeatureMa
import com.android.systemui.statusbar.notification.TestableNotificationEntryManager;
import com.android.systemui.statusbar.notification.VisualStabilityManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.collection.NotificationRankingManager;
import com.android.systemui.statusbar.notification.logging.NotifLog;
import com.android.systemui.statusbar.notification.people.PeopleHubSectionFooterViewAdapter;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/BiometricsUnlockControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/BiometricsUnlockControllerTest.java
index 4451fa416912..5907a0a683a8 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/BiometricsUnlockControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/BiometricsUnlockControllerTest.java
@@ -21,6 +21,7 @@ import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyFloat;
+import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
@@ -76,6 +77,8 @@ public class BiometricsUnlockControllerTest extends SysuiTestCase {
@Mock
private StatusBar mStatusBar;
@Mock
+ private ShadeController mShadeController;
+ @Mock
private KeyguardStateController mKeyguardStateController;
@Mock
private Handler mHandler;
@@ -98,13 +101,12 @@ public class BiometricsUnlockControllerTest extends SysuiTestCase {
when(mKeyguardBypassController.canPlaySubtleWindowAnimations()).thenReturn(true);
mContext.addMockSystemService(PowerManager.class, mPowerManager);
mDependency.injectTestDependency(NotificationMediaManager.class, mMediaManager);
- mDependency.injectTestDependency(StatusBarWindowController.class,
- mStatusBarWindowController);
res.addOverride(com.android.internal.R.integer.config_wakeUpDelayDoze, 0);
mBiometricUnlockController = new BiometricUnlockController(mContext, mDozeScrimController,
- mKeyguardViewMediator, mScrimController, mStatusBar, mKeyguardStateController,
- mHandler, mUpdateMonitor, res.getResources(), mKeyguardBypassController,
- mDozeParameters, mMetricsLogger, mDumpController);
+ mKeyguardViewMediator, mScrimController, mStatusBar, mShadeController,
+ mStatusBarWindowController, mKeyguardStateController, mHandler, mUpdateMonitor,
+ res.getResources(), mKeyguardBypassController, mDozeParameters, mMetricsLogger,
+ mDumpController);
mBiometricUnlockController.setStatusBarKeyguardViewManager(mStatusBarKeyguardViewManager);
}
@@ -113,7 +115,8 @@ public class BiometricsUnlockControllerTest extends SysuiTestCase {
mBiometricUnlockController.onBiometricAuthenticated(UserHandle.USER_CURRENT,
BiometricSourceType.FINGERPRINT);
verify(mStatusBarKeyguardViewManager).showBouncer(eq(false));
- verify(mStatusBarKeyguardViewManager).animateCollapsePanels(anyFloat());
+ verify(mShadeController).animateCollapsePanels(anyInt(), anyBoolean(), anyBoolean(),
+ anyFloat());
}
@Test
@@ -136,7 +139,8 @@ public class BiometricsUnlockControllerTest extends SysuiTestCase {
BiometricSourceType.FINGERPRINT);
verify(mStatusBarKeyguardViewManager, never()).showBouncer(anyBoolean());
- verify(mStatusBarKeyguardViewManager).animateCollapsePanels(anyFloat());
+ verify(mShadeController).animateCollapsePanels(anyInt(), anyBoolean(), anyBoolean(),
+ anyFloat());
}
@Test
@@ -155,7 +159,8 @@ public class BiometricsUnlockControllerTest extends SysuiTestCase {
mBiometricUnlockController.onBiometricAuthenticated(UserHandle.USER_CURRENT,
BiometricSourceType.FACE);
- verify(mStatusBarKeyguardViewManager, never()).animateCollapsePanels(anyFloat());
+ verify(mShadeController, never()).animateCollapsePanels(anyInt(), anyBoolean(),
+ anyBoolean(), anyFloat());
verify(mStatusBarKeyguardViewManager, never()).notifyKeyguardAuthenticated(anyBoolean());
}
@@ -168,7 +173,8 @@ public class BiometricsUnlockControllerTest extends SysuiTestCase {
mBiometricUnlockController.onBiometricAuthenticated(UserHandle.USER_CURRENT,
BiometricSourceType.FACE);
- verify(mStatusBarKeyguardViewManager, never()).animateCollapsePanels(anyFloat());
+ verify(mShadeController, never()).animateCollapsePanels(anyInt(), anyBoolean(),
+ anyBoolean(), anyFloat());
verify(mStatusBarKeyguardViewManager).notifyKeyguardAuthenticated(eq(false));
}
@@ -201,7 +207,8 @@ public class BiometricsUnlockControllerTest extends SysuiTestCase {
BiometricSourceType.FACE);
verify(mStatusBarKeyguardViewManager, never()).showBouncer(anyBoolean());
- verify(mStatusBarKeyguardViewManager, never()).animateCollapsePanels(anyFloat());
+ verify(mShadeController, never()).animateCollapsePanels(anyInt(), anyBoolean(),
+ anyBoolean(), anyFloat());
assertThat(mBiometricUnlockController.getMode())
.isEqualTo(BiometricUnlockController.MODE_NONE);
}
@@ -253,7 +260,8 @@ public class BiometricsUnlockControllerTest extends SysuiTestCase {
mBiometricUnlockController.onBiometricAuthenticated(UserHandle.USER_CURRENT,
BiometricSourceType.FACE);
- verify(mStatusBarKeyguardViewManager, never()).animateCollapsePanels(anyFloat());
+ verify(mShadeController, never()).animateCollapsePanels(anyInt(), anyBoolean(),
+ anyBoolean(), anyFloat());
}
@Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhoneTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhoneTest.java
index dfd994139af8..7fa69018b496 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhoneTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhoneTest.java
@@ -33,9 +33,9 @@ import com.android.systemui.bubbles.BubbleController;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.AlertingNotificationManager;
import com.android.systemui.statusbar.AlertingNotificationManagerTest;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.VisualStabilityManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.policy.AccessibilityManagerWrapper;
import com.android.systemui.statusbar.policy.ConfigurationController;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarFragmentTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarFragmentTest.java
index 0df2ebc8adfd..39afbe0a1a23 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarFragmentTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarFragmentTest.java
@@ -254,6 +254,7 @@ public class NavigationBarFragmentTest extends SysuiBaseFragmentTest {
mDivider,
Optional.of(mRecents),
() -> mock(StatusBar.class),
+ mock(ShadeController.class),
mHandler);
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationGroupTestHelper.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationGroupTestHelper.java
index 3ad1e39f441e..54dc728e0c8b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationGroupTestHelper.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationGroupTestHelper.java
@@ -26,8 +26,8 @@ import android.content.Context;
import android.os.UserHandle;
import com.android.systemui.R;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
/**
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java
index 4d6ff1f95caf..008a3499997d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java
@@ -760,6 +760,17 @@ public class ScrimControllerTest extends SysuiTestCase {
}
@Test
+ public void testWillHideDockedWallpaper() {
+ mAlwaysOnEnabled = false;
+ when(mDockManager.isDocked()).thenReturn(true);
+ mScrimController.setWallpaperSupportsAmbientMode(true);
+
+ mScrimController.transitionTo(ScrimState.AOD);
+
+ verify(mAlarmManager).setExact(anyInt(), anyLong(), any(), any(), any());
+ }
+
+ @Test
public void testConservesExpansionOpacityAfterTransition() {
mScrimController.transitionTo(ScrimState.UNLOCKED);
mScrimController.setPanelExpansion(0.5f);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java
index d7c00cf3038d..532192ba97ae 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java
@@ -111,6 +111,8 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
private Handler mHandler;
@Mock
private BubbleController mBubbleController;
+ @Mock
+ private ShadeControllerImpl mShadeController;
@Mock
private ActivityIntentHelper mActivityIntentHelper;
@@ -177,7 +179,7 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
mKeyguardStateController,
mock(NotificationInterruptionStateProvider.class), mock(MetricsLogger.class),
mock(LockPatternUtils.class), mHandler, mHandler, mActivityIntentHelper,
- mBubbleController, mSuperStatusBarViewFactory))
+ mBubbleController, mShadeController, mSuperStatusBarViewFactory))
.setStatusBar(mStatusBar)
.setNotificationPresenter(mock(NotificationPresenter.class))
.setActivityLaunchAnimator(mock(ActivityLaunchAnimator.class))
@@ -194,7 +196,7 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
// set up addPostCollapseAction to synchronously invoke the Runnable arg
doAnswer(answerVoid(Runnable::run))
- .when(mStatusBar).addPostCollapseAction(any(Runnable.class));
+ .when(mShadeController).addPostCollapseAction(any(Runnable.class));
// set up Handler to synchronously invoke the Runnable arg
doAnswer(answerVoid(Runnable::run))
@@ -219,7 +221,7 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
mNotificationActivityStarter.onNotificationClicked(sbn, mNotificationRow);
// Then
- verify(mStatusBar, atLeastOnce()).collapsePanel();
+ verify(mShadeController, atLeastOnce()).collapsePanel();
verify(mContentIntent).sendAndReturnResult(
any(Context.class),
@@ -254,7 +256,7 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
verify(mBubbleController).expandStackAndSelectBubble(eq(sbn.getKey()));
// This is called regardless, and simply short circuits when there is nothing to do.
- verify(mStatusBar, atLeastOnce()).collapsePanel();
+ verify(mShadeController, atLeastOnce()).collapsePanel();
verify(mAssistManager).hideAssist();
@@ -284,7 +286,7 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
// Then
verify(mBubbleController).expandStackAndSelectBubble(eq(sbn.getKey()));
- verify(mStatusBar, atLeastOnce()).collapsePanel();
+ verify(mShadeController, atLeastOnce()).collapsePanel();
verify(mAssistManager).hideAssist();
@@ -314,7 +316,7 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
// Then
verify(mBubbleController).expandStackAndSelectBubble(eq(sbn.getKey()));
- verify(mStatusBar, atLeastOnce()).collapsePanel();
+ verify(mShadeController, atLeastOnce()).collapsePanel();
verify(mAssistManager).hideAssist();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenterTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenterTest.java
index fb6e1684c376..f6ed4e6a2386 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenterTest.java
@@ -40,7 +40,6 @@ import com.android.systemui.SysuiTestCase;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.CommandQueue;
import com.android.systemui.statusbar.KeyguardIndicationController;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.NotificationLockscreenUserManager;
import com.android.systemui.statusbar.NotificationMediaManager;
import com.android.systemui.statusbar.NotificationRemoteInputManager;
@@ -54,6 +53,7 @@ import com.android.systemui.statusbar.notification.NotificationEntryManager;
import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.VisualStabilityManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.collection.NotificationRowBinderImpl;
import com.android.systemui.statusbar.notification.row.ActivatableNotificationView;
import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
@@ -115,7 +115,7 @@ public class StatusBarNotificationPresenterTest extends SysuiTestCase {
mock(NotificationAlertingManager.class),
mock(NotificationRowBinderImpl.class), mock(KeyguardStateController.class),
mock(KeyguardIndicationController.class),
- mStatusBar, mCommandQueue);
+ mStatusBar, mock(ShadeControllerImpl.class), mCommandQueue);
}
@Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallbackTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallbackTest.java
index 6dfd0828de9a..cd2c3498ce56 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallbackTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallbackTest.java
@@ -73,7 +73,7 @@ public class StatusBarRemoteInputCallbackTest extends SysuiTestCase {
mRemoteInputCallback = spy(new StatusBarRemoteInputCallback(mContext,
mock(NotificationGroupManager.class), mNotificationLockscreenUserManager,
mKeyguardStateController, mStatusBarStateController, mStatusBarKeyguardViewManager,
- mActivityStarter, () -> mShadeController, new CommandQueue(mContext)));
+ mActivityStarter, mShadeController, new CommandQueue(mContext)));
mRemoteInputCallback.mChallengeReceiver = mRemoteInputCallback.new ChallengeReceiver();
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java
index be6809732963..d3ae7a783404 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java
@@ -63,6 +63,7 @@ import android.util.DisplayMetrics;
import android.util.SparseArray;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
+import android.view.WindowManager;
import android.widget.LinearLayout;
import androidx.test.filters.SmallTest;
@@ -97,7 +98,6 @@ import com.android.systemui.statusbar.CommandQueue;
import com.android.systemui.statusbar.FeatureFlags;
import com.android.systemui.statusbar.KeyguardIndicationController;
import com.android.systemui.statusbar.NavigationBarController;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.NotificationListener;
import com.android.systemui.statusbar.NotificationLockscreenUserManager;
import com.android.systemui.statusbar.NotificationMediaManager;
@@ -119,6 +119,7 @@ import com.android.systemui.statusbar.notification.NotificationInterruptionState
import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator;
import com.android.systemui.statusbar.notification.VisualStabilityManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.collection.init.NewNotifPipeline;
import com.android.systemui.statusbar.notification.logging.NotificationLogger;
import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
@@ -243,6 +244,7 @@ public class StatusBarTest extends SysuiTestCase {
@Mock private LockscreenLockIconController mLockscreenLockIconController;
@Mock private StatusBarNotificationActivityStarter.Builder
mStatusBarNotificationActivityStarterBuilder;
+ private ShadeController mShadeController;
@Before
public void setup() throws Exception {
@@ -310,6 +312,11 @@ public class StatusBarTest extends SysuiTestCase {
when(mStatusBarComponent.getStatusBarWindowViewController()).thenReturn(
mStatusBarWindowViewController);
+ mShadeController = new ShadeControllerImpl(mCommandQueue,
+ mStatusBarStateController, mStatusBarWindowController,
+ mStatusBarKeyguardViewManager, mContext.getSystemService(WindowManager.class),
+ () -> mStatusBar, () -> mAssistManager, () -> mBubbleController);
+
mStatusBar = new StatusBar(
mContext,
mFeatureFlags,
@@ -382,6 +389,7 @@ public class StatusBarTest extends SysuiTestCase {
Optional.of(mDivider),
mLightsOutNotifController,
mStatusBarNotificationActivityStarterBuilder,
+ mShadeController,
mSuperStatusBarViewFactory,
mStatusBarKeyguardViewManager,
mViewMediatorCallback,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowViewTest.java
index 00ea18749de3..9f899ee117e9 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowViewTest.java
@@ -102,7 +102,7 @@ public class StatusBarWindowViewTest extends SysuiTestCase {
mDozeLog,
mDozeParameters,
new CommandQueue(mContext),
- () -> mShadeController,
+ mShadeController,
mDockManager,
mView);
mController.setupExpandedStatusBar();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/BluetoothControllerImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/BluetoothControllerImplTest.java
index e629a4f03586..fbbfa9611217 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/BluetoothControllerImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/BluetoothControllerImplTest.java
@@ -38,6 +38,7 @@ import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.bluetooth.CachedBluetoothDeviceManager;
import com.android.settingslib.bluetooth.LocalBluetoothAdapter;
import com.android.settingslib.bluetooth.LocalBluetoothManager;
+import com.android.settingslib.bluetooth.LocalBluetoothProfile;
import com.android.settingslib.bluetooth.LocalBluetoothProfileManager;
import com.android.systemui.SysuiTestCase;
@@ -204,4 +205,28 @@ public class BluetoothControllerImplTest extends SysuiTestCase {
assertTrue(mBluetoothControllerImpl.isBluetoothConnected());
verify(callback, atLeastOnce()).onBluetoothStateChange(anyBoolean());
}
+
+ @Test
+ public void testOnActiveDeviceChanged_updatesAudioActive() {
+ assertFalse(mBluetoothControllerImpl.isBluetoothAudioActive());
+ assertFalse(mBluetoothControllerImpl.isBluetoothAudioProfileOnly());
+
+ CachedBluetoothDevice device = mock(CachedBluetoothDevice.class);
+ mDevices.add(device);
+ when(device.isActiveDevice(BluetoothProfile.HEADSET)).thenReturn(true);
+
+ List<LocalBluetoothProfile> profiles = new ArrayList<>();
+ LocalBluetoothProfile profile = mock(LocalBluetoothProfile.class);
+ profiles.add(profile);
+ when(profile.getProfileId()).thenReturn(BluetoothProfile.HEADSET);
+ when(device.getProfiles()).thenReturn(profiles);
+ when(device.isConnectedProfile(profile)).thenReturn(true);
+
+ mBluetoothControllerImpl.onAclConnectionStateChanged(device,
+ BluetoothProfile.STATE_CONNECTED);
+ mBluetoothControllerImpl.onActiveDeviceChanged(device, BluetoothProfile.HEADSET);
+
+ assertTrue(mBluetoothControllerImpl.isBluetoothAudioActive());
+ assertTrue(mBluetoothControllerImpl.isBluetoothAudioProfileOnly());
+ }
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/InflatedSmartRepliesTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/InflatedSmartRepliesTest.java
index c1f376bee525..53d8e5866347 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/InflatedSmartRepliesTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/InflatedSmartRepliesTest.java
@@ -42,9 +42,9 @@ import com.android.systemui.SysuiTestCase;
import com.android.systemui.shared.system.ActivityManagerWrapper;
import com.android.systemui.shared.system.DevicePolicyManagerWrapper;
import com.android.systemui.shared.system.PackageManagerWrapper;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.NotificationEntryHelper;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.policy.InflatedSmartReplies.SmartRepliesAndActions;
import com.android.systemui.statusbar.policy.SmartReplyView.SmartActions;
import com.android.systemui.statusbar.policy.SmartReplyView.SmartReplies;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyViewTest.java
index b5e4cb965de8..f1a6e67edb43 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyViewTest.java
@@ -51,10 +51,10 @@ import com.android.systemui.R;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.plugins.ActivityStarter;
import com.android.systemui.plugins.ActivityStarter.OnDismissAction;
-import com.android.systemui.statusbar.NotificationEntryBuilder;
import com.android.systemui.statusbar.NotificationRemoteInputManager;
import com.android.systemui.statusbar.SmartReplyController;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.phone.KeyguardDismissUtil;
import com.android.systemui.statusbar.phone.ShadeController;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/DeviceConfigProxyFake.java b/packages/SystemUI/tests/src/com/android/systemui/util/DeviceConfigProxyFake.java
index 426aba03d5d8..260ff2dafeed 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/DeviceConfigProxyFake.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/DeviceConfigProxyFake.java
@@ -69,8 +69,11 @@ public class DeviceConfigProxyFake extends DeviceConfigProxy {
}
for (Pair<Executor, OnPropertiesChangedListener> listener : mListeners) {
- listener.first.execute(() -> listener.second.onPropertiesChanged(
- new Properties(namespace, mProperties.get(namespace))));
+ Properties.Builder propBuilder = new Properties.Builder(namespace);
+ for (String key : mProperties.get(namespace).keySet()) {
+ propBuilder.setString(key, mProperties.get(namespace).get(key));
+ }
+ listener.first.execute(() -> listener.second.onPropertiesChanged(propBuilder.build()));
}
return true;
}
@@ -88,10 +91,12 @@ public class DeviceConfigProxyFake extends DeviceConfigProxy {
private Properties propsForNamespaceAndName(String namespace, String name) {
if (mProperties.containsKey(namespace) && mProperties.get(namespace).containsKey(name)) {
- return new Properties(namespace, mProperties.get(namespace));
+ return new Properties.Builder(namespace)
+ .setString(name, mProperties.get(namespace).get(name)).build();
}
if (mDefaultProperties.containsKey(namespace)) {
- return new Properties(namespace, mDefaultProperties.get(namespace));
+ return new Properties.Builder(namespace)
+ .setString(name, mDefaultProperties.get(namespace).get(name)).build();
}
return null;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/animation/PhysicsAnimatorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/util/animation/PhysicsAnimatorTest.kt
new file mode 100644
index 000000000000..a39fbc4c232e
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/animation/PhysicsAnimatorTest.kt
@@ -0,0 +1,436 @@
+package com.android.systemui.util.animation
+
+import android.testing.AndroidTestingRunner
+import android.testing.TestableLooper
+import android.util.ArrayMap
+import android.view.View
+import android.view.ViewGroup
+import android.widget.FrameLayout
+import androidx.dynamicanimation.animation.DynamicAnimation
+import androidx.dynamicanimation.animation.FloatPropertyCompat
+import androidx.dynamicanimation.animation.SpringForce
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.util.animation.PhysicsAnimator.EndListener
+import com.android.systemui.util.animation.PhysicsAnimator.UpdateListener
+import com.android.systemui.util.animation.PhysicsAnimatorTestUtils.clearAnimationUpdateFrames
+import com.android.systemui.util.animation.PhysicsAnimatorTestUtils.getAnimationUpdateFrames
+import com.android.systemui.util.animation.PhysicsAnimatorTestUtils.verifyAnimationUpdateFrames
+import org.junit.After
+import org.junit.Assert
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotEquals
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.ArgumentMatchers.anyFloat
+import org.mockito.Mockito
+import org.mockito.Mockito.mock
+import org.mockito.Mockito.times
+import org.mockito.Mockito.verify
+import org.mockito.Mockito.verifyNoMoreInteractions
+import org.mockito.MockitoAnnotations
+
+@TestableLooper.RunWithLooper
+@RunWith(AndroidTestingRunner::class)
+@SmallTest
+class PhysicsAnimatorTest : SysuiTestCase() {
+ private lateinit var viewGroup: ViewGroup
+ private lateinit var testView: View
+ private lateinit var testView2: View
+
+ private lateinit var animator: PhysicsAnimator<View>
+
+ private val springConfig = PhysicsAnimator.SpringConfig(
+ SpringForce.STIFFNESS_LOW, SpringForce.DAMPING_RATIO_NO_BOUNCY)
+ private val flingConfig = PhysicsAnimator.FlingConfig(2f)
+
+ private lateinit var mockUpdateListener: UpdateListener<View>
+ private lateinit var mockEndListener: EndListener<View>
+ private lateinit var mockEndAction: Runnable
+
+ private fun <T> eq(value: T): T = Mockito.eq(value) ?: value
+
+ @Before
+ fun setup() {
+ MockitoAnnotations.initMocks(this)
+
+ mockUpdateListener = mock(UpdateListener::class.java) as UpdateListener<View>
+ mockEndListener = mock(EndListener::class.java) as EndListener<View>
+ mockEndAction = mock(Runnable::class.java)
+
+ viewGroup = FrameLayout(context)
+ testView = View(context)
+ testView2 = View(context)
+ viewGroup.addView(testView)
+ viewGroup.addView(testView2)
+
+ PhysicsAnimatorTestUtils.prepareForTest()
+
+ // Most of our tests involve checking the end state of animations, so we want calls that
+ // start animations to block the test thread until the animations have ended.
+ PhysicsAnimatorTestUtils.setAllAnimationsBlock(true)
+
+ animator = PhysicsAnimator.getInstance(testView)
+ }
+
+ @After
+ fun tearDown() {
+ PhysicsAnimatorTestUtils.tearDown()
+ }
+
+ @Test
+ fun testOneAnimatorPerView() {
+ assertEquals(animator, PhysicsAnimator.getInstance(testView))
+ assertEquals(PhysicsAnimator.getInstance(testView), PhysicsAnimator.getInstance(testView))
+ assertNotEquals(animator, PhysicsAnimator.getInstance(testView2))
+ }
+
+ @Test
+ fun testSpringOneProperty() {
+ animator
+ .spring(DynamicAnimation.TRANSLATION_X, 50f, springConfig)
+ .start()
+
+ assertEquals(testView.translationX, 50f, 1f)
+ }
+
+ @Test
+ fun testSpringMultipleProperties() {
+ animator
+ .spring(DynamicAnimation.TRANSLATION_X, 10f, springConfig)
+ .spring(DynamicAnimation.TRANSLATION_Y, 50f, springConfig)
+ .spring(DynamicAnimation.SCALE_Y, 1.1f, springConfig)
+ .start()
+
+ assertEquals(10f, testView.translationX, 1f)
+ assertEquals(50f, testView.translationY, 1f)
+ assertEquals(1.1f, testView.scaleY, 0.01f)
+ }
+
+ @Test
+ fun testFling() {
+ val startTime = System.currentTimeMillis()
+
+ animator
+ .fling(DynamicAnimation.TRANSLATION_X, 1000f /* startVelocity */, flingConfig)
+ .fling(DynamicAnimation.TRANSLATION_Y, 500f, flingConfig)
+ .start()
+
+ val elapsedTimeSeconds = (System.currentTimeMillis() - startTime) / 1000f
+
+ // If the fling worked, the view should be somewhere between its starting position and the
+ // and the theoretical no-friction maximum of startVelocity (in pixels per second)
+ // multiplied by elapsedTimeSeconds. We can't calculate an exact expected location for a
+ // fling, so this is close enough.
+ assertTrue(testView.translationX > 0f)
+ assertTrue(testView.translationX < 1000f * elapsedTimeSeconds)
+ assertTrue(testView.translationY > 0f)
+ assertTrue(testView.translationY < 500f * elapsedTimeSeconds)
+ }
+
+ @Test
+ @Throws(InterruptedException::class)
+ fun testEndListenersAndActions() {
+ PhysicsAnimatorTestUtils.setAllAnimationsBlock(false)
+ animator
+ .spring(DynamicAnimation.TRANSLATION_X, 10f, springConfig)
+ .spring(DynamicAnimation.TRANSLATION_Y, 500f, springConfig)
+ .addEndListener(mockEndListener)
+ .withEndActions(mockEndAction::run)
+ .start()
+
+ PhysicsAnimatorTestUtils.blockUntilAnimationsEnd(animator, DynamicAnimation.TRANSLATION_X)
+
+ // Once TRANSLATION_X is done, the view should be at x = 10...
+ assertEquals(10f, testView.translationX, 1f)
+
+ // / ...TRANSLATION_Y should still be running...
+ assertTrue(animator.isPropertyAnimating(DynamicAnimation.TRANSLATION_Y))
+
+ // ...and our end listener should have been called with x = 10, velocity = 0, and allEnded =
+ // false since TRANSLATION_Y is still running.
+ verify(mockEndListener).onAnimationEnd(
+ testView,
+ DynamicAnimation.TRANSLATION_X,
+ canceled = false,
+ finalValue = 10f,
+ finalVelocity = 0f,
+ allRelevantPropertyAnimsEnded = false)
+ verifyNoMoreInteractions(mockEndListener)
+
+ // The end action should not have been run yet.
+ verify(mockEndAction, times(0)).run()
+
+ // Block until TRANSLATION_Y finishes.
+ PhysicsAnimatorTestUtils.blockUntilAnimationsEnd(animator, DynamicAnimation.TRANSLATION_Y)
+
+ // The view should have been moved.
+ assertEquals(10f, testView.translationX, 1f)
+ assertEquals(500f, testView.translationY, 1f)
+
+ // The end listener should have been called, this time with TRANSLATION_Y, y = 50, and
+ // allEnded = true.
+ verify(mockEndListener).onAnimationEnd(
+ testView,
+ DynamicAnimation.TRANSLATION_Y,
+ canceled = false,
+ finalValue = 500f,
+ finalVelocity = 0f,
+ allRelevantPropertyAnimsEnded = true)
+ verifyNoMoreInteractions(mockEndListener)
+
+ // Now that all properties are done animating, the end action should have been called.
+ verify(mockEndAction, times(1)).run()
+ }
+
+ @Test
+ fun testUpdateListeners() {
+ animator
+ .spring(DynamicAnimation.TRANSLATION_X, 100f, springConfig)
+ .spring(DynamicAnimation.TRANSLATION_Y, 50f, springConfig)
+ .addUpdateListener(object : UpdateListener<View> {
+ override fun onAnimationUpdateForProperty(
+ target: View,
+ values: UpdateMap<View>
+ ) {
+ mockUpdateListener.onAnimationUpdateForProperty(target, values)
+ }
+ })
+ .start()
+
+ verifyUpdateListenerCalls(animator, mockUpdateListener)
+ }
+
+ @Test
+ fun testListenersNotCalledOnSubsequentAnimations() {
+ animator
+ .spring(DynamicAnimation.TRANSLATION_X, 10f, springConfig)
+ .addUpdateListener(mockUpdateListener)
+ .addEndListener(mockEndListener)
+ .withEndActions(mockEndAction::run)
+ .start()
+
+ verifyUpdateListenerCalls(animator, mockUpdateListener)
+ verify(mockEndListener, times(1)).onAnimationEnd(
+ eq(testView), eq(DynamicAnimation.TRANSLATION_X), eq(false), anyFloat(), anyFloat(),
+ eq(true))
+ verify(mockEndAction, times(1)).run()
+
+ animator
+ .spring(DynamicAnimation.TRANSLATION_X, 0f, springConfig)
+ .start()
+
+ // We didn't pass any of the listeners/actions to the subsequent animation, so they should
+ // never have been called.
+ verifyNoMoreInteractions(mockUpdateListener)
+ verifyNoMoreInteractions(mockEndListener)
+ verifyNoMoreInteractions(mockEndAction)
+ }
+
+ @Test
+ @Throws(InterruptedException::class)
+ fun testAnimationsUpdatedWhileInMotion() {
+ PhysicsAnimatorTestUtils.setAllAnimationsBlock(false)
+
+ // Spring towards x = 100f.
+ animator
+ .spring(
+ DynamicAnimation.TRANSLATION_X,
+ 100f,
+ springConfig)
+ .start()
+
+ // Block until it reaches x = 50f.
+ PhysicsAnimatorTestUtils.blockUntilFirstAnimationFrameWhereTrue(
+ animator) { view -> view.translationX > 50f }
+
+ // Translation X value at the time of reversing the animation to spring to x = 0f.
+ val reversalTranslationX = testView.translationX
+
+ // Spring back towards 0f.
+ animator
+ .spring(
+ DynamicAnimation.TRANSLATION_X,
+ 0f,
+ // Lower the stiffness to ensure the update listener receives at least one
+ // update frame where the view has continued to move to the right.
+ springConfig.apply { stiffness = SpringForce.STIFFNESS_LOW })
+ .start()
+
+ // Wait for TRANSLATION_X.
+ PhysicsAnimatorTestUtils.blockUntilAnimationsEnd(animator, DynamicAnimation.TRANSLATION_X)
+
+ // Verify that the animation continued past the X value at the time of reversal, before
+ // springing back. This ensures the change in direction was not abrupt.
+ verifyAnimationUpdateFrames(
+ animator, DynamicAnimation.TRANSLATION_X,
+ { u -> u.value > reversalTranslationX },
+ { u -> u.value < reversalTranslationX })
+
+ // Verify that the view is where it should be.
+ assertEquals(0f, testView.translationX, 1f)
+ }
+
+ @Test
+ @Throws(InterruptedException::class)
+ fun testAnimationsUpdatedWhileInMotion_originalListenersStillCalled() {
+ PhysicsAnimatorTestUtils.setAllAnimationsBlock(false)
+
+ // Spring TRANSLATION_X to 100f, with an update and end listener provided.
+ animator
+ .spring(DynamicAnimation.TRANSLATION_X, 100f, springConfig)
+ .addUpdateListener(mockUpdateListener)
+ .addEndListener(mockEndListener)
+ .start()
+
+ // Wait until the animation is halfway there.
+ PhysicsAnimatorTestUtils.blockUntilFirstAnimationFrameWhereTrue(
+ animator) { view -> view.translationX > 50f }
+
+ // The end listener shouldn't have been called since the animation hasn't ended.
+ verifyNoMoreInteractions(mockEndListener)
+
+ // Make sure we called the update listener with appropriate values.
+ verifyAnimationUpdateFrames(animator, DynamicAnimation.TRANSLATION_X,
+ { u -> u.value > 0f },
+ { u -> u.value >= 50f })
+
+ // Mock a second end listener.
+ val secondEndListener = mock(EndListener::class.java) as EndListener<View>
+ val secondUpdateListener = mock(UpdateListener::class.java) as UpdateListener<View>
+
+ // Start a new animation that springs both TRANSLATION_X and TRANSLATION_Y, and provide it
+ // the second end listener. This new end listener should be called for the end of
+ // TRANSLATION_X and TRANSLATION_Y, with allEnded = true when both have ended.
+ animator
+ .spring(DynamicAnimation.TRANSLATION_X, 200f, springConfig)
+ .spring(DynamicAnimation.TRANSLATION_Y, 4000f, springConfig)
+ .addUpdateListener(secondUpdateListener)
+ .addEndListener(secondEndListener)
+ .start()
+
+ // Wait for TRANSLATION_X to end.
+ PhysicsAnimatorTestUtils.blockUntilAnimationsEnd(animator, DynamicAnimation.TRANSLATION_X)
+
+ // The update listener provided to the initial animation call (the one that only animated
+ // TRANSLATION_X) should have been called with values on the way to x = 200f. This is
+ // because the second animation call updated the original TRANSLATION_X animation.
+ verifyAnimationUpdateFrames(
+ animator, DynamicAnimation.TRANSLATION_X,
+ { u -> u.value > 100f }, { u -> u.value >= 200f })
+
+ // The original end listener should also have been called, with allEnded = true since it was
+ // provided to an animator that animated only TRANSLATION_X.
+ verify(mockEndListener, times(1))
+ .onAnimationEnd(testView, DynamicAnimation.TRANSLATION_X, false, 200f, 0f, true)
+ verifyNoMoreInteractions(mockEndListener)
+
+ // The second end listener should have been called, but with allEnded = false since it was
+ // provided to an animator that animated both TRANSLATION_X and TRANSLATION_Y.
+ verify(secondEndListener, times(1))
+ .onAnimationEnd(testView, DynamicAnimation.TRANSLATION_X, false, 200f, 0f, false)
+ verifyNoMoreInteractions(secondEndListener)
+
+ PhysicsAnimatorTestUtils.blockUntilAnimationsEnd(animator, DynamicAnimation.TRANSLATION_Y)
+
+ // The original end listener shouldn't receive any callbacks because it was not provided to
+ // an animator that animated TRANSLATION_Y.
+ verifyNoMoreInteractions(mockEndListener)
+
+ verify(secondEndListener, times(1))
+ .onAnimationEnd(testView, DynamicAnimation.TRANSLATION_Y, false, 4000f, 0f, true)
+ verifyNoMoreInteractions(secondEndListener)
+ }
+
+ @Test
+ fun testFlingRespectsMinMax() {
+ animator
+ .fling(DynamicAnimation.TRANSLATION_X,
+ startVelocity = 1000f,
+ friction = 1.1f,
+ max = 10f)
+ .addEndListener(mockEndListener)
+ .start()
+
+ // Ensure that the view stopped at x = 10f, and the end listener was called once with that
+ // value.
+ assertEquals(10f, testView.translationX, 1f)
+ verify(mockEndListener, times(1))
+ .onAnimationEnd(
+ eq(testView), eq(DynamicAnimation.TRANSLATION_X), eq(false), eq(10f),
+ anyFloat(), eq(true))
+
+ animator
+ .fling(
+ DynamicAnimation.TRANSLATION_X,
+ startVelocity = -1000f,
+ friction = 1.1f,
+ min = -5f)
+ .addEndListener(mockEndListener)
+ .start()
+
+ // Ensure that the view stopped at x = -5f, and the end listener was called once with that
+ // value.
+ assertEquals(-5f, testView.translationX, 1f)
+ verify(mockEndListener, times(1))
+ .onAnimationEnd(
+ eq(testView), eq(DynamicAnimation.TRANSLATION_X), eq(false), eq(-5f),
+ anyFloat(), eq(true))
+ }
+
+ @Test
+ fun testExtensionProperty() {
+ testView
+ .physicsAnimator
+ .spring(DynamicAnimation.TRANSLATION_X, 200f)
+ .start()
+
+ assertEquals(200f, testView.translationX, 1f)
+ }
+
+ /**
+ * Verifies that the calls to the mock update listener match the animation update frames
+ * reported by the test internal listener, in order.
+ */
+ private fun <T : Any> verifyUpdateListenerCalls(
+ animator: PhysicsAnimator<T>,
+ mockUpdateListener: UpdateListener<T>
+ ) {
+ val updates = getAnimationUpdateFrames(animator)
+
+ for (invocation in Mockito.mockingDetails(mockUpdateListener).invocations) {
+
+ // Grab the update map of Property -> AnimationUpdate that was passed to the mock update
+ // listener.
+ val updateMap = invocation.arguments[1]
+ as ArrayMap<FloatPropertyCompat<in T>, PhysicsAnimator.AnimationUpdate>
+
+ //
+ for ((property, update) in updateMap) {
+ val updatesForProperty = updates[property]!!
+
+ // This update should be the next one in the list for this property.
+ if (update != updatesForProperty[0]) {
+ Assert.fail("The update listener was called with an unexpected value: $update.")
+ }
+
+ updatesForProperty.remove(update)
+ }
+
+ // Mark this invocation verified.
+ verify(mockUpdateListener).onAnimationUpdateForProperty(animator.target, updateMap)
+ }
+
+ verifyNoMoreInteractions(mockUpdateListener)
+
+ // Since we were removing values as matching invocations were found, there should no longer
+ // be any values remaining. If there are, it means the update listener wasn't notified when
+ // it should have been.
+ assertEquals(0,
+ updates.values.fold(0, { count, propertyUpdates -> count + propertyUpdates.size }))
+
+ clearAnimationUpdateFrames(animator)
+ }
+} \ No newline at end of file
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/concurrency/FakeExecutorTest.java b/packages/SystemUI/tests/src/com/android/systemui/util/concurrency/FakeExecutorTest.java
index b1716ff47129..bd641243be12 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/concurrency/FakeExecutorTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/concurrency/FakeExecutorTest.java
@@ -49,7 +49,6 @@ public class FakeExecutorTest extends SysuiTestCase {
@Test
public void testNoDelay() {
FakeSystemClock clock = new FakeSystemClock();
- clock.setAutoIncrement(false);
FakeExecutor fakeExecutor = new FakeExecutor(clock);
RunnableImpl runnable = new RunnableImpl();
@@ -99,7 +98,6 @@ public class FakeExecutorTest extends SysuiTestCase {
@Test
public void testDelayed() {
FakeSystemClock clock = new FakeSystemClock();
- clock.setAutoIncrement(false);
FakeExecutor fakeExecutor = new FakeExecutor(clock);
RunnableImpl runnable = new RunnableImpl();
@@ -134,7 +132,6 @@ public class FakeExecutorTest extends SysuiTestCase {
@Test
public void testDelayed_AdvanceAndRun() {
FakeSystemClock clock = new FakeSystemClock();
- clock.setAutoIncrement(false);
FakeExecutor fakeExecutor = new FakeExecutor(clock);
RunnableImpl runnable = new RunnableImpl();
@@ -181,7 +178,6 @@ public class FakeExecutorTest extends SysuiTestCase {
@Test
public void testExecutionOrder() {
FakeSystemClock clock = new FakeSystemClock();
- clock.setAutoIncrement(false);
FakeExecutor fakeExecutor = new FakeExecutor(clock);
RunnableImpl runnableA = new RunnableImpl();
RunnableImpl runnableB = new RunnableImpl();
@@ -251,7 +247,6 @@ public class FakeExecutorTest extends SysuiTestCase {
@Test
public void testRemoval_single() {
FakeSystemClock clock = new FakeSystemClock();
- clock.setAutoIncrement(false);
FakeExecutor fakeExecutor = new FakeExecutor(clock);
RunnableImpl runnable = new RunnableImpl();
Runnable removeFunction;
@@ -291,7 +286,6 @@ public class FakeExecutorTest extends SysuiTestCase {
@Test
public void testRemoval_multi() {
FakeSystemClock clock = new FakeSystemClock();
- clock.setAutoIncrement(false);
FakeExecutor fakeExecutor = new FakeExecutor(clock);
List<Runnable> removeFunctions = new ArrayList<>();
RunnableImpl runnable = new RunnableImpl();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/time/FakeSystemClock.java b/packages/SystemUI/tests/src/com/android/systemui/util/time/FakeSystemClock.java
index 65e5902c84df..e94eaafdb692 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/time/FakeSystemClock.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/time/FakeSystemClock.java
@@ -20,8 +20,6 @@ import java.util.ArrayList;
import java.util.List;
public class FakeSystemClock implements SystemClock {
- private boolean mAutoIncrement = true;
-
private long mUptimeMillis;
private long mElapsedRealtime;
private long mElapsedRealtimeNanos;
@@ -34,54 +32,36 @@ public class FakeSystemClock implements SystemClock {
@Override
public long uptimeMillis() {
long value = mUptimeMillis;
- if (mAutoIncrement) {
- setUptimeMillis(mUptimeMillis + 1);
- }
return value;
}
@Override
public long elapsedRealtime() {
long value = mElapsedRealtime;
- if (mAutoIncrement) {
- setElapsedRealtime(mElapsedRealtime + 1);
- }
return value;
}
@Override
public long elapsedRealtimeNanos() {
long value = mElapsedRealtimeNanos;
- if (mAutoIncrement) {
- setElapsedRealtimeNanos(mElapsedRealtimeNanos + 1);
- }
return value;
}
@Override
public long currentThreadTimeMillis() {
long value = mCurrentThreadTimeMillis;
- if (mAutoIncrement) {
- setCurrentThreadTimeMillis(mCurrentThreadTimeMillis + 1);
- }
return value;
}
@Override
public long currentThreadTimeMicro() {
long value = mCurrentThreadTimeMicro;
- if (mAutoIncrement) {
- setCurrentThreadTimeMicro(mCurrentThreadTimeMicro + 1);
- }
return value;
}
@Override
public long currentTimeMicro() {
long value = mCurrentTimeMicro;
- if (mAutoIncrement) {
- setCurrentTimeMicro(mCurrentTimeMicro + 1);
- }
return value;
}
@@ -127,11 +107,6 @@ public class FakeSystemClock implements SystemClock {
}
}
- /** If true, each call to get____ will be one higher than the previous call to that method. */
- public void setAutoIncrement(boolean autoIncrement) {
- mAutoIncrement = autoIncrement;
- }
-
public void addListener(ClockTickListener listener) {
mListeners.add(listener);
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakeBluetoothController.java b/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakeBluetoothController.java
index cac6bf7ca3f0..6cbd175c1084 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakeBluetoothController.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakeBluetoothController.java
@@ -57,6 +57,16 @@ public class FakeBluetoothController extends BaseLeakChecker<Callback> implement
}
@Override
+ public boolean isBluetoothAudioProfileOnly() {
+ return false;
+ }
+
+ @Override
+ public boolean isBluetoothAudioActive() {
+ return false;
+ }
+
+ @Override
public String getConnectedDeviceName() {
return null;
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/volume/EventsTest.java b/packages/SystemUI/tests/src/com/android/systemui/volume/EventsTest.java
new file mode 100644
index 000000000000..701b2fab5f85
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/volume/EventsTest.java
@@ -0,0 +1,215 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.volume;
+
+import static org.junit.Assert.assertEquals;
+
+import android.media.AudioManager;
+import android.media.AudioSystem;
+import android.metrics.LogMaker;
+import android.provider.Settings;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.internal.logging.UiEventLogger;
+import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
+import com.android.internal.logging.testing.FakeMetricsLogger;
+import com.android.internal.logging.testing.UiEventLoggerFake;
+import com.android.systemui.SysuiTestCase;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Queue;
+
+/**
+ * Parameterized unit test for Events.logEvent.
+ *
+ * This test captures a translation table between the Event class tags, the debugging logs,
+ * the event-buffer logs, and the statsd logs.
+ *
+ * This test works as a straight JUnit4 test, but is declared as a SysuiTestCase because
+ * AAAPlusPlusVerifySysuiRequiredTestPropertiesTest requires all tests in SystemUiTest extend
+ * either SysuiTestCase or SysUiBaseFragmentTest.
+ *
+ */
+@RunWith(Parameterized.class)
+@SmallTest
+public class EventsTest extends SysuiTestCase {
+ private FakeMetricsLogger mLegacyLogger;
+ private UiEventLoggerFake mUiEventLogger;
+
+ @Before
+ public void setFakeLoggers() {
+ mLegacyLogger = new FakeMetricsLogger();
+ Events.sLegacyLogger = mLegacyLogger;
+ mUiEventLogger = new UiEventLoggerFake();
+ Events.sUiEventLogger = mUiEventLogger;
+ }
+
+ // Parameters for calling writeEvent with arbitrary args.
+ @Parameterized.Parameter
+ public int mTag;
+
+ @Parameterized.Parameter(1)
+ public Object[] mArgs;
+
+ // Expect returned string exactly matches.
+ @Parameterized.Parameter(2)
+ public String mExpectedMessage;
+
+ // Expect these MetricsLogger calls.
+
+ @Parameterized.Parameter(3)
+ public int[] mExpectedMetrics;
+
+ // Expect this UiEvent (use null if there isn't one).
+ @Parameterized.Parameter(4)
+ public UiEventLogger.UiEventEnum mUiEvent;
+
+ @Test
+ public void testLogEvent() {
+ String result = Events.logEvent(mTag, mArgs);
+ assertEquals("Show Dialog", mExpectedMessage, result);
+
+ Queue<LogMaker> logs = mLegacyLogger.getLogs();
+ if (mExpectedMetrics == null) {
+ assertEquals(0, logs.size());
+ } else {
+ assertEquals(mExpectedMetrics.length, logs.size());
+ if (mExpectedMetrics.length > 0) {
+ assertEquals(mExpectedMetrics[0], logs.remove().getCategory());
+ }
+ if (mExpectedMetrics.length > 1) {
+ assertEquals(mExpectedMetrics[1], logs.remove().getCategory());
+ }
+ }
+ Queue<UiEventLoggerFake.FakeUiEvent> events = mUiEventLogger.getLogs();
+ if (mUiEvent != null) {
+ assertEquals(mUiEvent.getId(), events.remove().eventId);
+ }
+ }
+
+ @Parameterized.Parameters(name = "{index}: {2}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][]{
+ {Events.EVENT_SETTINGS_CLICK, null,
+ "writeEvent settings_click",
+ new int[]{MetricsEvent.ACTION_VOLUME_SETTINGS},
+ Events.VolumeDialogEvent.VOLUME_DIALOG_SETTINGS_CLICK},
+ {Events.EVENT_SHOW_DIALOG, new Object[]{Events.SHOW_REASON_VOLUME_CHANGED, false},
+ "writeEvent show_dialog volume_changed keyguard=false",
+ new int[]{MetricsEvent.VOLUME_DIALOG,
+ MetricsEvent.RESERVED_FOR_LOGBUILDER_HISTOGRAM},
+ Events.VolumeDialogOpenEvent.VOLUME_DIALOG_SHOW_VOLUME_CHANGED},
+ {Events.EVENT_EXPAND, new Object[]{true},
+ "writeEvent expand true",
+ new int[]{MetricsEvent.VOLUME_DIALOG_DETAILS},
+ Events.VolumeDialogEvent.VOLUME_DIALOG_EXPAND_DETAILS},
+ {Events.EVENT_DISMISS_DIALOG,
+ new Object[]{Events.DISMISS_REASON_TOUCH_OUTSIDE, true},
+ "writeEvent dismiss_dialog touch_outside",
+ new int[]{MetricsEvent.VOLUME_DIALOG},
+ Events.VolumeDialogCloseEvent.VOLUME_DIALOG_DISMISS_TOUCH_OUTSIDE},
+ {Events.EVENT_ACTIVE_STREAM_CHANGED, new Object[]{AudioSystem.STREAM_ACCESSIBILITY},
+ "writeEvent active_stream_changed STREAM_ACCESSIBILITY",
+ new int[]{MetricsEvent.ACTION_VOLUME_STREAM},
+ Events.VolumeDialogEvent.VOLUME_DIALOG_ACTIVE_STREAM_CHANGED},
+ {Events.EVENT_ICON_CLICK,
+ new Object[]{AudioSystem.STREAM_MUSIC, Events.ICON_STATE_MUTE},
+ "writeEvent icon_click STREAM_MUSIC mute",
+ new int[]{MetricsEvent.ACTION_VOLUME_ICON},
+ Events.VolumeDialogEvent.VOLUME_DIALOG_MUTE_STREAM},
+ {Events.EVENT_TOUCH_LEVEL_DONE,
+ new Object[]{AudioSystem.STREAM_MUSIC, /* volume */ 0},
+ "writeEvent touch_level_done STREAM_MUSIC 0",
+ new int[]{MetricsEvent.ACTION_VOLUME_SLIDER},
+ Events.VolumeDialogEvent.VOLUME_DIALOG_SLIDER_TO_ZERO},
+ {Events.EVENT_TOUCH_LEVEL_DONE,
+ new Object[]{AudioSystem.STREAM_MUSIC, /* volume */ 1},
+ "writeEvent touch_level_done STREAM_MUSIC 1",
+ new int[]{MetricsEvent.ACTION_VOLUME_SLIDER},
+ Events.VolumeDialogEvent.VOLUME_DIALOG_SLIDER},
+ {Events.EVENT_TOUCH_LEVEL_CHANGED,
+ new Object[]{AudioSystem.STREAM_MUSIC, /* volume */ 0},
+ "writeEvent touch_level_changed STREAM_MUSIC 0",
+ null, null},
+ {Events.EVENT_LEVEL_CHANGED,
+ new Object[]{AudioSystem.STREAM_MUSIC, /* volume */ 0},
+ "writeEvent level_changed STREAM_MUSIC 0",
+ null, null},
+ {Events.EVENT_MUTE_CHANGED,
+ new Object[]{AudioSystem.STREAM_MUSIC, /* volume */ 0},
+ "writeEvent mute_changed STREAM_MUSIC 0",
+ null, null},
+ {Events.EVENT_KEY,
+ new Object[]{AudioSystem.STREAM_MUSIC, /* volume */ 0},
+ "writeEvent key STREAM_MUSIC 0",
+ new int[]{MetricsEvent.ACTION_VOLUME_KEY},
+ Events.VolumeDialogEvent.VOLUME_KEY_TO_ZERO},
+ {Events.EVENT_KEY,
+ new Object[]{AudioSystem.STREAM_MUSIC, /* volume */ 1},
+ "writeEvent key STREAM_MUSIC 1",
+ new int[]{MetricsEvent.ACTION_VOLUME_KEY},
+ Events.VolumeDialogEvent.VOLUME_KEY},
+ {Events.EVENT_RINGER_TOGGLE, new Object[]{AudioManager.RINGER_MODE_NORMAL},
+ "writeEvent ringer_toggle normal",
+ new int[]{MetricsEvent.ACTION_VOLUME_RINGER_TOGGLE},
+ Events.VolumeDialogEvent.RINGER_MODE_NORMAL},
+ {Events.EVENT_EXTERNAL_RINGER_MODE_CHANGED,
+ new Object[]{AudioManager.RINGER_MODE_NORMAL},
+ "writeEvent external_ringer_mode_changed normal",
+ new int[]{MetricsEvent.ACTION_RINGER_MODE},
+ null},
+ {Events.EVENT_INTERNAL_RINGER_MODE_CHANGED,
+ new Object[]{AudioManager.RINGER_MODE_NORMAL},
+ "writeEvent internal_ringer_mode_changed normal",
+ null, null},
+ {Events.EVENT_ZEN_MODE_CHANGED,
+ new Object[]{Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS},
+ "writeEvent zen_mode_changed important_interruptions",
+ null, Events.ZenModeEvent.ZEN_MODE_IMPORTANT_ONLY},
+ {Events.EVENT_ZEN_MODE_CHANGED,
+ new Object[]{Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS},
+ "writeEvent zen_mode_changed important_interruptions",
+ null, Events.ZenModeEvent.ZEN_MODE_IMPORTANT_ONLY},
+ {Events.EVENT_SUPPRESSOR_CHANGED,
+ new Object[]{"component", "name"},
+ "writeEvent suppressor_changed component name",
+ null, null},
+ {Events.EVENT_SHOW_USB_OVERHEAT_ALARM,
+ new Object[]{Events.SHOW_REASON_USB_OVERHEAD_ALARM_CHANGED, true},
+ "writeEvent show_usb_overheat_alarm usb_temperature_above_threshold "
+ + "keyguard=true",
+ new int[]{MetricsEvent.POWER_OVERHEAT_ALARM,
+ MetricsEvent.RESERVED_FOR_LOGBUILDER_HISTOGRAM},
+ Events.VolumeDialogEvent.USB_OVERHEAT_ALARM},
+ {Events.EVENT_DISMISS_USB_OVERHEAT_ALARM,
+ new Object[]{Events.DISMISS_REASON_USB_OVERHEAD_ALARM_CHANGED, true},
+ "writeEvent dismiss_usb_overheat_alarm usb_temperature_below_threshold "
+ + "keyguard=true",
+ new int[]{MetricsEvent.POWER_OVERHEAT_ALARM,
+ MetricsEvent.RESERVED_FOR_LOGBUILDER_HISTOGRAM},
+ Events.VolumeDialogEvent.USB_OVERHEAT_ALARM_DISMISSED},
+ });
+ }
+}
+
diff --git a/packages/SystemUI/tests/src/com/android/systemui/wm/DisplayLayoutTest.java b/packages/SystemUI/tests/src/com/android/systemui/wm/DisplayLayoutTest.java
new file mode 100644
index 000000000000..9596a73eaf3e
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/wm/DisplayLayoutTest.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright (C) 2019 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 com.android.systemui.wm;
+
+import static android.content.res.Configuration.UI_MODE_TYPE_NORMAL;
+import static android.view.Surface.ROTATION_0;
+import static android.view.Surface.ROTATION_270;
+import static android.view.Surface.ROTATION_90;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+
+import android.content.res.Configuration;
+import android.content.res.Resources;
+import android.graphics.Insets;
+import android.graphics.Rect;
+import android.view.DisplayCutout;
+import android.view.DisplayInfo;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.internal.R;
+import com.android.systemui.SysuiTestCase;
+
+import org.junit.Test;
+
+@SmallTest
+public class DisplayLayoutTest extends SysuiTestCase {
+
+ @Test
+ public void testInsets() {
+ Resources res = createResources(40, 50, false, 30, 40);
+ // Test empty display, no bars or anything
+ DisplayInfo info = createDisplayInfo(1000, 1500, 0, ROTATION_0);
+ DisplayLayout dl = new DisplayLayout(info, res, false, false);
+ assertEquals(new Rect(0, 0, 0, 0), dl.stableInsets());
+ assertEquals(new Rect(0, 0, 0, 0), dl.nonDecorInsets());
+
+ // Test with bars
+ dl = new DisplayLayout(info, res, true, true);
+ assertEquals(new Rect(0, 40, 0, 50), dl.stableInsets());
+ assertEquals(new Rect(0, 0, 0, 50), dl.nonDecorInsets());
+
+ // Test just cutout
+ info = createDisplayInfo(1000, 1500, 60, ROTATION_0);
+ dl = new DisplayLayout(info, res, false, false);
+ assertEquals(new Rect(0, 60, 0, 0), dl.stableInsets());
+ assertEquals(new Rect(0, 60, 0, 0), dl.nonDecorInsets());
+
+ // Test with bars and cutout
+ dl = new DisplayLayout(info, res, true, true);
+ assertEquals(new Rect(0, 60, 0, 50), dl.stableInsets());
+ assertEquals(new Rect(0, 60, 0, 50), dl.nonDecorInsets());
+ }
+
+ @Test
+ public void testRotate() {
+ // Basic rotate utility
+ Rect testParent = new Rect(0, 0, 1000, 600);
+ Rect testInner = new Rect(40, 20, 120, 80);
+ Rect testResult = new Rect(testInner);
+ DisplayLayout.rotateBounds(testResult, testParent, 1);
+ assertEquals(new Rect(20, 880, 80, 960), testResult);
+ testResult.set(testInner);
+ DisplayLayout.rotateBounds(testResult, testParent, 2);
+ assertEquals(new Rect(880, 20, 960, 80), testResult);
+ testResult.set(testInner);
+ DisplayLayout.rotateBounds(testResult, testParent, 3);
+ assertEquals(new Rect(520, 40, 580, 120), testResult);
+
+ Resources res = createResources(40, 50, false, 30, 40);
+ DisplayInfo info = createDisplayInfo(1000, 1500, 60, ROTATION_0);
+ DisplayLayout dl = new DisplayLayout(info, res, true, true);
+ assertEquals(new Rect(0, 60, 0, 50), dl.stableInsets());
+ assertEquals(new Rect(0, 60, 0, 50), dl.nonDecorInsets());
+
+ // Rotate to 90
+ dl.rotateTo(res, ROTATION_90);
+ assertEquals(new Rect(60, 30, 0, 40), dl.stableInsets());
+ assertEquals(new Rect(60, 0, 0, 40), dl.nonDecorInsets());
+
+ // Rotate with moving navbar
+ res = createResources(40, 50, true, 30, 40);
+ dl = new DisplayLayout(info, res, true, true);
+ dl.rotateTo(res, ROTATION_270);
+ assertEquals(new Rect(40, 30, 60, 0), dl.stableInsets());
+ assertEquals(new Rect(40, 0, 60, 0), dl.nonDecorInsets());
+ }
+
+ private Resources createResources(
+ int navLand, int navPort, boolean navMoves, int statusLand, int statusPort) {
+ Configuration cfg = new Configuration();
+ cfg.uiMode = UI_MODE_TYPE_NORMAL;
+ Resources res = mock(Resources.class);
+ doReturn(navLand).when(res).getDimensionPixelSize(
+ R.dimen.navigation_bar_height_landscape_car_mode);
+ doReturn(navPort).when(res).getDimensionPixelSize(R.dimen.navigation_bar_height_car_mode);
+ doReturn(navLand).when(res).getDimensionPixelSize(R.dimen.navigation_bar_width_car_mode);
+ doReturn(navLand).when(res).getDimensionPixelSize(R.dimen.navigation_bar_height_landscape);
+ doReturn(navPort).when(res).getDimensionPixelSize(R.dimen.navigation_bar_height);
+ doReturn(navLand).when(res).getDimensionPixelSize(R.dimen.navigation_bar_width);
+ doReturn(navMoves).when(res).getBoolean(R.bool.config_navBarCanMove);
+ doReturn(statusLand).when(res).getDimensionPixelSize(R.dimen.status_bar_height_landscape);
+ doReturn(statusPort).when(res).getDimensionPixelSize(R.dimen.status_bar_height_portrait);
+ doReturn(cfg).when(res).getConfiguration();
+ return res;
+ }
+
+ private DisplayInfo createDisplayInfo(int width, int height, int cutoutHeight, int rotation) {
+ DisplayInfo info = new DisplayInfo();
+ info.logicalWidth = width;
+ info.logicalHeight = height;
+ info.rotation = rotation;
+ if (cutoutHeight > 0) {
+ info.displayCutout = new DisplayCutout(
+ Insets.of(0, cutoutHeight, 0, 0) /* safeInsets */, null /* boundLeft */,
+ new Rect(width / 2 - cutoutHeight, 0, width / 2 + cutoutHeight,
+ cutoutHeight) /* boundTop */, null /* boundRight */,
+ null /* boundBottom */);
+ } else {
+ info.displayCutout = DisplayCutout.NO_CUTOUT;
+ }
+ info.logicalDensityDpi = 300;
+ return info;
+ }
+}
diff --git a/packages/Tethering/Android.bp b/packages/Tethering/Android.bp
index 7e8721d3cc70..3c953b348ed9 100644
--- a/packages/Tethering/Android.bp
+++ b/packages/Tethering/Android.bp
@@ -31,6 +31,7 @@ java_defaults {
"android.hardware.tetheroffload.control-V1.0-java",
"tethering-client",
],
+ libs: ["unsupportedappusage"],
manifest: "AndroidManifestBase.xml",
}
diff --git a/packages/Tethering/AndroidManifest.xml b/packages/Tethering/AndroidManifest.xml
index 1430ed00aa91..8ba05df99e96 100644
--- a/packages/Tethering/AndroidManifest.xml
+++ b/packages/Tethering/AndroidManifest.xml
@@ -17,7 +17,7 @@
*/
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.tethering"
+ package="com.android.networkstack.tethering"
android:sharedUserId="android.uid.networkstack">
<uses-sdk android:minSdkVersion="29" android:targetSdkVersion="29" />
diff --git a/packages/Tethering/AndroidManifestBase.xml b/packages/Tethering/AndroidManifestBase.xml
index dc013da33869..fa85f66489d7 100644
--- a/packages/Tethering/AndroidManifestBase.xml
+++ b/packages/Tethering/AndroidManifestBase.xml
@@ -17,7 +17,7 @@
*/
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.tethering"
+ package="com.android.networkstack.tethering"
android:versionCode="1"
android:versionName="R-initial">
<application
diff --git a/packages/Tethering/AndroidManifest_InProcess.xml b/packages/Tethering/AndroidManifest_InProcess.xml
index 28d405c3133a..029b6c3313a7 100644
--- a/packages/Tethering/AndroidManifest_InProcess.xml
+++ b/packages/Tethering/AndroidManifest_InProcess.xml
@@ -17,7 +17,7 @@
*/
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.tethering.inprocess"
+ package="com.android.networkstack.tethering.inprocess"
android:sharedUserId="android.uid.system"
android:process="system">
<uses-sdk android:minSdkVersion="29" android:targetSdkVersion="29" />
diff --git a/packages/Tethering/apex/Android.bp b/packages/Tethering/apex/Android.bp
index bca01ebdf819..af6af93650af 100644
--- a/packages/Tethering/apex/Android.bp
+++ b/packages/Tethering/apex/Android.bp
@@ -15,21 +15,21 @@
//
apex {
- name: "com.android.tethering.apex",
+ name: "com.android.tethering",
apps: ["Tethering"],
manifest: "manifest.json",
- key: "com.android.tethering.apex.key",
+ key: "com.android.tethering.key",
androidManifest: "AndroidManifest.xml",
}
apex_key {
- name: "com.android.tethering.apex.key",
- public_key: "com.android.tethering.apex.avbpubkey",
- private_key: "com.android.tethering.apex.pem",
+ name: "com.android.tethering.key",
+ public_key: "com.android.tethering.avbpubkey",
+ private_key: "com.android.tethering.pem",
}
android_app_certificate {
- name: "com.android.tethering.apex.certificate",
- certificate: "com.android.tethering.apex",
+ name: "com.android.tethering.certificate",
+ certificate: "com.android.tethering",
}
diff --git a/packages/Tethering/apex/AndroidManifest.xml b/packages/Tethering/apex/AndroidManifest.xml
index 7769b799b6f9..5c35c51dc77f 100644
--- a/packages/Tethering/apex/AndroidManifest.xml
+++ b/packages/Tethering/apex/AndroidManifest.xml
@@ -15,7 +15,7 @@
* limitations under the License.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.tethering.apex">
+ package="com.android.tethering">
<!-- APEX does not have classes.dex -->
<application android:hasCode="false" />
<!-- b/145383354: Current minSdk is locked to Q for development cycle, lock it to next version
diff --git a/packages/Tethering/apex/com.android.tethering.apex.avbpubkey b/packages/Tethering/apex/com.android.tethering.apex.avbpubkey
deleted file mode 100644
index 9c8711161547..000000000000
--- a/packages/Tethering/apex/com.android.tethering.apex.avbpubkey
+++ /dev/null
Binary files differ
diff --git a/packages/Tethering/apex/com.android.tethering.apex.pem b/packages/Tethering/apex/com.android.tethering.apex.pem
deleted file mode 100644
index a8cd12e92e8d..000000000000
--- a/packages/Tethering/apex/com.android.tethering.apex.pem
+++ /dev/null
@@ -1,51 +0,0 @@
------BEGIN RSA PRIVATE KEY-----
-MIIJKQIBAAKCAgEAwloHpMmwszNBEgUVion141BTvF/oJ5g5DlQIYBtmht4tSpc3
-6elWXd+dhMzFxf/RkxSNRsU+dhD11cPKGp9nUYQQGrHEf3xEKwAHJKRMq26TkJ3o
-1TwOO70TaRKKA4ThNiM3VFDX2vy1ijArhZDIBTGVJCUl9HOHiO+ZJG5DKCx3KXbO
-QWz3c+Lbprr1L76dwIsl5kuoAFwgG0J+9BZhHEzIG1lVpGG7RRLxc8eDIxNN/oKT
-gPYBcOxFYqOECKGBBvElf6MxdRv6xG7gooALY2/HDMYUjAJSOosfwzeymugCzMhK
-e+6CSTAaEfUzuVZvMc2qnd1ly7zpLo9x+TOdH5LEVZpSwqmu2n5bqrUnSEAJUvMz
-SSw0YbsLWJZuTiTV7lecSITgqsmwuZyDexDmUkDQChzrTixsQV6S8vsh/FanjWoi
-zBlPneX8Q7/LME3hxHyLbrabxX0zWiyj8iM9h/8Y4mpO/MjEmmavglTAP4J8zrKD
-FBsntCoch9I49IpYBuO6NfKw1h7AUpLf8gARAjFjRxiJVcSgGY/Wt4/pBzJ57T5g
-xPvqxfpPQP0OA2CT8LqqzZIR8jXs8/TquvwLkkY2kRRPXx+azd5oU2A0uonrUY31
-Bc1obfmWPuEMz9bO/i06ETHuWPd4RiUNaB8qEmjYuKJfhv72YNcRwhrAYJECAwEA
-AQKCAgAaQn3b5yCH5fn5zFQPxvpBP35A6ph8mRXEeNg03B7rRCPMe0gjw9JWlrs6
-0Uw7p4gSnmlEUaxR2ZLN0kmBdV5JZlWitbg+HXU8diGA8u4lD6jCloN6JEYsDi0M
-OmQJe6/OV83HB7FStmh1BnMq9dgA06U6IAbT07RRbUY85OUQDYoAQTw3HNkGgHV7
-PrGYROIdvO9fAYPuoIP6Cu8KXee7Iii7gUOQFWBvQdL7+M4gNCCKrevuNc8WCeaK
-IFvbqq67WGPfrhYlo6UrW2vgqPpg8h5r/GuUS0/+9wNQpjrssUKHltxxiFV0PBqZ
-qI7XkPUvPoG6GMsDT0AWeW1F5ZJqEGPN67Xek0BCD0cpUli+nHD0yWGVHtkpHU2D
-qUOZdB2COfBuXRdW1LsYNPg8YjTCPsmGhISLTwiTNcZJeTxoK1y0CcVW9d7Af2aD
-lYzCegscQlXkSZiFj9s90Vd3KdD2XKrH/ADxzsOxQJ89ka004efdQa5/MKs9aChG
-/5XrwBEfN4O92OjY7KqXUAwB7CcVzNymOjD6r07LM24zbkRpwwXlkP0wmjsHBXkh
-8p0ISmY9QRdvhBgYmFmoPWZncM0zym9LI8atBs4CijQ7JjuOQ8HgHg+Se2eppWfe
-t8r6TVkDB8JeNAMxjX9q0G7icf3JjlIrgERZfyXLmpduR9NdkQKCAQEA5rp2fSKh
-RwihHNtJhNktFJuLR9OA++vyfjqhWnB8CrLPo3//LGWW/+WBr8EwXi/76hQpeKlf
-u8SmkTtxIHlTP2Brh2koh1Qf8HKzPHGjZeDFOoVPKHPqe3nV+cv3srd1mS0Eq3BA
-ZFQq+l61f2iiTZKxDroCahNEa8VMzirW6nKb5xhyMPHXgncCUdphHbwAGatas6be
-RUFg4ChH8BwX6jYw7leRUy2K6OqEl0fckT4Laitlb/ezKtwmD4PPE95q5hH0v3SO
-wetHWafiNrOXPn2wQqBrI2y+AfbTjNmQiaIPgcFKAQ7V3n+c3XfGZ9Xfv4L8m/wo
-RZ4ika1zur021QKCAQEA16OUBPA7BnWd+RJFri2kJBG5JZElaV9chO2ZHcXUbFR9
-HIPkWN19bJbki8Ca0w8FUQuS/M7JeeFjoZ194NlczbR899GVmb0X2AUKXilMacs3
-IONxIDczx3KFtsge8ewXRAjQvgE7M3NpmmJfPLPog7spMCbUIxbc3jzjiZgB/J1s
-WytlUTUY/Zy4V1wujkoydgK2KcHcEWG2oIy7EP0RwnL1NhTksXOtBH6+MoRMAT+H
-fcBK6yfJBNBRQzJ0PdkCCLdQPN1VtwRlWjPXZ3ey4fWvZ399wSLUkM2V1jB4GcOZ
-+DAgtwFKs9+HfOdV42GgFWFcjP+bkM3bcdrQFnmYzQKCAQAQnf1KpePXqddwrJpu
-5vVINquhUKpJeoTMcoyMZu2IF7i8nctS9z4Yz/63GcLSBcKu6STTe99ZNqCIdS+A
-lzxXpCoaZoh0tqpWNuyRvd12yOlrfY5l63NH0U6H3xjH1k6x6XwcnMkGcMlnnsqT
-koWd8KKv3NWvrhOPb3ZIou03lWmFC02uGLzcuJWCL6gu7AtVzfGKXspDUqIXgs8r
-i9ptE9oSUFw3EWCfxcQm4RYRn9ZSny1/EufkflZ/Z47Sb4Jjb4ehAlQFw1wwKNcx
-+V07MvIu2j7dHkfQ/GXgDwtJ3lIfljwuN1NP4wD5Mlcnw0+KC3UGBvMfkHQM6eEb
-4eTBAoIBAQDWfZsqHlpX3n431XkB+9wdFJP5ThrMaVJ51mxLNRBKgO/BgV+NFSNA
-9AZ5DCf0cCh1qPGYDYhSd2LGywT+trac1j7Hse0AcxpYgQsDBkk/oic/y3wm80HJ
-zZw7Z2uAb7nkrnATzt24G8CbE+ZvVvScs3oQr06raH5hgGdD4bN4No4lUVECKbKl
-8VFbdBHK7vqqb6AKgQ4JLAygPduE1nTn2bkXBklESS98HSXK0dVYGH0JFFBw/63v
-39Y05ObC7iwbx1tEb1RnKzQ1OQO1o1aHc/35ENNhXOfa8ONtneCYn/ty50xjPCG2
-MU1vbBv+hIjbO3D3vvhaXKk+4svAz0qxAoIBAQC84FJEjKHJHx17jLeoTuDfuxwX
-6bOQrI3nHbtnFRvPrMryWRDtHLv89Zma3o68/n4vTn5+AnvgYMZifOYlTlIPxinH
-tlE+qCD8KBXUlZdrc+5GGM18lp5tF3Ro4LireH+OhiOAWawaSzDIDYdiR6Kz9NU+
-SjcHKjDObeM6iMEukoaRsufMedpUSrnbzMraAJgBZGay1NZs/o8Icl3OySYPZWEK
-MJxVBMXU9QcUp2GEioYd/eNuP9rwyjq/EIUDJbP2vESAe6+FdGbIgvyYTV/gnKaH
-GcvyMNVZbCMp/wCYNonjlu+18m2w+pVs2uuZLqORkrKYhisK83TKxh4YOWJh
------END RSA PRIVATE KEY-----
diff --git a/packages/Tethering/apex/com.android.tethering.apex.pk8 b/packages/Tethering/apex/com.android.tethering.apex.pk8
deleted file mode 100644
index 56632462941f..000000000000
--- a/packages/Tethering/apex/com.android.tethering.apex.pk8
+++ /dev/null
Binary files differ
diff --git a/packages/Tethering/apex/com.android.tethering.apex.x509.pem b/packages/Tethering/apex/com.android.tethering.apex.x509.pem
deleted file mode 100644
index a5e94011f7c5..000000000000
--- a/packages/Tethering/apex/com.android.tethering.apex.x509.pem
+++ /dev/null
@@ -1,36 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIGMzCCBBugAwIBAgIUXVtoDaXanhs7ma8VIICambMkj5UwDQYJKoZIhvcNAQEL
-BQAwgacxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQH
-DA1Nb3VudGFpbiBWaWV3MRAwDgYDVQQKDAdBbmRyb2lkMRAwDgYDVQQLDAdBbmRy
-b2lkMSMwIQYDVQQDDBpjb20uYW5kcm9pZC50ZXRoZXJpbmcuYXBleDEiMCAGCSqG
-SIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTAgFw0xOTExMjgwNjU4MTRaGA80
-NzU3MTAyNDA2NTgxNFowgacxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9y
-bmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MRAwDgYDVQQKDAdBbmRyb2lkMRAw
-DgYDVQQLDAdBbmRyb2lkMSMwIQYDVQQDDBpjb20uYW5kcm9pZC50ZXRoZXJpbmcu
-YXBleDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTCCAiIwDQYJ
-KoZIhvcNAQEBBQADggIPADCCAgoCggIBANwzufMBdOj9XlNwiX+bXl/94G0DklWW
-nzob0jPlubCFfRqYkjCf2eOd28Mu/O1pOBcvobnrs9OTpGzcHkz2h58L5/0UMVTS
-tBugwCE49XF5FHawqVHNZE+s5tDmnp2cufhNc5HXHY4oZKh80/WVdbcKxiLjSY2T
-PgRAfB6E6XByKD3t1cSsc3liRVKADoJOVDvmF+xnyvSV/SN38bvTQk9aVs95mj0W
-yov6gzXBnqN7iQlvkhcijZBnFWxvoNbJ5KFy1abYOrm+ueXje4BcNhVOeRMb4E9N
-eo7+9k1GEI7TYG7laNNcp7UJ1IXCJzv/wBFKRg3f1HB3unKfx2rtKerDnVsr3o7V
-KProkgRNKNhhQ6opNguiH1YMzKpWMaC988n4AQPryPdIOmVIxIC5jJrixdxgzDXT
-qeiwFiXis291uyls08B03PQFlY9oWaY9P8s+4hIUjB6rLl+XZXsLDtDFxXeJ97NB
-8XZN1gBJoBoLknFs0C4LKpmJZB/EBao9tXV9dL/5lydRo6HzQDpjW8QX06CTUM6z
-Lr3LVelhqbsuZsV42yBKl+/LfrvNjBLEPdSevt2oMrlJW7m4iSNaMtDtJ2Oy8fA5
-WSIgLWuMbkaFDza3JzwiMzxbtbJHYiy6rY7aVywo3Vqwr1+KO3cq4eLQq62zUjRY
-e6KJwvgE2YmpAgMBAAGjUzBRMB0GA1UdDgQWBBQ8h1oF5JfKFmJCN8nfimbUK+IR
-wjAfBgNVHSMEGDAWgBQ8h1oF5JfKFmJCN8nfimbUK+IRwjAPBgNVHRMBAf8EBTAD
-AQH/MA0GCSqGSIb3DQEBCwUAA4ICAQAP5hIkAxSyt9hRafMKiFlmXcL277bgoxNd
-qGZYbdcCFjfvM2r0QQcM/K7x2ZslFe7mJSzcyMifpm4YQTEo2yYbzKItXQV+eV1K
-9RNksRGFG9umsdWaSHhfQmcmxtr2nu9rGAgxy5OQFtyXmJPUPEM2cb/YeILwYhuQ
-Ux3kaj/fxGltX1JBag7HnMzCTZK++fRo5nqFVOJQgJH8ZpuzGeM9kZvP1+b55046
-PhSnlqmZoKhG4i5POPvvZvaakh/lM3x/N7lIlSaQpCGf7jmldni4L0/GenULVKzH
-iN73aBfh4GEvE0HRcOoH3L7V6kc3WMMLve0chZBHpoVYbzUJEJOUL4yrmwEehqtf
-xm4vlYg3vqtcE3UnU/UGdMb16t77Nz88LlpBY5ierIt0jZMU0M81ppRhr1uiD2Lj
-091sEA0Bxcw/6Q8QNF2eR7SG7Qwipnms+lw6Vcxve+7DdTrdEA0k3XgpdXp8Ya+2
-PAp9SLVp1UHiGq3qD9Jvm34QmlUWAIUTHZs3DSgs1y3K5eyw/cnzTvUUOljc/n2y
-VF0FFZtJ1dVLrzQ80Ik7apEXpBqkgBGV04/L3QYk4C0/sP+1yk6zjeeeAvDtUcHS
-gLtjAfacQl/kwfVQWfrF7VByLcivApC6EUdvT3cURM5DfZRQ4RcKr1D61VYPnNRH
-+/NVbMObwQ==
------END CERTIFICATE-----
diff --git a/packages/Tethering/apex/com.android.tethering.avbpubkey b/packages/Tethering/apex/com.android.tethering.avbpubkey
new file mode 100644
index 000000000000..9a2c0174e496
--- /dev/null
+++ b/packages/Tethering/apex/com.android.tethering.avbpubkey
Binary files differ
diff --git a/packages/Tethering/apex/com.android.tethering.pem b/packages/Tethering/apex/com.android.tethering.pem
new file mode 100644
index 000000000000..d4f39abd3bb2
--- /dev/null
+++ b/packages/Tethering/apex/com.android.tethering.pem
@@ -0,0 +1,51 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIIJKgIBAAKCAgEA+AWTp03PBRMGt4mVNLt5PDoFFSfmFOVTM7jt5AJXnQMIDsAM
+1cyWGWRridGIpoHAaCALVgW5aRySgi8yV5xP4w0YHcKbfh9M6I9oz4RUo4GQBZfX
++lFIGaLjb6I3tEJxPuxps4sW26Io63ihwTnKeGyADHdHGWDUs9WU0Ml+QTvKrdjy
+qC03M0dehYXILGiA9m+UXwKoKxhWgfDUhWLhDBUtLJLPL4WeqKc9sG9h+zzVqE+8
+LzJsfrodKhTTrLpWOXi6YLRTk8dzsuPz/Nu98sJd1w3fHd20DrmkqsxVhgN1h+nk
+zcPpxyGYIP6qYVZCmIXCwZZNtPeb7y/tOs967VHoZ4Qj7p2tE0CAWFMZFGjA/pcZ
+7fi6CsIuMOYBbj4+wRlJwpG1g5zSJBCjzhv7dZp8S5oXmLShNYOMYEdsPfaZbm08
+3pVY+k8DVf7idcANXNw1lM+sPbE2hp5VuEuVpK+ca5x8hIMpTqJ84wDAjnC1kCwm
+X2xfNvYPKNF58SvqlNCPN8X7hQjoeaEb7w24vCdZMRqeGBmu1GNQvCyzbBO0huQm
+f5CQPrZjPcnoImlP879VPxY4YB6tAjsA/ZLiub9VdT108lCjb5r8criMzpMAA/AQ
+NqQLWFI3M43xPemGBTiIguTYgpRgGcdRZf7XuTgTY5qzQZZuZMVuwaqSD2cCAwEA
+AQKCAgEA0jMvw3BPTrakT7Lb8JgelKt7mUV6WyVMUZ6eh0pw5JIoJxAfEKfWYmjY
+NzKNRMjcv6LA2MP7MplTld/YI6ZHkl+Lm9VOISL39HVuV8mIThbFb+gT1INEvu1t
+IjRyT2SsQ67rmo377mLNmVtgg7mt3kfecjI44MpPGqad/CF4zmKVUKd4aI4BpYUM
+F8+dKf3bpoBEWA2RZwy2bGQmSXHW132vDoLR8y2knL04rCqJ+PrC/WWuULXEe9bS
+VtLV3yMBZq3qD4Fk/+7fILLPGvNFVdPi4htQiChYrM4rP9HzfaO63VieYMF0hR70
+pqoOznXj9Q4QVC9FZmUgFCQjQ1+KhqJw3OldIo0SnvpsLdTO/inKkhQWKC5HlPyh
+/rqvro2j3pTHWPAziuBr+oQPcdVCOlCBZ+B99L1tO7aGktVPEIVQG7G7jlFMBiJ1
+j/kRGk2RTX8RaPQJTnwUqp8mWUV2fwxHiXNadjejA5ZU3eQT2eAOhXl1w6Lv2jEl
+0wMOwPMJGcF77CcqnnWHON8fkxCbAfyy5Uo6Pm9g/Zzecn+ji2sabG7Ge5t0gzdL
+LKRcGoyakN2CrbQ8pxlCTgE4HX5oPY+VuqOf8L3AIWIJBsyLbXHVkL1mqQ/Ed2uz
+zaaSFYUZw81+m/5bl8JLPaIFNPyikZrXTD0YRer3V06XiyP/kYECggEBAP033xeF
+OhgRwkRTjd68hwRJpyHsZDWxHiUqQf6l6yFv5mEE355G2IGI7cZmR2+tUDjQdxLv
+tAZIszTK4PFCdVTeWfGVFbVF84eNWLB124pHDMM79GN/AMcuHnQPR756a8IO1hIy
+4KxIUE1a1PKN5b9IgE5Lu4TZM96HDpFcUAmCT5urdYDmg3++IWT9PYQlGS7Hhiar
+r+Hh646waM8Qx619CwXBqy+Y37+WHVbYqJClr6AcpVMrGA+6cgpskFpZAPLsoy7G
+RSsVfyV8pH2JKm/hzk7XCwIpczxeWQSfpJWZ+oOPFHu+zM60Cdj2UrQyKrNHwew8
++WYe9eCA+MiNBcECggEBAPq/F1vdqROiLv9uzhKb8ybgdL7CmREELiqwK+MvNE9t
+W7lQz7lcWzav+b2n0M+VJBxUWB3XClgoIvA/AllgTgsYXfKAxNakhKLSBoMmvKCW
+HtWcGr/D3RcmacK+DTMWlVS/LuueAFLuH6UmBIUFKc+qA5x7oQecAFALBFupE3G4
+LtAspLBI6P8gRtRav5p2whs9H8qjYcyf2f6liWpkmFITcXvPvAxFHicR6ZJdwZ/S
+PiX2LJQnOpT7L3+2PWnYwzFStb4MkMGlFKcscU9CvS53JcP/J4Asjk0I4zDB2gri
+xzFHPlVzCr2IVVGptKCQ3sdYiMIzQKzEXQHCU8h37ycCggEBAJu8aC48Fz3Edlm1
+ldS+2L9vWSaJEBzhoSu0cMBgZVu8SdGzwKDE69XHVI4oS5lI28UFmaaA3JTc07MN
+cAmSGT2oP2NQkPhbXGsrKLfm1K6YAiZ1Ulp7OwxFth8lYreo7Wt92nV46yuqkhDx
+Y3UGhp39xkPhWiRbvgYHxJLsVqFyjumsK2mq3IeNdVZ6VgJXGsTlnAFeqJ7hZxHs
+N5natSRjeosA0PtGJ57agZLvT8Ue0gREef3LzFGoFwmIOcQHZ4kAt2BGOzZDU17H
+6Rb4bKxBEbT1l2St/5zKXi90zDHicOvG7Q8qiyY6HrBc1wLSs+ZtpLxZx/3h3tFE
+IT6fVUECggEBAMSAQm8Ey76OJ+SXUjk1K50442SnHcs/Cmr7urkEQitImUwl71Pk
+87pst/uP6szypOTqmE9yOTIS6iZ6Sn3+QcriIqWrkhZfwW3Tx7S6A7KZUrq15iSH
++thsiw9JXxC9TvOmC8AsBzb2U6hZncsc28JZCxFztSNAduJDb/vhCVLiMxWDFuDr
+kmR1R+yc3XDQRpeQFDz6QudYEj9EPOc6xD/16sZLaqP2+oVFvVSt0tJLsdaQECle
+gMNGAdhE2eX8MCOUHMc+E6cdlozYAEhMFfO2/cqWR79jq3TlVR3dnOFRDScqHMhc
+KnuTvsELjHkUbvGsCSiff7yk+fop7vy4OJsCggEAPemJdItO2rhib8EofrZdY72I
+oifX1jhPZ1BWD2GKgcx+eVyJGbONBbJVexvvskTfZBvCcAegmgp+sngP6MO6yZkr
+cHMfAJeApYZnshsgXksHGMDtSB50/w1JLrc/nqpxdpy/aTazt0Eu1pLWpze1HFZ/
+Xyu4PcmrU+4P1vN7c396slHMktEvly6QqOn4nfBbGDJ17Ow6X1XFvGjAxQPIDTB+
+6loV14AHymwmqwMrGn84O72rzqyw+41GxW5+oXhOZ4MeXF3u89TBLWvXDpPy/YQU
+EiKpodN0YeEn6Ghzplan8rUha+7TP7AYnS5pCszsCHKd03Py0lMLkF+uAfVsDA==
+-----END RSA PRIVATE KEY-----
diff --git a/packages/Tethering/apex/com.android.tethering.pk8 b/packages/Tethering/apex/com.android.tethering.pk8
new file mode 100644
index 000000000000..3b94405945cb
--- /dev/null
+++ b/packages/Tethering/apex/com.android.tethering.pk8
Binary files differ
diff --git a/packages/Tethering/apex/com.android.tethering.x509.pem b/packages/Tethering/apex/com.android.tethering.x509.pem
new file mode 100644
index 000000000000..a1786e35e854
--- /dev/null
+++ b/packages/Tethering/apex/com.android.tethering.x509.pem
@@ -0,0 +1,35 @@
+-----BEGIN CERTIFICATE-----
+MIIGKTCCBBGgAwIBAgIUNiSs5EMqxCZ31gWWCcRJVp9HffAwDQYJKoZIhvcNAQEL
+BQAwgaIxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQH
+DA1Nb3VudGFpbiBWaWV3MRAwDgYDVQQKDAdBbmRyb2lkMRAwDgYDVQQLDAdBbmRy
+b2lkMR4wHAYDVQQDDBVjb20uYW5kcm9pZC50ZXRoZXJpbmcxIjAgBgkqhkiG9w0B
+CQEWE2FuZHJvaWRAYW5kcm9pZC5jb20wIBcNMTkxMjE4MDcwMDQ4WhgPNDc1NzEx
+MTMwNzAwNDhaMIGiMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEW
+MBQGA1UEBwwNTW91bnRhaW4gVmlldzEQMA4GA1UECgwHQW5kcm9pZDEQMA4GA1UE
+CwwHQW5kcm9pZDEeMBwGA1UEAwwVY29tLmFuZHJvaWQudGV0aGVyaW5nMSIwIAYJ
+KoZIhvcNAQkBFhNhbmRyb2lkQGFuZHJvaWQuY29tMIICIjANBgkqhkiG9w0BAQEF
+AAOCAg8AMIICCgKCAgEAxvTUA4seblYjZLfTVNwZuJH914QVNFTj+vD94pWmt5Aq
+sH1DVTpBvpXXegc/P5HI2XF/71poSBib1WaQSuXG0fU5K75T18bOGL0qF+fhMtBO
+wUyvulcjO0h4XE/xf0txY54exUjAA4JS9ERGJOgb4GOwSbPyzekfmzIyCZ2Yawwu
++oGwD2ZNzZRaPOoWxjwohBWQ6mySuvF9RRRb300qmxxUGFM9Ki3aqrWlYlHEOwOC
+M+gIXxYFO7S+yUzf6/gMZLOz2YqfcTOup4hAxtExR7niutxJSsRLPBL237exAJoz
+OupoXjtWAlPK4ZwZ/Nl1jdTWauJ+Kv3WqzhHGEb2gn3ZpeO3IdOjJhDgFJ6m1OT/
+kjRbW1LCuKGrKaoqsEDT2X3a7Izfripn65hSNTfR5gNLtgELaI3/vXi8Fmzw1AfH
++qi6ulElZvSwx0qm+S0QiPyGFlxrsdnHoGJl1tzjJW8KdNZRvzRLUQtbphPp+VkL
+5i0bNKum+AwbfdUkLkNLfw9XdbujgBkZTZDQbZGsNjgrvyXcPO2KiJee0hVCZRs0
+rhDi5Pfm7BnN/I2vaTRz/W4mdct9H2RWMuqlSH90JvmKtWcND8ahmOJ3sggrvzfO
+QNs3k4JTRecamMzqIkylhlnEC4FjWc6Bx4wsEpwBMZOkF/tGGMZYf2C09a8tpP0C
+AwEAAaNTMFEwHQYDVR0OBBYEFNP5gIpNWmq0xa411M1GaRPbEijvMB8GA1UdIwQY
+MBaAFNP5gIpNWmq0xa411M1GaRPbEijvMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZI
+hvcNAQELBQADggIBADJGmU3QP4EGbt6eBhVPeo/efsqrHsuB2fvFzvIobJbfkSob
+cmvjbzIikOlPAgFWj8lT5SDcIWRorFf1u2JylClJ0nSDcqJMHVKmT7wseV/KtX//
+1yUyJFRQVzmjC89dp8OIc00GmItivKLer3NbJdkR3rTUjg7+bNUO27Qp3AFREmiJ
+P+M7ouvcQRvByUWbp/LOrJpMdJLysRBO562RwrtwTjltdvufyYswbBZOKEiUh1Jc
+Ged+3+SJdhwq3Wy+R3Uj7YE7mUMu1QNbANIMrwF8W93EA53eoL2+cKmuaVU6ZURL
+xgSJaY6TrunnSI9XTROLtjsFlJorYWy2tvG7Q5Hw3OkO2Xdz/mm85VTkiusg9DMB
+WWTv607YtsIO0FhKmcV4bp3q/EkRj3t/zLvL9uFJrWDGkuShZq6fQvqbCvaokOPY
++M0ZRIwgwa9UpEE0BMklVWqR6BGyap614gOgcOjYM70WRNl59Qne+g128ZN7g9nz
+61F70i7kUngV0ZUz1/Fu/NCG+6wGF85ZbFmQl60YHPDw1FtjVUuKyBblaDzdJunx
+yQr2t9RUokzFBFK0lGW3+yf0WDQ5fqTMs5h8bz1FCq8/HzWmpdOfqePLe4zsld3b
+1nFuSohaIfbn/HDdTNtTBGQPgz8ZswQ6ejJJqTLz9D/odbqn9LeIhDZXcQTf
+-----END CERTIFICATE-----
diff --git a/packages/Tethering/apex/manifest.json b/packages/Tethering/apex/manifest.json
index 078302ac51a4..538ffb3ad6e4 100644
--- a/packages/Tethering/apex/manifest.json
+++ b/packages/Tethering/apex/manifest.json
@@ -1,4 +1,4 @@
{
- "name": "com.android.tethering.apex",
+ "name": "com.android.tethering",
"version": 300000000
}
diff --git a/packages/Tethering/common/TetheringLib/src/android/net/TetheringManager.java b/packages/Tethering/common/TetheringLib/src/android/net/TetheringManager.java
index eb0d443f4bfc..7fb286b5fa11 100644
--- a/packages/Tethering/common/TetheringLib/src/android/net/TetheringManager.java
+++ b/packages/Tethering/common/TetheringLib/src/android/net/TetheringManager.java
@@ -17,6 +17,7 @@ package android.net;
import static android.Manifest.permission.NETWORK_STACK;
import static android.net.ConnectivityManager.TETHER_ERROR_NO_ERROR;
+import static android.net.ConnectivityManager.TETHER_ERROR_SERVICE_UNAVAIL;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -175,6 +176,10 @@ public class TetheringManager {
*/
@Deprecated
public int tether(@NonNull String iface) {
+ if (mConnector == null) {
+ Slog.wtf(TAG, "Tethering not ready yet");
+ return TETHER_ERROR_SERVICE_UNAVAIL;
+ }
try {
mConnector.tether(iface);
} catch (RemoteException e) {
@@ -191,6 +196,10 @@ public class TetheringManager {
*/
@Deprecated
public int untether(@NonNull String iface) {
+ if (mConnector == null) {
+ Slog.wtf(TAG, "Tethering not ready yet");
+ return TETHER_ERROR_SERVICE_UNAVAIL;
+ }
try {
mConnector.untether(iface);
} catch (RemoteException e) {
@@ -210,6 +219,10 @@ public class TetheringManager {
*/
@Deprecated
public int setUsbTethering(boolean enable) {
+ if (mConnector == null) {
+ Slog.wtf(TAG, "Tethering not ready yet");
+ return TETHER_ERROR_SERVICE_UNAVAIL;
+ }
try {
mConnector.setUsbTethering(enable);
} catch (RemoteException e) {
@@ -227,6 +240,10 @@ public class TetheringManager {
// TODO: improve the usage of ResultReceiver, b/145096122
public void startTethering(int type, @NonNull ResultReceiver receiver,
boolean showProvisioningUi) {
+ if (mConnector == null) {
+ Slog.wtf(TAG, "Tethering not ready yet");
+ return;
+ }
try {
mConnector.startTethering(type, receiver, showProvisioningUi);
} catch (RemoteException e) {
@@ -241,6 +258,10 @@ public class TetheringManager {
* {@hide}
*/
public void stopTethering(int type) {
+ if (mConnector == null) {
+ Slog.wtf(TAG, "Tethering not ready yet");
+ return;
+ }
try {
mConnector.stopTethering(type);
} catch (RemoteException e) {
@@ -258,6 +279,10 @@ public class TetheringManager {
// TODO: improve the usage of ResultReceiver, b/145096122
public void requestLatestTetheringEntitlementResult(int type, @NonNull ResultReceiver receiver,
boolean showEntitlementUi) {
+ if (mConnector == null) {
+ Slog.wtf(TAG, "Tethering not ready yet");
+ return;
+ }
try {
mConnector.requestLatestTetheringEntitlementResult(type, receiver, showEntitlementUi);
} catch (RemoteException e) {
diff --git a/packages/Tethering/src/com/android/server/connectivity/tethering/Tethering.java b/packages/Tethering/src/com/android/server/connectivity/tethering/Tethering.java
index 7c78ef8994a2..c4b360d929eb 100644
--- a/packages/Tethering/src/com/android/server/connectivity/tethering/Tethering.java
+++ b/packages/Tethering/src/com/android/server/connectivity/tethering/Tethering.java
@@ -109,7 +109,7 @@ import com.android.internal.util.MessageUtils;
import com.android.internal.util.Protocol;
import com.android.internal.util.State;
import com.android.internal.util.StateMachine;
-import com.android.tethering.R;
+import com.android.networkstack.tethering.R;
import java.io.FileDescriptor;
import java.io.PrintWriter;
@@ -456,7 +456,7 @@ public class Tethering {
mLog.e("setWifiTethering: failed to get WifiManager!");
return TETHER_ERROR_SERVICE_UNAVAIL;
}
- if ((enable && mgr.startSoftAp(null /* use existing wifi config */))
+ if ((enable && mgr.startTetheredHotspot(null /* use existing softap config */))
|| (!enable && mgr.stopSoftAp())) {
mWifiTetherRequested = enable;
return TETHER_ERROR_NO_ERROR;
diff --git a/packages/Tethering/tests/unit/AndroidManifest.xml b/packages/Tethering/tests/unit/AndroidManifest.xml
index 049ff6d415f3..0a1cdd35b10c 100644
--- a/packages/Tethering/tests/unit/AndroidManifest.xml
+++ b/packages/Tethering/tests/unit/AndroidManifest.xml
@@ -14,13 +14,13 @@
limitations under the License.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.tethering.tests.unit">
+ package="com.android.networkstack.tethering.tests.unit">
<application android:debuggable="true">
<uses-library android:name="android.test.runner" />
</application>
<instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
- android:targetPackage="com.android.tethering.tests.unit"
+ android:targetPackage="com.android.networkstack.tethering.tests.unit"
android:label="Tethering service tests">
</instrumentation>
</manifest>
diff --git a/packages/Tethering/tests/unit/src/com/android/server/connectivity/tethering/TetheringTest.java b/packages/Tethering/tests/unit/src/com/android/server/connectivity/tethering/TetheringTest.java
index 0273ed358673..cdbc54106ce8 100644
--- a/packages/Tethering/tests/unit/src/com/android/server/connectivity/tethering/TetheringTest.java
+++ b/packages/Tethering/tests/unit/src/com/android/server/connectivity/tethering/TetheringTest.java
@@ -94,7 +94,7 @@ import android.net.ip.RouterAdvertisementDaemon;
import android.net.util.InterfaceParams;
import android.net.util.NetworkConstants;
import android.net.util.SharedLog;
-import android.net.wifi.WifiConfiguration;
+import android.net.wifi.SoftApConfiguration;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pInfo;
@@ -806,12 +806,12 @@ public class TetheringTest {
// TODO: Test with and without interfaceStatusChanged().
@Test
public void failingWifiTetheringLegacyApBroadcast() throws Exception {
- when(mWifiManager.startSoftAp(any(WifiConfiguration.class))).thenReturn(true);
+ when(mWifiManager.startTetheredHotspot(any(SoftApConfiguration.class))).thenReturn(true);
// Emulate pressing the WiFi tethering button.
mTethering.startTethering(TETHERING_WIFI, null, false);
mLooper.dispatchAll();
- verify(mWifiManager, times(1)).startSoftAp(null);
+ verify(mWifiManager, times(1)).startTetheredHotspot(null);
verifyNoMoreInteractions(mWifiManager);
verifyNoMoreInteractions(mNMService);
@@ -833,12 +833,12 @@ public class TetheringTest {
// TODO: Test with and without interfaceStatusChanged().
@Test
public void workingWifiTetheringEnrichedApBroadcast() throws Exception {
- when(mWifiManager.startSoftAp(any(WifiConfiguration.class))).thenReturn(true);
+ when(mWifiManager.startTetheredHotspot(any(SoftApConfiguration.class))).thenReturn(true);
// Emulate pressing the WiFi tethering button.
mTethering.startTethering(TETHERING_WIFI, null, false);
mLooper.dispatchAll();
- verify(mWifiManager, times(1)).startSoftAp(null);
+ verify(mWifiManager, times(1)).startTetheredHotspot(null);
verifyNoMoreInteractions(mWifiManager);
verifyNoMoreInteractions(mNMService);
@@ -907,13 +907,13 @@ public class TetheringTest {
// TODO: Test with and without interfaceStatusChanged().
@Test
public void failureEnablingIpForwarding() throws Exception {
- when(mWifiManager.startSoftAp(any(WifiConfiguration.class))).thenReturn(true);
+ when(mWifiManager.startTetheredHotspot(any(SoftApConfiguration.class))).thenReturn(true);
doThrow(new RemoteException()).when(mNMService).setIpForwardingEnabled(true);
// Emulate pressing the WiFi tethering button.
mTethering.startTethering(TETHERING_WIFI, null, false);
mLooper.dispatchAll();
- verify(mWifiManager, times(1)).startSoftAp(null);
+ verify(mWifiManager, times(1)).startTetheredHotspot(null);
verifyNoMoreInteractions(mWifiManager);
verifyNoMoreInteractions(mNMService);
@@ -1155,7 +1155,7 @@ public class TetheringTest {
when(mUpstreamNetworkMonitor.getCurrentPreferredUpstream()).thenReturn(upstreamState);
when(mUpstreamNetworkMonitor.selectPreferredUpstreamType(any()))
.thenReturn(upstreamState);
- when(mWifiManager.startSoftAp(any(WifiConfiguration.class))).thenReturn(true);
+ when(mWifiManager.startTetheredHotspot(any(SoftApConfiguration.class))).thenReturn(true);
mTethering.interfaceStatusChanged(TEST_WLAN_IFNAME, true);
mLooper.dispatchAll();
tetherState = callback.pollTetherStatesChanged();
diff --git a/services/Android.bp b/services/Android.bp
index 3b566078bd51..cf0c15c67a61 100644
--- a/services/Android.bp
+++ b/services/Android.bp
@@ -14,6 +14,7 @@ filegroup {
":services.appwidget-sources",
":services.autofill-sources",
":services.backup-sources",
+ ":backuplib-sources",
":services.companion-sources",
":services.contentcapture-sources",
":services.contentsuggestions-sources",
@@ -101,3 +102,26 @@ filegroup {
name: "art-profile",
srcs: ["art-profile"],
}
+
+// API stub
+// =============================================================
+
+droidstubs {
+ name: "services-stubs.sources",
+ srcs: [":services-sources"],
+ installable: false,
+ // TODO: remove the --hide options below
+ args: " --show-single-annotation android.annotation.SystemApi\\(client=android.annotation.SystemApi.Client.MODULE_LIBRARIES,process=android.annotation.SystemApi.Process.SYSTEM_SERVER\\)" +
+ " --hide-annotation android.annotation.Hide" +
+ " --hide-package com.google.android.startop.iorap" +
+ " --hide ReferencesHidden" +
+ " --hide DeprecationMismatch" +
+ " --hide HiddenTypedefConstant",
+ visibility: ["//visibility:private"],
+}
+
+java_library {
+ name: "services-stubs",
+ srcs: [":services-stubs.sources"],
+ installable: false,
+}
diff --git a/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java b/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java
index 7fdd83bebbcd..6a6e2b2f3467 100644
--- a/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java
+++ b/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java
@@ -16,6 +16,11 @@
package com.android.server.accessibility;
+import static android.view.accessibility.AccessibilityManager.ACCESSIBILITY_BUTTON;
+import static android.view.accessibility.AccessibilityManager.ACCESSIBILITY_SHORTCUT_KEY;
+import static android.view.accessibility.AccessibilityManager.ShortcutType;
+
+import static com.android.internal.accessibility.AccessibilityShortcutController.MAGNIFICATION_CONTROLLER_NAME;
import static com.android.internal.util.FunctionalUtils.ignoreRemoteException;
import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage;
@@ -31,6 +36,7 @@ import android.app.ActivityOptions;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManagerInternal;
+import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
@@ -70,6 +76,7 @@ import android.provider.Settings;
import android.provider.SettingsStringUtil.SettingStringHelper;
import android.text.TextUtils;
import android.text.TextUtils.SimpleStringSplitter;
+import android.util.ArraySet;
import android.util.IntArray;
import android.util.Slog;
import android.util.SparseArray;
@@ -113,9 +120,9 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
+import java.util.function.Function;
/**
* This class is instantiated by the system as a system level service and can be
@@ -754,6 +761,8 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
userState.setTouchExplorationEnabledLocked(touchExplorationEnabled);
userState.setDisplayMagnificationEnabledLocked(false);
userState.setNavBarMagnificationEnabledLocked(false);
+ userState.disableShortcutMagnificationLocked();
+
userState.setAutoclickEnabledLocked(false);
userState.mEnabledServices.clear();
userState.mEnabledServices.add(service);
@@ -1072,6 +1081,8 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
}
}
+ // TODO(a11y shortcut): Remove this function and Use #performAccessibilityShortcutInternal(
+ // ACCESSIBILITY_BUTTON) instead, after the new Settings shortcut Ui merged.
private void notifyAccessibilityButtonClickedLocked(int displayId) {
final AccessibilityUserState state = getCurrentUserStateLocked();
@@ -1105,8 +1116,8 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
if (state.getServiceAssignedToAccessibilityButtonLocked() == null
&& !state.isNavBarMagnificationAssignedToAccessibilityButtonLocked()) {
mMainHandler.sendMessage(obtainMessage(
- AccessibilityManagerService::showAccessibilityButtonTargetSelection, this,
- displayId));
+ AccessibilityManagerService::showAccessibilityTargetsSelection, this,
+ displayId, ACCESSIBILITY_BUTTON));
} else if (state.isNavBarMagnificationEnabledLocked()
&& state.isNavBarMagnificationAssignedToAccessibilityButtonLocked()) {
mMainHandler.sendMessage(obtainMessage(
@@ -1125,8 +1136,8 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
}
// The user may have turned off the assigned service or feature
mMainHandler.sendMessage(obtainMessage(
- AccessibilityManagerService::showAccessibilityButtonTargetSelection, this,
- displayId));
+ AccessibilityManagerService::showAccessibilityTargetsSelection, this,
+ displayId, ACCESSIBILITY_BUTTON));
}
}
@@ -1138,13 +1149,27 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
}
}
- private void showAccessibilityButtonTargetSelection(int displayId) {
+ private void showAccessibilityTargetsSelection(int displayId,
+ @ShortcutType int shortcutType) {
Intent intent = new Intent(AccessibilityManager.ACTION_CHOOSE_ACCESSIBILITY_BUTTON);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
final Bundle bundle = ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle();
+ bundle.putInt(AccessibilityManager.EXTRA_SHORTCUT_TYPE, shortcutType);
mContext.startActivityAsUser(intent, bundle, UserHandle.of(mCurrentUserId));
}
+ private void launchShortcutTargetActivity(int displayId, ComponentName name) {
+ final Intent intent = new Intent();
+ final Bundle bundle = ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle();
+ intent.setComponent(name);
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
+ try {
+ mContext.startActivityAsUser(intent, bundle, UserHandle.of(mCurrentUserId));
+ } catch (ActivityNotFoundException ignore) {
+ // ignore the exception
+ }
+ }
+
private void notifyAccessibilityButtonVisibilityChangedLocked(boolean available) {
final AccessibilityUserState state = getCurrentUserStateLocked();
mIsAccessibilityButtonShown = available;
@@ -1353,9 +1378,8 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
*/
private void readComponentNamesFromSettingLocked(String settingName, int userId,
Set<ComponentName> outComponentNames) {
- String settingValue = Settings.Secure.getStringForUser(mContext.getContentResolver(),
- settingName, userId);
- readComponentNamesFromStringLocked(settingValue, outComponentNames, false);
+ readColonDelimitedSettingToSet(settingName, userId, outComponentNames,
+ str -> ComponentName.unflattenFromString(str));
}
/**
@@ -1370,34 +1394,57 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
private void readComponentNamesFromStringLocked(String names,
Set<ComponentName> outComponentNames,
boolean doMerge) {
+ readColonDelimitedStringToSet(names, outComponentNames, doMerge,
+ str -> ComponentName.unflattenFromString(str));
+ }
+
+ @Override
+ public void persistComponentNamesToSettingLocked(String settingName,
+ Set<ComponentName> componentNames, int userId) {
+ persistColonDelimitedSetToSettingLocked(settingName, userId, componentNames,
+ componentName -> componentName.flattenToShortString());
+ }
+
+ private <T> void readColonDelimitedSettingToSet(String settingName, int userId, Set<T> outSet,
+ Function<String, T> toItem) {
+ final String settingValue = Settings.Secure.getStringForUser(mContext.getContentResolver(),
+ settingName, userId);
+ readColonDelimitedStringToSet(settingValue, outSet, false, toItem);
+ }
+
+ private <T> void readColonDelimitedStringToSet(String names, Set<T> outSet, boolean doMerge,
+ Function<String, T> toItem) {
if (!doMerge) {
- outComponentNames.clear();
+ outSet.clear();
}
- if (names != null) {
- TextUtils.SimpleStringSplitter splitter = mStringColonSplitter;
+ if (!TextUtils.isEmpty(names)) {
+ final TextUtils.SimpleStringSplitter splitter = mStringColonSplitter;
splitter.setString(names);
while (splitter.hasNext()) {
- String str = splitter.next();
- if (str == null || str.length() <= 0) {
+ final String str = splitter.next();
+ if (TextUtils.isEmpty(str)) {
continue;
}
- ComponentName enabledService = ComponentName.unflattenFromString(str);
- if (enabledService != null) {
- outComponentNames.add(enabledService);
+ final T item = toItem.apply(str);
+ if (item != null) {
+ outSet.add(item);
}
}
}
}
- @Override
- public void persistComponentNamesToSettingLocked(String settingName,
- Set<ComponentName> componentNames, int userId) {
- StringBuilder builder = new StringBuilder();
- for (ComponentName componentName : componentNames) {
+ private <T> void persistColonDelimitedSetToSettingLocked(String settingName, int userId,
+ Set<T> set, Function<T, String> toString) {
+ final StringBuilder builder = new StringBuilder();
+ for (T item : set) {
+ final String str = (item != null ? toString.apply(item) : null);
+ if (TextUtils.isEmpty(str)) {
+ continue;
+ }
if (builder.length() > 0) {
builder.append(COMPONENT_NAME_SEPARATOR);
}
- builder.append(componentName.flattenToShortString());
+ builder.append(str);
}
final long identity = Binder.clearCallingIdentity();
try {
@@ -1537,7 +1584,8 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
if (userState.isDisplayMagnificationEnabledLocked()) {
flags |= AccessibilityInputFilter.FLAG_FEATURE_SCREEN_MAGNIFIER;
}
- if (userState.isNavBarMagnificationEnabledLocked()) {
+ if (userState.isNavBarMagnificationEnabledLocked()
+ || userState.isShortcutKeyMagnificationEnabledLocked()) {
flags |= AccessibilityInputFilter.FLAG_FEATURE_TRIGGERED_SCREEN_MAGNIFIER;
}
if (userHasMagnificationServicesLocked(userState)) {
@@ -1647,7 +1695,6 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
mInitialized = true;
updateLegacyCapabilitiesLocked(userState);
updateServicesLocked(userState);
- updateAccessibilityShortcutLocked(userState);
updateWindowsForAccessibilityCallbackLocked(userState);
updateFilterKeyEventsLocked(userState);
updateTouchExplorationLocked(userState);
@@ -1657,6 +1704,7 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
scheduleUpdateInputFilter(userState);
updateRelevantEventsLocked(userState);
scheduleUpdateClientsIfNeededLocked(userState);
+ updateAccessibilityShortcutKeyTargetsLocked(userState);
updateAccessibilityButtonTargetsLocked(userState);
}
@@ -1751,7 +1799,7 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
somethingChanged |= readHighTextContrastEnabledSettingLocked(userState);
somethingChanged |= readMagnificationEnabledSettingsLocked(userState);
somethingChanged |= readAutoclickEnabledSettingLocked(userState);
- somethingChanged |= readAccessibilityShortcutSettingLocked(userState);
+ somethingChanged |= readAccessibilityShortcutKeySettingLocked(userState);
somethingChanged |= readAccessibilityButtonSettingsLocked(userState);
somethingChanged |= readUserRecommendedUiTimeoutSettingsLocked(userState);
return somethingChanged;
@@ -1847,57 +1895,43 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
}
}
- private boolean readAccessibilityShortcutSettingLocked(AccessibilityUserState userState) {
- String componentNameToEnableString = AccessibilityShortcutController
- .getTargetServiceComponentNameString(mContext, userState.mUserId);
- if ((componentNameToEnableString == null) || componentNameToEnableString.isEmpty()) {
- if (userState.getServiceToEnableWithShortcutLocked() == null) {
- return false;
+ private boolean readAccessibilityShortcutKeySettingLocked(AccessibilityUserState userState) {
+ final Set<String> targetsFromSetting = new ArraySet<>();
+ readColonDelimitedSettingToSet(Settings.Secure.ACCESSIBILITY_SHORTCUT_TARGET_SERVICE,
+ userState.mUserId, targetsFromSetting, str -> str);
+ if (targetsFromSetting.isEmpty()) {
+ // Fall back to device's default a11y service.
+ final String defaultService = mContext.getString(
+ R.string.config_defaultAccessibilityService);
+ if (!TextUtils.isEmpty(defaultService)) {
+ targetsFromSetting.add(defaultService);
}
- userState.setServiceToEnableWithShortcutLocked(null);
- return true;
}
- ComponentName componentNameToEnable =
- ComponentName.unflattenFromString(componentNameToEnableString);
- if ((componentNameToEnable != null)
- && componentNameToEnable.equals(userState.getServiceToEnableWithShortcutLocked())) {
+
+ final Set<String> currentTargets =
+ userState.getShortcutTargetsLocked(ACCESSIBILITY_SHORTCUT_KEY);
+ if (targetsFromSetting.equals(currentTargets)) {
return false;
}
-
- userState.setServiceToEnableWithShortcutLocked(componentNameToEnable);
+ currentTargets.clear();
+ currentTargets.addAll(targetsFromSetting);
scheduleNotifyClientsOfServicesStateChangeLocked(userState);
return true;
}
private boolean readAccessibilityButtonSettingsLocked(AccessibilityUserState userState) {
- String componentId = Settings.Secure.getStringForUser(mContext.getContentResolver(),
- Settings.Secure.ACCESSIBILITY_BUTTON_TARGET_COMPONENT, userState.mUserId);
- if (TextUtils.isEmpty(componentId)) {
- if ((userState.getServiceAssignedToAccessibilityButtonLocked() == null)
- && !userState.isNavBarMagnificationAssignedToAccessibilityButtonLocked()) {
- return false;
- }
- userState.setServiceAssignedToAccessibilityButtonLocked(null);
- userState.setNavBarMagnificationAssignedToAccessibilityButtonLocked(false);
- return true;
- }
-
- if (componentId.equals(MagnificationController.class.getName())) {
- if (userState.isNavBarMagnificationAssignedToAccessibilityButtonLocked()) {
- return false;
- }
- userState.setServiceAssignedToAccessibilityButtonLocked(null);
- userState.setNavBarMagnificationAssignedToAccessibilityButtonLocked(true);
- return true;
- }
+ final Set<String> targetsFromSetting = new ArraySet<>();
+ readColonDelimitedSettingToSet(Settings.Secure.ACCESSIBILITY_BUTTON_TARGET_COMPONENT,
+ userState.mUserId, targetsFromSetting, str -> str);
- ComponentName componentName = ComponentName.unflattenFromString(componentId);
- if (Objects.equals(componentName,
- userState.getServiceAssignedToAccessibilityButtonLocked())) {
+ final Set<String> currentTargets =
+ userState.getShortcutTargetsLocked(ACCESSIBILITY_BUTTON);
+ if (targetsFromSetting.equals(currentTargets)) {
return false;
}
- userState.setServiceAssignedToAccessibilityButtonLocked(componentName);
- userState.setNavBarMagnificationAssignedToAccessibilityButtonLocked(false);
+ currentTargets.clear();
+ currentTargets.addAll(targetsFromSetting);
+ scheduleNotifyClientsOfServicesStateChangeLocked(userState);
return true;
}
@@ -1921,34 +1955,33 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
}
/**
- * Check if the service that will be enabled by the shortcut is installed. If it isn't,
- * clear the value and the associated setting so a sideloaded service can't spoof the
- * package name of the default service.
- *
- * @param userState
+ * Check if the targets that will be enabled by the accessibility shortcut key is installed.
+ * If it isn't, remove it from the list and associated setting so a side loaded service can't
+ * spoof the package name of the default service.
*/
- private void updateAccessibilityShortcutLocked(AccessibilityUserState userState) {
- if (userState.getServiceToEnableWithShortcutLocked() == null) {
+ private void updateAccessibilityShortcutKeyTargetsLocked(AccessibilityUserState userState) {
+ final Set<String> currentTargets =
+ userState.getShortcutTargetsLocked(ACCESSIBILITY_SHORTCUT_KEY);
+ final int lastSize = currentTargets.size();
+ if (lastSize == 0) {
return;
}
- boolean shortcutServiceIsInstalled =
- AccessibilityShortcutController.getFrameworkShortcutFeaturesMap()
- .containsKey(userState.getServiceToEnableWithShortcutLocked());
- for (int i = 0; !shortcutServiceIsInstalled && (i < userState.mInstalledServices.size());
- i++) {
- if (userState.mInstalledServices.get(i).getComponentName()
- .equals(userState.getServiceToEnableWithShortcutLocked())) {
- shortcutServiceIsInstalled = true;
- }
+ currentTargets.removeIf(
+ name -> !userState.isShortcutTargetInstalledLocked(name));
+ if (lastSize == currentTargets.size()) {
+ return;
}
- if (!shortcutServiceIsInstalled) {
- userState.setServiceToEnableWithShortcutLocked(null);
+
+ // Update setting key with new value.
+ persistColonDelimitedSetToSettingLocked(
+ Settings.Secure.ACCESSIBILITY_SHORTCUT_TARGET_SERVICE,
+ userState.mUserId, currentTargets, str -> str);
+ scheduleNotifyClientsOfServicesStateChangeLocked(userState);
+
+ // Disable accessibility shortcut key if there's no shortcut installed.
+ if (currentTargets.isEmpty()) {
final long identity = Binder.clearCallingIdentity();
try {
- Settings.Secure.putStringForUser(mContext.getContentResolver(),
- Settings.Secure.ACCESSIBILITY_SHORTCUT_TARGET_SERVICE, null,
- userState.mUserId);
-
Settings.Secure.putIntForUser(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_SHORTCUT_ENABLED, 0, userState.mUserId);
} finally {
@@ -2004,7 +2037,8 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
// displays in one display. It's not a real display and there's no input events for it.
final ArrayList<Display> displays = getValidDisplayList();
if (userState.isDisplayMagnificationEnabledLocked()
- || userState.isNavBarMagnificationEnabledLocked()) {
+ || userState.isNavBarMagnificationEnabledLocked()
+ || userState.isShortcutKeyMagnificationEnabledLocked()) {
for (int i = 0; i < displays.size(); i++) {
final Display display = displays.get(i);
getMagnificationController().register(display.getDisplayId());
@@ -2088,7 +2122,14 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
}
}
+ /**
+ * 1) Update accessibility button availability to accessibility services.
+ * 2) Check if the targets that will be enabled by the accessibility button is installed.
+ * If it isn't, remove it from the list and associated setting so a side loaded service can't
+ * spoof the package name of the default service.
+ */
private void updateAccessibilityButtonTargetsLocked(AccessibilityUserState userState) {
+ // Update accessibility button availability.
for (int i = userState.mBoundServices.size() - 1; i >= 0; i--) {
final AccessibilityServiceConnection service = userState.mBoundServices.get(i);
if (service.mRequestAccessibilityButton) {
@@ -2096,6 +2137,24 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
service.isAccessibilityButtonAvailableLocked(userState));
}
}
+
+ final Set<String> currentTargets =
+ userState.getShortcutTargetsLocked(ACCESSIBILITY_BUTTON);
+ final int lastSize = currentTargets.size();
+ if (lastSize == 0) {
+ return;
+ }
+ currentTargets.removeIf(
+ name -> !userState.isShortcutTargetInstalledLocked(name));
+ if (lastSize == currentTargets.size()) {
+ return;
+ }
+
+ // Update setting key with new value.
+ persistColonDelimitedSetToSettingLocked(
+ Settings.Secure.ACCESSIBILITY_BUTTON_TARGET_COMPONENT,
+ userState.mUserId, currentTargets, str -> str);
+ scheduleNotifyClientsOfServicesStateChangeLocked(userState);
}
private void updateRecommendedUiTimeoutLocked(AccessibilityUserState userState) {
@@ -2156,7 +2215,7 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
}
/**
- * AIDL-exposed method to be called when the accessibility shortcut is enabled. Requires
+ * AIDL-exposed method to be called when the accessibility shortcut key is enabled. Requires
* permission to write secure settings, since someone with that permission can enable
* accessibility services themselves.
*/
@@ -2168,52 +2227,177 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
throw new SecurityException(
"performAccessibilityShortcut requires the MANAGE_ACCESSIBILITY permission");
}
+ mMainHandler.sendMessage(obtainMessage(
+ AccessibilityManagerService::performAccessibilityShortcutInternal, this,
+ Display.DEFAULT_DISPLAY, ACCESSIBILITY_SHORTCUT_KEY));
+ }
+
+ /**
+ * Perform the accessibility shortcut action.
+ *
+ * @param shortcutType The shortcut type.
+ * @param displayId The display id of the accessibility button.
+ */
+ private void performAccessibilityShortcutInternal(int displayId,
+ @ShortcutType int shortcutType) {
+ final List<String> shortcutTargets = getAccessibilityShortcutTargetsInternal(shortcutType);
+ if (shortcutTargets.isEmpty()) {
+ Slog.d(LOG_TAG, "No target to perform shortcut, shortcutType=" + shortcutType);
+ return;
+ }
+ // In case there are many targets assigned to the given shortcut.
+ if (shortcutTargets.size() > 1) {
+ showAccessibilityTargetsSelection(displayId, shortcutType);
+ return;
+ }
+ final String targetName = shortcutTargets.get(0);
+ // In case user assigned magnification to the given shortcut.
+ if (targetName.equals(MAGNIFICATION_CONTROLLER_NAME)) {
+ sendAccessibilityButtonToInputFilter(displayId);
+ return;
+ }
+ final ComponentName targetComponentName = ComponentName.unflattenFromString(targetName);
+ if (targetComponentName == null) {
+ Slog.d(LOG_TAG, "Perform shortcut failed, invalid target name:" + targetName);
+ return;
+ }
+ // In case user assigned an accessibility framework feature to the given shortcut.
+ if (performAccessibilityFrameworkFeature(targetComponentName)) {
+ return;
+ }
+ // In case user assigned an accessibility shortcut target to the given shortcut.
+ if (performAccessibilityShortcutTargetActivity(displayId, targetComponentName)) {
+ return;
+ }
+ // in case user assigned an accessibility service to the given shortcut.
+ if (performAccessibilityShortcutTargetService(
+ displayId, shortcutType, targetComponentName)) {
+ return;
+ }
+ }
+
+ private boolean performAccessibilityFrameworkFeature(ComponentName assignedTarget) {
final Map<ComponentName, ToggleableFrameworkFeatureInfo> frameworkFeatureMap =
AccessibilityShortcutController.getFrameworkShortcutFeaturesMap();
- synchronized(mLock) {
- final AccessibilityUserState userState = getUserStateLocked(mCurrentUserId);
- final ComponentName serviceName = userState.getServiceToEnableWithShortcutLocked();
- if (serviceName == null) {
- return;
- }
- if (frameworkFeatureMap.containsKey(serviceName)) {
- // Toggle the requested framework feature
- ToggleableFrameworkFeatureInfo featureInfo = frameworkFeatureMap.get(serviceName);
- SettingStringHelper setting = new SettingStringHelper(mContext.getContentResolver(),
- featureInfo.getSettingKey(), mCurrentUserId);
- // Assuming that the default state will be to have the feature off
- if (!TextUtils.equals(featureInfo.getSettingOnValue(), setting.read())) {
- setting.write(featureInfo.getSettingOnValue());
- } else {
- setting.write(featureInfo.getSettingOffValue());
+ if (!frameworkFeatureMap.containsKey(assignedTarget)) {
+ return false;
+ }
+ // Toggle the requested framework feature
+ final ToggleableFrameworkFeatureInfo featureInfo = frameworkFeatureMap.get(assignedTarget);
+ final SettingStringHelper setting = new SettingStringHelper(mContext.getContentResolver(),
+ featureInfo.getSettingKey(), mCurrentUserId);
+ // Assuming that the default state will be to have the feature off
+ if (!TextUtils.equals(featureInfo.getSettingOnValue(), setting.read())) {
+ setting.write(featureInfo.getSettingOnValue());
+ } else {
+ setting.write(featureInfo.getSettingOffValue());
+ }
+ return true;
+ }
+
+ private boolean performAccessibilityShortcutTargetActivity(int displayId,
+ ComponentName assignedTarget) {
+ synchronized (mLock) {
+ final AccessibilityUserState userState = getCurrentUserStateLocked();
+ for (int i = 0; i < userState.mInstalledShortcuts.size(); i++) {
+ final AccessibilityShortcutInfo shortcutInfo = userState.mInstalledShortcuts.get(i);
+ if (!shortcutInfo.getComponentName().equals(assignedTarget)) {
+ continue;
}
+ launchShortcutTargetActivity(displayId, assignedTarget);
+ return true;
}
- final long identity = Binder.clearCallingIdentity();
- try {
- if (userState.mComponentNameToServiceMap.get(serviceName) == null) {
- enableAccessibilityServiceLocked(serviceName, mCurrentUserId);
+ }
+ return false;
+ }
+
+ /**
+ * Perform accessibility service shortcut action.
+ *
+ * 1) For {@link AccessibilityManager#ACCESSIBILITY_BUTTON} type and services targeting sdk
+ * version <= Q: callbacks to accessibility service if service is bounded and requests
+ * accessibility button.
+ * 2) For {@link AccessibilityManager#ACCESSIBILITY_SHORTCUT_KEY} type and service targeting sdk
+ * version <= Q: turns on / off the accessibility service.
+ * 3) For services targeting sdk version > Q:
+ * a) Turns on / off the accessibility service, if service does not request accessibility
+ * button.
+ * b) Callbacks to accessibility service if service is bounded and requests accessibility
+ * button.
+ */
+ private boolean performAccessibilityShortcutTargetService(int displayId,
+ @ShortcutType int shortcutType, ComponentName assignedTarget) {
+ synchronized (mLock) {
+ final AccessibilityUserState userState = getCurrentUserStateLocked();
+ final AccessibilityServiceInfo installedServiceInfo =
+ userState.getInstalledServiceInfoLocked(assignedTarget);
+ if (installedServiceInfo == null) {
+ Slog.d(LOG_TAG, "Perform shortcut failed, invalid component name:"
+ + assignedTarget);
+ return false;
+ }
+
+ final AccessibilityServiceConnection serviceConnection =
+ userState.getServiceConnectionLocked(assignedTarget);
+ final int targetSdk = installedServiceInfo.getResolveInfo()
+ .serviceInfo.applicationInfo.targetSdkVersion;
+ final boolean requestA11yButton = (installedServiceInfo.flags
+ & AccessibilityServiceInfo.FLAG_REQUEST_ACCESSIBILITY_BUTTON) != 0;
+ // Turns on / off the accessibility service
+ if ((targetSdk <= Build.VERSION_CODES.Q && shortcutType == ACCESSIBILITY_SHORTCUT_KEY)
+ || (targetSdk > Build.VERSION_CODES.Q && !requestA11yButton)) {
+ if (serviceConnection == null) {
+ enableAccessibilityServiceLocked(assignedTarget, mCurrentUserId);
} else {
- disableAccessibilityServiceLocked(serviceName, mCurrentUserId);
+ disableAccessibilityServiceLocked(assignedTarget, mCurrentUserId);
}
- } finally {
- Binder.restoreCallingIdentity(identity);
+ return true;
+ }
+ // Callbacks to a11y service if it's bounded and requests a11y button.
+ if (serviceConnection == null
+ || !userState.mBoundServices.contains(serviceConnection)
+ || !serviceConnection.mRequestAccessibilityButton) {
+ Slog.d(LOG_TAG, "Perform shortcut failed, service is not ready:"
+ + assignedTarget);
+ return false;
}
+ serviceConnection.notifyAccessibilityButtonClickedLocked(displayId);
+ return true;
}
- };
+ }
@Override
- public String getAccessibilityShortcutService() {
- if (mContext.checkCallingPermission(Manifest.permission.MANAGE_ACCESSIBILITY)
+ public List<String> getAccessibilityShortcutTargets(@ShortcutType int shortcutType) {
+ if (mContext.checkCallingOrSelfPermission(Manifest.permission.MANAGE_ACCESSIBILITY)
!= PackageManager.PERMISSION_GRANTED) {
throw new SecurityException(
"getAccessibilityShortcutService requires the MANAGE_ACCESSIBILITY permission");
}
- synchronized(mLock) {
- final AccessibilityUserState userState = getUserStateLocked(mCurrentUserId);
- if (userState.getServiceToEnableWithShortcutLocked() == null) {
- return null;
+ return getAccessibilityShortcutTargetsInternal(shortcutType);
+ }
+
+ private List<String> getAccessibilityShortcutTargetsInternal(@ShortcutType int shortcutType) {
+ synchronized (mLock) {
+ final AccessibilityUserState userState = getCurrentUserStateLocked();
+ final ArrayList<String> shortcutTargets = new ArrayList<>(
+ userState.getShortcutTargetsLocked(shortcutType));
+ if (shortcutType != ACCESSIBILITY_BUTTON) {
+ return shortcutTargets;
+ }
+ // Adds legacy a11y services requesting a11y button into the list.
+ for (int i = userState.mBoundServices.size() - 1; i >= 0; i--) {
+ final AccessibilityServiceConnection service = userState.mBoundServices.get(i);
+ if (!service.mRequestAccessibilityButton
+ || service.getServiceInfo().getResolveInfo().serviceInfo.applicationInfo
+ .targetSdkVersion > Build.VERSION_CODES.Q) {
+ continue;
+ }
+ final String serviceName = service.getComponentName().flattenToString();
+ if (!TextUtils.isEmpty(serviceName)) {
+ shortcutTargets.add(serviceName);
+ }
}
- return userState.getServiceToEnableWithShortcutLocked().flattenToString();
+ return shortcutTargets;
}
}
@@ -2609,6 +2793,8 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
private final Uri mDisplayMagnificationEnabledUri = Settings.Secure.getUriFor(
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED);
+ // TODO(a11y shortcut): Remove this setting key, and have a migrate function in
+ // Setting provider after new shortcut UI merged.
private final Uri mNavBarMagnificationEnabledUri = Settings.Secure.getUriFor(
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_NAVBAR_ENABLED);
@@ -2713,7 +2899,7 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
|| mShowImeWithHardKeyboardUri.equals(uri)) {
userState.reconcileSoftKeyboardModeWithSettingsLocked();
} else if (mAccessibilityShortcutServiceIdUri.equals(uri)) {
- if (readAccessibilityShortcutSettingLocked(userState)) {
+ if (readAccessibilityShortcutKeySettingLocked(userState)) {
onUserStateChangedLocked(userState);
}
} else if (mAccessibilityButtonComponentIdUri.equals(uri)) {
@@ -2724,8 +2910,6 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
|| mUserInteractiveUiTimeoutUri.equals(uri)) {
readUserRecommendedUiTimeoutSettingsLocked(userState);
}
- // TODO(a11y shortcut): Monitor new setting keys, when user adds shortcut, and
- // remove from the list of enabled targets anything that's been uninstalled.
}
}
}
diff --git a/services/accessibility/java/com/android/server/accessibility/AccessibilityServiceConnection.java b/services/accessibility/java/com/android/server/accessibility/AccessibilityServiceConnection.java
index 6cadb6d0f31f..cbff6bdcec77 100644
--- a/services/accessibility/java/com/android/server/accessibility/AccessibilityServiceConnection.java
+++ b/services/accessibility/java/com/android/server/accessibility/AccessibilityServiceConnection.java
@@ -294,6 +294,7 @@ class AccessibilityServiceConnection extends AbstractAccessibilityServiceConnect
}
}
+ // TODO(a11y shortcut): Refactoring the logic here, after the new Settings shortcut Ui merged.
public boolean isAccessibilityButtonAvailableLocked(AccessibilityUserState userState) {
// If the service does not request the accessibility button, it isn't available
if (!mRequestAccessibilityButton) {
diff --git a/services/accessibility/java/com/android/server/accessibility/AccessibilityUserState.java b/services/accessibility/java/com/android/server/accessibility/AccessibilityUserState.java
index a0b9866e24d2..a163f7434e1f 100644
--- a/services/accessibility/java/com/android/server/accessibility/AccessibilityUserState.java
+++ b/services/accessibility/java/com/android/server/accessibility/AccessibilityUserState.java
@@ -22,6 +22,11 @@ import static android.accessibilityservice.AccessibilityService.SHOW_MODE_HARD_K
import static android.accessibilityservice.AccessibilityService.SHOW_MODE_HIDDEN;
import static android.accessibilityservice.AccessibilityService.SHOW_MODE_IGNORE_HARD_KEYBOARD;
import static android.accessibilityservice.AccessibilityService.SHOW_MODE_MASK;
+import static android.view.accessibility.AccessibilityManager.ACCESSIBILITY_BUTTON;
+import static android.view.accessibility.AccessibilityManager.ACCESSIBILITY_SHORTCUT_KEY;
+import static android.view.accessibility.AccessibilityManager.ShortcutType;
+
+import static com.android.internal.accessibility.AccessibilityShortcutController.MAGNIFICATION_CONTROLLER_NAME;
import android.accessibilityservice.AccessibilityService.SoftKeyboardShowMode;
import android.accessibilityservice.AccessibilityServiceInfo;
@@ -33,10 +38,14 @@ import android.content.Context;
import android.os.Binder;
import android.os.RemoteCallbackList;
import android.provider.Settings;
+import android.text.TextUtils;
+import android.util.ArraySet;
import android.util.Slog;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.IAccessibilityManagerClient;
+import com.android.internal.accessibility.AccessibilityShortcutController;
+
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
@@ -79,19 +88,18 @@ class AccessibilityUserState {
final Set<ComponentName> mTouchExplorationGrantedServices = new HashSet<>();
- private final ServiceInfoChangeListener mServiceInfoChangeListener;
+ final ArraySet<String> mAccessibilityShortcutKeyTargets = new ArraySet<>();
- private ComponentName mServiceAssignedToAccessibilityButton;
+ final ArraySet<String> mAccessibilityButtonTargets = new ArraySet<>();
- private ComponentName mServiceChangingSoftKeyboardMode;
+ private final ServiceInfoChangeListener mServiceInfoChangeListener;
- private ComponentName mServiceToEnableWithShortcut;
+ private ComponentName mServiceChangingSoftKeyboardMode;
private boolean mBindInstantServiceAllowed;
private boolean mIsAutoclickEnabled;
private boolean mIsDisplayMagnificationEnabled;
private boolean mIsFilterKeyEventsEnabled;
- private boolean mIsNavBarMagnificationAssignedToAccessibilityButton;
private boolean mIsNavBarMagnificationEnabled;
private boolean mIsPerformGesturesEnabled;
private boolean mIsTextHighContrastEnabled;
@@ -141,11 +149,11 @@ class AccessibilityUserState {
// Clear state persisted in settings.
mEnabledServices.clear();
mTouchExplorationGrantedServices.clear();
+ mAccessibilityShortcutKeyTargets.clear();
+ mAccessibilityButtonTargets.clear();
mIsTouchExplorationEnabled = false;
mIsDisplayMagnificationEnabled = false;
mIsNavBarMagnificationEnabled = false;
- mServiceAssignedToAccessibilityButton = null;
- mIsNavBarMagnificationAssignedToAccessibilityButton = false;
mIsAutoclickEnabled = false;
mUserNonInteractiveUiTimeout = 0;
mUserInteractiveUiTimeout = 0;
@@ -435,6 +443,26 @@ class AccessibilityUserState {
pw.append(", installedServiceCount=").append(String.valueOf(mInstalledServices.size()));
pw.append("}");
pw.println();
+ pw.append(" shortcut key:{");
+ int size = mAccessibilityShortcutKeyTargets.size();
+ for (int i = 0; i < size; i++) {
+ final String componentId = mAccessibilityShortcutKeyTargets.valueAt(i);
+ pw.append(componentId);
+ if (i + 1 < size) {
+ pw.append(", ");
+ }
+ }
+ pw.println("}");
+ pw.append(" button:{");
+ size = mAccessibilityButtonTargets.size();
+ for (int i = 0; i < size; i++) {
+ final String componentId = mAccessibilityButtonTargets.valueAt(i);
+ pw.append(componentId);
+ if (i + 1 < size) {
+ pw.append(", ");
+ }
+ }
+ pw.println("}");
pw.append(" Bound services:{");
final int serviceCount = mBoundServices.size();
for (int j = 0; j < serviceCount; j++) {
@@ -525,20 +553,85 @@ class AccessibilityUserState {
mLastSentClientState = state;
}
- public boolean isNavBarMagnificationAssignedToAccessibilityButtonLocked() {
- return mIsNavBarMagnificationAssignedToAccessibilityButton;
+ public boolean isShortcutKeyMagnificationEnabledLocked() {
+ return mAccessibilityShortcutKeyTargets.contains(MAGNIFICATION_CONTROLLER_NAME);
}
- public void setNavBarMagnificationAssignedToAccessibilityButtonLocked(boolean assigned) {
- mIsNavBarMagnificationAssignedToAccessibilityButton = assigned;
+ /**
+ * Disable both shortcuts' magnification function.
+ */
+ public void disableShortcutMagnificationLocked() {
+ mAccessibilityShortcutKeyTargets.remove(MAGNIFICATION_CONTROLLER_NAME);
+ mAccessibilityButtonTargets.remove(MAGNIFICATION_CONTROLLER_NAME);
}
- public boolean isNavBarMagnificationEnabledLocked() {
- return mIsNavBarMagnificationEnabled;
+ /**
+ * Returns a set which contains the flattened component names and the system class names
+ * assigned to the given shortcut.
+ *
+ * @param shortcutType The shortcut type.
+ * @return The array set of the strings
+ */
+ public ArraySet<String> getShortcutTargetsLocked(@ShortcutType int shortcutType) {
+ if (shortcutType == ACCESSIBILITY_SHORTCUT_KEY) {
+ return mAccessibilityShortcutKeyTargets;
+ } else if (shortcutType == ACCESSIBILITY_BUTTON) {
+ return mAccessibilityButtonTargets;
+ }
+ return null;
}
- public void setNavBarMagnificationEnabledLocked(boolean enabled) {
- mIsNavBarMagnificationEnabled = enabled;
+ /**
+ * Whether or not the given shortcut target is installed in device.
+ *
+ * @param name The shortcut target name
+ * @return true if the shortcut target is installed.
+ */
+ public boolean isShortcutTargetInstalledLocked(String name) {
+ if (TextUtils.isEmpty(name)) {
+ return false;
+ }
+ if (MAGNIFICATION_CONTROLLER_NAME.equals(name)) {
+ return true;
+ }
+
+ final ComponentName componentName = ComponentName.unflattenFromString(name);
+ if (componentName == null) {
+ return false;
+ }
+ if (AccessibilityShortcutController.getFrameworkShortcutFeaturesMap()
+ .containsKey(componentName)) {
+ return true;
+ }
+ if (getInstalledServiceInfoLocked(componentName) != null) {
+ return true;
+ }
+ for (int i = 0; i < mInstalledShortcuts.size(); i++) {
+ if (mInstalledShortcuts.get(i).getComponentName().equals(componentName)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Returns installed accessibility service info by the given service component name.
+ */
+ public AccessibilityServiceInfo getInstalledServiceInfoLocked(ComponentName componentName) {
+ for (int i = 0; i < mInstalledServices.size(); i++) {
+ final AccessibilityServiceInfo serviceInfo = mInstalledServices.get(i);
+ if (serviceInfo.getComponentName().equals(componentName)) {
+ return serviceInfo;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns accessibility service connection by the given service component name.
+ */
+ public AccessibilityServiceConnection getServiceConnectionLocked(ComponentName componentName) {
+ return mComponentNameToServiceMap.get(componentName);
}
public int getNonInteractiveUiTimeoutLocked() {
@@ -557,14 +650,6 @@ class AccessibilityUserState {
mIsPerformGesturesEnabled = enabled;
}
- public ComponentName getServiceAssignedToAccessibilityButtonLocked() {
- return mServiceAssignedToAccessibilityButton;
- }
-
- public void setServiceAssignedToAccessibilityButtonLocked(ComponentName componentName) {
- mServiceAssignedToAccessibilityButton = componentName;
- }
-
public ComponentName getServiceChangingSoftKeyboardModeLocked() {
return mServiceChangingSoftKeyboardMode;
}
@@ -574,14 +659,6 @@ class AccessibilityUserState {
mServiceChangingSoftKeyboardMode = serviceChangingSoftKeyboardMode;
}
- public ComponentName getServiceToEnableWithShortcutLocked() {
- return mServiceToEnableWithShortcut;
- }
-
- public void setServiceToEnableWithShortcutLocked(ComponentName componentName) {
- mServiceToEnableWithShortcut = componentName;
- }
-
public boolean isTextHighContrastEnabledLocked() {
return mIsTextHighContrastEnabled;
}
@@ -613,4 +690,28 @@ class AccessibilityUserState {
public void setUserNonInteractiveUiTimeoutLocked(int timeout) {
mUserNonInteractiveUiTimeout = timeout;
}
+
+ // TODO(a11y shortcut): These functions aren't necessary, after the new Settings shortcut Ui
+ // is merged.
+ boolean isNavBarMagnificationEnabledLocked() {
+ return mIsNavBarMagnificationEnabled;
+ }
+
+ void setNavBarMagnificationEnabledLocked(boolean enabled) {
+ mIsNavBarMagnificationEnabled = enabled;
+ }
+
+ boolean isNavBarMagnificationAssignedToAccessibilityButtonLocked() {
+ return mAccessibilityButtonTargets.contains(MAGNIFICATION_CONTROLLER_NAME);
+ }
+
+ ComponentName getServiceAssignedToAccessibilityButtonLocked() {
+ final String targetName = mAccessibilityButtonTargets.isEmpty() ? null
+ : mAccessibilityButtonTargets.valueAt(0);
+ if (targetName == null) {
+ return null;
+ }
+ return ComponentName.unflattenFromString(targetName);
+ }
+ // TODO(a11y shortcut): End
}
diff --git a/services/accessibility/java/com/android/server/accessibility/gestures/AccessibilityGestureDetector.java b/services/accessibility/java/com/android/server/accessibility/gestures/AccessibilityGestureDetector.java
deleted file mode 100644
index 3dfe59e142a6..000000000000
--- a/services/accessibility/java/com/android/server/accessibility/gestures/AccessibilityGestureDetector.java
+++ /dev/null
@@ -1,640 +0,0 @@
-/*
- ** Copyright 2015, 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 com.android.server.accessibility.gestures;
-
-import android.accessibilityservice.AccessibilityGestureEvent;
-import android.accessibilityservice.AccessibilityService;
-import android.content.Context;
-import android.gesture.GesturePoint;
-import android.graphics.PointF;
-import android.util.Slog;
-import android.util.TypedValue;
-import android.view.GestureDetector;
-import android.view.MotionEvent;
-
-import java.util.ArrayList;
-
-/**
- * This class handles gesture detection for the Touch Explorer. It collects
- * touch events and determines when they match a gesture, as well as when they
- * won't match a gesture. These state changes are then surfaced to mListener.
- */
-class AccessibilityGestureDetector extends GestureDetector.SimpleOnGestureListener {
-
- private static final boolean DEBUG = false;
-
- // Tag for logging received events.
- private static final String LOG_TAG = "AccessibilityGestureDetector";
-
- // Constants for sampling motion event points.
- // We sample based on a minimum distance between points, primarily to improve accuracy by
- // reducing noisy minor changes in direction.
- private static final float MIN_INCHES_BETWEEN_SAMPLES = 0.1f;
- private final float mMinPixelsBetweenSamplesX;
- private final float mMinPixelsBetweenSamplesY;
-
- // Constants for separating gesture segments
- private static final float ANGLE_THRESHOLD = 0.0f;
-
- // Constants for line segment directions
- private static final int LEFT = 0;
- private static final int RIGHT = 1;
- private static final int UP = 2;
- private static final int DOWN = 3;
- private static final int[][] DIRECTIONS_TO_GESTURE_ID = {
- {
- AccessibilityService.GESTURE_SWIPE_LEFT,
- AccessibilityService.GESTURE_SWIPE_LEFT_AND_RIGHT,
- AccessibilityService.GESTURE_SWIPE_LEFT_AND_UP,
- AccessibilityService.GESTURE_SWIPE_LEFT_AND_DOWN
- },
- {
- AccessibilityService.GESTURE_SWIPE_RIGHT_AND_LEFT,
- AccessibilityService.GESTURE_SWIPE_RIGHT,
- AccessibilityService.GESTURE_SWIPE_RIGHT_AND_UP,
- AccessibilityService.GESTURE_SWIPE_RIGHT_AND_DOWN
- },
- {
- AccessibilityService.GESTURE_SWIPE_UP_AND_LEFT,
- AccessibilityService.GESTURE_SWIPE_UP_AND_RIGHT,
- AccessibilityService.GESTURE_SWIPE_UP,
- AccessibilityService.GESTURE_SWIPE_UP_AND_DOWN
- },
- {
- AccessibilityService.GESTURE_SWIPE_DOWN_AND_LEFT,
- AccessibilityService.GESTURE_SWIPE_DOWN_AND_RIGHT,
- AccessibilityService.GESTURE_SWIPE_DOWN_AND_UP,
- AccessibilityService.GESTURE_SWIPE_DOWN
- }
- };
-
-
- /**
- * Listener functions are called as a result of onMoveEvent(). The current
- * MotionEvent in the context of these functions is the event passed into
- * onMotionEvent.
- */
- public interface Listener {
- /**
- * Called when the user has performed a double tap and then held down
- * the second tap.
- *
- * @param event The most recent MotionEvent received.
- * @param policyFlags The policy flags of the most recent event.
- */
- void onDoubleTapAndHold(MotionEvent event, int policyFlags);
-
- /**
- * Called when the user lifts their finger on the second tap of a double
- * tap.
- *
- * @param event The most recent MotionEvent received.
- * @param policyFlags The policy flags of the most recent event.
- *
- * @return true if the event is consumed, else false
- */
- boolean onDoubleTap(MotionEvent event, int policyFlags);
-
- /**
- * Called when the system has decided the event stream is a gesture.
- *
- * @return true if the event is consumed, else false
- */
- boolean onGestureStarted();
-
- /**
- * Called when an event stream is recognized as a gesture.
- *
- * @param gestureEvent Information about the gesture.
- *
- * @return true if the event is consumed, else false
- */
- boolean onGestureCompleted(AccessibilityGestureEvent gestureEvent);
-
- /**
- * Called when the system has decided an event stream doesn't match any
- * known gesture.
- *
- * @param event The most recent MotionEvent received.
- * @param policyFlags The policy flags of the most recent event.
- *
- * @return true if the event is consumed, else false
- */
- public boolean onGestureCancelled(MotionEvent event, int policyFlags);
- }
-
- private final Listener mListener;
- private final Context mContext; // Retained for on-demand construction of GestureDetector.
- private final GestureDetector mGestureDetector; // Double-tap detector.
-
- // Indicates that a single tap has occurred.
- private boolean mFirstTapDetected;
-
- // Indicates that the down event of a double tap has occured.
- private boolean mDoubleTapDetected;
-
- // Indicates that motion events are being collected to match a gesture.
- private boolean mRecognizingGesture;
-
- // Indicates that we've collected enough data to be sure it could be a
- // gesture.
- private boolean mGestureStarted;
-
- // Indicates that motion events from the second pointer are being checked
- // for a double tap.
- private boolean mSecondFingerDoubleTap;
-
- // Tracks the most recent time where ACTION_POINTER_DOWN was sent for the
- // second pointer.
- private long mSecondPointerDownTime;
-
- // Policy flags of the previous event.
- private int mPolicyFlags;
-
- // These values track the previous point that was saved to use for gesture
- // detection. They are only updated when the user moves more than the
- // recognition threshold.
- private float mPreviousGestureX;
- private float mPreviousGestureY;
-
- // These values track the previous point that was used to determine if there
- // was a transition into or out of gesture detection. They are updated when
- // the user moves more than the detection threshold.
- private float mBaseX;
- private float mBaseY;
- private long mBaseTime;
-
- // This is the calculated movement threshold used track if the user is still
- // moving their finger.
- private final float mGestureDetectionThreshold;
-
- // Buffer for storing points for gesture detection.
- private final ArrayList<GesturePoint> mStrokeBuffer = new ArrayList<GesturePoint>(100);
-
- // The minimal delta between moves to add a gesture point.
- private static final int TOUCH_TOLERANCE = 3;
-
- // The minimal score for accepting a predicted gesture.
- private static final float MIN_PREDICTION_SCORE = 2.0f;
-
- // Distance a finger must travel before we decide if it is a gesture or not.
- private static final int GESTURE_CONFIRM_MM = 10;
-
- // Time threshold used to determine if an interaction is a gesture or not.
- // If the first movement of 1cm takes longer than this value, we assume it's
- // a slow movement, and therefore not a gesture.
- //
- // This value was determined by measuring the time for the first 1cm
- // movement when gesturing, and touch exploring. Based on user testing,
- // all gestures started with the initial movement taking less than 100ms.
- // When touch exploring, the first movement almost always takes longer than
- // 200ms.
- private static final long CANCEL_ON_PAUSE_THRESHOLD_NOT_STARTED_MS = 150;
-
- // Time threshold used to determine if a gesture should be cancelled. If
- // the finger takes more than this time to move 1cm, the ongoing gesture is
- // cancelled.
- private static final long CANCEL_ON_PAUSE_THRESHOLD_STARTED_MS = 300;
-
- /**
- * Construct the gesture detector for {@link TouchExplorer}.
- *
- * @see #AccessibilityGestureDetector(Context, Listener, GestureDetector)
- */
- AccessibilityGestureDetector(Context context, Listener listener) {
- this(context, listener, null);
- }
-
- /**
- * Construct the gesture detector for {@link TouchExplorer}.
- *
- * @param context A context handle for accessing resources.
- * @param listener A listener to callback with gesture state or information.
- * @param detector The gesture detector to handle touch event. If null the default one created
- * in place, or for testing purpose.
- */
- AccessibilityGestureDetector(Context context, Listener listener, GestureDetector detector) {
- mListener = listener;
- mContext = context;
-
- // Break the circular dependency between constructors and let the class to be testable
- if (detector == null) {
- mGestureDetector = new GestureDetector(context, this);
- } else {
- mGestureDetector = detector;
- }
- mGestureDetector.setOnDoubleTapListener(this);
- mGestureDetectionThreshold = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, 1,
- context.getResources().getDisplayMetrics()) * GESTURE_CONFIRM_MM;
-
- // Calculate minimum gesture velocity
- final float pixelsPerInchX = context.getResources().getDisplayMetrics().xdpi;
- final float pixelsPerInchY = context.getResources().getDisplayMetrics().ydpi;
- mMinPixelsBetweenSamplesX = MIN_INCHES_BETWEEN_SAMPLES * pixelsPerInchX;
- mMinPixelsBetweenSamplesY = MIN_INCHES_BETWEEN_SAMPLES * pixelsPerInchY;
- }
-
- /**
- * Handle a motion event. If an action is completed, the appropriate
- * callback on mListener is called, and the return value of the callback is
- * passed to the caller.
- *
- * @param event The transformed motion event to be handled.
- * @param rawEvent The raw motion event. It's important that this be the raw
- * event, before any transformations have been applied, so that measurements
- * can be made in physical units.
- * @param policyFlags Policy flags for the event.
- *
- * @return true if the event is consumed, else false
- */
- public boolean onMotionEvent(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
- // The accessibility gesture detector is interested in the movements in physical space,
- // so it uses the rawEvent to ignore magnification and other transformations.
- final float x = rawEvent.getX();
- final float y = rawEvent.getY();
- final long time = rawEvent.getEventTime();
-
- mPolicyFlags = policyFlags;
- switch (rawEvent.getActionMasked()) {
- case MotionEvent.ACTION_DOWN:
- mDoubleTapDetected = false;
- mSecondFingerDoubleTap = false;
- mRecognizingGesture = true;
- mGestureStarted = false;
- mPreviousGestureX = x;
- mPreviousGestureY = y;
- mStrokeBuffer.clear();
- mStrokeBuffer.add(new GesturePoint(x, y, time));
-
- mBaseX = x;
- mBaseY = y;
- mBaseTime = time;
- break;
-
- case MotionEvent.ACTION_MOVE:
- if (mRecognizingGesture) {
- final float deltaX = mBaseX - x;
- final float deltaY = mBaseY - y;
- final double moveDelta = Math.hypot(deltaX, deltaY);
- if (moveDelta > mGestureDetectionThreshold) {
- // If the pointer has moved more than the threshold,
- // update the stored values.
- mBaseX = x;
- mBaseY = y;
- mBaseTime = time;
-
- // Since the pointer has moved, this is not a double
- // tap.
- mFirstTapDetected = false;
- mDoubleTapDetected = false;
-
- // If this hasn't been confirmed as a gesture yet, send
- // the event.
- if (!mGestureStarted) {
- mGestureStarted = true;
- return mListener.onGestureStarted();
- }
- } else if (!mFirstTapDetected) {
- // The finger may not move if they are double tapping.
- // In that case, we shouldn't cancel the gesture.
- final long timeDelta = time - mBaseTime;
- final long threshold = mGestureStarted ?
- CANCEL_ON_PAUSE_THRESHOLD_STARTED_MS :
- CANCEL_ON_PAUSE_THRESHOLD_NOT_STARTED_MS;
-
- // If the pointer hasn't moved for longer than the
- // timeout, cancel gesture detection.
- if (timeDelta > threshold) {
- cancelGesture();
- return mListener.onGestureCancelled(rawEvent, policyFlags);
- }
- }
-
- final float dX = Math.abs(x - mPreviousGestureX);
- final float dY = Math.abs(y - mPreviousGestureY);
- if (dX >= mMinPixelsBetweenSamplesX || dY >= mMinPixelsBetweenSamplesY) {
- mPreviousGestureX = x;
- mPreviousGestureY = y;
- mStrokeBuffer.add(new GesturePoint(x, y, time));
- }
- }
- break;
-
- case MotionEvent.ACTION_UP:
- if (mDoubleTapDetected) {
- return finishDoubleTap(rawEvent, policyFlags);
- }
- if (mGestureStarted) {
- final float dX = Math.abs(x - mPreviousGestureX);
- final float dY = Math.abs(y - mPreviousGestureY);
- if (dX >= mMinPixelsBetweenSamplesX || dY >= mMinPixelsBetweenSamplesY) {
- mStrokeBuffer.add(new GesturePoint(x, y, time));
- }
- return recognizeGesture(rawEvent, policyFlags);
- }
- break;
-
- case MotionEvent.ACTION_POINTER_DOWN:
- // Once a second finger is used, we're definitely not
- // recognizing a gesture.
- cancelGesture();
-
- if (rawEvent.getPointerCount() == 2) {
- // If this was the second finger, attempt to recognize double
- // taps on it.
- mSecondFingerDoubleTap = true;
- mSecondPointerDownTime = time;
- } else {
- // If there are more than two fingers down, stop watching
- // for a double tap.
- mSecondFingerDoubleTap = false;
- }
- break;
-
- case MotionEvent.ACTION_POINTER_UP:
- // If we're detecting taps on the second finger, see if we
- // should finish the double tap.
- if (mSecondFingerDoubleTap && mDoubleTapDetected) {
- return finishDoubleTap(rawEvent, policyFlags);
- }
- break;
-
- case MotionEvent.ACTION_CANCEL:
- clear();
- break;
- }
-
- // If we're detecting taps on the second finger, map events from the
- // finger to the first finger.
- if (mSecondFingerDoubleTap) {
- MotionEvent newEvent = mapSecondPointerToFirstPointer(rawEvent);
- if (newEvent == null) {
- return false;
- }
- boolean handled = mGestureDetector.onTouchEvent(newEvent);
- newEvent.recycle();
- return handled;
- }
-
- if (!mRecognizingGesture) {
- return false;
- }
-
- // Pass the transformed event on to the standard gesture detector.
- return mGestureDetector.onTouchEvent(event);
- }
-
- public void clear() {
- mFirstTapDetected = false;
- mDoubleTapDetected = false;
- mSecondFingerDoubleTap = false;
- mGestureStarted = false;
- mGestureDetector.onTouchEvent(MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_CANCEL,
- 0.0f, 0.0f, 0));
- cancelGesture();
- }
-
-
- @Override
- public void onLongPress(MotionEvent e) {
- maybeSendLongPress(e, mPolicyFlags);
- }
-
- @Override
- public boolean onSingleTapUp(MotionEvent event) {
- mFirstTapDetected = true;
- return false;
- }
-
- @Override
- public boolean onSingleTapConfirmed(MotionEvent event) {
- clear();
- return false;
- }
-
- @Override
- public boolean onDoubleTap(MotionEvent event) {
- // The processing of the double tap is deferred until the finger is
- // lifted, so that we can detect a long press on the second tap.
- mDoubleTapDetected = true;
- return false;
- }
-
- private void maybeSendLongPress(MotionEvent event, int policyFlags) {
- if (!mDoubleTapDetected) {
- return;
- }
-
- clear();
-
- mListener.onDoubleTapAndHold(event, policyFlags);
- }
-
- private boolean finishDoubleTap(MotionEvent event, int policyFlags) {
- clear();
-
- return mListener.onDoubleTap(event, policyFlags);
- }
-
- private void cancelGesture() {
- mRecognizingGesture = false;
- mGestureStarted = false;
- mStrokeBuffer.clear();
- }
-
- /**
- * Looks at the sequence of motions in mStrokeBuffer, classifies the gesture, then calls
- * Listener callbacks for success or failure.
- *
- * @param event The raw motion event to pass to the listener callbacks.
- * @param policyFlags Policy flags for the event.
- *
- * @return true if the event is consumed, else false
- */
- private boolean recognizeGesture(MotionEvent event, int policyFlags) {
- if (mStrokeBuffer.size() < 2) {
- return mListener.onGestureCancelled(event, policyFlags);
- }
-
- // Look at mStrokeBuffer and extract 2 line segments, delimited by near-perpendicular
- // direction change.
- // Method: for each sampled motion event, check the angle of the most recent motion vector
- // versus the preceding motion vector, and segment the line if the angle is about
- // 90 degrees.
-
- ArrayList<PointF> path = new ArrayList<>();
- PointF lastDelimiter = new PointF(mStrokeBuffer.get(0).x, mStrokeBuffer.get(0).y);
- path.add(lastDelimiter);
-
- float dX = 0; // Sum of unit vectors from last delimiter to each following point
- float dY = 0;
- int count = 0; // Number of points since last delimiter
- float length = 0; // Vector length from delimiter to most recent point
-
- PointF next = new PointF();
- for (int i = 1; i < mStrokeBuffer.size(); ++i) {
- next = new PointF(mStrokeBuffer.get(i).x, mStrokeBuffer.get(i).y);
- if (count > 0) {
- // Average of unit vectors from delimiter to following points
- float currentDX = dX / count;
- float currentDY = dY / count;
-
- // newDelimiter is a possible new delimiter, based on a vector with length from
- // the last delimiter to the previous point, but in the direction of the average
- // unit vector from delimiter to previous points.
- // Using the averaged vector has the effect of "squaring off the curve",
- // creating a sharper angle between the last motion and the preceding motion from
- // the delimiter. In turn, this sharper angle achieves the splitting threshold
- // even in a gentle curve.
- PointF newDelimiter = new PointF(length * currentDX + lastDelimiter.x,
- length * currentDY + lastDelimiter.y);
-
- // Unit vector from newDelimiter to the most recent point
- float nextDX = next.x - newDelimiter.x;
- float nextDY = next.y - newDelimiter.y;
- float nextLength = (float) Math.sqrt(nextDX * nextDX + nextDY * nextDY);
- nextDX = nextDX / nextLength;
- nextDY = nextDY / nextLength;
-
- // Compare the initial motion direction to the most recent motion direction,
- // and segment the line if direction has changed by about 90 degrees.
- float dot = currentDX * nextDX + currentDY * nextDY;
- if (dot < ANGLE_THRESHOLD) {
- path.add(newDelimiter);
- lastDelimiter = newDelimiter;
- dX = 0;
- dY = 0;
- count = 0;
- }
- }
-
- // Vector from last delimiter to most recent point
- float currentDX = next.x - lastDelimiter.x;
- float currentDY = next.y - lastDelimiter.y;
- length = (float) Math.sqrt(currentDX * currentDX + currentDY * currentDY);
-
- // Increment sum of unit vectors from delimiter to each following point
- count = count + 1;
- dX = dX + currentDX / length;
- dY = dY + currentDY / length;
- }
-
- path.add(next);
- Slog.i(LOG_TAG, "path=" + path.toString());
-
- // Classify line segments, and call Listener callbacks.
- return recognizeGesturePath(event, policyFlags, path);
- }
-
- /**
- * Classifies a pair of line segments, by direction.
- * Calls Listener callbacks for success or failure.
- *
- * @param event The raw motion event to pass to the listener's onGestureCanceled method.
- * @param policyFlags Policy flags for the event.
- * @param path A sequence of motion line segments derived from motion points in mStrokeBuffer.
- *
- * @return true if the event is consumed, else false
- */
- private boolean recognizeGesturePath(MotionEvent event, int policyFlags,
- ArrayList<PointF> path) {
-
- final int displayId = event.getDisplayId();
- if (path.size() == 2) {
- PointF start = path.get(0);
- PointF end = path.get(1);
-
- float dX = end.x - start.x;
- float dY = end.y - start.y;
- int direction = toDirection(dX, dY);
- switch (direction) {
- case LEFT:
- return mListener.onGestureCompleted(
- new AccessibilityGestureEvent(AccessibilityService.GESTURE_SWIPE_LEFT,
- displayId));
- case RIGHT:
- return mListener.onGestureCompleted(
- new AccessibilityGestureEvent(AccessibilityService.GESTURE_SWIPE_RIGHT,
- displayId));
- case UP:
- return mListener.onGestureCompleted(
- new AccessibilityGestureEvent(AccessibilityService.GESTURE_SWIPE_UP,
- displayId));
- case DOWN:
- return mListener.onGestureCompleted(
- new AccessibilityGestureEvent(AccessibilityService.GESTURE_SWIPE_DOWN,
- displayId));
- default:
- // Do nothing.
- }
-
- } else if (path.size() == 3) {
- PointF start = path.get(0);
- PointF mid = path.get(1);
- PointF end = path.get(2);
-
- float dX0 = mid.x - start.x;
- float dY0 = mid.y - start.y;
-
- float dX1 = end.x - mid.x;
- float dY1 = end.y - mid.y;
-
- int segmentDirection0 = toDirection(dX0, dY0);
- int segmentDirection1 = toDirection(dX1, dY1);
- int gestureId = DIRECTIONS_TO_GESTURE_ID[segmentDirection0][segmentDirection1];
- return mListener.onGestureCompleted(
- new AccessibilityGestureEvent(gestureId, displayId));
- }
- // else if (path.size() < 2 || 3 < path.size()) then no gesture recognized.
- return mListener.onGestureCancelled(event, policyFlags);
- }
-
- /** Maps a vector to a dominant direction in set {LEFT, RIGHT, UP, DOWN}. */
- private static int toDirection(float dX, float dY) {
- if (Math.abs(dX) > Math.abs(dY)) {
- // Horizontal
- return (dX < 0) ? LEFT : RIGHT;
- } else {
- // Vertical
- return (dY < 0) ? UP : DOWN;
- }
- }
-
- private MotionEvent mapSecondPointerToFirstPointer(MotionEvent event) {
- // Only map basic events when two fingers are down.
- if (event.getPointerCount() != 2 ||
- (event.getActionMasked() != MotionEvent.ACTION_POINTER_DOWN &&
- event.getActionMasked() != MotionEvent.ACTION_POINTER_UP &&
- event.getActionMasked() != MotionEvent.ACTION_MOVE)) {
- return null;
- }
-
- int action = event.getActionMasked();
-
- if (action == MotionEvent.ACTION_POINTER_DOWN) {
- action = MotionEvent.ACTION_DOWN;
- } else if (action == MotionEvent.ACTION_POINTER_UP) {
- action = MotionEvent.ACTION_UP;
- }
-
- // Map the information from the second pointer to the first.
- return MotionEvent.obtain(mSecondPointerDownTime, event.getEventTime(), action,
- event.getX(1), event.getY(1), event.getPressure(1), event.getSize(1),
- event.getMetaState(), event.getXPrecision(), event.getYPrecision(),
- event.getDeviceId(), event.getEdgeFlags());
- }
-}
diff --git a/services/accessibility/java/com/android/server/accessibility/gestures/GestureManifold.java b/services/accessibility/java/com/android/server/accessibility/gestures/GestureManifold.java
new file mode 100644
index 000000000000..9b7adc883dee
--- /dev/null
+++ b/services/accessibility/java/com/android/server/accessibility/gestures/GestureManifold.java
@@ -0,0 +1,232 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.accessibility.gestures;
+
+import static android.accessibilityservice.AccessibilityService.GESTURE_DOUBLE_TAP;
+import static android.accessibilityservice.AccessibilityService.GESTURE_DOUBLE_TAP_AND_HOLD;
+import static android.accessibilityservice.AccessibilityService.GESTURE_SWIPE_DOWN;
+import static android.accessibilityservice.AccessibilityService.GESTURE_SWIPE_DOWN_AND_LEFT;
+import static android.accessibilityservice.AccessibilityService.GESTURE_SWIPE_DOWN_AND_RIGHT;
+import static android.accessibilityservice.AccessibilityService.GESTURE_SWIPE_DOWN_AND_UP;
+import static android.accessibilityservice.AccessibilityService.GESTURE_SWIPE_LEFT;
+import static android.accessibilityservice.AccessibilityService.GESTURE_SWIPE_LEFT_AND_DOWN;
+import static android.accessibilityservice.AccessibilityService.GESTURE_SWIPE_LEFT_AND_RIGHT;
+import static android.accessibilityservice.AccessibilityService.GESTURE_SWIPE_LEFT_AND_UP;
+import static android.accessibilityservice.AccessibilityService.GESTURE_SWIPE_RIGHT;
+import static android.accessibilityservice.AccessibilityService.GESTURE_SWIPE_RIGHT_AND_DOWN;
+import static android.accessibilityservice.AccessibilityService.GESTURE_SWIPE_RIGHT_AND_LEFT;
+import static android.accessibilityservice.AccessibilityService.GESTURE_SWIPE_RIGHT_AND_UP;
+import static android.accessibilityservice.AccessibilityService.GESTURE_SWIPE_UP;
+import static android.accessibilityservice.AccessibilityService.GESTURE_SWIPE_UP_AND_DOWN;
+import static android.accessibilityservice.AccessibilityService.GESTURE_SWIPE_UP_AND_LEFT;
+import static android.accessibilityservice.AccessibilityService.GESTURE_SWIPE_UP_AND_RIGHT;
+
+import static com.android.server.accessibility.gestures.Swipe.DOWN;
+import static com.android.server.accessibility.gestures.Swipe.LEFT;
+import static com.android.server.accessibility.gestures.Swipe.RIGHT;
+import static com.android.server.accessibility.gestures.Swipe.UP;
+import static com.android.server.accessibility.gestures.TouchExplorer.DEBUG;
+
+import android.accessibilityservice.AccessibilityGestureEvent;
+import android.content.Context;
+import android.os.Handler;
+import android.util.Slog;
+import android.view.MotionEvent;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * This class coordinates a series of individual gesture matchers to serve as a unified gesture
+ * detector. Gesture matchers are tied to a single gesture. It calls listener callback functions
+ * when a gesture starts or completes.
+ */
+class GestureManifold implements GestureMatcher.StateChangeListener {
+
+ private static final String LOG_TAG = "GestureManifold";
+
+ private final List<GestureMatcher> mGestures = new ArrayList<>();
+ private final Context mContext;
+ // Handler for performing asynchronous operations.
+ private final Handler mHandler;
+ // Listener to be notified of gesture start and end.
+ private Listener mListener;
+ // Shared state information.
+ private TouchState mState;
+
+ GestureManifold(Context context, Listener listener, TouchState state) {
+ mContext = context;
+ mHandler = new Handler(context.getMainLooper());
+ mListener = listener;
+ mState = state;
+ // Set up gestures.
+ // Start with double tap.
+ mGestures.add(new MultiTap(context, 2, GESTURE_DOUBLE_TAP, this));
+ mGestures.add(new MultiTapAndHold(context, 2, GESTURE_DOUBLE_TAP_AND_HOLD, this));
+ // One-direction swipes.
+ mGestures.add(new Swipe(context, RIGHT, GESTURE_SWIPE_RIGHT, this));
+ mGestures.add(new Swipe(context, LEFT, GESTURE_SWIPE_LEFT, this));
+ mGestures.add(new Swipe(context, UP, GESTURE_SWIPE_UP, this));
+ mGestures.add(new Swipe(context, DOWN, GESTURE_SWIPE_DOWN, this));
+ // Two-direction swipes.
+ mGestures.add(new Swipe(context, LEFT, RIGHT, GESTURE_SWIPE_LEFT_AND_RIGHT, this));
+ mGestures.add(new Swipe(context, LEFT, UP, GESTURE_SWIPE_LEFT_AND_UP, this));
+ mGestures.add(new Swipe(context, LEFT, DOWN, GESTURE_SWIPE_LEFT_AND_DOWN, this));
+ mGestures.add(new Swipe(context, RIGHT, UP, GESTURE_SWIPE_RIGHT_AND_UP, this));
+ mGestures.add(new Swipe(context, RIGHT, DOWN, GESTURE_SWIPE_RIGHT_AND_DOWN, this));
+ mGestures.add(new Swipe(context, RIGHT, LEFT, GESTURE_SWIPE_RIGHT_AND_LEFT, this));
+ mGestures.add(new Swipe(context, DOWN, UP, GESTURE_SWIPE_DOWN_AND_UP, this));
+ mGestures.add(new Swipe(context, DOWN, LEFT, GESTURE_SWIPE_DOWN_AND_LEFT, this));
+ mGestures.add(new Swipe(context, DOWN, RIGHT, GESTURE_SWIPE_DOWN_AND_RIGHT, this));
+ mGestures.add(new Swipe(context, UP, DOWN, GESTURE_SWIPE_UP_AND_DOWN, this));
+ mGestures.add(new Swipe(context, UP, LEFT, GESTURE_SWIPE_UP_AND_LEFT, this));
+ mGestures.add(new Swipe(context, UP, RIGHT, GESTURE_SWIPE_UP_AND_RIGHT, this));
+ }
+
+ /**
+ * Processes a motion event.
+ *
+ * @param event The event as received from the previous entry in the event stream.
+ * @param rawEvent The event without any transformations e.g. magnification.
+ * @param policyFlags
+ * @return True if the event has been appropriately handled by the gesture manifold and related
+ * callback functions, false if it should be handled further by the calling function.
+ */
+ boolean onMotionEvent(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ if (mState.isClear()) {
+ if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
+ // Sanity safeguard: if touch state is clear, then matchers should always be clear
+ // before processing the next down event.
+ clear();
+ } else {
+ // If for some reason other events come through while in the clear state they could
+ // compromise the state of particular matchers, so we just ignore them.
+ return false;
+ }
+ }
+ for (GestureMatcher matcher : mGestures) {
+ if (matcher.getState() != GestureMatcher.STATE_GESTURE_CANCELED) {
+ if (DEBUG) {
+ Slog.d(LOG_TAG, matcher.toString());
+ }
+ matcher.onMotionEvent(event, rawEvent, policyFlags);
+ if (DEBUG) {
+ Slog.d(LOG_TAG, matcher.toString());
+ }
+ if (matcher.getState() == GestureMatcher.STATE_GESTURE_COMPLETED) {
+ // Here we just clear and return. The actual gesture dispatch is done in
+ // onStateChanged().
+ clear();
+ // No need to process this event any further.
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public void clear() {
+ for (GestureMatcher matcher : mGestures) {
+ matcher.clear();
+ }
+ }
+
+ /**
+ * Listener that receives notifications of the state of the gesture detector. Listener functions
+ * are called as a result of onMotionEvent(). The current MotionEvent in the context of these
+ * functions is the event passed into onMotionEvent.
+ */
+ public interface Listener {
+ /**
+ * Called when the user has performed a double tap and then held down the second tap.
+ */
+ void onDoubleTapAndHold();
+
+ /**
+ * Called when the user lifts their finger on the second tap of a double tap.
+ * @return true if the event is consumed, else false
+ */
+ boolean onDoubleTap();
+
+ /**
+ * Called when the system has decided the event stream is a gesture.
+ *
+ * @return true if the event is consumed, else false
+ */
+ boolean onGestureStarted();
+
+ /**
+ * Called when an event stream is recognized as a gesture.
+ *
+ * @param gestureEvent Information about the gesture.
+ * @return true if the event is consumed, else false
+ */
+ boolean onGestureCompleted(AccessibilityGestureEvent gestureEvent);
+
+ /**
+ * Called when the system has decided an event stream doesn't match any known gesture.
+ *
+ * @param event The most recent MotionEvent received.
+ * @param policyFlags The policy flags of the most recent event.
+ * @return true if the event is consumed, else false
+ */
+ boolean onGestureCancelled(MotionEvent event, MotionEvent rawEvent, int policyFlags);
+ }
+
+ @Override
+ public void onStateChanged(
+ int gestureId, int state, MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ if (state == GestureMatcher.STATE_GESTURE_STARTED && !mState.isGestureDetecting()) {
+ mListener.onGestureStarted();
+ } else if (state == GestureMatcher.STATE_GESTURE_COMPLETED) {
+ onGestureCompleted(gestureId);
+ } else if (state == GestureMatcher.STATE_GESTURE_CANCELED && mState.isGestureDetecting()) {
+ // We only want to call the cancelation callback if there are no other pending
+ // detectors.
+ for (GestureMatcher matcher : mGestures) {
+ if (matcher.getState() == GestureMatcher.STATE_GESTURE_STARTED) {
+ return;
+ }
+ }
+ if (DEBUG) {
+ Slog.d(LOG_TAG, "Cancelling.");
+ }
+ mListener.onGestureCancelled(event, rawEvent, policyFlags);
+ }
+ }
+
+ private void onGestureCompleted(int gestureId) {
+ MotionEvent event = mState.getLastReceivedEvent();
+ // Note that gestures that complete immediately call clear() from onMotionEvent.
+ // Gestures that complete on a delay call clear() here.
+ switch (gestureId) {
+ case GESTURE_DOUBLE_TAP:
+ mListener.onDoubleTap();
+ clear();
+ break;
+ case GESTURE_DOUBLE_TAP_AND_HOLD:
+ mListener.onDoubleTapAndHold();
+ clear();
+ break;
+ default:
+ AccessibilityGestureEvent gestureEvent =
+ new AccessibilityGestureEvent(gestureId, event.getDisplayId());
+ mListener.onGestureCompleted(gestureEvent);
+ break;
+ }
+ }
+}
diff --git a/services/accessibility/java/com/android/server/accessibility/gestures/GestureMatcher.java b/services/accessibility/java/com/android/server/accessibility/gestures/GestureMatcher.java
new file mode 100644
index 000000000000..0b30ff57ddde
--- /dev/null
+++ b/services/accessibility/java/com/android/server/accessibility/gestures/GestureMatcher.java
@@ -0,0 +1,371 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.accessibility.gestures;
+
+import static com.android.server.accessibility.gestures.TouchExplorer.DEBUG;
+
+import android.annotation.IntDef;
+import android.os.Handler;
+import android.util.Slog;
+import android.view.MotionEvent;
+import android.view.ViewConfiguration;
+
+/**
+ * This class describes a common base for gesture matchers. A gesture matcher checks a series of
+ * motion events against a single gesture. Coordinating the individual gesture matchers is done by
+ * the GestureManifold. To create a new Gesture, extend this class and override the onDown, onMove,
+ * onUp, etc methods as necessary. If you don't override a method your matcher will do nothing in
+ * response to that type of event. Finally, be sure to give your gesture a name by overriding
+ * getGestureName().
+ */
+abstract class GestureMatcher {
+ // Potential states for this individual gesture matcher.
+ // In STATE_CLEAR, this matcher is accepting new motion events but has not formally signaled
+ // that there is enough data to judge that a gesture has started.
+ static final int STATE_CLEAR = 0;
+ // In STATE_GESTURE_STARTED, this matcher continues to accept motion events and it has signaled
+ // to the gesture manifold that what looks like the specified gesture has started.
+ static final int STATE_GESTURE_STARTED = 1;
+ // In STATE_GESTURE_COMPLETED, this matcher has successfully matched the specified gesture. and
+ // will not accept motion events until it is cleared.
+ static final int STATE_GESTURE_COMPLETED = 2;
+ // In STATE_GESTURE_CANCELED, this matcher will not accept new motion events because it is
+ // impossible that this set of motion events will match the specified gesture.
+ static final int STATE_GESTURE_CANCELED = 3;
+
+ @IntDef({STATE_CLEAR, STATE_GESTURE_STARTED, STATE_GESTURE_COMPLETED, STATE_GESTURE_CANCELED})
+ public @interface State {}
+
+ @State private int mState = STATE_CLEAR;
+ // The id number of the gesture that gets passed to accessibility services.
+ private final int mGestureId;
+ // handler for asynchronous operations like timeouts
+ private final Handler mHandler;
+
+ private final StateChangeListener mListener;
+
+ // Use this to transition to new states after a delay.
+ // e.g. cancel or complete after some timeout.
+ // Convenience functions for tapTimeout and doubleTapTimeout are already defined here.
+ protected final DelayedTransition mDelayedTransition;
+
+ GestureMatcher(int gestureId, Handler handler, StateChangeListener listener) {
+ mGestureId = gestureId;
+ mHandler = handler;
+ mDelayedTransition = new DelayedTransition();
+ mListener = listener;
+ }
+
+ /**
+ * Resets all state information for this matcher. Subclasses that include their own state
+ * information should override this method to reset their own state information and call
+ * super.clear().
+ */
+ protected void clear() {
+ mState = STATE_CLEAR;
+ cancelPendingTransitions();
+ }
+
+ public int getState() {
+ return mState;
+ }
+
+ /**
+ * Transitions to a new state and notifies any listeners. Note that any pending transitions are
+ * canceled.
+ */
+ private void setState(
+ @State int state, MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ mState = state;
+ cancelPendingTransitions();
+ mListener.onStateChanged(mGestureId, mState, event, rawEvent, policyFlags);
+ }
+
+ /** Indicates that there is evidence to suggest that this gesture has started. */
+ protected final void startGesture(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ setState(STATE_GESTURE_STARTED, event, rawEvent, policyFlags);
+ }
+
+ /** Indicates this stream of motion events can no longer match this gesture. */
+ protected final void cancelGesture(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ setState(STATE_GESTURE_CANCELED, event, rawEvent, policyFlags);
+ }
+
+ /** Indicates this gesture is completed. */
+ protected final void completeGesture(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ setState(STATE_GESTURE_COMPLETED, event, rawEvent, policyFlags);
+ }
+
+ public int getGestureId() {
+ return mGestureId;
+ }
+
+ /**
+ * Process a motion event and attempt to match it to this gesture.
+ *
+ * @param event the event as passed in from the event stream.
+ * @param rawEvent the original un-modified event. Useful for calculating movements in physical
+ * space.
+ * @param policyFlags the policy flags as passed in from the event stream.
+ * @return the state of this matcher.
+ */
+ public final int onMotionEvent(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ if (mState == STATE_GESTURE_CANCELED || mState == STATE_GESTURE_COMPLETED) {
+ return mState;
+ }
+ switch (event.getActionMasked()) {
+ case MotionEvent.ACTION_DOWN:
+ onDown(event, rawEvent, policyFlags);
+ break;
+ case MotionEvent.ACTION_POINTER_DOWN:
+ onPointerDown(event, rawEvent, policyFlags);
+ break;
+ case MotionEvent.ACTION_MOVE:
+ onMove(event, rawEvent, policyFlags);
+ break;
+ case MotionEvent.ACTION_POINTER_UP:
+ onPointerUp(event, rawEvent, policyFlags);
+ break;
+ case MotionEvent.ACTION_UP:
+ onUp(event, rawEvent, policyFlags);
+ break;
+ default:
+ // Cancel because of invalid event.
+ setState(STATE_GESTURE_CANCELED, event, rawEvent, policyFlags);
+ break;
+ }
+ return mState;
+ }
+
+ /**
+ * Matchers override this method to respond to ACTION_DOWN events. ACTION_DOWN events indicate
+ * the first finger has touched the screen. If not overridden the default response is to do
+ * nothing.
+ */
+ protected void onDown(MotionEvent event, MotionEvent rawEvent, int policyFlags) {}
+
+ /**
+ * Matchers override this method to respond to ACTION_POINTER_DOWN events. ACTION_POINTER_DOWN
+ * indicates that more than one finger has touched the screen. If not overridden the default
+ * response is to do nothing.
+ *
+ * @param event the event as passed in from the event stream.
+ * @param rawEvent the original un-modified event. Useful for calculating movements in physical
+ * space.
+ * @param policyFlags the policy flags as passed in from the event stream.
+ */
+ protected void onPointerDown(MotionEvent event, MotionEvent rawEvent, int policyFlags) {}
+
+ /**
+ * Matchers override this method to respond to ACTION_MOVE events. ACTION_MOVE indicates that
+ * one or fingers has moved. If not overridden the default response is to do nothing.
+ *
+ * @param event the event as passed in from the event stream.
+ * @param rawEvent the original un-modified event. Useful for calculating movements in physical
+ * space.
+ * @param policyFlags the policy flags as passed in from the event stream.
+ */
+ protected void onMove(MotionEvent event, MotionEvent rawEvent, int policyFlags) {}
+
+ /**
+ * Matchers override this method to respond to ACTION_POINTER_UP events. ACTION_POINTER_UP
+ * indicates that a finger has lifted from the screen but at least one finger continues to touch
+ * the screen. If not overridden the default response is to do nothing.
+ *
+ * @param event the event as passed in from the event stream.
+ * @param rawEvent the original un-modified event. Useful for calculating movements in physical
+ * space.
+ * @param policyFlags the policy flags as passed in from the event stream.
+ */
+ protected void onPointerUp(MotionEvent event, MotionEvent rawEvent, int policyFlags) {}
+
+ /**
+ * Matchers override this method to respond to ACTION_UP events. ACTION_UP indicates that there
+ * are no more fingers touching the screen. If not overridden the default response is to do
+ * nothing.
+ *
+ * @param event the event as passed in from the event stream.
+ * @param rawEvent the original un-modified event. Useful for calculating movements in physical
+ * space.
+ * @param policyFlags the policy flags as passed in from the event stream.
+ */
+ protected void onUp(MotionEvent event, MotionEvent rawEvent, int policyFlags) {}
+
+ /** Cancels this matcher after the tap timeout. Any pending state transitions are removed. */
+ protected void cancelAfterTapTimeout(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ cancelAfter(ViewConfiguration.getTapTimeout(), event, rawEvent, policyFlags);
+ }
+
+ /** Cancels this matcher after the double tap timeout. Any pending cancelations are removed. */
+ protected final void cancelAfterDoubleTapTimeout(
+ MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ cancelAfter(ViewConfiguration.getDoubleTapTimeout(), event, rawEvent, policyFlags);
+ }
+
+ /**
+ * Cancels this matcher after the specified timeout. Any pending cancelations are removed. Used
+ * to prevent this matcher from accepting motion events until it is cleared.
+ */
+ protected final void cancelAfter(
+ long timeout, MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ mDelayedTransition.cancel();
+ mDelayedTransition.post(STATE_GESTURE_CANCELED, timeout, event, rawEvent, policyFlags);
+ }
+
+ /** Cancels any delayed transitions between states scheduled for this matcher. */
+ protected final void cancelPendingTransitions() {
+ mDelayedTransition.cancel();
+ }
+
+ /**
+ * Signals that this gesture has been completed after the tap timeout has expired. Used to
+ * ensure that there is no conflict with another gesture or for gestures that explicitly require
+ * a hold.
+ */
+ protected final void completeAfterLongPressTimeout(
+ MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ completeAfter(ViewConfiguration.getLongPressTimeout(), event, rawEvent, policyFlags);
+ }
+
+ /**
+ * Signals that this gesture has been completed after the tap timeout has expired. Used to
+ * ensure that there is no conflict with another gesture or for gestures that explicitly require
+ * a hold.
+ */
+ protected final void completeAfterTapTimeout(
+ MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ completeAfter(ViewConfiguration.getTapTimeout(), event, rawEvent, policyFlags);
+ }
+
+ /**
+ * Signals that this gesture has been completed after the specified timeout has expired. Used to
+ * ensure that there is no conflict with another gesture or for gestures that explicitly require
+ * a hold.
+ */
+ protected final void completeAfter(
+ long timeout, MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ mDelayedTransition.cancel();
+ mDelayedTransition.post(STATE_GESTURE_COMPLETED, timeout, event, rawEvent, policyFlags);
+ }
+
+ /**
+ * Signals that this gesture has been completed after the double-tap timeout has expired. Used
+ * to ensure that there is no conflict with another gesture or for gestures that explicitly
+ * require a hold.
+ */
+ protected final void completeAfterDoubleTapTimeout(
+ MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ completeAfter(ViewConfiguration.getDoubleTapTimeout(), event, rawEvent, policyFlags);
+ }
+
+ public static String getStateSymbolicName(@State int state) {
+ switch (state) {
+ case STATE_CLEAR:
+ return "STATE_CLEAR";
+ case STATE_GESTURE_STARTED:
+ return "STATE_GESTURE_STARTED";
+ case STATE_GESTURE_COMPLETED:
+ return "STATE_GESTURE_COMPLETED";
+ case STATE_GESTURE_CANCELED:
+ return "STATE_GESTURE_CANCELED";
+ default:
+ return "Unknown state: " + state;
+ }
+ }
+
+ /**
+ * Returns a readable name for this matcher that can be displayed to the user and in system
+ * logs.
+ */
+ abstract String getGestureName();
+
+ /**
+ * Returns a String representation of this matcher. Each matcher can override this method to add
+ * extra state information to the string representation.
+ */
+ public String toString() {
+ return getGestureName() + ":" + getStateSymbolicName(mState);
+ }
+
+ /** This class allows matchers to transition between states on a delay. */
+ protected final class DelayedTransition implements Runnable {
+
+ private static final String LOG_TAG = "GestureMatcher.DelayedTransition";
+ int mTargetState;
+ MotionEvent mEvent;
+ MotionEvent mRawEvent;
+ int mPolicyFlags;
+
+ public void cancel() {
+ // Avoid meaningless debug messages.
+ if (DEBUG && isPending()) {
+ Slog.d(
+ LOG_TAG,
+ getGestureName()
+ + ": canceling delayed transition to "
+ + getStateSymbolicName(mTargetState));
+ }
+ mHandler.removeCallbacks(this);
+ }
+
+ public void post(
+ int state, long delay, MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ mTargetState = state;
+ mEvent = event;
+ mRawEvent = rawEvent;
+ mPolicyFlags = policyFlags;
+ mHandler.postDelayed(this, delay);
+ if (DEBUG) {
+ Slog.d(
+ LOG_TAG,
+ getGestureName()
+ + ": posting delayed transition to "
+ + getStateSymbolicName(mTargetState));
+ }
+ }
+
+ public boolean isPending() {
+ return mHandler.hasCallbacks(this);
+ }
+
+ public void forceSendAndRemove() {
+ if (isPending()) {
+ run();
+ cancel();
+ }
+ }
+
+ @Override
+ public void run() {
+ if (DEBUG) {
+ Slog.d(
+ LOG_TAG,
+ getGestureName()
+ + ": executing delayed transition to "
+ + getStateSymbolicName(mTargetState));
+ }
+ setState(mTargetState, mEvent, mRawEvent, mPolicyFlags);
+ }
+ }
+
+ /** Interface to allow a class to listen for state changes in a specific gesture matcher */
+ interface StateChangeListener {
+
+ void onStateChanged(
+ int gestureId, int state, MotionEvent event, MotionEvent rawEvent, int policyFlags);
+ }
+}
diff --git a/services/accessibility/java/com/android/server/accessibility/gestures/MultiTap.java b/services/accessibility/java/com/android/server/accessibility/gestures/MultiTap.java
new file mode 100644
index 000000000000..2891c6c294f5
--- /dev/null
+++ b/services/accessibility/java/com/android/server/accessibility/gestures/MultiTap.java
@@ -0,0 +1,145 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.accessibility.gestures;
+
+import android.content.Context;
+import android.os.Handler;
+import android.view.MotionEvent;
+import android.view.ViewConfiguration;
+
+/**
+ * This class matches multi-tap gestures. The number of taps for each instance is specified in the
+ * constructor.
+ */
+class MultiTap extends GestureMatcher {
+
+ // Maximum reasonable number of taps.
+ public static final int MAX_TAPS = 10;
+ final int mTargetTaps;
+ // The acceptable distance between two taps
+ int mDoubleTapSlop;
+ // The acceptable distance the pointer can move and still count as a tap.
+ int mTouchSlop;
+ int mTapTimeout;
+ int mDoubleTapTimeout;
+ int mCurrentTaps;
+ float mBaseX;
+ float mBaseY;
+
+ MultiTap(Context context, int taps, int gesture, GestureMatcher.StateChangeListener listener) {
+ super(gesture, new Handler(context.getMainLooper()), listener);
+ mTargetTaps = taps;
+ mDoubleTapSlop = ViewConfiguration.get(context).getScaledDoubleTapSlop();
+ mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
+ mTapTimeout = ViewConfiguration.getTapTimeout();
+ mDoubleTapTimeout = ViewConfiguration.getDoubleTapTimeout();
+ clear();
+ }
+
+ @Override
+ protected void clear() {
+ mCurrentTaps = 0;
+ mBaseX = Float.NaN;
+ mBaseY = Float.NaN;
+ super.clear();
+ }
+
+ @Override
+ protected void onDown(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ cancelAfterTapTimeout(event, rawEvent, policyFlags);
+ if (Float.isNaN(mBaseX) && Float.isNaN(mBaseY)) {
+ mBaseX = event.getX();
+ mBaseY = event.getY();
+ }
+ if (!isInsideSlop(rawEvent, mDoubleTapSlop)) {
+ cancelGesture(event, rawEvent, policyFlags);
+ }
+ mBaseX = event.getX();
+ mBaseY = event.getY();
+ }
+
+ @Override
+ protected void onUp(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ cancelAfterDoubleTapTimeout(event, rawEvent, policyFlags);
+ if (!isInsideSlop(rawEvent, mTouchSlop)) {
+ cancelGesture(event, rawEvent, policyFlags);
+ }
+ if (getState() == STATE_GESTURE_STARTED || getState() == STATE_CLEAR) {
+ mCurrentTaps++;
+ if (mCurrentTaps == mTargetTaps) {
+ // Done.
+ completeAfterTapTimeout(event, rawEvent, policyFlags);
+ return;
+ }
+ // Needs more taps.
+ cancelAfterDoubleTapTimeout(event, rawEvent, policyFlags);
+ } else {
+ // Either too many taps or nonsensical event stream.
+ cancelGesture(event, rawEvent, policyFlags);
+ }
+ }
+
+ @Override
+ protected void onMove(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ if (!isInsideSlop(rawEvent, mTouchSlop)) {
+ cancelGesture(event, rawEvent, policyFlags);
+ }
+ }
+
+ @Override
+ protected void onPointerDown(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ cancelGesture(event, rawEvent, policyFlags);
+ }
+
+ @Override
+ protected void onPointerUp(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ cancelGesture(event, rawEvent, policyFlags);
+ }
+
+ @Override
+ public String getGestureName() {
+ switch (mTargetTaps) {
+ case 2:
+ return "Double Tap";
+ case 3:
+ return "Triple Tap";
+ default:
+ return Integer.toString(mTargetTaps) + " Taps";
+ }
+ }
+
+ private boolean isInsideSlop(MotionEvent rawEvent, int slop) {
+ final float deltaX = mBaseX - rawEvent.getX();
+ final float deltaY = mBaseY - rawEvent.getY();
+ if (deltaX == 0 && deltaY == 0) {
+ return true;
+ }
+ final double moveDelta = Math.hypot(deltaX, deltaY);
+ return moveDelta <= slop;
+ }
+
+ @Override
+ public String toString() {
+ return super.toString()
+ + ", Taps:"
+ + mCurrentTaps
+ + ", mBaseX: "
+ + Float.toString(mBaseX)
+ + ", mBaseY: "
+ + Float.toString(mBaseY);
+ }
+}
diff --git a/services/accessibility/java/com/android/server/accessibility/gestures/MultiTapAndHold.java b/services/accessibility/java/com/android/server/accessibility/gestures/MultiTapAndHold.java
new file mode 100644
index 000000000000..6a1f1a546bc2
--- /dev/null
+++ b/services/accessibility/java/com/android/server/accessibility/gestures/MultiTapAndHold.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.accessibility.gestures;
+
+import android.content.Context;
+import android.view.MotionEvent;
+
+/**
+ * This class matches gestures of the form multi-tap and hold. The number of taps for each instance
+ * is specified in the constructor.
+ */
+class MultiTapAndHold extends MultiTap {
+ MultiTapAndHold(
+ Context context, int taps, int gesture, GestureMatcher.StateChangeListener listener) {
+ super(context, taps, gesture, listener);
+ }
+
+ @Override
+ protected void onDown(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ super.onDown(event, rawEvent, policyFlags);
+ if (mCurrentTaps + 1 == mTargetTaps) {
+ completeAfterLongPressTimeout(event, rawEvent, policyFlags);
+ }
+ }
+
+ @Override
+ public String getGestureName() {
+ switch (mTargetTaps) {
+ case 2:
+ return "Double Tap and Hold";
+ case 3:
+ return "Triple Tap and Hold";
+ default:
+ return Integer.toString(mTargetTaps) + " Taps and Hold";
+ }
+ }
+}
diff --git a/services/accessibility/java/com/android/server/accessibility/gestures/Swipe.java b/services/accessibility/java/com/android/server/accessibility/gestures/Swipe.java
new file mode 100644
index 000000000000..b246c67944c7
--- /dev/null
+++ b/services/accessibility/java/com/android/server/accessibility/gestures/Swipe.java
@@ -0,0 +1,430 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.accessibility.gestures;
+
+import static com.android.server.accessibility.gestures.TouchExplorer.DEBUG;
+
+import android.content.Context;
+import android.gesture.GesturePoint;
+import android.graphics.PointF;
+import android.os.Handler;
+import android.util.DisplayMetrics;
+import android.util.Slog;
+import android.util.TypedValue;
+import android.view.MotionEvent;
+
+import java.util.ArrayList;
+
+/**
+ * This class is responsible for matching one-finger swipe gestures. Each instance matches one swipe
+ * gesture. A swipe is specified as a series of one or more directions e.g. left, left and up, etc.
+ * At this time swipes with more than two directions are not supported.
+ */
+class Swipe extends GestureMatcher {
+
+ // Direction constants.
+ public static final int LEFT = 0;
+ public static final int RIGHT = 1;
+ public static final int UP = 2;
+ public static final int DOWN = 3;
+ // This is the calculated movement threshold used track if the user is still
+ // moving their finger.
+ private final float mGestureDetectionThreshold;
+
+ // Buffer for storing points for gesture detection.
+ private final ArrayList<GesturePoint> mStrokeBuffer = new ArrayList<GesturePoint>(100);
+
+ // The minimal delta between moves to add a gesture point.
+ private static final int TOUCH_TOLERANCE_PIX = 3;
+
+ // The minimal score for accepting a predicted gesture.
+ private static final float MIN_PREDICTION_SCORE = 2.0f;
+
+ // Distance a finger must travel before we decide if it is a gesture or not.
+ private static final int GESTURE_CONFIRM_CM = 1;
+
+ // Time threshold used to determine if an interaction is a gesture or not.
+ // If the first movement of 1cm takes longer than this value, we assume it's
+ // a slow movement, and therefore not a gesture.
+ //
+ // This value was determined by measuring the time for the first 1cm
+ // movement when gesturing, and touch exploring. Based on user testing,
+ // all gestures started with the initial movement taking less than 100ms.
+ // When touch exploring, the first movement almost always takes longer than
+ // 200ms.
+ private static final long CANCEL_ON_PAUSE_THRESHOLD_NOT_STARTED_MS = 150;
+
+ // Time threshold used to determine if a gesture should be cancelled. If
+ // the finger takes more than this time to move 1cm, the ongoing gesture is
+ // cancelled.
+ private static final long CANCEL_ON_PAUSE_THRESHOLD_STARTED_MS = 300;
+
+ private int[] mDirections;
+ private float mBaseX;
+ private float mBaseY;
+ private long mBaseTime;
+ private float mPreviousGestureX;
+ private float mPreviousGestureY;
+ // Constants for sampling motion event points.
+ // We sample based on a minimum distance between points, primarily to improve accuracy by
+ // reducing noisy minor changes in direction.
+ private static final float MIN_CM_BETWEEN_SAMPLES = 0.25f;
+ private final float mMinPixelsBetweenSamplesX;
+ private final float mMinPixelsBetweenSamplesY;
+
+ // Constants for separating gesture segments
+ private static final float ANGLE_THRESHOLD = 0.0f;
+
+ Swipe(
+ Context context,
+ int direction,
+ int gesture,
+ GestureMatcher.StateChangeListener listener) {
+ this(context, new int[] {direction}, gesture, listener);
+ }
+
+ Swipe(
+ Context context,
+ int direction1,
+ int direction2,
+ int gesture,
+ GestureMatcher.StateChangeListener listener) {
+ this(context, new int[] {direction1, direction2}, gesture, listener);
+ }
+
+ private Swipe(
+ Context context,
+ int[] directions,
+ int gesture,
+ GestureMatcher.StateChangeListener listener) {
+ super(gesture, new Handler(context.getMainLooper()), listener);
+ mDirections = directions;
+ DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
+ mGestureDetectionThreshold =
+ TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, 10, displayMetrics)
+ * GESTURE_CONFIRM_CM;
+ // Calculate minimum gesture velocity
+ final float pixelsPerCmX = displayMetrics.xdpi / 2.54f;
+ final float pixelsPerCmY = displayMetrics.ydpi / 2.54f;
+ mMinPixelsBetweenSamplesX = MIN_CM_BETWEEN_SAMPLES * pixelsPerCmX;
+ mMinPixelsBetweenSamplesY = MIN_CM_BETWEEN_SAMPLES * pixelsPerCmY;
+ clear();
+ }
+
+ @Override
+ protected void clear() {
+ mBaseX = Float.NaN;
+ mBaseY = Float.NaN;
+ mBaseTime = 0;
+ mStrokeBuffer.clear();
+ super.clear();
+ }
+
+ @Override
+ protected void onDown(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ cancelAfterDelay(event, rawEvent, policyFlags);
+ if (Float.isNaN(mBaseX) && Float.isNaN(mBaseY)) {
+ mBaseX = rawEvent.getX();
+ mBaseY = rawEvent.getY();
+ mBaseTime = event.getEventTime();
+ mPreviousGestureX = mBaseX;
+ mPreviousGestureY = mBaseY;
+ }
+ // Otherwise do nothing because this event doesn't make sense in the middle of a gesture.
+ }
+
+ @Override
+ protected void onMove(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ final float x = rawEvent.getX();
+ final float y = rawEvent.getY();
+ final long time = event.getEventTime();
+ final float dX = Math.abs(x - mPreviousGestureX);
+ final float dY = Math.abs(y - mPreviousGestureY);
+ final long timeDelta = time - mBaseTime;
+ final double moveDelta = Math.hypot(Math.abs(x - mBaseX), Math.abs(y - mBaseY));
+ if (DEBUG) {
+ Slog.d(
+ getGestureName(),
+ "moveDelta:"
+ + Double.toString(moveDelta)
+ + " mGestureDetectionThreshold: "
+ + Float.toString(mGestureDetectionThreshold));
+ }
+ if (getState() == STATE_CLEAR) {
+ if (mStrokeBuffer.size() == 0) {
+ // First, make sure the pointer is going in the right direction.
+ cancelAfterDelay(event, rawEvent, policyFlags);
+ int direction = toDirection(x - mBaseX, y - mBaseY);
+ if (direction != mDirections[0]) {
+ cancelGesture(event, rawEvent, policyFlags);
+ return;
+ } else {
+ // This is confirmed to be some kind of swipe so start tracking points.
+ mStrokeBuffer.add(new GesturePoint(mBaseX, mBaseY, mBaseTime));
+ }
+ }
+ if (moveDelta > mGestureDetectionThreshold) {
+ // If the pointer has moved more than the threshold,
+ // update the stored values.
+ mBaseX = x;
+ mBaseY = y;
+ mBaseTime = time;
+ if (getState() == STATE_CLEAR) {
+ startGesture(event, rawEvent, policyFlags);
+ cancelAfterDelay(event, rawEvent, policyFlags);
+ }
+ }
+ }
+ if (getState() == STATE_GESTURE_STARTED) {
+ if (dX >= mMinPixelsBetweenSamplesX || dY >= mMinPixelsBetweenSamplesY) {
+ mPreviousGestureX = x;
+ mPreviousGestureY = y;
+ mStrokeBuffer.add(new GesturePoint(x, y, time));
+ cancelAfterDelay(event, rawEvent, policyFlags);
+ }
+ }
+ }
+
+ @Override
+ protected void onUp(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ if (getState() != STATE_GESTURE_STARTED) {
+ cancelGesture(event, rawEvent, policyFlags);
+ return;
+ }
+
+ final float x = rawEvent.getX();
+ final float y = rawEvent.getY();
+ final long time = event.getEventTime();
+ final float dX = Math.abs(x - mPreviousGestureX);
+ final float dY = Math.abs(y - mPreviousGestureY);
+ if (dX >= mMinPixelsBetweenSamplesX || dY >= mMinPixelsBetweenSamplesY) {
+ mStrokeBuffer.add(new GesturePoint(x, y, time));
+ }
+ recognizeGesture(event, rawEvent, policyFlags);
+ }
+
+ @Override
+ protected void onPointerDown(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ cancelGesture(event, rawEvent, policyFlags);
+ }
+
+ @Override
+ protected void onPointerUp(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ cancelGesture(event, rawEvent, policyFlags);
+ }
+
+ /**
+ * queues a transition to STATE_GESTURE_CANCEL based on the current state. If we have
+ * transitioned to STATE_GESTURE_STARTED the delay is longer.
+ */
+ private void cancelAfterDelay(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ cancelPendingTransitions();
+ switch (getState()) {
+ case STATE_CLEAR:
+ cancelAfter(CANCEL_ON_PAUSE_THRESHOLD_NOT_STARTED_MS, event, rawEvent, policyFlags);
+ break;
+ case STATE_GESTURE_STARTED:
+ cancelAfter(CANCEL_ON_PAUSE_THRESHOLD_STARTED_MS, event, rawEvent, policyFlags);
+ break;
+ default:
+ break;
+ }
+ }
+
+ /**
+ * Looks at the sequence of motions in mStrokeBuffer, classifies the gesture, then calls
+ * Listener callbacks for success or failure.
+ *
+ * @param event The raw motion event to pass to the listener callbacks.
+ * @param policyFlags Policy flags for the event.
+ * @return true if the event is consumed, else false
+ */
+ private void recognizeGesture(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ if (mStrokeBuffer.size() < 2) {
+ cancelGesture(event, rawEvent, policyFlags);
+ return;
+ }
+
+ // Look at mStrokeBuffer and extract 2 line segments, delimited by near-perpendicular
+ // direction change.
+ // Method: for each sampled motion event, check the angle of the most recent motion vector
+ // versus the preceding motion vector, and segment the line if the angle is about
+ // 90 degrees.
+
+ ArrayList<PointF> path = new ArrayList<>();
+ PointF lastDelimiter = new PointF(mStrokeBuffer.get(0).x, mStrokeBuffer.get(0).y);
+ path.add(lastDelimiter);
+
+ float dX = 0; // Sum of unit vectors from last delimiter to each following point
+ float dY = 0;
+ int count = 0; // Number of points since last delimiter
+ float length = 0; // Vector length from delimiter to most recent point
+
+ PointF next = new PointF();
+ for (int i = 1; i < mStrokeBuffer.size(); ++i) {
+ next = new PointF(mStrokeBuffer.get(i).x, mStrokeBuffer.get(i).y);
+ if (count > 0) {
+ // Average of unit vectors from delimiter to following points
+ float currentDX = dX / count;
+ float currentDY = dY / count;
+
+ // newDelimiter is a possible new delimiter, based on a vector with length from
+ // the last delimiter to the previous point, but in the direction of the average
+ // unit vector from delimiter to previous points.
+ // Using the averaged vector has the effect of "squaring off the curve",
+ // creating a sharper angle between the last motion and the preceding motion from
+ // the delimiter. In turn, this sharper angle achieves the splitting threshold
+ // even in a gentle curve.
+ PointF newDelimiter =
+ new PointF(
+ length * currentDX + lastDelimiter.x,
+ length * currentDY + lastDelimiter.y);
+
+ // Unit vector from newDelimiter to the most recent point
+ float nextDX = next.x - newDelimiter.x;
+ float nextDY = next.y - newDelimiter.y;
+ float nextLength = (float) Math.sqrt(nextDX * nextDX + nextDY * nextDY);
+ nextDX = nextDX / nextLength;
+ nextDY = nextDY / nextLength;
+
+ // Compare the initial motion direction to the most recent motion direction,
+ // and segment the line if direction has changed by about 90 degrees.
+ float dot = currentDX * nextDX + currentDY * nextDY;
+ if (dot < ANGLE_THRESHOLD) {
+ path.add(newDelimiter);
+ lastDelimiter = newDelimiter;
+ dX = 0;
+ dY = 0;
+ count = 0;
+ }
+ }
+
+ // Vector from last delimiter to most recent point
+ float currentDX = next.x - lastDelimiter.x;
+ float currentDY = next.y - lastDelimiter.y;
+ length = (float) Math.sqrt(currentDX * currentDX + currentDY * currentDY);
+
+ // Increment sum of unit vectors from delimiter to each following point
+ count = count + 1;
+ dX = dX + currentDX / length;
+ dY = dY + currentDY / length;
+ }
+
+ path.add(next);
+ if (DEBUG) {
+ Slog.d(getGestureName(), "path=" + path.toString());
+ }
+ // Classify line segments, and call Listener callbacks.
+ recognizeGesturePath(event, rawEvent, policyFlags, path);
+ }
+
+ /**
+ * Classifies a pair of line segments, by direction. Calls Listener callbacks for success or
+ * failure.
+ *
+ * @param event The raw motion event to pass to the listener's onGestureCanceled method.
+ * @param policyFlags Policy flags for the event.
+ * @param path A sequence of motion line segments derived from motion points in mStrokeBuffer.
+ * @return true if the event is consumed, else false
+ */
+ private void recognizeGesturePath(
+ MotionEvent event, MotionEvent rawEvent, int policyFlags, ArrayList<PointF> path) {
+
+ final int displayId = event.getDisplayId();
+ if (path.size() != mDirections.length + 1) {
+ cancelGesture(event, rawEvent, policyFlags);
+ return;
+ }
+ for (int i = 0; i < path.size() - 1; ++i) {
+ PointF start = path.get(i);
+ PointF end = path.get(i + 1);
+
+ float dX = end.x - start.x;
+ float dY = end.y - start.y;
+ int direction = toDirection(dX, dY);
+ if (direction != mDirections[i]) {
+ if (DEBUG) {
+ Slog.d(
+ getGestureName(),
+ "Found direction "
+ + directionToString(direction)
+ + " when expecting "
+ + directionToString(mDirections[i]));
+ }
+ cancelGesture(event, rawEvent, policyFlags);
+ return;
+ }
+ }
+ if (DEBUG) {
+ Slog.d(getGestureName(), "Completed.");
+ }
+ completeGesture(event, rawEvent, policyFlags);
+ }
+
+ private static int toDirection(float dX, float dY) {
+ if (Math.abs(dX) > Math.abs(dY)) {
+ // Horizontal
+ return (dX < 0) ? LEFT : RIGHT;
+ } else {
+ // Vertical
+ return (dY < 0) ? UP : DOWN;
+ }
+ }
+
+ public static String directionToString(int direction) {
+ switch (direction) {
+ case LEFT:
+ return "left";
+ case RIGHT:
+ return "right";
+ case UP:
+ return "up";
+ case DOWN:
+ return "down";
+ default:
+ return "Unknown Direction";
+ }
+ }
+
+ @Override
+ String getGestureName() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("Swipe ").append(directionToString(mDirections[0]));
+ for (int i = 1; i < mDirections.length; ++i) {
+ builder.append(" and ").append(directionToString(mDirections[i]));
+ }
+ return builder.toString();
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder(super.toString());
+ if (getState() != STATE_GESTURE_CANCELED) {
+ builder.append(", mBaseX: ")
+ .append(mBaseX)
+ .append(", mBaseY: ")
+ .append(mBaseY)
+ .append(", mGestureDetectionThreshold:")
+ .append(mGestureDetectionThreshold)
+ .append(", mMinPixelsBetweenSamplesX:")
+ .append(mMinPixelsBetweenSamplesX)
+ .append(", mMinPixelsBetweenSamplesY:")
+ .append(mMinPixelsBetweenSamplesY);
+ }
+ return builder.toString();
+ }
+}
diff --git a/services/accessibility/java/com/android/server/accessibility/gestures/TouchExplorer.java b/services/accessibility/java/com/android/server/accessibility/gestures/TouchExplorer.java
index b62e260aacad..5f4163880366 100644
--- a/services/accessibility/java/com/android/server/accessibility/gestures/TouchExplorer.java
+++ b/services/accessibility/java/com/android/server/accessibility/gestures/TouchExplorer.java
@@ -59,7 +59,7 @@ import java.util.List;
* @hide
*/
public class TouchExplorer extends BaseEventStreamTransformation
- implements AccessibilityGestureDetector.Listener {
+ implements GestureManifold.Listener {
static final boolean DEBUG = false;
@@ -104,7 +104,7 @@ public class TouchExplorer extends BaseEventStreamTransformation
private final ExitGestureDetectionModeDelayed mExitGestureDetectionModeDelayed;
// Helper to detect gestures.
- private final AccessibilityGestureDetector mGestureDetector;
+ private final GestureManifold mGestureDetector;
// Helper class to track received pointers.
private final TouchState.ReceivedPointerTracker mReceivedPointerTracker;
@@ -142,7 +142,7 @@ public class TouchExplorer extends BaseEventStreamTransformation
* one created in place, or for testing purpose.
*/
public TouchExplorer(Context context, AccessibilityManagerService service,
- AccessibilityGestureDetector detector) {
+ GestureManifold detector) {
mContext = context;
mAms = service;
mState = new TouchState();
@@ -161,7 +161,7 @@ public class TouchExplorer extends BaseEventStreamTransformation
AccessibilityEvent.TYPE_TOUCH_INTERACTION_END,
mDetermineUserIntentTimeout);
if (detector == null) {
- mGestureDetector = new AccessibilityGestureDetector(context, this);
+ mGestureDetector = new GestureManifold(context, this, mState);
} else {
mGestureDetector = detector;
}
@@ -285,7 +285,7 @@ public class TouchExplorer extends BaseEventStreamTransformation
}
@Override
- public void onDoubleTapAndHold(MotionEvent event, int policyFlags) {
+ public void onDoubleTapAndHold() {
// Ignore the event if we aren't touch interacting.
if (!mState.isTouchInteracting()) {
return;
@@ -303,7 +303,7 @@ public class TouchExplorer extends BaseEventStreamTransformation
}
@Override
- public boolean onDoubleTap(MotionEvent event, int policyFlags) {
+ public boolean onDoubleTap() {
if (!mState.isTouchInteracting()) {
return false;
}
@@ -319,7 +319,7 @@ public class TouchExplorer extends BaseEventStreamTransformation
// Announce the end of a new touch interaction.
mDispatcher.sendAccessibilityEvent(AccessibilityEvent.TYPE_TOUCH_INTERACTION_END);
-
+ mSendTouchInteractionEndDelayed.cancel();
// Try to use the standard accessibility API to click
if (!mAms.performActionOnAccessibilityFocusedItem(
AccessibilityNodeInfo.AccessibilityAction.ACTION_CLICK)) {
@@ -356,7 +356,7 @@ public class TouchExplorer extends BaseEventStreamTransformation
}
@Override
- public boolean onGestureCancelled(MotionEvent event, int policyFlags) {
+ public boolean onGestureCancelled(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
if (mState.isGestureDetecting()) {
endGestureDetection(event.getActionMasked() == MotionEvent.ACTION_UP);
return true;
diff --git a/services/accessibility/java/com/android/server/accessibility/gestures/TouchState.java b/services/accessibility/java/com/android/server/accessibility/gestures/TouchState.java
index f463260a9d02..d23dbbefd325 100644
--- a/services/accessibility/java/com/android/server/accessibility/gestures/TouchState.java
+++ b/services/accessibility/java/com/android/server/accessibility/gestures/TouchState.java
@@ -71,7 +71,10 @@ public class TouchState {
// Helper class to track received pointers.
// Todo: collapse or hide this class so multiple classes don't modify it.
private final ReceivedPointerTracker mReceivedPointerTracker;
+ // The most recently received motion event.
private MotionEvent mLastReceivedEvent;
+ // The accompanying raw event without any transformations.
+ private MotionEvent mLastReceivedRawEvent;
public TouchState() {
mReceivedPointerTracker = new ReceivedPointerTracker();
@@ -97,6 +100,9 @@ public class TouchState {
if (mLastReceivedEvent != null) {
mLastReceivedEvent.recycle();
}
+ if (mLastReceivedRawEvent != null) {
+ mLastReceivedRawEvent.recycle();
+ }
mLastReceivedEvent = MotionEvent.obtain(rawEvent);
mReceivedPointerTracker.onMotionEvent(rawEvent);
}
@@ -246,7 +252,6 @@ public class TouchState {
// or if it goes up the next one that most recently went down.
private int mPrimaryPointerId;
-
ReceivedPointerTracker() {
clear();
}
diff --git a/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java b/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java
index d7ed2e9abde4..202f90068fc1 100644
--- a/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java
+++ b/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java
@@ -82,6 +82,7 @@ import com.android.server.autofill.AutofillManagerService.AutofillCompatState;
import com.android.server.autofill.RemoteAugmentedAutofillService.RemoteAugmentedAutofillServiceCallbacks;
import com.android.server.autofill.ui.AutoFillUI;
import com.android.server.infra.AbstractPerUserSystemService;
+import com.android.server.inputmethod.InputMethodManagerInternal;
import java.io.PrintWriter;
import java.util.ArrayList;
@@ -168,6 +169,8 @@ final class AutofillManagerServiceImpl
@Nullable
private ServiceInfo mRemoteAugmentedAutofillServiceInfo;
+ private final InputMethodManagerInternal mInputMethodManagerInternal;
+
AutofillManagerServiceImpl(AutofillManagerService master, Object lock,
LocalLog uiLatencyHistory, LocalLog wtfHistory, int userId, AutoFillUI ui,
AutofillCompatState autofillCompatState,
@@ -179,6 +182,7 @@ final class AutofillManagerServiceImpl
mUi = ui;
mFieldClassificationStrategy = new FieldClassificationStrategy(getContext(), userId);
mAutofillCompatState = autofillCompatState;
+ mInputMethodManagerInternal = LocalServices.getService(InputMethodManagerInternal.class);
updateLocked(disabled);
}
@@ -493,7 +497,7 @@ final class AutofillManagerServiceImpl
sessionId, taskId, uid, activityToken, appCallbackToken, hasCallback,
mUiLatencyHistory, mWtfHistory, serviceComponentName,
componentName, compatMode, bindInstantServiceAllowed, forAugmentedAutofillOnly,
- flags);
+ flags, mInputMethodManagerInternal);
mSessions.put(newSession.id, newSession);
return newSession;
diff --git a/services/autofill/java/com/android/server/autofill/Session.java b/services/autofill/java/com/android/server/autofill/Session.java
index 3b2da911a849..67bcccd1d7de 100644
--- a/services/autofill/java/com/android/server/autofill/Session.java
+++ b/services/autofill/java/com/android/server/autofill/Session.java
@@ -42,6 +42,8 @@ import android.app.IAssistDataReceiver;
import android.app.assist.AssistStructure;
import android.app.assist.AssistStructure.AutofillOverlay;
import android.app.assist.AssistStructure.ViewNode;
+import android.app.slice.Slice;
+import android.app.slice.SliceItem;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
@@ -80,6 +82,8 @@ import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.LocalLog;
+import android.util.Log;
+import android.util.Size;
import android.util.Slog;
import android.util.SparseArray;
import android.util.TimeUtils;
@@ -90,22 +94,38 @@ import android.view.autofill.AutofillManager.SmartSuggestionMode;
import android.view.autofill.AutofillValue;
import android.view.autofill.IAutoFillManagerClient;
import android.view.autofill.IAutofillWindowPresenter;
+import android.view.inline.InlinePresentationSpec;
+import android.view.inputmethod.InlineSuggestion;
+import android.view.inputmethod.InlineSuggestionInfo;
+import android.view.inputmethod.InlineSuggestionsRequest;
+import android.view.inputmethod.InlineSuggestionsResponse;
import com.android.internal.R;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.logging.MetricsLogger;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.internal.util.ArrayUtils;
+import com.android.internal.view.IInlineSuggestionsRequestCallback;
+import com.android.internal.view.IInlineSuggestionsResponseCallback;
+import com.android.internal.view.inline.IInlineContentCallback;
+import com.android.internal.view.inline.IInlineContentProvider;
import com.android.server.autofill.ui.AutoFillUI;
import com.android.server.autofill.ui.PendingUi;
+import com.android.server.inputmethod.InputMethodManagerInternal;
import java.io.PrintWriter;
+import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
/**
@@ -290,6 +310,23 @@ final class Session implements RemoteFillService.FillServiceCallbacks, ViewState
@GuardedBy("mLock")
private boolean mForAugmentedAutofillOnly;
+ @NonNull
+ private final InputMethodManagerInternal mInputMethodManagerInternal;
+
+ @GuardedBy("mLock")
+ @Nullable
+ private CompletableFuture<InlineSuggestionsRequest> mSuggestionsRequestFuture;
+
+ @GuardedBy("mLock")
+ @Nullable
+ private CompletableFuture<IInlineSuggestionsResponseCallback>
+ mInlineSuggestionsResponseCallbackFuture;
+
+ @Nullable
+ private InlineSuggestionsRequestCallback mInlineSuggestionsRequestCallback;
+
+ private static final int INLINE_REQUEST_TIMEOUT_MS = 1000;
+
/**
* Receiver of assist data from the app's {@link Activity}.
*/
@@ -386,7 +423,23 @@ final class Session implements RemoteFillService.FillServiceCallbacks, ViewState
final ArrayList<FillContext> contexts =
mergePreviousSessionLocked(/* forSave= */ false);
- request = new FillRequest(requestId, contexts, mClientState, flags);
+
+ InlineSuggestionsRequest suggestionsRequest = null;
+ if (mSuggestionsRequestFuture != null) {
+ try {
+ suggestionsRequest = mSuggestionsRequestFuture.get(
+ INLINE_REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+ } catch (TimeoutException e) {
+ Log.w(TAG, "Exception getting inline suggestions request in time: " + e);
+ } catch (CancellationException e) {
+ Log.w(TAG, "Inline suggestions request cancelled");
+ } catch (InterruptedException | ExecutionException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ request = new FillRequest(requestId, contexts, mClientState, flags,
+ suggestionsRequest);
}
mRemoteFillService.onFillRequest(request);
@@ -569,6 +622,70 @@ final class Session implements RemoteFillService.FillServiceCallbacks, ViewState
}
/**
+ * Returns whether inline suggestions are enabled for Autofill.
+ */
+ // TODO(b/137800469): Implement this
+ private boolean isInlineSuggestionsEnabled() {
+ return true;
+ }
+
+ /**
+ * Ask the IME to make an inline suggestions request if enabled.
+ */
+ private void maybeRequestInlineSuggestionsRequestThenFillLocked(@NonNull ViewState viewState,
+ int newState, int flags) {
+ if (isInlineSuggestionsEnabled()) {
+ mSuggestionsRequestFuture = new CompletableFuture<>();
+ mInlineSuggestionsResponseCallbackFuture = new CompletableFuture<>();
+
+ if (mInlineSuggestionsRequestCallback == null) {
+ mInlineSuggestionsRequestCallback = new InlineSuggestionsRequestCallback(this);
+ }
+
+ mInputMethodManagerInternal.onCreateInlineSuggestionsRequest(
+ mComponentName, mCurrentViewId, mInlineSuggestionsRequestCallback);
+ }
+
+ requestNewFillResponseLocked(viewState, newState, flags);
+ }
+
+ private static final class InlineSuggestionsRequestCallback
+ extends IInlineSuggestionsRequestCallback.Stub {
+ private final WeakReference<Session> mSession;
+
+ private InlineSuggestionsRequestCallback(Session session) {
+ mSession = new WeakReference<>(session);
+ }
+
+ @Override
+ public void onInlineSuggestionsUnsupported() throws RemoteException {
+ Log.i(TAG, "inline suggestions request unsupported, "
+ + "falling back to regular autofill");
+ final Session session = mSession.get();
+ if (session != null) {
+ synchronized (session.mLock) {
+ session.mSuggestionsRequestFuture.cancel(true);
+ session.mInlineSuggestionsResponseCallbackFuture.cancel(true);
+ }
+ }
+ }
+
+ @Override
+ public void onInlineSuggestionsRequest(InlineSuggestionsRequest request,
+ IInlineSuggestionsResponseCallback callback) throws RemoteException {
+ Log.i(TAG, "onInlineSuggestionsRequest() received: "
+ + request);
+ final Session session = mSession.get();
+ if (session != null) {
+ synchronized (session.mLock) {
+ session.mSuggestionsRequestFuture.complete(request);
+ session.mInlineSuggestionsResponseCallbackFuture.complete(callback);
+ }
+ }
+ }
+ }
+
+ /**
* Reads a new structure and then request a new fill response from the fill service.
*/
@GuardedBy("mLock")
@@ -584,6 +701,7 @@ final class Session implements RemoteFillService.FillServiceCallbacks, ViewState
triggerAugmentedAutofillLocked();
return;
}
+
viewState.setState(newState);
int requestId;
@@ -636,7 +754,8 @@ final class Session implements RemoteFillService.FillServiceCallbacks, ViewState
@NonNull IBinder client, boolean hasCallback, @NonNull LocalLog uiLatencyHistory,
@NonNull LocalLog wtfHistory, @Nullable ComponentName serviceComponentName,
@NonNull ComponentName componentName, boolean compatMode,
- boolean bindInstantServiceAllowed, boolean forAugmentedAutofillOnly, int flags) {
+ boolean bindInstantServiceAllowed, boolean forAugmentedAutofillOnly, int flags,
+ @NonNull InputMethodManagerInternal inputMethodManagerInternal) {
if (sessionId < 0) {
wtf(null, "Non-positive sessionId: %s", sessionId);
}
@@ -661,6 +780,8 @@ final class Session implements RemoteFillService.FillServiceCallbacks, ViewState
mForAugmentedAutofillOnly = forAugmentedAutofillOnly;
setClientLocked(client);
+ mInputMethodManagerInternal = inputMethodManagerInternal;
+
mMetricsLogger.write(newLogMaker(MetricsEvent.AUTOFILL_SESSION_STARTED)
.addTaggedData(MetricsEvent.FIELD_AUTOFILL_FLAGS, flags));
}
@@ -2208,7 +2329,8 @@ final class Session implements RemoteFillService.FillServiceCallbacks, ViewState
if ((flags & FLAG_MANUAL_REQUEST) != 0) {
mForAugmentedAutofillOnly = false;
if (sDebug) Slog.d(TAG, "Re-starting session on view " + id + " and flags " + flags);
- requestNewFillResponseLocked(viewState, ViewState.STATE_RESTARTED_SESSION, flags);
+ maybeRequestInlineSuggestionsRequestThenFillLocked(viewState,
+ ViewState.STATE_RESTARTED_SESSION, flags);
return;
}
@@ -2218,7 +2340,8 @@ final class Session implements RemoteFillService.FillServiceCallbacks, ViewState
Slog.d(TAG, "Starting partition or augmented request for view id " + id + ": "
+ viewState.getStateAsString());
}
- requestNewFillResponseLocked(viewState, ViewState.STATE_STARTED_PARTITION, flags);
+ maybeRequestInlineSuggestionsRequestThenFillLocked(viewState,
+ ViewState.STATE_STARTED_PARTITION, flags);
} else {
if (sVerbose) {
Slog.v(TAG, "Not starting new partition for view " + id + ": "
@@ -2325,7 +2448,8 @@ final class Session implements RemoteFillService.FillServiceCallbacks, ViewState
// View is triggering autofill.
mCurrentViewId = viewState.id;
viewState.update(value, virtualBounds, flags);
- requestNewFillResponseLocked(viewState, ViewState.STATE_STARTED_SESSION, flags);
+ maybeRequestInlineSuggestionsRequestThenFillLocked(viewState,
+ ViewState.STATE_STARTED_SESSION, flags);
break;
case ACTION_VALUE_CHANGED:
if (mCompatMode && (viewState.getState() & ViewState.STATE_URL_BAR) != 0) {
@@ -2527,6 +2651,16 @@ final class Session implements RemoteFillService.FillServiceCallbacks, ViewState
wtf(null, "onFillReady(): no service label or icon");
return;
}
+
+ final List<Slice> inlineSuggestionSlices = response.getInlineSuggestionSlices();
+ if (inlineSuggestionSlices != null) {
+ if (requestShowInlineSuggestions(inlineSuggestionSlices, response)) {
+ //TODO(b/137800469): Add logging instead of bypassing below logic.
+ return;
+ }
+ }
+
+
getUiForShowing().showFillUi(filledId, response, filterText,
mService.getServicePackageName(), mComponentName,
serviceLabel, serviceIcon, this, id, mCompatMode);
@@ -2558,6 +2692,109 @@ final class Session implements RemoteFillService.FillServiceCallbacks, ViewState
}
}
+ /**
+ * Returns whether we made a request to show inline suggestions.
+ */
+ private boolean requestShowInlineSuggestions(List<Slice> inlineSuggestionSlices,
+ FillResponse response) {
+ IInlineSuggestionsResponseCallback inlineContentCallback = null;
+ synchronized (mLock) {
+ if (mInlineSuggestionsResponseCallbackFuture != null) {
+ try {
+ inlineContentCallback = mInlineSuggestionsResponseCallbackFuture.get(
+ INLINE_REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+ } catch (TimeoutException e) {
+ Log.w(TAG, "Exception getting inline suggestions callback in time: " + e);
+ } catch (CancellationException e) {
+ Log.w(TAG, "Inline suggestions callback cancelled");
+ } catch (InterruptedException | ExecutionException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ if (inlineContentCallback == null) {
+ Log.w(TAG, "Session input method callback is not set yet");
+ return false;
+ }
+
+ final List<Dataset> datasets = response.getDatasets();
+ if (datasets == null) {
+ Log.w(TAG, "response returned null datasets");
+ return false;
+ }
+
+ final ArrayList<InlineSuggestion> inlineSuggestions = new ArrayList<>();
+ final int slicesSize = inlineSuggestionSlices.size();
+ if (datasets.size() < slicesSize) {
+ Log.w(TAG, "Too many slices provided, not enough corresponding datasets");
+ return false;
+ }
+
+ for (int sliceIndex = 0; sliceIndex < slicesSize; sliceIndex++) {
+ Log.i(TAG, "Reading slice-" + sliceIndex + " at requestshowinlinesuggestions");
+ final Slice inlineSuggestionSlice = inlineSuggestionSlices.get(sliceIndex);
+ final List<SliceItem> sliceItems = inlineSuggestionSlice.getItems();
+
+ final int itemsSize = sliceItems.size();
+ int minWidth = -1;
+ int maxWidth = -1;
+ int minHeight = -1;
+ int maxHeight = -1;
+ for (int itemIndex = 0; itemIndex < itemsSize; itemIndex++) {
+ final SliceItem item = sliceItems.get(itemIndex);
+ final String subtype = item.getSubType();
+ switch (item.getSubType()) {
+ case "SUBTYPE_MIN_WIDTH":
+ minWidth = item.getInt();
+ break;
+ case "SUBTYPE_MAX_WIDTH":
+ maxWidth = item.getInt();
+ break;
+ case "SUBTYPE_MIN_HEIGHT":
+ minHeight = item.getInt();
+ break;
+ case "SUBTYPE_MAX_HEIGHT":
+ maxHeight = item.getInt();
+ break;
+ default:
+ Log.i(TAG, "unrecognized inline suggestions subtype: " + subtype);
+ }
+ }
+
+ if (minWidth < 0 || maxWidth < 0 || minHeight < 0 || maxHeight < 0) {
+ Log.w(TAG, "missing inline suggestion requirements");
+ return false;
+ }
+
+ final InlinePresentationSpec spec = new InlinePresentationSpec.Builder(
+ new Size(minWidth, minHeight), new Size(maxWidth, maxHeight)).build();
+ final InlineSuggestionInfo inlineSuggestionInfo = new InlineSuggestionInfo(
+ spec, InlineSuggestionInfo.SOURCE_AUTOFILL, new String[] { "" });
+ final Dataset dataset = datasets.get(sliceIndex);
+
+ inlineSuggestions.add(new InlineSuggestion(inlineSuggestionInfo,
+ new IInlineContentProvider.Stub() {
+ @Override
+ public void provideContent(int width, int height,
+ IInlineContentCallback callback) throws RemoteException {
+ getUiForShowing().getSuggestionSurfaceForShowing(dataset, response,
+ mCurrentViewId, width, height, callback);
+ }
+ }));
+ }
+
+ try {
+ inlineContentCallback.onInlineSuggestionsResponse(
+ new InlineSuggestionsResponse(inlineSuggestions));
+ } catch (RemoteException e) {
+ Log.w(TAG, "onFillReady() remote error calling onInlineSuggestionsResponse()");
+ return false;
+ }
+
+ return true;
+ }
+
boolean isDestroyed() {
synchronized (mLock) {
return mDestroyed;
@@ -2831,6 +3068,7 @@ final class Session implements RemoteFillService.FillServiceCallbacks, ViewState
final AutofillId focusedId = AutofillId.withoutSession(mCurrentViewId);
+ // TODO(b/137800469): implement inlined suggestions for augmented autofill
remoteService.onRequestAutofillLocked(id, mClient, taskId, mComponentName, focusedId,
currentValue);
diff --git a/services/autofill/java/com/android/server/autofill/ui/AutoFillUI.java b/services/autofill/java/com/android/server/autofill/ui/AutoFillUI.java
index 7e8edf212bdd..eadfd31c27bf 100644
--- a/services/autofill/java/com/android/server/autofill/ui/AutoFillUI.java
+++ b/services/autofill/java/com/android/server/autofill/ui/AutoFillUI.java
@@ -24,6 +24,8 @@ import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
+import android.graphics.Color;
+import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.metrics.LogMaker;
import android.os.Bundle;
@@ -37,13 +39,19 @@ import android.service.autofill.ValueFinder;
import android.text.TextUtils;
import android.util.Slog;
import android.view.KeyEvent;
+import android.view.SurfaceControl;
+import android.view.WindowManager;
+import android.view.WindowlessViewRoot;
import android.view.autofill.AutofillId;
import android.view.autofill.AutofillManager;
+import android.view.autofill.AutofillValue;
import android.view.autofill.IAutofillWindowPresenter;
+import android.widget.TextView;
import android.widget.Toast;
import com.android.internal.logging.MetricsLogger;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
+import com.android.internal.view.inline.IInlineContentCallback;
import com.android.server.LocalServices;
import com.android.server.UiModeManagerInternal;
import com.android.server.UiThread;
@@ -171,6 +179,75 @@ public final class AutoFillUI {
}
/**
+ * TODO(b/137800469): Fill in javadoc.
+ * TODO(b/137800469): peoperly manage lifecycle of suggestions surfaces.
+ */
+ public void getSuggestionSurfaceForShowing(@NonNull Dataset dataset,
+ @NonNull FillResponse response, AutofillId autofillId, int width, int height,
+ IInlineContentCallback cb) {
+ if (dataset == null) {
+ Slog.w(TAG, "getSuggestionSurfaceForShowing() called with null dataset");
+ }
+ mHandler.post(() -> {
+ final SurfaceControl suggestionSurface = inflateInlineSuggestion(dataset, response,
+ autofillId, width, height);
+
+ try {
+ cb.onContent(suggestionSurface);
+ } catch (RemoteException e) {
+ Slog.w(TAG, "RemoteException replying onContent(" + suggestionSurface + "): " + e);
+ }
+ });
+ }
+
+ /**
+ * TODO(b/137800469): Fill in javadoc, generate custom templated view for inline suggestions.
+ * TODO: Move to ExtServices.
+ *
+ * @return a {@link SurfaceControl} with the inflated content embedded in it.
+ */
+ private SurfaceControl inflateInlineSuggestion(@NonNull Dataset dataset,
+ @NonNull FillResponse response, AutofillId autofillId, int width, int height) {
+ Slog.i(TAG, "inflate() called");
+ final Context context = mContext;
+ final int index = dataset.getFieldIds().indexOf(autofillId);
+ if (index < 0) {
+ Slog.w(TAG, "inflateInlineSuggestion(): AutofillId=" + autofillId
+ + " not found in dataset");
+ }
+
+ final AutofillValue datasetValue = dataset.getFieldValues().get(index);
+ final SurfaceControl sc = new SurfaceControl.Builder()
+ // TODO(b/137800469): sanitize name
+ .setName("af suggestion")
+ .build();
+
+ //TODO(b/137800469): Pass in inputToken from IME.
+ final WindowlessViewRoot wvr = new WindowlessViewRoot(context, context.getDisplay(), sc,
+ null);
+
+ TextView textView = new TextView(context);
+ textView.setText(datasetValue.getTextValue());
+ textView.setBackgroundColor(Color.WHITE);
+ textView.setTextColor(Color.BLACK);
+ textView.setOnClickListener(v -> {
+ Slog.d(TAG, "Inline suggestion clicked");
+ hideFillUiUiThread(mCallback, true);
+ if (mCallback != null) {
+ final int datasetIndex = response.getDatasets().indexOf(dataset);
+ mCallback.fill(response.getRequestId(), datasetIndex, dataset);
+ }
+ });
+
+ WindowManager.LayoutParams lp =
+ new WindowManager.LayoutParams(width, height,
+ WindowManager.LayoutParams.TYPE_APPLICATION, 0, PixelFormat.OPAQUE);
+ wvr.addView(textView, lp);
+
+ return sc;
+ }
+
+ /**
* Shows the fill UI, removing the previous fill UI if the has changed.
*
* @param focusedId the currently focused field
@@ -465,7 +542,7 @@ public final class AutoFillUI {
if (mCreateFillUiRunnable != null) {
if (sDebug) Slog.d(TAG, "start the pending fill UI request..");
- mCreateFillUiRunnable.run();
+ mHandler.post(mCreateFillUiRunnable);
mCreateFillUiRunnable = null;
}
}
diff --git a/services/backup/java/com/android/server/backup/BackupManagerService.java b/services/backup/java/com/android/server/backup/BackupManagerService.java
index e8c5299f47a3..3651a4143953 100644
--- a/services/backup/java/com/android/server/backup/BackupManagerService.java
+++ b/services/backup/java/com/android/server/backup/BackupManagerService.java
@@ -274,9 +274,14 @@ public class BackupManagerService extends IBackupManager.Stub {
}
}
- // This method should not perform any I/O (e.g. do not call isBackupActivatedForUser),
- // it's used in multiple places where I/O waits would cause system lock-ups.
- private boolean isUserReadyForBackup(int userId) {
+ /**
+ * This method should not perform any I/O (e.g. do not call isBackupActivatedForUser),
+ * it's used in multiple places where I/O waits would cause system lock-ups.
+ * @param userId User id for which this operation should be performed.
+ * @return true if the user is ready for backup and false otherwise.
+ */
+ @Override
+ public boolean isUserReadyForBackup(int userId) {
return mUserServices.get(UserHandle.USER_SYSTEM) != null
&& mUserServices.get(userId) != null;
}
diff --git a/services/backup/java/com/android/server/backup/restore/PerformUnifiedRestoreTask.java b/services/backup/java/com/android/server/backup/restore/PerformUnifiedRestoreTask.java
index be597d7b40d6..de6a080f1330 100644
--- a/services/backup/java/com/android/server/backup/restore/PerformUnifiedRestoreTask.java
+++ b/services/backup/java/com/android/server/backup/restore/PerformUnifiedRestoreTask.java
@@ -766,8 +766,10 @@ public class PerformUnifiedRestoreTask implements BackupRestoreTask {
backupManagerService.prepareOperationTimeout(
mEphemeralOpToken, restoreAgentTimeoutMillis, this, OP_TYPE_RESTORE_WAIT);
startedAgentRestore = true;
- mAgent.doRestore(mBackupData, appVersionCode, mNewState,
- mEphemeralOpToken, backupManagerService.getBackupManagerBinder());
+ mAgent.doRestoreWithExcludedKeys(mBackupData, appVersionCode, mNewState,
+ mEphemeralOpToken, backupManagerService.getBackupManagerBinder(),
+ mExcludedKeys.containsKey(packageName)
+ ? new ArrayList<>(mExcludedKeys.get(packageName)) : null);
} catch (Exception e) {
Slog.e(TAG, "Unable to call app for restore: " + packageName, e);
EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
diff --git a/services/core/Android.bp b/services/core/Android.bp
index 203bc61c2022..b7adfa4a3ff1 100644
--- a/services/core/Android.bp
+++ b/services/core/Android.bp
@@ -116,6 +116,7 @@ java_library_static {
"android.hardware.oemlock-V1.0-java",
"android.hardware.configstore-V1.0-java",
"android.hardware.contexthub-V1.0-java",
+ "android.hardware.soundtrigger-V2.3-java",
"android.hidl.manager-V1.2-java",
"dnsresolver_aidl_interface-V2-java",
"netd_event_listener_interface-java",
diff --git a/services/core/java/android/content/pm/PackageManagerInternal.java b/services/core/java/android/content/pm/PackageManagerInternal.java
index 21f5f899e75c..d2f1113ec5a9 100644
--- a/services/core/java/android/content/pm/PackageManagerInternal.java
+++ b/services/core/java/android/content/pm/PackageManagerInternal.java
@@ -133,6 +133,12 @@ public abstract class PackageManagerInternal {
@PackageInfoFlags int flags, int filterCallingUid, int userId);
/**
+ * Retrieve CE data directory inode number of an application.
+ * Return 0 if there's error.
+ */
+ public abstract long getCeDataInode(String packageName, int userId);
+
+ /**
* Return a List of all application packages that are installed on the
* device, for a specific user. If flag GET_UNINSTALLED_PACKAGES has been
* set, a list of all applications including those deleted with
@@ -275,6 +281,11 @@ public abstract class PackageManagerInternal {
public abstract ComponentName getDefaultHomeActivity(int userId);
/**
+ * @return The SystemUI service component name.
+ */
+ public abstract ComponentName getSystemUiServiceComponent();
+
+ /**
* Called by DeviceOwnerManagerService to set the package names of device owner and profile
* owners.
*/
@@ -336,14 +347,16 @@ public abstract class PackageManagerInternal {
* @param responseObj The response of the first phase of ephemeral resolution
* @param origIntent The original intent that triggered ephemeral resolution
* @param resolvedType The resolved type of the intent
- * @param callingPackage The name of the package requesting the ephemeral application
+ * @param callingPkg The app requesting the ephemeral application
+ * @param isRequesterInstantApp Whether or not the app requesting the ephemeral application
+ * is an instant app
* @param verificationBundle Optional bundle to pass to the installer for additional
* verification
* @param userId The ID of the user that triggered ephemeral resolution
*/
public abstract void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
- Intent origIntent, String resolvedType, String callingPackage,
- Bundle verificationBundle, int userId);
+ Intent origIntent, String resolvedType, String callingPkg,
+ boolean isRequesterInstantApp, Bundle verificationBundle, int userId);
/**
* Grants implicit access based on an interaction between two apps. This grants the target app
@@ -822,4 +835,19 @@ public abstract class PackageManagerInternal {
/** Sets the enforcement of reading external storage */
public abstract void setReadExternalStorageEnforced(boolean enforced);
+
+ /**
+ * Allows the integrity component to respond to the
+ * {@link Intent#ACTION_PACKAGE_NEEDS_INTEGRITY_VERIFICATION package verification
+ * broadcast} to respond to the package manager. The response must include
+ * the {@code verificationCode} which is one of
+ * {@link PackageManager#VERIFICATION_ALLOW} or
+ * {@link PackageManager#VERIFICATION_REJECT}.
+ *
+ * @param verificationId pending package identifier as passed via the
+ * {@link PackageManager#EXTRA_VERIFICATION_ID} Intent extra.
+ * @param verificationResult either {@link PackageManager#VERIFICATION_ALLOW}
+ * or {@link PackageManager#VERIFICATION_REJECT}.
+ */
+ public abstract void setIntegrityVerificationResult(int verificationId, int verificationResult);
}
diff --git a/services/core/java/android/os/UserManagerInternal.java b/services/core/java/android/os/UserManagerInternal.java
index a2e9341bae71..d84197c749b6 100644
--- a/services/core/java/android/os/UserManagerInternal.java
+++ b/services/core/java/android/os/UserManagerInternal.java
@@ -57,7 +57,7 @@ public abstract class UserManagerInternal {
* Called by {@link com.android.server.devicepolicy.DevicePolicyManagerService} to set
* restrictions enforced by the user.
*
- * @param userId target user id for the local restrictions.
+ * @param originatingUserId user id of the user where the restriction originated.
* @param restrictions a bundle of user restrictions.
* @param restrictionOwnerType determines which admin {@code userId} corresponds to.
* The admin can be either
@@ -70,8 +70,8 @@ public abstract class UserManagerInternal {
* otherwise it will be applied just on the current user.
* @see OwnerType
*/
- public abstract void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
- @OwnerType int restrictionOwnerType);
+ public abstract void setDevicePolicyUserRestrictions(int originatingUserId,
+ @Nullable Bundle restrictions, @OwnerType int restrictionOwnerType);
/**
* Returns the "base" user restrictions.
diff --git a/services/core/java/com/android/server/AlarmManagerService.java b/services/core/java/com/android/server/AlarmManagerService.java
index 1e5b91502029..73b6c7a570ed 100644
--- a/services/core/java/com/android/server/AlarmManagerService.java
+++ b/services/core/java/com/android/server/AlarmManagerService.java
@@ -22,6 +22,8 @@ import static android.app.AlarmManager.FLAG_ALLOW_WHILE_IDLE;
import static android.app.AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
import static android.app.AlarmManager.RTC;
import static android.app.AlarmManager.RTC_WAKEUP;
+import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
+import static android.os.UserHandle.USER_SYSTEM;
import android.annotation.UserIdInt;
import android.app.Activity;
@@ -41,10 +43,7 @@ import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.content.pm.PermissionInfo;
+import android.content.pm.PackageManagerInternal;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.BatteryManager;
@@ -223,15 +222,6 @@ class AlarmManagerService extends SystemService {
long mLastTimeChangeRealtime;
int mNumTimeChanged;
- // Bookkeeping about the identity of the "System UI" package, determined at runtime.
-
- /**
- * This permission must be defined by the canonical System UI package,
- * with protection level "signature".
- */
- private static final String SYSTEM_UI_SELF_PERMISSION =
- "android.permission.systemui.IDENTITY";
-
/**
* At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
*/
@@ -3201,7 +3191,7 @@ class AlarmManagerService extends SystemService {
}
void removeUserLocked(int userHandle) {
- if (userHandle == UserHandle.USER_SYSTEM) {
+ if (userHandle == USER_SYSTEM) {
// If we're told we're removing the system user, ignore it.
return;
}
@@ -3845,21 +3835,9 @@ class AlarmManagerService extends SystemService {
}
int getSystemUiUid() {
- int sysUiUid = -1;
- final PackageManager pm = mContext.getPackageManager();
- try {
- PermissionInfo sysUiPerm = pm.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
- ApplicationInfo sysUi = pm.getApplicationInfo(sysUiPerm.packageName, 0);
- if ((sysUi.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
- sysUiUid = sysUi.uid;
- } else {
- Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
- + " defined by non-privileged app " + sysUi.packageName
- + " - ignoring");
- }
- } catch (NameNotFoundException e) {
- }
- return sysUiUid;
+ PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
+ return pm.getPackageUid(pm.getSystemUiServiceComponent().getPackageName(),
+ MATCH_SYSTEM_ONLY, USER_SYSTEM);
}
ClockReceiver getClockReceiver(AlarmManagerService service) {
diff --git a/services/core/java/com/android/server/BluetoothManagerService.java b/services/core/java/com/android/server/BluetoothManagerService.java
index 119b987f7ae7..470300e6485c 100644
--- a/services/core/java/com/android/server/BluetoothManagerService.java
+++ b/services/core/java/com/android/server/BluetoothManagerService.java
@@ -16,6 +16,9 @@
package com.android.server;
+import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
+import static android.os.UserHandle.USER_SYSTEM;
+
import android.Manifest;
import android.app.ActivityManager;
import android.app.AppGlobals;
@@ -42,6 +45,7 @@ import android.content.ServiceConnection;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageManager;
import android.content.pm.PackageManager;
+import android.content.pm.PackageManagerInternal;
import android.content.pm.UserInfo;
import android.database.ContentObserver;
import android.os.Binder;
@@ -242,10 +246,10 @@ class BluetoothManagerService extends IBluetoothManager.Stub {
}
// DISALLOW_BLUETOOTH can only be set by DO or PO on the system user.
- if (userId == UserHandle.USER_SYSTEM
+ if (userId == USER_SYSTEM
&& UserRestrictionsUtils.restrictionsChanged(prevRestrictions,
newRestrictions, UserManager.DISALLOW_BLUETOOTH)) {
- if (userId == UserHandle.USER_SYSTEM && newRestrictions.getBoolean(
+ if (userId == USER_SYSTEM && newRestrictions.getBoolean(
UserManager.DISALLOW_BLUETOOTH)) {
updateOppLauncherComponentState(userId, true); // Sharing disallowed
sendDisableMsg(BluetoothProtoEnums.ENABLE_DISABLE_REASON_DISALLOWED,
@@ -437,18 +441,18 @@ class BluetoothManagerService extends IBluetoothManager.Stub {
}
int systemUiUid = -1;
- try {
- // Check if device is configured with no home screen, which implies no SystemUI.
- boolean noHome = mContext.getResources().getBoolean(R.bool.config_noHomeScreen);
- if (!noHome) {
- systemUiUid = mContext.getPackageManager()
- .getPackageUidAsUser("com.android.systemui", PackageManager.MATCH_SYSTEM_ONLY,
- UserHandle.USER_SYSTEM);
- }
+ // Check if device is configured with no home screen, which implies no SystemUI.
+ boolean noHome = mContext.getResources().getBoolean(R.bool.config_noHomeScreen);
+ if (!noHome) {
+ PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
+ systemUiUid = pm.getPackageUid(pm.getSystemUiServiceComponent().getPackageName(),
+ MATCH_SYSTEM_ONLY, USER_SYSTEM);
+ }
+ if (systemUiUid >= 0) {
Slog.d(TAG, "Detected SystemUiUid: " + Integer.toString(systemUiUid));
- } catch (PackageManager.NameNotFoundException e) {
+ } else {
// Some platforms, such as wearables do not have a system ui.
- Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
+ Slog.w(TAG, "Unable to resolve SystemUI's UID.");
}
mSystemUiUid = systemUiUid;
}
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index 753c1171aeb3..b71943504bf6 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -5573,7 +5573,7 @@ public class ConnectivityService extends IConnectivityManager.Stub
* @param linkProperties the initial link properties of this network. They can be updated
* later : see {@link #updateLinkProperties}.
* @param networkCapabilities the initial capabilites of this network. They can be updated
- * later : see {@link #updateNetworkCapabilities}.
+ * later : see {@link #updateCapabilities}.
* @param currentScore the initial score of the network. See
* {@link NetworkAgentInfo#getCurrentScore}.
* @param networkMisc metadata about the network. This is never updated.
@@ -5596,7 +5596,7 @@ public class ConnectivityService extends IConnectivityManager.Stub
ns, mContext, mTrackerHandler, new NetworkMisc(networkMisc), this, mNetd,
mDnsResolver, mNMS, factorySerialNumber);
// Make sure the network capabilities reflect what the agent info says.
- nai.setNetworkCapabilities(mixInCapabilities(nai, nc));
+ nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
final String extraInfo = networkInfo.getExtraInfo();
final String name = TextUtils.isEmpty(extraInfo)
? nai.networkCapabilities.getSSID() : extraInfo;
@@ -5950,11 +5950,7 @@ public class ConnectivityService extends IConnectivityManager.Stub
}
}
- final NetworkCapabilities prevNc;
- synchronized (nai) {
- prevNc = nai.networkCapabilities;
- nai.setNetworkCapabilities(newNc);
- }
+ final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
updateUids(nai, prevNc, newNc);
@@ -5963,7 +5959,7 @@ public class ConnectivityService extends IConnectivityManager.Stub
// the change we're processing can't affect any requests, it can only affect the listens
// on this network. We might have been called by rematchNetworkAndRequests when a
// network changed foreground state.
- processListenRequests(nai, true);
+ processListenRequests(nai);
} else {
// If the requestable capabilities have changed or the score changed, we can't have been
// called by rematchNetworkAndRequests, so it's safe to start a rematch.
@@ -6271,8 +6267,14 @@ public class ConnectivityService extends IConnectivityManager.Stub
updateAllVpnsCapabilities();
}
- private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
+ private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
// For consistency with previous behaviour, send onLost callbacks before onAvailable.
+ processNewlyLostListenRequests(nai);
+ notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
+ processNewlySatisfiedListenRequests(nai);
+ }
+
+ private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
for (NetworkRequestInfo nri : mNetworkRequests.values()) {
NetworkRequest nr = nri.request;
if (!nr.isListen()) continue;
@@ -6281,11 +6283,9 @@ public class ConnectivityService extends IConnectivityManager.Stub
callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
}
}
+ }
- if (capabilitiesChanged) {
- notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
- }
-
+ private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
for (NetworkRequestInfo nri : mNetworkRequests.values()) {
NetworkRequest nr = nri.request;
if (!nr.isListen()) continue;
@@ -6468,19 +6468,20 @@ public class ConnectivityService extends IConnectivityManager.Stub
// before LegacyTypeTracker sends legacy broadcasts
for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
- // Second pass: process all listens.
- if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
- // TODO : most of the following is useless because the only thing that changed
- // here is whether the network is a background network. Clean this up.
+ // Finally, process listen requests and update capabilities if the background state has
+ // changed for this network. For consistency with previous behavior, send onLost callbacks
+ // before onAvailable.
+ processNewlyLostListenRequests(newNetwork);
- NetworkCapabilities newNc = mixInCapabilities(newNetwork,
+ // Maybe the network changed background states. Update its capabilities.
+ final boolean backgroundChanged = wasBackgroundNetwork != newNetwork.isBackgroundNetwork();
+ if (backgroundChanged) {
+ final NetworkCapabilities newNc = mixInCapabilities(newNetwork,
newNetwork.networkCapabilities);
- if (Objects.equals(newNetwork.networkCapabilities, newNc)) return;
-
final int oldPermission = getNetworkPermission(newNetwork.networkCapabilities);
final int newPermission = getNetworkPermission(newNc);
- if (oldPermission != newPermission && newNetwork.created && !newNetwork.isVPN()) {
+ if (oldPermission != newPermission) {
try {
mNMS.setNetworkPermission(newNetwork.network.netId, newPermission);
} catch (RemoteException e) {
@@ -6488,53 +6489,11 @@ public class ConnectivityService extends IConnectivityManager.Stub
}
}
- final NetworkCapabilities prevNc;
- synchronized (newNetwork) {
- prevNc = newNetwork.networkCapabilities;
- newNetwork.setNetworkCapabilities(newNc);
- }
-
- updateUids(newNetwork, prevNc, newNc);
-
- if (newNetwork.getCurrentScore() == score
- && newNc.equalRequestableCapabilities(prevNc)) {
- // If the requestable capabilities haven't changed, and the score hasn't changed,
- // then the change we're processing can't affect any requests, it can only affect
- // the listens on this network.
- processListenRequests(newNetwork, true);
- } else {
- rematchAllNetworksAndRequests();
- notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_CAP_CHANGED);
- }
-
- if (prevNc != null) {
- final boolean oldMetered = prevNc.isMetered();
- final boolean newMetered = newNc.isMetered();
- final boolean meteredChanged = oldMetered != newMetered;
-
- if (meteredChanged) {
- maybeNotifyNetworkBlocked(newNetwork, oldMetered, newMetered,
- mRestrictBackground, mRestrictBackground);
- }
-
- final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
- != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
-
- // Report changes that are interesting for network statistics tracking.
- if (meteredChanged || roamingChanged) {
- notifyIfacesChangedForNetworkStats();
- }
- }
-
- if (!newNc.hasTransport(TRANSPORT_VPN)) {
- // Tell VPNs about updated capabilities, since they may need to
- // bubble those changes through.
- updateAllVpnsCapabilities();
- }
-
- } else {
- processListenRequests(newNetwork, false);
+ newNetwork.getAndSetNetworkCapabilities(newNc);
+ notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_CAP_CHANGED);
}
+
+ processNewlySatisfiedListenRequests(newNetwork);
}
/**
@@ -6719,9 +6678,8 @@ public class ConnectivityService extends IConnectivityManager.Stub
// NetworkCapabilities need to be set before sending the private DNS config to
// NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
- synchronized (networkAgent) {
- networkAgent.setNetworkCapabilities(networkAgent.networkCapabilities);
- }
+ networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
+
handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
null);
diff --git a/services/core/java/com/android/server/CountryDetectorService.java b/services/core/java/com/android/server/CountryDetectorService.java
index d8a2fe35c7e8..861c731c69e0 100644
--- a/services/core/java/com/android/server/CountryDetectorService.java
+++ b/services/core/java/com/android/server/CountryDetectorService.java
@@ -16,14 +16,6 @@
package com.android.server;
-import java.io.FileDescriptor;
-import java.io.PrintWriter;
-import java.util.HashMap;
-
-import com.android.internal.os.BackgroundThread;
-import com.android.internal.util.DumpUtils;
-import com.android.server.location.ComprehensiveCountryDetector;
-
import android.content.Context;
import android.location.Country;
import android.location.CountryListener;
@@ -36,17 +28,25 @@ import android.util.PrintWriterPrinter;
import android.util.Printer;
import android.util.Slog;
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.os.BackgroundThread;
+import com.android.internal.util.DumpUtils;
+import com.android.server.location.ComprehensiveCountryDetector;
+
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
+import java.util.HashMap;
+
/**
- * This class detects the country that the user is in through
- * {@link ComprehensiveCountryDetector}.
+ * This class detects the country that the user is in through {@link ComprehensiveCountryDetector}.
*
* @hide
*/
-public class CountryDetectorService extends ICountryDetector.Stub implements Runnable {
+public class CountryDetectorService extends ICountryDetector.Stub {
/**
- * The class represents the remote listener, it will also removes itself
- * from listener list when the remote process was died.
+ * The class represents the remote listener, it will also removes itself from listener list when
+ * the remote process was died.
*/
private final class Receiver implements IBinder.DeathRecipient {
private final ICountryListener mListener;
@@ -79,9 +79,11 @@ public class CountryDetectorService extends ICountryDetector.Stub implements Run
}
}
- private final static String TAG = "CountryDetector";
+ private static final String TAG = "CountryDetector";
- /** Whether to dump the state of the country detector service to bugreports */
+ /**
+ * Whether to dump the state of the country detector service to bugreports
+ */
private static final boolean DEBUG = false;
private final HashMap<IBinder, Receiver> mReceivers;
@@ -92,15 +94,21 @@ public class CountryDetectorService extends ICountryDetector.Stub implements Run
private CountryListener mLocationBasedDetectorListener;
public CountryDetectorService(Context context) {
+ this(context, BackgroundThread.getHandler());
+ }
+
+ @VisibleForTesting
+ CountryDetectorService(Context context, Handler handler) {
super();
- mReceivers = new HashMap<IBinder, Receiver>();
+ mReceivers = new HashMap<>();
mContext = context;
+ mHandler = handler;
}
@Override
public Country detectCountry() {
if (!mSystemReady) {
- return null; // server not yet active
+ return null; // server not yet active
} else {
return mCountryDetector.detectCountry();
}
@@ -154,9 +162,8 @@ public class CountryDetectorService extends ICountryDetector.Stub implements Run
}
}
-
protected void notifyReceivers(Country country) {
- synchronized(mReceivers) {
+ synchronized (mReceivers) {
for (Receiver receiver : mReceivers.values()) {
try {
receiver.getListener().onCountryDetected(country);
@@ -170,38 +177,23 @@ public class CountryDetectorService extends ICountryDetector.Stub implements Run
void systemRunning() {
// Shall we wait for the initialization finish.
- BackgroundThread.getHandler().post(this);
+ mHandler.post(
+ () -> {
+ initialize();
+ mSystemReady = true;
+ });
}
private void initialize() {
mCountryDetector = new ComprehensiveCountryDetector(mContext);
- mLocationBasedDetectorListener = new CountryListener() {
- public void onCountryDetected(final Country country) {
- mHandler.post(new Runnable() {
- public void run() {
- notifyReceivers(country);
- }
- });
- }
- };
- }
-
- public void run() {
- mHandler = new Handler();
- initialize();
- mSystemReady = true;
+ mLocationBasedDetectorListener = country -> mHandler.post(() -> notifyReceivers(country));
}
protected void setCountryListener(final CountryListener listener) {
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- mCountryDetector.setCountryListener(listener);
- }
- });
+ mHandler.post(() -> mCountryDetector.setCountryListener(listener));
}
- // For testing
+ @VisibleForTesting
boolean isSystemReady() {
return mSystemReady;
}
diff --git a/services/core/java/com/android/server/GnssManagerService.java b/services/core/java/com/android/server/GnssManagerService.java
index cbf2a622fd2e..bbcfdc63f3f1 100644
--- a/services/core/java/com/android/server/GnssManagerService.java
+++ b/services/core/java/com/android/server/GnssManagerService.java
@@ -56,6 +56,7 @@ import com.android.server.location.GnssMeasurementCorrectionsProvider;
import com.android.server.location.GnssMeasurementsProvider;
import com.android.server.location.GnssNavigationMessageProvider;
import com.android.server.location.GnssStatusListenerHelper;
+import com.android.server.location.LocationUsageLogger;
import com.android.server.location.RemoteListenerHelper;
import java.io.FileDescriptor;
diff --git a/services/core/java/com/android/server/LocationManagerService.java b/services/core/java/com/android/server/LocationManagerService.java
index 54dfc98e888d..cad917b073a5 100644
--- a/services/core/java/com/android/server/LocationManagerService.java
+++ b/services/core/java/com/android/server/LocationManagerService.java
@@ -104,6 +104,7 @@ import com.android.server.location.LocationRequestStatistics;
import com.android.server.location.LocationRequestStatistics.PackageProviderKey;
import com.android.server.location.LocationRequestStatistics.PackageStatistics;
import com.android.server.location.LocationSettingsStore;
+import com.android.server.location.LocationUsageLogger;
import com.android.server.location.MockProvider;
import com.android.server.location.PassiveProvider;
import com.android.server.pm.permission.PermissionManagerServiceInternal;
@@ -158,21 +159,15 @@ public class LocationManagerService extends ILocationManager.Stub {
}
}
- private static final String TAG = "LocationManagerService";
+ public static final String TAG = "LocationManagerService";
public static final boolean D = Log.isLoggable(TAG, Log.DEBUG);
private static final String WAKELOCK_KEY = "*location*";
- // Location resolution level: no location data whatsoever
private static final int RESOLUTION_LEVEL_NONE = 0;
- // Location resolution level: coarse location data only
private static final int RESOLUTION_LEVEL_COARSE = 1;
- // Location resolution level: fine location data
private static final int RESOLUTION_LEVEL_FINE = 2;
- private static final String ACCESS_LOCATION_EXTRA_COMMANDS =
- android.Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS;
-
private static final String NETWORK_LOCATION_SERVICE_ACTION =
"com.android.location.service.v3.NetworkLocationProvider";
private static final String FUSED_LOCATION_SERVICE_ACTION =
@@ -198,6 +193,8 @@ public class LocationManagerService extends ILocationManager.Stub {
private final Object mLock = new Object();
private final Context mContext;
private final Handler mHandler;
+ private final LocationSettingsStore mSettingsStore;
+ private final LocationUsageLogger mLocationUsageLogger;
private AppOpsManager mAppOps;
private PackageManager mPackageManager;
@@ -205,8 +202,6 @@ public class LocationManagerService extends ILocationManager.Stub {
private ActivityManager mActivityManager;
private UserManager mUserManager;
- private LocationSettingsStore mSettingsStore;
-
private GeofenceManager mGeofenceManager;
private LocationFudger mLocationFudger;
private GeocoderProxy mGeocodeProvider;
@@ -219,12 +214,12 @@ public class LocationManagerService extends ILocationManager.Stub {
// list of currently active providers
@GuardedBy("mLock")
- private final ArrayList<LocationProvider> mProviders = new ArrayList<>();
+ private final ArrayList<LocationProviderManager> mProviders = new ArrayList<>();
// list of non-mock providers, so that when mock providers replace real providers, they can be
// later re-replaced
@GuardedBy("mLock")
- private final ArrayList<LocationProvider> mRealProviders = new ArrayList<>();
+ private final ArrayList<LocationProviderManager> mRealProviders = new ArrayList<>();
@GuardedBy("mLock")
private final HashMap<Object, Receiver> mReceivers = new HashMap<>();
@@ -251,12 +246,10 @@ public class LocationManagerService extends ILocationManager.Stub {
@PowerManager.LocationPowerSaveMode
private int mBatterySaverMode;
- @GuardedBy("mLock")
- private final LocationUsageLogger mLocationUsageLogger;
-
private LocationManagerService(Context context) {
mContext = context;
mHandler = FgThread.getHandler();
+ mSettingsStore = new LocationSettingsStore(mContext, mHandler);
mLocationUsageLogger = new LocationUsageLogger();
// Let the package manager query which are the default location
@@ -274,6 +267,8 @@ public class LocationManagerService extends ILocationManager.Stub {
}
private void onSystemReady() {
+ mSettingsStore.onSystemReady();
+
synchronized (mLock) {
mPackageManager = mContext.getPackageManager();
mAppOps = mContext.getSystemService(AppOpsManager.class);
@@ -281,7 +276,6 @@ public class LocationManagerService extends ILocationManager.Stub {
mActivityManager = mContext.getSystemService(ActivityManager.class);
mUserManager = mContext.getSystemService(UserManager.class);
- mSettingsStore = new LocationSettingsStore(mContext, mHandler);
mLocationFudger = new LocationFudger(mContext, mHandler);
mGeofenceManager = new GeofenceManager(mContext, mSettingsStore);
@@ -343,11 +337,6 @@ public class LocationManagerService extends ILocationManager.Stub {
onLocationModeChangedLocked(userId);
}
});
- mSettingsStore.addOnLocationProvidersAllowedChangedListener((userId) -> {
- synchronized (mLock) {
- onProviderAllowedChangedLocked(userId);
- }
- });
mSettingsStore.addOnBackgroundThrottleIntervalChangedListener(() -> {
synchronized (mLock) {
onBackgroundThrottleIntervalChangedLocked();
@@ -426,14 +415,14 @@ public class LocationManagerService extends ILocationManager.Stub {
for (Receiver receiver : mReceivers.values()) {
receiver.updateMonitoring(true);
}
- for (LocationProvider p : mProviders) {
+ for (LocationProviderManager p : mProviders) {
applyRequirementsLocked(p);
}
}
@GuardedBy("mLock")
private void onPermissionsChangedLocked() {
- for (LocationProvider p : mProviders) {
+ for (LocationProviderManager p : mProviders) {
applyRequirementsLocked(p);
}
}
@@ -453,7 +442,7 @@ public class LocationManagerService extends ILocationManager.Stub {
mBatterySaverMode = newLocationMode;
- for (LocationProvider p : mProviders) {
+ for (LocationProviderManager p : mProviders) {
applyRequirementsLocked(p);
}
}
@@ -461,7 +450,7 @@ public class LocationManagerService extends ILocationManager.Stub {
@GuardedBy("mLock")
private void onScreenStateChangedLocked() {
if (mBatterySaverMode == PowerManager.LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF) {
- for (LocationProvider p : mProviders) {
+ for (LocationProviderManager p : mProviders) {
applyRequirementsLocked(p);
}
}
@@ -474,18 +463,11 @@ public class LocationManagerService extends ILocationManager.Stub {
}
Intent intent = new Intent(LocationManager.MODE_CHANGED_ACTION);
- intent.putExtra(LocationManager.EXTRA_LOCATION_ENABLED, isLocationEnabled());
+ intent.putExtra(LocationManager.EXTRA_LOCATION_ENABLED, isLocationEnabledForUser(userId));
mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
- for (LocationProvider p : mProviders) {
- p.onLocationModeChangedLocked(userId);
- }
- }
-
- @GuardedBy("mLock")
- private void onProviderAllowedChangedLocked(int userId) {
- for (LocationProvider p : mProviders) {
- p.onAllowedChangedLocked(userId);
+ for (LocationProviderManager p : mProviders) {
+ p.onUseableChangedLocked(userId);
}
}
@@ -539,21 +521,21 @@ public class LocationManagerService extends ILocationManager.Stub {
@GuardedBy("mLock")
private void onBackgroundThrottleIntervalChangedLocked() {
- for (LocationProvider provider : mProviders) {
+ for (LocationProviderManager provider : mProviders) {
applyRequirementsLocked(provider);
}
}
@GuardedBy("mLock")
private void onBackgroundThrottleWhitelistChangedLocked() {
- for (LocationProvider p : mProviders) {
+ for (LocationProviderManager p : mProviders) {
applyRequirementsLocked(p);
}
}
@GuardedBy("lock")
private void onIgnoreSettingsWhitelistChangedLocked() {
- for (LocationProvider p : mProviders) {
+ for (LocationProviderManager p : mProviders) {
applyRequirementsLocked(p);
}
}
@@ -642,14 +624,15 @@ public class LocationManagerService extends ILocationManager.Stub {
@GuardedBy("mLock")
private void initializeProvidersLocked() {
// create a passive location provider, which is always enabled
- LocationProvider passiveProviderManager = new LocationProvider(PASSIVE_PROVIDER);
+ LocationProviderManager passiveProviderManager = new LocationProviderManager(
+ PASSIVE_PROVIDER);
addProviderLocked(passiveProviderManager);
mPassiveProvider = new PassiveProvider(mContext, passiveProviderManager);
passiveProviderManager.attachLocked(mPassiveProvider);
if (GnssManagerService.isGnssSupported()) {
// Create a gps location provider manager
- LocationProvider gnssProviderManager = new LocationProvider(GPS_PROVIDER, true);
+ LocationProviderManager gnssProviderManager = new LocationProviderManager(GPS_PROVIDER);
mRealProviders.add(gnssProviderManager);
addProviderLocked(gnssProviderManager);
@@ -680,7 +663,8 @@ public class LocationManagerService extends ILocationManager.Stub {
ensureFallbackFusedProviderPresentLocked(pkgs);
// bind to network provider
- LocationProvider networkProviderManager = new LocationProvider(NETWORK_PROVIDER, true);
+ LocationProviderManager networkProviderManager = new LocationProviderManager(
+ NETWORK_PROVIDER);
LocationProviderProxy networkProvider = LocationProviderProxy.createAndBind(
mContext,
networkProviderManager,
@@ -697,7 +681,7 @@ public class LocationManagerService extends ILocationManager.Stub {
}
// bind to fused provider
- LocationProvider fusedProviderManager = new LocationProvider(FUSED_PROVIDER);
+ LocationProviderManager fusedProviderManager = new LocationProviderManager(FUSED_PROVIDER);
LocationProviderProxy fusedProvider = LocationProviderProxy.createAndBind(
mContext,
fusedProviderManager,
@@ -770,7 +754,7 @@ public class LocationManagerService extends ILocationManager.Stub {
Boolean.parseBoolean(fragments[7]) /* supportsBearing */,
Integer.parseInt(fragments[8]) /* powerRequirement */,
Integer.parseInt(fragments[9]) /* accuracy */);
- LocationProvider testProviderManager = new LocationProvider(name);
+ LocationProviderManager testProviderManager = new LocationProviderManager(name);
addProviderLocked(testProviderManager);
testProviderManager.attachLocked(
new MockProvider(mContext, testProviderManager, properties));
@@ -792,22 +776,19 @@ public class LocationManagerService extends ILocationManager.Stub {
onUserProfilesChangedLocked();
// let providers know the current user has changed
- for (LocationProvider p : mProviders) {
- p.onCurrentUserChangedLocked(oldUserId);
- p.onCurrentUserChangedLocked(mCurrentUserId);
+ for (LocationProviderManager p : mProviders) {
+ p.onUseableChangedLocked(oldUserId);
+ p.onUseableChangedLocked(mCurrentUserId);
}
}
/**
* Location provider manager, manages a LocationProvider.
*/
- class LocationProvider implements AbstractLocationProvider.LocationProviderManager {
+ class LocationProviderManager implements AbstractLocationProvider.LocationProviderManager {
private final String mName;
- // whether this provider should respect LOCATION_PROVIDERS_ALLOWED (ie gps and network)
- private final boolean mIsManagedBySettings;
-
// remember to clear binder identity before invoking any provider operation
@GuardedBy("mLock")
@Nullable
@@ -816,36 +797,26 @@ public class LocationManagerService extends ILocationManager.Stub {
@GuardedBy("mLock")
private SparseArray<Boolean> mUseable; // combined state for each user id
@GuardedBy("mLock")
- private boolean mAllowed; // state of LOCATION_PROVIDERS_ALLOWED
- @GuardedBy("mLock")
private boolean mEnabled; // state of provider
@GuardedBy("mLock")
@Nullable
private ProviderProperties mProperties;
- private LocationProvider(String name) {
- this(name, false);
- }
-
- private LocationProvider(String name, boolean isManagedBySettings) {
+ private LocationProviderManager(String name) {
mName = name;
- mIsManagedBySettings = isManagedBySettings;
mProvider = null;
mUseable = new SparseArray<>(1);
- mAllowed = !mIsManagedBySettings;
mEnabled = false;
mProperties = null;
- if (mIsManagedBySettings) {
- // since we assume providers are disabled by default
- Settings.Secure.putStringForUser(
- mContext.getContentResolver(),
- Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
- "-" + mName,
- mCurrentUserId);
- }
+ // update LOCATION_PROVIDERS_ALLOWED for best effort backwards compatibility
+ Settings.Secure.putStringForUser(
+ mContext.getContentResolver(),
+ Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
+ "-" + mName,
+ mCurrentUserId);
}
@GuardedBy("mLock")
@@ -861,7 +832,7 @@ public class LocationManagerService extends ILocationManager.Stub {
// it would be more correct to call this for all users, but we know this can only
// affect the current user since providers are disabled for non-current users
- onUseableChangedLocked(false, mCurrentUserId);
+ onUseableChangedLocked(mCurrentUserId);
}
public String getName() {
@@ -931,9 +902,6 @@ public class LocationManagerService extends ILocationManager.Stub {
pw.println("useable=" + isUseableLocked(mCurrentUserId));
if (!isUseableLocked(mCurrentUserId)) {
pw.println("attached=" + (mProvider != null));
- if (mIsManagedBySettings) {
- pw.println("allowed=" + mAllowed);
- }
pw.println("enabled=" + mEnabled);
}
@@ -972,7 +940,7 @@ public class LocationManagerService extends ILocationManager.Stub {
return;
}
synchronized (mLock) {
- LocationProvider gpsProvider = getLocationProviderLocked(GPS_PROVIDER);
+ LocationProviderManager gpsProvider = getLocationProviderLocked(GPS_PROVIDER);
if (gpsProvider == null || !gpsProvider.isUseableLocked()) {
Slog.w(TAG, "reportLocationBatch() called without user permission");
return;
@@ -997,7 +965,7 @@ public class LocationManagerService extends ILocationManager.Stub {
// it would be more correct to call this for all users, but we know this can only
// affect the current user since providers are disabled for non-current users
- onUseableChangedLocked(false, mCurrentUserId);
+ onUseableChangedLocked(mCurrentUserId);
}
}
@@ -1009,43 +977,6 @@ public class LocationManagerService extends ILocationManager.Stub {
}
@GuardedBy("mLock")
- public void onLocationModeChangedLocked(int userId) {
- if (!isCurrentProfileLocked(userId)) {
- return;
- }
-
- onUseableChangedLocked(false, userId);
- }
-
- @GuardedBy("mLock")
- public void onAllowedChangedLocked(int userId) {
- if (!isCurrentProfileLocked(userId)) {
- return;
- }
-
- if (mIsManagedBySettings) {
- boolean allowed = mSettingsStore.getLocationProvidersAllowed(
- mCurrentUserId).contains(mName);
-
- if (allowed == mAllowed) {
- return;
- }
-
- if (D) {
- Log.d(TAG, mName + " provider allowed is now " + mAllowed);
- }
-
- mAllowed = allowed;
- onUseableChangedLocked(true, userId);
- }
- }
-
- @GuardedBy("mLock")
- public void onCurrentUserChangedLocked(int userId) {
- onUseableChangedLocked(false, userId);
- }
-
- @GuardedBy("mLock")
public boolean isUseableLocked() {
return isUseableLocked(mCurrentUserId);
}
@@ -1056,38 +987,13 @@ public class LocationManagerService extends ILocationManager.Stub {
}
@GuardedBy("mLock")
- public void onUseableChangedLocked(boolean isAllowedChanged, int userId) {
+ public void onUseableChangedLocked(int userId) {
// if any property that contributes to "useability" here changes state, it MUST result
// in a direct or indrect call to onUseableChangedLocked. this allows the provider to
// guarantee that it will always eventually reach the correct state.
- boolean useableIgnoringAllowed = mProvider != null && mProviders.contains(this)
+ boolean useable = mProvider != null && mProviders.contains(this)
&& isCurrentProfileLocked(userId) && isLocationEnabledForUser(userId)
&& mEnabled;
- boolean useable = useableIgnoringAllowed && mAllowed;
-
- // update deprecated provider allowed settings for backwards compatibility
- if (mIsManagedBySettings) {
- // a "-" change derived from the allowed setting should not be overwritten, but a
- // "+" change should be corrected if necessary
- if (useableIgnoringAllowed && !isAllowedChanged) {
- Settings.Secure.putStringForUser(
- mContext.getContentResolver(),
- Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
- "+" + mName,
- userId);
- } else if (!useableIgnoringAllowed) {
- Settings.Secure.putStringForUser(
- mContext.getContentResolver(),
- Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
- "-" + mName,
- userId);
- }
-
- Intent intent = new Intent(LocationManager.PROVIDERS_CHANGED_ACTION);
- intent.putExtra(LocationManager.EXTRA_PROVIDER_NAME, mName);
- intent.putExtra(LocationManager.EXTRA_PROVIDER_ENABLED, useable);
- mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
- }
if (useable == isUseableLocked(userId)) {
return;
@@ -1098,6 +1004,21 @@ public class LocationManagerService extends ILocationManager.Stub {
Log.d(TAG, "[u" + userId + "] " + mName + " provider useable = " + useable);
}
+ // fused and passive provider never get public updates for legacy reasons
+ if (!FUSED_PROVIDER.equals(mName) && !PASSIVE_PROVIDER.equals(mName)) {
+ // update LOCATION_PROVIDERS_ALLOWED for best effort backwards compatibility
+ Settings.Secure.putStringForUser(
+ mContext.getContentResolver(),
+ Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
+ (useable ? "+" : "-") + mName,
+ userId);
+
+ Intent intent = new Intent(LocationManager.PROVIDERS_CHANGED_ACTION);
+ intent.putExtra(LocationManager.EXTRA_PROVIDER_NAME, mName);
+ intent.putExtra(LocationManager.EXTRA_PROVIDER_ENABLED, useable);
+ mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
+ }
+
if (!useable) {
// If any provider has been disabled, clear all last locations for all
// providers. This is to be on the safe side in case a provider has location
@@ -1110,7 +1031,7 @@ public class LocationManagerService extends ILocationManager.Stub {
}
}
- private class MockLocationProvider extends LocationProvider {
+ private class MockLocationProvider extends LocationProviderManager {
private ProviderRequest mCurrentRequest;
@@ -1260,7 +1181,8 @@ public class LocationManagerService extends ILocationManager.Stub {
// See if receiver has any enabled update records. Also note if any update records
// are high power (has a high power provider with an interval under a threshold).
for (UpdateRecord updateRecord : mUpdateRecords.values()) {
- LocationProvider provider = getLocationProviderLocked(updateRecord.mProvider);
+ LocationProviderManager provider = getLocationProviderLocked(
+ updateRecord.mProvider);
if (provider == null) {
continue;
}
@@ -1536,32 +1458,29 @@ public class LocationManagerService extends ILocationManager.Stub {
}
@GuardedBy("mLock")
- private void addProviderLocked(LocationProvider provider) {
+ private void addProviderLocked(LocationProviderManager provider) {
Preconditions.checkState(getLocationProviderLocked(provider.getName()) == null);
mProviders.add(provider);
- // allowed state may change while provider was inactive
- provider.onAllowedChangedLocked(mCurrentUserId);
-
// it would be more correct to call this for all users, but we know this can only
// affect the current user since providers are disabled for non-current users
- provider.onUseableChangedLocked(false, mCurrentUserId);
+ provider.onUseableChangedLocked(mCurrentUserId);
}
@GuardedBy("mLock")
- private void removeProviderLocked(LocationProvider provider) {
+ private void removeProviderLocked(LocationProviderManager provider) {
if (mProviders.remove(provider)) {
// it would be more correct to call this for all users, but we know this can only
// affect the current user since providers are disabled for non-current users
- provider.onUseableChangedLocked(false, mCurrentUserId);
+ provider.onUseableChangedLocked(mCurrentUserId);
}
}
@GuardedBy("mLock")
@Nullable
- private LocationProvider getLocationProviderLocked(String providerName) {
- for (LocationProvider provider : mProviders) {
+ private LocationProviderManager getLocationProviderLocked(String providerName) {
+ for (LocationProviderManager provider : mProviders) {
if (providerName.equals(provider.getName())) {
return provider;
}
@@ -1612,7 +1531,7 @@ public class LocationManagerService extends ILocationManager.Stub {
// network and fused providers are ok with COARSE or FINE
return RESOLUTION_LEVEL_COARSE;
} else {
- for (LocationProvider lp : mProviders) {
+ for (LocationProviderManager lp : mProviders) {
if (!lp.getName().equals(provider)) {
continue;
}
@@ -1712,7 +1631,7 @@ public class LocationManagerService extends ILocationManager.Stub {
public List<String> getAllProviders() {
synchronized (mLock) {
ArrayList<String> providers = new ArrayList<>(mProviders.size());
- for (LocationProvider provider : mProviders) {
+ for (LocationProviderManager provider : mProviders) {
String name = provider.getName();
if (FUSED_PROVIDER.equals(name)) {
continue;
@@ -1733,7 +1652,7 @@ public class LocationManagerService extends ILocationManager.Stub {
int allowedResolutionLevel = getCallerAllowedResolutionLevel();
synchronized (mLock) {
ArrayList<String> providers = new ArrayList<>(mProviders.size());
- for (LocationProvider provider : mProviders) {
+ for (LocationProviderManager provider : mProviders) {
String name = provider.getName();
if (FUSED_PROVIDER.equals(name)) {
continue;
@@ -1783,7 +1702,7 @@ public class LocationManagerService extends ILocationManager.Stub {
}
@GuardedBy("mLock")
- private void updateProviderUseableLocked(LocationProvider provider) {
+ private void updateProviderUseableLocked(LocationProviderManager provider) {
boolean useable = provider.isUseableLocked();
ArrayList<Receiver> deadReceivers = null;
@@ -1822,14 +1741,14 @@ public class LocationManagerService extends ILocationManager.Stub {
@GuardedBy("mLock")
private void applyRequirementsLocked(String providerName) {
- LocationProvider provider = getLocationProviderLocked(providerName);
+ LocationProviderManager provider = getLocationProviderLocked(providerName);
if (provider != null) {
applyRequirementsLocked(provider);
}
}
@GuardedBy("mLock")
- private void applyRequirementsLocked(LocationProvider provider) {
+ private void applyRequirementsLocked(LocationProviderManager provider) {
ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider.getName());
WorkSource worksource = new WorkSource();
ProviderRequest providerRequest = new ProviderRequest();
@@ -2279,7 +2198,7 @@ public class LocationManagerService extends ILocationManager.Stub {
throw new IllegalArgumentException("provider name must not be null");
}
- LocationProvider provider = getLocationProviderLocked(name);
+ LocationProviderManager provider = getLocationProviderLocked(name);
if (provider == null) {
throw new IllegalArgumentException("provider doesn't exist: " + name);
}
@@ -2401,7 +2320,7 @@ public class LocationManagerService extends ILocationManager.Stub {
// or use the fused provider
String name = request.getProvider();
if (name == null) name = LocationManager.FUSED_PROVIDER;
- LocationProvider provider = getLocationProviderLocked(name);
+ LocationProviderManager provider = getLocationProviderLocked(name);
if (provider == null) return null;
// only the current user or location providers may get location this way
@@ -2531,7 +2450,7 @@ public class LocationManagerService extends ILocationManager.Stub {
"Access Fine Location permission not granted to inject Location");
synchronized (mLock) {
- LocationProvider provider = getLocationProviderLocked(location.getProvider());
+ LocationProviderManager provider = getLocationProviderLocked(location.getProvider());
if (provider == null || !provider.isUseableLocked()) {
return false;
}
@@ -2702,6 +2621,10 @@ public class LocationManagerService extends ILocationManager.Stub {
// throw NullPointerException to remain compatible with previous implementation
throw new NullPointerException();
}
+
+ mContext.enforceCallingOrSelfPermission(
+ Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS, null);
+
synchronized (mLock) {
checkResolutionLevelIsSufficientForProviderUseLocked(getCallerAllowedResolutionLevel(),
providerName);
@@ -2711,13 +2634,7 @@ public class LocationManagerService extends ILocationManager.Stub {
LocationStatsEnums.API_SEND_EXTRA_COMMAND,
providerName);
- // and check for ACCESS_LOCATION_EXTRA_COMMANDS
- if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
- != PERMISSION_GRANTED)) {
- throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
- }
-
- LocationProvider provider = getLocationProviderLocked(providerName);
+ LocationProviderManager provider = getLocationProviderLocked(providerName);
if (provider != null) {
provider.sendExtraCommand(command, extras);
}
@@ -2740,7 +2657,7 @@ public class LocationManagerService extends ILocationManager.Stub {
@Override
public ProviderProperties getProviderProperties(String providerName) {
synchronized (mLock) {
- LocationProvider provider = getLocationProviderLocked(providerName);
+ LocationProviderManager provider = getLocationProviderLocked(providerName);
if (provider == null) {
return null;
}
@@ -2753,7 +2670,7 @@ public class LocationManagerService extends ILocationManager.Stub {
mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_DEVICE_CONFIG,
Manifest.permission.READ_DEVICE_CONFIG + " permission required");
synchronized (mLock) {
- for (LocationProvider provider : mProviders) {
+ for (LocationProviderManager provider : mProviders) {
if (provider.getPackagesLocked().contains(packageName)) {
return true;
}
@@ -2767,7 +2684,7 @@ public class LocationManagerService extends ILocationManager.Stub {
mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_DEVICE_CONFIG,
Manifest.permission.READ_DEVICE_CONFIG + " permission required");
synchronized (mLock) {
- LocationProvider provider = getLocationProviderLocked(providerName);
+ LocationProviderManager provider = getLocationProviderLocked(providerName);
return provider == null ? Collections.emptyList() : provider.getPackagesLocked();
}
}
@@ -2805,10 +2722,6 @@ public class LocationManagerService extends ILocationManager.Stub {
}
}
- private boolean isLocationEnabled() {
- return isLocationEnabledForUser(mCurrentUserId);
- }
-
@Override
public boolean isLocationEnabledForUser(int userId) {
// Check INTERACT_ACROSS_USERS permission if userId is not current user id.
@@ -2840,7 +2753,7 @@ public class LocationManagerService extends ILocationManager.Stub {
if (FUSED_PROVIDER.equals(providerName)) return false;
synchronized (mLock) {
- LocationProvider provider = getLocationProviderLocked(providerName);
+ LocationProviderManager provider = getLocationProviderLocked(providerName);
return provider != null && provider.isUseableLocked(userId);
}
}
@@ -2879,7 +2792,7 @@ public class LocationManagerService extends ILocationManager.Stub {
}
@GuardedBy("mLock")
- private void handleLocationChangedLocked(Location location, LocationProvider provider) {
+ private void handleLocationChangedLocked(Location location, LocationProviderManager provider) {
if (!mProviders.contains(provider)) {
return;
}
@@ -3111,7 +3024,7 @@ public class LocationManagerService extends ILocationManager.Stub {
synchronized (mLock) {
long identity = Binder.clearCallingIdentity();
try {
- LocationProvider oldProvider = getLocationProviderLocked(name);
+ LocationProviderManager oldProvider = getLocationProviderLocked(name);
if (oldProvider != null) {
removeProviderLocked(oldProvider);
}
@@ -3135,7 +3048,7 @@ public class LocationManagerService extends ILocationManager.Stub {
synchronized (mLock) {
long identity = Binder.clearCallingIdentity();
try {
- LocationProvider testProvider = getLocationProviderLocked(name);
+ LocationProviderManager testProvider = getLocationProviderLocked(name);
if (testProvider == null || !testProvider.isMock()) {
return;
}
@@ -3143,8 +3056,8 @@ public class LocationManagerService extends ILocationManager.Stub {
removeProviderLocked(testProvider);
// reinstate real provider if available
- LocationProvider realProvider = null;
- for (LocationProvider provider : mRealProviders) {
+ LocationProviderManager realProvider = null;
+ for (LocationProviderManager provider : mRealProviders) {
if (name.equals(provider.getName())) {
realProvider = provider;
break;
@@ -3168,7 +3081,7 @@ public class LocationManagerService extends ILocationManager.Stub {
}
synchronized (mLock) {
- LocationProvider testProvider = getLocationProviderLocked(providerName);
+ LocationProviderManager testProvider = getLocationProviderLocked(providerName);
if (testProvider == null || !testProvider.isMock()) {
throw new IllegalArgumentException("Provider \"" + providerName + "\" unknown");
}
@@ -3192,7 +3105,7 @@ public class LocationManagerService extends ILocationManager.Stub {
}
synchronized (mLock) {
- LocationProvider testProvider = getLocationProviderLocked(providerName);
+ LocationProviderManager testProvider = getLocationProviderLocked(providerName);
if (testProvider == null || !testProvider.isMock()) {
throw new IllegalArgumentException("Provider \"" + providerName + "\" unknown");
}
@@ -3210,7 +3123,7 @@ public class LocationManagerService extends ILocationManager.Stub {
}
synchronized (mLock) {
- LocationProvider testProvider = getLocationProviderLocked(providerName);
+ LocationProviderManager testProvider = getLocationProviderLocked(providerName);
if (testProvider == null || !testProvider.isMock()) {
throw new IllegalArgumentException("Provider \"" + providerName + "\" unknown");
}
@@ -3247,7 +3160,7 @@ public class LocationManagerService extends ILocationManager.Stub {
+ TimeUtils.formatDuration(SystemClock.elapsedRealtime()));
ipw.println("Current user: " + mCurrentUserId + " " + Arrays.toString(
mCurrentUserProfiles));
- ipw.println("Location Mode: " + isLocationEnabled());
+ ipw.println("Location Mode: " + isLocationEnabledForUser(mCurrentUserId));
ipw.println("Battery Saver Location Mode: "
+ locationPowerSaveModeToString(mBatterySaverMode));
@@ -3319,7 +3232,7 @@ public class LocationManagerService extends ILocationManager.Stub {
ipw.println("Location Providers:");
ipw.increaseIndent();
- for (LocationProvider provider : mProviders) {
+ for (LocationProviderManager provider : mProviders) {
provider.dumpLocked(fd, ipw, args);
}
ipw.decreaseIndent();
diff --git a/services/core/java/com/android/server/MmsServiceBroker.java b/services/core/java/com/android/server/MmsServiceBroker.java
index c0f10a3c86e1..92d1da5be7a2 100644
--- a/services/core/java/com/android/server/MmsServiceBroker.java
+++ b/services/core/java/com/android/server/MmsServiceBroker.java
@@ -16,6 +16,8 @@
package com.android.server;
+import static android.telephony.SubscriptionManager.INVALID_SIM_SLOT_INDEX;
+
import android.Manifest;
import android.app.AppOpsManager;
import android.app.PendingIntent;
@@ -37,6 +39,7 @@ import android.os.SystemClock;
import android.os.UserHandle;
import android.service.carrier.CarrierMessagingService;
import android.telephony.SmsManager;
+import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.Slog;
@@ -523,11 +526,11 @@ public class MmsServiceBroker extends SystemService {
// Grant permission for the carrier app.
Intent intent = new Intent(action);
- TelephonyManager telephonyManager =
- (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
- List<String> carrierPackages =
- telephonyManager.getCarrierPackageNamesForIntentAndPhone(
- intent, SubscriptionManager.getPhoneId(subId));
+ TelephonyManager telephonyManager = (TelephonyManager)
+ mContext.getSystemService(Context.TELEPHONY_SERVICE);
+ List<String> carrierPackages = telephonyManager
+ .getCarrierPackageNamesForIntentAndPhone(
+ intent, getPhoneIdFromSubId(subId));
if (carrierPackages != null && carrierPackages.size() == 1) {
LocalServices.getService(UriGrantsManagerInternal.class)
.grantUriPermissionFromIntent(callingUid, carrierPackages.get(0),
@@ -539,4 +542,13 @@ public class MmsServiceBroker extends SystemService {
return contentUri;
}
}
+
+ private int getPhoneIdFromSubId(int subId) {
+ SubscriptionManager subManager = (SubscriptionManager)
+ mContext.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
+ if (subManager == null) return INVALID_SIM_SLOT_INDEX;
+ SubscriptionInfo info = subManager.getActiveSubscriptionInfo(subId);
+ if (info == null) return INVALID_SIM_SLOT_INDEX;
+ return info.getSimSlotIndex();
+ }
}
diff --git a/services/core/java/com/android/server/NetworkManagementService.java b/services/core/java/com/android/server/NetworkManagementService.java
index 840b7af19890..0d496b6b427d 100644
--- a/services/core/java/com/android/server/NetworkManagementService.java
+++ b/services/core/java/com/android/server/NetworkManagementService.java
@@ -58,6 +58,7 @@ import android.net.NetworkStack;
import android.net.NetworkStats;
import android.net.NetworkUtils;
import android.net.RouteInfo;
+import android.net.TetherConfigParcel;
import android.net.TetherStatsParcel;
import android.net.UidRange;
import android.net.UidRangeParcel;
@@ -1023,7 +1024,10 @@ public class NetworkManagementService extends INetworkManagementService.Stub {
NetworkStack.checkNetworkStackPermission(mContext);
// an odd number of addrs will fail
try {
- mNetdService.tetherStartWithConfiguration(usingLegacyDnsProxy, dhcpRange);
+ final TetherConfigParcel config = new TetherConfigParcel();
+ config.usingLegacyDnsProxy = usingLegacyDnsProxy;
+ config.dhcpRanges = dhcpRange;
+ mNetdService.tetherStartWithConfiguration(config);
} catch (RemoteException | ServiceSpecificException e) {
throw new IllegalStateException(e);
}
diff --git a/services/core/java/com/android/server/NetworkTimeUpdateServiceImpl.java b/services/core/java/com/android/server/NetworkTimeUpdateServiceImpl.java
index b0b45f411d34..39be311e902d 100644
--- a/services/core/java/com/android/server/NetworkTimeUpdateServiceImpl.java
+++ b/services/core/java/com/android/server/NetworkTimeUpdateServiceImpl.java
@@ -35,11 +35,11 @@ import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.provider.Settings;
+import android.telephony.TelephonyManager;
import android.util.Log;
import android.util.NtpTrustedTime;
import android.util.TimeUtils;
-import com.android.internal.telephony.TelephonyIntents;
import com.android.internal.util.DumpUtils;
import java.io.FileDescriptor;
@@ -137,7 +137,7 @@ public class NetworkTimeUpdateServiceImpl extends Binder implements NetworkTimeU
private void registerForTelephonyIntents() {
IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction(TelephonyIntents.ACTION_NETWORK_SET_TIME);
+ intentFilter.addAction(TelephonyManager.ACTION_NETWORK_SET_TIME);
mContext.registerReceiver(mNitzReceiver, intentFilter);
}
@@ -247,7 +247,7 @@ public class NetworkTimeUpdateServiceImpl extends Binder implements NetworkTimeU
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DBG) Log.d(TAG, "Received " + action);
- if (TelephonyIntents.ACTION_NETWORK_SET_TIME.equals(action)) {
+ if (TelephonyManager.ACTION_NETWORK_SET_TIME.equals(action)) {
mNitzTimeSetTime = SystemClock.elapsedRealtime();
}
}
diff --git a/services/core/java/com/android/server/PackageWatchdog.java b/services/core/java/com/android/server/PackageWatchdog.java
index 521b39305d9d..deff440aa0a6 100644
--- a/services/core/java/com/android/server/PackageWatchdog.java
+++ b/services/core/java/com/android/server/PackageWatchdog.java
@@ -29,6 +29,7 @@ import android.net.ConnectivityModuleConnector;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
+import android.os.SystemProperties;
import android.provider.DeviceConfig;
import android.text.TextUtils;
import android.util.ArrayMap;
@@ -82,6 +83,12 @@ public class PackageWatchdog {
static final String PROPERTY_WATCHDOG_EXPLICIT_HEALTH_CHECK_ENABLED =
"watchdog_explicit_health_check_enabled";
+ // TODO: make the following values configurable via DeviceConfig
+ private static final long NATIVE_CRASH_POLLING_INTERVAL_MILLIS =
+ TimeUnit.SECONDS.toMillis(30);
+ private static final long NUMBER_OF_NATIVE_CRASH_POLLS = 10;
+
+
public static final int FAILURE_REASON_UNKNOWN = 0;
public static final int FAILURE_REASON_NATIVE_CRASH = 1;
public static final int FAILURE_REASON_EXPLICIT_HEALTH_CHECK = 2;
@@ -110,6 +117,8 @@ public class PackageWatchdog {
// Whether explicit health checks are enabled or not
private static final boolean DEFAULT_EXPLICIT_HEALTH_CHECK_ENABLED = true;
+ private long mNumberOfNativeCrashPollsRemaining;
+
private static final int DB_VERSION = 1;
private static final String TAG_PACKAGE_WATCHDOG = "package-watchdog";
private static final String TAG_PACKAGE = "package";
@@ -188,6 +197,7 @@ public class PackageWatchdog {
mHealthCheckController = controller;
mConnectivityModuleConnector = connectivityModuleConnector;
mSystemClock = clock;
+ mNumberOfNativeCrashPollsRemaining = NUMBER_OF_NATIVE_CRASH_POLLS;
loadFromFile();
}
@@ -336,38 +346,70 @@ public class PackageWatchdog {
if (mAllObservers.isEmpty()) {
return;
}
-
- for (int pIndex = 0; pIndex < packages.size(); pIndex++) {
- VersionedPackage versionedPackage = packages.get(pIndex);
- // Observer that will receive failure for versionedPackage
- PackageHealthObserver currentObserverToNotify = null;
- int currentObserverImpact = Integer.MAX_VALUE;
-
- // Find observer with least user impact
- for (int oIndex = 0; oIndex < mAllObservers.size(); oIndex++) {
- ObserverInternal observer = mAllObservers.valueAt(oIndex);
- PackageHealthObserver registeredObserver = observer.registeredObserver;
- if (registeredObserver != null
- && observer.onPackageFailureLocked(
- versionedPackage.getPackageName())) {
- int impact = registeredObserver.onHealthCheckFailed(versionedPackage);
- if (impact != PackageHealthObserverImpact.USER_IMPACT_NONE
- && impact < currentObserverImpact) {
- currentObserverToNotify = registeredObserver;
- currentObserverImpact = impact;
+ boolean requiresImmediateAction = (failureReason == FAILURE_REASON_NATIVE_CRASH
+ || failureReason == FAILURE_REASON_EXPLICIT_HEALTH_CHECK);
+ if (requiresImmediateAction) {
+ handleFailureImmediately(packages, failureReason);
+ } else {
+ for (int pIndex = 0; pIndex < packages.size(); pIndex++) {
+ VersionedPackage versionedPackage = packages.get(pIndex);
+ // Observer that will receive failure for versionedPackage
+ PackageHealthObserver currentObserverToNotify = null;
+ int currentObserverImpact = Integer.MAX_VALUE;
+
+ // Find observer with least user impact
+ for (int oIndex = 0; oIndex < mAllObservers.size(); oIndex++) {
+ ObserverInternal observer = mAllObservers.valueAt(oIndex);
+ PackageHealthObserver registeredObserver = observer.registeredObserver;
+ if (registeredObserver != null
+ && observer.onPackageFailureLocked(
+ versionedPackage.getPackageName())) {
+ int impact = registeredObserver.onHealthCheckFailed(
+ versionedPackage, failureReason);
+ if (impact != PackageHealthObserverImpact.USER_IMPACT_NONE
+ && impact < currentObserverImpact) {
+ currentObserverToNotify = registeredObserver;
+ currentObserverImpact = impact;
+ }
}
}
- }
- // Execute action with least user impact
- if (currentObserverToNotify != null) {
- currentObserverToNotify.execute(versionedPackage, failureReason);
+ // Execute action with least user impact
+ if (currentObserverToNotify != null) {
+ currentObserverToNotify.execute(versionedPackage, failureReason);
+ }
}
}
}
});
}
+ /**
+ * For native crashes or explicit health check failures, call directly into each observer to
+ * mitigate the error without going through failure threshold logic.
+ */
+ private void handleFailureImmediately(List<VersionedPackage> packages,
+ @FailureReasons int failureReason) {
+ VersionedPackage failingPackage = packages.size() > 0 ? packages.get(0) : null;
+ PackageHealthObserver currentObserverToNotify = null;
+ int currentObserverImpact = Integer.MAX_VALUE;
+ for (ObserverInternal observer: mAllObservers.values()) {
+ PackageHealthObserver registeredObserver = observer.registeredObserver;
+ if (registeredObserver != null) {
+ int impact = registeredObserver.onHealthCheckFailed(
+ failingPackage, failureReason);
+ if (impact != PackageHealthObserverImpact.USER_IMPACT_NONE
+ && impact < currentObserverImpact) {
+ currentObserverToNotify = registeredObserver;
+ currentObserverImpact = impact;
+ }
+ }
+ }
+ if (currentObserverToNotify != null) {
+ currentObserverToNotify.execute(failingPackage, failureReason);
+ }
+ }
+
// TODO(b/120598832): Optimize write? Maybe only write a separate smaller file? Also
// avoid holding lock?
// This currently adds about 7ms extra to shutdown thread
@@ -400,6 +442,37 @@ public class PackageWatchdog {
}
}
+ /**
+ * This method should be only called on mShortTaskHandler, since it modifies
+ * {@link #mNumberOfNativeCrashPollsRemaining}.
+ */
+ private void checkAndMitigateNativeCrashes() {
+ mNumberOfNativeCrashPollsRemaining--;
+ // Check if native watchdog reported a crash
+ if ("1".equals(SystemProperties.get("sys.init.updatable_crashing"))) {
+ // We rollback everything available when crash is unattributable
+ onPackageFailure(Collections.EMPTY_LIST, FAILURE_REASON_NATIVE_CRASH);
+ // we stop polling after an attempt to execute rollback, regardless of whether the
+ // attempt succeeds or not
+ } else {
+ if (mNumberOfNativeCrashPollsRemaining > 0) {
+ mShortTaskHandler.postDelayed(() -> checkAndMitigateNativeCrashes(),
+ NATIVE_CRASH_POLLING_INTERVAL_MILLIS);
+ }
+ }
+ }
+
+ /**
+ * Since this method can eventually trigger a rollback, it should be called
+ * only once boot has completed {@code onBootCompleted} and not earlier, because the install
+ * session must be entirely completed before we try to rollback.
+ */
+ public void scheduleCheckAndMitigateNativeCrashes() {
+ Slog.i(TAG, "Scheduling " + mNumberOfNativeCrashPollsRemaining + " polls to check "
+ + "and mitigate native crashes");
+ mShortTaskHandler.post(()->checkAndMitigateNativeCrashes());
+ }
+
/** Possible severity values of the user impact of a {@link PackageHealthObserver#execute}. */
@Retention(SOURCE)
@IntDef(value = {PackageHealthObserverImpact.USER_IMPACT_NONE,
@@ -422,17 +495,28 @@ public class PackageWatchdog {
/**
* Called when health check fails for the {@code versionedPackage}.
*
+ * @param versionedPackage the package that is failing. This may be null if a native
+ * service is crashing.
+ * @param failureReason the type of failure that is occurring.
+ *
+ *
* @return any one of {@link PackageHealthObserverImpact} to express the impact
* to the user on {@link #execute}
*/
- @PackageHealthObserverImpact int onHealthCheckFailed(VersionedPackage versionedPackage);
+ @PackageHealthObserverImpact int onHealthCheckFailed(
+ @Nullable VersionedPackage versionedPackage,
+ @FailureReasons int failureReason);
/**
* Executes mitigation for {@link #onHealthCheckFailed}.
*
+ * @param versionedPackage the package that is failing. This may be null if a native
+ * service is crashing.
+ * @param failureReason the type of failure that is occurring.
* @return {@code true} if action was executed successfully, {@code false} otherwise
*/
- boolean execute(VersionedPackage versionedPackage, @FailureReasons int failureReason);
+ boolean execute(@Nullable VersionedPackage versionedPackage,
+ @FailureReasons int failureReason);
// TODO(b/120598832): Ensure uniqueness?
/**
@@ -448,6 +532,17 @@ public class PackageWatchdog {
default boolean isPersistent() {
return false;
}
+
+ /**
+ * Returns {@code true} if this observer wishes to observe the given package, {@code false}
+ * otherwise
+ *
+ * <p> A persistent observer may choose to start observing certain failing packages, even if
+ * it has not explicitly asked to watch the package with {@link #startObservingHealth}.
+ */
+ default boolean mayObservePackage(String packageName) {
+ return false;
+ }
}
long getTriggerFailureCount() {
@@ -784,13 +879,8 @@ public class PackageWatchdog {
Slog.wtf(TAG, "NetworkStack failed but could not find its package");
return;
}
- // This is a severe failure and recovery should be attempted immediately.
- // TODO: have a better way to handle such failures.
final List<VersionedPackage> pkgList = Collections.singletonList(pkg);
- final long failureCount = getTriggerFailureCount();
- for (int i = 0; i < failureCount; i++) {
- onPackageFailure(pkgList, FAILURE_REASON_EXPLICIT_HEALTH_CHECK);
- }
+ onPackageFailure(pkgList, FAILURE_REASON_EXPLICIT_HEALTH_CHECK);
});
}
@@ -937,6 +1027,11 @@ public class PackageWatchdog {
*/
@GuardedBy("mLock")
public boolean onPackageFailureLocked(String packageName) {
+ if (packages.get(packageName) == null && registeredObserver.isPersistent()
+ && registeredObserver.mayObservePackage(packageName)) {
+ packages.put(packageName, sPackageWatchdog.newMonitoredPackage(
+ packageName, DEFAULT_OBSERVING_DURATION_MS, false));
+ }
MonitoredPackage p = packages.get(packageName);
if (p != null) {
return p.onFailureLocked();
diff --git a/services/core/java/com/android/server/StorageManagerService.java b/services/core/java/com/android/server/StorageManagerService.java
index 822fc90cd78e..22fa8ff4a0fa 100644
--- a/services/core/java/com/android/server/StorageManagerService.java
+++ b/services/core/java/com/android/server/StorageManagerService.java
@@ -20,6 +20,7 @@ import static android.Manifest.permission.INSTALL_PACKAGES;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
+import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
import static android.app.AppOpsManager.MODE_ALLOWED;
import static android.app.AppOpsManager.OP_LEGACY_STORAGE;
import static android.app.AppOpsManager.OP_READ_EXTERNAL_STORAGE;
@@ -49,6 +50,7 @@ import static org.xmlpull.v1.XmlPullParser.START_TAG;
import android.Manifest;
import android.annotation.Nullable;
import android.app.ActivityManager;
+import android.app.ActivityManagerInternal;
import android.app.AppOpsManager;
import android.app.IActivityManager;
import android.app.KeyguardManager;
@@ -116,6 +118,7 @@ import android.sysprop.VoldProperties;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.ArrayMap;
+import android.util.ArraySet;
import android.util.AtomicFile;
import android.util.DataUnit;
import android.util.FeatureFlagUtils;
@@ -141,6 +144,7 @@ import com.android.internal.util.HexDump;
import com.android.internal.util.IndentingPrintWriter;
import com.android.internal.util.Preconditions;
import com.android.internal.widget.LockPatternUtils;
+import com.android.server.pm.Installer;
import com.android.server.storage.AppFuseBridge;
import com.android.server.storage.StorageSessionController;
import com.android.server.storage.StorageSessionController.ExternalStorageServiceException;
@@ -253,6 +257,11 @@ class StorageManagerService extends IStorageManager.Stub
public void onCleanupUser(int userHandle) {
mStorageManagerService.onCleanupUser(userHandle);
}
+
+ @Override
+ public void onStopUser(int userHandle) {
+ mStorageManagerService.onStopUser(userHandle);
+ }
}
private static final boolean DEBUG_EVENTS = false;
@@ -359,6 +368,8 @@ class StorageManagerService extends IStorageManager.Stub
private volatile int mCurrentUserId = UserHandle.USER_SYSTEM;
+ private final Installer mInstaller;
+
/** Holding lock for AppFuse business */
private final Object mAppFuseLock = new Object();
@@ -1075,6 +1086,15 @@ class StorageManagerService extends IStorageManager.Stub
}
}
+ private void onStopUser(int userId) {
+ Slog.i(TAG, "onStopUser " + userId);
+ try {
+ mStorageSessionController.onUserStopping(userId);
+ } catch (Exception e) {
+ Slog.wtf(TAG, e);
+ }
+ }
+
private boolean supportsBlockCheckpoint() throws RemoteException {
enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
return mVold.supportsBlockCheckpoint();
@@ -1228,6 +1248,13 @@ class StorageManagerService extends IStorageManager.Stub
vol.state = newState;
onVolumeStateChangedLocked(vol, oldState, newState);
}
+ try {
+ if (vol.type == VolumeInfo.TYPE_PRIVATE && state == VolumeInfo.STATE_MOUNTED) {
+ mInstaller.onPrivateVolumeMounted(vol.getFsUuid());
+ }
+ } catch (Installer.InstallerException e) {
+ Slog.i(TAG, "Failed when private volume mounted " + vol, e);
+ }
}
}
@@ -1273,6 +1300,13 @@ class StorageManagerService extends IStorageManager.Stub
if (vol != null) {
mStorageSessionController.onVolumeRemove(vol);
+ try {
+ if (vol.type == VolumeInfo.TYPE_PRIVATE) {
+ mInstaller.onPrivateVolumeRemoved(vol.getFsUuid());
+ }
+ } catch (Installer.InstallerException e) {
+ Slog.i(TAG, "Failed when private volume unmounted " + vol, e);
+ }
}
}
};
@@ -1309,6 +1343,15 @@ class StorageManagerService extends IStorageManager.Stub
Slog.d(TAG, "System booted in core-only mode; ignoring volume " + vol.getId());
return;
}
+ final ActivityManagerInternal amInternal =
+ LocalServices.getService(ActivityManagerInternal.class);
+
+ if (mIsFuseEnabled && vol.mountUserId >= 0
+ && !amInternal.isUserRunning(vol.mountUserId, 0)) {
+ Slog.d(TAG, "Ignoring volume " + vol.getId() + " because user "
+ + Integer.toString(vol.mountUserId) + " is no longer running.");
+ return;
+ }
if (vol.type == VolumeInfo.TYPE_EMULATED) {
final StorageManager storage = mContext.getSystemService(StorageManager.class);
@@ -1559,10 +1602,8 @@ class StorageManagerService extends IStorageManager.Stub
// Snapshot feature flag used for this boot
SystemProperties.set(StorageManager.PROP_ISOLATED_STORAGE_SNAPSHOT, Boolean.toString(
SystemProperties.getBoolean(StorageManager.PROP_ISOLATED_STORAGE, true)));
- SystemProperties.set(StorageManager.PROP_FUSE_SNAPSHOT, Boolean.toString(
- SystemProperties.getBoolean(StorageManager.PROP_FUSE, false)));
- mIsFuseEnabled = SystemProperties.getBoolean(StorageManager.PROP_FUSE_SNAPSHOT, false);
+ mIsFuseEnabled = SystemProperties.getBoolean(StorageManager.PROP_FUSE, false);
mContext = context;
mResolver = mContext.getContentResolver();
mCallbacks = new Callbacks(FgThread.get().getLooper());
@@ -1577,6 +1618,9 @@ class StorageManagerService extends IStorageManager.Stub
mStorageSessionController = new StorageSessionController(mContext, mIsFuseEnabled);
+ mInstaller = new Installer(mContext);
+ mInstaller.onStart();
+
// Initialize the last-fstrim tracking if necessary
File dataDir = Environment.getDataDirectory();
File systemDir = new File(dataDir, "system");
@@ -1622,12 +1666,22 @@ class StorageManagerService extends IStorageManager.Stub
* and updates PROP_FUSE (reboots if changed).
*/
private void updateFusePropFromSettings() {
- Boolean settingsFuseFlag = SystemProperties.getBoolean((FeatureFlagUtils.PERSIST_PREFIX
- + FeatureFlagUtils.SETTINGS_FUSE_FLAG), false);
- Slog.d(TAG, "The value of Settings Fuse Flag is " + settingsFuseFlag);
- if (SystemProperties.getBoolean(StorageManager.PROP_FUSE, false) != settingsFuseFlag) {
+ String settingsFuseFlag = SystemProperties.get(StorageManager.PROP_SETTINGS_FUSE);
+ Slog.d(TAG, "The value of Settings Fuse Flag is "
+ + (settingsFuseFlag == null || settingsFuseFlag.isEmpty()
+ ? "null" : settingsFuseFlag));
+ // Set default value of PROP_SETTINGS_FUSE and PROP_FUSE if it
+ // is unset (neither true nor false, this happens only on the first boot
+ // after wiping data partition).
+ if (settingsFuseFlag == null || settingsFuseFlag.isEmpty()) {
+ SystemProperties.set(StorageManager.PROP_SETTINGS_FUSE, "false");
+ SystemProperties.set(StorageManager.PROP_FUSE, "false");
+ return;
+ }
+
+ if (!SystemProperties.get(StorageManager.PROP_FUSE).equals(settingsFuseFlag)) {
Slog.d(TAG, "Set persist.sys.fuse to " + settingsFuseFlag);
- SystemProperties.set(StorageManager.PROP_FUSE, Boolean.toString(settingsFuseFlag));
+ SystemProperties.set(StorageManager.PROP_FUSE, settingsFuseFlag);
// Perform hard reboot to kick policy into place
mContext.getSystemService(PowerManager.class).reboot("Reboot device for FUSE system"
+ "property change to take effect");
@@ -1940,6 +1994,13 @@ class StorageManagerService extends IStorageManager.Stub
try {
mVold.unmount(vol.id);
mStorageSessionController.onVolumeUnmount(vol);
+ try {
+ if (vol.type == VolumeInfo.TYPE_PRIVATE) {
+ mInstaller.onPrivateVolumeRemoved(vol.getFsUuid());
+ }
+ } catch (Installer.InstallerException e) {
+ Slog.e(TAG, "Failed unmount mirror data", e);
+ }
} catch (Exception e) {
Slog.wtf(TAG, e);
}
@@ -2229,6 +2290,11 @@ class StorageManagerService extends IStorageManager.Stub
}
private void remountUidExternalStorage(int uid, int mode) {
+ if (uid == Process.SYSTEM_UID) {
+ // No need to remount uid for system because it has all access anyways
+ return;
+ }
+
try {
mVold.remountUid(uid, mode);
} catch (Exception e) {
@@ -3067,14 +3133,6 @@ class StorageManagerService extends IStorageManager.Stub
@Override
public void mkdirs(String callingPkg, String appPath) {
- if (mIsFuseEnabled) {
- // TODO(b/144332951): Calling into Vold is risky because the FUSE daemon can go down
- // anytime and Vold will hang forever. We should either remove this call
- // or at least call into the FUSE daemon to mkdir instead
- Slog.w(TAG, "Not making dir for package " + callingPkg + " with path " + appPath);
- return;
- }
-
final int callingUid = Binder.getCallingUid();
final int userId = UserHandle.getUserId(callingUid);
final UserEnvironment userEnv = new UserEnvironment(userId);
@@ -3131,16 +3189,20 @@ class StorageManagerService extends IStorageManager.Stub
final boolean forWrite = (flags & StorageManager.FLAG_FOR_WRITE) != 0;
final boolean realState = (flags & StorageManager.FLAG_REAL_STATE) != 0;
final boolean includeInvisible = (flags & StorageManager.FLAG_INCLUDE_INVISIBLE) != 0;
+ final boolean includeRecent = (flags & StorageManager.FLAG_INCLUDE_RECENT) != 0;
// Report all volumes as unmounted until we've recorded that user 0 has unlocked. There
// are no guarantees that callers will see a consistent view of the volume before that
// point
final boolean systemUserUnlocked = isSystemUnlocked(UserHandle.USER_SYSTEM);
+ final boolean userIsDemo;
final boolean userKeyUnlocked;
final boolean storagePermission;
final long token = Binder.clearCallingIdentity();
try {
+ userIsDemo = LocalServices.getService(UserManagerInternal.class)
+ .getUserInfo(userId).isDemo();
userKeyUnlocked = isUserKeyUnlocked(userId);
storagePermission = mStorageManagerInternal.hasExternalStorage(uid, packageName);
} finally {
@@ -3150,6 +3212,7 @@ class StorageManagerService extends IStorageManager.Stub
boolean foundPrimary = false;
final ArrayList<StorageVolume> res = new ArrayList<>();
+ final ArraySet<String> resUuids = new ArraySet<>();
synchronized (mLock) {
for (int i = 0; i < mVolumes.size(); i++) {
final VolumeInfo vol = mVolumes.valueAt(i);
@@ -3192,9 +3255,45 @@ class StorageManagerService extends IStorageManager.Stub
} else {
res.add(userVol);
}
+ resUuids.add(userVol.getUuid());
+ }
+
+ if (includeRecent) {
+ final long lastWeek = System.currentTimeMillis() - DateUtils.WEEK_IN_MILLIS;
+ for (int i = 0; i < mRecords.size(); i++) {
+ final VolumeRecord rec = mRecords.valueAt(i);
+
+ // Skip if we've already included it above
+ if (resUuids.contains(rec.fsUuid)) continue;
+
+ // Treat as recent if mounted within the last week
+ if (rec.lastSeenMillis > 0 && rec.lastSeenMillis < lastWeek) {
+ final StorageVolume userVol = rec.buildStorageVolume(mContext);
+ res.add(userVol);
+ resUuids.add(userVol.getUuid());
+ }
+ }
}
}
+ // Synthesize a volume for preloaded media under demo users, so that
+ // it's scanned into MediaStore
+ if (userIsDemo) {
+ final String id = "demo";
+ final File path = Environment.getDataPreloadsMediaDirectory();
+ final boolean primary = false;
+ final boolean removable = false;
+ final boolean emulated = true;
+ final boolean allowMassStorage = false;
+ final long maxFileSize = 0;
+ final UserHandle user = new UserHandle(userId);
+ final String envState = Environment.MEDIA_MOUNTED_READ_ONLY;
+ final String description = mContext.getString(android.R.string.unknownName);
+
+ res.add(new StorageVolume(id, path, path, description, primary, removable,
+ emulated, allowMassStorage, maxFileSize, user, id, envState));
+ }
+
if (!foundPrimary) {
Slog.w(TAG, "No primary storage defined yet; hacking together a stub");
@@ -3399,7 +3498,13 @@ class StorageManagerService extends IStorageManager.Stub
public void opChanged(int op, int uid, String packageName) throws RemoteException {
if (!ENABLE_ISOLATED_STORAGE) return;
- remountUidExternalStorage(uid, getMountMode(uid, packageName));
+ int mountMode = getMountMode(uid, packageName);
+ boolean isUidActive = LocalServices.getService(ActivityManagerInternal.class)
+ .getUidProcessState(uid) != PROCESS_STATE_NONEXISTENT;
+
+ if (isUidActive) {
+ remountUidExternalStorage(uid, mountMode);
+ }
}
};
@@ -3788,7 +3893,7 @@ class StorageManagerService extends IStorageManager.Stub
}
}
if ((hasInstall || hasInstallOp) && hasWrite) {
- return Zygote.MOUNT_EXTERNAL_WRITE;
+ return Zygote.MOUNT_EXTERNAL_INSTALLER;
}
// Otherwise we're willing to give out sandboxed or non-sandboxed if
@@ -4092,6 +4197,13 @@ class StorageManagerService extends IStorageManager.Stub
}
}
+ @Override
+ public void resetUser(int userId) {
+ // TODO(b/145931219): ideally, we only reset storage for the user in question,
+ // but for now, reset everything.
+ mHandler.obtainMessage(H_RESET).sendToTarget();
+ }
+
public boolean hasExternalStorage(int uid, String packageName) {
// No need to check for system uid. This avoids a deadlock between
// PackageManagerService and AppOpsService.
diff --git a/services/core/java/com/android/server/SystemService.java b/services/core/java/com/android/server/SystemService.java
index 5e659b64dbbe..c5409f85bde3 100644
--- a/services/core/java/com/android/server/SystemService.java
+++ b/services/core/java/com/android/server/SystemService.java
@@ -29,6 +29,10 @@ import android.os.UserManager;
import com.android.server.pm.UserManagerService;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.List;
+
/**
* The base class for services running in the system process. Override and implement
* the lifecycle event callback methods as needed.
@@ -164,6 +168,25 @@ public abstract class SystemService {
}
/**
+ * Helper method used to dump which users are {@link #onStartUser(UserInfo) supported}.
+ */
+ protected void dumpSupportedUsers(@NonNull PrintWriter pw, @NonNull String prefix) {
+ final List<UserInfo> allUsers = UserManager.get(mContext).getUsers();
+ final List<Integer> supportedUsers = new ArrayList<>(allUsers.size());
+ for (UserInfo user : allUsers) {
+ supportedUsers.add(user.id);
+ }
+ if (allUsers.isEmpty()) {
+ pw.print(prefix); pw.println("No supported users");
+ } else {
+ final int size = supportedUsers.size();
+ pw.print(prefix); pw.print(size); pw.print(" supported user");
+ if (size > 1) pw.print("s");
+ pw.print(": "); pw.println(supportedUsers);
+ }
+ }
+
+ /**
* @deprecated subclasses should extend {@link #onStartUser(UserInfo)} instead (which by default
* calls this method).
*/
diff --git a/services/core/java/com/android/server/TelephonyRegistry.java b/services/core/java/com/android/server/TelephonyRegistry.java
index 6105c7422153..13eb55665741 100644
--- a/services/core/java/com/android/server/TelephonyRegistry.java
+++ b/services/core/java/com/android/server/TelephonyRegistry.java
@@ -16,6 +16,7 @@
package com.android.server;
+import static android.telephony.SubscriptionManager.INVALID_SIM_SLOT_INDEX;
import static android.telephony.TelephonyManager.ACTION_MULTI_SIM_CONFIG_CHANGED;
import static android.telephony.TelephonyRegistryManager.SIM_ACTIVATION_TYPE_DATA;
import static android.telephony.TelephonyRegistryManager.SIM_ACTIVATION_TYPE_VOICE;
@@ -31,7 +32,6 @@ import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.LinkProperties;
-import android.net.NetworkCapabilities;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
@@ -59,6 +59,7 @@ import android.telephony.PreciseDisconnectCause;
import android.telephony.Rlog;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
+import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.telephony.data.ApnSetting;
@@ -97,7 +98,7 @@ import java.util.NoSuchElementException;
* and 15973975 by saving the phoneId of the registrant and then using the
* phoneId when deciding to to make a callback. This is necessary because
* a subId changes from to a dummy value when a SIM is removed and thus won't
- * compare properly. Because SubscriptionManager.getPhoneId(int subId) handles
+ * compare properly. Because getPhoneIdFromSubId(int subId) handles
* the dummy value conversion we properly do the callbacks.
*
* Eventually we may want to remove the notion of dummy value but for now this
@@ -131,7 +132,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
int subId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
- int phoneId = SubscriptionManager.INVALID_PHONE_INDEX;
+ int phoneId = SubscriptionManager.INVALID_SIM_SLOT_INDEX;
boolean matchPhoneStateListenerEvent(int events) {
return (callback != null) && ((events & this.events) != 0);
@@ -210,8 +211,6 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
private int[] mDataConnectionNetworkType;
- private int[] mOtaspMode;
-
private ArrayList<List<CellInfo>> mCellInfo = null;
private Map<Integer, List<EmergencyNumber>> mEmergencyNumberList;
@@ -231,7 +230,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
private int mDefaultSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
- private int mDefaultPhoneId = SubscriptionManager.INVALID_PHONE_INDEX;
+ private int mDefaultPhoneId = SubscriptionManager.INVALID_SIM_SLOT_INDEX;
private int[] mRingingCallState;
@@ -260,7 +259,9 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
private final LocalLog mListenLog = new LocalLog(100);
- private PreciseDataConnectionState[] mPreciseDataConnectionState;
+ // Per-phoneMap of APN Type to DataConnectionState
+ private List<Map<String, PreciseDataConnectionState>> mPreciseDataConnectionStates =
+ new ArrayList<Map<String, PreciseDataConnectionState>>();
// Nothing here yet, but putting it here in case we want to add more in the future.
static final int ENFORCE_COARSE_LOCATION_PERMISSION_MASK = 0;
@@ -357,8 +358,8 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX,
SubscriptionManager.getDefaultSubscriptionId());
int newDefaultPhoneId = intent.getIntExtra(
- PhoneConstants.PHONE_KEY,
- SubscriptionManager.getPhoneId(newDefaultSubId));
+ SubscriptionManager.EXTRA_SLOT_INDEX,
+ getPhoneIdFromSubId(newDefaultSubId));
if (DBG) {
log("onReceive:current mDefaultSubId=" + mDefaultSubId
+ " current mDefaultPhoneId=" + mDefaultPhoneId
@@ -405,7 +406,6 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
mCallForwarding = copyOf(mCallForwarding, mNumPhones);
mCellLocation = copyOf(mCellLocation, mNumPhones);
mSrvccState = copyOf(mSrvccState, mNumPhones);
- mOtaspMode = copyOf(mOtaspMode, mNumPhones);
mPreciseCallState = copyOf(mPreciseCallState, mNumPhones);
mForegroundCallState = copyOf(mForegroundCallState, mNumPhones);
mBackgroundCallState = copyOf(mBackgroundCallState, mNumPhones);
@@ -415,7 +415,6 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
mCallQuality = copyOf(mCallQuality, mNumPhones);
mCallNetworkType = copyOf(mCallNetworkType, mNumPhones);
mCallAttributes = copyOf(mCallAttributes, mNumPhones);
- mPreciseDataConnectionState = copyOf(mPreciseDataConnectionState, mNumPhones);
mOutgoingCallEmergencyNumber = copyOf(mOutgoingCallEmergencyNumber, mNumPhones);
mOutgoingSmsEmergencyNumber = copyOf(mOutgoingSmsEmergencyNumber, mNumPhones);
@@ -423,6 +422,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
if (mNumPhones < oldNumPhones) {
cutListToSize(mCellInfo, mNumPhones);
cutListToSize(mImsReasonInfo, mNumPhones);
+ cutListToSize(mPreciseDataConnectionStates, mNumPhones);
return;
}
@@ -443,18 +443,17 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
mCellInfo.add(i, null);
mImsReasonInfo.add(i, null);
mSrvccState[i] = TelephonyManager.SRVCC_STATE_HANDOVER_NONE;
- mOtaspMode[i] = TelephonyManager.OTASP_UNKNOWN;
mCallDisconnectCause[i] = DisconnectCause.NOT_VALID;
mCallPreciseDisconnectCause[i] = PreciseDisconnectCause.NOT_VALID;
- mCallQuality[i] = new CallQuality();
+ mCallQuality[i] = createCallQuality();
mCallAttributes[i] = new CallAttributes(new PreciseCallState(),
- TelephonyManager.NETWORK_TYPE_UNKNOWN, new CallQuality());
+ TelephonyManager.NETWORK_TYPE_UNKNOWN, createCallQuality());
mCallNetworkType[i] = TelephonyManager.NETWORK_TYPE_UNKNOWN;
mPreciseCallState[i] = new PreciseCallState();
mRingingCallState[i] = PreciseCallState.PRECISE_CALL_STATE_IDLE;
mForegroundCallState[i] = PreciseCallState.PRECISE_CALL_STATE_IDLE;
mBackgroundCallState[i] = PreciseCallState.PRECISE_CALL_STATE_IDLE;
- mPreciseDataConnectionState[i] = new PreciseDataConnectionState();
+ mPreciseDataConnectionStates.add(new HashMap<String, PreciseDataConnectionState>());
}
// Note that location can be null for non-phone builds like
@@ -506,7 +505,6 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
mCallForwarding = new boolean[numPhones];
mCellLocation = new Bundle[numPhones];
mSrvccState = new int[numPhones];
- mOtaspMode = new int[numPhones];
mPreciseCallState = new PreciseCallState[numPhones];
mForegroundCallState = new int[numPhones];
mBackgroundCallState = new int[numPhones];
@@ -516,7 +514,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
mCallQuality = new CallQuality[numPhones];
mCallNetworkType = new int[numPhones];
mCallAttributes = new CallAttributes[numPhones];
- mPreciseDataConnectionState = new PreciseDataConnectionState[numPhones];
+ mPreciseDataConnectionStates = new ArrayList<>();
mCellInfo = new ArrayList<>();
mImsReasonInfo = new ArrayList<>();
mEmergencyNumberList = new HashMap<>();
@@ -538,18 +536,17 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
mCellInfo.add(i, null);
mImsReasonInfo.add(i, null);
mSrvccState[i] = TelephonyManager.SRVCC_STATE_HANDOVER_NONE;
- mOtaspMode[i] = TelephonyManager.OTASP_UNKNOWN;
mCallDisconnectCause[i] = DisconnectCause.NOT_VALID;
mCallPreciseDisconnectCause[i] = PreciseDisconnectCause.NOT_VALID;
- mCallQuality[i] = new CallQuality();
+ mCallQuality[i] = createCallQuality();
mCallAttributes[i] = new CallAttributes(new PreciseCallState(),
- TelephonyManager.NETWORK_TYPE_UNKNOWN, new CallQuality());
+ TelephonyManager.NETWORK_TYPE_UNKNOWN, createCallQuality());
mCallNetworkType[i] = TelephonyManager.NETWORK_TYPE_UNKNOWN;
mPreciseCallState[i] = new PreciseCallState();
mRingingCallState[i] = PreciseCallState.PRECISE_CALL_STATE_IDLE;
mForegroundCallState[i] = PreciseCallState.PRECISE_CALL_STATE_IDLE;
mBackgroundCallState[i] = PreciseCallState.PRECISE_CALL_STATE_IDLE;
- mPreciseDataConnectionState[i] = new PreciseDataConnectionState();
+ mPreciseDataConnectionStates.add(new HashMap<String, PreciseDataConnectionState>());
}
// Note that location can be null for non-phone builds like
@@ -768,7 +765,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
return;
}
- int phoneId = SubscriptionManager.getPhoneId(subId);
+ int phoneId = getPhoneIdFromSubId(subId);
synchronized (mRecords) {
// register
IBinder b = callback.asBinder();
@@ -880,13 +877,6 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
remove(r.binder);
}
}
- if ((events & PhoneStateListener.LISTEN_OTASP_CHANGED) != 0) {
- try {
- r.callback.onOtaspChanged(mOtaspMode[phoneId]);
- } catch (RemoteException ex) {
- remove(r.binder);
- }
- }
if (validateEventsAndUserLocked(r, PhoneStateListener.LISTEN_CELL_INFO)) {
try {
if (DBG_LOC) log("listen: mCellInfo[" + phoneId + "] = "
@@ -922,8 +912,10 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
}
if ((events & PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE) != 0) {
try {
- r.callback.onPreciseDataConnectionStateChanged(
- mPreciseDataConnectionState[phoneId]);
+ for (PreciseDataConnectionState pdcs
+ : mPreciseDataConnectionStates.get(phoneId).values()) {
+ r.callback.onPreciseDataConnectionStateChanged(pdcs);
+ }
} catch (RemoteException ex) {
remove(r.binder);
}
@@ -937,7 +929,8 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
}
if ((events & PhoneStateListener.LISTEN_VOICE_ACTIVATION_STATE) !=0) {
try {
- r.callback.onVoiceActivationStateChanged(mVoiceActivationState[phoneId]);
+ r.callback.onVoiceActivationStateChanged(
+ mVoiceActivationState[phoneId]);
} catch (RemoteException ex) {
remove(r.binder);
}
@@ -1099,7 +1092,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
// Called only by Telecomm to communicate call state across different phone accounts. So
// there is no need to add a valid subId or slotId.
broadcastCallStateChanged(state, phoneNumber,
- SubscriptionManager.INVALID_PHONE_INDEX,
+ SubscriptionManager.INVALID_SIM_SLOT_INDEX,
SubscriptionManager.INVALID_SUBSCRIPTION_ID);
}
@@ -1313,7 +1306,8 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
// only CarrierService with carrier privilege rule should have the permission
int[] subIds = Arrays.stream(SubscriptionManager.from(mContext)
.getActiveSubscriptionIdList(false))
- .filter(i -> TelephonyPermissions.checkCarrierPrivilegeForSubId(i)).toArray();
+ .filter(i -> TelephonyPermissions.checkCarrierPrivilegeForSubId(mContext,
+ i)).toArray();
if (ArrayUtils.isEmpty(subIds)) {
loge("notifyCarrierNetworkChange without carrier privilege");
// the active subId does not have carrier privilege.
@@ -1323,7 +1317,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
synchronized (mRecords) {
mCarrierNetworkChangeState = active;
for (int subId : subIds) {
- int phoneId = SubscriptionManager.getPhoneId(subId);
+ int phoneId = getPhoneIdFromSubId(subId);
if (VDBG) {
log("notifyCarrierNetworkChange: active=" + active + "subId: " + subId);
@@ -1356,7 +1350,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
log("notifyCellInfoForSubscriber: subId=" + subId
+ " cellInfo=" + cellInfo);
}
- int phoneId = SubscriptionManager.getPhoneId(subId);
+ int phoneId = getPhoneIdFromSubId(subId);
synchronized (mRecords) {
if (validatePhoneId(phoneId)) {
mCellInfo.set(phoneId, cellInfo);
@@ -1447,7 +1441,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
log("notifyCallForwardingChangedForSubscriber: subId=" + subId
+ " cfi=" + cfi);
}
- int phoneId = SubscriptionManager.getPhoneId(subId);
+ int phoneId = getPhoneIdFromSubId(subId);
synchronized (mRecords) {
if (validatePhoneId(phoneId)) {
mCallForwarding[phoneId] = cfi;
@@ -1475,7 +1469,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
if (!checkNotifyPermission("notifyDataActivity()" )) {
return;
}
- int phoneId = SubscriptionManager.getPhoneId(subId);
+ int phoneId = getPhoneIdFromSubId(subId);
synchronized (mRecords) {
if (validatePhoneId(phoneId)) {
mDataActivity[phoneId] = state;
@@ -1495,30 +1489,38 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
}
}
- public void notifyDataConnection(int state, boolean isDataAllowed, String apn, String apnType,
- LinkProperties linkProperties,
- NetworkCapabilities networkCapabilities, int networkType,
- boolean roaming) {
- notifyDataConnectionForSubscriber(SubscriptionManager.DEFAULT_PHONE_INDEX,
- SubscriptionManager.DEFAULT_SUBSCRIPTION_ID, state,
- isDataAllowed, apn, apnType, linkProperties,
- networkCapabilities, networkType, roaming);
- }
-
- public void notifyDataConnectionForSubscriber(int phoneId, int subId, int state,
- boolean isDataAllowed,
- String apn, String apnType,
- LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
- int networkType, boolean roaming) {
+ /**
+ * Send a notification to registrants that the data connection state has changed.
+ *
+ * @param phoneId the phoneId carrying the data connection
+ * @param subId the subscriptionId for the data connection
+ * @param apnType the APN type that triggered a change in the data connection
+ * @param preciseState a PreciseDataConnectionState that has info about the data connection
+ */
+ public void notifyDataConnectionForSubscriber(
+ int phoneId, int subId, String apnType, PreciseDataConnectionState preciseState) {
if (!checkNotifyPermission("notifyDataConnection()" )) {
return;
}
+
+ String apn = "";
+ int state = TelephonyManager.DATA_UNKNOWN;
+ int networkType = TelephonyManager.NETWORK_TYPE_UNKNOWN;
+ LinkProperties linkProps = null;
+
+ if (preciseState != null) {
+ apn = preciseState.getDataConnectionApn();
+ state = preciseState.getState();
+ networkType = preciseState.getNetworkType();
+ linkProps = preciseState.getDataConnectionLinkProperties();
+ }
if (VDBG) {
log("notifyDataConnectionForSubscriber: subId=" + subId
- + " state=" + state + " isDataAllowed=" + isDataAllowed
- + "' apn='" + apn + "' apnType=" + apnType + " networkType=" + networkType
- + " mRecords.size()=" + mRecords.size());
+ + " state=" + state + "' apn='" + apn
+ + "' apnType=" + apnType + " networkType=" + networkType
+ + "' preciseState=" + preciseState);
}
+
synchronized (mRecords) {
if (validatePhoneId(phoneId)) {
// We only call the callback when the change is for default APN type.
@@ -1550,38 +1552,48 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
mDataConnectionState[phoneId] = state;
mDataConnectionNetworkType[phoneId] = networkType;
}
- mPreciseDataConnectionState[phoneId] = new PreciseDataConnectionState(
- state, networkType,
- ApnSetting.getApnTypesBitmaskFromString(apnType), apn,
- linkProperties, DataFailCause.NONE);
- for (Record r : mRecords) {
- if (r.matchPhoneStateListenerEvent(
- PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE)
- && idMatch(r.subId, subId, phoneId)) {
- try {
- r.callback.onPreciseDataConnectionStateChanged(
- mPreciseDataConnectionState[phoneId]);
- } catch (RemoteException ex) {
- mRemoveList.add(r.binder);
+
+ boolean needsNotify = false;
+ // State has been cleared for this APN Type
+ if (preciseState == null) {
+ // We try clear the state and check if the state was previously not cleared
+ needsNotify = mPreciseDataConnectionStates.get(phoneId).remove(apnType) != null;
+ } else {
+ // We need to check to see if the state actually changed
+ PreciseDataConnectionState oldPreciseState =
+ mPreciseDataConnectionStates.get(phoneId).put(apnType, preciseState);
+ needsNotify = !preciseState.equals(oldPreciseState);
+ }
+
+ if (needsNotify) {
+ for (Record r : mRecords) {
+ if (r.matchPhoneStateListenerEvent(
+ PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE)
+ && idMatch(r.subId, subId, phoneId)) {
+ try {
+ r.callback.onPreciseDataConnectionStateChanged(preciseState);
+ } catch (RemoteException ex) {
+ mRemoveList.add(r.binder);
+ }
}
}
}
}
handleRemoveListLocked();
}
- broadcastDataConnectionStateChanged(state, isDataAllowed, apn, apnType, linkProperties,
- networkCapabilities, roaming, subId);
- broadcastPreciseDataConnectionStateChanged(state, networkType, apnType, apn,
- linkProperties, DataFailCause.NONE);
+
+ broadcastDataConnectionStateChanged(state, apn, apnType, subId);
}
+ /**
+ * Stub to satisfy the ITelephonyRegistry aidl interface; do not use this function.
+ * @see #notifyDataConnectionFailedForSubscriber
+ */
public void notifyDataConnectionFailed(String apnType) {
- notifyDataConnectionFailedForSubscriber(SubscriptionManager.DEFAULT_PHONE_INDEX,
- SubscriptionManager.DEFAULT_SUBSCRIPTION_ID,
- apnType);
+ loge("This function should not be invoked");
}
- public void notifyDataConnectionFailedForSubscriber(int phoneId, int subId, String apnType) {
+ private void notifyDataConnectionFailedForSubscriber(int phoneId, int subId, String apnType) {
if (!checkNotifyPermission("notifyDataConnectionFailed()")) {
return;
}
@@ -1591,17 +1603,20 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
}
synchronized (mRecords) {
if (validatePhoneId(phoneId)) {
- mPreciseDataConnectionState[phoneId] = new PreciseDataConnectionState(
- TelephonyManager.DATA_UNKNOWN,TelephonyManager.NETWORK_TYPE_UNKNOWN,
- ApnSetting.getApnTypesBitmaskFromString(apnType), null, null,
- DataFailCause.NONE);
+ mPreciseDataConnectionStates.get(phoneId).put(
+ apnType,
+ new PreciseDataConnectionState(
+ TelephonyManager.DATA_UNKNOWN,
+ TelephonyManager.NETWORK_TYPE_UNKNOWN,
+ ApnSetting.getApnTypesBitmaskFromString(apnType), null, null,
+ DataFailCause.NONE));
for (Record r : mRecords) {
if (r.matchPhoneStateListenerEvent(
PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE)
&& idMatch(r.subId, subId, phoneId)) {
try {
r.callback.onPreciseDataConnectionStateChanged(
- mPreciseDataConnectionState[phoneId]);
+ mPreciseDataConnectionStates.get(phoneId).get(apnType));
} catch (RemoteException ex) {
mRemoveList.add(r.binder);
}
@@ -1612,9 +1627,6 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
handleRemoveListLocked();
}
broadcastDataConnectionFailed(apnType, subId);
- broadcastPreciseDataConnectionStateChanged(TelephonyManager.DATA_UNKNOWN,
- TelephonyManager.NETWORK_TYPE_UNKNOWN, apnType, null, null,
- DataFailCause.NONE);
}
public void notifyCellLocation(Bundle cellLocation) {
@@ -1631,7 +1643,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
log("notifyCellLocationForSubscriber: subId=" + subId
+ " cellLocation=" + cellLocation);
}
- int phoneId = SubscriptionManager.getPhoneId(subId);
+ int phoneId = getPhoneIdFromSubId(subId);
synchronized (mRecords) {
if (validatePhoneId(phoneId)) {
mCellLocation[phoneId] = cellLocation;
@@ -1655,29 +1667,6 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
}
}
- public void notifyOtaspChanged(int subId, int otaspMode) {
- if (!checkNotifyPermission("notifyOtaspChanged()" )) {
- return;
- }
- int phoneId = SubscriptionManager.getPhoneId(subId);
- synchronized (mRecords) {
- if (validatePhoneId(phoneId)) {
- mOtaspMode[phoneId] = otaspMode;
- for (Record r : mRecords) {
- if (r.matchPhoneStateListenerEvent(PhoneStateListener.LISTEN_OTASP_CHANGED)
- && idMatch(r.subId, subId, phoneId)) {
- try {
- r.callback.onOtaspChanged(otaspMode);
- } catch (RemoteException ex) {
- mRemoveList.add(r.binder);
- }
- }
- }
- }
- handleRemoveListLocked();
- }
- }
-
public void notifyPreciseCallState(int phoneId, int subId, int ringingCallState,
int foregroundCallState, int backgroundCallState) {
if (!checkNotifyPermission("notifyPreciseCallState()")) {
@@ -1704,7 +1693,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
if (mPreciseCallState[phoneId].getForegroundCallState()
!= PreciseCallState.PRECISE_CALL_STATE_ACTIVE) {
mCallNetworkType[phoneId] = TelephonyManager.NETWORK_TYPE_UNKNOWN;
- mCallQuality[phoneId] = new CallQuality();
+ mCallQuality[phoneId] = createCallQuality();
}
mCallAttributes[phoneId] = new CallAttributes(mPreciseCallState[phoneId],
mCallNetworkType[phoneId], mCallQuality[phoneId]);
@@ -1732,8 +1721,6 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
}
handleRemoveListLocked();
}
- broadcastPreciseCallStateChanged(ringingCallState, foregroundCallState,
- backgroundCallState);
}
public void notifyDisconnectCause(int phoneId, int subId, int disconnectCause,
@@ -1765,7 +1752,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
if (!checkNotifyPermission("notifyImsCallDisconnectCause()")) {
return;
}
- int phoneId = SubscriptionManager.getPhoneId(subId);
+ int phoneId = getPhoneIdFromSubId(subId);
synchronized (mRecords) {
if (validatePhoneId(phoneId)) {
mImsReasonInfo.set(phoneId, imsReasonInfo);
@@ -1794,29 +1781,34 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
if (!checkNotifyPermission("notifyPreciseDataConnectionFailed()")) {
return;
}
+
+ // precise notify invokes imprecise notify
+ notifyDataConnectionFailedForSubscriber(phoneId, subId, apnType);
+
synchronized (mRecords) {
if (validatePhoneId(phoneId)) {
- mPreciseDataConnectionState[phoneId] = new PreciseDataConnectionState(
- TelephonyManager.DATA_UNKNOWN, TelephonyManager.NETWORK_TYPE_UNKNOWN,
- ApnSetting.getApnTypesBitmaskFromString(apnType), apn, null, failCause);
+ mPreciseDataConnectionStates.get(phoneId).put(
+ apnType,
+ new PreciseDataConnectionState(
+ TelephonyManager.DATA_UNKNOWN,
+ TelephonyManager.NETWORK_TYPE_UNKNOWN,
+ ApnSetting.getApnTypesBitmaskFromString(apnType), null, null,
+ failCause));
for (Record r : mRecords) {
if (r.matchPhoneStateListenerEvent(
PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE)
&& idMatch(r.subId, subId, phoneId)) {
try {
r.callback.onPreciseDataConnectionStateChanged(
- mPreciseDataConnectionState[phoneId]);
+ mPreciseDataConnectionStates.get(phoneId).get(apnType));
} catch (RemoteException ex) {
mRemoveList.add(r.binder);
}
}
}
}
-
handleRemoveListLocked();
}
- broadcastPreciseDataConnectionStateChanged(TelephonyManager.DATA_UNKNOWN,
- TelephonyManager.NETWORK_TYPE_UNKNOWN, apnType, apn, null, failCause);
}
@Override
@@ -1827,7 +1819,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
if (VDBG) {
log("notifySrvccStateChanged: subId=" + subId + " srvccState=" + state);
}
- int phoneId = SubscriptionManager.getPhoneId(subId);
+ int phoneId = getPhoneIdFromSubId(subId);
synchronized (mRecords) {
if (validatePhoneId(phoneId)) {
mSrvccState[phoneId] = state;
@@ -2072,7 +2064,6 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
}
}
-
@Override
public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
@@ -2106,12 +2097,11 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
pw.println("mCellInfo=" + mCellInfo.get(i));
pw.println("mImsCallDisconnectCause=" + mImsReasonInfo.get(i));
pw.println("mSrvccState=" + mSrvccState[i]);
- pw.println("mOtaspMode=" + mOtaspMode[i]);
pw.println("mCallPreciseDisconnectCause=" + mCallPreciseDisconnectCause[i]);
pw.println("mCallQuality=" + mCallQuality[i]);
pw.println("mCallAttributes=" + mCallAttributes[i]);
pw.println("mCallNetworkType=" + mCallNetworkType[i]);
- pw.println("mPreciseDataConnectionState=" + mPreciseDataConnectionState[i]);
+ pw.println("mPreciseDataConnectionStates=" + mPreciseDataConnectionStates.get(i));
pw.println("mOutgoingCallEmergencyNumber=" + mOutgoingCallEmergencyNumber[i]);
pw.println("mOutgoingSmsEmergencyNumber=" + mOutgoingSmsEmergencyNumber[i]);
pw.decreaseIndent();
@@ -2146,6 +2136,16 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
// the legacy intent broadcasting
//
+ // Legacy intent action.
+ /** Fired when a subscription's phone state changes. */
+ private static final String ACTION_SUBSCRIPTION_PHONE_STATE_CHANGED =
+ "android.intent.action.SUBSCRIPTION_PHONE_STATE";
+
+ // Legacy intent extra keys, copied from PhoneConstants.
+ // Used in legacy intents sent here, for backward compatibility.
+ private static final String PHONE_CONSTANTS_SLOT_KEY = "slot";
+ private static final String PHONE_CONSTANTS_SUBSCRIPTION_KEY = "subscription";
+
private void broadcastServiceStateChanged(ServiceState state, int phoneId, int subId) {
long ident = Binder.clearCallingIdentity();
try {
@@ -2162,9 +2162,10 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
state.fillInNotifierBundle(data);
intent.putExtras(data);
// Pass the subscription along with the intent.
- intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, subId);
+ intent.putExtra(PHONE_CONSTANTS_SUBSCRIPTION_KEY, subId);
intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
- intent.putExtra(PhoneConstants.SLOT_KEY, phoneId);
+ intent.putExtra(PHONE_CONSTANTS_SLOT_KEY, phoneId);
+ intent.putExtra(SubscriptionManager.EXTRA_SLOT_INDEX, phoneId);
mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
}
@@ -2183,8 +2184,8 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
Bundle data = new Bundle();
signalStrength.fillInNotifierBundle(data);
intent.putExtras(data);
- intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, subId);
- intent.putExtra(PhoneConstants.SLOT_KEY, phoneId);
+ intent.putExtra(PHONE_CONSTANTS_SUBSCRIPTION_KEY, subId);
+ intent.putExtra(PHONE_CONSTANTS_SLOT_KEY, phoneId);
mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
}
@@ -2219,13 +2220,14 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
// If a valid subId was specified, we should fire off a subId-specific state
// change intent and include the subId.
if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
- intent.setAction(PhoneConstants.ACTION_SUBSCRIPTION_PHONE_STATE_CHANGED);
- intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, subId);
+ intent.setAction(ACTION_SUBSCRIPTION_PHONE_STATE_CHANGED);
+ intent.putExtra(PHONE_CONSTANTS_SUBSCRIPTION_KEY, subId);
intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
}
// If the phoneId is invalid, the broadcast is for overall call state.
- if (phoneId != SubscriptionManager.INVALID_PHONE_INDEX) {
- intent.putExtra(PhoneConstants.SLOT_KEY, phoneId);
+ if (phoneId != SubscriptionManager.INVALID_SIM_SLOT_INDEX) {
+ intent.putExtra(PHONE_CONSTANTS_SLOT_KEY, phoneId);
+ intent.putExtra(SubscriptionManager.EXTRA_SLOT_INDEX, phoneId);
}
// Wakeup apps for the (SUBSCRIPTION_)PHONE_STATE broadcast.
@@ -2259,76 +2261,33 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
}
}
- private void broadcastDataConnectionStateChanged(int state, boolean isDataAllowed, String apn,
- String apnType, LinkProperties linkProperties,
- NetworkCapabilities networkCapabilities,
- boolean roaming, int subId) {
+ private void broadcastDataConnectionStateChanged(int state, String apn,
+ String apnType, int subId) {
// Note: not reporting to the battery stats service here, because the
// status bar takes care of that after taking into account all of the
// required info.
Intent intent = new Intent(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED);
intent.putExtra(TelephonyManager.EXTRA_STATE, dataStateToString(state));
- if (!isDataAllowed) {
- intent.putExtra(PhoneConstants.NETWORK_UNAVAILABLE_KEY, true);
- }
- if (linkProperties != null) {
- intent.putExtra(PhoneConstants.DATA_LINK_PROPERTIES_KEY, linkProperties);
- String iface = linkProperties.getInterfaceName();
- if (iface != null) {
- intent.putExtra(PhoneConstants.DATA_IFACE_NAME_KEY, iface);
- }
- }
- if (networkCapabilities != null) {
- intent.putExtra(PhoneConstants.DATA_NETWORK_CAPABILITIES_KEY, networkCapabilities);
- }
- if (roaming) intent.putExtra(PhoneConstants.DATA_NETWORK_ROAMING_KEY, true);
intent.putExtra(PhoneConstants.DATA_APN_KEY, apn);
intent.putExtra(PhoneConstants.DATA_APN_TYPE_KEY, apnType);
- intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, subId);
+ intent.putExtra(PHONE_CONSTANTS_SUBSCRIPTION_KEY, subId);
mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
}
private void broadcastDataConnectionFailed(String apnType, int subId) {
Intent intent = new Intent(TelephonyIntents.ACTION_DATA_CONNECTION_FAILED);
intent.putExtra(PhoneConstants.DATA_APN_TYPE_KEY, apnType);
- intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, subId);
+ intent.putExtra(PHONE_CONSTANTS_SUBSCRIPTION_KEY, subId);
mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
}
- private void broadcastPreciseCallStateChanged(int ringingCallState, int foregroundCallState,
- int backgroundCallState) {
- Intent intent = new Intent(TelephonyManager.ACTION_PRECISE_CALL_STATE_CHANGED);
- intent.putExtra(TelephonyManager.EXTRA_RINGING_CALL_STATE, ringingCallState);
- intent.putExtra(TelephonyManager.EXTRA_FOREGROUND_CALL_STATE, foregroundCallState);
- intent.putExtra(TelephonyManager.EXTRA_BACKGROUND_CALL_STATE, backgroundCallState);
- mContext.sendBroadcastAsUser(intent, UserHandle.ALL,
- android.Manifest.permission.READ_PRECISE_PHONE_STATE);
- }
-
- private void broadcastPreciseDataConnectionStateChanged(int state, int networkType,
- String apnType, String apn, LinkProperties linkProperties,
- @DataFailureCause int failCause) {
- Intent intent = new Intent(TelephonyManager.ACTION_PRECISE_DATA_CONNECTION_STATE_CHANGED);
- intent.putExtra(TelephonyManager.EXTRA_STATE, state);
- intent.putExtra(PhoneConstants.DATA_NETWORK_TYPE_KEY, networkType);
- if (apnType != null) intent.putExtra(PhoneConstants.DATA_APN_TYPE_KEY, apnType);
- if (apn != null) intent.putExtra(PhoneConstants.DATA_APN_KEY, apn);
- if (linkProperties != null) {
- intent.putExtra(PhoneConstants.DATA_LINK_PROPERTIES_KEY, linkProperties);
- }
- intent.putExtra(PhoneConstants.DATA_FAILURE_CAUSE_KEY, failCause);
-
- mContext.sendBroadcastAsUser(intent, UserHandle.ALL,
- android.Manifest.permission.READ_PRECISE_PHONE_STATE);
- }
-
private void enforceNotifyPermissionOrCarrierPrivilege(String method) {
if (checkNotifyPermission()) {
return;
}
- TelephonyPermissions.enforceCallingOrSelfCarrierPrivilege(
+ TelephonyPermissions.enforceCallingOrSelfCarrierPrivilege(mContext,
SubscriptionManager.getDefaultSubscriptionId(), method);
}
@@ -2719,4 +2678,22 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
}
}
+ /** Returns a new CallQuality object with default values. */
+ private static CallQuality createCallQuality() {
+ return new CallQuality(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
+ }
+
+ private int getPhoneIdFromSubId(int subId) {
+ SubscriptionManager subManager = (SubscriptionManager)
+ mContext.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
+ if (subManager == null) return INVALID_SIM_SLOT_INDEX;
+
+ if (subId == SubscriptionManager.DEFAULT_SUBSCRIPTION_ID) {
+ subId = SubscriptionManager.getDefaultSubscriptionId();
+ }
+
+ SubscriptionInfo info = subManager.getActiveSubscriptionInfo(subId);
+ if (info == null) return INVALID_SIM_SLOT_INDEX;
+ return info.getSimSlotIndex();
+ }
}
diff --git a/services/core/java/com/android/server/UiModeManagerService.java b/services/core/java/com/android/server/UiModeManagerService.java
index b1e2c0fe9586..5bec7a3f4a39 100644
--- a/services/core/java/com/android/server/UiModeManagerService.java
+++ b/services/core/java/com/android/server/UiModeManagerService.java
@@ -56,6 +56,7 @@ import android.service.vr.IVrManager;
import android.service.vr.IVrStateCallbacks;
import android.util.ArraySet;
import android.util.Slog;
+
import com.android.internal.R;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.app.DisableCarModeActivity;
@@ -73,8 +74,6 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Set;
-import static android.content.Intent.ACTION_SCREEN_OFF;
-
final class UiModeManagerService extends SystemService {
private static final String TAG = UiModeManager.class.getSimpleName();
private static final boolean LOG = false;
@@ -97,10 +96,15 @@ final class UiModeManagerService extends SystemService {
private boolean mCarModeEnabled = false;
private boolean mCharging = false;
private boolean mPowerSave = false;
+ // Do not change configuration now. wait until screen turns off.
+ // This prevents jank and activity restart when the user
+ // is actively using the device
+ private boolean mWaitForScreenOff = false;
private int mDefaultUiModeType;
private boolean mCarModeKeepsScreenOn;
private boolean mDeskModeKeepsScreenOn;
private boolean mTelevision;
+ private boolean mCar;
private boolean mWatch;
private boolean mVrHeadset;
private boolean mComputedNightMode;
@@ -208,24 +212,27 @@ final class UiModeManagerService extends SystemService {
public void onTwilightStateChanged(@Nullable TwilightState state) {
synchronized (mLock) {
if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
- final IntentFilter intentFilter =
- new IntentFilter(ACTION_SCREEN_OFF);
- getContext().registerReceiver(mOnScreenOffHandler, intentFilter);
+ if (mCar) {
+ updateLocked(0, 0);
+ } else {
+ registerScreenOffEvent();
+ }
}
}
}
};
+ /**
+ * DO NOT USE DIRECTLY
+ * see register registerScreenOffEvent and unregisterScreenOffEvent
+ */
private final BroadcastReceiver mOnScreenOffHandler = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
synchronized (mLock) {
+ // must unregister first before updating
+ unregisterScreenOffEvent();
updateLocked(0, 0);
- try {
- getContext().unregisterReceiver(mOnScreenOffHandler);
- } catch (IllegalArgumentException e) {
- // we ignore this exception if the receiver is unregistered already.
- }
}
}
};
@@ -327,6 +334,7 @@ final class UiModeManagerService extends SystemService {
final PackageManager pm = context.getPackageManager();
mTelevision = pm.hasSystemFeature(PackageManager.FEATURE_TELEVISION)
|| pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK);
+ mCar = pm.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
mWatch = pm.hasSystemFeature(PackageManager.FEATURE_WATCH);
updateNightModeFromSettings(context, res, UserHandle.getCallingUserId());
@@ -335,7 +343,7 @@ final class UiModeManagerService extends SystemService {
SystemServerInitThreadPool.submit(() -> {
synchronized (mLock) {
updateConfigurationLocked();
- sendConfigurationLocked();
+ applyConfigurationExternallyLocked();
}
}, TAG + ".onStart");
@@ -404,6 +412,22 @@ final class UiModeManagerService extends SystemService {
return oldNightMode != mNightMode;
}
+ private void registerScreenOffEvent() {
+ mWaitForScreenOff = true;
+ final IntentFilter intentFilter =
+ new IntentFilter(Intent.ACTION_SCREEN_OFF);
+ getContext().registerReceiver(mOnScreenOffHandler, intentFilter);
+ }
+
+ private void unregisterScreenOffEvent() {
+ mWaitForScreenOff = false;
+ try {
+ getContext().unregisterReceiver(mOnScreenOffHandler);
+ } catch (IllegalArgumentException e) {
+ // we ignore this exception if the receiver is unregistered already.
+ }
+ }
+
private final IUiModeManager.Stub mService = new IUiModeManager.Stub() {
@Override
public void enableCarMode(@UiModeManager.EnableCarMode int flags,
@@ -525,11 +549,7 @@ final class UiModeManagerService extends SystemService {
synchronized (mLock) {
if (mNightMode != mode) {
if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
- try {
- getContext().unregisterReceiver(mOnScreenOffHandler);
- } catch (IllegalArgumentException e) {
- // we ignore this exception if the receiver is unregistered already.
- }
+ unregisterScreenOffEvent();
}
// Only persist setting if not in car mode
if (!mCarModeEnabled) {
@@ -541,12 +561,11 @@ final class UiModeManagerService extends SystemService {
mNightMode = mode;
mNightModeOverride = mode;
- //on screen off will update configuration instead
- if (mNightMode != UiModeManager.MODE_NIGHT_AUTO) {
+ // on screen off will update configuration instead
+ if (mNightMode != UiModeManager.MODE_NIGHT_AUTO || mCar) {
updateLocked(0, 0);
} else {
- getContext().registerReceiver(
- mOnScreenOffHandler, new IntentFilter(ACTION_SCREEN_OFF));
+ registerScreenOffEvent();
}
}
}
@@ -594,10 +613,7 @@ final class UiModeManagerService extends SystemService {
final long ident = Binder.clearCallingIdentity();
try {
if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
- try {
- getContext().unregisterReceiver(mOnScreenOffHandler);
- } catch (IllegalArgumentException e) {
- }
+ unregisterScreenOffEvent();
mNightModeOverride = active
? UiModeManager.MODE_NIGHT_YES : UiModeManager.MODE_NIGHT_NO;
} else if (mNightMode == UiModeManager.MODE_NIGHT_NO
@@ -608,7 +624,7 @@ final class UiModeManagerService extends SystemService {
mNightMode = UiModeManager.MODE_NIGHT_NO;
}
updateConfigurationLocked();
- sendConfigurationLocked();
+ applyConfigurationExternallyLocked();
return true;
} finally {
Binder.restoreCallingIdentity(ident);
@@ -863,12 +879,12 @@ final class UiModeManagerService extends SystemService {
}
mCurUiMode = uiMode;
- if (!mHoldingConfiguration) {
+ if (!mHoldingConfiguration || !mWaitForScreenOff) {
mConfiguration.uiMode = uiMode;
}
}
- private void sendConfigurationLocked() {
+ private void applyConfigurationExternallyLocked() {
if (mSetUiMode != mConfiguration.uiMode) {
mSetUiMode = mConfiguration.uiMode;
// load splash screen instead of screenshot
@@ -1052,7 +1068,7 @@ final class UiModeManagerService extends SystemService {
}
// Send the new configuration.
- sendConfigurationLocked();
+ applyConfigurationExternallyLocked();
// If we did not start a dock app, then start dreaming if supported.
if (category != null && !dockAppStarted) {
@@ -1130,7 +1146,6 @@ final class UiModeManagerService extends SystemService {
final int user = UserHandle.getCallingUserId();
Secure.putIntForUser(getContext().getContentResolver(),
OVERRIDE_NIGHT_MODE, mNightModeOverride, user);
-
}
}
diff --git a/services/core/java/com/android/server/VibratorService.java b/services/core/java/com/android/server/VibratorService.java
index 3330882cc07d..76a8f92312ae 100644
--- a/services/core/java/com/android/server/VibratorService.java
+++ b/services/core/java/com/android/server/VibratorService.java
@@ -25,6 +25,7 @@ import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
+import android.content.pm.PackageManagerInternal;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.hardware.input.InputManager;
@@ -60,6 +61,7 @@ import android.provider.DeviceConfig;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.util.DebugUtils;
+import android.util.Pair;
import android.util.Slog;
import android.util.SparseArray;
import android.util.StatsLog;
@@ -79,7 +81,6 @@ public class VibratorService extends IVibratorService.Stub
implements InputManager.InputDeviceListener {
private static final String TAG = "VibratorService";
private static final boolean DEBUG = false;
- private static final String SYSTEM_UI_PACKAGE = "com.android.systemui";
private static final String EXTERNAL_VIBRATOR_SERVICE = "external_vibrator_service";
private static final String RAMPING_RINGER_ENABLED = "ramping_ringer_enabled";
@@ -139,6 +140,7 @@ public class VibratorService extends IVibratorService.Stub
private final PowerManager.WakeLock mWakeLock;
private final AppOpsManager mAppOps;
private final IBatteryStats mBatteryStatsService;
+ private final String mSystemUiPackage;
private PowerManagerInternal mPowerManagerInternal;
private InputManager mIm;
private Vibrator mVibrator;
@@ -161,6 +163,8 @@ public class VibratorService extends IVibratorService.Stub
private int mHapticFeedbackIntensity;
private int mNotificationIntensity;
private int mRingIntensity;
+ private SparseArray<Pair<VibrationEffect, AudioAttributes>> mAlwaysOnEffects =
+ new SparseArray<>();
static native boolean vibratorExists();
static native void vibratorInit();
@@ -172,6 +176,8 @@ public class VibratorService extends IVibratorService.Stub
static native boolean vibratorSupportsExternalControl();
static native void vibratorSetExternalControl(boolean enabled);
static native long vibratorGetCapabilities();
+ static native void vibratorAlwaysOnEnable(long id, long effect, long strength);
+ static native void vibratorAlwaysOnDisable(long id);
private final IUidObserver mUidObserver = new IUidObserver.Stub() {
@Override public void onUidStateChanged(int uid, int procState, long procStateSeq,
@@ -284,7 +290,7 @@ public class VibratorService extends IVibratorService.Stub
}
public boolean isFromSystem() {
- return uid == Process.SYSTEM_UID || uid == 0 || SYSTEM_UI_PACKAGE.equals(opPkg);
+ return uid == Process.SYSTEM_UID || uid == 0 || mSystemUiPackage.equals(opPkg);
}
public VibrationInfo toInfo() {
@@ -372,6 +378,8 @@ public class VibratorService extends IVibratorService.Stub
mAppOps = mContext.getSystemService(AppOpsManager.class);
mBatteryStatsService = IBatteryStats.Stub.asInterface(ServiceManager.getService(
BatteryStats.SERVICE_NAME));
+ mSystemUiPackage = LocalServices.getService(PackageManagerInternal.class)
+ .getSystemUiServiceComponent().getPackageName();
mPreviousVibrationsLimit = mContext.getResources().getInteger(
com.android.internal.R.integer.config_previousVibrationsDumpLimit);
@@ -519,6 +527,41 @@ public class VibratorService extends IVibratorService.Stub
}
}
+ @Override // Binder call
+ public boolean setAlwaysOnEffect(int id, VibrationEffect effect, AudioAttributes attrs) {
+ if (!hasPermission(android.Manifest.permission.VIBRATE_ALWAYS_ON)) {
+ throw new SecurityException("Requires VIBRATE_ALWAYS_ON permission");
+ }
+ if ((mCapabilities & IVibrator.CAP_ALWAYS_ON_CONTROL) == 0) {
+ Slog.e(TAG, "Always-on effects not supported.");
+ return false;
+ }
+ if (effect == null) {
+ synchronized (mLock) {
+ mAlwaysOnEffects.delete(id);
+ vibratorAlwaysOnDisable(id);
+ }
+ } else {
+ if (!verifyVibrationEffect(effect)) {
+ return false;
+ }
+ if (!(effect instanceof VibrationEffect.Prebaked)) {
+ Slog.e(TAG, "Only prebaked effects supported for always-on.");
+ return false;
+ }
+ if (attrs == null) {
+ attrs = new AudioAttributes.Builder()
+ .setUsage(AudioAttributes.USAGE_UNKNOWN)
+ .build();
+ }
+ synchronized (mLock) {
+ mAlwaysOnEffects.put(id, Pair.create(effect, attrs));
+ updateAlwaysOnLocked(id, effect, attrs);
+ }
+ }
+ return true;
+ }
+
private void verifyIncomingUid(int uid) {
if (uid == Binder.getCallingUid()) {
return;
@@ -989,6 +1032,8 @@ public class VibratorService extends IVibratorService.Stub
// If the state changes out from under us then just reset.
doCancelVibrateLocked();
}
+
+ updateAlwaysOnLocked();
}
}
@@ -1055,6 +1100,27 @@ public class VibratorService extends IVibratorService.Stub
mVibrator.getDefaultRingVibrationIntensity(), UserHandle.USER_CURRENT);
}
+ private void updateAlwaysOnLocked(int id, VibrationEffect effect, AudioAttributes attrs) {
+ // TODO: Check DND and LowPower settings
+ final Vibration vib = new Vibration(null, effect, attrs, 0, null, null);
+ final int intensity = getCurrentIntensityLocked(vib);
+ if (intensity == Vibrator.VIBRATION_INTENSITY_OFF) {
+ vibratorAlwaysOnDisable(id);
+ } else {
+ final VibrationEffect.Prebaked prebaked = (VibrationEffect.Prebaked) effect;
+ final int strength = intensityToEffectStrength(intensity);
+ vibratorAlwaysOnEnable(id, prebaked.getId(), strength);
+ }
+ }
+
+ private void updateAlwaysOnLocked() {
+ for (int i = 0; i < mAlwaysOnEffects.size(); i++) {
+ int id = mAlwaysOnEffects.keyAt(i);
+ Pair<VibrationEffect, AudioAttributes> pair = mAlwaysOnEffects.valueAt(i);
+ updateAlwaysOnLocked(id, pair.first, pair.second);
+ }
+ }
+
@Override
public void onInputDeviceAdded(int deviceId) {
updateVibrators();
diff --git a/services/core/java/com/android/server/accounts/AccountManagerService.java b/services/core/java/com/android/server/accounts/AccountManagerService.java
index b5cab1f8d62b..5996b7d848ea 100644
--- a/services/core/java/com/android/server/accounts/AccountManagerService.java
+++ b/services/core/java/com/android/server/accounts/AccountManagerService.java
@@ -1289,6 +1289,33 @@ public class AccountManagerService
}
protected UserAccounts getUserAccounts(int userId) {
+ try {
+ return getUserAccountsNotChecked(userId);
+ } catch (RuntimeException e) {
+ if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+ // Let it go...
+ throw e;
+ }
+ // User accounts database is corrupted, we must wipe out the whole user, otherwise the
+ // system will crash indefinitely
+ Slog.wtf(TAG, "Removing user " + userId + " due to exception (" + e + ") reading its "
+ + "account database");
+ if (userId == ActivityManager.getCurrentUser() && userId != UserHandle.USER_SYSTEM) {
+ Slog.i(TAG, "Switching to system user first");
+ try {
+ ActivityManager.getService().switchUser(UserHandle.USER_SYSTEM);
+ } catch (RemoteException re) {
+ Slog.e(TAG, "Could not switch to " + UserHandle.USER_SYSTEM + ": " + re);
+ }
+ }
+ if (!getUserManager().removeUserEvenWhenDisallowed(userId)) {
+ Slog.e(TAG, "could not remove user " + userId);
+ }
+ throw e;
+ }
+ }
+
+ private UserAccounts getUserAccountsNotChecked(int userId) {
synchronized (mUsers) {
UserAccounts accounts = mUsers.get(userId);
boolean validateAccounts = false;
@@ -4382,7 +4409,6 @@ public class AccountManagerService
return true;
}
- @Override
public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
userId = handleIncomingUser(userId);
UserAccounts accounts = getUserAccounts(userId);
@@ -4398,7 +4424,6 @@ public class AccountManagerService
return r > 0;
}
- @Override
public boolean removeSharedAccountAsUser(Account account, int userId) {
return removeSharedAccountAsUser(account, userId, getCallingUid());
}
@@ -4416,7 +4441,6 @@ public class AccountManagerService
return deleted;
}
- @Override
public Account[] getSharedAccountsAsUser(int userId) {
userId = handleIncomingUser(userId);
UserAccounts accounts = getUserAccounts(userId);
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 01f3c2666ff7..16096069631e 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -490,7 +490,7 @@ public class ActivityManagerService extends IActivityManager.Stub
static final String[] EMPTY_STRING_ARRAY = new String[0];
// How many bytes to write into the dropbox log before truncating
- static final int DROPBOX_MAX_SIZE = 192 * 1024;
+ static final int DROPBOX_DEFAULT_MAX_SIZE = 192 * 1024;
// Assumes logcat entries average around 100 bytes; that's not perfect stack traces count
// as one line, but close enough for now.
static final int RESERVED_BYTES_PER_LOGCAT_LINE = 100;
@@ -957,10 +957,12 @@ public class ActivityManagerService extends IActivityManager.Stub
new DeviceConfig.OnPropertiesChangedListener() {
@Override
public void onPropertiesChanged(Properties properties) {
- mPssDeferralTime = properties.getLong(ACTIVITY_START_PSS_DEFER_CONFIG, 0);
- if (DEBUG_PSS) {
- Slog.d(TAG_PSS, "Activity-start PSS delay now "
- + mPssDeferralTime + " ms");
+ if (properties.getKeyset().contains(ACTIVITY_START_PSS_DEFER_CONFIG)) {
+ mPssDeferralTime = properties.getLong(ACTIVITY_START_PSS_DEFER_CONFIG, 0);
+ if (DEBUG_PSS) {
+ Slog.d(TAG_PSS, "Activity-start PSS delay now "
+ + mPssDeferralTime + " ms");
+ }
}
}
};
@@ -2386,7 +2388,8 @@ public class ActivityManagerService extends IActivityManager.Stub
mConstants = hasHandlerThread
? new ActivityManagerConstants(mContext, this, mHandler) : null;
final ActiveUids activeUids = new ActiveUids(this, false /* postChangesToAtm */);
- mProcessList.init(this, activeUids);
+ mPlatformCompat = null;
+ mProcessList.init(this, activeUids, mPlatformCompat);
mLowMemDetector = null;
mOomAdjuster = hasHandlerThread
? new OomAdjuster(this, mProcessList, activeUids, handlerThread) : null;
@@ -2410,7 +2413,6 @@ public class ActivityManagerService extends IActivityManager.Stub
mFactoryTest = FACTORY_TEST_OFF;
mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
mInternal = new LocalService();
- mPlatformCompat = null;
}
// Note: This method is invoked on the main thread but may need to attach various
@@ -2439,7 +2441,9 @@ public class ActivityManagerService extends IActivityManager.Stub
mConstants = new ActivityManagerConstants(mContext, this, mHandler);
final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */);
- mProcessList.init(this, activeUids);
+ mPlatformCompat = (PlatformCompat) ServiceManager.getService(
+ Context.PLATFORM_COMPAT_SERVICE);
+ mProcessList.init(this, activeUids, mPlatformCompat);
mLowMemDetector = new LowMemDetector(this);
mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);
@@ -2547,9 +2551,6 @@ public class ActivityManagerService extends IActivityManager.Stub
mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
- mPlatformCompat = (PlatformCompat) ServiceManager.getService(
- Context.PLATFORM_COMPAT_SERVICE);
-
Watchdog.getInstance().addMonitor(this);
Watchdog.getInstance().addThread(mHandler);
@@ -5032,9 +5033,7 @@ public class ActivityManagerService extends IActivityManager.Stub
bindApplicationTimeMillis = SystemClock.elapsedRealtime();
mAtmInternal.preBindApplication(app.getWindowProcessController());
final ActiveInstrumentation instr2 = app.getActiveInstrumentation();
- long[] disabledCompatChanges = {};
if (mPlatformCompat != null) {
- disabledCompatChanges = mPlatformCompat.getDisabledChanges(app.info);
mPlatformCompat.resetReporting(app.info);
}
if (app.isolatedEntryPoint != null) {
@@ -5053,7 +5052,7 @@ public class ActivityManagerService extends IActivityManager.Stub
app.compat, getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, autofillOptions, contentCaptureOptions,
- disabledCompatChanges);
+ app.mDisabledCompatChanges);
} else {
thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
null, null, null, testMode,
@@ -5063,7 +5062,7 @@ public class ActivityManagerService extends IActivityManager.Stub
app.compat, getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, autofillOptions, contentCaptureOptions,
- disabledCompatChanges);
+ app.mDisabledCompatChanges);
}
if (profilerInfo != null) {
profilerInfo.closeFd();
@@ -8392,6 +8391,18 @@ public class ActivityManagerService extends IActivityManager.Stub
return BugReportHandlerUtil.launchBugReportHandlerApp(mContext);
}
+ /**
+ * Get packages of bugreport-whitelisted apps to handle a bug report.
+ *
+ * @return packages of bugreport-whitelisted apps to handle a bug report.
+ */
+ @Override
+ public List<String> getBugreportWhitelistedPackages() {
+ enforceCallingPermission(android.Manifest.permission.MANAGE_DEBUGGING,
+ "getBugreportWhitelistedPackages");
+ return new ArrayList<>(SystemConfig.getInstance().getBugreportWhitelistedPackages());
+ }
+
public void registerProcessObserver(IProcessObserver observer) {
enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
"registerProcessObserver()");
@@ -9773,9 +9784,12 @@ public class ActivityManagerService extends IActivityManager.Stub
sb.append(report);
}
- String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
- int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0);
- int maxDataFileSize = DROPBOX_MAX_SIZE - sb.length()
+ String logcatSetting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
+ String maxBytesSetting = Settings.Global.MAX_ERROR_BYTES_PREFIX + dropboxTag;
+ int lines = Settings.Global.getInt(mContext.getContentResolver(), logcatSetting, 0);
+ int dropboxMaxSize = Settings.Global.getInt(
+ mContext.getContentResolver(), maxBytesSetting, DROPBOX_DEFAULT_MAX_SIZE);
+ int maxDataFileSize = dropboxMaxSize - sb.length()
- lines * RESERVED_BYTES_PER_LOGCAT_LINE;
if (dataFile != null && maxDataFileSize > 0) {
@@ -18436,7 +18450,7 @@ public class ActivityManagerService extends IActivityManager.Stub
public ActivityPresentationInfo getActivityPresentationInfo(IBinder token) {
int displayId = Display.INVALID_DISPLAY;
try {
- displayId = mActivityTaskManager.getActivityDisplayId(token);
+ displayId = mActivityTaskManager.getDisplayId(token);
} catch (RemoteException e) {
}
diff --git a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
index 7f1d5a33f56a..79fe61072a44 100644
--- a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
+++ b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
@@ -2909,6 +2909,12 @@ final class ActivityManagerShellCommand extends ShellCommand {
final PlatformCompat platformCompat = (PlatformCompat)
ServiceManager.getService(Context.PLATFORM_COMPAT_SERVICE);
String toggleValue = getNextArgRequired();
+ if (toggleValue.equals("reset-all")) {
+ final String packageName = getNextArgRequired();
+ pw.println("Reset all changes for " + packageName + " to default value.");
+ platformCompat.clearOverrides(packageName);
+ return 0;
+ }
long changeId;
String changeIdString = getNextArgRequired();
try {
@@ -3267,9 +3273,14 @@ final class ActivityManagerShellCommand extends ShellCommand {
pw.println(" without restarting any processes.");
pw.println(" write");
pw.println(" Write all pending state to storage.");
- pw.println(" compat enable|disable|reset <CHANGE_ID|CHANGE_NAME> <PACKAGE_NAME>");
- pw.println(" Toggles a change either by id or by name for <PACKAGE_NAME>.");
- pw.println(" It kills <PACKAGE_NAME> (to allow the toggle to take effect).");
+ pw.println(" compat [COMMAND] [...]: sub-commands for toggling app-compat changes.");
+ pw.println(" enable|disable|reset <CHANGE_ID|CHANGE_NAME> <PACKAGE_NAME>");
+ pw.println(" Toggles a change either by id or by name for <PACKAGE_NAME>.");
+ pw.println(" It kills <PACKAGE_NAME> (to allow the toggle to take effect).");
+ pw.println(" reset-all <PACKAGE_NAME>");
+ pw.println(" Removes all existing overrides for all changes for ");
+ pw.println(" <PACKAGE_NAME> (back to default behaviour).");
+ pw.println(" It kills <PACKAGE_NAME> (to allow the toggle to take effect).");
pw.println();
Intent.printIntentArgsHelp(pw, "");
}
diff --git a/services/core/java/com/android/server/am/LmkdConnection.java b/services/core/java/com/android/server/am/LmkdConnection.java
index d1e09db39e41..f41c36404c50 100644
--- a/services/core/java/com/android/server/am/LmkdConnection.java
+++ b/services/core/java/com/android/server/am/LmkdConnection.java
@@ -18,6 +18,7 @@ package com.android.server.am;
import static android.os.MessageQueue.OnFileDescriptorEventListener.EVENT_ERROR;
import static android.os.MessageQueue.OnFileDescriptorEventListener.EVENT_INPUT;
+
import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
@@ -35,9 +36,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
-import java.util.concurrent.locks.Condition;
-import java.util.concurrent.locks.ReentrantLock;
-import java.util.concurrent.TimeUnit;
/**
* Lmkd connection to communicate with lowmemorykiller daemon.
@@ -46,7 +44,7 @@ public class LmkdConnection {
private static final String TAG = TAG_WITH_CLASS_NAME ? "LmkdConnection" : TAG_AM;
// lmkd reply max size in bytes
- private static final int LMKD_REPLY_MAX_SIZE = 8;
+ private static final int LMKD_REPLY_MAX_SIZE = 12;
// connection listener interface
interface LmkdConnectionListener {
@@ -64,6 +62,15 @@ public class LmkdConnection {
*/
public boolean isReplyExpected(ByteBuffer replyBuf, ByteBuffer dataReceived,
int receivedLen);
+
+ /**
+ * Handle the received message if it's unsolicited.
+ *
+ * @param dataReceived The buffer holding received data
+ * @param receivedLen Size of the data received
+ * @return True if the message has been handled correctly, false otherwise.
+ */
+ boolean handleUnsolicitedMessage(ByteBuffer dataReceived, int receivedLen);
}
private final MessageQueue mMsgQueue;
@@ -187,17 +194,17 @@ public class LmkdConnection {
mReplyBuf.rewind();
// wakeup the waiting thread
mReplyBufLock.notifyAll();
- } else {
- // received asynchronous or unexpected packet
+ } else if (!mListener.handleUnsolicitedMessage(mInputBuf, len)) {
+ // received unexpected packet
// treat this as an error
mReplyBuf = null;
mReplyBufLock.notifyAll();
- Slog.e(TAG, "Received unexpected packet from lmkd");
+ Slog.e(TAG, "Received an unexpected packet from lmkd");
}
- } else {
+ } else if (!mListener.handleUnsolicitedMessage(mInputBuf, len)) {
// received asynchronous communication from lmkd
- // we don't support this yet
- Slog.w(TAG, "Received an asynchronous packet from lmkd");
+ // but we don't recognize it.
+ Slog.w(TAG, "Received an unexpected packet from lmkd");
}
}
}
diff --git a/services/core/java/com/android/server/am/ProcessList.java b/services/core/java/com/android/server/am/ProcessList.java
index 32975d7792f5..557def44dc66 100644
--- a/services/core/java/com/android/server/am/ProcessList.java
+++ b/services/core/java/com/android/server/am/ProcessList.java
@@ -59,6 +59,7 @@ import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageManager;
+import android.content.pm.PackageManagerInternal;
import android.content.res.Resources;
import android.graphics.Point;
import android.os.AppZygote;
@@ -78,6 +79,7 @@ import android.os.Trace;
import android.os.UserHandle;
import android.os.storage.StorageManager;
import android.os.storage.StorageManagerInternal;
+import android.provider.DeviceConfig;
import android.system.ErrnoException;
import android.system.Os;
import android.system.OsConstants;
@@ -85,6 +87,7 @@ import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.EventLog;
import android.util.LongSparseArray;
+import android.util.Pair;
import android.util.Slog;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
@@ -101,6 +104,7 @@ import com.android.internal.util.MemInfoReader;
import com.android.server.LocalServices;
import com.android.server.ServiceThread;
import com.android.server.Watchdog;
+import com.android.server.compat.PlatformCompat;
import com.android.server.pm.dex.DexManager;
import com.android.server.wm.ActivityServiceConnectionsHolder;
import com.android.server.wm.WindowManagerService;
@@ -116,6 +120,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
+import java.util.Map;
/**
* Activity manager code dealing with processes.
@@ -123,6 +128,13 @@ import java.util.List;
public final class ProcessList {
static final String TAG = TAG_WITH_CLASS_NAME ? "ProcessList" : TAG_AM;
+ // A device config to control the minimum target SDK to enable app data isolation
+ static final String ANDROID_APP_DATA_ISOLATION_ENABLED_PROPERTY =
+ "persist.zygote.app_data_isolation";
+
+ // A device config to control the minimum target SDK to enable app data isolation
+ static final String ANDROID_APP_DATA_ISOLATION_MIN_SDK = "android_app_data_isolation_min_sdk";
+
// The minimum time we allow between crashes, for us to consider this
// application to be bad and stop and its services and reject broadcasts.
static final int MIN_CRASH_INTERVAL = 60 * 1000;
@@ -277,14 +289,16 @@ public final class ProcessList {
// LMK_PROCREMOVE <pid>
// LMK_PROCPURGE
// LMK_GETKILLCNT
+ // LMK_PROCKILL
static final byte LMK_TARGET = 0;
static final byte LMK_PROCPRIO = 1;
static final byte LMK_PROCREMOVE = 2;
static final byte LMK_PROCPURGE = 3;
static final byte LMK_GETKILLCNT = 4;
+ static final byte LMK_PROCKILL = 5; // Note: this is an unsolicated command
// lmkd reconnect delay in msecs
- private final static long LMDK_RECONNECT_DELAY_MS = 1000;
+ private static final long LMKD_RECONNECT_DELAY_MS = 1000;
/**
* How long between a process kill and we actually receive its death recipient
@@ -334,6 +348,8 @@ public final class ProcessList {
private boolean mOomLevelsSet = false;
+ private boolean mAppDataIsolationEnabled = false;
+
/**
* Temporary to avoid allocations. Protected by main lock.
*/
@@ -390,6 +406,12 @@ public final class ProcessList {
ActiveUids mActiveUids;
/**
+ * The listener who is intereted with the lmkd kills.
+ */
+ @GuardedBy("mService")
+ private LmkdKillListener mLmkdKillListener = null;
+
+ /**
* The currently running isolated processes.
*/
final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<>();
@@ -405,6 +427,15 @@ public final class ProcessList {
final ArrayMap<AppZygote, ArrayList<ProcessRecord>> mAppZygoteProcesses =
new ArrayMap<AppZygote, ArrayList<ProcessRecord>>();
+ private PlatformCompat mPlatformCompat = null;
+
+ interface LmkdKillListener {
+ /**
+ * Called when there is a process kill by lmkd.
+ */
+ void onLmkdKillOccurred(int pid, int uid);
+ }
+
final class IsolatedUidRange {
@VisibleForTesting
public final int mFirstUid;
@@ -443,9 +474,7 @@ public final class ProcessList {
@GuardedBy("ProcessList.this.mService")
void freeIsolatedUidLocked(int uid) {
- // Strip out userId
- final int appId = UserHandle.getAppId(uid);
- mUidUsed.delete(appId);
+ mUidUsed.delete(uid);
}
};
@@ -557,7 +586,8 @@ public final class ProcessList {
final class KillHandler extends Handler {
static final int KILL_PROCESS_GROUP_MSG = 4000;
- static final int LMDK_RECONNECT_MSG = 4001;
+ static final int LMKD_RECONNECT_MSG = 4001;
+ static final int LMKD_PROC_KILLED_MSG = 4002;
public KillHandler(Looper looper) {
super(looper, null, true);
@@ -571,15 +601,18 @@ public final class ProcessList {
Process.killProcessGroup(msg.arg1 /* uid */, msg.arg2 /* pid */);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
- case LMDK_RECONNECT_MSG:
+ case LMKD_RECONNECT_MSG:
if (!sLmkdConnection.connect()) {
Slog.i(TAG, "Failed to connect to lmkd, retry after " +
- LMDK_RECONNECT_DELAY_MS + " ms");
- // retry after LMDK_RECONNECT_DELAY_MS
+ LMKD_RECONNECT_DELAY_MS + " ms");
+ // retry after LMKD_RECONNECT_DELAY_MS
sKillHandler.sendMessageDelayed(sKillHandler.obtainMessage(
- KillHandler.LMDK_RECONNECT_MSG), LMDK_RECONNECT_DELAY_MS);
+ KillHandler.LMKD_RECONNECT_MSG), LMKD_RECONNECT_DELAY_MS);
}
break;
+ case LMKD_PROC_KILLED_MSG:
+ handleLmkdProcKilled(msg.arg1 /* pid */, msg.arg2 /* uid */);
+ break;
default:
super.handleMessage(msg);
@@ -596,9 +629,15 @@ public final class ProcessList {
updateOomLevels(0, 0, false);
}
- void init(ActivityManagerService service, ActiveUids activeUids) {
+ void init(ActivityManagerService service, ActiveUids activeUids,
+ PlatformCompat platformCompat) {
mService = service;
mActiveUids = activeUids;
+ mPlatformCompat = platformCompat;
+ // Get this after boot, and won't be changed until it's rebooted, as we don't
+ // want some apps enabled while some apps disabled
+ mAppDataIsolationEnabled =
+ SystemProperties.getBoolean(ANDROID_APP_DATA_ISOLATION_ENABLED_PROPERTY, false);
if (sKillHandler == null) {
sKillThread = new ServiceThread(TAG + ":kill",
@@ -612,13 +651,15 @@ public final class ProcessList {
Slog.i(TAG, "Connection with lmkd established");
return onLmkdConnect(ostream);
}
+
@Override
public void onDisconnect() {
Slog.w(TAG, "Lost connection to lmkd");
// start reconnection after delay to let lmkd restart
sKillHandler.sendMessageDelayed(sKillHandler.obtainMessage(
- KillHandler.LMDK_RECONNECT_MSG), LMDK_RECONNECT_DELAY_MS);
+ KillHandler.LMKD_RECONNECT_MSG), LMKD_RECONNECT_DELAY_MS);
}
+
@Override
public boolean isReplyExpected(ByteBuffer replyBuf,
ByteBuffer dataReceived, int receivedLen) {
@@ -627,6 +668,26 @@ public final class ProcessList {
return (receivedLen == replyBuf.array().length &&
dataReceived.getInt(0) == replyBuf.getInt(0));
}
+
+ @Override
+ public boolean handleUnsolicitedMessage(ByteBuffer dataReceived,
+ int receivedLen) {
+ if (receivedLen < 4) {
+ return false;
+ }
+ switch (dataReceived.getInt(0)) {
+ case LMK_PROCKILL:
+ if (receivedLen != 12) {
+ return false;
+ }
+ sKillHandler.obtainMessage(KillHandler.LMKD_PROC_KILLED_MSG,
+ dataReceived.getInt(4), dataReceived.getInt(8))
+ .sendToTarget();
+ return true;
+ default:
+ return false;
+ }
+ }
}
);
}
@@ -1303,10 +1364,10 @@ public final class ProcessList {
if (!sLmkdConnection.isConnected()) {
// try to connect immediately and then keep retrying
sKillHandler.sendMessage(
- sKillHandler.obtainMessage(KillHandler.LMDK_RECONNECT_MSG));
+ sKillHandler.obtainMessage(KillHandler.LMKD_RECONNECT_MSG));
// wait for connection retrying 3 times (up to 3 seconds)
- if (!sLmkdConnection.waitForConnection(3 * LMDK_RECONNECT_DELAY_MS)) {
+ if (!sLmkdConnection.waitForConnection(3 * LMKD_RECONNECT_DELAY_MS)) {
return false;
}
}
@@ -1664,6 +1725,10 @@ public final class ProcessList {
Slog.wtf(TAG, "startProcessLocked processName:" + app.processName
+ " with non-zero pid:" + app.pid);
}
+ app.mDisabledCompatChanges = null;
+ if (mPlatformCompat != null) {
+ app.mDisabledCompatChanges = mPlatformCompat.getDisabledChanges(app.info);
+ }
final long startSeq = app.startSeq = ++mProcStartSeqCounter;
app.setStartParams(uid, hostingRecord, seInfo, startTime);
app.setUsingWrapper(invokeWith != null
@@ -1805,6 +1870,32 @@ public final class ProcessList {
}
}
+ private boolean shouldIsolateAppData(ProcessRecord app) {
+ if (!mAppDataIsolationEnabled) {
+ return false;
+ }
+ if (!UserHandle.isApp(app.uid)) {
+ return false;
+ }
+ final int minTargetSdk = DeviceConfig.getInt(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
+ ANDROID_APP_DATA_ISOLATION_MIN_SDK, Build.VERSION_CODES.R);
+ return app.info.targetSdkVersion >= minTargetSdk;
+ }
+
+ private Map<String, Pair<String, Long>> getPackageAppDataInfoMap(PackageManagerInternal pmInt,
+ String[] packages, int uid) {
+ Map<String, Pair<String, Long>> result = new ArrayMap<>(packages.length);
+ int userId = UserHandle.getUserId(uid);
+ for (String packageName : packages) {
+ String volumeUuid = pmInt.getPackage(packageName).getVolumeUuid();
+ long inode = pmInt.getCeDataInode(packageName, userId);
+ if (inode != 0) {
+ result.put(packageName, Pair.create(volumeUuid, inode));
+ }
+ }
+ return result;
+ }
+
private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint,
ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
String seInfo, String requiredAbi, String instructionSet, String invokeWith,
@@ -1821,13 +1912,28 @@ public final class ProcessList {
app.setHasForegroundActivities(true);
}
+ final Map<String, Pair<String, Long>> pkgDataInfoMap;
+
+ if (shouldIsolateAppData(app)) {
+ // Get all packages belongs to the same shared uid. sharedPackages is empty array
+ // if it doesn't have shared uid.
+ final PackageManagerInternal pmInt = mService.getPackageManagerInternalLocked();
+ final String sharedUserId = pmInt.getSharedUserIdForPackage(app.info.packageName);
+ final String[] sharedPackages = pmInt.getPackagesForSharedUserId(sharedUserId,
+ app.userId);
+ pkgDataInfoMap = getPackageAppDataInfoMap(pmInt, sharedPackages.length == 0
+ ? new String[]{app.info.packageName} : sharedPackages, uid);
+ } else {
+ pkgDataInfoMap = null;
+ }
+
final Process.ProcessStartResult startResult;
if (hostingRecord.usesWebviewZygote()) {
startResult = startWebView(entryPoint,
app.processName, uid, uid, gids, runtimeFlags, mountExternal,
app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
- app.info.dataDir, null, app.info.packageName,
- new String[] {PROC_START_SEQ_IDENT + app.startSeq});
+ app.info.dataDir, null, app.info.packageName, app.mDisabledCompatChanges,
+ new String[]{PROC_START_SEQ_IDENT + app.startSeq});
} else if (hostingRecord.usesAppZygote()) {
final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app);
@@ -1835,14 +1941,15 @@ public final class ProcessList {
app.processName, uid, uid, gids, runtimeFlags, mountExternal,
app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
app.info.dataDir, null, app.info.packageName,
- /*useUsapPool=*/ false, isTopApp,
- new String[] {PROC_START_SEQ_IDENT + app.startSeq});
+ /*useUsapPool=*/ false, isTopApp, app.mDisabledCompatChanges,
+ pkgDataInfoMap, new String[]{PROC_START_SEQ_IDENT + app.startSeq});
} else {
startResult = Process.start(entryPoint,
app.processName, uid, uid, gids, runtimeFlags, mountExternal,
app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
app.info.dataDir, invokeWith, app.info.packageName, isTopApp,
- new String[] {PROC_START_SEQ_IDENT + app.startSeq});
+ app.mDisabledCompatChanges, pkgDataInfoMap,
+ new String[]{PROC_START_SEQ_IDENT + app.startSeq});
}
checkSlow(startTime, "startProcess: returned from zygote!");
return startResult;
@@ -3393,4 +3500,28 @@ public final class ProcessList {
}
}
}
+
+ void setLmkdKillListener(final LmkdKillListener listener) {
+ synchronized (mService) {
+ mLmkdKillListener = listener;
+ }
+ }
+
+ private void handleLmkdProcKilled(final int pid, final int uid) {
+ // Log only now
+ if (DEBUG_PROCESSES) {
+ Slog.i(TAG, "lmkd kill: pid=" + pid + " uid=" + uid);
+ }
+
+ if (mService == null) {
+ return;
+ }
+ // Notify any interesed party regarding the lmkd kills
+ synchronized (mService) {
+ final LmkdKillListener listener = mLmkdKillListener;
+ if (listener != null) {
+ mService.mHandler.post(()-> listener.onLmkdKillOccurred(pid, uid));
+ }
+ }
+ }
}
diff --git a/services/core/java/com/android/server/am/ProcessRecord.java b/services/core/java/com/android/server/am/ProcessRecord.java
index 6f6f193721fa..24fc743e0a08 100644
--- a/services/core/java/com/android/server/am/ProcessRecord.java
+++ b/services/core/java/com/android/server/am/ProcessRecord.java
@@ -310,6 +310,8 @@ class ProcessRecord implements WindowProcessListener {
long startTime;
// This will be same as {@link #uid} usually except for some apps used during factory testing.
int startUid;
+ // set of disabled compat changes for the process (all others are enabled)
+ long[] mDisabledCompatChanges;
// Cached task info for OomAdjuster
private static final int VALUE_INVALID = -1;
diff --git a/services/core/java/com/android/server/appop/AppOpsService.java b/services/core/java/com/android/server/appop/AppOpsService.java
index 366766e2e47b..14f96540bc6a 100644
--- a/services/core/java/com/android/server/appop/AppOpsService.java
+++ b/services/core/java/com/android/server/appop/AppOpsService.java
@@ -20,6 +20,7 @@ import static android.app.ActivityManager.PROCESS_CAPABILITY_FOREGROUND_LOCATION
import static android.app.AppOpsManager.MAX_PRIORITY_UID_STATE;
import static android.app.AppOpsManager.MIN_PRIORITY_UID_STATE;
import static android.app.AppOpsManager.OP_CAMERA;
+import static android.app.AppOpsManager.OP_COARSE_LOCATION;
import static android.app.AppOpsManager.OP_FLAGS_ALL;
import static android.app.AppOpsManager.OP_NONE;
import static android.app.AppOpsManager.OP_PLAY_AUDIO;
@@ -1642,6 +1643,13 @@ public class AppOpsService extends IAppOpsService.Stub {
return;
}
+ // STOPSHIP: Remove this check once we are sure no one is doing it.
+ if (code == OP_COARSE_LOCATION && mode != AppOpsManager.opToDefaultMode(code)) {
+ Slog.wtf(TAG, "Trying to setMode() instead of setUidMode(), " + "code=" + code
+ + ", uid=" + uid + ", packageName=" + packageName + ", mode=" + mode
+ + ", callingUid=" + Binder.getCallingUid(), new RuntimeException());
+ }
+
synchronized (this) {
UidState uidState = getUidStateLocked(uid, false);
Op op = getOpLocked(code, uid, packageName, isPrivileged, true);
diff --git a/services/core/java/com/android/server/attention/AttentionManagerService.java b/services/core/java/com/android/server/attention/AttentionManagerService.java
index 232bc08e5b5c..fc67e24684bb 100644
--- a/services/core/java/com/android/server/attention/AttentionManagerService.java
+++ b/services/core/java/com/android/server/attention/AttentionManagerService.java
@@ -77,21 +77,28 @@ public class AttentionManagerService extends SystemService {
private static final String LOG_TAG = "AttentionManagerService";
private static final boolean DEBUG = false;
+ /** Service will unbind if connection is not used for that amount of time. */
+ private static final long CONNECTION_TTL_MILLIS = 60_000;
+
+ /** DeviceConfig flag name, if {@code true}, enables AttentionManagerService features. */
+ private static final String KEY_SERVICE_ENABLED = "service_enabled";
+
/** Default value in absence of {@link DeviceConfig} override. */
private static final boolean DEFAULT_SERVICE_ENABLED = true;
- /** Service will unbind if connection is not used for that amount of time. */
- private static final long CONNECTION_TTL_MILLIS = 60_000;
+ /**
+ * DeviceConfig flag name, describes how much time we consider a result fresh; if the check
+ * attention called within that period - cached value will be returned.
+ */
+ @VisibleForTesting static final String KEY_STALE_AFTER_MILLIS = "stale_after_millis";
- /** If the check attention called within that period - cached value will be returned. */
- private static final long STALE_AFTER_MILLIS = 5_000;
+ /** Default value in absence of {@link DeviceConfig} override. */
+ @VisibleForTesting static final long DEFAULT_STALE_AFTER_MILLIS = 1_000;
/** The size of the buffer that stores recent attention check results. */
@VisibleForTesting
protected static final int ATTENTION_CACHE_BUFFER_SIZE = 5;
- /** DeviceConfig flag name, if {@code true}, enables AttentionManagerService features. */
- private static final String SERVICE_ENABLED = "service_enabled";
private static String sTestAttentionServicePackage;
private final Context mContext;
private final PowerManager mPowerManager;
@@ -160,11 +167,29 @@ public class AttentionManagerService extends SystemService {
@VisibleForTesting
protected boolean isServiceEnabled() {
- return DeviceConfig.getBoolean(NAMESPACE_ATTENTION_MANAGER_SERVICE, SERVICE_ENABLED,
+ return DeviceConfig.getBoolean(NAMESPACE_ATTENTION_MANAGER_SERVICE, KEY_SERVICE_ENABLED,
DEFAULT_SERVICE_ENABLED);
}
/**
+ * How much time we consider a result fresh; if the check attention called within that period -
+ * cached value will be returned.
+ */
+ @VisibleForTesting
+ protected long getStaleAfterMillis() {
+ final long millis = DeviceConfig.getLong(NAMESPACE_ATTENTION_MANAGER_SERVICE,
+ KEY_STALE_AFTER_MILLIS,
+ DEFAULT_STALE_AFTER_MILLIS);
+
+ if (millis < 0 || millis > 10_000) {
+ Slog.w(LOG_TAG, "Bad flag value supplied for: " + KEY_STALE_AFTER_MILLIS);
+ return DEFAULT_STALE_AFTER_MILLIS;
+ }
+
+ return millis;
+ }
+
+ /**
* Checks whether user attention is at the screen and calls in the provided callback.
*
* Calling this multiple times quickly in a row will result in either a) returning a cached
@@ -199,7 +224,7 @@ public class AttentionManagerService extends SystemService {
// throttle frequent requests
final AttentionCheckCache cache = userState.mAttentionCheckCacheBuffer == null ? null
: userState.mAttentionCheckCacheBuffer.getLast();
- if (cache != null && now < cache.mLastComputed + STALE_AFTER_MILLIS) {
+ if (cache != null && now < cache.mLastComputed + getStaleAfterMillis()) {
callbackInternal.onSuccess(cache.mResult, cache.mTimestamp);
return true;
}
diff --git a/services/core/java/com/android/server/audio/AudioDeviceBroker.java b/services/core/java/com/android/server/audio/AudioDeviceBroker.java
index 6010b1dc88c4..60f420e17e3b 100644
--- a/services/core/java/com/android/server/audio/AudioDeviceBroker.java
+++ b/services/core/java/com/android/server/audio/AudioDeviceBroker.java
@@ -24,6 +24,7 @@ import android.bluetooth.BluetoothProfile;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
+import android.media.AudioDeviceAddress;
import android.media.AudioManager;
import android.media.AudioRoutesInfo;
import android.media.AudioSystem;
@@ -400,6 +401,15 @@ import java.io.PrintWriter;
}
}
+ /*package*/ int setPreferredDeviceForStrategySync(int strategy,
+ @NonNull AudioDeviceAddress device) {
+ return mDeviceInventory.setPreferredDeviceForStrategySync(strategy, device);
+ }
+
+ /*package*/ int removePreferredDeviceForStrategySync(int strategy) {
+ return mDeviceInventory.removePreferredDeviceForStrategySync(strategy);
+ }
+
//---------------------------------------------------------------------
// Communication with (to) AudioService
//TODO check whether the AudioService methods are candidates to move here
@@ -533,6 +543,15 @@ import java.io.PrintWriter;
sendLMsgNoDelay(MSG_L_SCOCLIENT_DIED, SENDMSG_QUEUE, obj);
}
+ /*package*/ void postSaveSetPreferredDeviceForStrategy(int strategy, AudioDeviceAddress device)
+ {
+ sendILMsgNoDelay(MSG_IL_SAVE_PREF_DEVICE_FOR_STRATEGY, SENDMSG_QUEUE, strategy, device);
+ }
+
+ /*package*/ void postSaveRemovePreferredDeviceForStrategy(int strategy) {
+ sendIMsgNoDelay(MSG_I_SAVE_REMOVE_PREF_DEVICE_FOR_STRATEGY, SENDMSG_QUEUE, strategy);
+ }
+
//---------------------------------------------------------------------
// Method forwarding between the helper classes (BtHelper, AudioDeviceInventory)
// only call from a "handle"* method or "on"* method
@@ -581,19 +600,11 @@ import java.io.PrintWriter;
sendMsgNoDelay(MSG_REPORT_NEW_ROUTES, SENDMSG_NOOP);
}
- /*package*/ void cancelA2dpDockTimeout() {
- mBrokerHandler.removeMessages(MSG_IL_BTA2DP_DOCK_TIMEOUT);
- }
-
/*package*/ void postA2dpActiveDeviceChange(
@NonNull BtHelper.BluetoothA2dpDeviceInfo btDeviceInfo) {
sendLMsgNoDelay(MSG_L_A2DP_ACTIVE_DEVICE_CHANGE, SENDMSG_QUEUE, btDeviceInfo);
}
- /*package*/ boolean hasScheduledA2dpDockTimeout() {
- return mBrokerHandler.hasMessages(MSG_IL_BTA2DP_DOCK_TIMEOUT);
- }
-
// must be called synchronized on mConnectedDevices
/*package*/ boolean hasScheduledA2dpSinkConnectionState(BluetoothDevice btDevice) {
return (mBrokerHandler.hasMessages(MSG_IL_SET_A2DP_SINK_CONNECTION_STATE_CONNECTED,
@@ -602,8 +613,8 @@ import java.io.PrintWriter;
new BtHelper.BluetoothA2dpDeviceInfo(btDevice)));
}
- /*package*/ void setA2dpDockTimeout(String address, int a2dpCodec, int delayMs) {
- sendILMsg(MSG_IL_BTA2DP_DOCK_TIMEOUT, SENDMSG_QUEUE, a2dpCodec, address, delayMs);
+ /*package*/ void setA2dpTimeout(String address, int a2dpCodec, int delayMs) {
+ sendILMsg(MSG_IL_BTA2DP_TIMEOUT, SENDMSG_QUEUE, a2dpCodec, address, delayMs);
}
/*package*/ void setAvrcpAbsoluteVolumeSupported(boolean supported) {
@@ -631,6 +642,7 @@ import java.io.PrintWriter;
} else {
pw.println("Message handler is null");
}
+ mDeviceInventory.dump(pw, prefix);
}
//---------------------------------------------------------------------
@@ -761,7 +773,7 @@ import java.io.PrintWriter;
}
}
break;
- case MSG_IL_BTA2DP_DOCK_TIMEOUT:
+ case MSG_IL_BTA2DP_TIMEOUT:
// msg.obj == address of BTA2DP device
synchronized (mDeviceStateLock) {
mDeviceInventory.onMakeA2dpDeviceUnavailableNow((String) msg.obj, msg.arg1);
@@ -890,6 +902,15 @@ import java.io.PrintWriter;
info.mDevice, info.mState, info.mSupprNoisy, info.mMusicDevice);
}
} break;
+ case MSG_IL_SAVE_PREF_DEVICE_FOR_STRATEGY: {
+ final int strategy = msg.arg1;
+ final AudioDeviceAddress device = (AudioDeviceAddress) msg.obj;
+ mDeviceInventory.onSaveSetPreferredDevice(strategy, device);
+ } break;
+ case MSG_I_SAVE_REMOVE_PREF_DEVICE_FOR_STRATEGY: {
+ final int strategy = msg.arg1;
+ mDeviceInventory.onSaveRemovePreferredDevice(strategy);
+ } break;
default:
Log.wtf(TAG, "Invalid message " + msg.what);
}
@@ -916,7 +937,7 @@ import java.io.PrintWriter;
private static final int MSG_IL_SET_A2DP_SOURCE_CONNECTION_STATE = 7;
private static final int MSG_IL_SET_HEARING_AID_CONNECTION_STATE = 8;
private static final int MSG_BT_HEADSET_CNCT_FAILED = 9;
- private static final int MSG_IL_BTA2DP_DOCK_TIMEOUT = 10;
+ private static final int MSG_IL_BTA2DP_TIMEOUT = 10;
private static final int MSG_L_A2DP_DEVICE_CONFIG_CHANGE = 11;
private static final int MSG_BROADCAST_AUDIO_BECOMING_NOISY = 12;
private static final int MSG_REPORT_NEW_ROUTES = 13;
@@ -941,6 +962,8 @@ import java.io.PrintWriter;
private static final int MSG_L_HEARING_AID_DEVICE_CONNECTION_CHANGE_EXT = 31;
// a ScoClient died in BtHelper
private static final int MSG_L_SCOCLIENT_DIED = 32;
+ private static final int MSG_IL_SAVE_PREF_DEVICE_FOR_STRATEGY = 33;
+ private static final int MSG_I_SAVE_REMOVE_PREF_DEVICE_FOR_STRATEGY = 34;
private static boolean isMessageHandledUnderWakelock(int msgId) {
@@ -950,7 +973,7 @@ import java.io.PrintWriter;
case MSG_IL_SET_A2DP_SINK_CONNECTION_STATE_DISCONNECTED:
case MSG_IL_SET_A2DP_SOURCE_CONNECTION_STATE:
case MSG_IL_SET_HEARING_AID_CONNECTION_STATE:
- case MSG_IL_BTA2DP_DOCK_TIMEOUT:
+ case MSG_IL_BTA2DP_TIMEOUT:
case MSG_L_A2DP_DEVICE_CONFIG_CHANGE:
case MSG_TOGGLE_HDMI:
case MSG_L_A2DP_ACTIVE_DEVICE_CHANGE:
@@ -1040,7 +1063,7 @@ import java.io.PrintWriter;
case MSG_IL_SET_A2DP_SINK_CONNECTION_STATE_DISCONNECTED:
case MSG_IL_SET_HEARING_AID_CONNECTION_STATE:
case MSG_L_SET_WIRED_DEVICE_CONNECTION_STATE:
- case MSG_IL_BTA2DP_DOCK_TIMEOUT:
+ case MSG_IL_BTA2DP_TIMEOUT:
case MSG_L_A2DP_DEVICE_CONFIG_CHANGE:
case MSG_L_A2DP_ACTIVE_DEVICE_CHANGE:
if (sLastDeviceConnectMsgTime >= time) {
diff --git a/services/core/java/com/android/server/audio/AudioDeviceInventory.java b/services/core/java/com/android/server/audio/AudioDeviceInventory.java
index 37add3da5a48..352d0d56ca8a 100644
--- a/services/core/java/com/android/server/audio/AudioDeviceInventory.java
+++ b/services/core/java/com/android/server/audio/AudioDeviceInventory.java
@@ -23,6 +23,7 @@ import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHearingAid;
import android.bluetooth.BluetoothProfile;
import android.content.Intent;
+import android.media.AudioDeviceAddress;
import android.media.AudioDevicePort;
import android.media.AudioFormat;
import android.media.AudioManager;
@@ -35,6 +36,7 @@ import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.os.UserHandle;
import android.text.TextUtils;
+import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.Log;
import android.util.Slog;
@@ -42,6 +44,7 @@ import android.util.Slog;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
+import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
@@ -56,14 +59,25 @@ public class AudioDeviceInventory {
private static final String TAG = "AS.AudioDeviceInventory";
- // Actual list of connected devices
+ // lock to synchronize all access to mConnectedDevices and mApmConnectedDevices
+ private final Object mDevicesLock = new Object();
+
+ // List of connected devices
// Key for map created from DeviceInfo.makeDeviceListKey()
+ @GuardedBy("mDevicesLock")
private final LinkedHashMap<String, DeviceInfo> mConnectedDevices = new LinkedHashMap<>();
- private @NonNull AudioDeviceBroker mDeviceBroker;
+ // List of devices actually connected to AudioPolicy (through AudioSystem), only one
+ // by device type, which is used as the key, value is the DeviceInfo generated key.
+ // For the moment only for A2DP sink devices.
+ // TODO: extend to all device types
+ @GuardedBy("mDevicesLock")
+ private final ArrayMap<Integer, String> mApmConnectedDevices = new ArrayMap<>();
+
+ // List of preferred devices for strategies
+ private final ArrayMap<Integer, AudioDeviceAddress> mPreferredDevices = new ArrayMap<>();
- // cache of the address of the last dock the device was connected to
- private String mDockAddress;
+ private @NonNull AudioDeviceBroker mDeviceBroker;
// Monitoring of audio routes. Protected by mAudioRoutes.
final AudioRoutesInfo mCurAudioRoutes = new AudioRoutesInfo();
@@ -91,30 +105,35 @@ public class AudioDeviceInventory {
*/
private static class DeviceInfo {
final int mDeviceType;
- final String mDeviceName;
- final String mDeviceAddress;
+ final @NonNull String mDeviceName;
+ final @NonNull String mDeviceAddress;
int mDeviceCodecFormat;
DeviceInfo(int deviceType, String deviceName, String deviceAddress, int deviceCodecFormat) {
mDeviceType = deviceType;
- mDeviceName = deviceName;
- mDeviceAddress = deviceAddress;
+ mDeviceName = deviceName == null ? "" : deviceName;
+ mDeviceAddress = deviceAddress == null ? "" : deviceAddress;
mDeviceCodecFormat = deviceCodecFormat;
}
@Override
public String toString() {
return "[DeviceInfo: type:0x" + Integer.toHexString(mDeviceType)
- + " name:" + mDeviceName
+ + " (" + AudioSystem.getDeviceName(mDeviceType)
+ + ") name:" + mDeviceName
+ " addr:" + mDeviceAddress
+ " codec: " + Integer.toHexString(mDeviceCodecFormat) + "]";
}
+ @NonNull String getKey() {
+ return makeDeviceListKey(mDeviceType, mDeviceAddress);
+ }
+
/**
* Generate a unique key for the mConnectedDevices List by composing the device "type"
* and the "address" associated with a specific instance of that device type
*/
- private static String makeDeviceListKey(int device, String deviceAddress) {
+ @NonNull private static String makeDeviceListKey(int device, String deviceAddress) {
return "0x" + Integer.toHexString(device) + ":" + deviceAddress;
}
}
@@ -140,14 +159,31 @@ public class AudioDeviceInventory {
}
//------------------------------------------------------------
+ /*package*/ void dump(PrintWriter pw, String prefix) {
+ pw.println("\n" + prefix + "Preferred devices for strategy:");
+ mPreferredDevices.forEach((strategy, device) -> {
+ pw.println(" " + prefix + "strategy:" + strategy + " device:" + device); });
+ pw.println("\n" + prefix + "Connected devices:");
+ mConnectedDevices.forEach((key, deviceInfo) -> {
+ pw.println(" " + prefix + deviceInfo.toString()); });
+ pw.println("\n" + prefix + "APM Connected device (A2DP sink only):");
+ mApmConnectedDevices.forEach((keyType, valueAddress) -> {
+ pw.println(" " + prefix + " type:0x" + Integer.toHexString(keyType)
+ + " (" + AudioSystem.getDeviceName(keyType)
+ + ") addr:" + valueAddress); });
+ }
+
+ //------------------------------------------------------------
// Message handling from AudioDeviceBroker
/**
* Restore previously connected devices. Use in case of audio server crash
* (see AudioService.onAudioServerDied() method)
*/
+ // Always executed on AudioDeviceBroker message queue
/*package*/ void onRestoreDevices() {
- synchronized (mConnectedDevices) {
+ synchronized (mDevicesLock) {
+ //TODO iterate on mApmConnectedDevices instead once it handles all device types
for (DeviceInfo di : mConnectedDevices.values()) {
AudioSystem.setDeviceConnectionState(
di.mDeviceType,
@@ -157,6 +193,10 @@ public class AudioDeviceInventory {
di.mDeviceCodecFormat);
}
}
+ synchronized (mPreferredDevices) {
+ mPreferredDevices.forEach((strategy, device) -> {
+ AudioSystem.setPreferredDeviceForStrategy(strategy, device); });
+ }
}
// only public for mocking/spying
@@ -168,9 +208,12 @@ public class AudioDeviceInventory {
int a2dpVolume = btInfo.getVolume();
if (AudioService.DEBUG_DEVICES) {
Log.d(TAG, "onSetA2dpSinkConnectionState btDevice=" + btDevice + " state="
- + state + " is dock=" + btDevice.isBluetoothDock() + " vol=" + a2dpVolume);
+ + state + " vol=" + a2dpVolume);
}
String address = btDevice.getAddress();
+ if (address == null) {
+ address = "";
+ }
if (!BluetoothAdapter.checkBluetoothAddress(address)) {
address = "";
}
@@ -182,7 +225,7 @@ public class AudioDeviceInventory {
+ " codec=" + a2dpCodec
+ " vol=" + a2dpVolume));
- synchronized (mConnectedDevices) {
+ synchronized (mDevicesLock) {
final String key = DeviceInfo.makeDeviceListKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
btDevice.getAddress());
final DeviceInfo di = mConnectedDevices.get(key);
@@ -196,42 +239,17 @@ public class AudioDeviceInventory {
mDeviceBroker.postBluetoothA2dpDeviceConfigChange(btDevice);
}
} else {
- if (btDevice.isBluetoothDock()) {
- if (state == BluetoothProfile.STATE_DISCONNECTED) {
- // introduction of a delay for transient disconnections of docks when
- // power is rapidly turned off/on, this message will be canceled if
- // we reconnect the dock under a preset delay
- makeA2dpDeviceUnavailableLater(address,
- AudioDeviceBroker.BTA2DP_DOCK_TIMEOUT_MS);
- // the next time isConnected is evaluated, it will be false for the dock
- }
- } else {
- makeA2dpDeviceUnavailableNow(address, di.mDeviceCodecFormat);
- }
- }
- } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) {
- if (btDevice.isBluetoothDock()) {
- // this could be a reconnection after a transient disconnection
- mDeviceBroker.cancelA2dpDockTimeout();
- mDockAddress = address;
- } else {
- // this could be a connection of another A2DP device before the timeout of
- // a dock: cancel the dock timeout, and make the dock unavailable now
- if (mDeviceBroker.hasScheduledA2dpDockTimeout() && mDockAddress != null) {
- mDeviceBroker.cancelA2dpDockTimeout();
- makeA2dpDeviceUnavailableNow(mDockAddress,
- AudioSystem.AUDIO_FORMAT_DEFAULT);
- }
+ makeA2dpDeviceUnavailableNow(address, di.mDeviceCodecFormat);
}
- if (a2dpVolume != -1) {
- mDeviceBroker.postSetVolumeIndexOnDevice(AudioSystem.STREAM_MUSIC,
- // convert index to internal representation in VolumeStreamState
- a2dpVolume * 10,
- AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, "onSetA2dpSinkConnectionState");
- }
- makeA2dpDeviceAvailable(address, BtHelper.getName(btDevice),
- "onSetA2dpSinkConnectionState", a2dpCodec);
}
+ if (a2dpVolume != -1) {
+ mDeviceBroker.postSetVolumeIndexOnDevice(AudioSystem.STREAM_MUSIC,
+ // convert index to internal representation in VolumeStreamState
+ a2dpVolume * 10,
+ AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, "onSetA2dpSinkConnectionState");
+ }
+ makeA2dpDeviceAvailable(address, BtHelper.getName(btDevice),
+ "onSetA2dpSinkConnectionState", a2dpCodec);
}
}
@@ -247,7 +265,7 @@ public class AudioDeviceInventory {
address = "";
}
- synchronized (mConnectedDevices) {
+ synchronized (mDevicesLock) {
final String key = DeviceInfo.makeDeviceListKey(
AudioSystem.DEVICE_IN_BLUETOOTH_A2DP, address);
final DeviceInfo di = mConnectedDevices.get(key);
@@ -270,7 +288,7 @@ public class AudioDeviceInventory {
AudioService.sDeviceLogger.log(new AudioEventLogger.StringEvent(
"onSetHearingAidConnectionState addr=" + address));
- synchronized (mConnectedDevices) {
+ synchronized (mDevicesLock) {
final String key = DeviceInfo.makeDeviceListKey(AudioSystem.DEVICE_OUT_HEARING_AID,
btDevice.getAddress());
final DeviceInfo di = mConnectedDevices.get(key);
@@ -306,7 +324,7 @@ public class AudioDeviceInventory {
"onBluetoothA2dpActiveDeviceChange addr=" + address
+ " event=" + BtHelper.a2dpDeviceEventToString(event)));
- synchronized (mConnectedDevices) {
+ synchronized (mDevicesLock) {
if (mDeviceBroker.hasScheduledA2dpSinkConnectionState(btDevice)) {
AudioService.sDeviceLogger.log(new AudioEventLogger.StringEvent(
"A2dp config change ignored (scheduled connection change)"));
@@ -349,7 +367,7 @@ public class AudioDeviceInventory {
}
/*package*/ void onMakeA2dpDeviceUnavailableNow(String address, int a2dpCodec) {
- synchronized (mConnectedDevices) {
+ synchronized (mDevicesLock) {
makeA2dpDeviceUnavailableNow(address, a2dpCodec);
}
}
@@ -386,7 +404,7 @@ public class AudioDeviceInventory {
AudioDeviceInventory.WiredDeviceConnectionState wdcs) {
AudioService.sDeviceLogger.log(new AudioServiceEvents.WiredDevConnectEvent(wdcs));
- synchronized (mConnectedDevices) {
+ synchronized (mDevicesLock) {
if ((wdcs.mState == AudioService.CONNECTION_STATE_DISCONNECTED)
&& DEVICE_OVERRIDE_A2DP_ROUTE_ON_PLUG_SET.contains(wdcs.mType)) {
mDeviceBroker.setBluetoothA2dpOnInt(true,
@@ -414,7 +432,7 @@ public class AudioDeviceInventory {
}
/*package*/ void onToggleHdmi() {
- synchronized (mConnectedDevices) {
+ synchronized (mDevicesLock) {
// Is HDMI connected?
final String key = DeviceInfo.makeDeviceListKey(AudioSystem.DEVICE_OUT_HDMI, "");
final DeviceInfo di = mConnectedDevices.get(key);
@@ -431,9 +449,41 @@ public class AudioDeviceInventory {
"android"); // reconnect
}
}
+
+ /*package*/ void onSaveSetPreferredDevice(int strategy, @NonNull AudioDeviceAddress device) {
+ mPreferredDevices.put(strategy, device);
+ }
+
+ /*package*/ void onSaveRemovePreferredDevice(int strategy) {
+ mPreferredDevices.remove(strategy);
+ }
+
//------------------------------------------------------------
//
+ /*package*/ int setPreferredDeviceForStrategySync(int strategy,
+ @NonNull AudioDeviceAddress device) {
+ final long identity = Binder.clearCallingIdentity();
+ final int status = AudioSystem.setPreferredDeviceForStrategy(strategy, device);
+ Binder.restoreCallingIdentity(identity);
+
+ if (status == AudioSystem.SUCCESS) {
+ mDeviceBroker.postSaveSetPreferredDeviceForStrategy(strategy, device);
+ }
+ return status;
+ }
+
+ /*package*/ int removePreferredDeviceForStrategySync(int strategy) {
+ final long identity = Binder.clearCallingIdentity();
+ final int status = AudioSystem.removePreferredDeviceForStrategy(strategy);
+ Binder.restoreCallingIdentity(identity);
+
+ if (status == AudioSystem.SUCCESS) {
+ mDeviceBroker.postSaveRemovePreferredDeviceForStrategy(strategy);
+ }
+ return status;
+ }
+
/**
* Implements the communication with AudioSystem to (dis)connect a device in the native layers
* @param connect true if connection
@@ -449,7 +499,7 @@ public class AudioDeviceInventory {
+ Integer.toHexString(device) + " address:" + address
+ " name:" + deviceName + ")");
}
- synchronized (mConnectedDevices) {
+ synchronized (mDevicesLock) {
final String deviceKey = DeviceInfo.makeDeviceListKey(device, address);
if (AudioService.DEBUG_DEVICES) {
Slog.i(TAG, "deviceKey:" + deviceKey);
@@ -488,7 +538,7 @@ public class AudioDeviceInventory {
/*package*/ void disconnectA2dp() {
- synchronized (mConnectedDevices) {
+ synchronized (mDevicesLock) {
final ArraySet<String> toRemove = new ArraySet<>();
// Disconnect ALL DEVICE_OUT_BLUETOOTH_A2DP devices
mConnectedDevices.values().forEach(deviceInfo -> {
@@ -508,7 +558,7 @@ public class AudioDeviceInventory {
}
/*package*/ void disconnectA2dpSink() {
- synchronized (mConnectedDevices) {
+ synchronized (mDevicesLock) {
final ArraySet<String> toRemove = new ArraySet<>();
// Disconnect ALL DEVICE_IN_BLUETOOTH_A2DP devices
mConnectedDevices.values().forEach(deviceInfo -> {
@@ -521,7 +571,7 @@ public class AudioDeviceInventory {
}
/*package*/ void disconnectHearingAid() {
- synchronized (mConnectedDevices) {
+ synchronized (mDevicesLock) {
final ArraySet<String> toRemove = new ArraySet<>();
// Disconnect ALL DEVICE_OUT_HEARING_AID devices
mConnectedDevices.values().forEach(deviceInfo -> {
@@ -545,7 +595,7 @@ public class AudioDeviceInventory {
// from AudioSystem
/*package*/ int checkSendBecomingNoisyIntent(int device,
@AudioService.ConnectionState int state, int musicDevice) {
- synchronized (mConnectedDevices) {
+ synchronized (mDevicesLock) {
return checkSendBecomingNoisyIntentInt(device, state, musicDevice);
}
}
@@ -572,7 +622,7 @@ public class AudioDeviceInventory {
if (profile != BluetoothProfile.A2DP && profile != BluetoothProfile.A2DP_SINK) {
throw new IllegalArgumentException("invalid profile " + profile);
}
- synchronized (mConnectedDevices) {
+ synchronized (mDevicesLock) {
if (profile == BluetoothProfile.A2DP && !suppressNoisyIntent) {
@AudioService.ConnectionState int asState =
(state == BluetoothA2dp.STATE_CONNECTED)
@@ -612,7 +662,7 @@ public class AudioDeviceInventory {
/*package*/ int setWiredDeviceConnectionState(int type, @AudioService.ConnectionState int state,
String address, String name, String caller) {
- synchronized (mConnectedDevices) {
+ synchronized (mDevicesLock) {
int delay = checkSendBecomingNoisyIntentInt(type, state, AudioSystem.DEVICE_NONE);
mDeviceBroker.postSetWiredDeviceConnectionState(
new WiredDeviceConnectionState(type, state, address, name, caller),
@@ -625,7 +675,7 @@ public class AudioDeviceInventory {
@NonNull BluetoothDevice device, @AudioService.BtProfileConnectionState int state,
boolean suppressNoisyIntent, int musicDevice) {
int delay;
- synchronized (mConnectedDevices) {
+ synchronized (mDevicesLock) {
if (!suppressNoisyIntent) {
int intState = (state == BluetoothHearingAid.STATE_CONNECTED) ? 1 : 0;
delay = checkSendBecomingNoisyIntentInt(AudioSystem.DEVICE_OUT_HEARING_AID,
@@ -642,42 +692,58 @@ public class AudioDeviceInventory {
//-------------------------------------------------------------------
// Internal utilities
- @GuardedBy("mConnectedDevices")
+ @GuardedBy("mDevicesLock")
private void makeA2dpDeviceAvailable(String address, String name, String eventSource,
int a2dpCodec) {
// enable A2DP before notifying A2DP connection to avoid unnecessary processing in
// audio policy manager
mDeviceBroker.setBluetoothA2dpOnInt(true, eventSource);
+ // at this point there could be another A2DP device already connected in APM, but it
+ // doesn't matter as this new one will overwrite the previous one
AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
AudioSystem.DEVICE_STATE_AVAILABLE, address, name, a2dpCodec);
// Reset A2DP suspend state each time a new sink is connected
AudioSystem.setParameters("A2dpSuspended=false");
- mConnectedDevices.put(
- DeviceInfo.makeDeviceListKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, address),
- new DeviceInfo(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, name,
- address, a2dpCodec));
+
+ final DeviceInfo di = new DeviceInfo(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, name,
+ address, a2dpCodec);
+ final String diKey = di.getKey();
+ mConnectedDevices.put(diKey, di);
+ // on a connection always overwrite the device seen by AudioPolicy, see comment above when
+ // calling AudioSystem
+ mApmConnectedDevices.put(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, diKey);
+
mDeviceBroker.postAccessoryPlugMediaUnmute(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
setCurrentAudioRouteNameIfPossible(name);
}
- @GuardedBy("mConnectedDevices")
+ @GuardedBy("mDevicesLock")
private void makeA2dpDeviceUnavailableNow(String address, int a2dpCodec) {
if (address == null) {
return;
}
+ final String deviceToRemoveKey =
+ DeviceInfo.makeDeviceListKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, address);
+
+ mConnectedDevices.remove(deviceToRemoveKey);
+ if (!deviceToRemoveKey
+ .equals(mApmConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP))) {
+ // removing A2DP device not currently used by AudioPolicy, log but don't act on it
+ AudioService.sDeviceLogger.log((new AudioEventLogger.StringEvent(
+ "A2DP device " + address + " made unavailable, was not used")).printLog(TAG));
+ return;
+ }
+
+ // device to remove was visible by APM, update APM
mDeviceBroker.setAvrcpAbsoluteVolumeSupported(false);
AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
AudioSystem.DEVICE_STATE_UNAVAILABLE, address, "", a2dpCodec);
- mConnectedDevices.remove(
- DeviceInfo.makeDeviceListKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, address));
+ mApmConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
// Remove A2DP routes as well
setCurrentAudioRouteNameIfPossible(null);
- if (mDockAddress == address) {
- mDockAddress = null;
- }
}
- @GuardedBy("mConnectedDevices")
+ @GuardedBy("mDevicesLock")
private void makeA2dpDeviceUnavailableLater(String address, int delayMs) {
// prevent any activity on the A2DP audio output to avoid unwanted
// reconnection of the sink.
@@ -691,11 +757,11 @@ public class AudioDeviceInventory {
// the device will be made unavailable later, so consider it disconnected right away
mConnectedDevices.remove(deviceKey);
// send the delayed message to make the device unavailable later
- mDeviceBroker.setA2dpDockTimeout(address, a2dpCodec, delayMs);
+ mDeviceBroker.setA2dpTimeout(address, a2dpCodec, delayMs);
}
- @GuardedBy("mConnectedDevices")
+ @GuardedBy("mDevicesLock")
private void makeA2dpSrcAvailable(String address) {
AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP,
AudioSystem.DEVICE_STATE_AVAILABLE, address, "",
@@ -706,7 +772,7 @@ public class AudioDeviceInventory {
address, AudioSystem.AUDIO_FORMAT_DEFAULT));
}
- @GuardedBy("mConnectedDevices")
+ @GuardedBy("mDevicesLock")
private void makeA2dpSrcUnavailable(String address) {
AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP,
AudioSystem.DEVICE_STATE_UNAVAILABLE, address, "",
@@ -715,7 +781,7 @@ public class AudioDeviceInventory {
DeviceInfo.makeDeviceListKey(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP, address));
}
- @GuardedBy("mConnectedDevices")
+ @GuardedBy("mDevicesLock")
private void makeHearingAidDeviceAvailable(
String address, String name, int streamType, String eventSource) {
final int hearingAidVolIndex = mDeviceBroker.getVssVolumeForDevice(streamType,
@@ -735,7 +801,7 @@ public class AudioDeviceInventory {
setCurrentAudioRouteNameIfPossible(name);
}
- @GuardedBy("mConnectedDevices")
+ @GuardedBy("mDevicesLock")
private void makeHearingAidDeviceUnavailable(String address) {
AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_HEARING_AID,
AudioSystem.DEVICE_STATE_UNAVAILABLE, address, "",
@@ -746,7 +812,7 @@ public class AudioDeviceInventory {
setCurrentAudioRouteNameIfPossible(null);
}
- @GuardedBy("mConnectedDevices")
+ @GuardedBy("mDevicesLock")
private void setCurrentAudioRouteNameIfPossible(String name) {
synchronized (mCurAudioRoutes) {
if (TextUtils.equals(mCurAudioRoutes.bluetoothName, name)) {
@@ -759,7 +825,7 @@ public class AudioDeviceInventory {
}
}
- @GuardedBy("mConnectedDevices")
+ @GuardedBy("mDevicesLock")
private boolean isCurrentDeviceConnected() {
return mConnectedDevices.values().stream().anyMatch(deviceInfo ->
TextUtils.equals(deviceInfo.mDeviceName, mCurAudioRoutes.bluetoothName));
@@ -787,7 +853,7 @@ public class AudioDeviceInventory {
// must be called before removing the device from mConnectedDevices
// musicDevice argument is used when not AudioSystem.DEVICE_NONE instead of querying
// from AudioSystem
- @GuardedBy("mConnectedDevices")
+ @GuardedBy("mDevicesLock")
private int checkSendBecomingNoisyIntentInt(int device,
@AudioService.ConnectionState int state, int musicDevice) {
if (state != AudioService.CONNECTION_STATE_DISCONNECTED) {
@@ -995,7 +1061,7 @@ public class AudioDeviceInventory {
public boolean isA2dpDeviceConnected(@NonNull BluetoothDevice device) {
final String key = DeviceInfo.makeDeviceListKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
device.getAddress());
- synchronized (mConnectedDevices) {
+ synchronized (mDevicesLock) {
return (mConnectedDevices.get(key) != null);
}
}
diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java
index 4bf1de66b408..335cac86b543 100644
--- a/services/core/java/com/android/server/audio/AudioService.java
+++ b/services/core/java/com/android/server/audio/AudioService.java
@@ -63,6 +63,8 @@ import android.hardware.input.InputManager;
import android.hardware.usb.UsbManager;
import android.hidl.manager.V1_0.IServiceManager;
import android.media.AudioAttributes;
+import android.media.AudioDeviceAddress;
+import android.media.AudioDeviceInfo;
import android.media.AudioFocusInfo;
import android.media.AudioFocusRequest;
import android.media.AudioFormat;
@@ -1633,6 +1635,60 @@ public class AudioService extends IAudioService.Stub
///////////////////////////////////////////////////////////////////////////
// IPC methods
///////////////////////////////////////////////////////////////////////////
+ /** @see AudioManager#setPreferredDeviceForStrategy(AudioProductStrategy, AudioDeviceInfo) */
+ public int setPreferredDeviceForStrategy(int strategy, AudioDeviceAddress device) {
+ if (device == null) {
+ return AudioSystem.ERROR;
+ }
+ enforceModifyAudioRoutingPermission();
+ final String logString = String.format(
+ "setPreferredDeviceForStrategy u/pid:%d/%d strat:%d dev:%s",
+ Binder.getCallingUid(), Binder.getCallingPid(), strategy, device.toString());
+ sDeviceLogger.log(new AudioEventLogger.StringEvent(logString).printLog(TAG));
+ if (device.getRole() == AudioDeviceAddress.ROLE_INPUT) {
+ Log.e(TAG, "Unsupported input routing in " + logString);
+ return AudioSystem.ERROR;
+ }
+
+ final int status = mDeviceBroker.setPreferredDeviceForStrategySync(strategy, device);
+ if (status != AudioSystem.SUCCESS) {
+ Log.e(TAG, String.format("Error %d in %s)", status, logString));
+ }
+
+ return status;
+ }
+
+ /** @see AudioManager#removePreferredDeviceForStrategy(AudioProductStrategy) */
+ public int removePreferredDeviceForStrategy(int strategy) {
+ enforceModifyAudioRoutingPermission();
+ final String logString =
+ String.format("removePreferredDeviceForStrategy strat:%d", strategy);
+ sDeviceLogger.log(new AudioEventLogger.StringEvent(logString).printLog(TAG));
+
+ final int status = mDeviceBroker.removePreferredDeviceForStrategySync(strategy);
+ if (status != AudioSystem.SUCCESS) {
+ Log.e(TAG, String.format("Error %d in %s)", status, logString));
+ }
+ return status;
+ }
+
+ /** @see AudioManager#getPreferredDeviceForStrategy(AudioProductStrategy) */
+ public AudioDeviceAddress getPreferredDeviceForStrategy(int strategy) {
+ enforceModifyAudioRoutingPermission();
+ AudioDeviceAddress[] devices = new AudioDeviceAddress[1];
+ final long identity = Binder.clearCallingIdentity();
+ final int status = AudioSystem.getPreferredDeviceForStrategy(strategy, devices);
+ Binder.restoreCallingIdentity(identity);
+ if (status != AudioSystem.SUCCESS) {
+ Log.e(TAG, String.format("Error %d in getPreferredDeviceForStrategy(%d)",
+ status, strategy));
+ return null;
+ } else {
+ return devices[0];
+ }
+ }
+
+
/** @see AudioManager#adjustVolume(int, int) */
public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags,
String callingPackage, String caller) {
@@ -4432,12 +4488,13 @@ public class AudioService extends IAudioService.Stub
}
if (mNm.getZenMode() != Settings.Global.ZEN_MODE_NO_INTERRUPTIONS
+ && !isStreamMutedByRingerOrZenMode(AudioSystem.STREAM_MUSIC)
&& DEVICE_MEDIA_UNMUTED_ON_PLUG_SET.contains(newDevice)
&& mStreamStates[AudioSystem.STREAM_MUSIC].mIsMuted
&& mStreamStates[AudioSystem.STREAM_MUSIC].getIndex(newDevice) != 0
&& (newDevice & AudioSystem.getDevicesForStream(AudioSystem.STREAM_MUSIC)) != 0) {
if (DEBUG_VOL) {
- Log.i(TAG, String.format(" onAccessoryPlugMediaUnmute unmuting device=%d [%s]",
+ Log.i(TAG, String.format("onAccessoryPlugMediaUnmute unmuting device=%d [%s]",
newDevice, AudioSystem.getOutputDeviceName(newDevice)));
}
mStreamStates[AudioSystem.STREAM_MUSIC].mute(false);
@@ -6111,6 +6168,7 @@ public class AudioService extends IAudioService.Stub
pw.println("\nRinger mode: ");
pw.println("- mode (internal) = " + RINGER_MODE_NAMES[mRingerMode]);
pw.println("- mode (external) = " + RINGER_MODE_NAMES[mRingerModeExternal]);
+ pw.println("- zen mode:" + Settings.Global.zenModeToString(mNm.getZenMode()));
dumpRingerModeStreams(pw, "affected", mRingerModeAffectedStreams);
dumpRingerModeStreams(pw, "muted", mRingerAndZenModeMutedStreams);
pw.print("- delegate = "); pw.println(mRingerModeDelegate);
diff --git a/services/core/java/com/android/server/audio/BtHelper.java b/services/core/java/com/android/server/audio/BtHelper.java
index 9f1a6bd15ac3..36332c0ad25c 100644
--- a/services/core/java/com/android/server/audio/BtHelper.java
+++ b/services/core/java/com/android/server/audio/BtHelper.java
@@ -295,6 +295,7 @@ public class BtHelper {
&& mScoAudioState != SCO_STATE_DEACTIVATE_REQ) {
mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
}
+ broadcast = false;
break;
default:
// do not broadcast CONNECTING or invalid state
diff --git a/services/core/java/com/android/server/biometrics/AuthService.java b/services/core/java/com/android/server/biometrics/AuthService.java
index 22cb507d449f..0d88388742d2 100644
--- a/services/core/java/com/android/server/biometrics/AuthService.java
+++ b/services/core/java/com/android/server/biometrics/AuthService.java
@@ -26,10 +26,12 @@ import static android.Manifest.permission.USE_FINGERPRINT;
import static android.hardware.biometrics.BiometricAuthenticator.TYPE_FACE;
import static android.hardware.biometrics.BiometricAuthenticator.TYPE_FINGERPRINT;
import static android.hardware.biometrics.BiometricAuthenticator.TYPE_IRIS;
+import static android.hardware.biometrics.BiometricManager.Authenticators;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.biometrics.IAuthService;
+import android.hardware.biometrics.IBiometricAuthenticator;
import android.hardware.biometrics.IBiometricEnabledOnKeyguardCallback;
import android.hardware.biometrics.IBiometricService;
import android.hardware.biometrics.IBiometricServiceReceiver;
@@ -43,6 +45,7 @@ import android.os.ServiceManager;
import android.os.UserHandle;
import android.util.Slog;
+import com.android.internal.R;
import com.android.internal.annotations.VisibleForTesting;
import com.android.server.SystemService;
import com.android.server.biometrics.face.FaceAuthenticator;
@@ -57,9 +60,6 @@ public class AuthService extends SystemService {
private static final String TAG = "AuthService";
private static final boolean DEBUG = false;
- private final boolean mHasFeatureFace;
- private final boolean mHasFeatureFingerprint;
- private final boolean mHasFeatureIris;
private final Injector mInjector;
private IBiometricService mBiometricService;
@@ -89,6 +89,16 @@ public class AuthService extends SystemService {
public void publishBinderService(AuthService service, IAuthService.Stub impl) {
service.publishBinderService(Context.AUTH_SERVICE, impl);
}
+
+ /**
+ * Allows to test with various device sensor configurations.
+ * @param context
+ * @return
+ */
+ @VisibleForTesting
+ public String[] getConfiguration(Context context) {
+ return context.getResources().getStringArray(R.array.config_biometric_sensors);
+ }
}
private final class AuthServiceImpl extends IAuthService.Stub {
@@ -119,17 +129,17 @@ public class AuthService extends SystemService {
}
@Override
- public int canAuthenticate(String opPackageName, int userId) throws RemoteException {
+ public int canAuthenticate(String opPackageName, int userId,
+ @Authenticators.Types int authenticators) throws RemoteException {
final int callingUserId = UserHandle.getCallingUserId();
- Slog.d(TAG, "canAuthenticate, userId: " + userId
- + ", callingUserId: " + callingUserId);
-
+ Slog.d(TAG, "canAuthenticate, userId: " + userId + ", callingUserId: " + callingUserId
+ + ", authenticators: " + authenticators);
if (userId != callingUserId) {
checkInternalPermission();
} else {
checkPermission();
}
- return mBiometricService.canAuthenticate(opPackageName, userId);
+ return mBiometricService.canAuthenticate(opPackageName, userId, authenticators);
}
@Override
@@ -169,47 +179,56 @@ public class AuthService extends SystemService {
mInjector = injector;
mImpl = new AuthServiceImpl();
final PackageManager pm = context.getPackageManager();
- mHasFeatureFace = pm.hasSystemFeature(PackageManager.FEATURE_FACE);
- mHasFeatureFingerprint = pm.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT);
- mHasFeatureIris = pm.hasSystemFeature(PackageManager.FEATURE_IRIS);
+ }
+
+ private void registerAuthenticator(SensorConfig config) throws RemoteException {
+
+ Slog.d(TAG, "Registering ID: " + config.mId
+ + " Modality: " + config.mModality
+ + " Strength: " + config.mStrength);
+
+ final IBiometricAuthenticator.Stub authenticator;
+
+ switch (config.mModality) {
+ case TYPE_FINGERPRINT:
+ authenticator = new FingerprintAuthenticator(IFingerprintService.Stub.asInterface(
+ ServiceManager.getService(Context.FINGERPRINT_SERVICE)));
+ break;
+
+ case TYPE_FACE:
+ authenticator = new FaceAuthenticator(IFaceService.Stub.asInterface(
+ ServiceManager.getService(Context.FACE_SERVICE)));
+ break;
+
+ case TYPE_IRIS:
+ authenticator = new IrisAuthenticator(IIrisService.Stub.asInterface(
+ ServiceManager.getService(Context.IRIS_SERVICE)));
+ break;
+
+ default:
+ Slog.e(TAG, "Unknown modality: " + config.mModality);
+ return;
+ }
+
+ mBiometricService.registerAuthenticator(config.mId, config.mModality, config.mStrength,
+ authenticator);
}
@Override
public void onStart() {
mBiometricService = mInjector.getBiometricService();
- if (mHasFeatureFace) {
- final FaceAuthenticator faceAuthenticator = new FaceAuthenticator(
- IFaceService.Stub.asInterface(ServiceManager.getService(Context.FACE_SERVICE)));
- try {
- // TODO(b/141025588): Pass down the real id, strength, and modality.
- mBiometricService.registerAuthenticator(0, 0, TYPE_FACE, faceAuthenticator);
- } catch (RemoteException e) {
- Slog.e(TAG, "Remote exception", e);
- }
- }
- if (mHasFeatureFingerprint) {
- final FingerprintAuthenticator fingerprintAuthenticator = new FingerprintAuthenticator(
- IFingerprintService.Stub.asInterface(
- ServiceManager.getService(Context.FINGERPRINT_SERVICE)));
- try {
- // TODO(b/141025588): Pass down the real id, strength, and modality.
- mBiometricService.registerAuthenticator(1, 0, TYPE_FINGERPRINT,
- fingerprintAuthenticator);
- } catch (RemoteException e) {
- Slog.e(TAG, "Remote exception", e);
- }
- }
- if (mHasFeatureIris) {
- final IrisAuthenticator irisAuthenticator = new IrisAuthenticator(
- IIrisService.Stub.asInterface(ServiceManager.getService(Context.IRIS_SERVICE)));
+ final String[] configs = mInjector.getConfiguration(getContext());
+
+ for (int i = 0; i < configs.length; i++) {
try {
- // TODO(b/141025588): Pass down the real id, strength, and modality.
- mBiometricService.registerAuthenticator(2, 0, TYPE_IRIS, irisAuthenticator);
+ registerAuthenticator(new SensorConfig(configs[i]));
} catch (RemoteException e) {
Slog.e(TAG, "Remote exception", e);
}
+
}
+
mInjector.publishBinderService(this, mImpl);
}
diff --git a/services/core/java/com/android/server/biometrics/BiometricService.java b/services/core/java/com/android/server/biometrics/BiometricService.java
index 5d3679389b48..0f51e39d128a 100644
--- a/services/core/java/com/android/server/biometrics/BiometricService.java
+++ b/services/core/java/com/android/server/biometrics/BiometricService.java
@@ -23,15 +23,16 @@ import static android.hardware.biometrics.BiometricAuthenticator.TYPE_FACE;
import static android.hardware.biometrics.BiometricAuthenticator.TYPE_FINGERPRINT;
import static android.hardware.biometrics.BiometricAuthenticator.TYPE_IRIS;
import static android.hardware.biometrics.BiometricAuthenticator.TYPE_NONE;
+import static android.hardware.biometrics.BiometricManager.Authenticators;
import android.app.ActivityManager;
import android.app.IActivityManager;
import android.app.UserSwitchObserver;
+import android.app.trust.ITrustManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
-import android.hardware.biometrics.Authenticator;
import android.hardware.biometrics.BiometricAuthenticator;
import android.hardware.biometrics.BiometricConstants;
import android.hardware.biometrics.BiometricPrompt;
@@ -78,7 +79,7 @@ import java.util.Random;
*/
public class BiometricService extends SystemService {
- private static final String TAG = "BiometricService";
+ static final String TAG = "BiometricService";
private static final boolean DEBUG = true;
private static final int MSG_ON_AUTHENTICATION_SUCCEEDED = 2;
@@ -220,11 +221,15 @@ public class BiometricService extends SystemService {
IStatusBarService mStatusBarService;
@VisibleForTesting
KeyStore mKeyStore;
+ @VisibleForTesting
+ ITrustManager mTrustManager;
// Get and cache the available authenticator (manager) classes. Used since aidl doesn't support
// polymorphism :/
final ArrayList<AuthenticatorWrapper> mAuthenticators = new ArrayList<>();
+ BiometricStrengthController mBiometricStrengthController;
+
// The current authentication session, null if idle/done. We need to track both the current
// and pending sessions since errors may be sent to either.
@VisibleForTesting
@@ -345,17 +350,50 @@ public class BiometricService extends SystemService {
@VisibleForTesting
public static final class AuthenticatorWrapper {
public final int id;
- public final int strength;
+ public final int OEMStrength; // strength as configured by the OEM
+ private int updatedStrength; // strength updated by BiometricStrengthController
public final int modality;
public final IBiometricAuthenticator impl;
- AuthenticatorWrapper(int id, int strength, int modality,
+ AuthenticatorWrapper(int id, int modality, int strength,
IBiometricAuthenticator impl) {
this.id = id;
- this.strength = strength;
this.modality = modality;
+ this.OEMStrength = strength;
+ this.updatedStrength = strength;
this.impl = impl;
}
+
+ /**
+ * Returns the actual strength, taking any updated strengths into effect. Since more bits
+ * means lower strength, the resulting strength is never stronger than the OEM's configured
+ * strength.
+ * @return a bitfield, see {@link Authenticators}
+ */
+ public int getActualStrength() {
+ return OEMStrength | updatedStrength;
+ }
+
+ /**
+ * Stores the updated strength, which takes effect whenever {@link #getActualStrength()}
+ * is checked.
+ * @param newStrength
+ */
+ public void updateStrength(int newStrength) {
+ String log = "updateStrength: Before(" + toString() + ")";
+ updatedStrength = newStrength;
+ log += " After(" + toString() + ")";
+ Slog.d(TAG, log);
+ }
+
+ @Override
+ public String toString() {
+ return "ID(" + id + ")"
+ + " OEMStrength: " + OEMStrength
+ + " updatedStrength: " + updatedStrength
+ + " modality " + modality
+ + " authenticator: " + impl;
+ }
}
@VisibleForTesting
@@ -606,14 +644,14 @@ public class BiometricService extends SystemService {
return;
}
- if (bundle.get(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED) != null) {
- checkInternalPermission();
+ if (!Utils.isValidAuthenticatorConfig(bundle)) {
+ throw new SecurityException("Invalid authenticator configuration");
}
Utils.combineAuthenticatorBundles(bundle);
- // Check the usage of this in system server. Need to remove this check if it becomes
- // a public API.
+ // Check the usage of this in system server. Need to remove this check if it becomes a
+ // public API.
final boolean useDefaultTitle =
bundle.getBoolean(BiometricPrompt.KEY_USE_DEFAULT_TITLE, false);
if (useDefaultTitle) {
@@ -651,9 +689,11 @@ public class BiometricService extends SystemService {
}
@Override // Binder call
- public int canAuthenticate(String opPackageName, int userId) {
+ public int canAuthenticate(String opPackageName, int userId,
+ @Authenticators.Types int authenticators) {
Slog.d(TAG, "canAuthenticate: User=" + userId
- + ", Caller=" + UserHandle.getCallingUserId());
+ + ", Caller=" + UserHandle.getCallingUserId()
+ + ", Authenticators=" + authenticators);
if (userId != UserHandle.getCallingUserId()) {
checkInternalPermission();
@@ -661,16 +701,39 @@ public class BiometricService extends SystemService {
checkPermission();
}
+
+ if (!Utils.isValidAuthenticatorConfig(authenticators)) {
+ throw new SecurityException("Invalid authenticator configuration");
+ }
+
+ final Bundle bundle = new Bundle();
+ bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
+
+ int biometricConstantsResult = BiometricConstants.BIOMETRIC_ERROR_HW_UNAVAILABLE;
final long ident = Binder.clearCallingIdentity();
- int error;
try {
- final Pair<Integer, Integer> result = checkAndGetBiometricModality(userId,
- opPackageName);
- error = result.second;
+ biometricConstantsResult =
+ checkAndGetAuthenticators(userId, bundle, opPackageName).second;
+ if (biometricConstantsResult != BiometricConstants.BIOMETRIC_SUCCESS
+ && Utils.isDeviceCredentialAllowed(bundle)) {
+ // If there's an issue with biometrics, but device credential is allowed and
+ // set up, return SUCCESS. If device credential isn't set up either, return
+ // ERROR_NO_DEVICE_CREDENTIAL.
+ if (mTrustManager.isDeviceSecure(userId)) {
+ biometricConstantsResult = BiometricConstants.BIOMETRIC_SUCCESS;
+ } else {
+ biometricConstantsResult =
+ BiometricConstants.BIOMETRIC_ERROR_NO_DEVICE_CREDENTIAL;
+ }
+ }
+
+ } catch (RemoteException e) {
+ Slog.e(TAG, "Remote exception", e);
} finally {
Binder.restoreCallingIdentity(ident);
}
- return error;
+
+ return Utils.biometricConstantsToBiometricManager(biometricConstantsResult);
}
@Override
@@ -693,11 +756,46 @@ public class BiometricService extends SystemService {
}
@Override
- public void registerAuthenticator(int id, int strength, int modality,
+ public void registerAuthenticator(int id, int modality, int strength,
IBiometricAuthenticator authenticator) {
checkInternalPermission();
- mAuthenticators.add(new AuthenticatorWrapper(id, strength, modality, authenticator));
+ Slog.d(TAG, "Registering ID: " + id
+ + " Modality: " + modality
+ + " Strength: " + strength);
+
+ if (authenticator == null) {
+ throw new IllegalArgumentException("Authenticator must not be null."
+ + " Did you forget to modify the core/res/res/values/xml overlay for"
+ + " config_biometric_sensors?");
+ }
+
+ if (strength != Authenticators.BIOMETRIC_STRONG
+ && strength != Authenticators.BIOMETRIC_WEAK) {
+ throw new IllegalStateException("Unsupported strength");
+ }
+
+ for (AuthenticatorWrapper wrapper : mAuthenticators) {
+ if (wrapper.id == id) {
+ throw new IllegalStateException("Cannot register duplicate authenticator");
+ }
+ }
+
+ // This happens infrequently enough, not worth caching.
+ final String[] configs = mInjector.getConfiguration(getContext());
+ boolean idFound = false;
+ for (int i = 0; i < configs.length; i++) {
+ SensorConfig config = new SensorConfig(configs[i]);
+ if (config.mId == id) {
+ idFound = true;
+ break;
+ }
+ }
+ if (!idFound) {
+ throw new IllegalStateException("Cannot register unknown id");
+ }
+
+ mAuthenticators.add(new AuthenticatorWrapper(id, modality, strength, authenticator));
}
@Override // Binder call
@@ -771,6 +869,11 @@ public class BiometricService extends SystemService {
}
@VisibleForTesting
+ public ITrustManager getTrustManager() {
+ return ITrustManager.Stub.asInterface(ServiceManager.getService(Context.TRUST_SERVICE));
+ }
+
+ @VisibleForTesting
public IStatusBarService getStatusBarService() {
return IStatusBarService.Stub.asInterface(
ServiceManager.getService(Context.STATUS_BAR_SERVICE));
@@ -805,6 +908,25 @@ public class BiometricService extends SystemService {
public void publishBinderService(BiometricService service, IBiometricService.Stub impl) {
service.publishBinderService(Context.BIOMETRIC_SERVICE, impl);
}
+
+ /**
+ * Allows to mock BiometricStrengthController for testing.
+ */
+ @VisibleForTesting
+ public BiometricStrengthController getBiometricStrengthController(
+ BiometricService service) {
+ return new BiometricStrengthController(service);
+ }
+
+ /**
+ * Allows to test with various device sensor configurations.
+ * @param context System Server context
+ * @return the sensor configuration from core/res/res/values/config.xml
+ */
+ @VisibleForTesting
+ public String[] getConfiguration(Context context) {
+ return context.getResources().getStringArray(R.array.config_biometric_sensors);
+ }
}
/**
@@ -849,7 +971,10 @@ public class BiometricService extends SystemService {
public void onStart() {
mKeyStore = mInjector.getKeyStore();
mStatusBarService = mInjector.getStatusBarService();
+ mTrustManager = mInjector.getTrustManager();
mInjector.publishBinderService(this, mImpl);
+ mBiometricStrengthController = mInjector.getBiometricStrengthController(this);
+ mBiometricStrengthController.startListening();
}
/**
@@ -857,25 +982,36 @@ public class BiometricService extends SystemService {
* returns errors through the callback (no biometric feature, hardware not detected, no
* templates enrolled, etc). This service must not start authentication if errors are sent.
*
- * @Returns A pair [Modality, Error] with Modality being one of
+ * @param userId the user to check for
+ * @param bundle passed from {@link BiometricPrompt}
+ * @param opPackageName see {@link android.app.AppOpsManager}
+ *
+ * @return A pair [Modality, Error] with Modality being one of
* {@link BiometricAuthenticator#TYPE_NONE},
* {@link BiometricAuthenticator#TYPE_FINGERPRINT},
* {@link BiometricAuthenticator#TYPE_IRIS},
* {@link BiometricAuthenticator#TYPE_FACE}
* and the error containing one of the {@link BiometricConstants} errors.
+ *
+ * TODO(kchyn): Update this to handle DEVICE_CREDENTIAL better, reduce duplicate code in callers
*/
- private Pair<Integer, Integer> checkAndGetBiometricModality(int userId, String opPackageName) {
- // No biometric features, send error
- if (mAuthenticators.isEmpty()) {
- return new Pair<>(TYPE_NONE, BiometricConstants.BIOMETRIC_ERROR_HW_NOT_PRESENT);
+ private Pair<Integer, Integer> checkAndGetAuthenticators(int userId, Bundle bundle,
+ String opPackageName) throws RemoteException {
+ if (!Utils.isBiometricAllowed(bundle)
+ && Utils.isDeviceCredentialAllowed(bundle)
+ && !mTrustManager.isDeviceSecure(userId)) {
+ // If only device credential is being checked, and the user doesn't have one set up
+ return new Pair<>(TYPE_NONE, BiometricConstants.BIOMETRIC_ERROR_NO_DEVICE_CREDENTIAL);
}
// Assuming that authenticators are listed in priority-order, the rest of this function
- // will go through and find the first authenticator that's available, enrolled, and enabled.
- // The tricky part is returning the correct error. Error strings that are modality-specific
- // should also respect the priority-order.
+ // will attempt to find the first authenticator that's as strong or stronger than the
+ // requested strength, available, enrolled, and enabled. The tricky part is returning the
+ // correct error. Error strings that are modality-specific should also respect the
+ // priority-order.
- // Find first authenticator that's detected, enrolled, and enabled.
+ // Find first authenticator that's strong enough, detected, enrolled, and enabled.
+ boolean hasSufficientStrength = false;
boolean isHardwareDetected = false;
boolean hasTemplatesEnrolled = false;
boolean enabledForApps = false;
@@ -883,13 +1019,16 @@ public class BiometricService extends SystemService {
int modality = TYPE_NONE;
int firstHwAvailable = TYPE_NONE;
for (AuthenticatorWrapper authenticator : mAuthenticators) {
- modality = authenticator.modality;
- try {
+ final int actualStrength = authenticator.getActualStrength();
+ final int requestedStrength = Utils.getPublicBiometricStrength(bundle);
+ if (Utils.isAtLeastStrength(actualStrength, requestedStrength)) {
+ hasSufficientStrength = true;
+ modality = authenticator.modality;
if (authenticator.impl.isHardwareDetected(opPackageName)) {
isHardwareDetected = true;
if (firstHwAvailable == TYPE_NONE) {
- // Store the first one since we want to return the error in correct priority
- // order.
+ // Store the first one since we want to return the error in correct
+ // priority order.
firstHwAvailable = modality;
}
if (authenticator.impl.hasEnrolledTemplates(userId, opPackageName)) {
@@ -900,18 +1039,18 @@ public class BiometricService extends SystemService {
}
}
}
- } catch (RemoteException e) {
- Slog.e(TAG, "Remote exception", e);
}
}
- Slog.d(TAG, "checkAndGetBiometricModality: user=" + userId
+ Slog.d(TAG, "checkAndGetAuthenticators: user=" + userId
+ " isHardwareDetected=" + isHardwareDetected
+ " hasTemplatesEnrolled=" + hasTemplatesEnrolled
+ " enabledForApps=" + enabledForApps);
// Check error conditions
- if (!isHardwareDetected) {
+ if (!hasSufficientStrength) {
+ return new Pair<>(TYPE_NONE, BiometricConstants.BIOMETRIC_ERROR_HW_NOT_PRESENT);
+ } else if (!isHardwareDetected) {
return new Pair<>(TYPE_NONE, BiometricConstants.BIOMETRIC_ERROR_HW_UNAVAILABLE);
} else if (!hasTemplatesEnrolled) {
// Return the modality here so the correct error string can be sent. This error is
@@ -1107,13 +1246,16 @@ public class BiometricService extends SystemService {
// SystemUI handles transition from biometric to device credential.
mCurrentAuthSession.mState = STATE_SHOWING_DEVICE_CREDENTIAL;
mStatusBarService.onBiometricError(modality, error, vendorCode);
+ } else if (error == BiometricConstants.BIOMETRIC_ERROR_CANCELED) {
+ mStatusBarService.hideAuthenticationDialog();
+ // TODO: If multiple authenticators are simultaneously running, this will
+ // need to be modified. Send the error to the client here, instead of doing
+ // a round trip to SystemUI.
+ mCurrentAuthSession.mClientReceiver.onError(modality, error, vendorCode);
+ mCurrentAuthSession = null;
} else {
mCurrentAuthSession.mState = STATE_ERROR_PENDING_SYSUI;
- if (error == BiometricConstants.BIOMETRIC_ERROR_CANCELED) {
- mStatusBarService.hideAuthenticationDialog();
- } else {
- mStatusBarService.onBiometricError(modality, error, vendorCode);
- }
+ mStatusBarService.onBiometricError(modality, error, vendorCode);
}
} else if (mCurrentAuthSession.mState == STATE_AUTH_PAUSED) {
// In the "try again" state, we should forward canceled errors to
@@ -1135,10 +1277,11 @@ public class BiometricService extends SystemService {
// If any error is received while preparing the auth session (lockout, etc),
// and if device credential is allowed, just show the credential UI.
if (mPendingAuthSession.isAllowDeviceCredential()) {
- int authenticators = mPendingAuthSession.mBundle
- .getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, 0);
+ @Authenticators.Types int authenticators =
+ mPendingAuthSession.mBundle.getInt(
+ BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, 0);
// Disallow biometric and notify SystemUI to show the authentication prompt.
- authenticators &= ~Authenticator.TYPE_BIOMETRIC;
+ authenticators &= ~Authenticators.BIOMETRIC_WEAK;
mPendingAuthSession.mBundle.putInt(
BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED,
authenticators);
@@ -1355,31 +1498,43 @@ public class BiometricService extends SystemService {
int callingUid, int callingPid, int callingUserId) {
mHandler.post(() -> {
- final Pair<Integer, Integer> result = checkAndGetBiometricModality(userId,
- opPackageName);
- final int modality = result.first;
- final int error = result.second;
-
- final boolean credentialAllowed = Utils.isDeviceCredentialAllowed(bundle);
-
- if (error != BiometricConstants.BIOMETRIC_SUCCESS && credentialAllowed) {
- // If there's a problem but device credential is allowed, only show credential UI.
- bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED,
- Authenticator.TYPE_CREDENTIAL);
- } else if (error != BiometricConstants.BIOMETRIC_SUCCESS) {
- // Check for errors, notify callback, and return
- try {
- receiver.onError(modality, error, 0 /* vendorCode */);
- } catch (RemoteException e) {
- Slog.e(TAG, "Unable to send error", e);
- }
- return;
+ int modality = TYPE_NONE;
+ int result;
+
+ try {
+ final Pair<Integer, Integer> pair = checkAndGetAuthenticators(userId, bundle,
+ opPackageName);
+ modality = pair.first;
+ result = pair.second;
+ } catch (RemoteException e) {
+ Slog.e(TAG, "Remote exception", e);
+ result = BiometricConstants.BIOMETRIC_ERROR_HW_UNAVAILABLE;
}
- // Start preparing for authentication. Authentication starts when
- // all modalities requested have invoked onReadyForAuthentication.
- authenticateInternal(token, sessionId, userId, receiver, opPackageName, bundle,
- callingUid, callingPid, callingUserId, modality);
+ try {
+ if (result == BiometricConstants.BIOMETRIC_ERROR_NO_DEVICE_CREDENTIAL) {
+ // If the app allowed device credential but the user hasn't set it up yet,
+ // return this error.
+ receiver.onError(modality, result, 0 /* vendorCode */);
+ } else if (result != BiometricConstants.BIOMETRIC_SUCCESS) {
+ if (Utils.isDeviceCredentialAllowed(bundle)) {
+ // If there's a problem with biometrics but device credential is allowed,
+ // only show credential UI.
+ bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED,
+ Authenticators.DEVICE_CREDENTIAL);
+ authenticateInternal(token, sessionId, userId, receiver, opPackageName,
+ bundle, callingUid, callingPid, callingUserId, modality);
+ } else {
+ receiver.onError(modality, result, 0 /* vendorCode */);
+ }
+ } else {
+ // BIOMETRIC_SUCCESS, proceed to authentication
+ authenticateInternal(token, sessionId, userId, receiver, opPackageName, bundle,
+ callingUid, callingPid, callingUserId, modality);
+ }
+ } catch (RemoteException e) {
+ Slog.e(TAG, "Remote exception", e);
+ }
});
}
@@ -1407,7 +1562,8 @@ public class BiometricService extends SystemService {
// with the cookie. Once all cookies are received, we can show the prompt
// and let the services start authenticating. The cookie should be non-zero.
final int cookie = mRandom.nextInt(Integer.MAX_VALUE - 1) + 1;
- final int authenticators = bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED);
+ final @Authenticators.Types int authenticators = bundle.getInt(
+ BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, 0);
Slog.d(TAG, "Creating auth session. Modality: " + modality
+ ", cookie: " + cookie
+ ", authenticators: " + authenticators);
@@ -1415,7 +1571,7 @@ public class BiometricService extends SystemService {
// If it's only device credential, we don't need to wait - LockSettingsService is
// always ready to check credential (SystemUI invokes that path).
- if ((authenticators & ~Authenticator.TYPE_CREDENTIAL) != 0) {
+ if ((authenticators & ~Authenticators.DEVICE_CREDENTIAL) != 0) {
modalities.put(modality, cookie);
}
mPendingAuthSession = new AuthSession(modalities, token, sessionId, userId,
@@ -1423,7 +1579,7 @@ public class BiometricService extends SystemService {
modality, requireConfirmation);
try {
- if (authenticators == Authenticator.TYPE_CREDENTIAL) {
+ if (authenticators == Authenticators.DEVICE_CREDENTIAL) {
mPendingAuthSession.mState = STATE_SHOWING_DEVICE_CREDENTIAL;
mCurrentAuthSession = mPendingAuthSession;
mPendingAuthSession = null;
@@ -1438,9 +1594,13 @@ public class BiometricService extends SystemService {
} else {
mPendingAuthSession.mState = STATE_AUTH_CALLED;
for (AuthenticatorWrapper authenticator : mAuthenticators) {
- authenticator.impl.prepareForAuthentication(requireConfirmation, token,
- sessionId, userId, mInternalReceiver, opPackageName, cookie, callingUid,
- callingPid, callingUserId);
+ // TODO(b/141025588): use ids instead of modalities to avoid ambiguity.
+ if (authenticator.modality == modality) {
+ authenticator.impl.prepareForAuthentication(requireConfirmation, token,
+ sessionId, userId, mInternalReceiver, opPackageName, cookie,
+ callingUid, callingPid, callingUserId);
+ break;
+ }
}
}
} catch (RemoteException e) {
diff --git a/services/core/java/com/android/server/biometrics/BiometricServiceBase.java b/services/core/java/com/android/server/biometrics/BiometricServiceBase.java
index 2de18c391d4a..60f0e8e6c63d 100644
--- a/services/core/java/com/android/server/biometrics/BiometricServiceBase.java
+++ b/services/core/java/com/android/server/biometrics/BiometricServiceBase.java
@@ -16,6 +16,7 @@
package com.android.server.biometrics;
+import static android.Manifest.permission.USE_BIOMETRIC_INTERNAL;
import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE;
import android.app.ActivityManager;
@@ -1013,8 +1014,13 @@ public abstract class BiometricServiceBase extends SystemService
private boolean isForegroundActivity(int uid, int pid) {
try {
- List<ActivityManager.RunningAppProcessInfo> procs =
+ final List<ActivityManager.RunningAppProcessInfo> procs =
ActivityManager.getService().getRunningAppProcesses();
+ if (procs == null) {
+ Slog.e(getTag(), "Processes null, defaulting to true");
+ return true;
+ }
+
int N = procs.size();
for (int i = 0; i < N; i++) {
ActivityManager.RunningAppProcessInfo proc = procs.get(i);
@@ -1206,6 +1212,11 @@ public abstract class BiometricServiceBase extends SystemService
* @return authenticator id for the calling user
*/
protected long getAuthenticatorId(String opPackageName) {
+ if (isKeyguard(opPackageName)) {
+ // If an app tells us it's keyguard, check that it actually is.
+ checkPermission(USE_BIOMETRIC_INTERNAL);
+ }
+
final int userId = getUserOrWorkProfileId(opPackageName, UserHandle.getCallingUserId());
return mAuthenticatorIds.getOrDefault(userId, 0L);
}
diff --git a/services/core/java/com/android/server/biometrics/BiometricStrengthController.java b/services/core/java/com/android/server/biometrics/BiometricStrengthController.java
new file mode 100644
index 000000000000..4e16189e3ad1
--- /dev/null
+++ b/services/core/java/com/android/server/biometrics/BiometricStrengthController.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.biometrics;
+
+import android.annotation.NonNull;
+import android.provider.DeviceConfig;
+import android.util.Slog;
+
+import com.android.internal.os.BackgroundThread;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Class for maintaining and updating the strengths for biometric sensors. Strengths can only
+ * be downgraded from the device's default, and never upgraded.
+ */
+public class BiometricStrengthController implements DeviceConfig.OnPropertiesChangedListener {
+ private static final String TAG = "BiometricStrengthController";
+
+ private final BiometricService mService;
+
+ /**
+ * Flag stored in the DeviceConfig API: biometric modality strengths to downgrade.
+ * This is encoded as a key:value list, separated by comma, e.g.
+ *
+ * "id1:strength1,id2:strength2,id3:strength3"
+ *
+ * where strength is one of the values defined in
+ * {@link android.hardware.biometrics.Authenticators}
+ *
+ * Both id and strength should be int, otherwise Exception will be thrown when parsing and the
+ * downgrade will fail.
+ */
+ private static final String KEY_BIOMETRIC_STRENGTHS = "biometric_strengths";
+
+ /**
+ * Default (no-op) value of the flag KEY_BIOMETRIC_STRENGTHS
+ */
+ public static final String DEFAULT_BIOMETRIC_STRENGTHS = null;
+
+ BiometricStrengthController(@NonNull BiometricService service) {
+ mService = service;
+ }
+
+ void startListening() {
+ DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_BIOMETRICS,
+ BackgroundThread.getExecutor(), this);
+ updateStrengths();
+ }
+
+ @Override
+ public void onPropertiesChanged(@NonNull DeviceConfig.Properties properties) {
+ for (String name : properties.getKeyset()) {
+ if (KEY_BIOMETRIC_STRENGTHS.equals(name)) {
+ updateStrengths();
+ }
+ }
+ }
+
+ /**
+ * Updates the strengths of authenticators in BiometricService if a matching ID's configuration
+ * has been changed.
+ */
+ private void updateStrengths() {
+ final Map<Integer, Integer> idToStrength = getIdToStrengthMap();
+ if (idToStrength == null) {
+ return;
+ }
+
+ for (BiometricService.AuthenticatorWrapper authenticator : mService.mAuthenticators) {
+ final int id = authenticator.id;
+ if (idToStrength.containsKey(id)) {
+ final int newStrength = idToStrength.get(id);
+ authenticator.updateStrength(newStrength);
+ }
+ }
+ }
+
+ /**
+ * @return a map of <ID, Strength>
+ */
+ private Map<Integer, Integer> getIdToStrengthMap() {
+ final String flags = DeviceConfig.getString(DeviceConfig.NAMESPACE_BIOMETRICS,
+ KEY_BIOMETRIC_STRENGTHS, DEFAULT_BIOMETRIC_STRENGTHS);
+ if (flags == null || flags.isEmpty()) {
+ Slog.d(TAG, "Flags are null or empty");
+ return null;
+ }
+
+ Map<Integer, Integer> map = new HashMap<>();
+ try {
+ for (String item : flags.split(",")) {
+ String[] elems = item.split(":");
+ final int id = Integer.parseInt(elems[0]);
+ final int strength = Integer.parseInt(elems[1]);
+ map.put(id, strength);
+ }
+ } catch (Exception e) {
+ Slog.e(TAG, "Can't parse flag: " + flags);
+ map = null;
+ }
+ return map;
+ }
+}
diff --git a/services/core/java/com/android/server/biometrics/OWNERS b/services/core/java/com/android/server/biometrics/OWNERS
new file mode 100644
index 000000000000..8765c9a64b77
--- /dev/null
+++ b/services/core/java/com/android/server/biometrics/OWNERS
@@ -0,0 +1,7 @@
+set noparent
+
+kchyn@google.com
+jaggies@google.com
+curtislb@google.com
+ilyamaty@google.com
+joshmccloskey@google.com
diff --git a/services/core/java/com/android/server/biometrics/SensorConfig.java b/services/core/java/com/android/server/biometrics/SensorConfig.java
new file mode 100644
index 000000000000..9eda6da26967
--- /dev/null
+++ b/services/core/java/com/android/server/biometrics/SensorConfig.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.biometrics;
+
+/**
+ * Parsed sensor config. See core/res/res/values/config.xml config_biometric_sensors
+ */
+class SensorConfig {
+ final int mId;
+ final int mModality;
+ final int mStrength;
+
+ public SensorConfig(String config) {
+ String[] elems = config.split(":");
+ mId = Integer.parseInt(elems[0]);
+ mModality = Integer.parseInt(elems[1]);
+ mStrength = Integer.parseInt(elems[2]);
+ }
+}
diff --git a/services/core/java/com/android/server/biometrics/Utils.java b/services/core/java/com/android/server/biometrics/Utils.java
index ed5f9de01bcf..19f535876274 100644
--- a/services/core/java/com/android/server/biometrics/Utils.java
+++ b/services/core/java/com/android/server/biometrics/Utils.java
@@ -16,15 +16,17 @@
package com.android.server.biometrics;
+import static android.hardware.biometrics.BiometricManager.Authenticators;
+
import android.content.Context;
-import android.hardware.biometrics.Authenticator;
+import android.hardware.biometrics.BiometricConstants;
+import android.hardware.biometrics.BiometricManager;
import android.hardware.biometrics.BiometricPrompt;
import android.os.Build;
import android.os.Bundle;
import android.os.UserHandle;
import android.provider.Settings;
-
-import com.android.internal.annotations.VisibleForTesting;
+import android.util.Slog;
public class Utils {
public static boolean isDebugEnabled(Context context, int targetUserId) {
@@ -45,41 +47,167 @@ public class Utils {
}
/**
- * Combine {@link BiometricPrompt#KEY_ALLOW_DEVICE_CREDENTIAL} with
- * {@link BiometricPrompt#KEY_AUTHENTICATORS_ALLOWED}, as the former is not flexible
- * enough.
+ * Combines {@link BiometricPrompt#KEY_ALLOW_DEVICE_CREDENTIAL} with
+ * {@link BiometricPrompt#KEY_AUTHENTICATORS_ALLOWED}, as the former is not flexible enough.
*/
public static void combineAuthenticatorBundles(Bundle bundle) {
- boolean biometricEnabled = true; // enabled by default
- boolean credentialEnabled = bundle.getBoolean(
- BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL, false);
- if (bundle.get(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED) != null) {
- final int authenticatorFlags =
- bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED);
- biometricEnabled = (authenticatorFlags & Authenticator.TYPE_BIOMETRIC) != 0;
- // Using both KEY_ALLOW_DEVICE_CREDENTIAL and KEY_AUTHENTICATORS_ALLOWED together
- // is not supported. Default to overwriting.
- credentialEnabled = (authenticatorFlags & Authenticator.TYPE_CREDENTIAL) != 0;
- }
-
+ // Cache and remove explicit ALLOW_DEVICE_CREDENTIAL boolean flag from the bundle.
+ final boolean deviceCredentialAllowed =
+ bundle.getBoolean(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL, false);
bundle.remove(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL);
- int authenticators = 0;
- if (biometricEnabled) {
- authenticators |= Authenticator.TYPE_BIOMETRIC;
- }
- if (credentialEnabled) {
- authenticators |= Authenticator.TYPE_CREDENTIAL;
+ final @Authenticators.Types int authenticators;
+ if (bundle.containsKey(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED)) {
+ // Ignore ALLOW_DEVICE_CREDENTIAL flag if AUTH_TYPES_ALLOWED is defined.
+ authenticators = bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, 0);
+ } else {
+ // Otherwise, use ALLOW_DEVICE_CREDENTIAL flag along with Weak+ biometrics by default.
+ authenticators = deviceCredentialAllowed
+ ? Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_WEAK
+ : Authenticators.BIOMETRIC_WEAK;
}
+
bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
}
/**
+ * @param authenticators composed of one or more values from {@link Authenticators}
+ * @return true if device credential is allowed.
+ */
+ public static boolean isDeviceCredentialAllowed(@Authenticators.Types int authenticators) {
+ return (authenticators & Authenticators.DEVICE_CREDENTIAL) != 0;
+ }
+
+ /**
* @param bundle should be first processed by {@link #combineAuthenticatorBundles(Bundle)}
- * @return true if device credential allowed.
+ * @return true if device credential is allowed.
*/
public static boolean isDeviceCredentialAllowed(Bundle bundle) {
+ return isDeviceCredentialAllowed(bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED));
+ }
+
+ /**
+ * Checks if any of the publicly defined strengths are set.
+ *
+ * @param authenticators composed of one or more values from {@link Authenticators}
+ * @return minimal allowed biometric strength or 0 if biometric authentication is not allowed.
+ */
+ public static int getPublicBiometricStrength(@Authenticators.Types int authenticators) {
+ // Only biometrics WEAK and above are allowed to integrate with the public APIs.
+ return authenticators & Authenticators.BIOMETRIC_WEAK;
+ }
+
+ /**
+ * Checks if any of the publicly defined strengths are set.
+ *
+ * @param bundle should be first processed by {@link #combineAuthenticatorBundles(Bundle)}
+ * @return minimal allowed biometric strength or 0 if biometric authentication is not allowed.
+ */
+ public static int getPublicBiometricStrength(Bundle bundle) {
+ return getPublicBiometricStrength(
+ bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED));
+ }
+
+ /**
+ * Checks if any of the publicly defined strengths are set.
+ *
+ * @param bundle should be first processed by {@link #combineAuthenticatorBundles(Bundle)}
+ * @return true if biometric authentication is allowed.
+ */
+ public static boolean isBiometricAllowed(Bundle bundle) {
+ return getPublicBiometricStrength(bundle) != 0;
+ }
+
+ /**
+ * @param sensorStrength the strength of the sensor
+ * @param requestedStrength the strength that it must meet
+ * @return true only if the sensor is at least as strong as the requested strength
+ */
+ public static boolean isAtLeastStrength(int sensorStrength, int requestedStrength) {
+ // If the authenticator contains bits outside of the requested strength, it is too weak.
+ return (~requestedStrength & sensorStrength) == 0;
+ }
+
+ /**
+ * Checks if the authenticator configuration is a valid combination of the public APIs
+ * @param bundle
+ * @return
+ */
+ public static boolean isValidAuthenticatorConfig(Bundle bundle) {
final int authenticators = bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED);
- return (authenticators & Authenticator.TYPE_CREDENTIAL) != 0;
+ return isValidAuthenticatorConfig(authenticators);
+ }
+
+ /**
+ * Checks if the authenticator configuration is a valid combination of the public APIs
+ * @param authenticators
+ * @return
+ */
+ public static boolean isValidAuthenticatorConfig(int authenticators) {
+ // The caller is not required to set the authenticators. But if they do, check the below.
+ if (authenticators == 0) {
+ return true;
+ }
+
+ // Check if any of the non-biometric and non-credential bits are set. If so, this is
+ // invalid.
+ final int testBits = ~(Authenticators.DEVICE_CREDENTIAL
+ | Authenticators.BIOMETRIC_MIN_STRENGTH);
+ if ((authenticators & testBits) != 0) {
+ Slog.e(BiometricService.TAG, "Non-biometric, non-credential bits found."
+ + " Authenticators: " + authenticators);
+ return false;
+ }
+
+ // Check that biometrics bits are either NONE, WEAK, or STRONG. If NONE, DEVICE_CREDENTIAL
+ // should be set.
+ final int biometricBits = authenticators & Authenticators.BIOMETRIC_MIN_STRENGTH;
+ if (biometricBits == Authenticators.EMPTY_SET
+ && isDeviceCredentialAllowed(authenticators)) {
+ return true;
+ } else if (biometricBits == Authenticators.BIOMETRIC_STRONG) {
+ return true;
+ } else if (biometricBits == Authenticators.BIOMETRIC_WEAK) {
+ return true;
+ }
+
+ Slog.e(BiometricService.TAG, "Unsupported biometric flags. Authenticators: "
+ + authenticators);
+ // Non-supported biometric flags are being used
+ return false;
+ }
+
+ /**
+ * Converts error codes from BiometricConstants, which are used in most of the internal plumbing
+ * and eventually returned to {@link BiometricPrompt.AuthenticationCallback} to public
+ * {@link BiometricManager} constants, which are used by APIs such as
+ * {@link BiometricManager#canAuthenticate(int)}
+ *
+ * @param biometricConstantsCode see {@link BiometricConstants}
+ * @return see {@link BiometricManager}
+ */
+ public static int biometricConstantsToBiometricManager(int biometricConstantsCode) {
+ final int biometricManagerCode;
+
+ switch (biometricConstantsCode) {
+ case BiometricConstants.BIOMETRIC_SUCCESS:
+ biometricManagerCode = BiometricManager.BIOMETRIC_SUCCESS;
+ break;
+ case BiometricConstants.BIOMETRIC_ERROR_NO_BIOMETRICS:
+ case BiometricConstants.BIOMETRIC_ERROR_NO_DEVICE_CREDENTIAL:
+ biometricManagerCode = BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED;
+ break;
+ case BiometricConstants.BIOMETRIC_ERROR_HW_UNAVAILABLE:
+ biometricManagerCode = BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE;
+ break;
+ case BiometricConstants.BIOMETRIC_ERROR_HW_NOT_PRESENT:
+ biometricManagerCode = BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE;
+ break;
+ default:
+ Slog.e(BiometricService.TAG, "Unhandled result code: " + biometricConstantsCode);
+ biometricManagerCode = BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE;
+ break;
+ }
+ return biometricManagerCode;
}
}
diff --git a/services/core/java/com/android/server/connectivity/DataConnectionStats.java b/services/core/java/com/android/server/connectivity/DataConnectionStats.java
index 27f11ffa60ce..1b1c54682255 100644
--- a/services/core/java/com/android/server/connectivity/DataConnectionStats.java
+++ b/services/core/java/com/android/server/connectivity/DataConnectionStats.java
@@ -31,8 +31,6 @@ import android.telephony.TelephonyManager;
import android.util.Log;
import com.android.internal.app.IBatteryStats;
-import com.android.internal.telephony.IccCardConstants;
-import com.android.internal.telephony.TelephonyIntents;
import com.android.server.am.BatteryStatsService;
public class DataConnectionStats extends BroadcastReceiver {
@@ -44,7 +42,7 @@ public class DataConnectionStats extends BroadcastReceiver {
private final Handler mListenerHandler;
private final PhoneStateListener mPhoneStateListener;
- private IccCardConstants.State mSimState = IccCardConstants.State.READY;
+ private int mSimState = TelephonyManager.SIM_STATE_READY;
private SignalStrength mSignalStrength;
private ServiceState mServiceState;
private int mDataState = TelephonyManager.DATA_DISCONNECTED;
@@ -66,7 +64,7 @@ public class DataConnectionStats extends BroadcastReceiver {
| PhoneStateListener.LISTEN_DATA_ACTIVITY);
IntentFilter filter = new IntentFilter();
- filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
+ filter.addAction(Intent.ACTION_SIM_STATE_CHANGED);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(ConnectivityManager.INET_CONDITION_ACTION);
mContext.registerReceiver(this, filter, null /* broadcastPermission */, mListenerHandler);
@@ -75,7 +73,7 @@ public class DataConnectionStats extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
- if (action.equals(TelephonyIntents.ACTION_SIM_STATE_CHANGED)) {
+ if (action.equals(Intent.ACTION_SIM_STATE_CHANGED)) {
updateSimState(intent);
notePhoneDataConnectionState();
} else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION) ||
@@ -88,8 +86,8 @@ public class DataConnectionStats extends BroadcastReceiver {
if (mServiceState == null) {
return;
}
- boolean simReadyOrUnknown = mSimState == IccCardConstants.State.READY
- || mSimState == IccCardConstants.State.UNKNOWN;
+ boolean simReadyOrUnknown = mSimState == TelephonyManager.SIM_STATE_READY
+ || mSimState == TelephonyManager.SIM_STATE_UNKNOWN;
boolean visible = (simReadyOrUnknown || isCdma()) // we only check the sim state for GSM
&& hasService()
&& mDataState == TelephonyManager.DATA_CONNECTED;
@@ -105,23 +103,23 @@ public class DataConnectionStats extends BroadcastReceiver {
}
private final void updateSimState(Intent intent) {
- String stateExtra = intent.getStringExtra(IccCardConstants.INTENT_KEY_ICC_STATE);
- if (IccCardConstants.INTENT_VALUE_ICC_ABSENT.equals(stateExtra)) {
- mSimState = IccCardConstants.State.ABSENT;
- } else if (IccCardConstants.INTENT_VALUE_ICC_READY.equals(stateExtra)) {
- mSimState = IccCardConstants.State.READY;
- } else if (IccCardConstants.INTENT_VALUE_ICC_LOCKED.equals(stateExtra)) {
+ String stateExtra = intent.getStringExtra(Intent.EXTRA_SIM_STATE);
+ if (Intent.SIM_STATE_ABSENT.equals(stateExtra)) {
+ mSimState = TelephonyManager.SIM_STATE_ABSENT;
+ } else if (Intent.SIM_STATE_READY.equals(stateExtra)) {
+ mSimState = TelephonyManager.SIM_STATE_READY;
+ } else if (Intent.SIM_STATE_LOCKED.equals(stateExtra)) {
final String lockedReason =
- intent.getStringExtra(IccCardConstants.INTENT_KEY_LOCKED_REASON);
- if (IccCardConstants.INTENT_VALUE_LOCKED_ON_PIN.equals(lockedReason)) {
- mSimState = IccCardConstants.State.PIN_REQUIRED;
- } else if (IccCardConstants.INTENT_VALUE_LOCKED_ON_PUK.equals(lockedReason)) {
- mSimState = IccCardConstants.State.PUK_REQUIRED;
+ intent.getStringExtra(Intent.EXTRA_SIM_LOCKED_REASON);
+ if (Intent.SIM_LOCKED_ON_PIN.equals(lockedReason)) {
+ mSimState = TelephonyManager.SIM_STATE_PIN_REQUIRED;
+ } else if (Intent.SIM_LOCKED_ON_PUK.equals(lockedReason)) {
+ mSimState = TelephonyManager.SIM_STATE_PUK_REQUIRED;
} else {
- mSimState = IccCardConstants.State.NETWORK_LOCKED;
+ mSimState = TelephonyManager.SIM_STATE_NETWORK_LOCKED;
}
} else {
- mSimState = IccCardConstants.State.UNKNOWN;
+ mSimState = TelephonyManager.SIM_STATE_UNKNOWN;
}
}
diff --git a/services/core/java/com/android/server/connectivity/KeepaliveTracker.java b/services/core/java/com/android/server/connectivity/KeepaliveTracker.java
index 9bae902eb7b1..af8a3666e9b7 100644
--- a/services/core/java/com/android/server/connectivity/KeepaliveTracker.java
+++ b/services/core/java/com/android/server/connectivity/KeepaliveTracker.java
@@ -39,11 +39,11 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.Context;
import android.net.ISocketKeepaliveCallback;
+import android.net.InvalidPacketException;
import android.net.KeepalivePacketData;
import android.net.NattKeepalivePacketData;
import android.net.NetworkAgent;
import android.net.NetworkUtils;
-import android.net.SocketKeepalive.InvalidPacketException;
import android.net.SocketKeepalive.InvalidSocketException;
import android.net.TcpKeepalivePacketData;
import android.net.util.IpUtils;
@@ -657,7 +657,10 @@ public class KeepaliveTracker {
final TcpKeepalivePacketData packet;
try {
packet = TcpKeepaliveController.getTcpKeepalivePacket(fd);
- } catch (InvalidPacketException | InvalidSocketException e) {
+ } catch (InvalidSocketException e) {
+ notifyErrorCallback(cb, e.error);
+ return;
+ } catch (InvalidPacketException e) {
notifyErrorCallback(cb, e.error);
return;
}
diff --git a/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java b/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
index bb7f86233a40..5e085ca293a4 100644
--- a/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
+++ b/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
@@ -291,13 +291,18 @@ public class NetworkAgentInfo implements Comparable<NetworkAgentInfo> {
*
* <p>If {@link NetworkMonitor#notifyNetworkCapabilitiesChanged(NetworkCapabilities)} fails,
* the exception is logged but not reported to callers.
+ *
+ * @return the old capabilities of this network.
*/
- public void setNetworkCapabilities(NetworkCapabilities nc) {
+ public synchronized NetworkCapabilities getAndSetNetworkCapabilities(
+ @NonNull final NetworkCapabilities nc) {
+ final NetworkCapabilities oldNc = networkCapabilities;
networkCapabilities = nc;
final NetworkMonitorManager nm = mNetworkMonitor;
if (nm != null) {
nm.notifyNetworkCapabilitiesChanged(nc);
}
+ return oldNc;
}
public ConnectivityService connService() {
diff --git a/services/core/java/com/android/server/connectivity/TcpKeepaliveController.java b/services/core/java/com/android/server/connectivity/TcpKeepaliveController.java
index e570ef1e9bf2..1129899ee3ff 100644
--- a/services/core/java/com/android/server/connectivity/TcpKeepaliveController.java
+++ b/services/core/java/com/android/server/connectivity/TcpKeepaliveController.java
@@ -30,8 +30,8 @@ import static android.system.OsConstants.IP_TTL;
import static android.system.OsConstants.TIOCOUTQ;
import android.annotation.NonNull;
+import android.net.InvalidPacketException;
import android.net.NetworkUtils;
-import android.net.SocketKeepalive.InvalidPacketException;
import android.net.SocketKeepalive.InvalidSocketException;
import android.net.TcpKeepalivePacketData;
import android.net.TcpKeepalivePacketDataParcelable;
diff --git a/services/core/java/com/android/server/display/AutomaticBrightnessController.java b/services/core/java/com/android/server/display/AutomaticBrightnessController.java
index 31632dc007a5..177e2d8b5fa2 100644
--- a/services/core/java/com/android/server/display/AutomaticBrightnessController.java
+++ b/services/core/java/com/android/server/display/AutomaticBrightnessController.java
@@ -41,6 +41,7 @@ import android.util.MathUtils;
import android.util.Slog;
import android.util.TimeUtils;
+import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.os.BackgroundThread;
import com.android.server.EventLogTags;
@@ -215,7 +216,26 @@ class AutomaticBrightnessController {
private IActivityTaskManager mActivityTaskManager;
private PackageManager mPackageManager;
- public AutomaticBrightnessController(Callbacks callbacks, Looper looper,
+ private final Injector mInjector;
+
+ AutomaticBrightnessController(Callbacks callbacks, Looper looper,
+ SensorManager sensorManager, Sensor lightSensor, BrightnessMappingStrategy mapper,
+ int lightSensorWarmUpTime, int brightnessMin, int brightnessMax, float dozeScaleFactor,
+ int lightSensorRate, int initialLightSensorRate, long brighteningLightDebounceConfig,
+ long darkeningLightDebounceConfig, boolean resetAmbientLuxAfterWarmUpConfig,
+ HysteresisLevels ambientBrightnessThresholds,
+ HysteresisLevels screenBrightnessThresholds, long shortTermModelTimeout,
+ PackageManager packageManager) {
+ this(new Injector(), callbacks, looper, sensorManager, lightSensor, mapper,
+ lightSensorWarmUpTime, brightnessMin, brightnessMax, dozeScaleFactor,
+ lightSensorRate, initialLightSensorRate, brighteningLightDebounceConfig,
+ darkeningLightDebounceConfig, resetAmbientLuxAfterWarmUpConfig,
+ ambientBrightnessThresholds, screenBrightnessThresholds, shortTermModelTimeout,
+ packageManager);
+ }
+
+ @VisibleForTesting
+ AutomaticBrightnessController(Injector injector, Callbacks callbacks, Looper looper,
SensorManager sensorManager, Sensor lightSensor, BrightnessMappingStrategy mapper,
int lightSensorWarmUpTime, int brightnessMin, int brightnessMax, float dozeScaleFactor,
int lightSensorRate, int initialLightSensorRate, long brighteningLightDebounceConfig,
@@ -223,6 +243,7 @@ class AutomaticBrightnessController {
HysteresisLevels ambientBrightnessThresholds,
HysteresisLevels screenBrightnessThresholds, long shortTermModelTimeout,
PackageManager packageManager) {
+ mInjector = injector;
mCallbacks = callbacks;
mSensorManager = sensorManager;
mBrightnessMapper = mapper;
@@ -725,8 +746,8 @@ class AutomaticBrightnessController {
float value = mBrightnessMapper.getBrightness(mAmbientLux, mForegroundAppPackageName,
mForegroundAppCategory);
- int newScreenAutoBrightness =
- clampScreenBrightness(Math.round(value * PowerManager.BRIGHTNESS_ON));
+ int newScreenAutoBrightness = Math.round(clampScreenBrightness(
+ value * PowerManager.BRIGHTNESS_ON));
// If screenAutoBrightness is set, we should have screen{Brightening,Darkening}Threshold,
// in which case we ignore the new screen brightness if it doesn't differ enough from the
@@ -750,10 +771,10 @@ class AutomaticBrightnessController {
}
mScreenAutoBrightness = newScreenAutoBrightness;
- mScreenBrighteningThreshold =
- mScreenBrightnessThresholds.getBrighteningThreshold(newScreenAutoBrightness);
- mScreenDarkeningThreshold =
- mScreenBrightnessThresholds.getDarkeningThreshold(newScreenAutoBrightness);
+ mScreenBrighteningThreshold = clampScreenBrightness(
+ mScreenBrightnessThresholds.getBrighteningThreshold(newScreenAutoBrightness));
+ mScreenDarkeningThreshold = clampScreenBrightness(
+ mScreenBrightnessThresholds.getDarkeningThreshold(newScreenAutoBrightness));
if (sendUpdate) {
mCallbacks.updateBrightness();
@@ -761,7 +782,7 @@ class AutomaticBrightnessController {
}
}
- private int clampScreenBrightness(int value) {
+ private float clampScreenBrightness(float value) {
return MathUtils.constrain(value,
mScreenBrightnessRangeMinimum, mScreenBrightnessRangeMaximum);
}
@@ -839,7 +860,7 @@ class AutomaticBrightnessController {
}
// The ActivityTaskManager's lock tends to get contended, so this is done in a background
// thread and applied via this thread's handler synchronously.
- BackgroundThread.getHandler().post(new Runnable() {
+ mInjector.getBackgroundThreadHandler().post(new Runnable() {
public void run() {
try {
// The foreground app is the top activity of the focused tasks stack.
@@ -965,6 +986,9 @@ class AutomaticBrightnessController {
private int mCount;
public AmbientLightRingBuffer(long lightSensorRate, int ambientLightHorizon) {
+ if (lightSensorRate <= 0) {
+ throw new IllegalArgumentException("lightSensorRate must be above 0");
+ }
mCapacity = (int) Math.ceil(ambientLightHorizon * BUFFER_SLACK / lightSensorRate);
mRingLux = new float[mCapacity];
mRingTime = new long[mCapacity];
@@ -1076,4 +1100,10 @@ class AutomaticBrightnessController {
return index;
}
}
+
+ public static class Injector {
+ public Handler getBackgroundThreadHandler() {
+ return BackgroundThread.getHandler();
+ }
+ }
}
diff --git a/services/core/java/com/android/server/display/HysteresisLevels.java b/services/core/java/com/android/server/display/HysteresisLevels.java
index 2db1d03893d2..f0a505d4d818 100644
--- a/services/core/java/com/android/server/display/HysteresisLevels.java
+++ b/services/core/java/com/android/server/display/HysteresisLevels.java
@@ -18,13 +18,16 @@ package com.android.server.display;
import android.util.Slog;
+import com.android.internal.annotations.VisibleForTesting;
+
import java.io.PrintWriter;
import java.util.Arrays;
/**
* A helper class for handling access to illuminance hysteresis level values.
*/
-final class HysteresisLevels {
+@VisibleForTesting
+public class HysteresisLevels {
private static final String TAG = "HysteresisLevels";
// Default hysteresis constraints for brightening or darkening.
@@ -60,7 +63,7 @@ final class HysteresisLevels {
/**
* Return the brightening hysteresis threshold for the given value level.
*/
- float getBrighteningThreshold(float value) {
+ public float getBrighteningThreshold(float value) {
float brightConstant = getReferenceLevel(value, mBrighteningThresholds);
float brightThreshold = value * (1.0f + brightConstant);
if (DEBUG) {
@@ -73,7 +76,7 @@ final class HysteresisLevels {
/**
* Return the darkening hysteresis threshold for the given value level.
*/
- float getDarkeningThreshold(float value) {
+ public float getDarkeningThreshold(float value) {
float darkConstant = getReferenceLevel(value, mDarkeningThresholds);
float darkThreshold = value * (1.0f - darkConstant);
if (DEBUG) {
diff --git a/services/core/java/com/android/server/display/LocalDisplayAdapter.java b/services/core/java/com/android/server/display/LocalDisplayAdapter.java
index 1d7c942e8224..308c755a0868 100644
--- a/services/core/java/com/android/server/display/LocalDisplayAdapter.java
+++ b/services/core/java/com/android/server/display/LocalDisplayAdapter.java
@@ -410,6 +410,9 @@ final class LocalDisplayAdapter extends DisplayAdapter {
final DisplayAddress.Physical physicalAddress =
DisplayAddress.fromPhysicalDisplayId(mPhysicalDisplayId);
mInfo.address = physicalAddress;
+ mInfo.densityDpi = (int) (phys.density * 160 + 0.5f);
+ mInfo.xDpi = phys.xDpi;
+ mInfo.yDpi = phys.yDpi;
// Assume that all built-in displays that have secure output (eg. HDCP) also
// support compositing from gralloc protected buffers.
@@ -436,9 +439,6 @@ final class LocalDisplayAdapter extends DisplayAdapter {
mInfo.displayCutout = DisplayCutout.fromResourcesRectApproximation(res,
mInfo.width, mInfo.height);
mInfo.type = Display.TYPE_BUILT_IN;
- mInfo.densityDpi = (int)(phys.density * 160 + 0.5f);
- mInfo.xDpi = phys.xDpi;
- mInfo.yDpi = phys.yDpi;
mInfo.touch = DisplayDeviceInfo.TOUCH_INTERNAL;
} else {
mInfo.displayCutout = null;
@@ -447,7 +447,6 @@ final class LocalDisplayAdapter extends DisplayAdapter {
mInfo.name = getContext().getResources().getString(
com.android.internal.R.string.display_manager_hdmi_display_name);
mInfo.touch = DisplayDeviceInfo.TOUCH_EXTERNAL;
- mInfo.setAssumedDensityForExternalDisplay(phys.width, phys.height);
// For demonstration purposes, allow rotation of the external display.
// In the future we might allow the user to configure this directly.
diff --git a/services/core/java/com/android/server/emergency/EmergencyAffordanceService.java b/services/core/java/com/android/server/emergency/EmergencyAffordanceService.java
index a91fe773a5cf..1cf27ffd1903 100644
--- a/services/core/java/com/android/server/emergency/EmergencyAffordanceService.java
+++ b/services/core/java/com/android/server/emergency/EmergencyAffordanceService.java
@@ -231,7 +231,8 @@ public class EmergencyAffordanceService extends SystemService {
// a Sim with a different mcc code was found
neededNow = false;
}
- String simOperator = mTelephonyManager.getSimOperator(info.getSubscriptionId());
+ String simOperator = mTelephonyManager
+ .createForSubscriptionId(info.getSubscriptionId()).getSimOperator();
mcc = 0;
if (simOperator != null && simOperator.length() >= 3) {
mcc = Integer.parseInt(simOperator.substring(0, 3));
diff --git a/services/core/java/com/android/server/hdmi/HdmiCecKeycode.java b/services/core/java/com/android/server/hdmi/HdmiCecKeycode.java
index 52cede2121bd..23b5c1411b0e 100644
--- a/services/core/java/com/android/server/hdmi/HdmiCecKeycode.java
+++ b/services/core/java/com/android/server/hdmi/HdmiCecKeycode.java
@@ -250,7 +250,11 @@ final class HdmiCecKeycode {
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_LEFT_UP),
// No Android keycode defined for CEC_KEYCODE_LEFT_DOWN
new KeycodeEntry(UNSUPPORTED_KEYCODE, CEC_KEYCODE_LEFT_DOWN),
+ // Both KEYCODE_HOME and KEYCODE_MENU keys are sent as CEC_KEYCODE_ROOT_MENU
+ // NOTE that the HOME key is not usually forwarded.
+ // When CEC_KEYCODE_ROOT_MENU is received, it is translated to KEYCODE_HOME
new KeycodeEntry(KeyEvent.KEYCODE_HOME, CEC_KEYCODE_ROOT_MENU),
+ new KeycodeEntry(KeyEvent.KEYCODE_MENU, CEC_KEYCODE_ROOT_MENU),
new KeycodeEntry(KeyEvent.KEYCODE_SETTINGS, CEC_KEYCODE_SETUP_MENU),
new KeycodeEntry(KeyEvent.KEYCODE_TV_CONTENTS_MENU, CEC_KEYCODE_CONTENTS_MENU, false),
// No Android keycode defined for CEC_KEYCODE_FAVORITE_MENU
diff --git a/services/core/java/com/android/server/incremental/IncrementalManagerService.java b/services/core/java/com/android/server/incremental/IncrementalManagerService.java
new file mode 100644
index 000000000000..789551bb2263
--- /dev/null
+++ b/services/core/java/com/android/server/incremental/IncrementalManagerService.java
@@ -0,0 +1,155 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.incremental;
+
+import android.annotation.NonNull;
+import android.content.Context;
+import android.content.pm.DataLoaderManager;
+import android.content.pm.DataLoaderParamsParcel;
+import android.content.pm.FileSystemControlParcel;
+import android.content.pm.IDataLoader;
+import android.content.pm.IDataLoaderStatusListener;
+import android.os.Bundle;
+import android.os.RemoteException;
+import android.os.ResultReceiver;
+import android.os.ServiceManager;
+import android.os.ShellCallback;
+import android.os.incremental.IIncrementalManager;
+import android.util.Slog;
+
+import java.io.FileDescriptor;
+
+/**
+ * This service has the following purposes:
+ * 1) Starts the IIncrementalManager binder service.
+ * 1) Starts the native IIncrementalManagerService binder service.
+ * 2) Handles shell commands for "incremental" service.
+ * 3) Handles binder calls from the native IIncrementalManagerService binder service and pass
+ * them to a data loader binder service.
+ */
+
+public class IncrementalManagerService extends IIncrementalManager.Stub {
+ private static final String TAG = "IncrementalManagerService";
+ private static final String BINDER_SERVICE_NAME = "incremental";
+ // DataLoaderManagerService should have been started before us
+ private @NonNull DataLoaderManager mDataLoaderManager;
+ private long mNativeInstance;
+ private final @NonNull Context mContext;
+
+ /**
+ * Starts IIncrementalManager binder service and register to Service Manager.
+ * Starts the native IIncrementalManagerNative binder service.
+ */
+ public static IncrementalManagerService start(Context context) {
+ IncrementalManagerService self = new IncrementalManagerService(context);
+ if (self.mNativeInstance == 0) {
+ return null;
+ }
+ return self;
+ }
+
+ private IncrementalManagerService(Context context) {
+ mContext = context;
+ mDataLoaderManager = mContext.getSystemService(DataLoaderManager.class);
+ ServiceManager.addService(BINDER_SERVICE_NAME, this);
+ // Starts and register IIncrementalManagerNative service
+ // TODO(b/136132412): add jni implementation
+ }
+ /**
+ * Notifies native IIncrementalManager service that system is ready.
+ */
+ public void systemReady() {
+ // TODO(b/136132412): add jni implementation
+ }
+
+ /**
+ * Finds data loader service provider and binds to it. This requires PackageManager.
+ */
+ @Override
+ public boolean prepareDataLoader(int mountId, FileSystemControlParcel control,
+ DataLoaderParamsParcel params,
+ IDataLoaderStatusListener listener) {
+ Bundle dataLoaderParams = new Bundle();
+ dataLoaderParams.putCharSequence("packageName", params.packageName);
+ dataLoaderParams.putParcelable("control", control);
+ dataLoaderParams.putParcelable("params", params);
+ DataLoaderManager dataLoaderManager = mContext.getSystemService(DataLoaderManager.class);
+ if (dataLoaderManager == null) {
+ Slog.e(TAG, "Failed to find data loader manager service");
+ return false;
+ }
+ if (!dataLoaderManager.initializeDataLoader(mountId, dataLoaderParams, listener)) {
+ Slog.e(TAG, "Failed to initialize data loader");
+ return false;
+ }
+ return true;
+ }
+
+
+ @Override
+ public boolean startDataLoader(int mountId) {
+ IDataLoader dataLoader = mDataLoaderManager.getDataLoader(mountId);
+ if (dataLoader == null) {
+ Slog.e(TAG, "Start failed to retrieve data loader for ID=" + mountId);
+ return false;
+ }
+ try {
+ // TODO: fix file list
+ dataLoader.start(null);
+ return true;
+ } catch (RemoteException ex) {
+ return false;
+ }
+ }
+
+ @Override
+ public void destroyDataLoader(int mountId) {
+ IDataLoader dataLoader = mDataLoaderManager.getDataLoader(mountId);
+ if (dataLoader == null) {
+ Slog.e(TAG, "Destroy failed to retrieve data loader for ID=" + mountId);
+ return;
+ }
+ try {
+ dataLoader.destroy();
+ } catch (RemoteException ex) {
+ return;
+ }
+ }
+
+ // TODO: remove this
+ @Override
+ public void newFileForDataLoader(int mountId, long inode, byte[] metadata) {
+ IDataLoader dataLoader = mDataLoaderManager.getDataLoader(mountId);
+ if (dataLoader == null) {
+ Slog.e(TAG, "Failed to retrieve data loader for ID=" + mountId);
+ return;
+ }
+ }
+
+ @Override
+ public void showHealthBlockedUI(int mountId) {
+ // TODO(b/136132412): implement this
+ }
+
+ @Override
+ public void onShellCommand(@NonNull FileDescriptor in, @NonNull FileDescriptor out,
+ FileDescriptor err, @NonNull String[] args, ShellCallback callback,
+ @NonNull ResultReceiver resultReceiver) {
+ (new IncrementalManagerShellCommand(mContext)).exec(
+ this, in, out, err, args, callback, resultReceiver);
+ }
+}
diff --git a/services/core/java/com/android/server/incremental/IncrementalManagerShellCommand.java b/services/core/java/com/android/server/incremental/IncrementalManagerShellCommand.java
new file mode 100644
index 000000000000..6a8434aad88b
--- /dev/null
+++ b/services/core/java/com/android/server/incremental/IncrementalManagerShellCommand.java
@@ -0,0 +1,295 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.incremental;
+
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.content.Context;
+import android.content.IIntentReceiver;
+import android.content.IIntentSender;
+import android.content.Intent;
+import android.content.IntentSender;
+import android.content.pm.DataLoaderParams;
+import android.content.pm.InstallationFile;
+import android.content.pm.PackageInstaller;
+import android.content.pm.PackageManager;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.ParcelFileDescriptor;
+import android.os.ShellCommand;
+import android.util.Slog;
+
+import java.io.FileDescriptor;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Defines actions to handle adb commands like "adb abb incremental ...".
+ */
+public final class IncrementalManagerShellCommand extends ShellCommand {
+ private static final String TAG = "IncrementalShellCommand";
+ // Assuming the adb data loader is always installed on the device
+ private static final String LOADER_PACKAGE_NAME = "com.android.incremental.nativeadb";
+ private final @NonNull Context mContext;
+
+ private static final int ERROR_INVALID_ARGUMENTS = -1;
+ private static final int ERROR_DATA_LOADER_INIT = -2;
+ private static final int ERROR_COMMAND_EXECUTION = -3;
+
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef({ERROR_INVALID_ARGUMENTS, ERROR_DATA_LOADER_INIT, ERROR_COMMAND_EXECUTION})
+ public @interface IncrementalShellCommandErrorCode {
+ }
+
+ IncrementalManagerShellCommand(@NonNull Context context) {
+ mContext = context;
+ }
+
+ @Override
+ public int onCommand(@Nullable String cmd) {
+ if (cmd == null) {
+ return handleDefaultCommands(null);
+ }
+ switch (cmd) {
+ case "install-start":
+ return runInstallStart();
+ case "install-finish":
+ return runInstallFinish();
+ default:
+ return handleDefaultCommands(cmd);
+ }
+ }
+
+ @Override
+ public void onHelp() {
+ PrintWriter pw = getOutPrintWriter();
+ pw.println("Incremental Service Commands:");
+ pw.println(" help");
+ pw.println(" Print this help text.");
+ pw.println(" install-start");
+ pw.println(" Opens an installation session");
+ pw.println(" install-finish SESSION_ID --file NAME:SIZE:INDEX --file NAME:SIZE:INDEX ...");
+ pw.println(" Commits an installation session specified by session ID for an APK ");
+ pw.println(" or a bundle of splits. Configures lib dirs or OBB files if specified.");
+ }
+
+ private int runInstallStart() {
+ final PrintWriter pw = getOutPrintWriter();
+ final PackageInstaller packageInstaller =
+ mContext.getPackageManager().getPackageInstaller();
+ if (packageInstaller == null) {
+ pw.println("Failed to get PackageInstaller.");
+ return ERROR_COMMAND_EXECUTION;
+ }
+
+ final Map<String, ParcelFileDescriptor> dataLoaderDynamicArgs = getDataLoaderDynamicArgs();
+ if (dataLoaderDynamicArgs == null) {
+ pw.println("File names and sizes don't match.");
+ return ERROR_DATA_LOADER_INIT;
+ }
+ final DataLoaderParams params = new DataLoaderParams(
+ "", LOADER_PACKAGE_NAME, dataLoaderDynamicArgs);
+ PackageInstaller.SessionParams sessionParams = new PackageInstaller.SessionParams(
+ PackageInstaller.SessionParams.MODE_FULL_INSTALL);
+ sessionParams.installFlags |= PackageManager.INSTALL_ALL_USERS;
+ // Replace existing if same package is already installed
+ sessionParams.installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
+ sessionParams.setIncrementalParams(params);
+
+ try {
+ int sessionId = packageInstaller.createSession(sessionParams);
+ pw.println("Successfully opened session: sessionId = " + sessionId);
+ } catch (Exception ex) {
+ pw.println("Failed to create session.");
+ return ERROR_COMMAND_EXECUTION;
+ } finally {
+ try {
+ for (Map.Entry<String, ParcelFileDescriptor> nfd
+ : dataLoaderDynamicArgs.entrySet()) {
+ nfd.getValue().close();
+ }
+ } catch (IOException ignored) {
+ }
+ }
+ return 0;
+ }
+
+ private int runInstallFinish() {
+ final PrintWriter pw = getOutPrintWriter();
+ final int sessionId = parseInt(getNextArgRequired());
+ final List<InstallationFile> installationFiles = parseFileArgs(pw);
+ if (installationFiles == null) {
+ pw.println("Must specify at least one file to install.");
+ return ERROR_INVALID_ARGUMENTS;
+ }
+ final int numFiles = installationFiles.size();
+ if (numFiles == 0) {
+ pw.println("Must specify at least one file to install.");
+ return ERROR_INVALID_ARGUMENTS;
+ }
+
+ final PackageInstaller packageInstaller = mContext.getPackageManager()
+ .getPackageInstaller();
+ if (packageInstaller == null) {
+ pw.println("Failed to get PackageInstaller.");
+ return ERROR_COMMAND_EXECUTION;
+ }
+
+ final LocalIntentReceiver localReceiver = new LocalIntentReceiver();
+ boolean success = false;
+
+ PackageInstaller.Session session = null;
+ try {
+ session = packageInstaller.openSession(sessionId);
+ for (int i = 0; i < numFiles; i++) {
+ InstallationFile file = installationFiles.get(i);
+ session.addFile(file.getName(), file.getSize(), file.getMetadata());
+ }
+ session.commit(localReceiver.getIntentSender());
+ final Intent result = localReceiver.getResult();
+ final int status = result.getIntExtra(PackageInstaller.EXTRA_STATUS,
+ PackageInstaller.STATUS_FAILURE);
+ if (status == PackageInstaller.STATUS_SUCCESS) {
+ success = true;
+ pw.println("Success");
+ return 0;
+ } else {
+ pw.println("Failure ["
+ + result.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE) + "]");
+ return ERROR_COMMAND_EXECUTION;
+ }
+ } catch (Exception e) {
+ e.printStackTrace(pw);
+ return ERROR_COMMAND_EXECUTION;
+ } finally {
+ if (!success) {
+ try {
+ if (session != null) {
+ session.abandon();
+ }
+ } catch (Exception ignore) {
+ }
+ }
+ }
+ }
+
+ private static class LocalIntentReceiver {
+ private final LinkedBlockingQueue<Intent> mResult = new LinkedBlockingQueue<>();
+
+ private IIntentSender.Stub mLocalSender = new IIntentSender.Stub() {
+ @Override
+ public void send(int code, Intent intent, String resolvedType, IBinder whitelistToken,
+ IIntentReceiver finishedReceiver, String requiredPermission,
+ Bundle options) {
+ try {
+ mResult.offer(intent, 5, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ };
+
+ public IntentSender getIntentSender() {
+ return new IntentSender((IIntentSender) mLocalSender);
+ }
+
+ public Intent getResult() {
+ try {
+ return mResult.take();
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ /** Helpers. */
+ private Map<String, ParcelFileDescriptor> getDataLoaderDynamicArgs() {
+ Map<String, ParcelFileDescriptor> dataLoaderDynamicArgs = new HashMap<>();
+ final FileDescriptor outFd = getOutFileDescriptor();
+ final FileDescriptor inFd = getInFileDescriptor();
+ try {
+ dataLoaderDynamicArgs.put("inFd", ParcelFileDescriptor.dup(inFd));
+ dataLoaderDynamicArgs.put("outFd", ParcelFileDescriptor.dup(outFd));
+ return dataLoaderDynamicArgs;
+ } catch (Exception ex) {
+ Slog.e(TAG, "Failed to dup FDs");
+ return null;
+ }
+ }
+
+ private long parseLong(String arg) {
+ long result = -1;
+ try {
+ result = Long.parseLong(arg);
+ } catch (NumberFormatException e) {
+ }
+ return result;
+ }
+
+ private int parseInt(String arg) {
+ int result = -1;
+ try {
+ result = Integer.parseInt(arg);
+ } catch (NumberFormatException e) {
+ }
+ return result;
+ }
+
+ private List<InstallationFile> parseFileArgs(PrintWriter pw) {
+ List<InstallationFile> fileList = new ArrayList<>();
+ String opt;
+ while ((opt = getNextOption()) != null) {
+ switch (opt) {
+ case "--file": {
+ final String fileArgs = getNextArgRequired();
+ final String[] args = fileArgs.split(":");
+ if (args.length != 3) {
+ pw.println("Invalid file args: " + fileArgs);
+ return null;
+ }
+ final String name = args[0];
+ final long size = parseLong(args[1]);
+ if (size < 0) {
+ pw.println("Invalid file size in: " + fileArgs);
+ return null;
+ }
+ final long index = parseLong(args[2]);
+ if (index < 0) {
+ pw.println("Invalid file index in: " + fileArgs);
+ return null;
+ }
+ final byte[] metadata = String.valueOf(index).getBytes(StandardCharsets.UTF_8);
+ fileList.add(new InstallationFile(name, size, metadata));
+ break;
+ }
+ default:
+ break;
+ }
+ }
+ return fileList;
+ }
+}
diff --git a/services/core/java/com/android/server/infra/AbstractMasterSystemService.java b/services/core/java/com/android/server/infra/AbstractMasterSystemService.java
index d71ffb770cc3..58f6ba2fd67f 100644
--- a/services/core/java/com/android/server/infra/AbstractMasterSystemService.java
+++ b/services/core/java/com/android/server/infra/AbstractMasterSystemService.java
@@ -762,6 +762,7 @@ public abstract class AbstractMasterSystemService<M extends AbstractMasterSystem
if (mUpdatingPackageNames != null) {
pw.print("Packages being updated: "); pw.println(mUpdatingPackageNames);
}
+ dumpSupportedUsers(pw, prefix);
if (mServiceNameResolver != null) {
pw.print(prefix); pw.print("Name resolver: ");
mServiceNameResolver.dumpShort(pw); pw.println();
diff --git a/services/core/java/com/android/server/input/ConfigurationProcessor.java b/services/core/java/com/android/server/input/ConfigurationProcessor.java
index 970e86acf8b8..3888b1b71096 100644
--- a/services/core/java/com/android/server/input/ConfigurationProcessor.java
+++ b/services/core/java/com/android/server/input/ConfigurationProcessor.java
@@ -17,7 +17,6 @@
package com.android.server.input;
import android.text.TextUtils;
-import android.util.Pair;
import android.util.Slog;
import android.util.Xml;
@@ -29,7 +28,9 @@ import org.xmlpull.v1.XmlPullParser;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
class ConfigurationProcessor {
@@ -86,9 +87,9 @@ class ConfigurationProcessor {
* the second item in the pair is the display port.
*/
@VisibleForTesting
- static List<Pair<String, String>> processInputPortAssociations(InputStream xml)
+ static Map<String, Integer> processInputPortAssociations(InputStream xml)
throws Exception {
- List<Pair<String, String>> associations = new ArrayList<>();
+ Map<String, Integer> associations = new HashMap<String, Integer>();
try (InputStreamReader confReader = new InputStreamReader(xml)) {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(confReader);
@@ -101,19 +102,18 @@ class ConfigurationProcessor {
break;
}
String inputPort = parser.getAttributeValue(null, "input");
- String displayPort = parser.getAttributeValue(null, "display");
- if (TextUtils.isEmpty(inputPort) || TextUtils.isEmpty(displayPort)) {
+ String displayPortStr = parser.getAttributeValue(null, "display");
+ if (TextUtils.isEmpty(inputPort) || TextUtils.isEmpty(displayPortStr)) {
// This is likely an error by an OEM during device configuration
Slog.wtf(TAG, "Ignoring incomplete entry");
continue;
}
try {
- Integer.parseUnsignedInt(displayPort);
+ int displayPort = Integer.parseUnsignedInt(displayPortStr);
+ associations.put(inputPort, displayPort);
} catch (NumberFormatException e) {
Slog.wtf(TAG, "Display port should be an integer");
- continue;
}
- associations.add(new Pair<>(inputPort, displayPort));
}
}
return associations;
diff --git a/services/core/java/com/android/server/input/InputManagerService.java b/services/core/java/com/android/server/input/InputManagerService.java
index 16b7d9951ad4..b77c85929dd6 100644
--- a/services/core/java/com/android/server/input/InputManagerService.java
+++ b/services/core/java/com/android/server/input/InputManagerService.java
@@ -64,7 +64,6 @@ import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.text.TextUtils;
import android.util.Log;
-import android.util.Pair;
import android.util.Slog;
import android.util.SparseArray;
import android.view.Display;
@@ -113,8 +112,8 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
+import java.util.Map;
import java.util.Objects;
-
/*
* Wraps the C++ InputManager and provides its callbacks.
*/
@@ -184,6 +183,10 @@ public class InputManagerService extends IInputManager.Stub
IInputFilter mInputFilter; // guarded by mInputFilterLock
InputFilterHost mInputFilterHost; // guarded by mInputFilterLock
+ // The associations of input devices to displays by port. Maps from input device port (String)
+ // to display id (int). Currently only accessed by InputReader.
+ private final Map<String, Integer> mStaticAssociations;
+
private static native long nativeInit(InputManagerService service,
Context context, MessageQueue messageQueue);
private static native void nativeStart(long ptr);
@@ -325,6 +328,7 @@ public class InputManagerService extends IInputManager.Stub
mDoubleTouchGestureEnableFile = TextUtils.isEmpty(doubleTouchGestureEnablePath) ? null :
new File(doubleTouchGestureEnablePath);
+ mStaticAssociations = loadStaticInputPortAssociations();
LocalServices.addService(InputManagerInternal.class, new LocalService());
}
@@ -1727,6 +1731,17 @@ public class InputManagerService extends IInputManager.Stub
String dumpStr = nativeDump(mPtr);
if (dumpStr != null) {
pw.println(dumpStr);
+ dumpAssociations(pw);
+ }
+ }
+
+ private void dumpAssociations(PrintWriter pw) {
+ if (!mStaticAssociations.isEmpty()) {
+ pw.println("Static Associations:");
+ mStaticAssociations.forEach((k, v) -> {
+ pw.print(" port: " + k);
+ pw.println(" display: " + v);
+ });
}
}
@@ -1910,15 +1925,16 @@ public class InputManagerService extends IInputManager.Stub
}
/**
- * Flatten a list of pairs into a list, with value positioned directly next to the key
+ * Flatten a map into a string list, with value positioned directly next to the
+ * key.
* @return Flattened list
*/
- private static <T> List<T> flatten(@NonNull List<Pair<T, T>> pairs) {
- List<T> list = new ArrayList<>(pairs.size() * 2);
- for (Pair<T, T> pair : pairs) {
- list.add(pair.first);
- list.add(pair.second);
- }
+ private static List<String> flatten(@NonNull Map<String, Integer> map) {
+ List<String> list = new ArrayList<>(map.size() * 2);
+ map.forEach((k, v)-> {
+ list.add(k);
+ list.add(v.toString());
+ });
return list;
}
@@ -1926,23 +1942,26 @@ public class InputManagerService extends IInputManager.Stub
* Ports are highly platform-specific, so only allow these to be specified in the vendor
* directory.
*/
- // Native callback
- private static String[] getInputPortAssociations() {
+ private static Map<String, Integer> loadStaticInputPortAssociations() {
File baseDir = Environment.getVendorDirectory();
File confFile = new File(baseDir, PORT_ASSOCIATIONS_PATH);
try {
InputStream stream = new FileInputStream(confFile);
- List<Pair<String, String>> associations =
- ConfigurationProcessor.processInputPortAssociations(stream);
- List<String> associationList = flatten(associations);
- return associationList.toArray(new String[0]);
+ return ConfigurationProcessor.processInputPortAssociations(stream);
} catch (FileNotFoundException e) {
// Most of the time, file will not exist, which is expected.
} catch (Exception e) {
Slog.e(TAG, "Could not parse '" + confFile.getAbsolutePath() + "'", e);
}
- return new String[0];
+
+ return new HashMap<>();
+ }
+
+ // Native callback
+ private String[] getInputPortAssociations() {
+ List<String> associationList = flatten(mStaticAssociations);
+ return associationList.toArray(new String[0]);
}
/**
diff --git a/services/core/java/com/android/server/inputmethod/InputMethodManagerInternal.java b/services/core/java/com/android/server/inputmethod/InputMethodManagerInternal.java
index 944a95dda99b..44c8971ba4c2 100644
--- a/services/core/java/com/android/server/inputmethod/InputMethodManagerInternal.java
+++ b/services/core/java/com/android/server/inputmethod/InputMethodManagerInternal.java
@@ -18,8 +18,14 @@ package com.android.server.inputmethod;
import android.annotation.NonNull;
import android.annotation.UserIdInt;
+import android.content.ComponentName;
+import android.os.RemoteException;
+import android.util.Log;
+import android.view.autofill.AutofillId;
+import android.view.inputmethod.InlineSuggestionsRequest;
import android.view.inputmethod.InputMethodInfo;
+import com.android.internal.view.IInlineSuggestionsRequestCallback;
import com.android.server.LocalServices;
import java.util.Collections;
@@ -57,6 +63,17 @@ public abstract class InputMethodManagerInternal {
public abstract List<InputMethodInfo> getEnabledInputMethodListAsUser(@UserIdInt int userId);
/**
+ * Called by the Autofill Frameworks to request an {@link InlineSuggestionsRequest} from
+ * the input method.
+ *
+ * @param componentName {@link ComponentName} of current app/activity.
+ * @param autofillId {@link AutofillId} of currently focused field.
+ * @param cb {@link IInlineSuggestionsRequestCallback} used to pass back the request object.
+ */
+ public abstract void onCreateInlineSuggestionsRequest(ComponentName componentName,
+ AutofillId autofillId, IInlineSuggestionsRequestCallback cb);
+
+ /**
* Fake implementation of {@link InputMethodManagerInternal}. All the methods do nothing.
*/
private static final InputMethodManagerInternal NOP =
@@ -78,6 +95,17 @@ public abstract class InputMethodManagerInternal {
public List<InputMethodInfo> getEnabledInputMethodListAsUser(int userId) {
return Collections.emptyList();
}
+
+ @Override
+ public void onCreateInlineSuggestionsRequest(ComponentName componentName,
+ AutofillId autofillId, IInlineSuggestionsRequestCallback cb) {
+ try {
+ cb.onInlineSuggestionsUnsupported();
+ } catch (RemoteException e) {
+ Log.w("IMManagerInternal", "RemoteException calling"
+ + " onInlineSuggestionsUnsupported: " + e);
+ }
+ }
};
/**
diff --git a/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java b/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
index 471fa72b1957..5865dc471b30 100644
--- a/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
+++ b/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
@@ -109,6 +109,7 @@ import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.view.WindowManager.LayoutParams.SoftInputModeFlags;
+import android.view.autofill.AutofillId;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputBinding;
import android.view.inputmethod.InputConnection;
@@ -140,6 +141,7 @@ import com.android.internal.os.SomeArgs;
import com.android.internal.os.TransferPipe;
import com.android.internal.util.DumpUtils;
import com.android.internal.util.IndentingPrintWriter;
+import com.android.internal.view.IInlineSuggestionsRequestCallback;
import com.android.internal.view.IInputContext;
import com.android.internal.view.IInputMethod;
import com.android.internal.view.IInputMethodClient;
@@ -211,6 +213,8 @@ public class InputMethodManagerService extends IInputMethodManager.Stub
static final int MSG_SYSTEM_UNLOCK_USER = 5000;
+ static final int MSG_INLINE_SUGGESTIONS_REQUEST = 6000;
+
static final long TIME_TO_RECONNECT = 3 * 1000;
static final int SECURE_SUGGESTION_SPANS_MAX_SIZE = 20;
@@ -1785,6 +1789,16 @@ public class InputMethodManagerService extends IInputMethodManager.Stub
return settings.getEnabledInputMethodListLocked();
}
+ @GuardedBy("mMethodMap")
+ private void onCreateInlineSuggestionsRequestLocked(ComponentName componentName,
+ AutofillId autofillId, IInlineSuggestionsRequestCallback callback) {
+ if (mCurMethod != null) {
+ executeOrSendMessage(mCurMethod,
+ mCaller.obtainMessageOOOO(MSG_INLINE_SUGGESTIONS_REQUEST, mCurMethod,
+ componentName, autofillId, callback));
+ }
+ }
+
/**
* @param imiId if null, returns enabled subtypes for the current imi
* @return enabled subtypes of the specified imi
@@ -3874,6 +3888,21 @@ public class InputMethodManagerService extends IInputMethodManager.Stub
final int userId = msg.arg1;
onUnlockUser(userId);
return true;
+
+ // ---------------------------------------------------------------
+ case MSG_INLINE_SUGGESTIONS_REQUEST:
+ args = (SomeArgs) msg.obj;
+ final ComponentName componentName = (ComponentName) args.arg2;
+ final AutofillId autofillId = (AutofillId) args.arg3;
+ final IInlineSuggestionsRequestCallback callback =
+ (IInlineSuggestionsRequestCallback) args.arg4;
+ try {
+ ((IInputMethod) args.arg1).onCreateInlineSuggestionsRequest(componentName,
+ autofillId, callback);
+ } catch (RemoteException e) {
+ Slog.w(TAG, "RemoteException calling onCreateInlineSuggestionsRequest(): " + e);
+ }
+ return true;
}
return false;
}
@@ -4434,6 +4463,13 @@ public class InputMethodManagerService extends IInputMethodManager.Stub
}
}
+ private void onCreateInlineSuggestionsRequest(ComponentName componentName,
+ AutofillId autofillId, IInlineSuggestionsRequestCallback callback) {
+ synchronized (mMethodMap) {
+ onCreateInlineSuggestionsRequestLocked(componentName, autofillId, callback);
+ }
+ }
+
private static final class LocalServiceImpl extends InputMethodManagerInternal {
@NonNull
private final InputMethodManagerService mService;
@@ -4464,6 +4500,12 @@ public class InputMethodManagerService extends IInputMethodManager.Stub
public List<InputMethodInfo> getEnabledInputMethodListAsUser(int userId) {
return mService.getEnabledInputMethodListAsUser(userId);
}
+
+ @Override
+ public void onCreateInlineSuggestionsRequest(ComponentName componentName,
+ AutofillId autofillId, IInlineSuggestionsRequestCallback cb) {
+ mService.onCreateInlineSuggestionsRequest(componentName, autofillId, cb);
+ }
}
@BinderThread
diff --git a/services/core/java/com/android/server/inputmethod/MultiClientInputMethodManagerService.java b/services/core/java/com/android/server/inputmethod/MultiClientInputMethodManagerService.java
index 02e29e0b2ab5..c13d55adda08 100644
--- a/services/core/java/com/android/server/inputmethod/MultiClientInputMethodManagerService.java
+++ b/services/core/java/com/android/server/inputmethod/MultiClientInputMethodManagerService.java
@@ -59,10 +59,12 @@ import android.provider.Settings;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.ArraySet;
+import android.util.Log;
import android.util.Slog;
import android.util.SparseArray;
import android.view.InputChannel;
import android.view.WindowManager.LayoutParams.SoftInputModeFlags;
+import android.view.autofill.AutofillId;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnectionInspector.MissingMethodFlags;
import android.view.inputmethod.InputMethodInfo;
@@ -82,6 +84,7 @@ import com.android.internal.os.TransferPipe;
import com.android.internal.util.DumpUtils;
import com.android.internal.util.IndentingPrintWriter;
import com.android.internal.util.function.pooled.PooledLambda;
+import com.android.internal.view.IInlineSuggestionsRequestCallback;
import com.android.internal.view.IInputContext;
import com.android.internal.view.IInputMethodClient;
import com.android.internal.view.IInputMethodManager;
@@ -187,6 +190,18 @@ public final class MultiClientInputMethodManagerService {
@UserIdInt int userId) {
return userIdToInputMethodInfoMapper.getAsList(userId);
}
+
+ @Override
+ public void onCreateInlineSuggestionsRequest(ComponentName componentName,
+ AutofillId autofillId, IInlineSuggestionsRequestCallback cb) {
+ try {
+ //TODO(b/137800469): support multi client IMEs.
+ cb.onInlineSuggestionsUnsupported();
+ } catch (RemoteException e) {
+ Log.w("MultiClientIMManager", "RemoteException calling"
+ + " onInlineSuggestionsUnsupported: " + e);
+ }
+ }
});
}
diff --git a/apex/sdkext/framework/tests/src/android/os/ext/SdkExtensionsTest.java b/services/core/java/com/android/server/integrity/AppIntegrityManagerService.java
index d7dca90e0b8f..005fb696b089 100644
--- a/apex/sdkext/framework/tests/src/android/os/ext/SdkExtensionsTest.java
+++ b/services/core/java/com/android/server/integrity/AppIntegrityManagerService.java
@@ -14,27 +14,30 @@
* limitations under the License.
*/
-package android.os.ext;
+package com.android.server.integrity;
-import android.os.Build;
-import android.test.suitebuilder.annotation.SmallTest;
+import android.content.Context;
-import junit.framework.TestCase;
+import com.android.server.SystemService;
-public class SdkExtensionsTest extends TestCase {
+/**
+ * Service that manages app integrity rules and verifications.
+ *
+ * @hide
+ */
+public class AppIntegrityManagerService extends SystemService {
- @SmallTest
- public void testBadArgument() throws Exception {
- try {
- SdkExtensions.getExtensionVersion(Build.VERSION_CODES.Q);
- fail("expected IllegalArgumentException");
- } catch (IllegalArgumentException expected) { }
- }
+ private Context mContext;
+ private AppIntegrityManagerServiceImpl mService;
- @SmallTest
- public void testDefault() throws Exception {
- int r = SdkExtensions.getExtensionVersion(Build.VERSION_CODES.R);
- assertTrue(r >= 0);
+ public AppIntegrityManagerService(Context context) {
+ super(context);
+ mContext = context;
}
+ @Override
+ public void onStart() {
+ mService = new AppIntegrityManagerServiceImpl(mContext);
+ // TODO: define and publish a binder service.
+ }
}
diff --git a/services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java b/services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java
new file mode 100644
index 000000000000..39c1b8535565
--- /dev/null
+++ b/services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.integrity;
+
+import static android.content.Intent.ACTION_PACKAGE_NEEDS_INTEGRITY_VERIFICATION;
+import static android.content.pm.PackageManager.EXTRA_VERIFICATION_ID;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManagerInternal;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.util.Slog;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.LocalServices;
+
+/** Implementation of {@link AppIntegrityManagerService}. */
+class AppIntegrityManagerServiceImpl {
+ private static final String TAG = "AppIntegrityManagerServiceImpl";
+
+ private final Context mContext;
+ private final Handler mHandler;
+ private final PackageManagerInternal mPackageManagerInternal;
+
+ AppIntegrityManagerServiceImpl(Context context) {
+ mContext = context;
+
+ HandlerThread handlerThread = new HandlerThread("AppIntegrityManagerServiceHandler");
+ handlerThread.start();
+ mHandler = handlerThread.getThreadHandler();
+
+ mPackageManagerInternal = LocalServices.getService(PackageManagerInternal.class);
+
+ IntentFilter integrityVerificationFilter = new IntentFilter();
+ integrityVerificationFilter.addAction(ACTION_PACKAGE_NEEDS_INTEGRITY_VERIFICATION);
+
+ mContext.registerReceiver(
+ new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ if (!ACTION_PACKAGE_NEEDS_INTEGRITY_VERIFICATION.equals(
+ intent.getAction())) {
+ return;
+ }
+ mHandler.post(() -> handleIntegrityVerification(intent));
+ }
+ },
+ integrityVerificationFilter,
+ /* broadcastPermission= */ null,
+ mHandler);
+ }
+
+ // protected broadcasts cannot be sent in the test.
+ @VisibleForTesting
+ void handleIntegrityVerification(Intent intent) {
+ int verificationId = intent.getIntExtra(EXTRA_VERIFICATION_ID, -1);
+ // TODO: implement this method.
+ Slog.i(TAG, "Received integrity verification intent " + intent.toString());
+ mPackageManagerInternal.setIntegrityVerificationResult(
+ verificationId, PackageManager.VERIFICATION_ALLOW);
+ }
+}
diff --git a/services/core/java/com/android/server/integrity/OWNERS b/services/core/java/com/android/server/integrity/OWNERS
index 019aa4fb0f2b..55a4e409c767 100644
--- a/services/core/java/com/android/server/integrity/OWNERS
+++ b/services/core/java/com/android/server/integrity/OWNERS
@@ -3,4 +3,3 @@ khelmy@google.com
mdchurchill@google.com
sturla@google.com
songpan@google.com
-bjy@google.com
diff --git a/services/core/java/com/android/server/integrity/serializer/RuleIndexingDetails.java b/services/core/java/com/android/server/integrity/serializer/RuleIndexingDetails.java
new file mode 100644
index 000000000000..dd871e2bbe6c
--- /dev/null
+++ b/services/core/java/com/android/server/integrity/serializer/RuleIndexingDetails.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.integrity.serializer;
+
+import android.annotation.IntDef;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/** Holds the indexing type and indexing key of a given formula. */
+class RuleIndexingDetails {
+
+ static final int NOT_INDEXED = 0;
+ static final int PACKAGE_NAME_INDEXED = 1;
+ static final int APP_CERTIFICATE_INDEXED = 2;
+
+ /** Represents which indexed file the rule should be located. */
+ @IntDef(
+ value = {
+ NOT_INDEXED,
+ PACKAGE_NAME_INDEXED,
+ APP_CERTIFICATE_INDEXED
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface IndexType {
+ }
+
+ private @IndexType int mIndexType;
+ private String mRuleKey;
+
+ /** Constructor without a ruleKey for {@code NOT_INDEXED}. */
+ RuleIndexingDetails(@IndexType int indexType) {
+ this.mIndexType = indexType;
+ this.mRuleKey = null;
+ }
+
+ /** Constructor with a ruleKey for indexed rules. */
+ RuleIndexingDetails(@IndexType int indexType, String ruleKey) {
+ this.mIndexType = indexType;
+ this.mRuleKey = ruleKey;
+ }
+
+ /** Returns the indexing type for the rule. */
+ @IndexType
+ public int getIndexType() {
+ return mIndexType;
+ }
+
+ /** Returns the identified rule key. */
+ public String getRuleKey() {
+ return mRuleKey;
+ }
+}
diff --git a/services/core/java/com/android/server/integrity/serializer/RuleIndexingDetailsIdentifier.java b/services/core/java/com/android/server/integrity/serializer/RuleIndexingDetailsIdentifier.java
new file mode 100644
index 000000000000..7d5e83649373
--- /dev/null
+++ b/services/core/java/com/android/server/integrity/serializer/RuleIndexingDetailsIdentifier.java
@@ -0,0 +1,169 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.integrity.serializer;
+
+import static com.android.server.integrity.serializer.RuleIndexingDetails.APP_CERTIFICATE_INDEXED;
+import static com.android.server.integrity.serializer.RuleIndexingDetails.NOT_INDEXED;
+import static com.android.server.integrity.serializer.RuleIndexingDetails.PACKAGE_NAME_INDEXED;
+
+import android.content.integrity.AtomicFormula;
+import android.content.integrity.CompoundFormula;
+import android.content.integrity.Formula;
+import android.content.integrity.Rule;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.TreeMap;
+
+/** A helper class for identifying the indexing type and key of a given rule. */
+class RuleIndexingDetailsIdentifier {
+
+ private static final String DEFAULT_RULE_KEY = "N/A";
+
+ /**
+ * Splits a given rule list into three indexing categories and returns a sorted list of rules
+ * per each index.
+ *
+ * The sorting guarantees an order based on the key but the rules that have the same key
+ * can be in arbitrary order. For example, given the rules of [package_name_a_rule_1,
+ * package_name_a_rule_2, package_name_b_rule_3, package_name_b_rule_4], the method will
+ * guarantee that package_name_b rules (i.e., 3 and 4) will never come before package_name_a
+ * rules (i.e., 1 and 2). However, we do not care about the ordering between rule 1 and 2.
+ * We also do not care about the ordering between rule 3 and 4.
+ */
+ public static Map<Integer, List<Rule>> splitRulesIntoIndexBuckets(List<Rule> rules) {
+ if (rules == null) {
+ throw new IllegalArgumentException(
+ "Index buckets cannot be created for null rule list.");
+ }
+
+ Map<Integer, Map<String, List<Rule>>> typeOrganizedRuleMap = new HashMap();
+ typeOrganizedRuleMap.put(NOT_INDEXED, new TreeMap());
+ typeOrganizedRuleMap.put(PACKAGE_NAME_INDEXED, new TreeMap());
+ typeOrganizedRuleMap.put(APP_CERTIFICATE_INDEXED, new TreeMap());
+
+ // Split the rules into the appropriate indexed pattern. The Tree Maps help us to keep the
+ // entries sorted by their index key.
+ for (Rule rule : rules) {
+ RuleIndexingDetails indexingDetails = getIndexingDetails(rule.getFormula());
+ String ruleKey =
+ indexingDetails.getIndexType() != NOT_INDEXED
+ ? indexingDetails.getRuleKey()
+ : DEFAULT_RULE_KEY;
+
+ if (!typeOrganizedRuleMap.get(indexingDetails.getIndexType()).containsKey(ruleKey)) {
+ typeOrganizedRuleMap
+ .get(indexingDetails.getIndexType())
+ .put(ruleKey, new ArrayList());
+ }
+
+ typeOrganizedRuleMap
+ .get(indexingDetails.getIndexType())
+ .get(ruleKey)
+ .add(rule);
+ }
+
+ // Per indexing type, create the sorted rule set based on their key.
+ Map<Integer, List<Rule>> orderedListPerIndexingType = new HashMap<>();
+
+ for (Integer indexingKey : typeOrganizedRuleMap.keySet()) {
+ List<Rule> sortedRules = new ArrayList();
+ for (Map.Entry<String, List<Rule>> entry :
+ typeOrganizedRuleMap.get(indexingKey).entrySet()) {
+ sortedRules.addAll(entry.getValue());
+ }
+ orderedListPerIndexingType.put(indexingKey, sortedRules);
+ }
+
+ return orderedListPerIndexingType;
+ }
+
+ private static RuleIndexingDetails getIndexingDetails(Formula formula) {
+ switch (formula.getTag()) {
+ case Formula.COMPOUND_FORMULA_TAG:
+ return getIndexingDetailsForCompoundFormula((CompoundFormula) formula);
+ case Formula.STRING_ATOMIC_FORMULA_TAG:
+ return getIndexingDetailsForStringAtomicFormula(
+ (AtomicFormula.StringAtomicFormula) formula);
+ case Formula.INT_ATOMIC_FORMULA_TAG:
+ case Formula.BOOLEAN_ATOMIC_FORMULA_TAG:
+ // Package name and app certificate related formulas are string atomic formulas.
+ return new RuleIndexingDetails(NOT_INDEXED);
+ default:
+ throw new IllegalArgumentException(
+ String.format("Invalid formula tag type: %s", formula.getTag()));
+ }
+ }
+
+ private static RuleIndexingDetails getIndexingDetailsForCompoundFormula(
+ CompoundFormula compoundFormula) {
+ int connector = compoundFormula.getConnector();
+ List<Formula> formulas = compoundFormula.getFormulas();
+
+ switch (connector) {
+ case CompoundFormula.AND:
+ case CompoundFormula.OR:
+ // If there is a package name related atomic rule, return package name indexed.
+ Optional<RuleIndexingDetails> packageNameRule =
+ formulas.stream()
+ .map(formula -> getIndexingDetails(formula))
+ .filter(ruleIndexingDetails -> ruleIndexingDetails.getIndexType()
+ == PACKAGE_NAME_INDEXED)
+ .findAny();
+ if (packageNameRule.isPresent()) {
+ return packageNameRule.get();
+ }
+
+ // If there is an app certificate related atomic rule but no package name related
+ // atomic rule, return app certificate indexed.
+ Optional<RuleIndexingDetails> appCertificateRule =
+ formulas.stream()
+ .map(formula -> getIndexingDetails(formula))
+ .filter(ruleIndexingDetails -> ruleIndexingDetails.getIndexType()
+ == APP_CERTIFICATE_INDEXED)
+ .findAny();
+ if (appCertificateRule.isPresent()) {
+ return appCertificateRule.get();
+ }
+
+ // Do not index when there is not package name or app certificate indexing.
+ return new RuleIndexingDetails(NOT_INDEXED);
+ default:
+ // Having a NOT operator in the indexing messes up the indexing; e.g., deny
+ // installation if app certificate is NOT X (should not be indexed with app cert
+ // X). We will not keep these rules indexed.
+ // Also any other type of unknown operators will not be indexed.
+ return new RuleIndexingDetails(NOT_INDEXED);
+ }
+ }
+
+ private static RuleIndexingDetails getIndexingDetailsForStringAtomicFormula(
+ AtomicFormula.StringAtomicFormula atomicFormula) {
+ switch (atomicFormula.getKey()) {
+ case AtomicFormula.PACKAGE_NAME:
+ return new RuleIndexingDetails(PACKAGE_NAME_INDEXED, atomicFormula.getValue());
+ case AtomicFormula.APP_CERTIFICATE:
+ return new RuleIndexingDetails(APP_CERTIFICATE_INDEXED, atomicFormula.getValue());
+ default:
+ return new RuleIndexingDetails(NOT_INDEXED);
+ }
+ }
+}
+
diff --git a/services/core/java/com/android/server/location/LocationSettingsStore.java b/services/core/java/com/android/server/location/LocationSettingsStore.java
index eb2a37b38f1c..f625452975c0 100644
--- a/services/core/java/com/android/server/location/LocationSettingsStore.java
+++ b/services/core/java/com/android/server/location/LocationSettingsStore.java
@@ -23,7 +23,6 @@ import static android.provider.Settings.Global.LOCATION_IGNORE_SETTINGS_PACKAGE_
import static android.provider.Settings.Global.LOCATION_LAST_LOCATION_MAX_AGE_MILLIS;
import static android.provider.Settings.Secure.LOCATION_MODE;
import static android.provider.Settings.Secure.LOCATION_MODE_OFF;
-import static android.provider.Settings.Secure.LOCATION_PROVIDERS_ALLOWED;
import android.app.ActivityManager;
import android.content.Context;
@@ -35,6 +34,7 @@ import android.provider.Settings;
import android.text.TextUtils;
import android.util.ArraySet;
+import com.android.internal.annotations.GuardedBy;
import com.android.internal.util.IndentingPrintWriter;
import com.android.internal.util.Preconditions;
import com.android.server.SystemConfig;
@@ -89,7 +89,6 @@ public class LocationSettingsStore {
private final Context mContext;
private final IntegerSecureSetting mLocationMode;
- private final StringListCachedSecureSetting mLocationProvidersAllowed;
private final LongGlobalSetting mBackgroundThrottleIntervalMs;
private final StringListCachedSecureSetting mLocationPackageBlacklist;
private final StringListCachedSecureSetting mLocationPackageWhitelist;
@@ -101,8 +100,6 @@ public class LocationSettingsStore {
mContext = context;
mLocationMode = new IntegerSecureSetting(context, LOCATION_MODE, handler);
- mLocationProvidersAllowed = new StringListCachedSecureSetting(context,
- LOCATION_PROVIDERS_ALLOWED, handler);
mBackgroundThrottleIntervalMs = new LongGlobalSetting(context,
LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS, handler);
mLocationPackageBlacklist = new StringListCachedSecureSetting(context,
@@ -117,6 +114,16 @@ public class LocationSettingsStore {
() -> SystemConfig.getInstance().getAllowIgnoreLocationSettings(), handler);
}
+ /** Called when system is ready. */
+ public synchronized void onSystemReady() {
+ mLocationMode.register();
+ mBackgroundThrottleIntervalMs.register();
+ mLocationPackageBlacklist.register();
+ mLocationPackageWhitelist.register();
+ mBackgroundThrottlePackageWhitelist.register();
+ mIgnoreSettingsPackageWhitelist.register();
+ }
+
/**
* Retrieve if location is enabled or not.
*/
@@ -139,28 +146,6 @@ public class LocationSettingsStore {
}
/**
- * Retrieve the currently allowed location providers.
- */
- public List<String> getLocationProvidersAllowed(int userId) {
- return mLocationProvidersAllowed.getValueForUser(userId);
- }
-
- /**
- * Add a listener for changes to the currently allowed location providers.
- */
- public void addOnLocationProvidersAllowedChangedListener(UserSettingChangedListener listener) {
- mLocationProvidersAllowed.addListener(listener);
- }
-
- /**
- * Remove a listener for changes to the currently allowed location providers.
- */
- public void removeOnLocationProvidersAllowedChangedListener(
- UserSettingChangedListener listener) {
- mLocationProvidersAllowed.removeListener(listener);
- }
-
- /**
* Retrieve the background throttle interval.
*/
public long getBackgroundThrottleIntervalMs() {
@@ -280,9 +265,6 @@ public class LocationSettingsStore {
ipw.print("Location Enabled: ");
ipw.println(isLocationEnabled(userId));
- ipw.print("Location Providers Allowed: ");
- ipw.println(getLocationProvidersAllowed(userId));
-
List<String> locationPackageBlacklist = mLocationPackageBlacklist.getValueForUser(userId);
if (!locationPackageBlacklist.isEmpty()) {
ipw.println("Location Blacklisted Packages:");
@@ -329,13 +311,25 @@ public class LocationSettingsStore {
private abstract static class ObservingSetting extends ContentObserver {
private final CopyOnWriteArrayList<UserSettingChangedListener> mListeners;
+ private boolean mRegistered;
- private ObservingSetting(Context context, String settingName, Handler handler) {
+ private ObservingSetting(Handler handler) {
super(handler);
mListeners = new CopyOnWriteArrayList<>();
+ }
+
+ protected boolean isRegistered() {
+ return mRegistered;
+ }
+
+ protected void register(Context context, Uri uri) {
+ if (mRegistered) {
+ return;
+ }
context.getContentResolver().registerContentObserver(
- getUriFor(settingName), false, this, UserHandle.USER_ALL);
+ uri, false, this, UserHandle.USER_ALL);
+ mRegistered = true;
}
public void addListener(UserSettingChangedListener listener) {
@@ -346,8 +340,6 @@ public class LocationSettingsStore {
mListeners.remove(listener);
}
- protected abstract Uri getUriFor(String settingName);
-
@Override
public void onChange(boolean selfChange, Uri uri, int userId) {
for (UserSettingChangedListener listener : mListeners) {
@@ -362,20 +354,19 @@ public class LocationSettingsStore {
private final String mSettingName;
private IntegerSecureSetting(Context context, String settingName, Handler handler) {
- super(context, settingName, handler);
+ super(handler);
mContext = context;
mSettingName = settingName;
}
+ private void register() {
+ register(mContext, Settings.Secure.getUriFor(mSettingName));
+ }
+
public int getValueForUser(int defaultValue, int userId) {
return Settings.Secure.getIntForUser(mContext.getContentResolver(), mSettingName,
defaultValue, userId);
}
-
- @Override
- protected Uri getUriFor(String settingName) {
- return Settings.Secure.getUriFor(settingName);
- }
}
private static class StringListCachedSecureSetting extends ObservingSetting {
@@ -383,31 +374,44 @@ public class LocationSettingsStore {
private final Context mContext;
private final String mSettingName;
- private int mCachedUserId = UserHandle.USER_NULL;
+ @GuardedBy("this")
+ private int mCachedUserId;
+ @GuardedBy("this")
private List<String> mCachedValue;
private StringListCachedSecureSetting(Context context, String settingName,
Handler handler) {
- super(context, settingName, handler);
+ super(handler);
mContext = context;
mSettingName = settingName;
+
+ mCachedUserId = UserHandle.USER_NULL;
+ }
+
+ public synchronized void register() {
+ register(mContext, Settings.Secure.getUriFor(mSettingName));
}
public synchronized List<String> getValueForUser(int userId) {
Preconditions.checkArgument(userId != UserHandle.USER_NULL);
+ List<String> value = mCachedValue;
if (userId != mCachedUserId) {
String setting = Settings.Secure.getStringForUser(mContext.getContentResolver(),
mSettingName, userId);
if (TextUtils.isEmpty(setting)) {
- mCachedValue = Collections.emptyList();
+ value = Collections.emptyList();
} else {
- mCachedValue = Arrays.asList(setting.split(","));
+ value = Arrays.asList(setting.split(","));
+ }
+
+ if (isRegistered()) {
+ mCachedUserId = userId;
+ mCachedValue = value;
}
- mCachedUserId = userId;
}
- return mCachedValue;
+ return value;
}
public synchronized void invalidateForUser(int userId) {
@@ -422,11 +426,6 @@ public class LocationSettingsStore {
invalidateForUser(userId);
super.onChange(selfChange, uri, userId);
}
-
- @Override
- protected Uri getUriFor(String settingName) {
- return Settings.Secure.getUriFor(settingName);
- }
}
private static class LongGlobalSetting extends ObservingSetting {
@@ -435,20 +434,19 @@ public class LocationSettingsStore {
private final String mSettingName;
private LongGlobalSetting(Context context, String settingName, Handler handler) {
- super(context, settingName, handler);
+ super(handler);
mContext = context;
mSettingName = settingName;
}
+ public void register() {
+ register(mContext, Settings.Global.getUriFor(mSettingName));
+ }
+
public long getValue(long defaultValue) {
return Settings.Global.getLong(mContext.getContentResolver(), mSettingName,
defaultValue);
}
-
- @Override
- protected Uri getUriFor(String settingName) {
- return Settings.Global.getUriFor(settingName);
- }
}
private static class StringSetCachedGlobalSetting extends ObservingSetting {
@@ -457,29 +455,42 @@ public class LocationSettingsStore {
private final String mSettingName;
private final Supplier<ArraySet<String>> mBaseValuesSupplier;
+ @GuardedBy("this")
private boolean mValid;
+ @GuardedBy("this")
private ArraySet<String> mCachedValue;
private StringSetCachedGlobalSetting(Context context, String settingName,
Supplier<ArraySet<String>> baseValuesSupplier, Handler handler) {
- super(context, settingName, handler);
+ super(handler);
mContext = context;
mSettingName = settingName;
mBaseValuesSupplier = baseValuesSupplier;
+
+ mValid = false;
+ }
+
+ public synchronized void register() {
+ register(mContext, Settings.Global.getUriFor(mSettingName));
}
public synchronized Set<String> getValue() {
+ ArraySet<String> value = mCachedValue;
if (!mValid) {
- mCachedValue = new ArraySet<>(mBaseValuesSupplier.get());
+ value = new ArraySet<>(mBaseValuesSupplier.get());
String setting = Settings.Global.getString(mContext.getContentResolver(),
mSettingName);
if (!TextUtils.isEmpty(setting)) {
- mCachedValue.addAll(Arrays.asList(setting.split(",")));
+ value.addAll(Arrays.asList(setting.split(",")));
+ }
+
+ if (isRegistered()) {
+ mValid = true;
+ mCachedValue = value;
}
- mValid = true;
}
- return mCachedValue;
+ return value;
}
public synchronized void invalidate() {
@@ -492,10 +503,5 @@ public class LocationSettingsStore {
invalidate();
super.onChange(selfChange, uri, userId);
}
-
- @Override
- protected Uri getUriFor(String settingName) {
- return Settings.Global.getUriFor(settingName);
- }
}
}
diff --git a/services/core/java/com/android/server/LocationUsageLogger.java b/services/core/java/com/android/server/location/LocationUsageLogger.java
index a8a3cc47cfb0..755438b1a413 100644
--- a/services/core/java/com/android/server/LocationUsageLogger.java
+++ b/services/core/java/com/android/server/location/LocationUsageLogger.java
@@ -14,37 +14,113 @@
* limitations under the License.
*/
-package com.android.server;
+package com.android.server.location;
+
+import static com.android.server.LocationManagerService.TAG;
import android.app.ActivityManager;
import android.location.Geofence;
import android.location.LocationManager;
import android.location.LocationRequest;
-import android.os.SystemClock;
import android.stats.location.LocationStatsEnums;
import android.util.Log;
import android.util.StatsLog;
+import com.android.internal.annotations.GuardedBy;
+
import java.time.Instant;
/**
* Logger for Location API usage logging.
*/
public class LocationUsageLogger {
- private static final String TAG = "LocationUsageLogger";
- private static final boolean D = Log.isLoggable(TAG, Log.DEBUG);
private static final int ONE_SEC_IN_MILLIS = 1000;
private static final int ONE_MINUTE_IN_MILLIS = 60000;
private static final int ONE_HOUR_IN_MILLIS = 3600000;
- private long mLastApiUsageLogHour = 0;
+ private static final int API_USAGE_LOG_HOURLY_CAP = 60;
+ @GuardedBy("this")
+ private long mLastApiUsageLogHour = 0;
+ @GuardedBy("this")
private int mApiUsageLogHourlyCount = 0;
- private static final int API_USAGE_LOG_HOURLY_CAP = 60;
+ /**
+ * Log a location API usage event.
+ */
+ public void logLocationApiUsage(int usageType, int apiInUse,
+ String packageName, LocationRequest locationRequest,
+ boolean hasListener, boolean hasIntent,
+ Geofence geofence, int activityImportance) {
+ try {
+ if (hitApiUsageLogCap()) {
+ return;
+ }
+
+ boolean isLocationRequestNull = locationRequest == null;
+ boolean isGeofenceNull = geofence == null;
+
+ StatsLog.write(StatsLog.LOCATION_MANAGER_API_USAGE_REPORTED, usageType,
+ apiInUse, packageName,
+ isLocationRequestNull
+ ? LocationStatsEnums.PROVIDER_UNKNOWN
+ : bucketizeProvider(locationRequest.getProvider()),
+ isLocationRequestNull
+ ? LocationStatsEnums.QUALITY_UNKNOWN
+ : locationRequest.getQuality(),
+ isLocationRequestNull
+ ? LocationStatsEnums.INTERVAL_UNKNOWN
+ : bucketizeInterval(locationRequest.getInterval()),
+ isLocationRequestNull
+ ? LocationStatsEnums.DISTANCE_UNKNOWN
+ : bucketizeDistance(
+ locationRequest.getSmallestDisplacement()),
+ isLocationRequestNull ? 0 : locationRequest.getNumUpdates(),
+ // only log expireIn for USAGE_STARTED
+ isLocationRequestNull || usageType == LocationStatsEnums.USAGE_ENDED
+ ? LocationStatsEnums.EXPIRATION_UNKNOWN
+ : bucketizeExpireIn(locationRequest.getExpireIn()),
+ getCallbackType(apiInUse, hasListener, hasIntent),
+ isGeofenceNull
+ ? LocationStatsEnums.RADIUS_UNKNOWN
+ : bucketizeRadius(geofence.getRadius()),
+ categorizeActivityImportance(activityImportance));
+ } catch (Exception e) {
+ // Swallow exceptions to avoid crashing LMS.
+ Log.w(TAG, "Failed to log API usage to statsd.", e);
+ }
+ }
- private static int providerNameToStatsdEnum(String provider) {
+ /**
+ * Log a location API usage event.
+ */
+ public void logLocationApiUsage(int usageType, int apiInUse, String providerName) {
+ try {
+ if (hitApiUsageLogCap()) {
+ return;
+ }
+
+ StatsLog.write(StatsLog.LOCATION_MANAGER_API_USAGE_REPORTED, usageType, apiInUse,
+ /* package_name= */ null,
+ bucketizeProvider(providerName),
+ LocationStatsEnums.QUALITY_UNKNOWN,
+ LocationStatsEnums.INTERVAL_UNKNOWN,
+ LocationStatsEnums.DISTANCE_UNKNOWN,
+ /* numUpdates= */ 0,
+ LocationStatsEnums.EXPIRATION_UNKNOWN,
+ getCallbackType(
+ apiInUse,
+ /* isListenerNull= */ true,
+ /* isIntentNull= */ true),
+ /* bucketizedRadius= */ 0,
+ LocationStatsEnums.IMPORTANCE_UNKNOWN);
+ } catch (Exception e) {
+ Log.w(TAG, "Failed to log API usage to statsd.", e);
+ }
+ }
+
+ private static int bucketizeProvider(String provider) {
if (LocationManager.NETWORK_PROVIDER.equals(provider)) {
return LocationStatsEnums.PROVIDER_NETWORK;
} else if (LocationManager.GPS_PROVIDER.equals(provider)) {
@@ -58,8 +134,7 @@ public class LocationUsageLogger {
}
}
- private static int bucketizeIntervalToStatsdEnum(long interval) {
- // LocationManager already converts negative values to 0.
+ private static int bucketizeInterval(long interval) {
if (interval < ONE_SEC_IN_MILLIS) {
return LocationStatsEnums.INTERVAL_BETWEEN_0_SEC_AND_1_SEC;
} else if (interval < ONE_SEC_IN_MILLIS * 5) {
@@ -75,9 +150,8 @@ public class LocationUsageLogger {
}
}
- private static int bucketizeSmallestDisplacementToStatsdEnum(float smallestDisplacement) {
- // LocationManager already converts negative values to 0.
- if (smallestDisplacement == 0) {
+ private static int bucketizeDistance(float smallestDisplacement) {
+ if (smallestDisplacement <= 0) {
return LocationStatsEnums.DISTANCE_ZERO;
} else if (smallestDisplacement > 0 && smallestDisplacement <= 100) {
return LocationStatsEnums.DISTANCE_BETWEEN_0_AND_100;
@@ -86,7 +160,7 @@ public class LocationUsageLogger {
}
}
- private static int bucketizeRadiusToStatsdEnum(float radius) {
+ private static int bucketizeRadius(float radius) {
if (radius < 0) {
return LocationStatsEnums.RADIUS_NEGATIVE;
} else if (radius < 100) {
@@ -104,14 +178,11 @@ public class LocationUsageLogger {
}
}
- private static int getBucketizedExpireIn(long expireAt) {
- if (expireAt == Long.MAX_VALUE) {
+ private static int bucketizeExpireIn(long expireIn) {
+ if (expireIn == Long.MAX_VALUE) {
return LocationStatsEnums.EXPIRATION_NO_EXPIRY;
}
- long elapsedRealtime = SystemClock.elapsedRealtime();
- long expireIn = Math.max(0, expireAt - elapsedRealtime);
-
if (expireIn < 20 * ONE_SEC_IN_MILLIS) {
return LocationStatsEnums.EXPIRATION_BETWEEN_0_AND_20_SEC;
} else if (expireIn < ONE_MINUTE_IN_MILLIS) {
@@ -129,8 +200,8 @@ public class LocationUsageLogger {
if (importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return LocationStatsEnums.IMPORTANCE_TOP;
} else if (importance == ActivityManager
- .RunningAppProcessInfo
- .IMPORTANCE_FOREGROUND_SERVICE) {
+ .RunningAppProcessInfo
+ .IMPORTANCE_FOREGROUND_SERVICE) {
return LocationStatsEnums.IMPORTANCE_FORGROUND_SERVICE;
} else {
return LocationStatsEnums.IMPORTANCE_BACKGROUND;
@@ -154,117 +225,16 @@ public class LocationUsageLogger {
}
}
- // Update the hourly count of APIUsage log event.
- // Returns false if hit the hourly log cap.
- private boolean checkApiUsageLogCap() {
- if (D) {
- Log.d(TAG, "checking APIUsage log cap.");
- }
-
+ private synchronized boolean hitApiUsageLogCap() {
long currentHour = Instant.now().toEpochMilli() / ONE_HOUR_IN_MILLIS;
if (currentHour > mLastApiUsageLogHour) {
mLastApiUsageLogHour = currentHour;
mApiUsageLogHourlyCount = 0;
- return true;
+ return false;
} else {
mApiUsageLogHourlyCount = Math.min(
- mApiUsageLogHourlyCount + 1, API_USAGE_LOG_HOURLY_CAP);
- return mApiUsageLogHourlyCount < API_USAGE_LOG_HOURLY_CAP;
- }
- }
-
- /**
- * Log a Location API usage event to Statsd.
- * Logging event is capped at 60 per hour. Usage events exceeding
- * the cap will be dropped by LocationUsageLogger.
- */
- public void logLocationApiUsage(int usageType, int apiInUse,
- String packageName, LocationRequest locationRequest,
- boolean hasListener, boolean hasIntent,
- Geofence geofence, int activityImportance) {
- try {
- if (!checkApiUsageLogCap()) {
- return;
- }
-
- boolean isLocationRequestNull = locationRequest == null;
- boolean isGeofenceNull = geofence == null;
- if (D) {
- Log.d(TAG, "log API Usage to statsd. usageType: " + usageType + ", apiInUse: "
- + apiInUse + ", packageName: " + (packageName == null ? "" : packageName)
- + ", locationRequest: "
- + (isLocationRequestNull ? "" : locationRequest.toString())
- + ", hasListener: " + hasListener
- + ", hasIntent: " + hasIntent
- + ", geofence: "
- + (isGeofenceNull ? "" : geofence.toString())
- + ", importance: " + activityImportance);
- }
-
- StatsLog.write(StatsLog.LOCATION_MANAGER_API_USAGE_REPORTED, usageType,
- apiInUse, packageName,
- isLocationRequestNull
- ? LocationStatsEnums.PROVIDER_UNKNOWN
- : providerNameToStatsdEnum(locationRequest.getProvider()),
- isLocationRequestNull
- ? LocationStatsEnums.QUALITY_UNKNOWN
- : locationRequest.getQuality(),
- isLocationRequestNull
- ? LocationStatsEnums.INTERVAL_UNKNOWN
- : bucketizeIntervalToStatsdEnum(locationRequest.getInterval()),
- isLocationRequestNull
- ? LocationStatsEnums.DISTANCE_UNKNOWN
- : bucketizeSmallestDisplacementToStatsdEnum(
- locationRequest.getSmallestDisplacement()),
- isLocationRequestNull ? 0 : locationRequest.getNumUpdates(),
- // only log expireIn for USAGE_STARTED
- isLocationRequestNull || usageType == LocationStatsEnums.USAGE_ENDED
- ? LocationStatsEnums.EXPIRATION_UNKNOWN
- : getBucketizedExpireIn(locationRequest.getExpireAt()),
- getCallbackType(apiInUse, hasListener, hasIntent),
- isGeofenceNull
- ? LocationStatsEnums.RADIUS_UNKNOWN
- : bucketizeRadiusToStatsdEnum(geofence.getRadius()),
- categorizeActivityImportance(activityImportance));
- } catch (Exception e) {
- // Swallow exceptions to avoid crashing LMS.
- Log.w(TAG, "Failed to log API usage to statsd.", e);
- }
- }
-
- /**
- * Log a Location API usage event to Statsd.
- * Logging event is capped at 60 per hour. Usage events exceeding
- * the cap will be dropped by LocationUsageLogger.
- */
- public void logLocationApiUsage(int usageType, int apiInUse, String providerName) {
- try {
- if (!checkApiUsageLogCap()) {
- return;
- }
-
- if (D) {
- Log.d(TAG, "log API Usage to statsd. usageType: " + usageType + ", apiInUse: "
- + apiInUse + ", providerName: " + providerName);
- }
-
- StatsLog.write(StatsLog.LOCATION_MANAGER_API_USAGE_REPORTED, usageType, apiInUse,
- /* package_name= */ null,
- providerNameToStatsdEnum(providerName),
- LocationStatsEnums.QUALITY_UNKNOWN,
- LocationStatsEnums.INTERVAL_UNKNOWN,
- LocationStatsEnums.DISTANCE_UNKNOWN,
- /* numUpdates= */ 0,
- LocationStatsEnums.EXPIRATION_UNKNOWN,
- getCallbackType(
- apiInUse,
- /* isListenerNull= */ true,
- /* isIntentNull= */ true),
- /* bucketizedRadius= */ 0,
- LocationStatsEnums.IMPORTANCE_UNKNOWN);
- } catch (Exception e) {
- // Swallow exceptions to avoid crashing LMS.
- Log.w(TAG, "Failed to log API usage to statsd.", e);
+ mApiUsageLogHourlyCount + 1, API_USAGE_LOG_HOURLY_CAP);
+ return mApiUsageLogHourlyCount >= API_USAGE_LOG_HOURLY_CAP;
}
}
}
diff --git a/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java b/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java
index 9fcee50d7037..e7b88604db32 100644
--- a/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java
+++ b/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java
@@ -183,8 +183,9 @@ class MediaRouter2ServiceImpl {
}
public void setControlCategories(@NonNull IMediaRouter2Client client,
- @Nullable List<String> categories) {
+ @NonNull List<String> categories) {
Objects.requireNonNull(client, "client must not be null");
+ Objects.requireNonNull(categories, "categories must not be null");
final long token = Binder.clearCallingIdentity();
try {
@@ -390,8 +391,11 @@ class MediaRouter2ServiceImpl {
private void setControlCategoriesLocked(Client2Record clientRecord, List<String> categories) {
if (clientRecord != null) {
- clientRecord.mControlCategories = categories;
+ if (clientRecord.mControlCategories.equals(categories)) {
+ return;
+ }
+ clientRecord.mControlCategories = categories;
clientRecord.mUserRecord.mHandler.sendMessage(
obtainMessage(UserHandler::updateClientUsage,
clientRecord.mUserRecord.mHandler, clientRecord));
diff --git a/services/core/java/com/android/server/media/MediaSessionService.java b/services/core/java/com/android/server/media/MediaSessionService.java
index c25e206d9104..069aeefd7a73 100644
--- a/services/core/java/com/android/server/media/MediaSessionService.java
+++ b/services/core/java/com/android/server/media/MediaSessionService.java
@@ -47,7 +47,8 @@ import android.media.MediaController2;
import android.media.Session2CommandGroup;
import android.media.Session2Token;
import android.media.session.IActiveSessionsListener;
-import android.media.session.ICallback;
+import android.media.session.IOnMediaKeyEventDispatchedListener;
+import android.media.session.IOnMediaKeyEventSessionChangedListener;
import android.media.session.IOnMediaKeyListener;
import android.media.session.IOnVolumeKeyLongPressListener;
import android.media.session.ISession;
@@ -70,6 +71,7 @@ import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.os.ResultReceiver;
import android.os.ServiceManager;
+import android.os.ShellCallback;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.Settings;
@@ -749,7 +751,10 @@ public class MediaSessionService extends SystemService implements Monitor {
private final int mFullUserId;
private final MediaSessionStack mPriorityStack;
- private final HashMap<IBinder, CallbackRecord> mCallbacks = new HashMap<>();
+ private final HashMap<IBinder, OnMediaKeyEventDispatchedListenerRecord>
+ mOnMediaKeyEventDispatchedListeners = new HashMap<>();
+ private final HashMap<IBinder, OnMediaKeyEventSessionChangedListenerRecord>
+ mOnMediaKeyEventSessionChangedListeners = new HashMap<>();
private PendingIntent mLastMediaButtonReceiver;
private ComponentName mRestoredMediaButtonReceiver;
@@ -795,21 +800,47 @@ public class MediaSessionService extends SystemService implements Monitor {
}
}
- public void registerCallbackLocked(ICallback callback, int uid) {
- IBinder cbBinder = callback.asBinder();
- CallbackRecord cr = new CallbackRecord(callback, uid);
- mCallbacks.put(cbBinder, cr);
+ public void addOnMediaKeyEventDispatchedListenerLocked(
+ IOnMediaKeyEventDispatchedListener listener, int uid) {
+ IBinder cbBinder = listener.asBinder();
+ OnMediaKeyEventDispatchedListenerRecord cr =
+ new OnMediaKeyEventDispatchedListenerRecord(listener, uid);
+ mOnMediaKeyEventDispatchedListeners.put(cbBinder, cr);
try {
cbBinder.linkToDeath(cr, 0);
} catch (RemoteException e) {
- Log.w(TAG, "Failed to register callback", e);
- mCallbacks.remove(cbBinder);
+ Log.w(TAG, "Failed to add listener", e);
+ mOnMediaKeyEventDispatchedListeners.remove(cbBinder);
}
}
- public void unregisterCallbackLocked(ICallback callback) {
- IBinder cbBinder = callback.asBinder();
- CallbackRecord cr = mCallbacks.remove(cbBinder);
+ public void removeOnMediaKeyEventDispatchedListenerLocked(
+ IOnMediaKeyEventDispatchedListener listener) {
+ IBinder cbBinder = listener.asBinder();
+ OnMediaKeyEventDispatchedListenerRecord cr =
+ mOnMediaKeyEventDispatchedListeners.remove(cbBinder);
+ cbBinder.unlinkToDeath(cr, 0);
+ }
+
+ public void addOnMediaKeyEventSessionChangedListenerLocked(
+ IOnMediaKeyEventSessionChangedListener listener, int uid) {
+ IBinder cbBinder = listener.asBinder();
+ OnMediaKeyEventSessionChangedListenerRecord cr =
+ new OnMediaKeyEventSessionChangedListenerRecord(listener, uid);
+ mOnMediaKeyEventSessionChangedListeners.put(cbBinder, cr);
+ try {
+ cbBinder.linkToDeath(cr, 0);
+ } catch (RemoteException e) {
+ Log.w(TAG, "Failed to add listener", e);
+ mOnMediaKeyEventSessionChangedListeners.remove(cbBinder);
+ }
+ }
+
+ public void removeOnMediaKeyEventSessionChangedListener(
+ IOnMediaKeyEventSessionChangedListener listener) {
+ IBinder cbBinder = listener.asBinder();
+ OnMediaKeyEventSessionChangedListenerRecord cr =
+ mOnMediaKeyEventSessionChangedListeners.remove(cbBinder);
cbBinder.unlinkToDeath(cr, 0);
}
@@ -831,8 +862,16 @@ public class MediaSessionService extends SystemService implements Monitor {
pw.println(indent + "Media key listener: " + mOnMediaKeyListener);
pw.println(indent + "Media key listener package: "
+ getCallingPackageName(mOnMediaKeyListenerUid));
- pw.println(indent + "Callbacks: registered " + mCallbacks.size() + " callback(s)");
- for (CallbackRecord cr : mCallbacks.values()) {
+ pw.println(indent + "OnMediaKeyEventDispatchedListener: added "
+ + mOnMediaKeyEventDispatchedListeners.size() + " listener(s)");
+ for (OnMediaKeyEventDispatchedListenerRecord cr
+ : mOnMediaKeyEventDispatchedListeners.values()) {
+ pw.println(indent + " from " + getCallingPackageName(cr.uid));
+ }
+ pw.println(indent + "OnMediaKeyEventSessionChangedListener: added "
+ + mOnMediaKeyEventSessionChangedListeners.size() + " listener(s)");
+ for (OnMediaKeyEventSessionChangedListenerRecord cr
+ : mOnMediaKeyEventSessionChangedListeners.values()) {
pw.println(indent + " from " + getCallingPackageName(cr.uid));
}
pw.println(indent + "Last MediaButtonReceiver: " + mLastMediaButtonReceiver);
@@ -894,19 +933,22 @@ public class MediaSessionService extends SystemService implements Monitor {
mFullUserId);
}
- private void pushAddressedPlayerChangedLocked(ICallback callback) {
+ private void pushAddressedPlayerChangedLocked(
+ IOnMediaKeyEventSessionChangedListener callback) {
try {
MediaSessionRecord mediaButtonSession = getMediaButtonSessionLocked();
if (mediaButtonSession != null) {
- callback.onAddressedPlayerChangedToMediaSession(
+ callback.onMediaKeyEventSessionChanged(mediaButtonSession.getPackageName(),
mediaButtonSession.getSessionToken());
} else if (mCurrentFullUserRecord.mLastMediaButtonReceiver != null) {
- callback.onAddressedPlayerChangedToMediaButtonReceiver(
+ callback.onMediaKeyEventSessionChanged(
mCurrentFullUserRecord.mLastMediaButtonReceiver
- .getIntent().getComponent());
+ .getIntent().getComponent().getPackageName(),
+ null);
} else if (mCurrentFullUserRecord.mRestoredMediaButtonReceiver != null) {
- callback.onAddressedPlayerChangedToMediaButtonReceiver(
- mCurrentFullUserRecord.mRestoredMediaButtonReceiver);
+ callback.onMediaKeyEventSessionChanged(
+ mCurrentFullUserRecord.mRestoredMediaButtonReceiver.getPackageName(),
+ null);
}
} catch (RemoteException e) {
Log.w(TAG, "Failed to pushAddressedPlayerChangedLocked", e);
@@ -914,7 +956,8 @@ public class MediaSessionService extends SystemService implements Monitor {
}
private void pushAddressedPlayerChangedLocked() {
- for (CallbackRecord cr : mCallbacks.values()) {
+ for (OnMediaKeyEventSessionChangedListenerRecord cr
+ : mOnMediaKeyEventSessionChangedListeners.values()) {
pushAddressedPlayerChangedLocked(cr.callback);
}
}
@@ -953,11 +996,12 @@ public class MediaSessionService extends SystemService implements Monitor {
return COMPONENT_TYPE_BROADCAST;
}
- final class CallbackRecord implements IBinder.DeathRecipient {
- public final ICallback callback;
+ final class OnMediaKeyEventDispatchedListenerRecord implements IBinder.DeathRecipient {
+ public final IOnMediaKeyEventDispatchedListener callback;
public final int uid;
- CallbackRecord(ICallback callback, int uid) {
+ OnMediaKeyEventDispatchedListenerRecord(IOnMediaKeyEventDispatchedListener callback,
+ int uid) {
this.callback = callback;
this.uid = uid;
}
@@ -965,7 +1009,25 @@ public class MediaSessionService extends SystemService implements Monitor {
@Override
public void binderDied() {
synchronized (mLock) {
- mCallbacks.remove(callback.asBinder());
+ mOnMediaKeyEventDispatchedListeners.remove(callback.asBinder());
+ }
+ }
+ }
+
+ final class OnMediaKeyEventSessionChangedListenerRecord implements IBinder.DeathRecipient {
+ public final IOnMediaKeyEventSessionChangedListener callback;
+ public final int uid;
+
+ OnMediaKeyEventSessionChangedListenerRecord(
+ IOnMediaKeyEventSessionChangedListener callback, int uid) {
+ this.callback = callback;
+ this.uid = uid;
+ }
+
+ @Override
+ public void binderDied() {
+ synchronized (mLock) {
+ mOnMediaKeyEventSessionChangedListeners.remove(callback.asBinder());
}
}
}
@@ -1042,6 +1104,13 @@ public class MediaSessionService extends SystemService implements Monitor {
private boolean mVoiceButtonHandled = false;
@Override
+ public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
+ String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
+ (new MediaShellCommand()).exec(this, in, out, err, args, callback,
+ resultReceiver);
+ }
+
+ @Override
public ISession createSession(String packageName, ISessionCallback cb, String tag,
Bundle sessionInfo, int userId) throws RemoteException {
final int pid = Binder.getCallingPid();
@@ -1347,7 +1416,64 @@ public class MediaSessionService extends SystemService implements Monitor {
}
@Override
- public void registerCallback(final ICallback callback) {
+ public void addOnMediaKeyEventDispatchedListener(
+ final IOnMediaKeyEventDispatchedListener listener) {
+ final int pid = Binder.getCallingPid();
+ final int uid = Binder.getCallingUid();
+ final int userId = UserHandle.getUserId(uid);
+ final long token = Binder.clearCallingIdentity();
+ try {
+ if (!hasMediaControlPermission(pid, uid)) {
+ throw new SecurityException("MEDIA_CONTENT_CONTROL permission is required to"
+ + " add MediaKeyEventDispatchedListener");
+ }
+ synchronized (mLock) {
+ FullUserRecord user = getFullUserRecordLocked(userId);
+ if (user == null || user.mFullUserId != userId) {
+ Log.w(TAG, "Only the full user can add the listener"
+ + ", userId=" + userId);
+ return;
+ }
+ user.addOnMediaKeyEventDispatchedListenerLocked(listener, uid);
+ Log.d(TAG, "The MediaKeyEventDispatchedListener (" + listener.asBinder()
+ + ") is added by " + getCallingPackageName(uid));
+ }
+ } finally {
+ Binder.restoreCallingIdentity(token);
+ }
+ }
+
+ @Override
+ public void removeOnMediaKeyEventDispatchedListener(
+ final IOnMediaKeyEventDispatchedListener listener) {
+ final int pid = Binder.getCallingPid();
+ final int uid = Binder.getCallingUid();
+ final int userId = UserHandle.getUserId(uid);
+ final long token = Binder.clearCallingIdentity();
+ try {
+ if (!hasMediaControlPermission(pid, uid)) {
+ throw new SecurityException("MEDIA_CONTENT_CONTROL permission is required to"
+ + " remove MediaKeyEventDispatchedListener");
+ }
+ synchronized (mLock) {
+ FullUserRecord user = getFullUserRecordLocked(userId);
+ if (user == null || user.mFullUserId != userId) {
+ Log.w(TAG, "Only the full user can remove the listener"
+ + ", userId=" + userId);
+ return;
+ }
+ user.removeOnMediaKeyEventDispatchedListenerLocked(listener);
+ Log.d(TAG, "The MediaKeyEventDispatchedListener (" + listener.asBinder()
+ + ") is removed by " + getCallingPackageName(uid));
+ }
+ } finally {
+ Binder.restoreCallingIdentity(token);
+ }
+ }
+
+ @Override
+ public void addOnMediaKeyEventSessionChangedListener(
+ final IOnMediaKeyEventSessionChangedListener listener) {
final int pid = Binder.getCallingPid();
final int uid = Binder.getCallingUid();
final int userId = UserHandle.getUserId(uid);
@@ -1355,18 +1481,18 @@ public class MediaSessionService extends SystemService implements Monitor {
try {
if (!hasMediaControlPermission(pid, uid)) {
throw new SecurityException("MEDIA_CONTENT_CONTROL permission is required to"
- + " register Callback");
+ + " add MediaKeyEventSessionChangedListener");
}
synchronized (mLock) {
FullUserRecord user = getFullUserRecordLocked(userId);
if (user == null || user.mFullUserId != userId) {
- Log.w(TAG, "Only the full user can register the callback"
+ Log.w(TAG, "Only the full user can add the listener"
+ ", userId=" + userId);
return;
}
- user.registerCallbackLocked(callback, uid);
- Log.d(TAG, "The callback (" + callback.asBinder()
- + ") is registered by " + getCallingPackageName(uid));
+ user.addOnMediaKeyEventSessionChangedListenerLocked(listener, uid);
+ Log.d(TAG, "The MediaKeyEventSessionChangedListener (" + listener.asBinder()
+ + ") is added by " + getCallingPackageName(uid));
}
} finally {
Binder.restoreCallingIdentity(token);
@@ -1374,7 +1500,8 @@ public class MediaSessionService extends SystemService implements Monitor {
}
@Override
- public void unregisterCallback(final ICallback callback) {
+ public void removeOnMediaKeyEventSessionChangedListener(
+ final IOnMediaKeyEventSessionChangedListener listener) {
final int pid = Binder.getCallingPid();
final int uid = Binder.getCallingUid();
final int userId = UserHandle.getUserId(uid);
@@ -1382,18 +1509,18 @@ public class MediaSessionService extends SystemService implements Monitor {
try {
if (!hasMediaControlPermission(pid, uid)) {
throw new SecurityException("MEDIA_CONTENT_CONTROL permission is required to"
- + " unregister Callback");
+ + " remove MediaKeyEventSessionChangedListener");
}
synchronized (mLock) {
FullUserRecord user = getFullUserRecordLocked(userId);
if (user == null || user.mFullUserId != userId) {
- Log.w(TAG, "Only the full user can unregister the callback"
+ Log.w(TAG, "Only the full user can remove the listener"
+ ", userId=" + userId);
return;
}
- user.unregisterCallbackLocked(callback);
- Log.d(TAG, "The callback (" + callback.asBinder()
- + ") is unregistered by " + getCallingPackageName(uid));
+ user.removeOnMediaKeyEventSessionChangedListener(listener);
+ Log.d(TAG, "The MediaKeyEventSessionChangedListener (" + listener.asBinder()
+ + ") is removed by " + getCallingPackageName(uid));
}
} finally {
Binder.restoreCallingIdentity(token);
@@ -2007,10 +2134,10 @@ public class MediaSessionService extends SystemService implements Monitor {
needWakeLock ? mKeyEventReceiver.mLastTimeoutId : -1,
mKeyEventReceiver);
try {
- for (FullUserRecord.CallbackRecord cr
- : mCurrentFullUserRecord.mCallbacks.values()) {
- cr.callback.onMediaKeyEventDispatchedToMediaSession(
- keyEvent, session.getSessionToken());
+ for (FullUserRecord.OnMediaKeyEventDispatchedListenerRecord cr
+ : mCurrentFullUserRecord.mOnMediaKeyEventDispatchedListeners.values()) {
+ cr.callback.onMediaKeyEventDispatched(
+ keyEvent, session.getPackageName(), session.getSessionToken());
}
} catch (RemoteException e) {
Log.w(TAG, "Failed to send callback", e);
@@ -2040,10 +2167,11 @@ public class MediaSessionService extends SystemService implements Monitor {
ComponentName componentName = mCurrentFullUserRecord
.mLastMediaButtonReceiver.getIntent().getComponent();
if (componentName != null) {
- for (FullUserRecord.CallbackRecord cr
- : mCurrentFullUserRecord.mCallbacks.values()) {
- cr.callback.onMediaKeyEventDispatchedToMediaButtonReceiver(
- keyEvent, componentName);
+ for (FullUserRecord.OnMediaKeyEventDispatchedListenerRecord cr
+ : mCurrentFullUserRecord
+ .mOnMediaKeyEventDispatchedListeners.values()) {
+ cr.callback.onMediaKeyEventDispatched(keyEvent,
+ componentName.getPackageName(), null);
}
}
} else {
@@ -2075,10 +2203,11 @@ public class MediaSessionService extends SystemService implements Monitor {
Log.w(TAG, "Error sending media button to the restored intent "
+ receiver + ", type=" + componentType, e);
}
- for (FullUserRecord.CallbackRecord cr
- : mCurrentFullUserRecord.mCallbacks.values()) {
- cr.callback.onMediaKeyEventDispatchedToMediaButtonReceiver(
- keyEvent, receiver);
+ for (FullUserRecord.OnMediaKeyEventDispatchedListenerRecord cr
+ : mCurrentFullUserRecord
+ .mOnMediaKeyEventDispatchedListeners.values()) {
+ cr.callback.onMediaKeyEventDispatched(keyEvent,
+ receiver.getPackageName(), null);
}
}
} catch (CanceledException e) {
diff --git a/cmds/media/src/com/android/commands/media/Media.java b/services/core/java/com/android/server/media/MediaShellCommand.java
index 1e915f8232d3..20df271a1de2 100644
--- a/cmds/media/src/com/android/commands/media/Media.java
+++ b/services/core/java/com/android/server/media/MediaShellCommand.java
@@ -1,29 +1,27 @@
/*
-**
-** Copyright 2013, 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 com.android.commands.media;
+ * Copyright (C) 2019 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 com.android.server.media;
import android.app.ActivityThread;
import android.content.Context;
import android.media.MediaMetadata;
import android.media.session.ISessionManager;
import android.media.session.MediaController;
-import android.media.session.MediaController.PlaybackInfo;
-import android.media.session.MediaSession.QueueItem;
+import android.media.session.MediaSession;
import android.media.session.MediaSessionManager;
import android.media.session.PlaybackState;
import android.os.Bundle;
@@ -31,59 +29,41 @@ import android.os.HandlerThread;
import android.os.Looper;
import android.os.RemoteException;
import android.os.ServiceManager;
+import android.os.ShellCommand;
import android.os.SystemClock;
-import android.util.AndroidException;
+import android.text.TextUtils;
import android.view.InputDevice;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
-import com.android.internal.os.BaseCommand;
-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
-import java.io.PrintStream;
+import java.io.PrintWriter;
import java.util.List;
-public class Media extends BaseCommand {
+/**
+ * ShellCommand for MediaSessionService.
+ */
+public class MediaShellCommand extends ShellCommand {
// This doesn't belongs to any package. Setting the package name to empty string.
private static final String PACKAGE_NAME = "";
private static ActivityThread sThread;
private static MediaSessionManager sMediaSessionManager;
private ISessionManager mSessionService;
-
- /**
- * Command-line entry point.
- *
- * @param args The command-line arguments
- */
- public static void main(String[] args) {
- (new Media()).run(args);
- }
+ private PrintWriter mWriter;
+ private PrintWriter mErrorWriter;
@Override
- public void onShowUsage(PrintStream out) {
- out.println(
- "usage: media [subcommand] [options]\n" +
- " media dispatch KEY\n" +
- " media list-sessions\n" +
- " media monitor <tag>\n" +
- " media volume [options]\n" +
- "\n" +
- "media dispatch: dispatch a media key to the system.\n" +
- " KEY may be: play, pause, play-pause, mute, headsethook,\n" +
- " stop, next, previous, rewind, record, fast-forword.\n" +
- "media list-sessions: print a list of the current sessions.\n" +
- "media monitor: monitor updates to the specified session.\n" +
- " Use the tag from list-sessions.\n" +
- "media volume: " + VolumeCtrl.USAGE
- );
- }
+ public int onCommand(String cmd) {
+ mWriter = getOutPrintWriter();
+ mErrorWriter = getErrPrintWriter();
- @Override
- public void onRun() throws Exception {
+ if (TextUtils.isEmpty(cmd)) {
+ return handleDefaultCommands(cmd);
+ }
if (sThread == null) {
- Looper.prepareMainLooper();
+ Looper.prepare();
sThread = ActivityThread.systemMain();
Context context = sThread.getSystemContext();
sMediaSessionManager =
@@ -92,25 +72,47 @@ public class Media extends BaseCommand {
mSessionService = ISessionManager.Stub.asInterface(ServiceManager.checkService(
Context.MEDIA_SESSION_SERVICE));
if (mSessionService == null) {
- System.err.println(NO_SYSTEM_ERROR_CODE);
- throw new AndroidException(
+ throw new IllegalStateException(
"Can't connect to media session service; is the system running?");
}
- String op = nextArgRequired();
-
- if (op.equals("dispatch")) {
- runDispatch();
- } else if (op.equals("list-sessions")) {
- runListSessions();
- } else if (op.equals("monitor")) {
- runMonitor();
- } else if (op.equals("volume")) {
- runVolume();
- } else {
- showError("Error: unknown command '" + op + "'");
- return;
+ try {
+ if (cmd.equals("dispatch")) {
+ runDispatch();
+ } else if (cmd.equals("list-sessions")) {
+ runListSessions();
+ } else if (cmd.equals("monitor")) {
+ runMonitor();
+ } else if (cmd.equals("volume")) {
+ runVolume();
+ } else {
+ showError("Error: unknown command '" + cmd + "'");
+ return -1;
+ }
+ } catch (Exception e) {
+ showError(e.toString());
+ return -1;
}
+ return 0;
+ }
+
+ @Override
+ public void onHelp() {
+ mWriter.println("usage: media_session [subcommand] [options]");
+ mWriter.println(" media_session dispatch KEY");
+ mWriter.println(" media_session dispatch KEY");
+ mWriter.println(" media_session list-sessions");
+ mWriter.println(" media_session monitor <tag>");
+ mWriter.println(" media_session volume [options]");
+ mWriter.println();
+ mWriter.println("media_session dispatch: dispatch a media key to the system.");
+ mWriter.println(" KEY may be: play, pause, play-pause, mute, headsethook,");
+ mWriter.println(" stop, next, previous, rewind, record, fast-forword.");
+ mWriter.println("media_session list-sessions: print a list of the current sessions.");
+ mWriter.println("media_session monitor: monitor updates to the specified session.");
+ mWriter.println(" Use the tag from list-sessions.");
+ mWriter.println("media_session volume: " + VolumeCtrl.USAGE);
+ mWriter.println();
}
private void sendMediaKey(KeyEvent event) {
@@ -121,7 +123,7 @@ public class Media extends BaseCommand {
}
private void runMonitor() throws Exception {
- String id = nextArgRequired();
+ String id = getNextArgRequired();
if (id == null) {
showError("Error: must include a session id");
return;
@@ -133,7 +135,8 @@ public class Media extends BaseCommand {
for (MediaController controller : controllers) {
try {
if (controller != null && id.equals(controller.getTag())) {
- ControllerMonitor monitor = new ControllerMonitor(controller);
+ MediaShellCommand.ControllerMonitor monitor =
+ new MediaShellCommand.ControllerMonitor(controller);
monitor.run();
success = true;
break;
@@ -143,15 +146,15 @@ public class Media extends BaseCommand {
}
}
} catch (Exception e) {
- System.out.println("***Error monitoring session*** " + e.getMessage());
+ mErrorWriter.println("***Error monitoring session*** " + e.getMessage());
}
if (!success) {
- System.out.println("No session found with id " + id);
+ mErrorWriter.println("No session found with id " + id);
}
}
private void runDispatch() throws Exception {
- String cmd = nextArgRequired();
+ String cmd = getNextArgRequired();
int keycode;
if ("play".equals(cmd)) {
keycode = KeyEvent.KEYCODE_MEDIA_PLAY;
@@ -186,68 +189,73 @@ public class Media extends BaseCommand {
KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, InputDevice.SOURCE_KEYBOARD));
}
+ void showError(String errMsg) {
+ onHelp();
+ mErrorWriter.println(errMsg);
+ }
+
class ControllerCallback extends MediaController.Callback {
@Override
public void onSessionDestroyed() {
- System.out.println("onSessionDestroyed. Enter q to quit.");
+ mWriter.println("onSessionDestroyed. Enter q to quit.");
}
@Override
public void onSessionEvent(String event, Bundle extras) {
- System.out.println("onSessionEvent event=" + event + ", extras=" + extras);
+ mWriter.println("onSessionEvent event=" + event + ", extras=" + extras);
}
@Override
public void onPlaybackStateChanged(PlaybackState state) {
- System.out.println("onPlaybackStateChanged " + state);
+ mWriter.println("onPlaybackStateChanged " + state);
}
@Override
public void onMetadataChanged(MediaMetadata metadata) {
String mmString = metadata == null ? null : "title=" + metadata
.getDescription();
- System.out.println("onMetadataChanged " + mmString);
+ mWriter.println("onMetadataChanged " + mmString);
}
@Override
- public void onQueueChanged(List<QueueItem> queue) {
- System.out.println("onQueueChanged, "
+ public void onQueueChanged(List<MediaSession.QueueItem> queue) {
+ mWriter.println("onQueueChanged, "
+ (queue == null ? "null queue" : " size=" + queue.size()));
}
@Override
public void onQueueTitleChanged(CharSequence title) {
- System.out.println("onQueueTitleChange " + title);
+ mWriter.println("onQueueTitleChange " + title);
}
@Override
public void onExtrasChanged(Bundle extras) {
- System.out.println("onExtrasChanged " + extras);
+ mWriter.println("onExtrasChanged " + extras);
}
@Override
- public void onAudioInfoChanged(PlaybackInfo info) {
- System.out.println("onAudioInfoChanged " + info);
+ public void onAudioInfoChanged(MediaController.PlaybackInfo info) {
+ mWriter.println("onAudioInfoChanged " + info);
}
}
private class ControllerMonitor {
private final MediaController mController;
- private final ControllerCallback mControllerCallback;
+ private final MediaShellCommand.ControllerCallback mControllerCallback;
ControllerMonitor(MediaController controller) {
mController = controller;
- mControllerCallback = new ControllerCallback();
+ mControllerCallback = new MediaShellCommand.ControllerCallback();
}
void printUsageMessage() {
try {
- System.out.println("V2Monitoring session " + mController.getTag()
+ mWriter.println("V2Monitoring session " + mController.getTag()
+ "... available commands: play, pause, next, previous");
} catch (RuntimeException e) {
- System.out.println("Error trying to monitor session!");
+ mWriter.println("Error trying to monitor session!");
}
- System.out.println("(q)uit: finish monitoring");
+ mWriter.println("(q)uit: finish monitoring");
}
void run() throws RemoteException {
@@ -258,7 +266,7 @@ public class Media extends BaseCommand {
try {
mController.registerCallback(mControllerCallback);
} catch (RuntimeException e) {
- System.out.println("Error registering monitor callback");
+ mErrorWriter.println("Error registering monitor callback");
}
}
};
@@ -284,7 +292,7 @@ public class Media extends BaseCommand {
} else if ("previous".equals(line)) {
dispatchKeyCode(KeyEvent.KEYCODE_MEDIA_PREVIOUS);
} else {
- System.out.println("Invalid command: " + line);
+ mErrorWriter.println("Invalid command: " + line);
}
synchronized (this) {
@@ -316,19 +324,19 @@ public class Media extends BaseCommand {
mController.dispatchMediaButtonEvent(down);
mController.dispatchMediaButtonEvent(up);
} catch (RuntimeException e) {
- System.out.println("Failed to dispatch " + keyCode);
+ mErrorWriter.println("Failed to dispatch " + keyCode);
}
}
}
private void runListSessions() {
- System.out.println("Sessions:");
+ mWriter.println("Sessions:");
try {
List<MediaController> controllers = sMediaSessionManager.getActiveSessions(null);
for (MediaController controller : controllers) {
if (controller != null) {
try {
- System.out.println(" tag=" + controller.getTag()
+ mWriter.println(" tag=" + controller.getTag()
+ ", package=" + controller.getPackageName());
} catch (RuntimeException e) {
// ignore
@@ -336,7 +344,7 @@ public class Media extends BaseCommand {
}
}
} catch (Exception e) {
- System.out.println("***Error listing sessions***");
+ mErrorWriter.println("***Error listing sessions***");
}
}
diff --git a/cmds/media/src/com/android/commands/media/VolumeCtrl.java b/services/core/java/com/android/server/media/VolumeCtrl.java
index 1629c6f178f0..7a2666566ea2 100755..100644
--- a/cmds/media/src/com/android/commands/media/VolumeCtrl.java
+++ b/services/core/java/com/android/server/media/VolumeCtrl.java
@@ -1,21 +1,20 @@
/*
-**
-** Copyright 2016, 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 com.android.commands.media;
+ * Copyright (C) 2019 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 com.android.server.media;
import android.content.Context;
import android.media.AudioManager;
@@ -26,45 +25,41 @@ import android.util.AndroidException;
import com.android.internal.os.BaseCommand;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.PrintStream;
-import java.lang.ArrayIndexOutOfBoundsException;
-
/**
* Command line tool to exercise AudioService.setStreamVolume()
* and AudioService.adjustStreamVolume()
*/
public class VolumeCtrl {
- private final static String TAG = "VolumeCtrl";
+ private static final String TAG = "VolumeCtrl";
// --stream affects --set, --adj or --get options.
// --show affects --set and --adj options.
// --get can be used with --set, --adj or by itself.
- public final static String USAGE = new String(
- "the options are as follows: \n" +
- "\t\t--stream STREAM selects the stream to control, see AudioManager.STREAM_*\n" +
- "\t\t controls AudioManager.STREAM_MUSIC if no stream is specified\n"+
- "\t\t--set INDEX sets the volume index value\n" +
- "\t\t--adj DIRECTION adjusts the volume, use raise|same|lower for the direction\n" +
- "\t\t--get outputs the current volume\n" +
- "\t\t--show shows the UI during the volume change\n" +
- "\texamples:\n" +
- "\t\tadb shell media volume --show --stream 3 --set 11\n" +
- "\t\tadb shell media volume --stream 0 --adj lower\n" +
- "\t\tadb shell media volume --stream 3 --get\n"
- );
-
- private final static int VOLUME_CONTROL_MODE_SET = 1;
- private final static int VOLUME_CONTROL_MODE_ADJUST = 2;
-
- private final static String ADJUST_LOWER = "lower";
- private final static String ADJUST_SAME = "same";
- private final static String ADJUST_RAISE = "raise";
-
- public static void run(BaseCommand cmd) throws Exception {
+ public static final String USAGE = new String("the options are as follows: \n"
+ + "\t\t--stream STREAM selects the stream to control, see AudioManager.STREAM_*\n"
+ + "\t\t controls AudioManager.STREAM_MUSIC if no stream is specified\n"
+ + "\t\t--set INDEX sets the volume index value\n"
+ + "\t\t--adj DIRECTION adjusts the volume, use raise|same|lower for the direction\n"
+ + "\t\t--get outputs the current volume\n"
+ + "\t\t--show shows the UI during the volume change\n"
+ + "\texamples:\n"
+ + "\t\tadb shell media volume --show --stream 3 --set 11\n"
+ + "\t\tadb shell media volume --stream 0 --adj lower\n"
+ + "\t\tadb shell media volume --stream 3 --get\n"
+ );
+
+ private static final int VOLUME_CONTROL_MODE_SET = 1;
+ private static final int VOLUME_CONTROL_MODE_ADJUST = 2;
+
+ private static final String ADJUST_LOWER = "lower";
+ private static final String ADJUST_SAME = "same";
+ private static final String ADJUST_RAISE = "raise";
+
+ /**
+ * Runs a given MediaShellCommand
+ */
+ public static void run(MediaShellCommand cmd) throws Exception {
//----------------------------------------
// Default parameters
int stream = AudioManager.STREAM_MUSIC;
@@ -78,7 +73,7 @@ public class VolumeCtrl {
// read options
String option;
String adjustment = null;
- while ((option = cmd.nextOption()) != null) {
+ while ((option = cmd.getNextOption()) != null) {
switch (option) {
case "--show":
showUi = true;
@@ -88,17 +83,17 @@ public class VolumeCtrl {
log(LOG_V, "will get volume");
break;
case "--stream":
- stream = Integer.decode(cmd.nextArgRequired()).intValue();
+ stream = Integer.decode(cmd.getNextArgRequired()).intValue();
log(LOG_V, "will control stream=" + stream + " (" + streamName(stream) + ")");
break;
case "--set":
- volIndex = Integer.decode(cmd.nextArgRequired()).intValue();
+ volIndex = Integer.decode(cmd.getNextArgRequired()).intValue();
mode = VOLUME_CONTROL_MODE_SET;
log(LOG_V, "will set volume to index=" + volIndex);
break;
case "--adj":
mode = VOLUME_CONTROL_MODE_ADJUST;
- adjustment = cmd.nextArgRequired();
+ adjustment = cmd.getNextArgRequired();
log(LOG_V, "will adjust volume");
break;
default:
@@ -140,7 +135,7 @@ public class VolumeCtrl {
if ((volIndex > audioService.getStreamMaxVolume(stream))
|| (volIndex < audioService.getStreamMinVolume(stream))) {
cmd.showError(String.format("Error: invalid volume index %d for stream %d "
- + "(should be in [%d..%d])", volIndex, stream,
+ + "(should be in [%d..%d])", volIndex, stream,
audioService.getStreamMinVolume(stream),
audioService.getStreamMaxVolume(stream)));
return;
@@ -149,7 +144,7 @@ public class VolumeCtrl {
//----------------------------------------
// Non-interactive test
- final int flag = showUi? AudioManager.FLAG_SHOW_UI : 0;
+ final int flag = showUi ? AudioManager.FLAG_SHOW_UI : 0;
final String pack = cmd.getClass().getPackage().getName();
if (mode == VOLUME_CONTROL_MODE_SET) {
audioService.setStreamVolume(stream, volIndex, flag, pack/*callingPackage*/);
@@ -157,9 +152,9 @@ public class VolumeCtrl {
audioService.adjustStreamVolume(stream, adjDir, flag, pack);
}
if (doGet) {
- log(LOG_V, "volume is " + audioService.getStreamVolume(stream) +
- " in range [" + audioService.getStreamMinVolume(stream) +
- ".." + audioService.getStreamMaxVolume(stream) + "]");
+ log(LOG_V, "volume is " + audioService.getStreamVolume(stream)
+ + " in range [" + audioService.getStreamMinVolume(stream)
+ + ".." + audioService.getStreamMaxVolume(stream) + "]");
}
}
@@ -181,5 +176,4 @@ public class VolumeCtrl {
return "invalid stream";
}
}
-
}
diff --git a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
index 82d74bc197b7..83d0ecd33fbc 100644
--- a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
+++ b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
@@ -1032,6 +1032,7 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
// READ_NETWORK_USAGE_HISTORY permission above.
synchronized (mNetworkPoliciesSecondLock) {
+ updateNetworkRulesNL();
updateNetworkEnabledNL();
updateNotificationsNL();
}
diff --git a/services/core/java/com/android/server/net/NetworkStatsService.java b/services/core/java/com/android/server/net/NetworkStatsService.java
index 673e8302a426..0288f0c5e3cf 100644
--- a/services/core/java/com/android/server/net/NetworkStatsService.java
+++ b/services/core/java/com/android/server/net/NetworkStatsService.java
@@ -873,6 +873,8 @@ public class NetworkStatsService extends INetworkStatsService.Stub {
+ mPersistThreshold);
}
+ final long oldGlobalAlertBytes = mGlobalAlertBytes;
+
// update and persist if beyond new thresholds
final long currentTime = mClock.millis();
synchronized (mStatsLock) {
@@ -886,8 +888,9 @@ public class NetworkStatsService extends INetworkStatsService.Stub {
mUidTagRecorder.maybePersistLocked(currentTime);
}
- // re-arm global alert
- registerGlobalAlert();
+ if (oldGlobalAlertBytes != mGlobalAlertBytes) {
+ registerGlobalAlert();
+ }
}
@Override
diff --git a/services/core/java/com/android/server/notification/NotificationComparator.java b/services/core/java/com/android/server/notification/NotificationComparator.java
index bc051547a53f..a7e40cbc5b66 100644
--- a/services/core/java/com/android/server/notification/NotificationComparator.java
+++ b/services/core/java/com/android/server/notification/NotificationComparator.java
@@ -23,7 +23,6 @@ import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
-import android.provider.Settings;
import android.telecom.TelecomManager;
import com.android.internal.util.NotificationMessagingUtil;
@@ -55,14 +54,15 @@ public class NotificationComparator
final boolean isLeftHighImportance = leftImportance >= IMPORTANCE_DEFAULT;
final boolean isRightHighImportance = rightImportance >= IMPORTANCE_DEFAULT;
- // With new interruption model, prefer importance bucket above all other criteria
- // (to ensure buckets are contiguous)
- if (Settings.Secure.getInt(mContext.getContentResolver(),
- Settings.Secure.NOTIFICATION_NEW_INTERRUPTION_MODEL, 1) == 1) {
- if (isLeftHighImportance != isRightHighImportance) {
- // by importance bucket, high importance higher than low importance
- return -1 * Boolean.compare(isLeftHighImportance, isRightHighImportance);
- }
+ if (isLeftHighImportance != isRightHighImportance) {
+ // by importance bucket, high importance higher than low importance
+ return -1 * Boolean.compare(isLeftHighImportance, isRightHighImportance);
+ }
+
+ // If a score has been assigned by notification assistant service, use this service
+ // rank results within each bucket instead of this comparator implementation.
+ if (left.getRankingScore() != right.getRankingScore()) {
+ return -1 * Float.compare(left.getRankingScore(), right.getRankingScore());
}
// first all colorized notifications
diff --git a/services/core/java/com/android/server/notification/NotificationRecord.java b/services/core/java/com/android/server/notification/NotificationRecord.java
index b57bfa06d579..c8afcc97d5b1 100644
--- a/services/core/java/com/android/server/notification/NotificationRecord.java
+++ b/services/core/java/com/android/server/notification/NotificationRecord.java
@@ -144,6 +144,7 @@ public final class NotificationRecord {
private int mSystemImportance = IMPORTANCE_UNSPECIFIED;
private int mAssistantImportance = IMPORTANCE_UNSPECIFIED;
private int mImportance = IMPORTANCE_UNSPECIFIED;
+ private float mRankingScore = 0f;
// Field used in global sort key to bypass normal notifications
private int mCriticality = CriticalNotificationExtractor.NORMAL;
// A MetricsEvent.NotificationImportanceExplanation, tracking source of mImportance.
@@ -655,6 +656,9 @@ public final class NotificationRecord {
importance = Math.min(IMPORTANCE_HIGH, importance);
setAssistantImportance(importance);
}
+ if (signals.containsKey(Adjustment.KEY_RANKING_SCORE)) {
+ mRankingScore = signals.getFloat(Adjustment.KEY_RANKING_SCORE);
+ }
if (!signals.isEmpty() && adjustment.getIssuer() != null) {
mAdjustmentIssuer = adjustment.getIssuer();
}
@@ -772,6 +776,10 @@ public final class NotificationRecord {
return mImportance;
}
+ public float getRankingScore() {
+ return mRankingScore;
+ }
+
public CharSequence getImportanceExplanation() {
switch (mImportanceExplanationCode) {
case MetricsEvent.IMPORTANCE_EXPLANATION_UNKNOWN:
@@ -1289,6 +1297,18 @@ public final class NotificationRecord {
return getLogMaker().setCategory(MetricsEvent.NOTIFICATION_ITEM);
}
+ public boolean hasUndecoratedRemoteView() {
+ Notification notification = getNotification();
+ Class<? extends Notification.Style> style = notification.getNotificationStyle();
+ boolean hasDecoratedStyle = style != null
+ && (Notification.DecoratedCustomViewStyle.class.equals(style)
+ || Notification.DecoratedMediaCustomViewStyle.class.equals(style));
+ boolean hasCustomRemoteView = notification.contentView != null
+ || notification.bigContentView != null
+ || notification.headsUpContentView != null;
+ return hasCustomRemoteView && !hasDecoratedStyle;
+ }
+
@VisibleForTesting
static final class Light {
public final int color;
diff --git a/services/core/java/com/android/server/notification/NotificationUsageStats.java b/services/core/java/com/android/server/notification/NotificationUsageStats.java
index ac8d1a9a9ad4..d1fe0d9351cb 100644
--- a/services/core/java/com/android/server/notification/NotificationUsageStats.java
+++ b/services/core/java/com/android/server/notification/NotificationUsageStats.java
@@ -149,7 +149,7 @@ public class NotificationUsageStats {
stats.numPostedByApp++;
stats.updateInterarrivalEstimate(now);
stats.countApiUse(notification);
- stats.numUndecoratedRemoteViews += (isUndecoratedRemoteView(notification) ? 1 : 0);
+ stats.numUndecoratedRemoteViews += (notification.hasUndecoratedRemoteView() ? 1 : 0);
}
releaseAggregatedStatsLocked(aggregatedStatsArray);
if (ENABLE_SQLITE_LOG) {
@@ -158,13 +158,6 @@ public class NotificationUsageStats {
}
/**
- * Does this notification use RemoveViews without a platform decoration?
- */
- protected static boolean isUndecoratedRemoteView(NotificationRecord notification) {
- return (notification.getNotification().getNotificationStyle() == null);
- }
-
- /**
* Called when a notification has been updated.
*/
public synchronized void registerUpdatedByApp(NotificationRecord notification,
@@ -1303,7 +1296,7 @@ public class NotificationUsageStats {
} else {
putPosttimeVisibility(r, cv);
}
- cv.put(COL_UNDECORATED, (isUndecoratedRemoteView(r) ? 1 : 0));
+ cv.put(COL_UNDECORATED, (r.hasUndecoratedRemoteView() ? 1 : 0));
SQLiteDatabase db = mHelper.getWritableDatabase();
if (db.insert(TAB_LOG, null, cv) < 0) {
Log.wtf(TAG, "Error while trying to insert values: " + cv);
diff --git a/tests/utils/testutils/java/test/package-info.java b/services/core/java/com/android/server/package-info.java
index c34d7b21ab84..dd94edd53c70 100644
--- a/tests/utils/testutils/java/test/package-info.java
+++ b/services/core/java/com/android/server/package-info.java
@@ -15,7 +15,8 @@
*/
/**
- * This package separated from android. because placing classes under android.'s .test/.util
- * may be confused with tests for that actual android subpackage.
- **/
-package test;
+ * @hide
+ * TODO(b/146466118) remove this javadoc tag
+ */
+@android.annotation.Hide
+package com.android.server;
diff --git a/services/core/java/com/android/server/pm/ApexManager.java b/services/core/java/com/android/server/pm/ApexManager.java
index 2b4b409f329a..5ae8c5881cb1 100644
--- a/services/core/java/com/android/server/pm/ApexManager.java
+++ b/services/core/java/com/android/server/pm/ApexManager.java
@@ -17,11 +17,11 @@
package com.android.server.pm;
import android.annotation.IntDef;
-import android.annotation.NonNull;
import android.annotation.Nullable;
import android.apex.ApexInfo;
import android.apex.ApexInfoList;
import android.apex.ApexSessionInfo;
+import android.apex.ApexSessionParams;
import android.apex.IApexService;
import android.content.BroadcastReceiver;
import android.content.Context;
@@ -176,13 +176,9 @@ abstract class ApexManager {
* enough for it to be activated at the next boot, the caller needs to call
* {@link #markStagedSessionReady(int)}.
*
- * @param sessionId the identifier of the {@link PackageInstallerSession} being submitted.
- * @param childSessionIds if {@code sessionId} is a multi-package session, this should contain
- * an array of identifiers of all the child sessions. Otherwise it should
- * be an empty array.
* @throws PackageManagerException if call to apexd fails
*/
- abstract ApexInfoList submitStagedSession(int sessionId, @NonNull int[] childSessionIds)
+ abstract ApexInfoList submitStagedSession(ApexSessionParams params)
throws PackageManagerException;
/**
@@ -450,11 +446,10 @@ abstract class ApexManager {
}
@Override
- ApexInfoList submitStagedSession(int sessionId, @NonNull int[] childSessionIds)
- throws PackageManagerException {
+ ApexInfoList submitStagedSession(ApexSessionParams params) throws PackageManagerException {
try {
final ApexInfoList apexInfoList = new ApexInfoList();
- mApexService.submitStagedSession(sessionId, childSessionIds, apexInfoList);
+ mApexService.submitStagedSession(params, apexInfoList);
return apexInfoList;
} catch (RemoteException re) {
Slog.e(TAG, "Unable to contact apexservice", re);
@@ -686,7 +681,7 @@ abstract class ApexManager {
}
@Override
- ApexInfoList submitStagedSession(int sessionId, int[] childSessionIds)
+ ApexInfoList submitStagedSession(ApexSessionParams params)
throws PackageManagerException {
throw new PackageManagerException(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
"Device doesn't support updating APEX");
diff --git a/services/core/java/com/android/server/pm/ComponentResolver.java b/services/core/java/com/android/server/pm/ComponentResolver.java
index f2a2e65f733b..13bd7e59de73 100644
--- a/services/core/java/com/android/server/pm/ComponentResolver.java
+++ b/services/core/java/com/android/server/pm/ComponentResolver.java
@@ -627,11 +627,13 @@ public class ComponentResolver {
final int providersSize = ArrayUtils.size(pkg.getProviders());
StringBuilder r = null;
for (int i = 0; i < providersSize; i++) {
- EffectiveProvider p = new EffectiveProvider(pkg.getProviders().get(i));
+ ParsedProvider p = pkg.getProviders().get(i);
mProviders.addProvider(p);
if (p.getAuthority() != null) {
String[] names = p.getAuthority().split(";");
- p.setEffectiveAuthority(null);
+
+ // TODO(b/135203078): Remove this mutation
+ p.setAuthority(null);
for (int j = 0; j < names.length; j++) {
if (j == 1 && p.isSyncable()) {
// We only want the first authority for a provider to possibly be
@@ -641,15 +643,15 @@ public class ComponentResolver {
// to a provider that we don't want to change.
// Only do this for the second authority since the resulting provider
// object can be the same for all future authorities for this provider.
- p = new EffectiveProvider(p);
- p.setEffectiveSyncable(false);
+ p = new ParsedProvider(p);
+ p.setSyncable(false);
}
if (!mProvidersByAuthority.containsKey(names[j])) {
mProvidersByAuthority.put(names[j], p);
if (p.getAuthority() == null) {
- p.setEffectiveAuthority(names[j]);
+ p.setAuthority(names[j]);
} else {
- p.setEffectiveAuthority(p.getAuthority() + ";" + names[j]);
+ p.setAuthority(p.getAuthority() + ";" + names[j]);
}
if (DEBUG_PACKAGE_SCANNING && chatty) {
Log.d(TAG, "Registered content provider: " + names[j]
@@ -2113,35 +2115,4 @@ public class ComponentResolver {
return info.authoritiesIterator();
}
}
-
- // TODO(b/135203078): Document or remove this if possible.
- class EffectiveProvider extends ParsedProvider {
-
- private String mEffectiveAuthority;
- private boolean mEffectiveSyncable;
-
- public EffectiveProvider(ParsedProvider parsedProvider) {
- this.setFrom(parsedProvider);
- this.mEffectiveAuthority = parsedProvider.getAuthority();
- this.mEffectiveSyncable = parsedProvider.isSyncable();
- }
-
- public void setEffectiveAuthority(String authority) {
- this.mEffectiveAuthority = authority;
- }
-
- public void setEffectiveSyncable(boolean syncable) {
- this.mEffectiveSyncable = syncable;
- }
-
- @Override
- public String getAuthority() {
- return mEffectiveAuthority;
- }
-
- @Override
- public boolean isSyncable() {
- return mEffectiveSyncable;
- }
- }
}
diff --git a/services/core/java/com/android/server/pm/Installer.java b/services/core/java/com/android/server/pm/Installer.java
index 26cd42daa9f8..f962eedb5111 100644
--- a/services/core/java/com/android/server/pm/Installer.java
+++ b/services/core/java/com/android/server/pm/Installer.java
@@ -28,6 +28,7 @@ import android.os.IBinder.DeathRecipient;
import android.os.IInstalld;
import android.os.RemoteException;
import android.os.ServiceManager;
+import android.os.storage.CrateMetadata;
import android.text.format.DateUtils;
import android.util.Slog;
@@ -293,6 +294,43 @@ public class Installer extends SystemService {
}
}
+ /**
+ * To get all of the CrateMetadata of the crates for the specified user app by the installd.
+ *
+ * @param uuid the UUID
+ * @param packageNames the application package names
+ * @param userId the user id
+ * @return the array of CrateMetadata
+ */
+ @Nullable
+ public CrateMetadata[] getAppCrates(@NonNull String uuid, @NonNull String[] packageNames,
+ @UserIdInt int userId) throws InstallerException {
+ if (!checkBeforeRemote()) return null;
+ try {
+ return mInstalld.getAppCrates(uuid, packageNames, userId);
+ } catch (Exception e) {
+ throw InstallerException.from(e);
+ }
+ }
+
+ /**
+ * To retrieve all of the CrateMetadata of the crate for the specified user app by the installd.
+ *
+ * @param uuid the UUID
+ * @param userId the user id
+ * @return the array of CrateMetadata
+ */
+ @Nullable
+ public CrateMetadata[] getUserCrates(String uuid, @UserIdInt int userId)
+ throws InstallerException {
+ if (!checkBeforeRemote()) return null;
+ try {
+ return mInstalld.getUserCrates(uuid, userId);
+ } catch (Exception e) {
+ throw InstallerException.from(e);
+ }
+ }
+
public void setAppQuota(String uuid, int userId, int appId, long cacheQuota)
throws InstallerException {
if (!checkBeforeRemote()) return;
@@ -580,6 +618,30 @@ public class Installer extends SystemService {
}
}
+ /**
+ * Bind mount private volume CE and DE mirror storage.
+ */
+ public void onPrivateVolumeMounted(String volumeUuid) throws InstallerException {
+ if (!checkBeforeRemote()) return;
+ try {
+ mInstalld.onPrivateVolumeMounted(volumeUuid);
+ } catch (Exception e) {
+ throw InstallerException.from(e);
+ }
+ }
+
+ /**
+ * Unmount private volume CE and DE mirror storage.
+ */
+ public void onPrivateVolumeRemoved(String volumeUuid) throws InstallerException {
+ if (!checkBeforeRemote()) return;
+ try {
+ mInstalld.onPrivateVolumeRemoved(volumeUuid);
+ } catch (Exception e) {
+ throw InstallerException.from(e);
+ }
+ }
+
public boolean prepareAppProfile(String pkg, @UserIdInt int userId, @AppIdInt int appId,
String profileName, String codePath, String dexMetadataPath) throws InstallerException {
if (!checkBeforeRemote()) return false;
diff --git a/services/core/java/com/android/server/pm/InstantAppResolver.java b/services/core/java/com/android/server/pm/InstantAppResolver.java
index 30b2c9d21a6a..8333ae5cbbad 100644
--- a/services/core/java/com/android/server/pm/InstantAppResolver.java
+++ b/services/core/java/com/android/server/pm/InstantAppResolver.java
@@ -39,6 +39,7 @@ import android.content.pm.ActivityInfo;
import android.content.pm.AuxiliaryResolveInfo;
import android.content.pm.InstantAppIntentFilter;
import android.content.pm.InstantAppRequest;
+import android.content.pm.InstantAppRequestInfo;
import android.content.pm.InstantAppResolveInfo;
import android.content.pm.InstantAppResolveInfo.InstantAppDigest;
import android.metrics.LogMaker;
@@ -47,6 +48,8 @@ import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
+import android.os.UserHandle;
+import android.text.TextUtils;
import android.util.Log;
import android.util.Slog;
@@ -63,7 +66,6 @@ import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
-import java.util.UUID;
/** @hide */
public abstract class InstantAppResolver {
@@ -117,26 +119,40 @@ public abstract class InstantAppResolver {
return sanitizedIntent;
}
+ /**
+ * Generate an {@link InstantAppDigest} from an {@link Intent} which contains hashes of the
+ * host. The object contains both secure and insecure hash array variants, and the secure
+ * version must be passed along to ensure the random data is consistent.
+ */
+ @NonNull
+ public static InstantAppDigest parseDigest(@NonNull Intent origIntent) {
+ if (origIntent.getData() != null && !TextUtils.isEmpty(origIntent.getData().getHost())) {
+ return new InstantAppResolveInfo.InstantAppDigest(origIntent.getData().getHost(),
+ 5 /*maxDigests*/);
+ } else {
+ return InstantAppResolveInfo.InstantAppDigest.UNDEFINED;
+ }
+ }
+
public static AuxiliaryResolveInfo doInstantAppResolutionPhaseOne(
InstantAppResolverConnection connection, InstantAppRequest requestObj) {
final long startTime = System.currentTimeMillis();
- final String token = UUID.randomUUID().toString();
+ final String token = requestObj.token;
if (DEBUG_INSTANT) {
Log.d(TAG, "[" + token + "] Phase1; resolving");
}
- final Intent origIntent = requestObj.origIntent;
- final Intent sanitizedIntent = sanitizeIntent(origIntent);
AuxiliaryResolveInfo resolveInfo = null;
@ResolutionStatus int resolutionStatus = RESOLUTION_SUCCESS;
+ Intent origIntent = requestObj.origIntent;
try {
final List<InstantAppResolveInfo> instantAppResolveInfoList =
- connection.getInstantAppResolveInfoList(sanitizedIntent,
- requestObj.digest.getDigestPrefixSecure(), requestObj.userId, token);
+ connection.getInstantAppResolveInfoList(buildRequestInfo(requestObj));
if (instantAppResolveInfoList != null && instantAppResolveInfoList.size() > 0) {
resolveInfo = InstantAppResolver.filterInstantAppIntent(
instantAppResolveInfoList, origIntent, requestObj.resolvedType,
- requestObj.userId, origIntent.getPackage(), requestObj.digest, token);
+ requestObj.userId, origIntent.getPackage(), token,
+ requestObj.hostDigestPrefixSecure);
}
} catch (ConnectionException e) {
if (e.failure == ConnectionException.FAILURE_BIND) {
@@ -166,7 +182,7 @@ public abstract class InstantAppResolver {
// if the match external flag is set, return an empty resolve info instead of a null result.
if (resolveInfo == null && (origIntent.getFlags() & FLAG_ACTIVITY_MATCH_EXTERNAL) != 0) {
return new AuxiliaryResolveInfo(token, false, createFailureIntent(origIntent, token),
- null /* filters */);
+ null /* filters */, requestObj.hostDigestPrefixSecure);
}
return resolveInfo;
}
@@ -175,7 +191,7 @@ public abstract class InstantAppResolver {
InstantAppResolverConnection connection, InstantAppRequest requestObj,
ActivityInfo instantAppInstaller, Handler callbackHandler) {
final long startTime = System.currentTimeMillis();
- final String token = requestObj.responseObj.token;
+ final String token = requestObj.token;
if (DEBUG_INSTANT) {
Log.d(TAG, "[" + token + "] Phase2; resolving");
}
@@ -191,8 +207,8 @@ public abstract class InstantAppResolver {
final AuxiliaryResolveInfo instantAppIntentInfo =
InstantAppResolver.filterInstantAppIntent(
instantAppResolveInfoList, origIntent, null /*resolvedType*/,
- 0 /*userId*/, origIntent.getPackage(), requestObj.digest,
- token);
+ 0 /*userId*/, origIntent.getPackage(),
+ token, requestObj.hostDigestPrefixSecure);
if (instantAppIntentInfo != null) {
failureIntent = instantAppIntentInfo.failureIntent;
} else {
@@ -223,8 +239,7 @@ public abstract class InstantAppResolver {
}
};
try {
- connection.getInstantAppIntentFilterList(sanitizedIntent,
- requestObj.digest.getDigestPrefixSecure(), requestObj.userId, token, callback,
+ connection.getInstantAppIntentFilterList(buildRequestInfo(requestObj), callback,
callbackHandler, startTime);
} catch (ConnectionException e) {
@ResolutionStatus int resolutionStatus = RESOLUTION_FAILURE;
@@ -356,10 +371,22 @@ public abstract class InstantAppResolver {
return intent;
}
+ private static InstantAppRequestInfo buildRequestInfo(InstantAppRequest request) {
+ return new InstantAppRequestInfo(
+ sanitizeIntent(request.origIntent),
+ // This must only expose the secured version of the host
+ request.hostDigestPrefixSecure,
+ UserHandle.getUserHandleForUid(request.userId),
+ request.isRequesterInstantApp,
+ request.token
+ );
+ }
+
private static AuxiliaryResolveInfo filterInstantAppIntent(
- List<InstantAppResolveInfo> instantAppResolveInfoList,
- Intent origIntent, String resolvedType, int userId, String packageName,
- InstantAppDigest digest, String token) {
+ List<InstantAppResolveInfo> instantAppResolveInfoList, Intent origIntent,
+ String resolvedType, int userId, String packageName, String token,
+ int[] hostDigestPrefixSecure) {
+ InstantAppDigest digest = InstantAppResolver.parseDigest(origIntent);
final int[] shaPrefix = digest.getDigestPrefix();
final byte[][] digestBytes = digest.getDigestBytes();
boolean requiresSecondPhase = false;
@@ -404,7 +431,7 @@ public abstract class InstantAppResolver {
}
if (filters != null && !filters.isEmpty()) {
return new AuxiliaryResolveInfo(token, requiresSecondPhase,
- createFailureIntent(origIntent, token), filters);
+ createFailureIntent(origIntent, token), filters, hostDigestPrefixSecure);
}
// Hash or filter mis-match; no instant apps for this domain.
return null;
diff --git a/services/core/java/com/android/server/pm/InstantAppResolverConnection.java b/services/core/java/com/android/server/pm/InstantAppResolverConnection.java
index c0e9f58f3b8e..0fe2eb1e6f4b 100644
--- a/services/core/java/com/android/server/pm/InstantAppResolverConnection.java
+++ b/services/core/java/com/android/server/pm/InstantAppResolverConnection.java
@@ -24,6 +24,7 @@ import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
+import android.content.pm.InstantAppRequestInfo;
import android.content.pm.InstantAppResolveInfo;
import android.os.Binder;
import android.os.Build;
@@ -85,13 +86,13 @@ final class InstantAppResolverConnection implements DeathRecipient {
mBgHandler = BackgroundThread.getHandler();
}
- public List<InstantAppResolveInfo> getInstantAppResolveInfoList(Intent sanitizedIntent,
- int[] hashPrefix, int userId, String token) throws ConnectionException {
+ public List<InstantAppResolveInfo> getInstantAppResolveInfoList(InstantAppRequestInfo request)
+ throws ConnectionException {
throwIfCalledOnMainThread();
IInstantAppResolver target = null;
try {
try {
- target = getRemoteInstanceLazy(token);
+ target = getRemoteInstanceLazy(request.token);
} catch (TimeoutException e) {
throw new ConnectionException(ConnectionException.FAILURE_BIND);
} catch (InterruptedException e) {
@@ -99,8 +100,7 @@ final class InstantAppResolverConnection implements DeathRecipient {
}
try {
return mGetInstantAppResolveInfoCaller
- .getInstantAppResolveInfoList(target, sanitizedIntent, hashPrefix, userId,
- token);
+ .getInstantAppResolveInfoList(target, request);
} catch (TimeoutException e) {
throw new ConnectionException(ConnectionException.FAILURE_CALL);
} catch (RemoteException ignore) {
@@ -113,8 +113,8 @@ final class InstantAppResolverConnection implements DeathRecipient {
return null;
}
- public void getInstantAppIntentFilterList(Intent sanitizedIntent, int[] hashPrefix, int userId,
- String token, PhaseTwoCallback callback, Handler callbackHandler, final long startTime)
+ public void getInstantAppIntentFilterList(InstantAppRequestInfo request,
+ PhaseTwoCallback callback, Handler callbackHandler, final long startTime)
throws ConnectionException {
final IRemoteCallback remoteCallback = new IRemoteCallback.Stub() {
@Override
@@ -126,9 +126,8 @@ final class InstantAppResolverConnection implements DeathRecipient {
}
};
try {
- getRemoteInstanceLazy(token)
- .getInstantAppIntentFilterList(sanitizedIntent, hashPrefix, userId, token,
- remoteCallback);
+ getRemoteInstanceLazy(request.token)
+ .getInstantAppIntentFilterList(request, remoteCallback);
} catch (TimeoutException e) {
throw new ConnectionException(ConnectionException.FAILURE_BIND);
} catch (InterruptedException e) {
@@ -352,12 +351,10 @@ final class InstantAppResolverConnection implements DeathRecipient {
};
}
- public List<InstantAppResolveInfo> getInstantAppResolveInfoList(
- IInstantAppResolver target, Intent sanitizedIntent, int[] hashPrefix, int userId,
- String token) throws RemoteException, TimeoutException {
+ public List<InstantAppResolveInfo> getInstantAppResolveInfoList(IInstantAppResolver target,
+ InstantAppRequestInfo request) throws RemoteException, TimeoutException {
final int sequence = onBeforeRemoteCall();
- target.getInstantAppResolveInfoList(sanitizedIntent, hashPrefix, userId, token,
- sequence, mCallback);
+ target.getInstantAppResolveInfoList(request, sequence, mCallback);
return getResultTimed(sequence);
}
}
diff --git a/services/core/java/com/android/server/pm/PackageInstallerService.java b/services/core/java/com/android/server/pm/PackageInstallerService.java
index dceca0a749e3..a54534b461f1 100644
--- a/services/core/java/com/android/server/pm/PackageInstallerService.java
+++ b/services/core/java/com/android/server/pm/PackageInstallerService.java
@@ -637,7 +637,7 @@ public class PackageInstallerService extends IPackageInstaller.Stub implements
session = new PackageInstallerSession(mInternalCallback, mContext, mPm, this,
mInstallThread.getLooper(), mStagingManager, sessionId, userId, callingUid,
installSource, params, createdMillis,
- stageDir, stageCid, false, false, false, null, SessionInfo.INVALID_ID,
+ stageDir, stageCid, null, false, false, false, null, SessionInfo.INVALID_ID,
false, false, false, SessionInfo.STAGED_SESSION_NO_ERROR, "");
synchronized (mSessions) {
@@ -1014,12 +1014,28 @@ public class PackageInstallerService extends IPackageInstaller.Stub implements
}
}
+ static void sendPendingStreaming(Context context, IntentSender target, int sessionId,
+ Throwable cause) {
+ final Intent intent = new Intent();
+ intent.putExtra(PackageInstaller.EXTRA_SESSION_ID, sessionId);
+ intent.putExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_PENDING_STREAMING);
+ if (cause != null && !TextUtils.isEmpty(cause.getMessage())) {
+ intent.putExtra(PackageInstaller.EXTRA_STATUS_MESSAGE,
+ "Staging Image Not Ready [" + cause.getMessage() + "]");
+ } else {
+ intent.putExtra(PackageInstaller.EXTRA_STATUS_MESSAGE, "Staging Image Not Ready");
+ }
+ try {
+ target.sendIntent(context, 0, intent, null, null);
+ } catch (SendIntentException ignored) {
+ }
+ }
+
static void sendOnUserActionRequired(Context context, IntentSender target, int sessionId,
Intent intent) {
final Intent fillIn = new Intent();
fillIn.putExtra(PackageInstaller.EXTRA_SESSION_ID, sessionId);
- fillIn.putExtra(PackageInstaller.EXTRA_STATUS,
- PackageInstaller.STATUS_PENDING_USER_ACTION);
+ fillIn.putExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_PENDING_USER_ACTION);
fillIn.putExtra(Intent.EXTRA_INTENT, intent);
try {
target.sendIntent(context, 0, fillIn, null, null);
diff --git a/services/core/java/com/android/server/pm/PackageInstallerSession.java b/services/core/java/com/android/server/pm/PackageInstallerSession.java
index 518ec5085a5e..0acf7c8080a2 100644
--- a/services/core/java/com/android/server/pm/PackageInstallerSession.java
+++ b/services/core/java/com/android/server/pm/PackageInstallerSession.java
@@ -21,6 +21,7 @@ import static android.content.pm.PackageManager.INSTALL_FAILED_BAD_SIGNATURE;
import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
+import static android.content.pm.PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SPLIT;
import static android.content.pm.PackageParser.APEX_FILE_EXTENSION;
import static android.content.pm.PackageParser.APK_FILE_EXTENSION;
@@ -30,11 +31,13 @@ import static android.system.OsConstants.O_WRONLY;
import static com.android.internal.util.XmlUtils.readBitmapAttribute;
import static com.android.internal.util.XmlUtils.readBooleanAttribute;
+import static com.android.internal.util.XmlUtils.readByteArrayAttribute;
import static com.android.internal.util.XmlUtils.readIntAttribute;
import static com.android.internal.util.XmlUtils.readLongAttribute;
import static com.android.internal.util.XmlUtils.readStringAttribute;
import static com.android.internal.util.XmlUtils.readUriAttribute;
import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
+import static com.android.internal.util.XmlUtils.writeByteArrayAttribute;
import static com.android.internal.util.XmlUtils.writeIntAttribute;
import static com.android.internal.util.XmlUtils.writeLongAttribute;
import static com.android.internal.util.XmlUtils.writeStringAttribute;
@@ -54,6 +57,7 @@ import android.content.IntentSender;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageInstallObserver2;
import android.content.pm.IPackageInstallerSession;
+import android.content.pm.IPackageInstallerSessionFileSystemConnector;
import android.content.pm.InstallationFile;
import android.content.pm.PackageInfo;
import android.content.pm.PackageInstaller;
@@ -123,6 +127,7 @@ import java.io.FileDescriptor;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
@@ -142,6 +147,7 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
/** XML constants used for persisting a session */
static final String TAG_SESSION = "session";
static final String TAG_CHILD_SESSION = "childSession";
+ static final String TAG_SESSION_FILE = "sessionFile";
private static final String TAG_GRANTED_RUNTIME_PERMISSION = "granted-runtime-permission";
private static final String TAG_WHITELISTED_RESTRICTED_PERMISSION =
"whitelisted-restricted-permission";
@@ -183,6 +189,9 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
private static final String ATTR_VOLUME_UUID = "volumeUuid";
private static final String ATTR_NAME = "name";
private static final String ATTR_INSTALL_REASON = "installRason";
+ private static final String ATTR_DATA_LOADER_PACKAGE_NAME = "dataLoaderPackageName";
+ private static final String ATTR_LENGTH_BYTES = "lengthBytes";
+ private static final String ATTR_METADATA = "metadata";
private static final String PROPERTY_NAME_INHERIT_NATIVE = "pi.inherit_native_on_dont_kill";
private static final int[] EMPTY_CHILD_SESSION_ARRAY = {};
@@ -278,6 +287,29 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
@GuardedBy("mLock")
private int mParentSessionId;
+ static class FileInfo {
+ public final String name;
+ public final Long lengthBytes;
+ public final byte[] metadata;
+
+ public static FileInfo added(String name, Long lengthBytes, byte[] metadata) {
+ return new FileInfo(name, lengthBytes, metadata);
+ }
+
+ public static FileInfo removed(String name) {
+ return new FileInfo(name, -1L, null);
+ }
+
+ FileInfo(String name, Long lengthBytes, byte[] metadata) {
+ this.name = name;
+ this.lengthBytes = lengthBytes;
+ this.metadata = metadata;
+ }
+ }
+
+ @GuardedBy("mLock")
+ private ArrayList<FileInfo> mFiles = new ArrayList<>();
+
@GuardedBy("mLock")
private boolean mStagedSessionApplied;
@GuardedBy("mLock")
@@ -313,6 +345,7 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
@GuardedBy("mLock")
private boolean mVerityFound;
+ // TODO(b/146080380): merge file list with Callback installation.
private IncrementalFileStorages mIncrementalFileStorages;
private static final FileFilter sAddedFilter = new FileFilter() {
@@ -344,7 +377,9 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
IntentSender statusReceiver;
switch (msg.what) {
case MSG_SEAL:
- handleSeal((IntentSender) msg.obj);
+ statusReceiver = (IntentSender) msg.obj;
+
+ handleSeal(statusReceiver);
break;
case MSG_COMMIT:
handleCommit();
@@ -378,6 +413,10 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
}
};
+ private boolean isDataLoaderInstallation() {
+ return !TextUtils.isEmpty(params.dataLoaderPackageName);
+ }
+
/**
* @return {@code true} iff the installing is app an device owner or affiliated profile owner.
*/
@@ -435,7 +474,8 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
PackageSessionProvider sessionProvider, Looper looper, StagingManager stagingManager,
int sessionId, int userId, int installerUid, @NonNull InstallSource installSource,
SessionParams params, long createdMillis,
- File stageDir, String stageCid, boolean prepared, boolean committed, boolean sealed,
+ File stageDir, String stageCid, FileInfo[] files, boolean prepared,
+ boolean committed, boolean sealed,
@Nullable int[] childSessionIds, int parentSessionId, boolean isReady,
boolean isFailed, boolean isApplied, int stagedSessionErrorCode,
String stagedSessionErrorMessage) {
@@ -464,6 +504,12 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
}
this.mParentSessionId = parentSessionId;
+ if (files != null) {
+ for (FileInfo file : files) {
+ mFiles.add(file);
+ }
+ }
+
if (!params.isMultiPackage && (stageDir == null) == (stageCid == null)) {
throw new IllegalArgumentException(
"Exactly one of stageDir or stageCid stage must be set");
@@ -592,15 +638,19 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
}
}
+ @GuardedBy("mLock")
+ private void setClientProgressLocked(float progress) {
+ // Always publish first staging movement
+ final boolean forcePublish = (mClientProgress == 0);
+ mClientProgress = progress;
+ computeProgressLocked(forcePublish);
+ }
+
@Override
public void setClientProgress(float progress) {
synchronized (mLock) {
assertCallerIsOwnerOrRootLocked();
-
- // Always publish first staging movement
- final boolean forcePublish = (mClientProgress == 0);
- mClientProgress = progress;
- computeProgressLocked(forcePublish);
+ setClientProgressLocked(progress);
}
}
@@ -608,8 +658,7 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
public void addClientProgress(float progress) {
synchronized (mLock) {
assertCallerIsOwnerOrRootLocked();
-
- setClientProgress(mClientProgress + progress);
+ setClientProgressLocked(mClientProgress + progress);
}
}
@@ -637,7 +686,10 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
@GuardedBy("mLock")
private String[] getNamesLocked() {
- return stageDir.list();
+ if (!isDataLoaderInstallation()) {
+ return stageDir.list();
+ }
+ return mFiles.stream().map(fileInfo -> fileInfo.name).toArray(String[]::new);
}
private static File[] filterFiles(File parent, String[] names, FileFilter filter) {
@@ -659,6 +711,10 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
@Override
public void removeSplit(String splitName) {
+ if (isDataLoaderInstallation()) {
+ throw new IllegalStateException(
+ "Cannot remove splits in a callback installation session.");
+ }
if (TextUtils.isEmpty(params.appPackageName)) {
throw new IllegalStateException("Must specify package name to remove a split");
}
@@ -693,8 +749,31 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
}
}
+ private void assertCanWrite(boolean reverseMode) {
+ if (isDataLoaderInstallation()) {
+ throw new IllegalStateException(
+ "Cannot write regular files in a callback installation session.");
+ }
+ synchronized (mLock) {
+ assertCallerIsOwnerOrRootLocked();
+ assertPreparedAndNotSealedLocked("assertCanWrite");
+ }
+ if (reverseMode) {
+ switch (Binder.getCallingUid()) {
+ case android.os.Process.SHELL_UID:
+ case android.os.Process.ROOT_UID:
+ case android.os.Process.SYSTEM_UID:
+ break;
+ default:
+ throw new SecurityException(
+ "Reverse mode only supported from shell or system");
+ }
+ }
+ }
+
@Override
public ParcelFileDescriptor openWrite(String name, long offsetBytes, long lengthBytes) {
+ assertCanWrite(false);
try {
return doWriteInternal(name, offsetBytes, lengthBytes, null);
} catch (IOException e) {
@@ -705,6 +784,7 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
@Override
public void write(String name, long offsetBytes, long lengthBytes,
ParcelFileDescriptor fd) {
+ assertCanWrite(fd != null);
try {
doWriteInternal(name, offsetBytes, lengthBytes, fd);
} catch (IOException e) {
@@ -720,9 +800,6 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
final RevocableFileDescriptor fd;
final FileBridge bridge;
synchronized (mLock) {
- assertCallerIsOwnerOrRootLocked();
- assertPreparedAndNotSealedLocked("openWrite");
-
if (PackageInstaller.ENABLE_REVOCABLE_FD) {
fd = new RevocableFileDescriptor();
bridge = null;
@@ -765,16 +842,6 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
}
if (incomingFd != null) {
- switch (Binder.getCallingUid()) {
- case android.os.Process.SHELL_UID:
- case android.os.Process.ROOT_UID:
- case android.os.Process.SYSTEM_UID:
- break;
- default:
- throw new SecurityException(
- "Reverse mode only supported from shell or system");
- }
-
// In "reverse" mode, we're streaming data ourselves from the
// incoming FD, which means we never have to hand out our
// sensitive internal FD. We still rely on a "bridge" being
@@ -786,7 +853,10 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
if (params.sizeBytes > 0) {
final long delta = progress - last.value;
last.value = progress;
- addClientProgress((float) delta / (float) params.sizeBytes);
+ synchronized (mLock) {
+ setClientProgressLocked(mClientProgress
+ + (float) delta / (float) params.sizeBytes);
+ }
}
});
} finally {
@@ -821,6 +891,10 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
@Override
public ParcelFileDescriptor openRead(String name) {
+ if (isDataLoaderInstallation()) {
+ throw new IllegalStateException(
+ "Cannot read regular files in a callback installation session.");
+ }
synchronized (mLock) {
assertCallerIsOwnerOrRootLocked();
assertPreparedAndNotCommittedOrDestroyedLocked("openRead");
@@ -926,9 +1000,25 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
return;
}
}
+
mHandler.obtainMessage(MSG_COMMIT).sendToTarget();
}
+ private class FileSystemConnector extends IPackageInstallerSessionFileSystemConnector.Stub {
+ @Override
+ public void writeData(String name, long offsetBytes, long lengthBytes,
+ ParcelFileDescriptor incomingFd) {
+ if (incomingFd == null) {
+ throw new IllegalArgumentException("incomingFd can't be null");
+ }
+ try {
+ doWriteInternal(name, offsetBytes, lengthBytes, incomingFd);
+ } catch (IOException e) {
+ throw ExceptionUtils.wrap(e);
+ }
+ }
+ }
+
private class ChildStatusIntentReceiver {
private final SparseIntArray mChildSessionsRemaining;
private final IntentSender mStatusReceiver;
@@ -988,6 +1078,14 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
}
}
+ /** {@hide} */
+ private class StreamingException extends Exception {
+ StreamingException(Throwable cause) {
+ super(cause);
+ }
+ }
+
+
/**
* Sanity checks to make sure it's ok to commit the session.
*/
@@ -1039,12 +1137,22 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
}
wasSealed = mSealed;
- if (!mSealed) {
+ try {
+ if (!mSealed) {
+ sealLocked(childSessions);
+ }
+
try {
- sealAndValidateLocked(childSessions);
- } catch (PackageManagerException e) {
+ streamAndValidateLocked();
+ } catch (StreamingException e) {
+ // In case of streaming failure we don't want to fail or commit the session.
+ // Just return from this method and allow caller to commit again.
+ PackageInstallerService.sendPendingStreaming(mContext, mRemoteStatusReceiver,
+ sessionId, e);
return false;
}
+ } catch (PackageManagerException e) {
+ return false;
}
// Client staging is fully done at this point
@@ -1131,17 +1239,26 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
}
/**
- * Seal the session to prevent further modification and validate the contents of it.
+ * Convenience wrapper, see {@link #sealLocked(List<PackageInstallerSession>) seal} and
+ * {@link #streamAndValidateLocked()}.
+ */
+ @GuardedBy("mLock")
+ private void sealAndValidateLocked(List<PackageInstallerSession> childSessions)
+ throws PackageManagerException, StreamingException {
+ sealLocked(childSessions);
+ streamAndValidateLocked();
+ }
+
+ /**
+ * Seal the session to prevent further modification.
*
* <p>The session will be sealed after calling this method even if it failed.
*
- * @param childSessions the child sessions of a multipackage that will be checked for
- * consistency. Can be null if session is not multipackage.
* @throws PackageManagerException if the session was sealed but something went wrong. If the
* session was sealed this is the only possible exception.
*/
@GuardedBy("mLock")
- private void sealAndValidateLocked(List<PackageInstallerSession> childSessions)
+ private void sealLocked(List<PackageInstallerSession> childSessions)
throws PackageManagerException {
try {
assertNoWriteFileTransfersOpenLocked();
@@ -1152,7 +1269,26 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
if (childSessions != null) {
assertMultiPackageConsistencyLocked(childSessions);
}
+ } catch (PackageManagerException e) {
+ throw onSessionVerificationFailure(e);
+ } catch (Throwable e) {
+ // Convert all exceptions into package manager exceptions as only those are handled
+ // in the code above.
+ throw onSessionVerificationFailure(new PackageManagerException(e));
+ }
+ }
+ /**
+ * Prepare DataLoader and stream content for DataLoader sessions.
+ * Validate the contents of all session.
+ *
+ * @throws StreamingException if streaming failed.
+ * @throws PackageManagerException if validation failed.
+ */
+ @GuardedBy("mLock")
+ private void streamAndValidateLocked()
+ throws PackageManagerException, StreamingException {
+ try {
// Read transfers from the original owner stay open, but as the session's data cannot
// be modified anymore, there is no leak of information. For staged sessions, further
// validation is performed by the staging manager.
@@ -1161,6 +1297,8 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
params.appPackageName, PackageManager.GET_SIGNATURES
| PackageManager.MATCH_STATIC_SHARED_LIBRARIES /*flags*/, userId);
+ prepareDataLoader();
+
if ((params.installFlags & PackageManager.INSTALL_APEX) != 0) {
validateApexInstallLocked();
} else {
@@ -1173,6 +1311,8 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
}
} catch (PackageManagerException e) {
throw onSessionVerificationFailure(e);
+ } catch (StreamingException e) {
+ throw e;
} catch (Throwable e) {
// Convert all exceptions into package manager exceptions as only those are handled
// in the code above.
@@ -1208,6 +1348,8 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
synchronized (mLock) {
try {
sealAndValidateLocked(childSessions);
+ } catch (StreamingException e) {
+ Slog.e(TAG, "Streaming failed", e);
} catch (PackageManagerException e) {
Slog.e(TAG, "Package not valid", e);
}
@@ -1277,6 +1419,8 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
try {
sealAndValidateLocked(childSessions);
+ } catch (StreamingException e) {
+ throw new IllegalArgumentException("Streaming failed", e);
} catch (PackageManagerException e) {
throw new IllegalArgumentException("Package is not valid", e);
}
@@ -1517,9 +1661,10 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
mInternalProgress = 0.5f;
computeProgressLocked(true);
- // Unpack native libraries
- // TODO(b/136132412): skip for incremental installation
- extractNativeLibraries(stageDir, params.abiOverride, mayInheritNativeLibs());
+ // Unpack native libraries for non-incremental installation
+ if (params.incrementalParams == null) {
+ extractNativeLibraries(stageDir, params.abiOverride, mayInheritNativeLibs());
+ }
}
// We've reached point of no return; call into PMS to install the stage.
@@ -2223,6 +2368,126 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
}
@Override
+ public void addFile(String name, long lengthBytes, byte[] metadata) {
+ if (mIncrementalFileStorages != null) {
+ try {
+ mIncrementalFileStorages.addFile(new InstallationFile(name, lengthBytes, metadata));
+ //TODO(b/136132412): merge incremental and callback installation schemes
+ return;
+ } catch (IOException ex) {
+ throw new IllegalStateException(
+ "Failed to add and configure Incremental File: " + name, ex);
+ }
+ }
+ if (!isDataLoaderInstallation()) {
+ throw new IllegalStateException(
+ "Cannot add files to non-callback installation session.");
+ }
+ // Use installer provided name for now; we always rename later
+ if (!FileUtils.isValidExtFilename(name)) {
+ throw new IllegalArgumentException("Invalid name: " + name);
+ }
+
+ synchronized (mLock) {
+ assertCallerIsOwnerOrRootLocked();
+ assertPreparedAndNotSealedLocked("addFile");
+
+ mFiles.add(FileInfo.added(name, lengthBytes, metadata));
+ }
+ }
+
+ @Override
+ public void removeFile(String name) {
+ if (!isDataLoaderInstallation()) {
+ throw new IllegalStateException(
+ "Cannot add files to non-callback installation session.");
+ }
+ if (TextUtils.isEmpty(params.appPackageName)) {
+ throw new IllegalStateException("Must specify package name to remove a split");
+ }
+
+ synchronized (mLock) {
+ assertCallerIsOwnerOrRootLocked();
+ assertPreparedAndNotSealedLocked("removeFile");
+
+ mFiles.add(FileInfo.removed(getRemoveMarkerName(name)));
+ }
+ }
+
+ /**
+ * Makes sure files are present in staging location.
+ */
+ private void prepareDataLoader()
+ throws PackageManagerException, StreamingException {
+ if (!isDataLoaderInstallation()) {
+ return;
+ }
+
+ FileSystemConnector connector = new FileSystemConnector();
+
+ FileInfo[] addedFiles = mFiles.stream().filter(
+ file -> sAddedFilter.accept(new File(file.name))).toArray(FileInfo[]::new);
+ String[] removedFiles = mFiles.stream().filter(
+ file -> sRemovedFilter.accept(new File(file.name))).map(
+ file -> file.name.substring(0,
+ file.name.length() - REMOVE_MARKER_EXTENSION.length())).toArray(
+ String[]::new);
+
+ DataLoader dataLoader = new DataLoader();
+ try {
+ dataLoader.onCreate(connector);
+
+ if (!dataLoader.onPrepareImage(addedFiles, removedFiles)) {
+ throw new PackageManagerException(INSTALL_FAILED_MEDIA_UNAVAILABLE,
+ "Failed to prepare image.");
+ }
+ } catch (IOException e) {
+ throw new StreamingException(e);
+ } finally {
+ dataLoader.onDestroy();
+ }
+ }
+
+ static class DataLoader {
+ private ParcelFileDescriptor mInFd = null;
+ private FileSystemConnector mConnector = null;
+
+ void onCreate(FileSystemConnector connector) throws IOException {
+ mConnector = connector;
+ }
+
+ void onDestroy() {
+ IoUtils.closeQuietly(mInFd);
+ }
+
+ private static final String STDIN_PATH = "-";
+ boolean onPrepareImage(FileInfo[] addedFiles, String[] removedFiles) throws IOException {
+ for (FileInfo fileInfo : addedFiles) {
+ String filePath = new String(fileInfo.metadata, StandardCharsets.UTF_8);
+ if (STDIN_PATH.equals(filePath) || TextUtils.isEmpty(filePath)) {
+ if (mInFd == null) {
+ Slog.e(TAG, "Invalid stdin file descriptor.");
+ return false;
+ }
+ ParcelFileDescriptor inFd = ParcelFileDescriptor.dup(mInFd.getFileDescriptor());
+ mConnector.writeData(fileInfo.name, 0, fileInfo.lengthBytes, inFd);
+ } else {
+ File localFile = new File(filePath);
+ ParcelFileDescriptor incomingFd = null;
+ try {
+ incomingFd = ParcelFileDescriptor.open(localFile,
+ ParcelFileDescriptor.MODE_READ_ONLY);
+ mConnector.writeData(fileInfo.name, 0, localFile.length(), incomingFd);
+ } finally {
+ IoUtils.closeQuietly(incomingFd);
+ }
+ }
+ }
+ return true;
+ }
+ }
+
+ @Override
public int[] getChildSessionIds() {
final int[] childSessionIds = mChildSessionIds.copyKeys();
if (childSessionIds != null) {
@@ -2294,20 +2559,6 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
return mParentSessionId;
}
- @Override
- public void addFile(@NonNull String name, long size, @NonNull byte[] metadata) {
- if (mIncrementalFileStorages == null) {
- throw new IllegalStateException(
- "Cannot add Incremental File to a non-Incremental session.");
- }
- try {
- mIncrementalFileStorages.addFile(new InstallationFile(name, size, metadata));
- } catch (IOException ex) {
- throw new IllegalStateException(
- "Failed to add and configure Incremental File: " + name, ex);
- }
- }
-
private void dispatchSessionFinished(int returnCode, String msg, Bundle extras) {
final IntentSender statusReceiver;
final String packageName;
@@ -2320,7 +2571,7 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
}
if (statusReceiver != null) {
- // Execute observer.onPackageInstalled on different tread as we don't want callers
+ // Execute observer.onPackageInstalled on different thread as we don't want callers
// inside the system server have to worry about catching the callbacks while they are
// calling into the session
final SomeArgs args = SomeArgs.obtain();
@@ -2594,6 +2845,8 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
writeStringAttribute(out, ATTR_VOLUME_UUID, params.volumeUuid);
writeIntAttribute(out, ATTR_INSTALL_REASON, params.installReason);
+ writeStringAttribute(out, ATTR_DATA_LOADER_PACKAGE_NAME, params.dataLoaderPackageName);
+
writeGrantedRuntimePermissionsLocked(out, params.grantedRuntimePermissions);
writeWhitelistedRestrictedPermissionsLocked(out,
params.whitelistedRestrictedPermissions);
@@ -2623,6 +2876,13 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
writeIntAttribute(out, ATTR_SESSION_ID, childSessionId);
out.endTag(null, TAG_CHILD_SESSION);
}
+ for (FileInfo fileInfo : mFiles) {
+ out.startTag(null, TAG_SESSION_FILE);
+ writeStringAttribute(out, ATTR_NAME, fileInfo.name);
+ writeLongAttribute(out, ATTR_LENGTH_BYTES, fileInfo.lengthBytes);
+ writeByteArrayAttribute(out, ATTR_METADATA, fileInfo.metadata);
+ out.endTag(null, TAG_SESSION_FILE);
+ }
}
out.endTag(null, TAG_SESSION);
@@ -2696,6 +2956,8 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
params.volumeUuid = readStringAttribute(in, ATTR_VOLUME_UUID);
params.installReason = readIntAttribute(in, ATTR_INSTALL_REASON);
+ params.dataLoaderPackageName = readStringAttribute(in, ATTR_DATA_LOADER_PACKAGE_NAME);
+
final File appIconFile = buildAppIconFile(sessionId, sessionsDir);
if (appIconFile.exists()) {
params.appIcon = BitmapFactory.decodeFile(appIconFile.getAbsolutePath());
@@ -2722,6 +2984,7 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
List<String> grantedRuntimePermissions = new ArrayList<>();
List<String> whitelistedRestrictedPermissions = new ArrayList<>();
List<Integer> childSessionIds = new ArrayList<>();
+ List<FileInfo> files = new ArrayList<>();
int outerDepth = in.getDepth();
int type;
while ((type = in.next()) != XmlPullParser.END_DOCUMENT
@@ -2739,6 +3002,11 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
if (TAG_CHILD_SESSION.equals(in.getName())) {
childSessionIds.add(readIntAttribute(in, ATTR_SESSION_ID, SessionInfo.INVALID_ID));
}
+ if (TAG_SESSION_FILE.equals(in.getName())) {
+ files.add(new FileInfo(readStringAttribute(in, ATTR_NAME),
+ readLongAttribute(in, ATTR_LENGTH_BYTES, -1),
+ readByteArrayAttribute(in, ATTR_METADATA)));
+ }
}
if (grantedRuntimePermissions.size() > 0) {
@@ -2757,11 +3025,16 @@ public class PackageInstallerSession extends IPackageInstallerSession.Stub {
childSessionIdsArray = EMPTY_CHILD_SESSION_ARRAY;
}
+ FileInfo[] fileInfosArray = null;
+ if (!files.isEmpty()) {
+ fileInfosArray = files.stream().toArray(FileInfo[]::new);
+ }
+
InstallSource installSource = InstallSource.create(installInitiatingPackageName,
installOriginatingPackageName, installerPackageName, false);
return new PackageInstallerSession(callback, context, pm, sessionProvider,
installerThread, stagingManager, sessionId, userId, installerUid,
- installSource, params, createdMillis, stageDir, stageCid,
+ installSource, params, createdMillis, stageDir, stageCid, fileInfosArray,
prepared, committed, sealed, childSessionIdsArray, parentSessionId,
isReady, isFailed, isApplied, stagedSessionErrorCode, stagedSessionErrorMessage);
}
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 73ab82dc01b2..cb362b0f0a23 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -155,6 +155,7 @@ import android.content.pm.IPackageStatsObserver;
import android.content.pm.InstallSourceInfo;
import android.content.pm.InstantAppInfo;
import android.content.pm.InstantAppRequest;
+import android.content.pm.InstantAppResolveInfo.InstantAppDigest;
import android.content.pm.InstrumentationInfo;
import android.content.pm.IntentFilterVerificationInfo;
import android.content.pm.KeySet;
@@ -376,6 +377,7 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
+import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
@@ -1439,6 +1441,7 @@ public class PackageManagerService extends IPackageManager.Stub
static final int ENABLE_ROLLBACK_TIMEOUT = 22;
static final int DEFERRED_NO_KILL_POST_DELETE = 23;
static final int DEFERRED_NO_KILL_INSTALL_OBSERVER = 24;
+ static final int INTEGRITY_VERIFICATION_COMPLETE = 25;
static final int DEFERRED_NO_KILL_POST_DELETE_DELAY_MS = 3 * 1000;
static final int DEFERRED_NO_KILL_INSTALL_OBSERVER_DELAY_MS = 500;
@@ -1603,6 +1606,10 @@ public class PackageManagerService extends IPackageManager.Stub
final boolean didRestore = (msg.arg2 != 0);
mRunningInstalls.delete(msg.arg1);
+ if (data != null && data.res.freezer != null) {
+ data.res.freezer.close();
+ }
+
if (data != null && data.mPostInstallRunnable != null) {
data.mPostInstallRunnable.run();
} else if (data != null) {
@@ -1763,6 +1770,10 @@ public class PackageManagerService extends IPackageManager.Stub
break;
}
+ case INTEGRITY_VERIFICATION_COMPLETE: {
+ // TODO: implement this case.
+ break;
+ }
case START_INTENT_FILTER_VERIFICATIONS: {
IFVerificationParams params = (IFVerificationParams) msg.obj;
verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, params.replacing,
@@ -3019,8 +3030,7 @@ public class PackageManagerService extends IPackageManager.Stub
mWellbeingPackage = getWellbeingPackageName();
mDocumenterPackage = getDocumenterPackageName();
- mConfiguratorPackage =
- mContext.getString(R.string.config_deviceConfiguratorPackageName);
+ mConfiguratorPackage = getDeviceConfiguratorPackageName();
mAppPredictionServicePackage = getAppPredictionServicePackageName();
mIncidentReportApproverPackage = getIncidentReportApproverPackageName();
mTelephonyPackages = getTelephonyPackageNames();
@@ -6135,10 +6145,12 @@ public class PackageManagerService extends IPackageManager.Stub
private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
Intent origIntent, String resolvedType, String callingPackage,
- Bundle verificationBundle, int userId) {
+ boolean isRequesterInstantApp, Bundle verificationBundle, int userId) {
final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
new InstantAppRequest(responseObj, origIntent, resolvedType,
- callingPackage, userId, verificationBundle, false /*resolveForStart*/));
+ callingPackage, isRequesterInstantApp, userId, verificationBundle,
+ false /*resolveForStart*/, responseObj.hostDigestPrefixSecure,
+ responseObj.token));
mHandler.sendMessage(msg);
}
@@ -6757,8 +6769,10 @@ public class PackageManagerService extends IPackageManager.Stub
}
}
if (addInstant) {
- result = maybeAddInstantAppInstaller(
- result, intent, resolvedType, flags, userId, resolveForStart);
+ String callingPkgName = getInstantAppPackageName(filterCallingUid);
+ boolean isRequesterInstantApp = isInstantApp(callingPkgName, userId);
+ result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId,
+ resolveForStart, isRequesterInstantApp);
}
if (sortResult) {
Collections.sort(result, RESOLVE_PRIORITY_SORTER);
@@ -6769,7 +6783,8 @@ public class PackageManagerService extends IPackageManager.Stub
}
private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
- String resolvedType, int flags, int userId, boolean resolveForStart) {
+ String resolvedType, int flags, int userId, boolean resolveForStart,
+ boolean isRequesterInstantApp) {
// first, check to see if we've got an instant app already installed
final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
ResolveInfo localInstantApp = null;
@@ -6817,10 +6832,13 @@ public class PackageManagerService extends IPackageManager.Stub
if (localInstantApp == null) {
// we don't have an instant app locally, resolve externally
Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
+ String token = UUID.randomUUID().toString();
+ InstantAppDigest digest = InstantAppResolver.parseDigest(intent);
final InstantAppRequest requestObject = new InstantAppRequest(
null /*responseObj*/, intent /*origIntent*/, resolvedType,
- null /*callingPackage*/, userId, null /*verificationBundle*/,
- resolveForStart);
+ null /*callingPackage*/, isRequesterInstantApp,
+ userId, null /*verificationBundle*/, resolveForStart,
+ digest.getDigestPrefixSecure(), token);
auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
mInstantAppResolverConnection, requestObject);
Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
@@ -13434,35 +13452,10 @@ public class PackageManagerService extends IPackageManager.Stub
// restore if appropriate, then pass responsibility back to the
// Package Manager to run the post-install observer callbacks
// and broadcasts.
- IBackupManager bm = IBackupManager.Stub.asInterface(
- ServiceManager.getService(Context.BACKUP_SERVICE));
- if (bm != null) {
- // For backwards compatibility as USER_ALL previously routed directly to USER_SYSTEM
- // in the BackupManager. USER_ALL is used in compatibility tests.
- if (userId == UserHandle.USER_ALL) {
- userId = UserHandle.USER_SYSTEM;
- }
- if (DEBUG_INSTALL) {
- Log.v(TAG, "token " + token + " to BM for possible restore for user " + userId);
- }
- Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
- try {
- if (bm.isBackupServiceActive(userId)) {
- bm.restoreAtInstallForUser(
- userId, res.pkg.getAppInfoPackageName(), token);
- } else {
- doRestore = false;
- }
- } catch (RemoteException e) {
- // can't happen; the backup manager is local
- } catch (Exception e) {
- Slog.e(TAG, "Exception trying to enqueue restore", e);
- doRestore = false;
- }
- } else {
- Slog.e(TAG, "Backup Manager not found!");
- doRestore = false;
+ if (res.freezer != null) {
+ res.freezer.close();
}
+ doRestore = performBackupManagerRestore(userId, token, res);
}
// If this is an update to a package that might be potentially downgraded, then we
@@ -13471,42 +13464,7 @@ public class PackageManagerService extends IPackageManager.Stub
//
// TODO(narayan): Get this working for cases where userId == UserHandle.USER_ALL.
if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && !doRestore && update) {
- IRollbackManager rm = IRollbackManager.Stub.asInterface(
- ServiceManager.getService(Context.ROLLBACK_SERVICE));
-
- final String packageName = res.pkg.getAppInfoPackageName();
- final String seInfo = res.pkg.getSeInfo();
- final int[] allUsers = mUserManager.getUserIds();
- final int[] installedUsers;
-
- final PackageSetting ps;
- int appId = -1;
- long ceDataInode = -1;
- synchronized (mSettings) {
- ps = mSettings.getPackageLPr(packageName);
- if (ps != null) {
- appId = ps.appId;
- ceDataInode = ps.getCeDataInode(userId);
- }
-
- // NOTE: We ignore the user specified in the InstallParam because we know this is
- // an update, and hence need to restore data for all installed users.
- installedUsers = ps.queryInstalledUsers(allUsers, true);
- }
-
- boolean doSnapshotOrRestore = data != null && data.args != null
- && ((data.args.installFlags & PackageManager.INSTALL_ENABLE_ROLLBACK) != 0
- || (data.args.installFlags & PackageManager.INSTALL_REQUEST_DOWNGRADE) != 0);
-
- if (ps != null && doSnapshotOrRestore) {
- try {
- rm.snapshotAndRestoreUserData(packageName, installedUsers, appId, ceDataInode,
- seInfo, token);
- } catch (RemoteException re) {
- Log.e(TAG, "Error snapshotting/restoring user data: " + re);
- }
- doRestore = true;
- }
+ doRestore = performRollbackManagerRestore(userId, token, res, data);
}
if (!doRestore) {
@@ -13522,6 +13480,91 @@ public class PackageManagerService extends IPackageManager.Stub
}
/**
+ * Perform Backup Manager restore for a given {@link PackageInstalledInfo}.
+ * Returns whether the restore successfully completed.
+ */
+ private boolean performBackupManagerRestore(int userId, int token, PackageInstalledInfo res) {
+ IBackupManager bm = IBackupManager.Stub.asInterface(
+ ServiceManager.getService(Context.BACKUP_SERVICE));
+ if (bm != null) {
+ // For backwards compatibility as USER_ALL previously routed directly to USER_SYSTEM
+ // in the BackupManager. USER_ALL is used in compatibility tests.
+ if (userId == UserHandle.USER_ALL) {
+ userId = UserHandle.USER_SYSTEM;
+ }
+ if (DEBUG_INSTALL) {
+ Log.v(TAG, "token " + token + " to BM for possible restore for user " + userId);
+ }
+ Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
+ try {
+ if (bm.isUserReadyForBackup(userId)) {
+ bm.restoreAtInstallForUser(
+ userId, res.pkg.getAppInfoPackageName(), token);
+ } else {
+ Slog.w(TAG, "User " + userId + " is not ready. Restore at install "
+ + "didn't take place.");
+ return false;
+ }
+ } catch (RemoteException e) {
+ // can't happen; the backup manager is local
+ } catch (Exception e) {
+ Slog.e(TAG, "Exception trying to enqueue restore", e);
+ return false;
+ }
+ } else {
+ Slog.e(TAG, "Backup Manager not found!");
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Perform Rollback Manager restore for a given {@link PackageInstalledInfo}.
+ * Returns whether the restore successfully completed.
+ */
+ private boolean performRollbackManagerRestore(int userId, int token, PackageInstalledInfo res,
+ PostInstallData data) {
+ IRollbackManager rm = IRollbackManager.Stub.asInterface(
+ ServiceManager.getService(Context.ROLLBACK_SERVICE));
+
+ final String packageName = res.pkg.getAppInfoPackageName();
+ final String seInfo = res.pkg.getSeInfo();
+ final int[] allUsers = mUserManager.getUserIds();
+ final int[] installedUsers;
+
+ final PackageSetting ps;
+ int appId = -1;
+ long ceDataInode = -1;
+ synchronized (mSettings) {
+ ps = mSettings.getPackageLPr(packageName);
+ if (ps != null) {
+ appId = ps.appId;
+ ceDataInode = ps.getCeDataInode(userId);
+ }
+
+ // NOTE: We ignore the user specified in the InstallParam because we know this is
+ // an update, and hence need to restore data for all installed users.
+ installedUsers = ps.queryInstalledUsers(allUsers, true);
+ }
+
+ boolean doSnapshotOrRestore = data != null && data.args != null
+ && ((data.args.installFlags & PackageManager.INSTALL_ENABLE_ROLLBACK) != 0
+ || (data.args.installFlags & PackageManager.INSTALL_REQUEST_DOWNGRADE) != 0);
+
+ if (ps != null && doSnapshotOrRestore) {
+ try {
+ rm.snapshotAndRestoreUserData(packageName, installedUsers, appId, ceDataInode,
+ seInfo, token);
+ } catch (RemoteException re) {
+ Log.e(TAG, "Error snapshotting/restoring user data: " + re);
+ return false;
+ }
+ return true;
+ }
+ return false;
+ }
+
+ /**
* Callback from PackageSettings whenever an app is first transitioned out of the
* 'stopped' state. Normally we just issue the broadcast, but we can't do that if
* the app was "launched" for a restoreAtInstall operation. Therefore we check
@@ -14113,7 +14156,7 @@ public class PackageManagerService extends IPackageManager.Stub
verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
- installSource.installerPackageName);
+ installSource.initiatingPackageName);
verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
installFlags);
@@ -14575,7 +14618,8 @@ public class PackageManagerService extends IPackageManager.Stub
return false;
}
- if (!SELinux.restoreconRecursive(afterCodeFile)) {
+ //TODO(b/136132412): enable selinux restorecon for incremental directories
+ if (!onIncremental && !SELinux.restoreconRecursive(afterCodeFile)) {
Slog.w(TAG, "Failed to restorecon");
return false;
}
@@ -14802,6 +14846,7 @@ public class PackageManagerService extends IPackageManager.Stub
ArrayMap<String, PackageInstalledInfo> addedChildPackages;
// The set of packages consuming this shared library or null if no consumers exist.
ArrayList<AndroidPackage> libraryConsumers;
+ PackageFreezer freezer;
public void setError(int code, String msg) {
setReturnCode(code);
@@ -15675,16 +15720,14 @@ public class PackageManagerService extends IPackageManager.Stub
// TODO(patb): create a more descriptive reason than unknown in future release
// mark all non-failure installs as UNKNOWN so we do not treat them as success
for (InstallRequest request : requests) {
+ if (request.installResult.freezer != null) {
+ request.installResult.freezer.close();
+ }
if (request.installResult.returnCode == PackageManager.INSTALL_SUCCEEDED) {
request.installResult.returnCode = PackageManager.INSTALL_UNKNOWN;
}
}
}
- for (PrepareResult result : prepareResults.values()) {
- if (result.freezer != null) {
- result.freezer.close();
- }
- }
Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
}
}
@@ -15792,15 +15835,13 @@ public class PackageManagerService extends IPackageManager.Stub
public final ParsedPackage packageToScan;
public final boolean clearCodeCache;
public final boolean system;
- public final PackageFreezer freezer;
public final PackageSetting originalPs;
public final PackageSetting disabledPs;
private PrepareResult(boolean replace, int scanFlags,
int parseFlags, AndroidPackage existingPackage,
ParsedPackage packageToScan, boolean clearCodeCache, boolean system,
- PackageFreezer freezer, PackageSetting originalPs,
- PackageSetting disabledPs) {
+ PackageSetting originalPs, PackageSetting disabledPs) {
this.replace = replace;
this.scanFlags = scanFlags;
this.parseFlags = parseFlags;
@@ -15808,7 +15849,6 @@ public class PackageManagerService extends IPackageManager.Stub
this.packageToScan = packageToScan;
this.clearCodeCache = clearCodeCache;
this.system = system;
- this.freezer = freezer;
this.originalPs = originalPs;
this.disabledPs = disabledPs;
}
@@ -16437,9 +16477,10 @@ public class PackageManagerService extends IPackageManager.Stub
shouldCloseFreezerBeforeReturn = false;
return new PrepareResult(replace, targetScanFlags, targetParseFlags,
- existingPackage, parsedPackage, replace /* clearCodeCache */, sysPkg, freezer,
+ existingPackage, parsedPackage, replace /* clearCodeCache */, sysPkg,
ps, disabledPs);
} finally {
+ res.freezer = freezer;
if (shouldCloseFreezerBeforeReturn) {
freezer.close();
}
@@ -17921,14 +17962,6 @@ public class PackageManagerService extends IPackageManager.Stub
}
}
mPermissionManager.resetRuntimePermissions(pkg, nextUserId);
- // Also delete contributed media, when requested
- if ((flags & PackageManager.DELETE_CONTRIBUTED_MEDIA) != 0) {
- try {
- MediaStore.deleteContributedMedia(mContext, ps.name, UserHandle.of(nextUserId));
- } catch (IOException e) {
- Slog.w(TAG, "Failed to delete contributed media for " + ps.name, e);
- }
- }
}
if (outInfo != null) {
@@ -19160,13 +19193,14 @@ public class PackageManagerService extends IPackageManager.Stub
@Override
public String getSystemTextClassifierPackageName() {
- return mContext.getString(R.string.config_defaultTextClassifierPackage);
+ return ensureSystemPackageName(mContext.getString(
+ R.string.config_defaultTextClassifierPackage));
}
@Override
public String[] getSystemTextClassifierPackages() {
- return mContext.getResources().getStringArray(
- R.array.config_defaultTextClassifierPackages);
+ return ensureSystemPackageNames(mContext.getResources().getStringArray(
+ R.array.config_defaultTextClassifierPackages));
}
@Override
@@ -19176,7 +19210,7 @@ public class PackageManagerService extends IPackageManager.Stub
if (flattenedComponentName != null) {
ComponentName componentName = ComponentName.unflattenFromString(flattenedComponentName);
if (componentName != null && componentName.getPackageName() != null) {
- return componentName.getPackageName();
+ return ensureSystemPackageName(componentName.getPackageName());
}
}
return null;
@@ -19201,9 +19235,15 @@ public class PackageManagerService extends IPackageManager.Stub
}
}
+ @Nullable
+ private String getDeviceConfiguratorPackageName() {
+ return ensureSystemPackageName(mContext.getString(
+ R.string.config_deviceConfiguratorPackageName));
+ }
+
@Override
public String getWellbeingPackageName() {
- return mContext.getString(R.string.config_defaultWellbeingPackage);
+ return ensureSystemPackageName(mContext.getString(R.string.config_defaultWellbeingPackage));
}
@Override
@@ -19218,7 +19258,7 @@ public class PackageManagerService extends IPackageManager.Stub
if (appPredictionServiceComponentName == null) {
return null;
}
- return appPredictionServiceComponentName.getPackageName();
+ return ensureSystemPackageName(appPredictionServiceComponentName.getPackageName());
}
@Override
@@ -19235,7 +19275,7 @@ public class PackageManagerService extends IPackageManager.Stub
if (systemCaptionsServiceComponentName == null) {
return null;
}
- return systemCaptionsServiceComponentName.getPackageName();
+ return ensureSystemPackageName(systemCaptionsServiceComponentName.getPackageName());
}
@Override
@@ -19247,7 +19287,8 @@ public class PackageManagerService extends IPackageManager.Stub
}
public String getIncidentReportApproverPackageName() {
- return mContext.getString(R.string.config_incidentReportApproverPackage);
+ return ensureSystemPackageName(mContext.getString(
+ R.string.config_incidentReportApproverPackage));
}
@Override
@@ -19257,7 +19298,7 @@ public class PackageManagerService extends IPackageManager.Stub
if (!TextUtils.isEmpty(names)) {
telephonyPackageNames = names.trim().split(",");
}
- return telephonyPackageNames;
+ return ensureSystemPackageNames(telephonyPackageNames);
}
@Override
@@ -19274,7 +19315,32 @@ public class PackageManagerService extends IPackageManager.Stub
if (contentCaptureServiceComponentName == null) {
return null;
}
- return contentCaptureServiceComponentName.getPackageName();
+ return ensureSystemPackageName(contentCaptureServiceComponentName.getPackageName());
+ }
+
+ @Nullable
+ private String ensureSystemPackageName(@Nullable String packageName) {
+ if (packageName == null) {
+ return null;
+ }
+ if (getPackageInfo(packageName, MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE
+ | MATCH_DIRECT_BOOT_UNAWARE | MATCH_DISABLED_COMPONENTS,
+ UserHandle.getCallingUserId()) == null) {
+ return null;
+ }
+ return packageName;
+ }
+
+ @Nullable
+ private String[] ensureSystemPackageNames(@Nullable String[] packageNames) {
+ if (packageNames == null) {
+ return null;
+ }
+ final int packageNamesLength = packageNames.length;
+ for (int i = 0; i < packageNamesLength; i++) {
+ packageNames[i] = ensureSystemPackageName(packageNames[i]);
+ }
+ return ArrayUtils.filterNotNull(packageNames, String[]::new);
}
@Override
@@ -22560,6 +22626,18 @@ public class PackageManagerService extends IPackageManager.Stub
}
@Override
+ public long getCeDataInode(String packageName, int userId) {
+ synchronized (mLock) {
+ final PackageSetting ps = mSettings.mPackages.get(packageName);
+ if (ps != null) {
+ return ps.getCeDataInode(userId);
+ }
+ Slog.e(TAG, "failed to find package " + packageName);
+ return 0;
+ }
+ }
+
+ @Override
public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) {
synchronized (mLock) {
final PackageSetting ps = mSettings.mPackages.get(packageName);
@@ -22684,6 +22762,12 @@ public class PackageManagerService extends IPackageManager.Stub
}
@Override
+ public ComponentName getSystemUiServiceComponent() {
+ return ComponentName.unflattenFromString(mContext.getResources().getString(
+ com.android.internal.R.string.config_systemUIServiceComponent));
+ }
+
+ @Override
public void setDeviceAndProfileOwnerPackages(
int deviceOwnerUserId, String deviceOwnerPackage,
SparseArray<String> profileOwnerPackages) {
@@ -22763,10 +22847,10 @@ public class PackageManagerService extends IPackageManager.Stub
@Override
public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
Intent origIntent, String resolvedType, String callingPackage,
- Bundle verificationBundle, int userId) {
+ boolean isRequesterInstantApp, Bundle verificationBundle, int userId) {
PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
- responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
- userId);
+ responseObj, origIntent, resolvedType, callingPackage, isRequesterInstantApp,
+ verificationBundle, userId);
}
@Override
@@ -23199,6 +23283,14 @@ public class PackageManagerService extends IPackageManager.Stub
mSettings.writeLPr();
}
}
+
+ @Override
+ public void setIntegrityVerificationResult(int verificationId, int verificationResult) {
+ final Message msg = mHandler.obtainMessage(INTEGRITY_VERIFICATION_COMPLETE);
+ msg.arg1 = verificationId;
+ msg.obj = verificationResult;
+ mHandler.sendMessage(msg);
+ }
}
@GuardedBy("mLock")
@@ -23233,11 +23325,12 @@ public class PackageManagerService extends IPackageManager.Stub
PackageSetting ps = it.next();
if (ps.getInstalled(userId)) {
res[i++] = ps.name;
- } else {
- res = ArrayUtils.removeElement(String.class, res, res[i]);
}
}
- return res;
+ res = ArrayUtils.trimToSize(res, i);
+ if (res != null) {
+ return res;
+ }
} catch (PackageManagerException e) {
// Should not happen
}
diff --git a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
index fff404f3ede6..dfffbd6cabef 100644
--- a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
+++ b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
@@ -114,6 +114,7 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URISyntaxException;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -135,6 +136,8 @@ class PackageManagerShellCommand extends ShellCommand {
private final static String ART_PROFILE_SNAPSHOT_DEBUG_LOCATION = "/data/misc/profman/";
private static final int DEFAULT_WAIT_MS = 60 * 1000;
+ private static final String PM_SHELL_DATALOADER = "com.android.pm.dataloader";
+
final IPackageManager mInterface;
final IPermissionManager mPermissionManager;
final private WeakHashMap<String, Resources> mResourceCache =
@@ -175,6 +178,8 @@ class PackageManagerShellCommand extends ShellCommand {
return runQueryIntentReceivers();
case "install":
return runInstall();
+ case "install-streaming":
+ return runStreamingInstall();
case "install-abandon":
case "install-destroy":
return runInstallAbandon();
@@ -1152,9 +1157,21 @@ class PackageManagerShellCommand extends ShellCommand {
return 0;
}
+ private int runStreamingInstall() throws RemoteException {
+ final InstallParams params = makeInstallParams();
+ if (TextUtils.isEmpty(params.sessionParams.dataLoaderPackageName)) {
+ params.sessionParams.setDataLoaderPackageName(PM_SHELL_DATALOADER);
+ }
+ return doRunInstall(params);
+ }
+
private int runInstall() throws RemoteException {
+ return doRunInstall(makeInstallParams());
+ }
+
+ private int doRunInstall(final InstallParams params) throws RemoteException {
final PrintWriter pw = getOutPrintWriter();
- final InstallParams params = makeInstallParams();
+ final boolean streaming = !TextUtils.isEmpty(params.sessionParams.dataLoaderPackageName);
ArrayList<String> inPaths = getRemainingArgs();
if (inPaths.isEmpty()) {
@@ -1181,17 +1198,30 @@ class PackageManagerShellCommand extends ShellCommand {
return 1;
}
- setParamsSize(params, inPaths);
+ if (!streaming) {
+ setParamsSize(params, inPaths);
+ }
+
final int sessionId = doCreateSession(params.sessionParams,
params.installerPackageName, params.userId);
boolean abandonSession = true;
try {
for (String inPath : inPaths) {
- String splitName = hasSplits ? (new File(inPath)).getName()
- : "base." + (isApex ? "apex" : "apk");
- if (doWriteSplit(sessionId, inPath, params.sessionParams.sizeBytes, splitName,
- false /*logSuccess*/) != PackageInstaller.STATUS_SUCCESS) {
- return 1;
+ if (streaming) {
+ String name = new File(inPath).getName();
+ byte[] metadata = inPath.getBytes(StandardCharsets.UTF_8);
+ if (doAddFile(sessionId, name, params.sessionParams.sizeBytes, metadata,
+ false /*logSuccess*/) != PackageInstaller.STATUS_SUCCESS) {
+ return 1;
+ }
+ } else {
+ String splitName = hasSplits ? new File(inPath).getName()
+ : "base." + (isApex ? "apex" : "apk");
+
+ if (doWriteSplit(sessionId, inPath, params.sessionParams.sizeBytes, splitName,
+ false /*logSuccess*/) != PackageInstaller.STATUS_SUCCESS) {
+ return 1;
+ }
}
}
if (doCommitSession(sessionId, false /*logSuccess*/)
@@ -2927,11 +2957,32 @@ class PackageManagerShellCommand extends ShellCommand {
return sessionId;
}
+ private int doAddFile(int sessionId, String name, long sizeBytes, byte[] metadata,
+ boolean logSuccess) throws RemoteException {
+ PackageInstaller.Session session = new PackageInstaller.Session(
+ mInterface.getPackageInstaller().openSession(sessionId));
+ try {
+ session.addFile(name, sizeBytes, metadata);
+
+ if (logSuccess) {
+ getOutPrintWriter().println("Success");
+ }
+
+ return 0;
+ } finally {
+ IoUtils.closeQuietly(session);
+ }
+ }
+
private int doWriteSplit(int sessionId, String inPath, long sizeBytes, String splitName,
boolean logSuccess) throws RemoteException {
PackageInstaller.Session session = null;
try {
+ session = new PackageInstaller.Session(
+ mInterface.getPackageInstaller().openSession(sessionId));
+
final PrintWriter pw = getOutPrintWriter();
+
final ParcelFileDescriptor fd;
if (STDIN_PATH.equals(inPath)) {
fd = ParcelFileDescriptor.dup(getInFileDescriptor());
@@ -2953,8 +3004,6 @@ class PackageManagerShellCommand extends ShellCommand {
return 1;
}
- session = new PackageInstaller.Session(
- mInterface.getPackageInstaller().openSession(sessionId));
session.write(splitName, 0, sizeBytes, fd);
if (logSuccess) {
@@ -3000,7 +3049,6 @@ class PackageManagerShellCommand extends ShellCommand {
try {
session = new PackageInstaller.Session(
mInterface.getPackageInstaller().openSession(sessionId));
-
for (String splitName : splitNames) {
session.removeSplit(splitName);
}
diff --git a/services/core/java/com/android/server/pm/StagingManager.java b/services/core/java/com/android/server/pm/StagingManager.java
index 7ea4e984b426..688c34fed44f 100644
--- a/services/core/java/com/android/server/pm/StagingManager.java
+++ b/services/core/java/com/android/server/pm/StagingManager.java
@@ -21,6 +21,7 @@ import android.annotation.Nullable;
import android.apex.ApexInfo;
import android.apex.ApexInfoList;
import android.apex.ApexSessionInfo;
+import android.apex.ApexSessionParams;
import android.content.Context;
import android.content.IIntentReceiver;
import android.content.IIntentSender;
@@ -36,6 +37,8 @@ import android.content.pm.PackageParser.SigningDetails;
import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
import android.content.pm.ParceledListSlice;
import android.content.rollback.IRollbackManager;
+import android.content.rollback.RollbackInfo;
+import android.content.rollback.RollbackManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
@@ -49,6 +52,7 @@ import android.os.storage.StorageManager;
import android.util.IntArray;
import android.util.Slog;
import android.util.SparseArray;
+import android.util.SparseIntArray;
import android.util.apk.ApkSignatureVerifier;
import com.android.internal.annotations.GuardedBy;
@@ -82,6 +86,9 @@ public class StagingManager {
@GuardedBy("mStagedSessions")
private final SparseArray<PackageInstallerSession> mStagedSessions = new SparseArray<>();
+ @GuardedBy("mStagedSessions")
+ private final SparseIntArray mSessionRollbackIds = new SparseIntArray();
+
StagingManager(PackageInstallerService pi, ApexManager am, Context context) {
mPi = pi;
mApexManager = am;
@@ -166,18 +173,32 @@ public class StagingManager {
private List<PackageInfo> submitSessionToApexService(
@NonNull PackageInstallerSession session) throws PackageManagerException {
- final IntArray childSessionsIds = new IntArray();
+ final IntArray childSessionIds = new IntArray();
if (session.isMultiPackage()) {
for (int id : session.getChildSessionIds()) {
if (isApexSession(mStagedSessions.get(id))) {
- childSessionsIds.add(id);
+ childSessionIds.add(id);
+ }
+ }
+ }
+ ApexSessionParams apexSessionParams = new ApexSessionParams();
+ apexSessionParams.sessionId = session.sessionId;
+ apexSessionParams.childSessionIds = childSessionIds.toArray();
+ if (session.params.installReason == PackageManager.INSTALL_REASON_ROLLBACK) {
+ apexSessionParams.isRollback = true;
+ apexSessionParams.rollbackId = retrieveRollbackIdForCommitSession(session.sessionId);
+ } else {
+ synchronized (mStagedSessions) {
+ int rollbackId = mSessionRollbackIds.get(session.sessionId, -1);
+ if (rollbackId != -1) {
+ apexSessionParams.hasRollbackEnabled = true;
+ apexSessionParams.rollbackId = rollbackId;
}
}
}
// submitStagedSession will throw a PackageManagerException if apexd verification fails,
// which will be propagated to populate stagedSessionErrorMessage of this session.
- final ApexInfoList apexInfoList = mApexManager.submitStagedSession(session.sessionId,
- childSessionsIds.toArray());
+ final ApexInfoList apexInfoList = mApexManager.submitStagedSession(apexSessionParams);
final List<PackageInfo> result = new ArrayList<>();
for (ApexInfo apexInfo : apexInfoList.apexInfos) {
final PackageInfo packageInfo;
@@ -208,6 +229,19 @@ public class StagingManager {
return result;
}
+ private int retrieveRollbackIdForCommitSession(int sessionId) throws PackageManagerException {
+ RollbackManager rm = mContext.getSystemService(RollbackManager.class);
+
+ List<RollbackInfo> rollbacks = rm.getRecentlyCommittedRollbacks();
+ for (RollbackInfo rollback : rollbacks) {
+ if (rollback.getCommittedSessionId() == sessionId) {
+ return rollback.getRollbackId();
+ }
+ }
+ throw new PackageManagerException(
+ "Could not find rollback id for commit session: " + sessionId);
+ }
+
private void checkRequiredVersionCode(final PackageInstallerSession session,
final PackageInfo activePackage) throws PackageManagerException {
if (session.params.requiredInstalledVersionCode == PackageManager.VERSION_CODE_HIGHEST) {
@@ -633,6 +667,7 @@ public class StagingManager {
void abortSession(@NonNull PackageInstallerSession session) {
synchronized (mStagedSessions) {
mStagedSessions.remove(session.sessionId);
+ mSessionRollbackIds.delete(session.sessionId);
}
}
@@ -865,6 +900,28 @@ public class StagingManager {
*/
private void handlePreRebootVerification_Start(@NonNull PackageInstallerSession session) {
Slog.d(TAG, "Starting preRebootVerification for session " + session.sessionId);
+
+ if ((session.params.installFlags & PackageManager.INSTALL_ENABLE_ROLLBACK) != 0) {
+ // If rollback is enabled for this session, we call through to the RollbackManager
+ // with the list of sessions it must enable rollback for. Note that
+ // notifyStagedSession is a synchronous operation.
+ final IRollbackManager rm = IRollbackManager.Stub.asInterface(
+ ServiceManager.getService(Context.ROLLBACK_SERVICE));
+ try {
+ // NOTE: To stay consistent with the non-staged install flow, we don't fail the
+ // entire install if rollbacks can't be enabled.
+ int rollbackId = rm.notifyStagedSession(session.sessionId);
+ if (rollbackId != -1) {
+ synchronized (mStagedSessions) {
+ mSessionRollbackIds.put(session.sessionId, rollbackId);
+ }
+ }
+ } catch (RemoteException re) {
+ Slog.e(TAG, "Failed to notifyStagedSession for session: "
+ + session.sessionId, re);
+ }
+ }
+
notifyPreRebootVerification_Start_Complete(session.sessionId);
}
@@ -929,25 +986,6 @@ public class StagingManager {
* </ul></p>
*/
private void handlePreRebootVerification_End(@NonNull PackageInstallerSession session) {
- if ((session.params.installFlags & PackageManager.INSTALL_ENABLE_ROLLBACK) != 0) {
- // If rollback is enabled for this session, we call through to the RollbackManager
- // with the list of sessions it must enable rollback for. Note that
- // notifyStagedSession is a synchronous operation.
- final IRollbackManager rm = IRollbackManager.Stub.asInterface(
- ServiceManager.getService(Context.ROLLBACK_SERVICE));
- try {
- // NOTE: To stay consistent with the non-staged install flow, we don't fail the
- // entire install if rollbacks can't be enabled.
- if (!rm.notifyStagedSession(session.sessionId)) {
- Slog.e(TAG, "Unable to enable rollback for session: "
- + session.sessionId);
- }
- } catch (RemoteException re) {
- Slog.e(TAG, "Failed to notifyStagedSession for session: "
- + session.sessionId, re);
- }
- }
-
// Proactively mark session as ready before calling apexd. Although this call order
// looks counter-intuitive, this is the easiest way to ensure that session won't end up
// in the inconsistent state:
diff --git a/services/core/java/com/android/server/pm/TEST_MAPPING b/services/core/java/com/android/server/pm/TEST_MAPPING
index e8798ffa3720..59a58042011e 100644
--- a/services/core/java/com/android/server/pm/TEST_MAPPING
+++ b/services/core/java/com/android/server/pm/TEST_MAPPING
@@ -24,7 +24,20 @@
]
},
{
- "name": "PackageManagerShellCommandTest"
+ "name": "CtsContentTestCases",
+ "options": [
+ {
+ "include-filter": "android.content.pm.cts.PackageManagerShellCommandTest"
+ }
+ ]
+ },
+ {
+ "name": "GtsSecurityHostTestCases",
+ "options": [
+ {
+ "include-filter": "com.google.android.security.gts.PackageVerifierTest"
+ }
+ ]
}
],
"postsubmit": [
diff --git a/services/core/java/com/android/server/pm/UserManagerService.java b/services/core/java/com/android/server/pm/UserManagerService.java
index ad4411c0da4d..3515cb71cd59 100644
--- a/services/core/java/com/android/server/pm/UserManagerService.java
+++ b/services/core/java/com/android/server/pm/UserManagerService.java
@@ -84,7 +84,6 @@ import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.AtomicFile;
import android.util.IntArray;
-import android.util.Log;
import android.util.Slog;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
@@ -351,6 +350,7 @@ public class UserManagerService extends IUserManager.Stub {
* User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
* that should be applied to all users, including guests. Only non-empty restriction bundles are
* stored.
+ * The key is the user id of the user whom the restriction originated from.
*/
@GuardedBy("mRestrictionsLock")
private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
@@ -364,6 +364,7 @@ public class UserManagerService extends IUserManager.Stub {
/**
* User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
* for each user. Only non-empty restriction bundles are stored.
+ * The key is the user id of the user whom the restriction originated from.
*/
@GuardedBy("mRestrictionsLock")
private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
@@ -579,15 +580,6 @@ public class UserManagerService extends IUserManager.Stub {
applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
}
- UserInfo currentGuestUser = findCurrentGuestUser();
- if (currentGuestUser != null && !hasUserRestriction(
- UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
- // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
- // to it, in case this guest was created in a previous version where this
- // user restriction was not a default guest restriction.
- setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
- }
-
mContext.registerReceiver(mDisableQuietModeCallback,
new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
null, mHandler);
@@ -1118,11 +1110,6 @@ public class UserManagerService extends IUserManager.Stub {
info.flags ^= UserInfo.FLAG_ADMIN;
writeUserLP(getUserDataLU(info.id));
}
-
- // Remove non-admin restrictions.
- // Keep synchronized with createUserEvenWhenDisallowed.
- setUserRestriction(UserManager.DISALLOW_SMS, false, userId);
- setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, false, userId);
}
/**
@@ -1522,7 +1509,7 @@ public class UserManagerService extends IUserManager.Stub {
public void setUserIcon(@UserIdInt int userId, Bitmap bitmap) {
checkManageUsersPermission("update users");
if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
- Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
+ Slog.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
return;
}
mLocalService.setUserIcon(userId, bitmap);
@@ -1570,7 +1557,7 @@ public class UserManagerService extends IUserManager.Stub {
return ParcelFileDescriptor.open(
new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
} catch (FileNotFoundException e) {
- Log.e(LOG_TAG, "Couldn't find icon file", e);
+ Slog.e(LOG_TAG, "Couldn't find icon file", e);
}
return null;
}
@@ -1602,10 +1589,12 @@ public class UserManagerService extends IUserManager.Stub {
private void initDefaultGuestRestrictions() {
synchronized (mGuestRestrictions) {
if (mGuestRestrictions.isEmpty()) {
- mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
- mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
- mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
- mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
+ UserTypeDetails guestType = mUserTypes.get(UserManager.USER_TYPE_FULL_GUEST);
+ if (guestType == null) {
+ Slog.wtf(LOG_TAG, "Can't set default guest restrictions: type doesn't exist.");
+ return;
+ }
+ guestType.addDefaultRestrictionsTo(mGuestRestrictions);
}
}
}
@@ -1633,7 +1622,7 @@ public class UserManagerService extends IUserManager.Stub {
/**
* See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
*/
- private void setDevicePolicyUserRestrictionsInner(@UserIdInt int userId,
+ private void setDevicePolicyUserRestrictionsInner(@UserIdInt int originatingUserId,
@Nullable Bundle restrictions,
@UserManagerInternal.OwnerType int restrictionOwnerType) {
final Bundle global = new Bundle();
@@ -1647,16 +1636,16 @@ public class UserManagerService extends IUserManager.Stub {
synchronized (mRestrictionsLock) {
// Update global and local restrictions if they were changed.
globalChanged = updateRestrictionsIfNeededLR(
- userId, global, mDevicePolicyGlobalUserRestrictions);
+ originatingUserId, global, mDevicePolicyGlobalUserRestrictions);
localChanged = updateRestrictionsIfNeededLR(
- userId, local, mDevicePolicyLocalUserRestrictions);
+ originatingUserId, local, mDevicePolicyLocalUserRestrictions);
if (restrictionOwnerType == UserManagerInternal.OWNER_TYPE_DEVICE_OWNER) {
// Remember the global restriction owner userId to be able to make a distinction
// in getUserRestrictionSource on who set local policies.
- mDeviceOwnerUserId = userId;
+ mDeviceOwnerUserId = originatingUserId;
} else {
- if (mDeviceOwnerUserId == userId) {
+ if (mDeviceOwnerUserId == originatingUserId) {
// When profile owner sets restrictions it passes null global bundle and we
// reset global restriction owner userId.
// This means this user used to have DO, but now the DO is gone and the user
@@ -1666,15 +1655,16 @@ public class UserManagerService extends IUserManager.Stub {
}
}
if (DBG) {
- Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
- + " global=" + global + (globalChanged ? " (changed)" : "")
- + " local=" + local + (localChanged ? " (changed)" : "")
+ Slog.d(LOG_TAG, "setDevicePolicyUserRestrictions: "
+ + " originatingUserId=" + originatingUserId
+ + " global=" + global + (globalChanged ? " (changed)" : "")
+ + " local=" + local + (localChanged ? " (changed)" : "")
);
}
// Don't call them within the mRestrictionsLock.
synchronized (mPackagesLock) {
if (localChanged || globalChanged) {
- writeUserLP(getUserDataNoChecks(userId));
+ writeUserLP(getUserDataNoChecks(originatingUserId));
}
}
@@ -1682,7 +1672,7 @@ public class UserManagerService extends IUserManager.Stub {
if (globalChanged) {
applyUserRestrictionsForAllUsersLR();
} else if (localChanged) {
- applyUserRestrictionsLR(userId);
+ applyUserRestrictionsLR(originatingUserId);
}
}
}
@@ -1727,7 +1717,7 @@ public class UserManagerService extends IUserManager.Stub {
@GuardedBy("mRestrictionsLock")
private void invalidateEffectiveUserRestrictionsLR(@UserIdInt int userId) {
if (DBG) {
- Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
+ Slog.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
}
mCachedEffectiveUserRestrictions.remove(userId);
}
@@ -1949,7 +1939,7 @@ public class UserManagerService extends IUserManager.Stub {
try {
mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
} catch (RemoteException e) {
- Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
+ Slog.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
}
}
});
@@ -2021,7 +2011,7 @@ public class UserManagerService extends IUserManager.Stub {
try {
runningUsers = ActivityManager.getService().getRunningUserIds();
} catch (RemoteException e) {
- Log.w(LOG_TAG, "Unable to access ActivityManagerService");
+ Slog.w(LOG_TAG, "Unable to access ActivityManagerService");
return;
}
// Then re-calculate the effective restrictions and apply, only for running users.
@@ -2494,6 +2484,12 @@ public class UserManagerService extends IUserManager.Stub {
mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
);
}
+ // DISALLOW_CONFIG_WIFI was made a default guest restriction some time during version 6.
+ final UserInfo currentGuestUser = findCurrentGuestUser();
+ if (currentGuestUser != null && !hasUserRestriction(
+ UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
+ setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
+ }
userVersion = 7;
}
@@ -2599,7 +2595,7 @@ public class UserManagerService extends IUserManager.Stub {
}
}
} catch (Resources.NotFoundException e) {
- Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
+ Slog.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
}
if (!restrictions.isEmpty()) {
@@ -3059,7 +3055,7 @@ public class UserManagerService extends IUserManager.Stub {
? UserManager.DISALLOW_ADD_MANAGED_PROFILE
: UserManager.DISALLOW_ADD_USER;
if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
- Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
+ Slog.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
return null;
}
return createUserInternalUnchecked(name, userType, flags, parentId,
@@ -3118,7 +3114,7 @@ public class UserManagerService extends IUserManager.Stub {
DeviceStorageMonitorInternal dsm = LocalServices
.getService(DeviceStorageMonitorInternal.class);
if (dsm.isMemoryLow()) {
- Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
+ Slog.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
return null;
}
@@ -3141,36 +3137,36 @@ public class UserManagerService extends IUserManager.Stub {
if (parent == null) return null;
}
if (!preCreate && !canAddMoreUsersOfType(userTypeDetails)) {
- Log.e(LOG_TAG, "Cannot add more users of type " + userType
+ Slog.e(LOG_TAG, "Cannot add more users of type " + userType
+ ". Maximum number of that type already exists.");
return null;
}
// TODO(b/142482943): Perhaps let the following code apply to restricted users too.
if (isProfile && !canAddMoreProfilesToUser(userType, parentId, false)) {
- Log.e(LOG_TAG, "Cannot add more profiles of type " + userType
+ Slog.e(LOG_TAG, "Cannot add more profiles of type " + userType
+ " for user " + parentId);
return null;
}
if (!isGuest && !isProfile && !isDemo && isUserLimitReached()) {
// If we're not adding a guest/demo user or a profile and the 'user limit' has
// been reached, cannot add a user.
- Log.e(LOG_TAG, "Cannot add user. Maximum user limit is reached.");
+ Slog.e(LOG_TAG, "Cannot add user. Maximum user limit is reached.");
return null;
}
// In legacy mode, restricted profile's parent can only be the owner user
if (isRestricted && !UserManager.isSplitSystemUser()
&& (parentId != UserHandle.USER_SYSTEM)) {
- Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
+ Slog.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
return null;
}
if (isRestricted && UserManager.isSplitSystemUser()) {
if (parent == null) {
- Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
+ Slog.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
+ "specified");
return null;
}
if (!parent.info.canHaveProfile()) {
- Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
+ Slog.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
+ "created for the specified parent user id " + parentId);
return null;
}
@@ -3245,12 +3241,15 @@ public class UserManagerService extends IUserManager.Stub {
writeUserLP(userData);
}
updateUserIds();
+
Bundle restrictions = new Bundle();
- // TODO(b/142482943): Generalize this using UserTypeDetails default restrictions.
if (isGuest) {
+ // Guest default restrictions can be modified via setDefaultGuestRestrictions.
synchronized (mGuestRestrictions) {
restrictions.putAll(mGuestRestrictions);
}
+ } else {
+ userTypeDetails.addDefaultRestrictionsTo(restrictions);
}
synchronized (mRestrictionsLock) {
mBaseUserRestrictions.append(userId, restrictions);
@@ -3318,7 +3317,7 @@ public class UserManagerService extends IUserManager.Stub {
+ Integer.toHexString(preCreatedUser.flags) + ").");
return null;
}
- Log.i(LOG_TAG, "Reusing pre-created user " + preCreatedUser.id + " of type "
+ Slog.i(LOG_TAG, "Reusing pre-created user " + preCreatedUser.id + " of type "
+ userType + " and bestowing on it flags " + UserInfo.flagsToString(flags));
preCreatedUser.name = name;
preCreatedUser.flags = newFlags;
@@ -3483,7 +3482,7 @@ public class UserManagerService extends IUserManager.Stub {
checkManageUsersPermission("Only the system can remove users");
if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
UserManager.DISALLOW_REMOVE_USER, false)) {
- Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
+ Slog.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
return false;
}
@@ -3535,7 +3534,7 @@ public class UserManagerService extends IUserManager.Stub {
String restriction = isManagedProfile
? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
- Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
+ Slog.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
return false;
}
return removeUserUnchecked(userId);
@@ -3553,25 +3552,25 @@ public class UserManagerService extends IUserManager.Stub {
final UserData userData;
int currentUser = ActivityManager.getCurrentUser();
if (currentUser == userId) {
- Log.w(LOG_TAG, "Current user cannot be removed.");
+ Slog.w(LOG_TAG, "Current user cannot be removed.");
return false;
}
synchronized (mPackagesLock) {
synchronized (mUsersLock) {
userData = mUsers.get(userId);
if (userId == UserHandle.USER_SYSTEM) {
- Log.e(LOG_TAG, "System user cannot be removed.");
+ Slog.e(LOG_TAG, "System user cannot be removed.");
return false;
}
if (userData == null) {
- Log.e(LOG_TAG, String.format(
+ Slog.e(LOG_TAG, String.format(
"Cannot remove user %d, invalid user id provided.", userId));
return false;
}
if (mRemovingUserIds.get(userId)) {
- Log.e(LOG_TAG, String.format(
+ Slog.e(LOG_TAG, String.format(
"User %d is already scheduled for removal.", userId));
return false;
}
@@ -3591,7 +3590,7 @@ public class UserManagerService extends IUserManager.Stub {
try {
mAppOpsService.removeUser(userId);
} catch (RemoteException e) {
- Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user.", e);
+ Slog.w(LOG_TAG, "Unable to notify AppOpsService of removing user.", e);
}
// TODO(b/142482943): Send some sort of broadcast for profiles even if non-managed?
@@ -3616,7 +3615,7 @@ public class UserManagerService extends IUserManager.Stub {
}
});
} catch (RemoteException e) {
- Log.w(LOG_TAG, "Failed to stop user during removal.", e);
+ Slog.w(LOG_TAG, "Failed to stop user during removal.", e);
return false;
}
return res == ActivityManager.USER_OP_SUCCESS;
@@ -3828,7 +3827,7 @@ public class UserManagerService extends IUserManager.Stub {
readEntry(restrictions, values, parser);
}
} catch (IOException|XmlPullParserException e) {
- Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
+ Slog.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
} finally {
IoUtils.closeQuietly(fis);
}
@@ -4510,9 +4509,10 @@ public class UserManagerService extends IUserManager.Stub {
private class LocalService extends UserManagerInternal {
@Override
- public void setDevicePolicyUserRestrictions(@UserIdInt int userId,
- @Nullable Bundle restrictions, @OwnerType int restrictionOwnerType) {
- UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId,
+ public void setDevicePolicyUserRestrictions(@UserIdInt int originatingUserId,
+ @Nullable Bundle restrictions,
+ @OwnerType int restrictionOwnerType) {
+ UserManagerService.this.setDevicePolicyUserRestrictionsInner(originatingUserId,
restrictions, restrictionOwnerType);
}
@@ -4666,14 +4666,8 @@ public class UserManagerService extends IUserManager.Stub {
@Override
public UserInfo createUserEvenWhenDisallowed(String name, @NonNull String userType,
@UserInfoFlag int flags, String[] disallowedPackages) {
- UserInfo user = createUserInternalUnchecked(name, userType, flags,
+ return createUserInternalUnchecked(name, userType, flags,
UserHandle.USER_NULL, /* preCreated= */ false, disallowedPackages);
- // Keep this in sync with UserManager.createUser
- if (user != null && !user.isAdmin() && !user.isDemo()) {
- setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
- setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
- }
- return user;
}
@Override
@@ -4867,8 +4861,8 @@ public class UserManagerService extends IUserManager.Stub {
}
private static void debug(String message) {
- Log.d(LOG_TAG, message +
- (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
+ Slog.d(LOG_TAG, message
+ + (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
}
/** @see #getMaxUsersOfTypePerParent(UserTypeDetails) */
diff --git a/services/core/java/com/android/server/pm/UserRestrictionsUtils.java b/services/core/java/com/android/server/pm/UserRestrictionsUtils.java
index 0beff7a32bc1..90bd94781a1e 100644
--- a/services/core/java/com/android/server/pm/UserRestrictionsUtils.java
+++ b/services/core/java/com/android/server/pm/UserRestrictionsUtils.java
@@ -208,13 +208,6 @@ public class UserRestrictionsUtils {
);
/**
- * User restrictions that default to {@code true} for device owners.
- */
- private static final Set<String> DEFAULT_ENABLED_FOR_DEVICE_OWNERS = Sets.newArraySet(
- UserManager.DISALLOW_ADD_MANAGED_PROFILE
- );
-
- /**
* User restrictions that default to {@code true} for managed profile owners.
*
* NB: {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} is also set by default but it is
@@ -411,11 +404,10 @@ public class UserRestrictionsUtils {
}
/**
- * Returns the user restrictions that default to {@code true} for device owners.
- * These user restrictions are local, though. ie only for the device owner's user id.
+ * @return true if a restriction is settable by profile owner of an organization owned device.
*/
- public static @NonNull Set<String> getDefaultEnabledForDeviceOwner() {
- return DEFAULT_ENABLED_FOR_DEVICE_OWNERS;
+ public static boolean canProfileOwnerOfOrganizationOwnedDeviceChange(String restriction) {
+ return PROFILE_OWNER_ORGANIZATION_OWNED_GLOBAL_RESTRICTIONS.contains(restriction);
}
/**
diff --git a/services/core/java/com/android/server/pm/UserSystemPackageInstaller.java b/services/core/java/com/android/server/pm/UserSystemPackageInstaller.java
index c36b9938a8cd..77bb48eadc41 100644
--- a/services/core/java/com/android/server/pm/UserSystemPackageInstaller.java
+++ b/services/core/java/com/android/server/pm/UserSystemPackageInstaller.java
@@ -67,10 +67,11 @@ import java.util.Set;
* then:
* <ul>
* <li>If {@link #isImplicitWhitelistMode()}, the package is implicitly treated as whitelisted
- * for all users</li>
- * <li>Otherwise, the package is implicitly treated as blacklisted for all non-SYSTEM users</li>
- * <li>Either way, for {@link UserHandle#USER_SYSTEM}, the package will be implicitly
- * whitelisted so that it can be used for local development purposes.</li>
+ * for <b>all</b> users</li>
+ * <li>Otherwise, if {@link #isImplicitWhitelistSystemMode()}, the package is implicitly treated
+ * as whitelisted for the <b>{@link UserHandle#USER_SYSTEM}</b> user (not other users),
+ * which is useful for local development purposes</li>
+ * <li>Otherwise, the package is implicitly treated as blacklisted for all users</li>
* </ul>
*
* <p><b>NOTE:</b> the {@code SystemConfig} state is only updated on first boot or after a system
@@ -86,22 +87,24 @@ class UserSystemPackageInstaller {
* System Property whether to only install system packages on a user if they're whitelisted for
* that user type. These are flags and can be freely combined.
* <ul>
- * <li> 0 (0b0000) - disable whitelist (install all system packages; no logging)</li>
- * <li> 1 (0b0001) - enforce (only install system packages if they are whitelisted)</li>
- * <li> 2 (0b0010) - log (log when a non-whitelisted package is run)</li>
- * <li> 4 (0b0100) - implicitly whitelist any package not mentioned in the whitelist</li>
- * <li> 8 (0b1000) - ignore OTAs (don't install system packages during OTAs)</li>
- * <li>-1 - use device default (as defined in res/res/values/config.xml)</li>
+ * <li> 0 - disable whitelist (install all system packages; no logging)</li>
+ * <li> 1 - enforce (only install system packages if they are whitelisted)</li>
+ * <li> 2 - log (log when a non-whitelisted package is run)</li>
+ * <li> 4 - for all users: implicitly whitelist any package not mentioned in the whitelist</li>
+ * <li> 8 - for SYSTEM: implicitly whitelist any package not mentioned in the whitelist</li>
+ * <li> 16 - ignore OTAs (don't install system packages during OTAs)</li>
+ * <li>-1 - use device default (as defined in res/res/values/config.xml)</li>
* </ul>
* Note: This list must be kept current with config_userTypePackageWhitelistMode in
* frameworks/base/core/res/res/values/config.xml
*/
static final String PACKAGE_WHITELIST_MODE_PROP = "persist.debug.user.package_whitelist_mode";
- static final int USER_TYPE_PACKAGE_WHITELIST_MODE_DISABLE = 0;
- static final int USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE = 0b0001;
- static final int USER_TYPE_PACKAGE_WHITELIST_MODE_LOG = 0b0010;
- static final int USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST = 0b0100;
- static final int USER_TYPE_PACKAGE_WHITELIST_MODE_IGNORE_OTA = 0b1000;
+ static final int USER_TYPE_PACKAGE_WHITELIST_MODE_DISABLE = 0x00;
+ static final int USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE = 0x01;
+ static final int USER_TYPE_PACKAGE_WHITELIST_MODE_LOG = 0x02;
+ static final int USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST = 0x04;
+ static final int USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST_SYSTEM = 0x08;
+ static final int USER_TYPE_PACKAGE_WHITELIST_MODE_IGNORE_OTA = 0x10;
static final int USER_TYPE_PACKAGE_WHITELIST_MODE_DEVICE_DEFAULT = -1;
@IntDef(flag = true, prefix = "USER_TYPE_PACKAGE_WHITELIST_MODE_", value = {
@@ -281,6 +284,14 @@ class UserSystemPackageInstaller {
return isImplicitWhitelistMode(getWhitelistMode());
}
+ /**
+ * Whether to treat all packages that are not mentioned at all in the whitelist to be implicitly
+ * whitelisted for the SYSTEM user.
+ */
+ boolean isImplicitWhitelistSystemMode() {
+ return isImplicitWhitelistSystemMode(getWhitelistMode());
+ }
+
/** See {@link #isEnforceMode()}. */
private static boolean isEnforceMode(int whitelistMode) {
return (whitelistMode & USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE) != 0;
@@ -301,6 +312,11 @@ class UserSystemPackageInstaller {
return (whitelistMode & USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST) != 0;
}
+ /** See {@link #isImplicitWhitelistSystemMode()}. */
+ private static boolean isImplicitWhitelistSystemMode(int whitelistMode) {
+ return (whitelistMode & USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST_SYSTEM) != 0;
+ }
+
/** Gets the PackageWhitelistMode for use of {@link #mWhitelistedPackagesForUserTypes}. */
private @PackageWhitelistMode int getWhitelistMode() {
final int runtimeMode = SystemProperties.getInt(
@@ -332,8 +348,8 @@ class UserSystemPackageInstaller {
if (!isEnforceMode(mode)) {
return null;
}
- final boolean isSystemUser = mUm.isUserTypeSubtypeOfSystem(userType);
- final boolean isImplicitWhitelistMode = isImplicitWhitelistMode(mode);
+ final boolean implicitlyWhitelist = isImplicitWhitelistMode(mode)
+ || (isImplicitWhitelistSystemMode(mode) && mUm.isUserTypeSubtypeOfSystem(userType));
final Set<String> whitelistedPackages = getWhitelistedPackagesForUserType(userType);
final Set<String> installPackages = new ArraySet<>();
@@ -343,7 +359,7 @@ class UserSystemPackageInstaller {
return;
}
if (shouldInstallPackage(pkg, mWhitelistedPackagesForUserTypes,
- whitelistedPackages, isImplicitWhitelistMode, isSystemUser)) {
+ whitelistedPackages, implicitlyWhitelist)) {
// Although the whitelist uses manifest names, this function returns packageNames.
installPackages.add(pkg.getPackageName());
}
@@ -360,31 +376,18 @@ class UserSystemPackageInstaller {
* installed. This is only used for overriding the userWhitelist in
* certain situations (based on its keyset).
* @param userWhitelist set of package manifest names that should be installed on this
- * particular user. This must be consistent with userTypeWhitelist, but is
- * passed in separately to avoid repeatedly calculating it from
+ * <b>particular</b> user. This must be consistent with userTypeWhitelist,
+ * but is passed in separately to avoid repeatedly calculating it from
* userTypeWhitelist.
- * @param isImplicitWhitelistMode whether non-mentioned packages are implicitly whitelisted.
- * @param isSystemUser whether the user is USER_SYSTEM (which gets special treatment).
+ * @param implicitlyWhitelist whether non-mentioned packages are implicitly whitelisted.
*/
@VisibleForTesting
static boolean shouldInstallPackage(AndroidPackage sysPkg,
@NonNull ArrayMap<String, Long> userTypeWhitelist,
- @NonNull Set<String> userWhitelist, boolean isImplicitWhitelistMode,
- boolean isSystemUser) {
-
+ @NonNull Set<String> userWhitelist, boolean implicitlyWhitelist) {
final String pkgName = sysPkg.getManifestPackageName();
- boolean install = (isImplicitWhitelistMode && !userTypeWhitelist.containsKey(pkgName))
+ return (implicitlyWhitelist && !userTypeWhitelist.containsKey(pkgName))
|| userWhitelist.contains(pkgName);
-
- // For the purposes of local development, any package that isn't even mentioned in the
- // whitelist at all is implicitly treated as whitelisted for the SYSTEM user.
- if (!install && isSystemUser && !userTypeWhitelist.containsKey(pkgName)) {
- install = true;
- Slog.e(TAG, "System package " + pkgName + " is not mentioned "
- + "in SystemConfig's 'install-in-user-type' but we are "
- + "implicitly treating it as whitelisted for the SYSTEM user.");
- }
- return install;
}
/**
diff --git a/services/core/java/com/android/server/pm/UserTypeDetails.java b/services/core/java/com/android/server/pm/UserTypeDetails.java
index 1631df33587f..826cd3f75222 100644
--- a/services/core/java/com/android/server/pm/UserTypeDetails.java
+++ b/services/core/java/com/android/server/pm/UserTypeDetails.java
@@ -19,18 +19,17 @@ package com.android.server.pm;
import android.annotation.ColorRes;
import android.annotation.DrawableRes;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.annotation.StringRes;
import android.content.pm.UserInfo;
import android.content.pm.UserInfo.UserInfoFlag;
import android.content.res.Resources;
+import android.os.Bundle;
import android.os.UserManager;
import com.android.internal.util.Preconditions;
import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
/**
* Contains the details about a multiuser "user type", such as a
@@ -75,8 +74,13 @@ public final class UserTypeDetails {
/** The {@link UserInfo.UserInfoFlag}s that all users of this type will automatically have. */
private final @UserInfoFlag int mDefaultUserInfoPropertyFlags;
- // TODO(b/142482943): Hook these up to something and set them for each type.
- private final List<String> mDefaultRestrictions;
+ /**
+ * List of User Restrictions to apply by default to newly created users of this type.
+ * <p>Does not apply to SYSTEM users (since they are not formally created); for them use
+ * {@link com.android.internal.R.array#config_defaultFirstUserRestrictions} instead.
+ * The Bundle is of the form used by {@link UserRestrictionsUtils}.
+ */
+ private final @Nullable Bundle mDefaultRestrictions;
// Fields for profiles only, controlling the nature of their badges.
@@ -99,7 +103,7 @@ public final class UserTypeDetails {
*
* <p>Must be set if mIconBadge is set.
*/
- private final int[] mBadgeLabels;
+ private final @Nullable int[] mBadgeLabels;
/**
* Resource ID ({@link ColorRes}) of the colors badge put on icons.
@@ -110,22 +114,21 @@ public final class UserTypeDetails {
*
* <p>Must be set if mIconBadge is set.
*/
- private final int[] mBadgeColors;
+ private final @Nullable int[] mBadgeColors;
private UserTypeDetails(@NonNull String name, boolean enabled, int maxAllowed,
@UserInfoFlag int baseType, @UserInfoFlag int defaultUserInfoPropertyFlags, int label,
int maxAllowedPerParent,
int iconBadge, int badgePlain, int badgeNoBackground,
- int[] badgeLabels, int[] badgeColors,
- ArrayList<String> defaultRestrictions) {
+ @Nullable int[] badgeLabels, @Nullable int[] badgeColors,
+ @Nullable Bundle defaultRestrictions) {
this.mName = name;
this.mEnabled = enabled;
this.mMaxAllowed = maxAllowed;
this.mMaxAllowedPerParent = maxAllowedPerParent;
this.mBaseType = baseType;
this.mDefaultUserInfoPropertyFlags = defaultUserInfoPropertyFlags;
- this.mDefaultRestrictions =
- Collections.unmodifiableList(new ArrayList<>(defaultRestrictions));
+ this.mDefaultRestrictions = defaultRestrictions;
this.mIconBadge = iconBadge;
this.mBadgePlain = badgePlain;
@@ -180,7 +183,7 @@ public final class UserTypeDetails {
return mIconBadge != Resources.ID_NULL;
}
- /** Resource ID of the badge put on icons. */
+ /** Resource ID of the badge to put on icons. */
public @DrawableRes int getIconBadge() {
return mIconBadge;
}
@@ -231,9 +234,14 @@ public final class UserTypeDetails {
return (mBaseType & UserInfo.FLAG_SYSTEM) != 0;
}
- // TODO(b/142482943): Hook this up and don't return the original.
- public List<String> getDefaultRestrictions() {
- return mDefaultRestrictions;
+ /** Returns a Bundle representing the default user restrictions. */
+ @NonNull Bundle getDefaultRestrictions() {
+ return UserRestrictionsUtils.clone(mDefaultRestrictions);
+ }
+
+ /** Adds the default user restrictions to the given bundle of restrictions. */
+ public void addDefaultRestrictionsTo(@NonNull Bundle currentRestrictions) {
+ UserRestrictionsUtils.merge(currentRestrictions, mDefaultRestrictions);
}
/** Dumps details of the UserTypeDetails. Do not parse this. */
@@ -247,7 +255,8 @@ public final class UserTypeDetails {
pw.print(prefix); pw.print("mDefaultUserInfoFlags: ");
pw.println(UserInfo.flagsToString(mDefaultUserInfoPropertyFlags));
pw.print(prefix); pw.print("mLabel: "); pw.println(mLabel);
- pw.print(prefix); pw.print("mDefaultRestrictions: "); pw.println(mDefaultRestrictions);
+ pw.print(prefix); pw.println("mDefaultRestrictions: ");
+ UserRestrictionsUtils.dumpRestrictions(pw, prefix + " ", mDefaultRestrictions);
pw.print(prefix); pw.print("mIconBadge: "); pw.println(mIconBadge);
pw.print(prefix); pw.print("mBadgePlain: "); pw.println(mBadgePlain);
pw.print(prefix); pw.print("mBadgeNoBackground: "); pw.println(mBadgeNoBackground);
@@ -265,14 +274,14 @@ public final class UserTypeDetails {
private int mMaxAllowed = UNLIMITED_NUMBER_OF_USERS;
private int mMaxAllowedPerParent = UNLIMITED_NUMBER_OF_USERS;
private int mDefaultUserInfoPropertyFlags = 0;
- private ArrayList<String> mDefaultRestrictions = new ArrayList<>();
+ private @Nullable Bundle mDefaultRestrictions = null;
private boolean mEnabled = true;
private int mLabel = Resources.ID_NULL;
- private int[] mBadgeLabels = null;
- private int[] mBadgeColors = null;
- private int mIconBadge = Resources.ID_NULL;
- private int mBadgePlain = Resources.ID_NULL;
- private int mBadgeNoBackground = Resources.ID_NULL;
+ private @Nullable int[] mBadgeLabels = null;
+ private @Nullable int[] mBadgeColors = null;
+ private @DrawableRes int mIconBadge = Resources.ID_NULL;
+ private @DrawableRes int mBadgePlain = Resources.ID_NULL;
+ private @DrawableRes int mBadgeNoBackground = Resources.ID_NULL;
public Builder setName(String name) {
mName = name;
@@ -304,27 +313,27 @@ public final class UserTypeDetails {
return this;
}
- public Builder setBadgeLabels(int ... badgeLabels) {
+ public Builder setBadgeLabels(@StringRes int ... badgeLabels) {
mBadgeLabels = badgeLabels;
return this;
}
- public Builder setBadgeColors(int ... badgeColors) {
+ public Builder setBadgeColors(@ColorRes int ... badgeColors) {
mBadgeColors = badgeColors;
return this;
}
- public Builder setIconBadge(int badgeIcon) {
+ public Builder setIconBadge(@DrawableRes int badgeIcon) {
mIconBadge = badgeIcon;
return this;
}
- public Builder setBadgePlain(int badgePlain) {
+ public Builder setBadgePlain(@DrawableRes int badgePlain) {
mBadgePlain = badgePlain;
return this;
}
- public Builder setBadgeNoBackground(int badgeNoBackground) {
+ public Builder setBadgeNoBackground(@DrawableRes int badgeNoBackground) {
mBadgeNoBackground = badgeNoBackground;
return this;
}
@@ -334,11 +343,15 @@ public final class UserTypeDetails {
return this;
}
- public Builder setDefaultRestrictions(ArrayList<String> restrictions) {
+ public Builder setDefaultRestrictions(@Nullable Bundle restrictions) {
mDefaultRestrictions = restrictions;
return this;
}
+ @UserInfoFlag int getBaseType() {
+ return mBaseType;
+ }
+
public UserTypeDetails createUserTypeDetails() {
Preconditions.checkArgument(mName != null,
"Cannot create a UserTypeDetails with no name.");
diff --git a/services/core/java/com/android/server/pm/UserTypeFactory.java b/services/core/java/com/android/server/pm/UserTypeFactory.java
index 43bbab192722..7d45516bdefc 100644
--- a/services/core/java/com/android/server/pm/UserTypeFactory.java
+++ b/services/core/java/com/android/server/pm/UserTypeFactory.java
@@ -34,18 +34,36 @@ import static android.os.UserManager.USER_TYPE_SYSTEM_HEADLESS;
import static com.android.server.pm.UserTypeDetails.UNLIMITED_NUMBER_OF_USERS;
+import android.content.pm.UserInfo;
import android.content.res.Resources;
+import android.content.res.XmlResourceParser;
+import android.os.Bundle;
import android.os.UserManager;
import android.util.ArrayMap;
+import android.util.Slog;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.util.XmlUtils;
+
+import org.xmlpull.v1.XmlPullParserException;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.function.Consumer;
/**
* Class for creating all {@link UserTypeDetails} on the device.
*
+ * This class is responsible both for defining the AOSP use types, as well as reading in customized
+ * user types from {@link com.android.internal.R.xml#config_user_types}.
+ *
* Tests are located in UserManagerServiceUserTypeTest.java.
* @hide
*/
public final class UserTypeFactory {
+ private static final String LOG_TAG = "UserTypeFactory";
+
/** This is a utility class, so no instantiable constructor. */
private UserTypeFactory() {}
@@ -55,21 +73,25 @@ public final class UserTypeFactory {
* @return mapping from the name of each user type to its {@link UserTypeDetails} object
*/
public static ArrayMap<String, UserTypeDetails> getUserTypes() {
- final ArrayMap<String, UserTypeDetails> map = new ArrayMap<>();
- // TODO(b/142482943): Read an xml file for OEM customized types.
- // Remember to disallow "android." namespace
- // TODO(b/142482943): Read an xml file to get any overrides for the built-in types.
- final int maxManagedProfiles = 1;
- map.put(USER_TYPE_PROFILE_MANAGED,
- getDefaultTypeProfileManaged().setMaxAllowedPerParent(maxManagedProfiles)
- .createUserTypeDetails());
- map.put(USER_TYPE_FULL_SYSTEM, getDefaultTypeSystemFull().createUserTypeDetails());
- map.put(USER_TYPE_FULL_SECONDARY, getDefaultTypeFullSecondary().createUserTypeDetails());
- map.put(USER_TYPE_FULL_GUEST, getDefaultTypeFullGuest().createUserTypeDetails());
- map.put(USER_TYPE_FULL_DEMO, getDefaultTypeFullDemo().createUserTypeDetails());
- map.put(USER_TYPE_FULL_RESTRICTED, getDefaultTypeFullRestricted().createUserTypeDetails());
- map.put(USER_TYPE_SYSTEM_HEADLESS, getDefaultTypeSystemHeadless().createUserTypeDetails());
- return map;
+ final ArrayMap<String, UserTypeDetails.Builder> builders = new ArrayMap<>();
+ builders.put(USER_TYPE_PROFILE_MANAGED, getDefaultTypeProfileManaged());
+ builders.put(USER_TYPE_FULL_SYSTEM, getDefaultTypeFullSystem());
+ builders.put(USER_TYPE_FULL_SECONDARY, getDefaultTypeFullSecondary());
+ builders.put(USER_TYPE_FULL_GUEST, getDefaultTypeFullGuest());
+ builders.put(USER_TYPE_FULL_DEMO, getDefaultTypeFullDemo());
+ builders.put(USER_TYPE_FULL_RESTRICTED, getDefaultTypeFullRestricted());
+ builders.put(USER_TYPE_SYSTEM_HEADLESS, getDefaultTypeSystemHeadless());
+
+ try (XmlResourceParser parser =
+ Resources.getSystem().getXml(com.android.internal.R.xml.config_user_types)) {
+ customizeBuilders(builders, parser);
+ }
+
+ final ArrayMap<String, UserTypeDetails> types = new ArrayMap<>(builders.size());
+ for (int i = 0; i < builders.size(); i++) {
+ types.put(builders.keyAt(i), builders.valueAt(i).createUserTypeDetails());
+ }
+ return types;
}
/**
@@ -93,7 +115,8 @@ public final class UserTypeFactory {
.setBadgeColors(
com.android.internal.R.color.profile_badge_1,
com.android.internal.R.color.profile_badge_2,
- com.android.internal.R.color.profile_badge_3);
+ com.android.internal.R.color.profile_badge_3)
+ .setDefaultRestrictions(null);
}
/**
@@ -104,7 +127,8 @@ public final class UserTypeFactory {
return new UserTypeDetails.Builder()
.setName(USER_TYPE_FULL_SECONDARY)
.setBaseType(FLAG_FULL)
- .setMaxAllowed(UNLIMITED_NUMBER_OF_USERS);
+ .setMaxAllowed(UNLIMITED_NUMBER_OF_USERS)
+ .setDefaultRestrictions(getDefaultSecondaryUserRestrictions());
}
/**
@@ -115,13 +139,12 @@ public final class UserTypeFactory {
.getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
final int flags = FLAG_GUEST | (ephemeralGuests ? FLAG_EPHEMERAL : 0);
- // TODO(b/142482943): Put UMS.initDefaultGuestRestrictions() here; then fetch them from here
-
return new UserTypeDetails.Builder()
.setName(USER_TYPE_FULL_GUEST)
.setBaseType(FLAG_FULL)
.setDefaultUserInfoPropertyFlags(flags)
- .setMaxAllowed(1);
+ .setMaxAllowed(1)
+ .setDefaultRestrictions(getDefaultGuestUserRestrictions());
}
/**
@@ -132,7 +155,8 @@ public final class UserTypeFactory {
.setName(USER_TYPE_FULL_DEMO)
.setBaseType(FLAG_FULL)
.setDefaultUserInfoPropertyFlags(FLAG_DEMO)
- .setMaxAllowed(UNLIMITED_NUMBER_OF_USERS);
+ .setMaxAllowed(UNLIMITED_NUMBER_OF_USERS)
+ .setDefaultRestrictions(null);
}
/**
@@ -144,13 +168,15 @@ public final class UserTypeFactory {
.setName(USER_TYPE_FULL_RESTRICTED)
.setBaseType(FLAG_FULL)
.setDefaultUserInfoPropertyFlags(FLAG_RESTRICTED)
- .setMaxAllowed(UNLIMITED_NUMBER_OF_USERS);
+ .setMaxAllowed(UNLIMITED_NUMBER_OF_USERS)
+ // NB: UserManagerService.createRestrictedProfile() applies hardcoded restrictions.
+ .setDefaultRestrictions(null);
}
/**
* Returns the Builder for the default {@link UserManager#USER_TYPE_FULL_SYSTEM} configuration.
*/
- private static UserTypeDetails.Builder getDefaultTypeSystemFull() {
+ private static UserTypeDetails.Builder getDefaultTypeFullSystem() {
return new UserTypeDetails.Builder()
.setName(USER_TYPE_FULL_SYSTEM)
.setBaseType(FLAG_SYSTEM | FLAG_FULL);
@@ -165,4 +191,193 @@ public final class UserTypeFactory {
.setName(USER_TYPE_SYSTEM_HEADLESS)
.setBaseType(FLAG_SYSTEM);
}
+
+ private static Bundle getDefaultSecondaryUserRestrictions() {
+ final Bundle restrictions = new Bundle();
+ restrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
+ restrictions.putBoolean(UserManager.DISALLOW_SMS, true);
+ return restrictions;
+ }
+
+ private static Bundle getDefaultGuestUserRestrictions() {
+ // Guest inherits the secondary user's restrictions, plus has some extra ones.
+ final Bundle restrictions = getDefaultSecondaryUserRestrictions();
+ restrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
+ restrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
+ return restrictions;
+ }
+
+ /**
+ * Reads the given xml parser to obtain device user-type customization, and updates the given
+ * map of {@link UserTypeDetails.Builder}s accordingly.
+ * <p>
+ * The xml file can specify the attributes according to the set... methods below.
+ */
+ @VisibleForTesting
+ static void customizeBuilders(ArrayMap<String, UserTypeDetails.Builder> builders,
+ XmlResourceParser parser) {
+ try {
+ XmlUtils.beginDocument(parser, "user-types");
+ for (XmlUtils.nextElement(parser);
+ parser.getEventType() != XmlResourceParser.END_DOCUMENT;
+ XmlUtils.nextElement(parser)) {
+ final boolean isProfile;
+ final String elementName = parser.getName();
+ if ("profile-type".equals(elementName)) {
+ isProfile = true;
+ } else if ("full-type".equals(elementName)) {
+ isProfile = false;
+ } else {
+ Slog.w(LOG_TAG, "Skipping unknown element " + elementName + " in "
+ + parser.getPositionDescription());
+ XmlUtils.skipCurrentTag(parser);
+ continue;
+ }
+
+ String typeName = parser.getAttributeValue(null, "name");
+ if (typeName == null) {
+ Slog.w(LOG_TAG, "Skipping user type with no name in "
+ + parser.getPositionDescription());
+ XmlUtils.skipCurrentTag(parser);
+ continue;
+ }
+ typeName.intern();
+
+ UserTypeDetails.Builder builder;
+ if (typeName.startsWith("android.")) {
+ // typeName refers to a AOSP-defined type which we are modifying.
+ Slog.i(LOG_TAG, "Customizing user type " + typeName);
+ builder = builders.get(typeName);
+ if (builder == null) {
+ throw new IllegalArgumentException("Illegal custom user type name "
+ + typeName + ": Non-AOSP user types cannot start with 'android.'");
+ }
+ final boolean isValid =
+ (isProfile && builder.getBaseType() == UserInfo.FLAG_PROFILE)
+ || (!isProfile && builder.getBaseType() == UserInfo.FLAG_FULL);
+ if (!isValid) {
+ throw new IllegalArgumentException("Wrong base type to customize user type "
+ + "(" + typeName + "), which is type "
+ + UserInfo.flagsToString(builder.getBaseType()));
+ }
+ } else if (isProfile) {
+ // typeName refers to a new OEM-defined profile type which we are defining.
+ Slog.i(LOG_TAG, "Creating custom user type " + typeName);
+ builder = new UserTypeDetails.Builder();
+ builder.setName(typeName);
+ builder.setBaseType(FLAG_PROFILE);
+ builders.put(typeName, builder);
+ } else {
+ throw new IllegalArgumentException("Creation of non-profile user type "
+ + "(" + typeName + ") is not currently supported.");
+ }
+
+ // Process the attributes (other than name).
+ if (isProfile) {
+ setIntAttribute(parser, "max-allowed-per-parent",
+ builder::setMaxAllowedPerParent);
+ setResAttribute(parser, "icon-badge", builder::setIconBadge);
+ setResAttribute(parser, "badge-plain", builder::setBadgePlain);
+ setResAttribute(parser, "badge-no-background", builder::setBadgeNoBackground);
+ }
+
+ // Process child elements.
+ final int depth = parser.getDepth();
+ while (XmlUtils.nextElementWithin(parser, depth)) {
+ final String childName = parser.getName();
+ if ("default-restrictions".equals(childName)) {
+ final Bundle restrictions = UserRestrictionsUtils.readRestrictions(parser);
+ builder.setDefaultRestrictions(restrictions);
+ } else if (isProfile && "badge-labels".equals(childName)) {
+ setResAttributeArray(parser, builder::setBadgeLabels);
+ } else if (isProfile && "badge-colors".equals(childName)) {
+ setResAttributeArray(parser, builder::setBadgeColors);
+ } else {
+ Slog.w(LOG_TAG, "Unrecognized tag " + childName + " in "
+ + parser.getPositionDescription());
+ }
+ }
+ }
+ } catch (XmlPullParserException | IOException e) {
+ Slog.w(LOG_TAG, "Cannot read user type configuration file.", e);
+ }
+ }
+
+ /**
+ * If the given attribute exists, gets the int stored in it and performs the given fcn using it.
+ * The stored value must be an int or NumberFormatException will be thrown.
+ *
+ * @param parser xml parser from which to read the attribute
+ * @param attributeName name of the attribute
+ * @param fcn one-int-argument function,
+ * like {@link UserTypeDetails.Builder#setMaxAllowedPerParent(int)}
+ */
+ private static void setIntAttribute(XmlResourceParser parser, String attributeName,
+ Consumer<Integer> fcn) {
+ final String intValue = parser.getAttributeValue(null, attributeName);
+ if (intValue == null) {
+ return;
+ }
+ try {
+ fcn.accept(Integer.parseInt(intValue));
+ } catch (NumberFormatException e) {
+ Slog.e(LOG_TAG, "Cannot parse value of '" + intValue + "' for " + attributeName
+ + " in " + parser.getPositionDescription(), e);
+ throw e;
+ }
+ }
+
+ /**
+ * If the given attribute exists, gets the resId stored in it (or 0 if it is not a valid resId)
+ * and performs the given fcn using it.
+ *
+ * @param parser xml parser from which to read the attribute
+ * @param attributeName name of the attribute
+ * @param fcn one-argument function, like {@link UserTypeDetails.Builder#setIconBadge(int)}
+ */
+ private static void setResAttribute(XmlResourceParser parser, String attributeName,
+ Consumer<Integer> fcn) {
+ if (parser.getAttributeValue(null, attributeName) == null) {
+ // Attribute is not present, i.e. use the default value.
+ return;
+ }
+ final int resId = parser.getAttributeResourceValue(null, attributeName, Resources.ID_NULL);
+ fcn.accept(resId);
+ }
+
+ /**
+ * Gets the resIds stored in "item" elements (in their "res" attribute) at the current depth.
+ * Then performs the given fcn using the int[] array of these resIds.
+ * <p>
+ * Each xml element is expected to be of the form {@code <item res="someResValue" />}.
+ *
+ * @param parser xml parser from which to read the elements and their attributes
+ * @param fcn function, like {@link UserTypeDetails.Builder#setBadgeColors(int...)}
+ */
+ private static void setResAttributeArray(XmlResourceParser parser, Consumer<int[]> fcn)
+ throws IOException, XmlPullParserException {
+
+ ArrayList<Integer> resList = new ArrayList<>();
+ final int depth = parser.getDepth();
+ while (XmlUtils.nextElementWithin(parser, depth)) {
+ final String elementName = parser.getName();
+ if (!"item".equals(elementName)) {
+ Slog.w(LOG_TAG, "Skipping unknown child element " + elementName + " in "
+ + parser.getPositionDescription());
+ XmlUtils.skipCurrentTag(parser);
+ continue;
+ }
+ final int resId = parser.getAttributeResourceValue(null, "res", -1);
+ if (resId == -1) {
+ continue;
+ }
+ resList.add(resId);
+ }
+
+ int[] result = new int[resList.size()];
+ for (int i = 0; i < resList.size(); i++) {
+ result[i] = resList.get(i);
+ }
+ fcn.accept(result);
+ }
}
diff --git a/services/core/java/com/android/server/pm/permission/BasePermission.java b/services/core/java/com/android/server/pm/permission/BasePermission.java
index 9668c21d0fab..05545cdbe50a 100644
--- a/services/core/java/com/android/server/pm/permission/BasePermission.java
+++ b/services/core/java/com/android/server/pm/permission/BasePermission.java
@@ -115,6 +115,12 @@ public final class BasePermission {
protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
}
+ @Override
+ public String toString() {
+ return "BasePermission{" + Integer.toHexString(System.identityHashCode(this)) + " " + name
+ + "}";
+ }
+
public String getName() {
return name;
}
@@ -170,7 +176,8 @@ public final class BasePermission {
if (this.perm == null) {
return false;
}
- return Objects.equals(this.perm.className, perm.className);
+ return Objects.equals(this.perm.getPackageName(), perm.getPackageName())
+ && Objects.equals(this.perm.className, perm.className);
}
public boolean isDynamic() {
@@ -406,7 +413,8 @@ public final class BasePermission {
r.append("DUP:");
r.append(p.getName());
}
- if (bp.perm != null && Objects.equals(bp.perm.className, p.className)) {
+ if (bp.perm != null && Objects.equals(bp.perm.getPackageName(), p.getPackageName())
+ && Objects.equals(bp.perm.className, p.className)) {
bp.protectionLevel = p.protectionLevel;
}
if (PackageManagerService.DEBUG_PACKAGE_SCANNING && r != null) {
@@ -643,20 +651,4 @@ public final class BasePermission {
}
return true;
}
-
- @Override
- public String toString() {
- return "BasePermission{" +
- "name='" + name + '\'' +
- ", type=" + type +
- ", sourcePackageName='" + sourcePackageName + '\'' +
- ", sourcePackageSetting=" + sourcePackageSetting +
- ", protectionLevel=" + protectionLevel +
- ", perm=" + perm +
- ", pendingPermissionInfo=" + pendingPermissionInfo +
- ", uid=" + uid +
- ", gids=" + Arrays.toString(gids) +
- ", perUser=" + perUser +
- '}';
- }
}
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
index 5adb64876ad4..8ce1a52afd0c 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
@@ -321,7 +321,10 @@ public class PermissionManagerService extends IPermissionManager.Stub {
public void onPermissionUpdatedNotifyListener(@UserIdInt int[] updatedUserIds, boolean sync,
int uid) {
onPermissionUpdated(updatedUserIds, sync);
- mOnPermissionChangeListeners.onPermissionsChanged(uid);
+ for (int i = 0; i < updatedUserIds.length; i++) {
+ int userUid = UserHandle.getUid(updatedUserIds[i], UserHandle.getAppId(uid));
+ mOnPermissionChangeListeners.onPermissionsChanged(userUid);
+ }
}
public void onInstallPermissionUpdatedNotifyListener(int uid) {
onInstallPermissionUpdated();
@@ -733,7 +736,8 @@ public class PermissionManagerService extends IPermissionManager.Stub {
// Install and runtime permissions are stored in different places,
// so figure out what permission changed and persist the change.
if (permissionsState.getInstallPermissionState(permName) != null) {
- callback.onInstallPermissionUpdatedNotifyListener(pkg.getUid());
+ int userUid = UserHandle.getUid(userId, UserHandle.getAppId(pkg.getUid()));
+ callback.onInstallPermissionUpdatedNotifyListener(userUid);
} else if (permissionsState.getRuntimePermissionState(permName, userId) != null
|| hadState) {
callback.onPermissionUpdatedNotifyListener(new int[]{userId}, false,
diff --git a/services/core/java/com/android/server/policy/PermissionPolicyService.java b/services/core/java/com/android/server/policy/PermissionPolicyService.java
index 5f39f51f9a42..b1feb148e5b3 100644
--- a/services/core/java/com/android/server/policy/PermissionPolicyService.java
+++ b/services/core/java/com/android/server/policy/PermissionPolicyService.java
@@ -677,10 +677,19 @@ public final class PermissionPolicyService extends SystemService {
private void setUidMode(int opCode, int uid, int mode,
@NonNull String packageName) {
- final int currentMode = mAppOpsManager.unsafeCheckOpRaw(AppOpsManager
- .opToPublicName(opCode), uid, packageName);
- if (currentMode != mode) {
+ final int oldMode = mAppOpsManager.unsafeCheckOpRaw(AppOpsManager.opToPublicName(
+ opCode), uid, packageName);
+ if (oldMode != mode) {
mAppOpsManager.setUidMode(opCode, uid, mode);
+ final int newMode = mAppOpsManager.unsafeCheckOpRaw(AppOpsManager.opToPublicName(
+ opCode), uid, packageName);
+ if (newMode != mode) {
+ // Work around incorrectly-set package mode. It never makes sense for app ops
+ // related to runtime permissions, but can get in the way and we have to reset
+ // it.
+ mAppOpsManager.setMode(opCode, uid, packageName, AppOpsManager.opToDefaultMode(
+ opCode));
+ }
}
}
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index 8435a8202762..0d8f25766e1f 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -157,6 +157,7 @@ import android.os.ServiceManager;
import android.os.StrictMode;
import android.os.SystemClock;
import android.os.SystemProperties;
+import android.os.Trace;
import android.os.UEventObserver;
import android.os.UserHandle;
import android.os.VibrationEffect;
@@ -4603,6 +4604,7 @@ public class PhoneWindowManager implements WindowManagerPolicy {
public void screenTurningOn(final ScreenOnListener screenOnListener) {
if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turning on...");
+ Trace.asyncTraceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "screenTurningOn", 0 /* cookie */);
updateScreenOffSleepToken(false);
mDefaultDisplayPolicy.screenTurnedOn(screenOnListener);
@@ -4665,6 +4667,7 @@ public class PhoneWindowManager implements WindowManagerPolicy {
if (!mDefaultDisplayPolicy.finishScreenTurningOn()) {
return; // Spurious or not ready yet.
}
+ Trace.asyncTraceEnd(Trace.TRACE_TAG_WINDOW_MANAGER, "screenTurningOn", 0 /* cookie */);
final boolean enableScreen;
final boolean awake = mDefaultDisplayPolicy.isAwake();
@@ -4949,6 +4952,7 @@ public class PhoneWindowManager implements WindowManagerPolicy {
mBootMsgDialog.getWindow().setDimAmount(1);
WindowManager.LayoutParams lp = mBootMsgDialog.getWindow().getAttributes();
lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
+ lp.setFitWindowInsetsTypes(0 /* types */);
mBootMsgDialog.getWindow().setAttributes(lp);
mBootMsgDialog.setCancelable(false);
mBootMsgDialog.show();
diff --git a/services/core/java/com/android/server/policy/WindowManagerPolicy.java b/services/core/java/com/android/server/policy/WindowManagerPolicy.java
index 95a5f52e5efb..a2425a349b7c 100644
--- a/services/core/java/com/android/server/policy/WindowManagerPolicy.java
+++ b/services/core/java/com/android/server/policy/WindowManagerPolicy.java
@@ -18,6 +18,7 @@ package com.android.server.policy;
import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW;
import static android.view.WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
+import static android.view.WindowManager.LayoutParams.TYPE_ACCESSIBILITY_MAGNIFICATION_OVERLAY;
import static android.view.WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_ABOVE_SUB_PANEL;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
@@ -272,14 +273,6 @@ public interface WindowManagerPolicy extends WindowManagerPolicyConstants {
public WindowManager.LayoutParams getAttrs();
/**
- * Return whether this window needs the menu key shown. Must be called
- * with window lock held, because it may need to traverse down through
- * window list to determine the result.
- * @param bottom The bottom-most window to consider when determining this.
- */
- public boolean getNeedsMenuLw(WindowState bottom);
-
- /**
* Retrieve the current system UI visibility flags associated with
* this window.
*/
@@ -343,13 +336,6 @@ public interface WindowManagerPolicy extends WindowManagerPolicyConstants {
boolean isAnimatingLw();
/**
- * @return Whether the window can affect SystemUI flags, meaning that SystemUI (system bars,
- * for example) will be affected by the flags specified in this window. This is the
- * case when the surface is on screen but not exiting.
- */
- boolean canAffectSystemUiFlags();
-
- /**
* Is this window considered to be gone for purposes of layout?
*/
boolean isGoneForLayoutLw();
@@ -876,13 +862,15 @@ public interface WindowManagerPolicy extends WindowManagerPolicyConstants {
case TYPE_ACCESSIBILITY_OVERLAY:
// overlay put by accessibility services to intercept user interaction
return 30;
+ case TYPE_ACCESSIBILITY_MAGNIFICATION_OVERLAY:
+ return 31;
case TYPE_SECURE_SYSTEM_OVERLAY:
- return 31;
- case TYPE_BOOT_PROGRESS:
return 32;
+ case TYPE_BOOT_PROGRESS:
+ return 33;
case TYPE_POINTER:
// the (mouse) pointer layer
- return 33;
+ return 34;
default:
Slog.e("WindowManager", "Unknown window type: " + type);
return APPLICATION_LAYER;
diff --git a/services/core/java/com/android/server/power/ShutdownThread.java b/services/core/java/com/android/server/power/ShutdownThread.java
index 6da8fb4b1edb..cc1cddd3a111 100644
--- a/services/core/java/com/android/server/power/ShutdownThread.java
+++ b/services/core/java/com/android/server/power/ShutdownThread.java
@@ -41,12 +41,12 @@ import android.os.Trace;
import android.os.UserHandle;
import android.os.UserManager;
import android.os.Vibrator;
+import android.telephony.TelephonyManager;
import android.util.ArrayMap;
import android.util.Log;
import android.util.TimingsTraceLog;
import android.view.WindowManager;
-import com.android.internal.telephony.ITelephony;
import com.android.server.LocalServices;
import com.android.server.RescueParty;
import com.android.server.pm.PackageManagerService;
@@ -586,19 +586,15 @@ public final class ShutdownThread extends Thread {
TimingsTraceLog shutdownTimingsTraceLog = newTimingsLog();
boolean radioOff;
- final ITelephony phone =
- ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
+ TelephonyManager telephonyManager = mContext.getSystemService(
+ TelephonyManager.class);
- try {
- radioOff = phone == null || !phone.needMobileRadioShutdown();
- if (!radioOff) {
- Log.w(TAG, "Turning off cellular radios...");
- metricStarted(METRIC_RADIO);
- phone.shutdownMobileRadios();
- }
- } catch (RemoteException ex) {
- Log.e(TAG, "RemoteException during radio shutdown", ex);
- radioOff = true;
+ radioOff = telephonyManager == null
+ || !telephonyManager.isAnyRadioPoweredOn();
+ if (!radioOff) {
+ Log.w(TAG, "Turning off cellular radios...");
+ metricStarted(METRIC_RADIO);
+ telephonyManager.shutdownAllRadios();
}
Log.i(TAG, "Waiting for Radio...");
@@ -613,12 +609,7 @@ public final class ShutdownThread extends Thread {
}
if (!radioOff) {
- try {
- radioOff = !phone.needMobileRadioShutdown();
- } catch (RemoteException ex) {
- Log.e(TAG, "RemoteException during radio shutdown", ex);
- radioOff = true;
- }
+ radioOff = !telephonyManager.isAnyRadioPoweredOn();
if (radioOff) {
Log.i(TAG, "Radio turned off.");
metricEnded(METRIC_RADIO);
diff --git a/services/core/java/com/android/server/power/batterysaver/BatterySaverStateMachine.java b/services/core/java/com/android/server/power/batterysaver/BatterySaverStateMachine.java
index ff9129956a3b..a62bb74730f8 100644
--- a/services/core/java/com/android/server/power/batterysaver/BatterySaverStateMachine.java
+++ b/services/core/java/com/android/server/power/batterysaver/BatterySaverStateMachine.java
@@ -773,9 +773,9 @@ public class BatterySaverStateMachine {
// Handle triggering the notification to show/hide when appropriate
if (intReason == BatterySaverController.REASON_DYNAMIC_POWER_SAVINGS_AUTOMATIC_ON) {
- runOnBgThread(this::triggerDynamicModeNotification);
+ triggerDynamicModeNotification();
} else if (!enable) {
- runOnBgThread(this::hideDynamicModeNotification);
+ hideDynamicModeNotification();
}
if (DEBUG) {
@@ -787,33 +787,42 @@ public class BatterySaverStateMachine {
@VisibleForTesting
void triggerDynamicModeNotification() {
- NotificationManager manager = mContext.getSystemService(NotificationManager.class);
- ensureNotificationChannelExists(manager, DYNAMIC_MODE_NOTIF_CHANNEL_ID,
- R.string.dynamic_mode_notification_channel_name);
-
- manager.notifyAsUser(TAG, DYNAMIC_MODE_NOTIFICATION_ID,
- buildNotification(DYNAMIC_MODE_NOTIF_CHANNEL_ID,
- mContext.getResources().getString(R.string.dynamic_mode_notification_title),
- R.string.dynamic_mode_notification_summary,
- Intent.ACTION_POWER_USAGE_SUMMARY),
- UserHandle.ALL);
+ // The current lock is the PowerManager lock, which sits very low in the service lock
+ // hierarchy. We shouldn't call out to NotificationManager with the PowerManager lock.
+ runOnBgThread(() -> {
+ NotificationManager manager = mContext.getSystemService(NotificationManager.class);
+ ensureNotificationChannelExists(manager, DYNAMIC_MODE_NOTIF_CHANNEL_ID,
+ R.string.dynamic_mode_notification_channel_name);
+
+ manager.notifyAsUser(TAG, DYNAMIC_MODE_NOTIFICATION_ID,
+ buildNotification(DYNAMIC_MODE_NOTIF_CHANNEL_ID,
+ mContext.getResources().getString(
+ R.string.dynamic_mode_notification_title),
+ R.string.dynamic_mode_notification_summary,
+ Intent.ACTION_POWER_USAGE_SUMMARY),
+ UserHandle.ALL);
+ });
}
@VisibleForTesting
void triggerStickyDisabledNotification() {
- NotificationManager manager = mContext.getSystemService(NotificationManager.class);
- ensureNotificationChannelExists(manager, BATTERY_SAVER_NOTIF_CHANNEL_ID,
- R.string.battery_saver_notification_channel_name);
-
- final String percentage = NumberFormat.getPercentInstance()
- .format((double) mBatteryLevel / 100.0);
- manager.notifyAsUser(TAG, STICKY_AUTO_DISABLED_NOTIFICATION_ID,
- buildNotification(BATTERY_SAVER_NOTIF_CHANNEL_ID,
- mContext.getResources().getString(
- R.string.battery_saver_charged_notification_title, percentage),
- R.string.battery_saver_off_notification_summary,
- Settings.ACTION_BATTERY_SAVER_SETTINGS),
- UserHandle.ALL);
+ // The current lock is the PowerManager lock, which sits very low in the service lock
+ // hierarchy. We shouldn't call out to NotificationManager with the PowerManager lock.
+ runOnBgThread(() -> {
+ NotificationManager manager = mContext.getSystemService(NotificationManager.class);
+ ensureNotificationChannelExists(manager, BATTERY_SAVER_NOTIF_CHANNEL_ID,
+ R.string.battery_saver_notification_channel_name);
+
+ final String percentage = NumberFormat.getPercentInstance()
+ .format((double) mBatteryLevel / 100.0);
+ manager.notifyAsUser(TAG, STICKY_AUTO_DISABLED_NOTIFICATION_ID,
+ buildNotification(BATTERY_SAVER_NOTIF_CHANNEL_ID,
+ mContext.getResources().getString(
+ R.string.battery_saver_charged_notification_title, percentage),
+ R.string.battery_saver_off_notification_summary,
+ Settings.ACTION_BATTERY_SAVER_SETTINGS),
+ UserHandle.ALL);
+ });
}
private void ensureNotificationChannelExists(NotificationManager manager,
@@ -854,8 +863,12 @@ public class BatterySaverStateMachine {
}
private void hideNotification(int notificationId) {
- NotificationManager manager = mContext.getSystemService(NotificationManager.class);
- manager.cancel(notificationId);
+ // The current lock is the PowerManager lock, which sits very low in the service lock
+ // hierarchy. We shouldn't call out to NotificationManager with the PowerManager lock.
+ runOnBgThread(() -> {
+ NotificationManager manager = mContext.getSystemService(NotificationManager.class);
+ manager.cancelAsUser(TAG, notificationId, UserHandle.ALL);
+ });
}
private void setStickyActive(boolean active) {
diff --git a/services/core/java/com/android/server/role/FinancialSmsManager.java b/services/core/java/com/android/server/role/FinancialSmsManager.java
deleted file mode 100644
index 2ec39931789a..000000000000
--- a/services/core/java/com/android/server/role/FinancialSmsManager.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * Copyright (C) 2019 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 com.android.server.role;
-
-import android.Manifest;
-import android.annotation.MainThread;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.ServiceConnection;
-import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-import android.content.pm.ServiceInfo;
-import android.os.Binder;
-import android.os.Bundle;
-import android.os.IBinder;
-import android.os.RemoteCallback;
-import android.os.RemoteException;
-import android.os.UserHandle;
-import android.service.sms.FinancialSmsService;
-import android.service.sms.IFinancialSmsService;
-import android.util.Slog;
-
-import com.android.internal.annotations.GuardedBy;
-
-import java.io.PrintWriter;
-import java.util.ArrayList;
-
-/**
- * This class binds to {@code FinancialSmsService}.
- */
-final class FinancialSmsManager {
-
- private static final String TAG = "FinancialSmsManager";
-
- private final Context mContext;
- private final Object mLock = new Object();
-
- @GuardedBy("mLock")
- private ServiceConnection mServiceConnection;
-
- @GuardedBy("mLock")
- private IFinancialSmsService mRemoteService;
-
- @GuardedBy("mLock")
- private ArrayList<Command> mQueuedCommands;
-
- FinancialSmsManager(Context context) {
- mContext = context;
- }
-
- @Nullable
- ServiceInfo getServiceInfo() {
- final String packageName =
- mContext.getPackageManager().getServicesSystemSharedLibraryPackageName();
- if (packageName == null) {
- Slog.w(TAG, "no external services package!");
- return null;
- }
-
- final Intent intent = new Intent(FinancialSmsService.ACTION_FINANCIAL_SERVICE_INTENT);
- intent.setPackage(packageName);
- final ResolveInfo resolveInfo = mContext.getPackageManager().resolveService(intent,
- PackageManager.GET_SERVICES);
- if (resolveInfo == null || resolveInfo.serviceInfo == null) {
- Slog.w(TAG, "No valid components found.");
- return null;
- }
- return resolveInfo.serviceInfo;
- }
-
- @Nullable
- private ComponentName getServiceComponentName() {
- final ServiceInfo serviceInfo = getServiceInfo();
- if (serviceInfo == null) return null;
-
- final ComponentName name = new ComponentName(serviceInfo.packageName, serviceInfo.name);
- if (!Manifest.permission.BIND_FINANCIAL_SMS_SERVICE.equals(serviceInfo.permission)) {
- Slog.w(TAG, name.flattenToShortString() + " does not require permission "
- + Manifest.permission.BIND_FINANCIAL_SMS_SERVICE);
- return null;
- }
-
- return name;
- }
-
- void reset() {
- synchronized (mLock) {
- if (mServiceConnection != null) {
- mContext.unbindService(mServiceConnection);
- mServiceConnection = null;
- } else {
- Slog.d(TAG, "reset(): service is not bound. Do nothing.");
- }
- }
- }
-
- /**
- * Run a command, starting the service connection if necessary.
- */
- private void connectAndRun(@NonNull Command command) {
- synchronized (mLock) {
- if (mRemoteService != null) {
- try {
- command.run(mRemoteService);
- } catch (RemoteException e) {
- Slog.w(TAG, "exception calling service: " + e);
- }
- return;
- } else {
- if (mQueuedCommands == null) {
- mQueuedCommands = new ArrayList<>(1);
- }
- mQueuedCommands.add(command);
- // If we're already connected, don't create a new connection, just leave - the
- // command will be run when the service connects
- if (mServiceConnection != null) return;
- }
-
- // Create the connection
- mServiceConnection = new ServiceConnection() {
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- synchronized (mLock) {
- mRemoteService = IFinancialSmsService.Stub.asInterface(service);
- if (mQueuedCommands != null) {
- final int size = mQueuedCommands.size();
- for (int i = 0; i < size; i++) {
- final Command queuedCommand = mQueuedCommands.get(i);
- try {
- queuedCommand.run(mRemoteService);
- } catch (RemoteException e) {
- Slog.w(TAG, "exception calling " + name + ": " + e);
- }
- }
- mQueuedCommands = null;
- }
- }
- }
-
- @Override
- @MainThread
- public void onServiceDisconnected(ComponentName name) {
- synchronized (mLock) {
- mRemoteService = null;
- }
- }
-
- @Override
- public void onBindingDied(ComponentName name) {
- synchronized (mLock) {
- mRemoteService = null;
- }
- }
-
- @Override
- public void onNullBinding(ComponentName name) {
- synchronized (mLock) {
- mRemoteService = null;
- }
- }
- };
-
- final ComponentName component = getServiceComponentName();
- if (component != null) {
- final Intent intent = new Intent();
- intent.setComponent(component);
- final long token = Binder.clearCallingIdentity();
- try {
- mContext.bindServiceAsUser(intent, mServiceConnection, Context.BIND_AUTO_CREATE,
- UserHandle.getUserHandleForUid(UserHandle.getCallingUserId()));
- } finally {
- Binder.restoreCallingIdentity(token);
- }
- }
- }
- }
-
- void getSmsMessages(RemoteCallback callback, @Nullable Bundle params) {
- connectAndRun((service) -> service.getSmsMessages(callback, params));
- }
-
- void dump(String prefix, PrintWriter pw) {
- final ComponentName impl = getServiceComponentName();
- pw.print(prefix); pw.print("User ID: "); pw.println(UserHandle.getCallingUserId());
- pw.print(prefix); pw.print("Queued commands: ");
- if (mQueuedCommands == null) {
- pw.println("N/A");
- } else {
- pw.println(mQueuedCommands.size());
- }
- pw.print(prefix); pw.print("Implementation: ");
- if (impl == null) {
- pw.println("N/A");
- return;
- }
- pw.println(impl.flattenToShortString());
- }
-
- private interface Command {
- void run(IFinancialSmsService service) throws RemoteException;
- }
-}
diff --git a/services/core/java/com/android/server/role/RoleManagerService.java b/services/core/java/com/android/server/role/RoleManagerService.java
index a4eef9bf8d2e..c4522e03b700 100644
--- a/services/core/java/com/android/server/role/RoleManagerService.java
+++ b/services/core/java/com/android/server/role/RoleManagerService.java
@@ -50,7 +50,6 @@ import android.os.ResultReceiver;
import android.os.ShellCallback;
import android.os.UserHandle;
import android.os.UserManagerInternal;
-import android.service.sms.FinancialSmsService;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.ArraySet;
diff --git a/services/core/java/com/android/server/rollback/Rollback.java b/services/core/java/com/android/server/rollback/Rollback.java
index 8b79c3ff66c6..6898e1cd1f83 100644
--- a/services/core/java/com/android/server/rollback/Rollback.java
+++ b/services/core/java/com/android/server/rollback/Rollback.java
@@ -418,6 +418,7 @@ class Rollback {
if (isStaged()) {
parentParams.setStaged();
}
+ parentParams.setInstallReason(PackageManager.INSTALL_REASON_ROLLBACK);
int parentSessionId = packageInstaller.createSession(parentParams);
PackageInstaller.Session parentSession = packageInstaller.openSession(
@@ -484,6 +485,7 @@ class Rollback {
synchronized (mLock) {
mState = ROLLBACK_STATE_AVAILABLE;
mRestoreUserDataInProgress = false;
+ info.setCommittedSessionId(-1);
}
sendFailure(context, statusReceiver,
RollbackManager.STATUS_FAILURE_INSTALL,
@@ -500,7 +502,6 @@ class Rollback {
mRestoreUserDataInProgress = false;
}
- info.setCommittedSessionId(parentSessionId);
info.getCausePackages().addAll(causePackages);
RollbackStore.deletePackageCodePaths(this);
RollbackStore.saveRollback(this);
@@ -528,6 +529,7 @@ class Rollback {
);
mState = ROLLBACK_STATE_COMMITTED;
+ info.setCommittedSessionId(parentSessionId);
mRestoreUserDataInProgress = true;
parentSession.commit(receiver.getIntentSender());
} catch (IOException e) {
diff --git a/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java b/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java
index 3f5e2a447d28..6cdfcff61415 100644
--- a/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java
+++ b/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java
@@ -58,6 +58,7 @@ import com.android.internal.util.DumpUtils;
import com.android.internal.util.IndentingPrintWriter;
import com.android.server.LocalServices;
import com.android.server.PackageWatchdog;
+import com.android.server.SystemConfig;
import com.android.server.Watchdog;
import com.android.server.pm.Installer;
@@ -897,11 +898,11 @@ class RollbackManagerServiceImpl extends IRollbackManager.Stub {
}
@Override
- public boolean notifyStagedSession(int sessionId) {
+ public int notifyStagedSession(int sessionId) {
if (Binder.getCallingUid() != Process.SYSTEM_UID) {
throw new SecurityException("notifyStagedSession may only be called by the system.");
}
- final LinkedBlockingQueue<Boolean> result = new LinkedBlockingQueue<>();
+ final LinkedBlockingQueue<Integer> result = new LinkedBlockingQueue<>();
// NOTE: We post this runnable on the RollbackManager's binder thread because we'd prefer
// to preserve the invariant that all operations that modify state happen there.
@@ -911,7 +912,7 @@ class RollbackManagerServiceImpl extends IRollbackManager.Stub {
final PackageInstaller.SessionInfo session = installer.getSessionInfo(sessionId);
if (session == null) {
Slog.e(TAG, "No matching install session for: " + sessionId);
- result.offer(false);
+ result.offer(-1);
return;
}
@@ -923,7 +924,7 @@ class RollbackManagerServiceImpl extends IRollbackManager.Stub {
if (!session.isMultiPackage()) {
if (!enableRollbackForPackageSession(newRollback.rollback, session)) {
Slog.e(TAG, "Unable to enable rollback for session: " + sessionId);
- result.offer(false);
+ result.offer(-1);
return;
}
} else {
@@ -932,25 +933,30 @@ class RollbackManagerServiceImpl extends IRollbackManager.Stub {
installer.getSessionInfo(childSessionId);
if (childSession == null) {
Slog.e(TAG, "No matching child install session for: " + childSessionId);
- result.offer(false);
+ result.offer(-1);
return;
}
if (!enableRollbackForPackageSession(newRollback.rollback, childSession)) {
Slog.e(TAG, "Unable to enable rollback for session: " + sessionId);
- result.offer(false);
+ result.offer(-1);
return;
}
}
}
- result.offer(completeEnableRollback(newRollback, true) != null);
+ Rollback rollback = completeEnableRollback(newRollback, true);
+ if (rollback == null) {
+ result.offer(-1);
+ } else {
+ result.offer(rollback.info.getRollbackId());
+ }
});
try {
return result.take();
} catch (InterruptedException ie) {
Slog.e(TAG, "Interrupted while waiting for notifyStagedSession response");
- return false;
+ return -1;
}
}
@@ -1003,11 +1009,19 @@ class RollbackManagerServiceImpl extends IRollbackManager.Stub {
installerPackageName) == PackageManager.PERMISSION_GRANTED;
// For now only allow rollbacks for modules or for testing.
- return (isModule(packageName) && manageRollbacksGranted)
+ return (isRollbackWhitelisted(packageName) && manageRollbacksGranted)
|| testManageRollbacksGranted;
}
/**
+ * Returns true is this package is eligible for enabling rollback.
+ */
+ private boolean isRollbackWhitelisted(String packageName) {
+ // TODO: Remove #isModule when the white list is ready.
+ return SystemConfig.getInstance().getRollbackWhitelistedPackages().contains(packageName)
+ || isModule(packageName);
+ }
+ /**
* Returns true if the package name is the name of a module.
*/
private boolean isModule(String packageName) {
diff --git a/services/core/java/com/android/server/rollback/RollbackPackageHealthObserver.java b/services/core/java/com/android/server/rollback/RollbackPackageHealthObserver.java
index a62616623cb5..bb095841bbaa 100644
--- a/services/core/java/com/android/server/rollback/RollbackPackageHealthObserver.java
+++ b/services/core/java/com/android/server/rollback/RollbackPackageHealthObserver.java
@@ -61,7 +61,6 @@ import java.io.PrintWriter;
import java.util.Collections;
import java.util.List;
import java.util.Set;
-import java.util.concurrent.TimeUnit;
/**
* {@link PackageHealthObserver} for {@link RollbackManagerService}.
@@ -74,10 +73,6 @@ public final class RollbackPackageHealthObserver implements PackageHealthObserve
private static final String TAG = "RollbackPackageHealthObserver";
private static final String NAME = "rollback-observer";
private static final int INVALID_ROLLBACK_ID = -1;
- // TODO: make the following values configurable via DeviceConfig
- private static final long NATIVE_CRASH_POLLING_INTERVAL_MILLIS =
- TimeUnit.SECONDS.toMillis(30);
- private static final long NUMBER_OF_NATIVE_CRASH_POLLS = 10;
private final Context mContext;
private final Handler mHandler;
@@ -85,13 +80,9 @@ public final class RollbackPackageHealthObserver implements PackageHealthObserve
// Staged rollback ids that have been committed but their session is not yet ready
@GuardedBy("mPendingStagedRollbackIds")
private final Set<Integer> mPendingStagedRollbackIds = new ArraySet<>();
- // this field is initialized in the c'tor and then only accessed from mHandler thread, so
- // no need to guard with a lock
- private long mNumberOfNativeCrashPollsRemaining;
RollbackPackageHealthObserver(Context context) {
mContext = context;
- mNumberOfNativeCrashPollsRemaining = NUMBER_OF_NATIVE_CRASH_POLLS;
HandlerThread handlerThread = new HandlerThread("RollbackPackageHealthObserver");
handlerThread.start();
mHandler = handlerThread.getThreadHandler();
@@ -102,9 +93,15 @@ public final class RollbackPackageHealthObserver implements PackageHealthObserve
}
@Override
- public int onHealthCheckFailed(VersionedPackage failedPackage) {
- if (getAvailableRollback(mContext.getSystemService(RollbackManager.class), failedPackage)
- == null) {
+ public int onHealthCheckFailed(@Nullable VersionedPackage failedPackage,
+ @FailureReasons int failureReason) {
+ // For native crashes, we will roll back any available rollbacks
+ if (failureReason == PackageWatchdog.FAILURE_REASON_NATIVE_CRASH
+ && !mContext.getSystemService(RollbackManager.class)
+ .getAvailableRollbacks().isEmpty()) {
+ return PackageHealthObserverImpact.USER_IMPACT_MEDIUM;
+ }
+ if (getAvailableRollback(failedPackage) == null) {
// Don't handle the notification, no rollbacks available for the package
return PackageHealthObserverImpact.USER_IMPACT_NONE;
} else {
@@ -114,52 +111,21 @@ public final class RollbackPackageHealthObserver implements PackageHealthObserve
}
@Override
- public boolean execute(VersionedPackage failedPackage, @FailureReasons int rollbackReason) {
- RollbackManager rollbackManager = mContext.getSystemService(RollbackManager.class);
- VersionedPackage moduleMetadataPackage = getModuleMetadataPackage();
- RollbackInfo rollback = getAvailableRollback(rollbackManager, failedPackage);
- int reasonToLog = mapFailureReasonToMetric(rollbackReason);
+ public boolean execute(@Nullable VersionedPackage failedPackage,
+ @FailureReasons int rollbackReason) {
+ if (rollbackReason == PackageWatchdog.FAILURE_REASON_NATIVE_CRASH) {
+ rollbackAll();
+ return true;
+ }
+ RollbackInfo rollback = getAvailableRollback(failedPackage);
if (rollback == null) {
Slog.w(TAG, "Expected rollback but no valid rollback found for package: [ "
+ failedPackage.getPackageName() + "] with versionCode: ["
+ failedPackage.getVersionCode() + "]");
return false;
}
-
- logEvent(moduleMetadataPackage,
- StatsLog.WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE,
- reasonToLog, failedPackage.getPackageName());
- LocalIntentReceiver rollbackReceiver = new LocalIntentReceiver((Intent result) -> {
- int status = result.getIntExtra(RollbackManager.EXTRA_STATUS,
- RollbackManager.STATUS_FAILURE);
- if (status == RollbackManager.STATUS_SUCCESS) {
- if (rollback.isStaged()) {
- int rollbackId = rollback.getRollbackId();
- synchronized (mPendingStagedRollbackIds) {
- mPendingStagedRollbackIds.add(rollbackId);
- }
- BroadcastReceiver listener =
- listenForStagedSessionReady(rollbackManager, rollbackId,
- moduleMetadataPackage);
- handleStagedSessionChange(rollbackManager, rollbackId, listener,
- moduleMetadataPackage);
- } else {
- logEvent(moduleMetadataPackage,
- StatsLog.WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS,
- reasonToLog, failedPackage.getPackageName());
- }
- } else {
- logEvent(moduleMetadataPackage,
- StatsLog.WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_FAILURE,
- reasonToLog, failedPackage.getPackageName());
- }
- });
-
- mHandler.post(() ->
- rollbackManager.commitRollback(rollback.getRollbackId(),
- Collections.singletonList(failedPackage),
- rollbackReceiver.getIntentSender()));
+ rollbackPackage(rollback, failedPackage, rollbackReason);
// Assume rollback executed successfully
return true;
}
@@ -188,10 +154,10 @@ public final class RollbackPackageHealthObserver implements PackageHealthObserve
RollbackManager rollbackManager = mContext.getSystemService(RollbackManager.class);
PackageInstaller packageInstaller = mContext.getPackageManager().getPackageInstaller();
String moduleMetadataPackageName = getModuleMetadataPackageName();
- VersionedPackage newModuleMetadataPackage = getModuleMetadataPackage();
- if (getAvailableRollback(rollbackManager, newModuleMetadataPackage) != null) {
- scheduleCheckAndMitigateNativeCrashes();
+ if (!rollbackManager.getAvailableRollbacks().isEmpty()) {
+ // TODO(gavincorkery): Call into Package Watchdog from outside the observer
+ PackageWatchdog.getInstance(mContext).scheduleCheckAndMitigateNativeCrashes();
}
int rollbackId = popLastStagedRollbackId();
@@ -242,8 +208,8 @@ public final class RollbackPackageHealthObserver implements PackageHealthObserve
}
}
- private RollbackInfo getAvailableRollback(RollbackManager rollbackManager,
- VersionedPackage failedPackage) {
+ private RollbackInfo getAvailableRollback(VersionedPackage failedPackage) {
+ RollbackManager rollbackManager = mContext.getSystemService(RollbackManager.class);
for (RollbackInfo rollback : rollbackManager.getAvailableRollbacks()) {
for (PackageRollbackInfo packageRollback : rollback.getPackages()) {
boolean hasFailedPackage = packageRollback.getPackageName().equals(
@@ -285,7 +251,7 @@ public final class RollbackPackageHealthObserver implements PackageHealthObserve
}
private BroadcastReceiver listenForStagedSessionReady(RollbackManager rollbackManager,
- int rollbackId, VersionedPackage moduleMetadataPackage) {
+ int rollbackId, @Nullable VersionedPackage moduleMetadataPackage) {
BroadcastReceiver sessionUpdatedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
@@ -300,7 +266,7 @@ public final class RollbackPackageHealthObserver implements PackageHealthObserve
}
private void handleStagedSessionChange(RollbackManager rollbackManager, int rollbackId,
- BroadcastReceiver listener, VersionedPackage moduleMetadataPackage) {
+ BroadcastReceiver listener, @Nullable VersionedPackage moduleMetadataPackage) {
PackageInstaller packageInstaller =
mContext.getPackageManager().getPackageInstaller();
List<RollbackInfo> recentRollbacks =
@@ -382,36 +348,102 @@ public final class RollbackPackageHealthObserver implements PackageHealthObserve
}
}
+
/**
- * This method should be only called on mHandler thread, since it modifies
- * {@link #mNumberOfNativeCrashPollsRemaining} and we want to keep this class lock free.
+ * Returns true if the package name is the name of a module.
*/
- private void checkAndMitigateNativeCrashes() {
- mNumberOfNativeCrashPollsRemaining--;
- // Check if native watchdog reported a crash
- if ("1".equals(SystemProperties.get("sys.init.updatable_crashing"))) {
- execute(getModuleMetadataPackage(), PackageWatchdog.FAILURE_REASON_NATIVE_CRASH);
- // we stop polling after an attempt to execute rollback, regardless of whether the
- // attempt succeeds or not
- } else {
- if (mNumberOfNativeCrashPollsRemaining > 0) {
- mHandler.postDelayed(() -> checkAndMitigateNativeCrashes(),
- NATIVE_CRASH_POLLING_INTERVAL_MILLIS);
- }
+ private boolean isModule(String packageName) {
+ PackageManager pm = mContext.getPackageManager();
+ try {
+ return pm.getModuleInfo(packageName, 0) != null;
+ } catch (PackageManager.NameNotFoundException ignore) {
+ return false;
+ }
+ }
+
+ private VersionedPackage getVersionedPackage(String packageName) {
+ try {
+ return new VersionedPackage(packageName, mContext.getPackageManager().getPackageInfo(
+ packageName, 0 /* flags */).getLongVersionCode());
+ } catch (PackageManager.NameNotFoundException e) {
+ return null;
}
}
/**
- * Since this method can eventually trigger a RollbackManager rollback, it should be called
- * only once boot has completed {@code onBootCompleted} and not earlier, because the install
- * session must be entirely completed before we try to rollback.
+ * Rolls back the session that owns {@code failedPackage}
+ *
+ * @param rollback {@code rollbackInfo} of the {@code failedPackage}
+ * @param failedPackage the package that needs to be rolled back
*/
- private void scheduleCheckAndMitigateNativeCrashes() {
- Slog.i(TAG, "Scheduling " + mNumberOfNativeCrashPollsRemaining + " polls to check "
- + "and mitigate native crashes");
- mHandler.post(()->checkAndMitigateNativeCrashes());
+ private void rollbackPackage(RollbackInfo rollback, VersionedPackage failedPackage,
+ @FailureReasons int rollbackReason) {
+ final RollbackManager rollbackManager = mContext.getSystemService(RollbackManager.class);
+ int reasonToLog = mapFailureReasonToMetric(rollbackReason);
+ final String failedPackageToLog;
+ if (rollbackReason == PackageWatchdog.FAILURE_REASON_NATIVE_CRASH) {
+ failedPackageToLog = SystemProperties.get(
+ "sys.init.updatable_crashing_process_name", "");
+ } else {
+ failedPackageToLog = failedPackage.getPackageName();
+ }
+ final VersionedPackage logPackage = isModule(failedPackage.getPackageName())
+ ? getModuleMetadataPackage()
+ : null;
+
+ logEvent(logPackage,
+ StatsLog.WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE,
+ reasonToLog, failedPackageToLog);
+ final LocalIntentReceiver rollbackReceiver = new LocalIntentReceiver((Intent result) -> {
+ int status = result.getIntExtra(RollbackManager.EXTRA_STATUS,
+ RollbackManager.STATUS_FAILURE);
+ if (status == RollbackManager.STATUS_SUCCESS) {
+ if (rollback.isStaged()) {
+ int rollbackId = rollback.getRollbackId();
+ synchronized (mPendingStagedRollbackIds) {
+ mPendingStagedRollbackIds.add(rollbackId);
+ }
+ BroadcastReceiver listener =
+ listenForStagedSessionReady(rollbackManager, rollbackId,
+ logPackage);
+ handleStagedSessionChange(rollbackManager, rollbackId, listener,
+ logPackage);
+ } else {
+ logEvent(logPackage,
+ StatsLog.WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS,
+ reasonToLog, failedPackageToLog);
+ }
+ } else {
+ logEvent(logPackage,
+ StatsLog.WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_FAILURE,
+ reasonToLog, failedPackageToLog);
+ }
+ });
+
+ mHandler.post(() ->
+ rollbackManager.commitRollback(rollback.getRollbackId(),
+ Collections.singletonList(failedPackage),
+ rollbackReceiver.getIntentSender()));
}
+ private void rollbackAll() {
+ Slog.i(TAG, "Rolling back all available rollbacks");
+ RollbackManager rollbackManager = mContext.getSystemService(RollbackManager.class);
+ List<RollbackInfo> rollbacks = rollbackManager.getAvailableRollbacks();
+
+ for (RollbackInfo rollback : rollbacks) {
+ String samplePackageName = rollback.getPackages().get(0).getPackageName();
+ VersionedPackage sampleVersionedPackage = getVersionedPackage(samplePackageName);
+ if (sampleVersionedPackage == null) {
+ Slog.e(TAG, "Failed to rollback " + samplePackageName);
+ continue;
+ }
+ rollbackPackage(rollback, sampleVersionedPackage,
+ PackageWatchdog.FAILURE_REASON_NATIVE_CRASH);
+ }
+ }
+
+
private int mapFailureReasonToMetric(@FailureReasons int failureReason) {
switch (failureReason) {
case PackageWatchdog.FAILURE_REASON_NATIVE_CRASH:
diff --git a/services/core/java/com/android/server/soundtrigger_middleware/AudioSessionProviderImpl.java b/services/core/java/com/android/server/soundtrigger_middleware/AudioSessionProviderImpl.java
new file mode 100644
index 000000000000..3fa52301d9a0
--- /dev/null
+++ b/services/core/java/com/android/server/soundtrigger_middleware/AudioSessionProviderImpl.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.soundtrigger_middleware;
+
+/**
+ * An implementation of SoundTriggerMiddlewareImpl.AudioSessionProvider that ties to native
+ * AudioSystem module via JNI.
+ */
+class AudioSessionProviderImpl extends SoundTriggerMiddlewareImpl.AudioSessionProvider {
+ @Override
+ public native AudioSession acquireSession();
+
+ @Override
+ public native void releaseSession(int sessionHandle);
+}
diff --git a/services/core/java/com/android/server/soundtrigger_middleware/ConversionUtil.java b/services/core/java/com/android/server/soundtrigger_middleware/ConversionUtil.java
new file mode 100644
index 000000000000..9b22f33a20b0
--- /dev/null
+++ b/services/core/java/com/android/server/soundtrigger_middleware/ConversionUtil.java
@@ -0,0 +1,390 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.soundtrigger_middleware;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.hardware.audio.common.V2_0.Uuid;
+import android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback;
+import android.hardware.soundtrigger.V2_3.ISoundTriggerHw;
+import android.media.audio.common.AudioConfig;
+import android.media.audio.common.AudioOffloadInfo;
+import android.media.soundtrigger_middleware.ConfidenceLevel;
+import android.media.soundtrigger_middleware.ModelParameter;
+import android.media.soundtrigger_middleware.ModelParameterRange;
+import android.media.soundtrigger_middleware.Phrase;
+import android.media.soundtrigger_middleware.PhraseRecognitionEvent;
+import android.media.soundtrigger_middleware.PhraseRecognitionExtra;
+import android.media.soundtrigger_middleware.PhraseSoundModel;
+import android.media.soundtrigger_middleware.RecognitionConfig;
+import android.media.soundtrigger_middleware.RecognitionEvent;
+import android.media.soundtrigger_middleware.RecognitionMode;
+import android.media.soundtrigger_middleware.RecognitionStatus;
+import android.media.soundtrigger_middleware.SoundModel;
+import android.media.soundtrigger_middleware.SoundModelType;
+import android.media.soundtrigger_middleware.SoundTriggerModuleProperties;
+import android.os.HidlMemoryUtil;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Utilities for type conversion between SoundTrigger HAL types and SoundTriggerMiddleware service
+ * types.
+ *
+ * @hide
+ */
+class ConversionUtil {
+ static @NonNull
+ SoundTriggerModuleProperties hidl2aidlProperties(
+ @NonNull ISoundTriggerHw.Properties hidlProperties) {
+ SoundTriggerModuleProperties aidlProperties = new SoundTriggerModuleProperties();
+ aidlProperties.implementor = hidlProperties.implementor;
+ aidlProperties.description = hidlProperties.description;
+ aidlProperties.version = hidlProperties.version;
+ aidlProperties.uuid = hidl2aidlUuid(hidlProperties.uuid);
+ aidlProperties.maxSoundModels = hidlProperties.maxSoundModels;
+ aidlProperties.maxKeyPhrases = hidlProperties.maxKeyPhrases;
+ aidlProperties.maxUsers = hidlProperties.maxUsers;
+ aidlProperties.recognitionModes = hidlProperties.recognitionModes;
+ aidlProperties.captureTransition = hidlProperties.captureTransition;
+ aidlProperties.maxBufferMs = hidlProperties.maxBufferMs;
+ aidlProperties.concurrentCapture = hidlProperties.concurrentCapture;
+ aidlProperties.triggerInEvent = hidlProperties.triggerInEvent;
+ aidlProperties.powerConsumptionMw = hidlProperties.powerConsumptionMw;
+ return aidlProperties;
+ }
+
+ static @NonNull
+ String hidl2aidlUuid(@NonNull Uuid hidlUuid) {
+ if (hidlUuid.node == null || hidlUuid.node.length != 6) {
+ throw new IllegalArgumentException("UUID.node must be of length 6.");
+ }
+ return String.format(UuidUtil.FORMAT,
+ hidlUuid.timeLow,
+ hidlUuid.timeMid,
+ hidlUuid.versionAndTimeHigh,
+ hidlUuid.variantAndClockSeqHigh,
+ hidlUuid.node[0],
+ hidlUuid.node[1],
+ hidlUuid.node[2],
+ hidlUuid.node[3],
+ hidlUuid.node[4],
+ hidlUuid.node[5]);
+ }
+
+ static @NonNull
+ Uuid aidl2hidlUuid(@NonNull String aidlUuid) {
+ Matcher matcher = UuidUtil.PATTERN.matcher(aidlUuid);
+ if (!matcher.matches()) {
+ throw new IllegalArgumentException("Illegal format for UUID: " + aidlUuid);
+ }
+ Uuid hidlUuid = new Uuid();
+ hidlUuid.timeLow = Integer.parseUnsignedInt(matcher.group(1), 16);
+ hidlUuid.timeMid = (short) Integer.parseUnsignedInt(matcher.group(2), 16);
+ hidlUuid.versionAndTimeHigh = (short) Integer.parseUnsignedInt(matcher.group(3), 16);
+ hidlUuid.variantAndClockSeqHigh = (short) Integer.parseUnsignedInt(matcher.group(4), 16);
+ hidlUuid.node = new byte[]{(byte) Integer.parseUnsignedInt(matcher.group(5), 16),
+ (byte) Integer.parseUnsignedInt(matcher.group(6), 16),
+ (byte) Integer.parseUnsignedInt(matcher.group(7), 16),
+ (byte) Integer.parseUnsignedInt(matcher.group(8), 16),
+ (byte) Integer.parseUnsignedInt(matcher.group(9), 16),
+ (byte) Integer.parseUnsignedInt(matcher.group(10), 16)};
+ return hidlUuid;
+ }
+
+ static int aidl2hidlSoundModelType(int aidlType) {
+ switch (aidlType) {
+ case SoundModelType.GENERIC:
+ return android.hardware.soundtrigger.V2_0.SoundModelType.GENERIC;
+ case SoundModelType.KEYPHRASE:
+ return android.hardware.soundtrigger.V2_0.SoundModelType.KEYPHRASE;
+ default:
+ throw new IllegalArgumentException("Unknown sound model type: " + aidlType);
+ }
+ }
+
+ static int hidl2aidlSoundModelType(int hidlType) {
+ switch (hidlType) {
+ case android.hardware.soundtrigger.V2_0.SoundModelType.GENERIC:
+ return SoundModelType.GENERIC;
+ case android.hardware.soundtrigger.V2_0.SoundModelType.KEYPHRASE:
+ return SoundModelType.KEYPHRASE;
+ default:
+ throw new IllegalArgumentException("Unknown sound model type: " + hidlType);
+ }
+ }
+
+ static @NonNull
+ ISoundTriggerHw.Phrase aidl2hidlPhrase(@NonNull Phrase aidlPhrase) {
+ ISoundTriggerHw.Phrase hidlPhrase = new ISoundTriggerHw.Phrase();
+ hidlPhrase.id = aidlPhrase.id;
+ hidlPhrase.recognitionModes = aidl2hidlRecognitionModes(aidlPhrase.recognitionModes);
+ for (int aidlUser : aidlPhrase.users) {
+ hidlPhrase.users.add(aidlUser);
+ }
+ hidlPhrase.locale = aidlPhrase.locale;
+ hidlPhrase.text = aidlPhrase.text;
+ return hidlPhrase;
+ }
+
+ static int aidl2hidlRecognitionModes(int aidlModes) {
+ int hidlModes = 0;
+
+ if ((aidlModes & RecognitionMode.VOICE_TRIGGER) != 0) {
+ hidlModes |= android.hardware.soundtrigger.V2_0.RecognitionMode.VOICE_TRIGGER;
+ }
+ if ((aidlModes & RecognitionMode.USER_IDENTIFICATION) != 0) {
+ hidlModes |= android.hardware.soundtrigger.V2_0.RecognitionMode.USER_IDENTIFICATION;
+ }
+ if ((aidlModes & RecognitionMode.USER_AUTHENTICATION) != 0) {
+ hidlModes |= android.hardware.soundtrigger.V2_0.RecognitionMode.USER_AUTHENTICATION;
+ }
+ if ((aidlModes & RecognitionMode.GENERIC_TRIGGER) != 0) {
+ hidlModes |= android.hardware.soundtrigger.V2_0.RecognitionMode.GENERIC_TRIGGER;
+ }
+ return hidlModes;
+ }
+
+ static int hidl2aidlRecognitionModes(int hidlModes) {
+ int aidlModes = 0;
+ if ((hidlModes & android.hardware.soundtrigger.V2_0.RecognitionMode.VOICE_TRIGGER) != 0) {
+ aidlModes |= RecognitionMode.VOICE_TRIGGER;
+ }
+ if ((hidlModes & android.hardware.soundtrigger.V2_0.RecognitionMode.USER_IDENTIFICATION)
+ != 0) {
+ aidlModes |= RecognitionMode.USER_IDENTIFICATION;
+ }
+ if ((hidlModes & android.hardware.soundtrigger.V2_0.RecognitionMode.USER_AUTHENTICATION)
+ != 0) {
+ aidlModes |= RecognitionMode.USER_AUTHENTICATION;
+ }
+ if ((hidlModes & android.hardware.soundtrigger.V2_0.RecognitionMode.GENERIC_TRIGGER) != 0) {
+ aidlModes |= RecognitionMode.GENERIC_TRIGGER;
+ }
+ return aidlModes;
+ }
+
+ static @NonNull
+ ISoundTriggerHw.SoundModel aidl2hidlSoundModel(@NonNull SoundModel aidlModel) {
+ ISoundTriggerHw.SoundModel hidlModel = new ISoundTriggerHw.SoundModel();
+ hidlModel.header.type = aidl2hidlSoundModelType(aidlModel.type);
+ hidlModel.header.uuid = aidl2hidlUuid(aidlModel.uuid);
+ hidlModel.header.vendorUuid = aidl2hidlUuid(aidlModel.vendorUuid);
+ hidlModel.data = HidlMemoryUtil.byteArrayToHidlMemory(aidlModel.data,
+ "SoundTrigger SoundModel");
+ return hidlModel;
+ }
+
+ static @NonNull
+ ISoundTriggerHw.PhraseSoundModel aidl2hidlPhraseSoundModel(
+ @NonNull PhraseSoundModel aidlModel) {
+ ISoundTriggerHw.PhraseSoundModel hidlModel = new ISoundTriggerHw.PhraseSoundModel();
+ hidlModel.common = aidl2hidlSoundModel(aidlModel.common);
+ for (Phrase aidlPhrase : aidlModel.phrases) {
+ hidlModel.phrases.add(aidl2hidlPhrase(aidlPhrase));
+ }
+ return hidlModel;
+ }
+
+ static @NonNull
+ ISoundTriggerHw.RecognitionConfig aidl2hidlRecognitionConfig(
+ @NonNull RecognitionConfig aidlConfig) {
+ ISoundTriggerHw.RecognitionConfig hidlConfig = new ISoundTriggerHw.RecognitionConfig();
+ hidlConfig.header.captureRequested = aidlConfig.captureRequested;
+ for (PhraseRecognitionExtra aidlPhraseExtra : aidlConfig.phraseRecognitionExtras) {
+ hidlConfig.header.phrases.add(aidl2hidlPhraseRecognitionExtra(aidlPhraseExtra));
+ }
+ hidlConfig.data = HidlMemoryUtil.byteArrayToHidlMemory(aidlConfig.data,
+ "SoundTrigger RecognitionConfig");
+ return hidlConfig;
+ }
+
+ static @NonNull
+ android.hardware.soundtrigger.V2_0.PhraseRecognitionExtra aidl2hidlPhraseRecognitionExtra(
+ @NonNull PhraseRecognitionExtra aidlExtra) {
+ android.hardware.soundtrigger.V2_0.PhraseRecognitionExtra hidlExtra =
+ new android.hardware.soundtrigger.V2_0.PhraseRecognitionExtra();
+ hidlExtra.id = aidlExtra.id;
+ hidlExtra.recognitionModes = aidl2hidlRecognitionModes(aidlExtra.recognitionModes);
+ hidlExtra.confidenceLevel = aidlExtra.confidenceLevel;
+ hidlExtra.levels.ensureCapacity(aidlExtra.levels.length);
+ for (ConfidenceLevel aidlLevel : aidlExtra.levels) {
+ hidlExtra.levels.add(aidl2hidlConfidenceLevel(aidlLevel));
+ }
+ return hidlExtra;
+ }
+
+ static @NonNull
+ PhraseRecognitionExtra hidl2aidlPhraseRecognitionExtra(
+ @NonNull android.hardware.soundtrigger.V2_0.PhraseRecognitionExtra hidlExtra) {
+ PhraseRecognitionExtra aidlExtra = new PhraseRecognitionExtra();
+ aidlExtra.id = hidlExtra.id;
+ aidlExtra.recognitionModes = hidl2aidlRecognitionModes(hidlExtra.recognitionModes);
+ aidlExtra.confidenceLevel = hidlExtra.confidenceLevel;
+ aidlExtra.levels = new ConfidenceLevel[hidlExtra.levels.size()];
+ for (int i = 0; i < hidlExtra.levels.size(); ++i) {
+ aidlExtra.levels[i] = hidl2aidlConfidenceLevel(hidlExtra.levels.get(i));
+ }
+ return aidlExtra;
+ }
+
+ static @NonNull
+ android.hardware.soundtrigger.V2_0.ConfidenceLevel aidl2hidlConfidenceLevel(
+ @NonNull ConfidenceLevel aidlLevel) {
+ android.hardware.soundtrigger.V2_0.ConfidenceLevel hidlLevel =
+ new android.hardware.soundtrigger.V2_0.ConfidenceLevel();
+ hidlLevel.userId = aidlLevel.userId;
+ hidlLevel.levelPercent = aidlLevel.levelPercent;
+ return hidlLevel;
+ }
+
+ static @NonNull
+ ConfidenceLevel hidl2aidlConfidenceLevel(
+ @NonNull android.hardware.soundtrigger.V2_0.ConfidenceLevel hidlLevel) {
+ ConfidenceLevel aidlLevel = new ConfidenceLevel();
+ aidlLevel.userId = hidlLevel.userId;
+ aidlLevel.levelPercent = hidlLevel.levelPercent;
+ return aidlLevel;
+ }
+
+ static int hidl2aidlRecognitionStatus(int hidlStatus) {
+ switch (hidlStatus) {
+ case ISoundTriggerHwCallback.RecognitionStatus.SUCCESS:
+ return RecognitionStatus.SUCCESS;
+ case ISoundTriggerHwCallback.RecognitionStatus.ABORT:
+ return RecognitionStatus.ABORTED;
+ case ISoundTriggerHwCallback.RecognitionStatus.FAILURE:
+ return RecognitionStatus.FAILURE;
+ case 3: // This doesn't have a constant in HIDL.
+ return RecognitionStatus.FORCED;
+ default:
+ throw new IllegalArgumentException("Unknown recognition status: " + hidlStatus);
+ }
+ }
+
+ static @NonNull
+ RecognitionEvent hidl2aidlRecognitionEvent(@NonNull
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.RecognitionEvent hidlEvent) {
+ RecognitionEvent aidlEvent = new RecognitionEvent();
+ aidlEvent.status = hidl2aidlRecognitionStatus(hidlEvent.status);
+ aidlEvent.type = hidl2aidlSoundModelType(hidlEvent.type);
+ aidlEvent.captureAvailable = hidlEvent.captureAvailable;
+ // hidlEvent.captureSession is never a valid field.
+ aidlEvent.captureSession = -1;
+ aidlEvent.captureDelayMs = hidlEvent.captureDelayMs;
+ aidlEvent.capturePreambleMs = hidlEvent.capturePreambleMs;
+ aidlEvent.triggerInData = hidlEvent.triggerInData;
+ aidlEvent.audioConfig = hidl2aidlAudioConfig(hidlEvent.audioConfig);
+ aidlEvent.data = new byte[hidlEvent.data.size()];
+ for (int i = 0; i < aidlEvent.data.length; ++i) {
+ aidlEvent.data[i] = hidlEvent.data.get(i);
+ }
+ return aidlEvent;
+ }
+
+ static @NonNull
+ RecognitionEvent hidl2aidlRecognitionEvent(
+ @NonNull ISoundTriggerHwCallback.RecognitionEvent hidlEvent) {
+ RecognitionEvent aidlEvent = hidl2aidlRecognitionEvent(hidlEvent.header);
+ // Data needs to get overridden with 2.1 data.
+ aidlEvent.data = HidlMemoryUtil.hidlMemoryToByteArray(hidlEvent.data);
+ return aidlEvent;
+ }
+
+ static @NonNull
+ PhraseRecognitionEvent hidl2aidlPhraseRecognitionEvent(@NonNull
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.PhraseRecognitionEvent hidlEvent) {
+ PhraseRecognitionEvent aidlEvent = new PhraseRecognitionEvent();
+ aidlEvent.common = hidl2aidlRecognitionEvent(hidlEvent.common);
+ aidlEvent.phraseExtras = new PhraseRecognitionExtra[hidlEvent.phraseExtras.size()];
+ for (int i = 0; i < hidlEvent.phraseExtras.size(); ++i) {
+ aidlEvent.phraseExtras[i] = hidl2aidlPhraseRecognitionExtra(
+ hidlEvent.phraseExtras.get(i));
+ }
+ return aidlEvent;
+ }
+
+ static @NonNull
+ PhraseRecognitionEvent hidl2aidlPhraseRecognitionEvent(
+ @NonNull ISoundTriggerHwCallback.PhraseRecognitionEvent hidlEvent) {
+ PhraseRecognitionEvent aidlEvent = new PhraseRecognitionEvent();
+ aidlEvent.common = hidl2aidlRecognitionEvent(hidlEvent.common);
+ aidlEvent.phraseExtras = new PhraseRecognitionExtra[hidlEvent.phraseExtras.size()];
+ for (int i = 0; i < hidlEvent.phraseExtras.size(); ++i) {
+ aidlEvent.phraseExtras[i] = hidl2aidlPhraseRecognitionExtra(
+ hidlEvent.phraseExtras.get(i));
+ }
+ return aidlEvent;
+ }
+
+ static @NonNull
+ AudioConfig hidl2aidlAudioConfig(
+ @NonNull android.hardware.audio.common.V2_0.AudioConfig hidlConfig) {
+ AudioConfig aidlConfig = new AudioConfig();
+ // TODO(ytai): channelMask and format might need a more careful conversion to make sure the
+ // constants match.
+ aidlConfig.sampleRateHz = hidlConfig.sampleRateHz;
+ aidlConfig.channelMask = hidlConfig.channelMask;
+ aidlConfig.format = hidlConfig.format;
+ aidlConfig.offloadInfo = hidl2aidlOffloadInfo(hidlConfig.offloadInfo);
+ aidlConfig.frameCount = hidlConfig.frameCount;
+ return aidlConfig;
+ }
+
+ static @NonNull
+ AudioOffloadInfo hidl2aidlOffloadInfo(
+ @NonNull android.hardware.audio.common.V2_0.AudioOffloadInfo hidlInfo) {
+ AudioOffloadInfo aidlInfo = new AudioOffloadInfo();
+ // TODO(ytai): channelMask, format, streamType and usage might need a more careful
+ // conversion to make sure the constants match.
+ aidlInfo.sampleRateHz = hidlInfo.sampleRateHz;
+ aidlInfo.channelMask = hidlInfo.channelMask;
+ aidlInfo.format = hidlInfo.format;
+ aidlInfo.streamType = hidlInfo.streamType;
+ aidlInfo.bitRatePerSecond = hidlInfo.bitRatePerSecond;
+ aidlInfo.durationMicroseconds = hidlInfo.durationMicroseconds;
+ aidlInfo.hasVideo = hidlInfo.hasVideo;
+ aidlInfo.isStreaming = hidlInfo.isStreaming;
+ aidlInfo.bitWidth = hidlInfo.bitWidth;
+ aidlInfo.bufferSize = hidlInfo.bufferSize;
+ aidlInfo.usage = hidlInfo.usage;
+ return aidlInfo;
+ }
+
+ @Nullable
+ static ModelParameterRange hidl2aidlModelParameterRange(
+ android.hardware.soundtrigger.V2_3.ModelParameterRange hidlRange) {
+ if (hidlRange == null) {
+ return null;
+ }
+ ModelParameterRange aidlRange = new ModelParameterRange();
+ aidlRange.minInclusive = hidlRange.start;
+ aidlRange.maxInclusive = hidlRange.end;
+ return aidlRange;
+ }
+
+ static int aidl2hidlModelParameter(int aidlParam) {
+ switch (aidlParam) {
+ case ModelParameter.THRESHOLD_FACTOR:
+ return android.hardware.soundtrigger.V2_3.ModelParameter.THRESHOLD_FACTOR;
+
+ default:
+ return android.hardware.soundtrigger.V2_3.ModelParameter.INVALID;
+ }
+ }
+}
diff --git a/services/core/java/com/android/server/soundtrigger_middleware/HalException.java b/services/core/java/com/android/server/soundtrigger_middleware/HalException.java
new file mode 100644
index 000000000000..8b3e70875183
--- /dev/null
+++ b/services/core/java/com/android/server/soundtrigger_middleware/HalException.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.soundtrigger_middleware;
+
+import android.annotation.NonNull;
+
+/**
+ * This exception represents a non-zero status code returned by a HAL invocation.
+ * Depending on the operation that threw the error, the integrity of the HAL implementation and the
+ * client's tolerance to error, this error may or may not be recoverable. The HAL itself is expected
+ * to retain the state it had prior to the invocation (so, unless the error is a result of a HAL
+ * bug, normal operation may resume).
+ * <p>
+ * The reason why this is a RuntimeException, even though the HAL interface allows returning them
+ * is because we expect none of them to actually occur as part of correct usage of the HAL.
+ *
+ * @hide
+ */
+public class HalException extends RuntimeException {
+ public final int errorCode;
+
+ public HalException(int errorCode, @NonNull String message) {
+ super(message);
+ this.errorCode = errorCode;
+ }
+
+ public HalException(int errorCode) {
+ this.errorCode = errorCode;
+ }
+
+ @Override
+ public @NonNull String toString() {
+ return super.toString() + " (code " + errorCode + ")";
+ }
+}
diff --git a/services/core/java/com/android/server/soundtrigger_middleware/Hw2CompatUtil.java b/services/core/java/com/android/server/soundtrigger_middleware/Hw2CompatUtil.java
new file mode 100644
index 000000000000..f0a0d8305bc6
--- /dev/null
+++ b/services/core/java/com/android/server/soundtrigger_middleware/Hw2CompatUtil.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.soundtrigger_middleware;
+
+import android.os.HidlMemoryUtil;
+
+import java.util.ArrayList;
+
+/**
+ * Utilities for maintaining data compatibility between different minor versions of soundtrigger@2.x
+ * HAL.
+ * Note that some of these conversion utilities are destructive, i.e. mutate their input (for the
+ * sake of simplifying code and reducing copies).
+ */
+class Hw2CompatUtil {
+ static android.hardware.soundtrigger.V2_0.ISoundTriggerHw.SoundModel convertSoundModel_2_1_to_2_0(
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.SoundModel soundModel) {
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw.SoundModel model_2_0 = soundModel.header;
+ // Note: this mutates the input!
+ model_2_0.data = HidlMemoryUtil.hidlMemoryToByteList(soundModel.data);
+ return model_2_0;
+ }
+
+ static android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.RecognitionEvent convertRecognitionEvent_2_0_to_2_1(
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.RecognitionEvent event) {
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.RecognitionEvent event_2_1 =
+ new android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.RecognitionEvent();
+ event_2_1.header = event;
+ event_2_1.data = HidlMemoryUtil.byteListToHidlMemory(event_2_1.header.data,
+ "SoundTrigger RecognitionEvent");
+ // Note: this mutates the input!
+ event_2_1.header.data = new ArrayList<>();
+ return event_2_1;
+ }
+
+ static android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.PhraseRecognitionEvent convertPhraseRecognitionEvent_2_0_to_2_1(
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.PhraseRecognitionEvent event) {
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.PhraseRecognitionEvent
+ event_2_1 =
+ new android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.PhraseRecognitionEvent();
+ event_2_1.common = convertRecognitionEvent_2_0_to_2_1(event.common);
+ event_2_1.phraseExtras = event.phraseExtras;
+ return event_2_1;
+ }
+
+ static android.hardware.soundtrigger.V2_0.ISoundTriggerHw.PhraseSoundModel convertPhraseSoundModel_2_1_to_2_0(
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.PhraseSoundModel soundModel) {
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw.PhraseSoundModel model_2_0 =
+ new android.hardware.soundtrigger.V2_0.ISoundTriggerHw.PhraseSoundModel();
+ model_2_0.common = convertSoundModel_2_1_to_2_0(soundModel.common);
+ model_2_0.phrases = soundModel.phrases;
+ return model_2_0;
+ }
+
+ static android.hardware.soundtrigger.V2_0.ISoundTriggerHw.RecognitionConfig convertRecognitionConfig_2_1_to_2_0(
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.RecognitionConfig config) {
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw.RecognitionConfig config_2_0 =
+ config.header;
+ // Note: this mutates the input!
+ config_2_0.data = HidlMemoryUtil.hidlMemoryToByteList(config.data);
+ return config_2_0;
+ }
+}
diff --git a/services/core/java/com/android/server/soundtrigger_middleware/ISoundTriggerHw2.java b/services/core/java/com/android/server/soundtrigger_middleware/ISoundTriggerHw2.java
new file mode 100644
index 000000000000..81252c9a8c14
--- /dev/null
+++ b/services/core/java/com/android/server/soundtrigger_middleware/ISoundTriggerHw2.java
@@ -0,0 +1,158 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.soundtrigger_middleware;
+
+import android.hardware.soundtrigger.V2_3.ISoundTriggerHw;
+import android.hardware.soundtrigger.V2_3.ModelParameterRange;
+import android.hidl.base.V1_0.IBase;
+import android.os.IHwBinder;
+
+/**
+ * This interface mimics android.hardware.soundtrigger.V2_x.ISoundTriggerHw and
+ * android.hardware.soundtrigger.V2_x.ISoundTriggerHwCallback, with a few key differences:
+ * <ul>
+ * <li>Methods in the original interface generally have a status return value and potentially a
+ * second return value which is the actual return value. This is reflected via a synchronous
+ * callback, which is not very pleasant to work with. This interface replaces that pattern with
+ * the convention that a HalException is thrown for non-OK status, and then we can use the
+ * return value for the actual return value.
+ * <li>This interface will always include all the methods from the latest 2.x version (and thus
+ * from every 2.x version) interface, with the convention that unsupported methods throw a
+ * {@link RecoverableException} with a
+ * {@link android.media.soundtrigger_middleware.Status#OPERATION_NOT_SUPPORTED}
+ * code.
+ * <li>Cases where the original interface had multiple versions of a method representing the exact
+ * thing, or there exists a trivial conversion between the new and old version, this interface
+ * represents only the latest version, without any _version suffixes.
+ * <li>Removes some of the obscure IBinder methods.
+ * <li>No RemoteExceptions are specified. Some implementations of this interface may rethrow
+ * RemoteExceptions as RuntimeExceptions, some can guarantee handling them somehow and never throw
+ * them.
+ * <li>soundModelCallback has been removed, since nobody cares about it. Implementations are free
+ * to silently discard it.
+ * </ul>
+ * For cases where the client wants to explicitly handle specific versions of the underlying driver
+ * interface, they may call {@link #interfaceDescriptor()}.
+ * <p>
+ * <b>Note to maintainers</b>: This class must always be kept in sync with the latest 2.x version,
+ * so that clients have access to the entire functionality without having to burden themselves with
+ * compatibility, as much as possible.
+ */
+public interface ISoundTriggerHw2 {
+ /**
+ * @see android.hardware.soundtrigger.V2_2.ISoundTriggerHw#getProperties(android.hardware.soundtrigger.V2_0.ISoundTriggerHw.getPropertiesCallback
+ */
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.Properties getProperties();
+
+ /**
+ * @see android.hardware.soundtrigger.V2_2.ISoundTriggerHw#loadSoundModel_2_1(android.hardware.soundtrigger.V2_1.ISoundTriggerHw.SoundModel,
+ * android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback, int,
+ * android.hardware.soundtrigger.V2_1.ISoundTriggerHw.loadSoundModel_2_1Callback)
+ */
+ int loadSoundModel(
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.SoundModel soundModel,
+ SoundTriggerHw2Compat.Callback callback, int cookie);
+
+ /**
+ * @see android.hardware.soundtrigger.V2_2.ISoundTriggerHw#loadPhraseSoundModel_2_1(android.hardware.soundtrigger.V2_1.ISoundTriggerHw.PhraseSoundModel,
+ * android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback, int,
+ * android.hardware.soundtrigger.V2_1.ISoundTriggerHw.loadPhraseSoundModel_2_1Callback)
+ */
+ int loadPhraseSoundModel(
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.PhraseSoundModel soundModel,
+ SoundTriggerHw2Compat.Callback callback, int cookie);
+
+ /**
+ * @see android.hardware.soundtrigger.V2_2.ISoundTriggerHw#unloadSoundModel(int)
+ */
+ void unloadSoundModel(int modelHandle);
+
+ /**
+ * @see android.hardware.soundtrigger.V2_2.ISoundTriggerHw#stopRecognition(int)
+ */
+ void stopRecognition(int modelHandle);
+
+ /**
+ * @see android.hardware.soundtrigger.V2_2.ISoundTriggerHw#stopAllRecognitions()
+ */
+ void stopAllRecognitions();
+
+ /**
+ * @see android.hardware.soundtrigger.V2_2.ISoundTriggerHw#startRecognition_2_1(int,
+ * android.hardware.soundtrigger.V2_1.ISoundTriggerHw.RecognitionConfig,
+ * android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback, int)
+ */
+ void startRecognition(int modelHandle,
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.RecognitionConfig config,
+ SoundTriggerHw2Compat.Callback callback, int cookie);
+
+ /**
+ * @see android.hardware.soundtrigger.V2_2.ISoundTriggerHw#getModelState(int)
+ */
+ void getModelState(int modelHandle);
+
+ /**
+ * @see android.hardware.soundtrigger.V2_3.ISoundTriggerHw#getParameter(int, int,
+ * ISoundTriggerHw.getParameterCallback)
+ */
+ int getModelParameter(int modelHandle, int param);
+
+ /**
+ * @see android.hardware.soundtrigger.V2_3.ISoundTriggerHw#setParameter(int, int, int)
+ */
+ void setModelParameter(int modelHandle, int param, int value);
+
+ /**
+ * @return null if not supported.
+ * @see android.hardware.soundtrigger.V2_3.ISoundTriggerHw#queryParameter(int, int,
+ * ISoundTriggerHw.queryParameterCallback)
+ */
+ ModelParameterRange queryParameter(int modelHandle, int param);
+
+ /**
+ * @see IHwBinder#linkToDeath(IHwBinder.DeathRecipient, long)
+ */
+ boolean linkToDeath(IHwBinder.DeathRecipient recipient, long cookie);
+
+ /**
+ * @see IHwBinder#unlinkToDeath(IHwBinder.DeathRecipient)
+ */
+ boolean unlinkToDeath(IHwBinder.DeathRecipient recipient);
+
+ /**
+ * @see IBase#interfaceDescriptor()
+ */
+ String interfaceDescriptor() throws android.os.RemoteException;
+
+ interface Callback {
+ /**
+ * @see android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback#recognitionCallback_2_1(android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.RecognitionEvent,
+ * int)
+ */
+ void recognitionCallback(
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.RecognitionEvent event,
+ int cookie);
+
+ /**
+ * @see android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback#phraseRecognitionCallback_2_1(android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.PhraseRecognitionEvent,
+ * int)
+ */
+ void phraseRecognitionCallback(
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.PhraseRecognitionEvent event,
+ int cookie);
+ }
+}
diff --git a/services/core/java/com/android/server/soundtrigger_middleware/InternalServerError.java b/services/core/java/com/android/server/soundtrigger_middleware/InternalServerError.java
new file mode 100644
index 000000000000..e1fb2266b7c6
--- /dev/null
+++ b/services/core/java/com/android/server/soundtrigger_middleware/InternalServerError.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.soundtrigger_middleware;
+
+import android.annotation.NonNull;
+
+/**
+ * An internal server error.
+ * <p>
+ * This exception wraps any exception thrown from a service implementation, which is a result of a
+ * bug in the server implementation (or any of its dependencies).
+ * <p>
+ * Specifically, this type is excluded from the set of whitelisted exceptions that binder would
+ * tunnel to the client process, since these exceptions are ambiguous regarding whether the client
+ * had done something wrong or the server is buggy. For example, a client getting an
+ * IllegalArgumentException cannot easily determine whether they had provided illegal arguments to
+ * the method they were calling, or whether the method implementation provided illegal arguments to
+ * some method it was calling due to a bug.
+ *
+ * @hide
+ */
+public class InternalServerError extends RuntimeException {
+ public InternalServerError(@NonNull Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/services/core/java/com/android/server/soundtrigger_middleware/RecoverableException.java b/services/core/java/com/android/server/soundtrigger_middleware/RecoverableException.java
new file mode 100644
index 000000000000..83618505814e
--- /dev/null
+++ b/services/core/java/com/android/server/soundtrigger_middleware/RecoverableException.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.soundtrigger_middleware;
+
+import android.annotation.NonNull;
+
+/**
+ * This exception represents a fault which:
+ * <ul>
+ * <li>Could not have been anticipated by a caller (i.e. is not a violation of any preconditions).
+ * <li>Is guaranteed to not have been caused any meaningful state change in the callee. The caller
+ * may continue operation as if the call has never been made.
+ * </ul>
+ * <p>
+ * Some recoverable faults are permanent and some are transient / circumstantial, the specific error
+ * code can provide more information about the possible recovery options.
+ * <p>
+ * The reason why this is a RuntimeException is to allow it to go through interfaces defined by
+ * AIDL, which we have no control over.
+ *
+ * @hide
+ */
+public class RecoverableException extends RuntimeException {
+ public final int errorCode;
+
+ public RecoverableException(int errorCode, @NonNull String message) {
+ super(message);
+ this.errorCode = errorCode;
+ }
+
+ public RecoverableException(int errorCode) {
+ this.errorCode = errorCode;
+ }
+
+ @Override
+ public @NonNull String toString() {
+ return super.toString() + " (code " + errorCode + ")";
+ }
+}
diff --git a/services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerHw2Compat.java b/services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerHw2Compat.java
new file mode 100644
index 000000000000..4a852c4b68e8
--- /dev/null
+++ b/services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerHw2Compat.java
@@ -0,0 +1,470 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.soundtrigger_middleware;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.media.soundtrigger_middleware.Status;
+import android.os.IHwBinder;
+import android.os.RemoteException;
+
+import java.util.Objects;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * An implementation of {@link ISoundTriggerHw2}, on top of any
+ * android.hardware.soundtrigger.V2_x.ISoundTriggerHw implementation. This class hides away some of
+ * the details involved with retaining backward compatibility and adapts to the more pleasant syntax
+ * exposed by {@link ISoundTriggerHw2}, compared to the bare driver interface.
+ * <p>
+ * Exception handling:
+ * <ul>
+ * <li>All {@link RemoteException}s get rethrown as {@link RuntimeException}.
+ * <li>All HAL malfunctions get thrown as {@link HalException}.
+ * <li>All unsupported operations get thrown as {@link RecoverableException} with a
+ * {@link android.media.soundtrigger_middleware.Status#OPERATION_NOT_SUPPORTED}
+ * code.
+ * </ul>
+ */
+final class SoundTriggerHw2Compat implements ISoundTriggerHw2 {
+ private final @NonNull
+ IHwBinder mBinder;
+ private final @NonNull
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw mUnderlying_2_0;
+ private final @Nullable
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw mUnderlying_2_1;
+ private final @Nullable
+ android.hardware.soundtrigger.V2_2.ISoundTriggerHw mUnderlying_2_2;
+ private final @Nullable
+ android.hardware.soundtrigger.V2_3.ISoundTriggerHw mUnderlying_2_3;
+
+ public SoundTriggerHw2Compat(
+ @NonNull android.hardware.soundtrigger.V2_0.ISoundTriggerHw underlying) {
+ this(underlying.asBinder());
+ }
+
+ public SoundTriggerHw2Compat(IHwBinder binder) {
+ Objects.requireNonNull(binder);
+
+ mBinder = binder;
+
+ // We want to share the proxy instances rather than create a separate proxy for every
+ // version, so we go down the versions in descending order to find the latest one supported,
+ // and then simply up-cast it to obtain all the versions that are earlier.
+
+ // Attempt 2.3
+ android.hardware.soundtrigger.V2_3.ISoundTriggerHw as2_3 =
+ android.hardware.soundtrigger.V2_3.ISoundTriggerHw.asInterface(binder);
+ if (as2_3 != null) {
+ mUnderlying_2_0 = mUnderlying_2_1 = mUnderlying_2_2 = mUnderlying_2_3 = as2_3;
+ return;
+ }
+
+ // Attempt 2.2
+ android.hardware.soundtrigger.V2_2.ISoundTriggerHw as2_2 =
+ android.hardware.soundtrigger.V2_2.ISoundTriggerHw.asInterface(binder);
+ if (as2_2 != null) {
+ mUnderlying_2_0 = mUnderlying_2_1 = mUnderlying_2_2 = as2_2;
+ mUnderlying_2_3 = null;
+ return;
+ }
+
+ // Attempt 2.1
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw as2_1 =
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.asInterface(binder);
+ if (as2_1 != null) {
+ mUnderlying_2_0 = mUnderlying_2_1 = as2_1;
+ mUnderlying_2_2 = mUnderlying_2_3 = null;
+ return;
+ }
+
+ // Attempt 2.0
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw as2_0 =
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw.asInterface(binder);
+ if (as2_0 != null) {
+ mUnderlying_2_0 = as2_0;
+ mUnderlying_2_1 = mUnderlying_2_2 = mUnderlying_2_3 = null;
+ return;
+ }
+
+ throw new RuntimeException("Binder doesn't support ISoundTriggerHw@2.0");
+ }
+
+ private static void handleHalStatus(int status, String methodName) {
+ if (status != 0) {
+ throw new HalException(status, methodName);
+ }
+ }
+
+ @Override
+ public android.hardware.soundtrigger.V2_1.ISoundTriggerHw.Properties getProperties() {
+ try {
+ AtomicInteger retval = new AtomicInteger(-1);
+ AtomicReference<android.hardware.soundtrigger.V2_1.ISoundTriggerHw.Properties>
+ properties =
+ new AtomicReference<>();
+ as2_0().getProperties(
+ (r, p) -> {
+ retval.set(r);
+ properties.set(p);
+ });
+ handleHalStatus(retval.get(), "getProperties");
+ return properties.get();
+ } catch (RemoteException e) {
+ throw e.rethrowAsRuntimeException();
+ }
+ }
+
+ @Override
+ public int loadSoundModel(
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.SoundModel soundModel,
+ Callback callback, int cookie) {
+ try {
+ AtomicInteger retval = new AtomicInteger(-1);
+ AtomicInteger handle = new AtomicInteger(0);
+ try {
+ as2_1().loadSoundModel_2_1(soundModel, new SoundTriggerCallback(callback), cookie,
+ (r, h) -> {
+ retval.set(r);
+ handle.set(h);
+ });
+ } catch (NotSupported e) {
+ // Fall-back to the 2.0 version:
+ return loadSoundModel_2_0(soundModel, callback, cookie);
+ }
+ handleHalStatus(retval.get(), "loadSoundModel_2_1");
+ return handle.get();
+ } catch (RemoteException e) {
+ throw e.rethrowAsRuntimeException();
+ }
+ }
+
+ @Override
+ public int loadPhraseSoundModel(
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.PhraseSoundModel soundModel,
+ Callback callback, int cookie) {
+ try {
+ AtomicInteger retval = new AtomicInteger(-1);
+ AtomicInteger handle = new AtomicInteger(0);
+ try {
+ as2_1().loadPhraseSoundModel_2_1(soundModel, new SoundTriggerCallback(callback),
+ cookie,
+ (r, h) -> {
+ retval.set(r);
+ handle.set(h);
+ });
+ } catch (NotSupported e) {
+ // Fall-back to the 2.0 version:
+ return loadPhraseSoundModel_2_0(soundModel, callback, cookie);
+ }
+ handleHalStatus(retval.get(), "loadSoundModel_2_1");
+ return handle.get();
+ } catch (RemoteException e) {
+ throw e.rethrowAsRuntimeException();
+ }
+ }
+
+ @Override
+ public void unloadSoundModel(int modelHandle) {
+ try {
+ int retval = as2_0().unloadSoundModel(modelHandle);
+ handleHalStatus(retval, "unloadSoundModel");
+ } catch (RemoteException e) {
+ throw e.rethrowAsRuntimeException();
+ }
+ }
+
+ @Override
+ public void stopRecognition(int modelHandle) {
+ try {
+ int retval = as2_0().stopRecognition(modelHandle);
+ handleHalStatus(retval, "stopRecognition");
+ } catch (RemoteException e) {
+ throw e.rethrowAsRuntimeException();
+ }
+
+ }
+
+ @Override
+ public void stopAllRecognitions() {
+ try {
+ int retval = as2_0().stopAllRecognitions();
+ handleHalStatus(retval, "stopAllRecognitions");
+ } catch (RemoteException e) {
+ throw e.rethrowAsRuntimeException();
+ }
+ }
+
+ @Override
+ public void startRecognition(int modelHandle,
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.RecognitionConfig config,
+ Callback callback, int cookie) {
+ try {
+ try {
+ int retval = as2_1().startRecognition_2_1(modelHandle, config,
+ new SoundTriggerCallback(callback), cookie);
+ handleHalStatus(retval, "startRecognition_2_1");
+ } catch (NotSupported e) {
+ // Fall-back to the 2.0 version:
+ startRecognition_2_0(modelHandle, config, callback, cookie);
+ }
+ } catch (RemoteException e) {
+ throw e.rethrowAsRuntimeException();
+ }
+ }
+
+ @Override
+ public void getModelState(int modelHandle) {
+ try {
+ int retval = as2_2().getModelState(modelHandle);
+ handleHalStatus(retval, "getModelState");
+ } catch (RemoteException e) {
+ throw e.rethrowAsRuntimeException();
+ } catch (NotSupported e) {
+ throw e.throwAsRecoverableException();
+ }
+ }
+
+ @Override
+ public int getModelParameter(int modelHandle, int param) {
+ AtomicInteger status = new AtomicInteger(-1);
+ AtomicInteger value = new AtomicInteger(0);
+ try {
+ as2_3().getParameter(modelHandle, param,
+ (s, v) -> {
+ status.set(s);
+ value.set(v);
+ });
+ } catch (RemoteException e) {
+ throw e.rethrowAsRuntimeException();
+ } catch (NotSupported e) {
+ throw e.throwAsRecoverableException();
+ }
+ handleHalStatus(status.get(), "getParameter");
+ return value.get();
+ }
+
+ @Override
+ public void setModelParameter(int modelHandle, int param, int value) {
+ try {
+ int retval = as2_3().setParameter(modelHandle, param, value);
+ handleHalStatus(retval, "setParameter");
+ } catch (RemoteException e) {
+ throw e.rethrowAsRuntimeException();
+ } catch (NotSupported e) {
+ throw e.throwAsRecoverableException();
+ }
+ }
+
+ @Override
+ public android.hardware.soundtrigger.V2_3.ModelParameterRange queryParameter(int modelHandle,
+ int param) {
+ AtomicInteger status = new AtomicInteger(-1);
+ AtomicReference<android.hardware.soundtrigger.V2_3.OptionalModelParameterRange>
+ optionalRange =
+ new AtomicReference<>();
+ try {
+ as2_3().queryParameter(modelHandle, param,
+ (s, r) -> {
+ status.set(s);
+ optionalRange.set(r);
+ });
+ } catch (NotSupported e) {
+ // For older drivers, we consider no model parameter to be supported.
+ return null;
+ } catch (RemoteException e) {
+ throw e.rethrowAsRuntimeException();
+ }
+ handleHalStatus(status.get(), "queryParameter");
+ return (optionalRange.get().getDiscriminator()
+ == android.hardware.soundtrigger.V2_3.OptionalModelParameterRange.hidl_discriminator.range)
+ ?
+ optionalRange.get().range() : null;
+ }
+
+ @Override
+ public boolean linkToDeath(IHwBinder.DeathRecipient recipient, long cookie) {
+ return mBinder.linkToDeath(recipient, cookie);
+ }
+
+ @Override
+ public boolean unlinkToDeath(IHwBinder.DeathRecipient recipient) {
+ return mBinder.unlinkToDeath(recipient);
+ }
+
+ @Override
+ public String interfaceDescriptor() throws RemoteException {
+ return as2_0().interfaceDescriptor();
+ }
+
+ private int loadSoundModel_2_0(
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.SoundModel soundModel,
+ Callback callback, int cookie)
+ throws RemoteException {
+ // Convert the soundModel to V2.0.
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw.SoundModel model_2_0 =
+ Hw2CompatUtil.convertSoundModel_2_1_to_2_0(soundModel);
+
+ AtomicInteger retval = new AtomicInteger(-1);
+ AtomicInteger handle = new AtomicInteger(0);
+ as2_0().loadSoundModel(model_2_0, new SoundTriggerCallback(callback), cookie, (r, h) -> {
+ retval.set(r);
+ handle.set(h);
+ });
+ handleHalStatus(retval.get(), "loadSoundModel");
+ return handle.get();
+ }
+
+ private int loadPhraseSoundModel_2_0(
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.PhraseSoundModel soundModel,
+ Callback callback, int cookie)
+ throws RemoteException {
+ // Convert the soundModel to V2.0.
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw.PhraseSoundModel model_2_0 =
+ Hw2CompatUtil.convertPhraseSoundModel_2_1_to_2_0(soundModel);
+
+ AtomicInteger retval = new AtomicInteger(-1);
+ AtomicInteger handle = new AtomicInteger(0);
+ as2_0().loadPhraseSoundModel(model_2_0, new SoundTriggerCallback(callback), cookie,
+ (r, h) -> {
+ retval.set(r);
+ handle.set(h);
+ });
+ handleHalStatus(retval.get(), "loadSoundModel");
+ return handle.get();
+ }
+
+ private void startRecognition_2_0(int modelHandle,
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.RecognitionConfig config,
+ Callback callback, int cookie)
+ throws RemoteException {
+
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw.RecognitionConfig config_2_0 =
+ Hw2CompatUtil.convertRecognitionConfig_2_1_to_2_0(config);
+ int retval = as2_0().startRecognition(modelHandle, config_2_0,
+ new SoundTriggerCallback(callback), cookie);
+ handleHalStatus(retval, "startRecognition");
+ }
+
+ private @NonNull
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw as2_0() {
+ return mUnderlying_2_0;
+ }
+
+ private @NonNull
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw as2_1() throws NotSupported {
+ if (mUnderlying_2_1 == null) {
+ throw new NotSupported("Underlying driver version < 2.1");
+ }
+ return mUnderlying_2_1;
+ }
+
+ private @NonNull
+ android.hardware.soundtrigger.V2_2.ISoundTriggerHw as2_2() throws NotSupported {
+ if (mUnderlying_2_2 == null) {
+ throw new NotSupported("Underlying driver version < 2.2");
+ }
+ return mUnderlying_2_2;
+ }
+
+ private @NonNull
+ android.hardware.soundtrigger.V2_3.ISoundTriggerHw as2_3() throws NotSupported {
+ if (mUnderlying_2_3 == null) {
+ throw new NotSupported("Underlying driver version < 2.3");
+ }
+ return mUnderlying_2_3;
+ }
+
+ /**
+ * A checked exception representing the requested interface version not being supported.
+ * At the public interface layer, use {@link #throwAsRecoverableException()} to propagate it to
+ * the caller if the request cannot be fulfilled.
+ */
+ private static class NotSupported extends Exception {
+ NotSupported(String message) {
+ super(message);
+ }
+
+ /**
+ * Throw this as a recoverable exception.
+ *
+ * @return Never actually returns anything. Always throws. Used so that caller can write
+ * throw e.throwAsRecoverableException().
+ */
+ RecoverableException throwAsRecoverableException() {
+ throw new RecoverableException(Status.OPERATION_NOT_SUPPORTED, getMessage());
+ }
+ }
+
+ private static class SoundTriggerCallback extends
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.Stub {
+ private final @NonNull
+ Callback mDelegate;
+
+ private SoundTriggerCallback(
+ @NonNull Callback delegate) {
+ mDelegate = Objects.requireNonNull(delegate);
+ }
+
+ @Override
+ public void recognitionCallback_2_1(
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.RecognitionEvent event,
+ int cookie) {
+ mDelegate.recognitionCallback(event, cookie);
+ }
+
+ @Override
+ public void phraseRecognitionCallback_2_1(
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.PhraseRecognitionEvent event,
+ int cookie) {
+ mDelegate.phraseRecognitionCallback(event, cookie);
+ }
+
+ @Override
+ public void soundModelCallback_2_1(
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.ModelEvent event,
+ int cookie) {
+ // Nobody cares.
+ }
+
+ @Override
+ public void recognitionCallback(
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.RecognitionEvent event,
+ int cookie) {
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.RecognitionEvent event_2_1 =
+ Hw2CompatUtil.convertRecognitionEvent_2_0_to_2_1(event);
+ mDelegate.recognitionCallback(event_2_1, cookie);
+ }
+
+ @Override
+ public void phraseRecognitionCallback(
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.PhraseRecognitionEvent event,
+ int cookie) {
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.PhraseRecognitionEvent
+ event_2_1 = Hw2CompatUtil.convertPhraseRecognitionEvent_2_0_to_2_1(event);
+ mDelegate.phraseRecognitionCallback(event_2_1, cookie);
+ }
+
+ @Override
+ public void soundModelCallback(
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.ModelEvent event,
+ int cookie) {
+ // Nobody cares.
+ }
+ }
+}
diff --git a/services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerMiddlewareImpl.java b/services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerMiddlewareImpl.java
new file mode 100644
index 000000000000..9d51b65ea152
--- /dev/null
+++ b/services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerMiddlewareImpl.java
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.soundtrigger_middleware;
+
+import android.annotation.NonNull;
+import android.hardware.soundtrigger.V2_0.ISoundTriggerHw;
+import android.media.soundtrigger_middleware.ISoundTriggerCallback;
+import android.media.soundtrigger_middleware.ISoundTriggerMiddlewareService;
+import android.media.soundtrigger_middleware.ISoundTriggerModule;
+import android.media.soundtrigger_middleware.SoundTriggerModuleDescriptor;
+import android.os.IBinder;
+import android.util.Log;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * This is an implementation of the ISoundTriggerMiddlewareService interface.
+ * <p>
+ * <b>Important conventions:</b>
+ * <ul>
+ * <li>Correct usage is assumed. This implementation does not attempt to gracefully handle invalid
+ * usage, and such usage will result in undefined behavior. If this service is to be offered to an
+ * untrusted client, it must be wrapped with input and state validation.
+ * <li>There is no binder instance associated with this implementation. Do not call asBinder().
+ * <li>The implementation may throw a {@link RecoverableException} to indicate non-fatal,
+ * recoverable faults. The error code would one of the
+ * {@link android.media.soundtrigger_middleware.Status}
+ * constants. Any other exception thrown should be regarded as a bug in the implementation or one
+ * of its dependencies (assuming correct usage).
+ * <li>The implementation is designed for testibility by featuring dependency injection (the
+ * underlying HAL driver instances are passed to the ctor) and by minimizing dependencies on
+ * Android runtime.
+ * <li>The implementation is thread-safe.
+ * </ul>
+ *
+ * @hide
+ */
+public class SoundTriggerMiddlewareImpl implements ISoundTriggerMiddlewareService {
+ static private final String TAG = "SoundTriggerMiddlewareImpl";
+ private final SoundTriggerModule[] mModules;
+
+ /**
+ * Interface to the audio system, which can allocate capture session handles.
+ * SoundTrigger uses those sessions in order to associate a recognition session with an optional
+ * capture from the same device that triggered the recognition.
+ */
+ public static abstract class AudioSessionProvider {
+ public static final class AudioSession {
+ final int mSessionHandle;
+ final int mIoHandle;
+ final int mDeviceHandle;
+
+ AudioSession(int sessionHandle, int ioHandle, int deviceHandle) {
+ mSessionHandle = sessionHandle;
+ mIoHandle = ioHandle;
+ mDeviceHandle = deviceHandle;
+ }
+ }
+
+ public abstract AudioSession acquireSession();
+
+ public abstract void releaseSession(int sessionHandle);
+ }
+
+ /**
+ * Most generic constructor - gets an array of HAL driver instances.
+ */
+ public SoundTriggerMiddlewareImpl(@NonNull ISoundTriggerHw[] halServices,
+ @NonNull AudioSessionProvider audioSessionProvider) {
+ List<SoundTriggerModule> modules = new ArrayList<>(halServices.length);
+
+ for (int i = 0; i < halServices.length; ++i) {
+ ISoundTriggerHw service = halServices[i];
+ try {
+ modules.add(new SoundTriggerModule(service, audioSessionProvider));
+ } catch (Exception e) {
+ Log.e(TAG, "Failed to a SoundTriggerModule instance", e);
+ }
+ }
+
+ mModules = modules.toArray(new SoundTriggerModule[modules.size()]);
+ }
+
+ /**
+ * Convenience constructor - gets a single HAL driver instance.
+ */
+ public SoundTriggerMiddlewareImpl(@NonNull ISoundTriggerHw halService,
+ @NonNull AudioSessionProvider audioSessionProvider) {
+ this(new ISoundTriggerHw[]{halService}, audioSessionProvider);
+ }
+
+ @Override
+ public @NonNull
+ SoundTriggerModuleDescriptor[] listModules() {
+ SoundTriggerModuleDescriptor[] result = new SoundTriggerModuleDescriptor[mModules.length];
+
+ for (int i = 0; i < mModules.length; ++i) {
+ SoundTriggerModuleDescriptor desc = new SoundTriggerModuleDescriptor();
+ desc.handle = i;
+ desc.properties = mModules[i].getProperties();
+ result[i] = desc;
+ }
+ return result;
+ }
+
+ @Override
+ public @NonNull
+ ISoundTriggerModule attach(int handle, @NonNull ISoundTriggerCallback callback) {
+ return mModules[handle].attach(callback);
+ }
+
+ @Override
+ public void setExternalCaptureState(boolean active) {
+ for (SoundTriggerModule module : mModules) {
+ module.setExternalCaptureState(active);
+ }
+ }
+
+ @Override
+ public @NonNull
+ IBinder asBinder() {
+ throw new UnsupportedOperationException(
+ "This implementation is not inteded to be used directly with Binder.");
+ }
+} \ No newline at end of file
diff --git a/services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerMiddlewareService.java b/services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerMiddlewareService.java
new file mode 100644
index 000000000000..a7cfe1037f11
--- /dev/null
+++ b/services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerMiddlewareService.java
@@ -0,0 +1,709 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.soundtrigger_middleware;
+
+import android.Manifest;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.content.Context;
+import android.hardware.soundtrigger.V2_0.ISoundTriggerHw;
+import android.media.soundtrigger_middleware.ISoundTriggerCallback;
+import android.media.soundtrigger_middleware.ISoundTriggerMiddlewareService;
+import android.media.soundtrigger_middleware.ISoundTriggerModule;
+import android.media.soundtrigger_middleware.ModelParameterRange;
+import android.media.soundtrigger_middleware.PhraseRecognitionEvent;
+import android.media.soundtrigger_middleware.PhraseSoundModel;
+import android.media.soundtrigger_middleware.RecognitionConfig;
+import android.media.soundtrigger_middleware.RecognitionEvent;
+import android.media.soundtrigger_middleware.RecognitionStatus;
+import android.media.soundtrigger_middleware.SoundModel;
+import android.media.soundtrigger_middleware.SoundTriggerModuleDescriptor;
+import android.os.RemoteException;
+import android.os.ServiceSpecificException;
+import android.util.Log;
+
+import com.android.internal.util.Preconditions;
+import com.android.server.SystemService;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * This is a wrapper around an {@link ISoundTriggerMiddlewareService} implementation, which exposes
+ * it as a Binder service and enforces permissions and correct usage by the client, as well as makes
+ * sure that exceptions representing a server malfunction do not get sent to the client.
+ * <p>
+ * This is intended to extract the non-business logic out of the underlying implementation and thus
+ * make it easier to maintain each one of those separate aspects. A design trade-off is being made
+ * here, in that this class would need to essentially eavesdrop on all the client-server
+ * communication and retain all state known to the client, while the client doesn't necessarily care
+ * about all of it, and while the server has its own representation of this information. However,
+ * in this case, this is a small amount of data, and the benefits in code elegance seem worth it.
+ * There is also some additional cost in employing a simplistic locking mechanism here, but
+ * following the same line of reasoning, the benefits in code simplicity outweigh it.
+ * <p>
+ * Every public method in this class, overriding an interface method, must follow the following
+ * pattern:
+ * <code><pre>
+ * @Override public T method(S arg) {
+ * // Permission check.
+ * checkPermissions();
+ * // Input validation.
+ * ValidationUtil.validateS(arg);
+ * synchronized (this) {
+ * // State validation.
+ * if (...state is not valid for this call...) {
+ * throw new IllegalStateException("State is invalid because...");
+ * }
+ * // From here on, every exception isn't client's fault.
+ * try {
+ * T result = mDelegate.method(arg);
+ * // Update state.;
+ * ...
+ * return result;
+ * } catch (Exception e) {
+ * throw handleException(e);
+ * }
+ * }
+ * }
+ * </pre></code>
+ * Following this patterns ensures a consistent and rigorous handling of all aspects associated
+ * with client-server separation.
+ * <p>
+ * <b>Exception handling approach:</b><br>
+ * We make sure all client faults (permissions, argument and state validation) happen first, and
+ * would throw {@link SecurityException}, {@link IllegalArgumentException}/
+ * {@link NullPointerException} or {@link
+ * IllegalStateException}, respectively. All those exceptions are treated specially by Binder and
+ * will get sent back to the client.<br>
+ * Once this is done, any subsequent fault is considered a server fault. Only {@link
+ * RecoverableException}s thrown by the implementation are special-cased: they would get sent back
+ * to the caller as a {@link ServiceSpecificException}, which is the behavior of Binder. Any other
+ * exception gets wrapped with a {@link InternalServerError}, which is specifically chosen as a type
+ * that <b>does NOT</b> get forwarded by binder. Those exceptions would be handled by a high-level
+ * exception handler on the server side, typically resulting in rebooting the server.
+ * <p>
+ * <b>Exposing this service as a System Service:</b><br>
+ * Insert this line into {@link com.android.server.SystemServer}:
+ * <code><pre>
+ * mSystemServiceManager.startService(SoundTriggerMiddlewareService.Lifecycle.class);
+ * </pre></code>
+ *
+ * {@hide}
+ */
+public class SoundTriggerMiddlewareService extends ISoundTriggerMiddlewareService.Stub {
+ static private final String TAG = "SoundTriggerMiddlewareService";
+
+ final ISoundTriggerMiddlewareService mDelegate;
+ final Context mContext;
+ Set<Integer> mModuleHandles;
+
+ /**
+ * Constructor for internal use only. Could be exposed for testing purposes in the future.
+ * Users should access this class via {@link Lifecycle}.
+ */
+ private SoundTriggerMiddlewareService(
+ @NonNull ISoundTriggerMiddlewareService delegate, @NonNull Context context) {
+ mDelegate = delegate;
+ mContext = context;
+ }
+
+ /**
+ * Generic exception handling for exceptions thrown by the underlying implementation.
+ *
+ * Would throw any {@link RecoverableException} as a {@link ServiceSpecificException} (passed
+ * by Binder to the caller) and <i>any other</i> exception as {@link InternalServerError}
+ * (<b>not</b> passed by Binder to the caller).
+ * <p>
+ * Typical usage:
+ * <code><pre>
+ * try {
+ * ... Do server operations ...
+ * } catch (Exception e) {
+ * throw handleException(e);
+ * }
+ * </pre></code>
+ */
+ private static @NonNull
+ RuntimeException handleException(@NonNull Exception e) {
+ if (e instanceof RecoverableException) {
+ throw new ServiceSpecificException(((RecoverableException) e).errorCode,
+ e.getMessage());
+ }
+ throw new InternalServerError(e);
+ }
+
+ @Override
+ public @NonNull
+ SoundTriggerModuleDescriptor[] listModules() {
+ // Permission check.
+ checkPermissions();
+ // Input validation (always valid).
+
+ synchronized (this) {
+ // State validation (always valid).
+
+ // From here on, every exception isn't client's fault.
+ try {
+ SoundTriggerModuleDescriptor[] result = mDelegate.listModules();
+ mModuleHandles = new HashSet<>(result.length);
+ for (SoundTriggerModuleDescriptor desc : result) {
+ mModuleHandles.add(desc.handle);
+ }
+ return result;
+ } catch (Exception e) {
+ throw handleException(e);
+ }
+ }
+ }
+
+ @Override
+ public @NonNull
+ ISoundTriggerModule attach(int handle, @NonNull ISoundTriggerCallback callback) {
+ // Permission check.
+ checkPermissions();
+ // Input validation.
+ Preconditions.checkNotNull(callback);
+ Preconditions.checkNotNull(callback.asBinder());
+
+ synchronized (this) {
+ // State validation.
+ if (mModuleHandles == null) {
+ throw new IllegalStateException(
+ "Client must call listModules() prior to attaching.");
+ }
+ if (!mModuleHandles.contains(handle)) {
+ throw new IllegalArgumentException("Invalid handle: " + handle);
+ }
+
+ // From here on, every exception isn't client's fault.
+ try {
+ ModuleService moduleService = new ModuleService(callback);
+ moduleService.attach(mDelegate.attach(handle, moduleService));
+ return moduleService;
+ } catch (Exception e) {
+ throw handleException(e);
+ }
+ }
+ }
+
+ @Override
+ public void setExternalCaptureState(boolean active) {
+ // Permission check.
+ checkPreemptPermissions();
+ // Input validation (always valid).
+
+ synchronized (this) {
+ // State validation (always valid).
+
+ // From here on, every exception isn't client's fault.
+ try {
+ mDelegate.setExternalCaptureState(active);
+ } catch (Exception e) {
+ throw handleException(e);
+ }
+ }
+ }
+
+ /**
+ * Throws a {@link SecurityException} if caller doesn't have the right permissions to use this
+ * service.
+ */
+ private void checkPermissions() {
+ mContext.enforceCallingOrSelfPermission(Manifest.permission.RECORD_AUDIO,
+ "Caller must have the android.permission.RECORD_AUDIO permission.");
+ mContext.enforceCallingOrSelfPermission(Manifest.permission.CAPTURE_AUDIO_HOTWORD,
+ "Caller must have the android.permission.CAPTURE_AUDIO_HOTWORD permission.");
+ }
+
+ /**
+ * Throws a {@link SecurityException} if caller doesn't have the right permissions to preempt
+ * active sound trigger sessions.
+ */
+ private void checkPreemptPermissions() {
+ mContext.enforceCallingOrSelfPermission(Manifest.permission.PREEMPT_SOUND_TRIGGER,
+ "Caller must have the android.permission.PREEMPT_SOUND_TRIGGER permission.");
+ }
+
+ /** State of a sound model. */
+ static class ModelState {
+ /** Activity state of a sound model. */
+ enum Activity {
+ /** Model is loaded, recognition is inactive. */
+ LOADED,
+ /** Model is loaded, recognition is active. */
+ ACTIVE
+ }
+
+ /** Activity state. */
+ public Activity activityState = Activity.LOADED;
+
+ /**
+ * A map of known parameter support. A missing key means we don't know yet whether the
+ * parameter is supported. A null value means it is known to not be supported. A non-null
+ * value indicates the valid value range.
+ */
+ private Map<Integer, ModelParameterRange> parameterSupport = new HashMap<>();
+
+ /**
+ * Check that the given parameter is known to be supported for this model.
+ *
+ * @param modelParam The parameter key.
+ */
+ public void checkSupported(int modelParam) {
+ if (!parameterSupport.containsKey(modelParam)) {
+ throw new IllegalStateException("Parameter has not been checked for support.");
+ }
+ ModelParameterRange range = parameterSupport.get(modelParam);
+ if (range == null) {
+ throw new IllegalArgumentException("Paramater is not supported.");
+ }
+ }
+
+ /**
+ * Check that the given parameter is known to be supported for this model and that the given
+ * value is a valid value for it.
+ *
+ * @param modelParam The parameter key.
+ * @param value The value.
+ */
+ public void checkSupported(int modelParam, int value) {
+ if (!parameterSupport.containsKey(modelParam)) {
+ throw new IllegalStateException("Parameter has not been checked for support.");
+ }
+ ModelParameterRange range = parameterSupport.get(modelParam);
+ if (range == null) {
+ throw new IllegalArgumentException("Paramater is not supported.");
+ }
+ Preconditions.checkArgumentInRange(value, range.minInclusive, range.maxInclusive,
+ "value");
+ }
+
+ /**
+ * Update support state for the given parameter for this model.
+ *
+ * @param modelParam The parameter key.
+ * @param range The parameter value range, or null if not supported.
+ */
+ public void updateParameterSupport(int modelParam, @Nullable ModelParameterRange range) {
+ parameterSupport.put(modelParam, range);
+ }
+ }
+
+ /**
+ * Entry-point to this module: exposes the module as a {@link SystemService}.
+ */
+ public static final class Lifecycle extends SystemService {
+ private SoundTriggerMiddlewareService mService;
+
+ public Lifecycle(Context context) {
+ super(context);
+ }
+
+ @Override
+ public void onStart() {
+ ISoundTriggerHw[] services;
+ try {
+ services = new ISoundTriggerHw[]{ISoundTriggerHw.getService(true)};
+ Log.d(TAG, "Connected to default ISoundTriggerHw");
+ } catch (Exception e) {
+ Log.e(TAG, "Failed to connect to default ISoundTriggerHw", e);
+ services = new ISoundTriggerHw[0];
+ }
+
+ mService = new SoundTriggerMiddlewareService(
+ new SoundTriggerMiddlewareImpl(services, new AudioSessionProviderImpl()),
+ getContext());
+ publishBinderService(Context.SOUND_TRIGGER_MIDDLEWARE_SERVICE, mService);
+ }
+ }
+
+ /**
+ * A wrapper around an {@link ISoundTriggerModule} implementation, to address the same aspects
+ * mentioned in {@link SoundTriggerModule} above. This class follows the same conventions.
+ */
+ private class ModuleService extends ISoundTriggerModule.Stub implements ISoundTriggerCallback,
+ DeathRecipient {
+ private final ISoundTriggerCallback mCallback;
+ private ISoundTriggerModule mDelegate;
+ private Map<Integer, ModelState> mLoadedModels = new HashMap<>();
+
+ ModuleService(@NonNull ISoundTriggerCallback callback) {
+ mCallback = callback;
+ try {
+ mCallback.asBinder().linkToDeath(this, 0);
+ } catch (RemoteException e) {
+ throw e.rethrowAsRuntimeException();
+ }
+ }
+
+ void attach(@NonNull ISoundTriggerModule delegate) {
+ mDelegate = delegate;
+ }
+
+ @Override
+ public int loadModel(@NonNull SoundModel model) {
+ // Permission check.
+ checkPermissions();
+ // Input validation.
+ ValidationUtil.validateGenericModel(model);
+
+ synchronized (this) {
+ // State validation.
+ if (mDelegate == null) {
+ throw new IllegalStateException("Module has been detached.");
+ }
+
+ // From here on, every exception isn't client's fault.
+ try {
+ int handle = mDelegate.loadModel(model);
+ mLoadedModels.put(handle, new ModelState());
+ return handle;
+ } catch (Exception e) {
+ throw handleException(e);
+ }
+ }
+ }
+
+ @Override
+ public int loadPhraseModel(@NonNull PhraseSoundModel model) {
+ // Permission check.
+ checkPermissions();
+ // Input validation.
+ ValidationUtil.validatePhraseModel(model);
+
+ synchronized (this) {
+ // State validation.
+ if (mDelegate == null) {
+ throw new IllegalStateException("Module has been detached.");
+ }
+
+ // From here on, every exception isn't client's fault.
+ try {
+ int handle = mDelegate.loadPhraseModel(model);
+ mLoadedModels.put(handle, new ModelState());
+ return handle;
+ } catch (Exception e) {
+ throw handleException(e);
+ }
+ }
+ }
+
+ @Override
+ public void unloadModel(int modelHandle) {
+ // Permission check.
+ checkPermissions();
+ // Input validation (always valid).
+
+ synchronized (this) {
+ // State validation.
+ if (mDelegate == null) {
+ throw new IllegalStateException("Module has been detached.");
+ }
+ ModelState modelState = mLoadedModels.get(modelHandle);
+ if (modelState == null) {
+ throw new IllegalStateException("Invalid handle: " + modelHandle);
+ }
+ if (modelState.activityState != ModelState.Activity.LOADED) {
+ throw new IllegalStateException("Model with handle: " + modelHandle
+ + " has invalid state for unloading: " + modelState.activityState);
+ }
+
+ // From here on, every exception isn't client's fault.
+ try {
+ mDelegate.unloadModel(modelHandle);
+ mLoadedModels.remove(modelHandle);
+ } catch (Exception e) {
+ throw handleException(e);
+ }
+ }
+ }
+
+ @Override
+ public void startRecognition(int modelHandle, @NonNull RecognitionConfig config) {
+ // Permission check.
+ checkPermissions();
+ // Input validation.
+ ValidationUtil.validateRecognitionConfig(config);
+
+ synchronized (this) {
+ // State validation.
+ if (mDelegate == null) {
+ throw new IllegalStateException("Module has been detached.");
+ }
+ ModelState modelState = mLoadedModels.get(modelHandle);
+ if (modelState == null) {
+ throw new IllegalStateException("Invalid handle: " + modelHandle);
+ }
+ if (modelState.activityState != ModelState.Activity.LOADED) {
+ throw new IllegalStateException("Model with handle: " + modelHandle
+ + " has invalid state for starting recognition: "
+ + modelState.activityState);
+ }
+
+ // From here on, every exception isn't client's fault.
+ try {
+ mDelegate.startRecognition(modelHandle, config);
+ modelState.activityState = ModelState.Activity.ACTIVE;
+ } catch (Exception e) {
+ throw handleException(e);
+ }
+ }
+ }
+
+ @Override
+ public void stopRecognition(int modelHandle) {
+ // Permission check.
+ checkPermissions();
+ // Input validation (always valid).
+
+ synchronized (this) {
+ // State validation.
+ if (mDelegate == null) {
+ throw new IllegalStateException("Module has been detached.");
+ }
+ ModelState modelState = mLoadedModels.get(modelHandle);
+ if (modelState == null) {
+ throw new IllegalStateException("Invalid handle: " + modelHandle);
+ }
+ // stopRecognition is idempotent - no need to check model state.
+
+ // From here on, every exception isn't client's fault.
+ try {
+ mDelegate.stopRecognition(modelHandle);
+ modelState.activityState = ModelState.Activity.LOADED;
+ } catch (Exception e) {
+ throw handleException(e);
+ }
+ }
+ }
+
+ @Override
+ public void forceRecognitionEvent(int modelHandle) {
+ // Permission check.
+ checkPermissions();
+ // Input validation (always valid).
+
+ synchronized (this) {
+ // State validation.
+ if (mDelegate == null) {
+ throw new IllegalStateException("Module has been detached.");
+ }
+ ModelState modelState = mLoadedModels.get(modelHandle);
+ if (modelState == null) {
+ throw new IllegalStateException("Invalid handle: " + modelHandle);
+ }
+ // forceRecognitionEvent is idempotent - no need to check model state.
+
+ // From here on, every exception isn't client's fault.
+ try {
+ mDelegate.forceRecognitionEvent(modelHandle);
+ } catch (Exception e) {
+ throw handleException(e);
+ }
+ }
+ }
+
+ @Override
+ public void setModelParameter(int modelHandle, int modelParam, int value) {
+ // Permission check.
+ checkPermissions();
+ // Input validation.
+ ValidationUtil.validateModelParameter(modelParam);
+
+ synchronized (this) {
+ // State validation.
+ if (mDelegate == null) {
+ throw new IllegalStateException("Module has been detached.");
+ }
+ ModelState modelState = mLoadedModels.get(modelHandle);
+ if (modelState == null) {
+ throw new IllegalStateException("Invalid handle: " + modelHandle);
+ }
+ modelState.checkSupported(modelParam, value);
+
+ // From here on, every exception isn't client's fault.
+ try {
+ mDelegate.setModelParameter(modelHandle, modelParam, value);
+ } catch (Exception e) {
+ throw handleException(e);
+ }
+ }
+ }
+
+ @Override
+ public int getModelParameter(int modelHandle, int modelParam) {
+ // Permission check.
+ checkPermissions();
+ // Input validation.
+ ValidationUtil.validateModelParameter(modelParam);
+
+ synchronized (this) {
+ // State validation.
+ if (mDelegate == null) {
+ throw new IllegalStateException("Module has been detached.");
+ }
+ ModelState modelState = mLoadedModels.get(modelHandle);
+ if (modelState == null) {
+ throw new IllegalStateException("Invalid handle: " + modelHandle);
+ }
+ modelState.checkSupported(modelParam);
+
+ // From here on, every exception isn't client's fault.
+ try {
+ return mDelegate.getModelParameter(modelHandle, modelParam);
+ } catch (Exception e) {
+ throw handleException(e);
+ }
+ }
+ }
+
+ @Override
+ @Nullable
+ public ModelParameterRange queryModelParameterSupport(int modelHandle, int modelParam) {
+ // Permission check.
+ checkPermissions();
+ // Input validation.
+ ValidationUtil.validateModelParameter(modelParam);
+
+ synchronized (this) {
+ // State validation.
+ if (mDelegate == null) {
+ throw new IllegalStateException("Module has been detached.");
+ }
+ ModelState modelState = mLoadedModels.get(modelHandle);
+ if (modelState == null) {
+ throw new IllegalStateException("Invalid handle: " + modelHandle);
+ }
+
+ // From here on, every exception isn't client's fault.
+ try {
+ ModelParameterRange result = mDelegate.queryModelParameterSupport(modelHandle,
+ modelParam);
+ modelState.updateParameterSupport(modelParam, result);
+ return result;
+ } catch (Exception e) {
+ throw handleException(e);
+ }
+ }
+ }
+
+ @Override
+ public void detach() {
+ // Permission check.
+ checkPermissions();
+ // Input validation (always valid).
+
+ synchronized (this) {
+ // State validation.
+ if (mDelegate == null) {
+ throw new IllegalStateException("Module has already been detached.");
+ }
+ if (!mLoadedModels.isEmpty()) {
+ throw new IllegalStateException("Cannot detach while models are loaded.");
+ }
+
+ // From here on, every exception isn't client's fault.
+ try {
+ detachInternal();
+ } catch (Exception e) {
+ throw handleException(e);
+ }
+ }
+ }
+
+ private void detachInternal() {
+ try {
+ mDelegate.detach();
+ mDelegate = null;
+ mCallback.asBinder().unlinkToDeath(this, 0);
+ } catch (RemoteException e) {
+ throw e.rethrowAsRuntimeException();
+ }
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////
+ // Callbacks
+
+ @Override
+ public void onRecognition(int modelHandle, @NonNull RecognitionEvent event) {
+ synchronized (this) {
+ if (event.status != RecognitionStatus.FORCED) {
+ mLoadedModels.get(modelHandle).activityState = ModelState.Activity.LOADED;
+ }
+ try {
+ mCallback.onRecognition(modelHandle, event);
+ } catch (RemoteException e) {
+ // Dead client will be handled by binderDied() - no need to handle here.
+ // In any case, client callbacks are considered best effort.
+ Log.e(TAG, "Client callback execption.", e);
+ }
+ }
+ }
+
+ @Override
+ public void onPhraseRecognition(int modelHandle, @NonNull PhraseRecognitionEvent event) {
+ synchronized (this) {
+ if (event.common.status != RecognitionStatus.FORCED) {
+ mLoadedModels.get(modelHandle).activityState = ModelState.Activity.LOADED;
+ }
+ try {
+ mCallback.onPhraseRecognition(modelHandle, event);
+ } catch (RemoteException e) {
+ // Dead client will be handled by binderDied() - no need to handle here.
+ // In any case, client callbacks are considered best effort.
+ Log.e(TAG, "Client callback execption.", e);
+ }
+ }
+ }
+
+ @Override
+ public void onRecognitionAvailabilityChange(boolean available) throws RemoteException {
+ synchronized (this) {
+ try {
+ mCallback.onRecognitionAvailabilityChange(available);
+ } catch (RemoteException e) {
+ // Dead client will be handled by binderDied() - no need to handle here.
+ // In any case, client callbacks are considered best effort.
+ Log.e(TAG, "Client callback execption.", e);
+ }
+ }
+ }
+
+ @Override
+ public void binderDied() {
+ // This is called whenever our client process dies.
+ synchronized (this) {
+ try {
+ // Gracefully stop all active recognitions and unload the models.
+ for (Map.Entry<Integer, ModelState> entry : mLoadedModels.entrySet()) {
+ if (entry.getValue().activityState == ModelState.Activity.ACTIVE) {
+ mDelegate.stopRecognition(entry.getKey());
+ }
+ mDelegate.unloadModel(entry.getKey());
+ }
+ // Detach.
+ detachInternal();
+ } catch (Exception e) {
+ throw handleException(e);
+ }
+ }
+ }
+ }
+}
diff --git a/services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerModule.java b/services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerModule.java
new file mode 100644
index 000000000000..81789e1362c0
--- /dev/null
+++ b/services/core/java/com/android/server/soundtrigger_middleware/SoundTriggerModule.java
@@ -0,0 +1,545 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.soundtrigger_middleware;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback;
+import android.hardware.soundtrigger.V2_2.ISoundTriggerHw;
+import android.media.soundtrigger_middleware.ISoundTriggerCallback;
+import android.media.soundtrigger_middleware.ISoundTriggerModule;
+import android.media.soundtrigger_middleware.ModelParameterRange;
+import android.media.soundtrigger_middleware.PhraseSoundModel;
+import android.media.soundtrigger_middleware.RecognitionConfig;
+import android.media.soundtrigger_middleware.SoundModel;
+import android.media.soundtrigger_middleware.SoundModelType;
+import android.media.soundtrigger_middleware.SoundTriggerModuleProperties;
+import android.media.soundtrigger_middleware.Status;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.util.Log;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * This is an implementation of a single module of the ISoundTriggerMiddlewareService interface,
+ * exposing itself through the {@link ISoundTriggerModule} interface, possibly to multiple separate
+ * clients.
+ * <p>
+ * Typical usage is to query the module capabilities using {@link #getProperties()} and then to use
+ * the module through an {@link ISoundTriggerModule} instance, obtained via {@link
+ * #attach(ISoundTriggerCallback)}. Every such interface is its own session and state is not shared
+ * between sessions (i.e. cannot use a handle obtained from one session through another).
+ * <p>
+ * <b>Important conventions:</b>
+ * <ul>
+ * <li>Correct usage is assumed. This implementation does not attempt to gracefully handle
+ * invalid usage, and such usage will result in undefined behavior. If this service is to be
+ * offered to an untrusted client, it must be wrapped with input and state validation.
+ * <li>The underlying driver is assumed to be correct. This implementation does not attempt to
+ * gracefully handle driver malfunction and such behavior will result in undefined behavior. If this
+ * service is to used with an untrusted driver, the driver must be wrapped with validation / error
+ * recovery code.
+ * <li>RemoteExceptions thrown by the driver are treated as RuntimeExceptions - they are not
+ * considered recoverable faults and should not occur in a properly functioning system.
+ * <li>There is no binder instance associated with this implementation. Do not call asBinder().
+ * <li>The implementation may throw a {@link RecoverableException} to indicate non-fatal,
+ * recoverable faults. The error code would one of the
+ * {@link android.media.soundtrigger_middleware.Status} constants. Any other exception
+ * thrown should be regarded as a bug in the implementation or one of its dependencies
+ * (assuming correct usage).
+ * <li>The implementation is designed for testability by featuring dependency injection (the
+ * underlying HAL driver instances are passed to the ctor) and by minimizing dependencies
+ * on Android runtime.
+ * <li>The implementation is thread-safe. This is achieved by a simplistic model, where all entry-
+ * points (both client API and driver callbacks) obtain a lock on the SoundTriggerModule instance
+ * for their entire scope. Any other method can be assumed to be running with the lock already
+ * obtained, so no further locking should be done. While this is not necessarily the most efficient
+ * synchronization strategy, it is very easy to reason about and this code is likely not on any
+ * performance-critical
+ * path.
+ * </ul>
+ *
+ * @hide
+ */
+class SoundTriggerModule {
+ static private final String TAG = "SoundTriggerModule";
+ @NonNull private final ISoundTriggerHw2 mHalService;
+ @NonNull private final SoundTriggerMiddlewareImpl.AudioSessionProvider mAudioSessionProvider;
+ private final Set<Session> mActiveSessions = new HashSet<>();
+ private int mNumLoadedModels = 0;
+ private SoundTriggerModuleProperties mProperties = null;
+ private boolean mRecognitionAvailable;
+
+ /**
+ * Ctor.
+ *
+ * @param halService The underlying HAL driver.
+ */
+ SoundTriggerModule(@NonNull android.hardware.soundtrigger.V2_0.ISoundTriggerHw halService,
+ @NonNull SoundTriggerMiddlewareImpl.AudioSessionProvider audioSessionProvider) {
+ assert halService != null;
+ mHalService = new SoundTriggerHw2Compat(halService);
+ mAudioSessionProvider = audioSessionProvider;
+ mProperties = ConversionUtil.hidl2aidlProperties(mHalService.getProperties());
+
+ // We conservatively assume that external capture is active until explicitly told otherwise.
+ mRecognitionAvailable = mProperties.concurrentCapture;
+ }
+
+ /**
+ * Establish a client session with this module.
+ *
+ * This module may be shared by multiple clients, each will get its own session. While resources
+ * are shared between the clients, each session has its own state and data should not be shared
+ * across sessions.
+ *
+ * @param callback The client callback, which will be used for all messages. This is a oneway
+ * callback, so will never block, throw an unchecked exception or return a
+ * value.
+ * @return The interface through which this module can be controlled.
+ */
+ synchronized @NonNull
+ Session attach(@NonNull ISoundTriggerCallback callback) {
+ Log.d(TAG, "attach()");
+ Session session = new Session(callback);
+ mActiveSessions.add(session);
+ return session;
+ }
+
+ /**
+ * Query the module's properties.
+ *
+ * @return The properties structure.
+ */
+ synchronized @NonNull
+ SoundTriggerModuleProperties getProperties() {
+ return mProperties;
+ }
+
+ /**
+ * Notify the module that external capture has started / finished, using the same input device
+ * used for recognition.
+ * If the underlying driver does not support recognition while capturing, capture will be
+ * aborted, and the recognition callback will receive and abort event. In addition, all active
+ * clients will be notified of the change in state.
+ *
+ * @param active true iff external capture is active.
+ */
+ synchronized void setExternalCaptureState(boolean active) {
+ Log.d(TAG, String.format("setExternalCaptureState(active=%b)", active));
+ if (mProperties.concurrentCapture) {
+ // If we support concurrent capture, we don't care about any of this.
+ return;
+ }
+ mRecognitionAvailable = !active;
+ if (!mRecognitionAvailable) {
+ // Our module does not support recognition while a capture is active -
+ // need to abort all active recognitions.
+ for (Session session : mActiveSessions) {
+ session.abortActiveRecognitions();
+ }
+ }
+ for (Session session : mActiveSessions) {
+ session.notifyRecognitionAvailability();
+ }
+ }
+
+ /**
+ * Remove session from the list of active sessions.
+ *
+ * @param session The session to remove.
+ */
+ private void removeSession(@NonNull Session session) {
+ mActiveSessions.remove(session);
+ }
+
+ /** State of a single sound model. */
+ private enum ModelState {
+ /** Initial state, until load() is called. */
+ INIT,
+ /** Model is loaded, but recognition is not active. */
+ LOADED,
+ /** Model is loaded and recognition is active. */
+ ACTIVE
+ }
+
+ /**
+ * A single client session with this module.
+ *
+ * This is the main interface used to interact with this module.
+ */
+ private class Session implements ISoundTriggerModule {
+ private ISoundTriggerCallback mCallback;
+ private Map<Integer, Model> mLoadedModels = new HashMap<>();
+
+ /**
+ * Ctor.
+ *
+ * @param callback The client callback interface.
+ */
+ private Session(@NonNull ISoundTriggerCallback callback) {
+ mCallback = callback;
+ notifyRecognitionAvailability();
+ }
+
+ @Override
+ public void detach() {
+ Log.d(TAG, "detach()");
+ synchronized (SoundTriggerModule.this) {
+ removeSession(this);
+ }
+ }
+
+ @Override
+ public int loadModel(@NonNull SoundModel model) {
+ Log.d(TAG, String.format("loadModel(model=%s)", model));
+ synchronized (SoundTriggerModule.this) {
+ if (mNumLoadedModels == mProperties.maxSoundModels) {
+ throw new RecoverableException(Status.RESOURCE_CONTENTION,
+ "Maximum number of models loaded.");
+ }
+ Model loadedModel = new Model();
+ int result = loadedModel.load(model);
+ ++mNumLoadedModels;
+ return result;
+ }
+ }
+
+ @Override
+ public int loadPhraseModel(@NonNull PhraseSoundModel model) {
+ Log.d(TAG, String.format("loadPhraseModel(model=%s)", model));
+ synchronized (SoundTriggerModule.this) {
+ if (mNumLoadedModels == mProperties.maxSoundModels) {
+ throw new RecoverableException(Status.RESOURCE_CONTENTION,
+ "Maximum number of models loaded.");
+ }
+ Model loadedModel = new Model();
+ int result = loadedModel.load(model);
+ ++mNumLoadedModels;
+ Log.d(TAG, String.format("loadPhraseModel()->%d", result));
+ return result;
+ }
+ }
+
+ @Override
+ public void unloadModel(int modelHandle) {
+ Log.d(TAG, String.format("unloadModel(handle=%d)", modelHandle));
+ synchronized (SoundTriggerModule.this) {
+ mLoadedModels.get(modelHandle).unload();
+ --mNumLoadedModels;
+ }
+ }
+
+ @Override
+ public void startRecognition(int modelHandle, @NonNull RecognitionConfig config) {
+ Log.d(TAG,
+ String.format("startRecognition(handle=%d, config=%s)", modelHandle, config));
+ synchronized (SoundTriggerModule.this) {
+ mLoadedModels.get(modelHandle).startRecognition(config);
+ }
+ }
+
+ @Override
+ public void stopRecognition(int modelHandle) {
+ Log.d(TAG, String.format("stopRecognition(handle=%d)", modelHandle));
+ synchronized (SoundTriggerModule.this) {
+ mLoadedModels.get(modelHandle).stopRecognition();
+ }
+ }
+
+ @Override
+ public void forceRecognitionEvent(int modelHandle) {
+ Log.d(TAG, String.format("forceRecognitionEvent(handle=%d)", modelHandle));
+ synchronized (SoundTriggerModule.this) {
+ mLoadedModels.get(modelHandle).forceRecognitionEvent();
+ }
+ }
+
+ @Override
+ public void setModelParameter(int modelHandle, int modelParam, int value)
+ throws RemoteException {
+ Log.d(TAG,
+ String.format("setModelParameter(handle=%d, param=%d, value=%d)", modelHandle,
+ modelParam, value));
+ synchronized (SoundTriggerModule.this) {
+ mLoadedModels.get(modelHandle).setParameter(modelParam, value);
+ }
+ }
+
+ @Override
+ public int getModelParameter(int modelHandle, int modelParam) throws RemoteException {
+ Log.d(TAG, String.format("getModelParameter(handle=%d, param=%d)", modelHandle,
+ modelParam));
+ synchronized (SoundTriggerModule.this) {
+ return mLoadedModels.get(modelHandle).getParameter(modelParam);
+ }
+ }
+
+ @Override
+ @Nullable
+ public ModelParameterRange queryModelParameterSupport(int modelHandle, int modelParam) {
+ Log.d(TAG, String.format("queryModelParameterSupport(handle=%d, param=%d)", modelHandle,
+ modelParam));
+ synchronized (SoundTriggerModule.this) {
+ return mLoadedModels.get(modelHandle).queryModelParameterSupport(modelParam);
+ }
+ }
+
+ /**
+ * Abort all currently active recognitions.
+ */
+ private void abortActiveRecognitions() {
+ for (Model model : mLoadedModels.values()) {
+ model.abortActiveRecognition();
+ }
+ }
+
+ private void notifyRecognitionAvailability() {
+ try {
+ mCallback.onRecognitionAvailabilityChange(mRecognitionAvailable);
+ } catch (RemoteException e) {
+ // Dead client will be handled by binderDied() - no need to handle here.
+ // In any case, client callbacks are considered best effort.
+ Log.e(TAG, "Client callback execption.", e);
+ }
+ }
+
+ @Override
+ public @NonNull
+ IBinder asBinder() {
+ throw new UnsupportedOperationException(
+ "This implementation is not intended to be used directly with Binder.");
+ }
+
+ /**
+ * A single sound model in the system.
+ *
+ * All model-based operations are delegated to this class and implemented here.
+ */
+ private class Model implements ISoundTriggerHw2.Callback {
+ public int mHandle;
+ private ModelState mState = ModelState.INIT;
+ private int mModelType = SoundModelType.UNKNOWN;
+ private SoundTriggerMiddlewareImpl.AudioSessionProvider.AudioSession mSession;
+
+ private @NonNull
+ ModelState getState() {
+ return mState;
+ }
+
+ private void setState(@NonNull ModelState state) {
+ mState = state;
+ SoundTriggerModule.this.notifyAll();
+ }
+
+ private void waitStateChange() throws InterruptedException {
+ SoundTriggerModule.this.wait();
+ }
+
+ private int load(@NonNull SoundModel model) {
+ mModelType = model.type;
+ ISoundTriggerHw.SoundModel hidlModel = ConversionUtil.aidl2hidlSoundModel(model);
+
+ mSession = mAudioSessionProvider.acquireSession();
+ try {
+ mHandle = mHalService.loadSoundModel(hidlModel, this, 0);
+ } catch (Exception e) {
+ mAudioSessionProvider.releaseSession(mSession.mSessionHandle);
+ throw e;
+ }
+
+ setState(ModelState.LOADED);
+ mLoadedModels.put(mHandle, this);
+ return mHandle;
+ }
+
+ private int load(@NonNull PhraseSoundModel model) {
+ mModelType = model.common.type;
+ ISoundTriggerHw.PhraseSoundModel hidlModel =
+ ConversionUtil.aidl2hidlPhraseSoundModel(model);
+
+ mSession = mAudioSessionProvider.acquireSession();
+ try {
+ mHandle = mHalService.loadPhraseSoundModel(hidlModel, this, 0);
+ } catch (Exception e) {
+ mAudioSessionProvider.releaseSession(mSession.mSessionHandle);
+ throw e;
+ }
+
+ setState(ModelState.LOADED);
+ mLoadedModels.put(mHandle, this);
+ return mHandle;
+ }
+
+ private void unload() {
+ mAudioSessionProvider.releaseSession(mSession.mSessionHandle);
+ mHalService.unloadSoundModel(mHandle);
+ mLoadedModels.remove(mHandle);
+ }
+
+ private void startRecognition(@NonNull RecognitionConfig config) {
+ if (!mRecognitionAvailable) {
+ // Recognition is unavailable - send an abort event immediately.
+ notifyAbort();
+ return;
+ }
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.RecognitionConfig hidlConfig =
+ ConversionUtil.aidl2hidlRecognitionConfig(config);
+ hidlConfig.header.captureDevice = mSession.mDeviceHandle;
+ hidlConfig.header.captureHandle = mSession.mIoHandle;
+ mHalService.startRecognition(mHandle, hidlConfig, this, 0);
+ setState(ModelState.ACTIVE);
+ }
+
+ private void stopRecognition() {
+ if (getState() == ModelState.LOADED) {
+ // This call is idempotent in order to avoid races.
+ return;
+ }
+ mHalService.stopRecognition(mHandle);
+ setState(ModelState.LOADED);
+ }
+
+ /** Request a forced recognition event. Will do nothing if recognition is inactive. */
+ private void forceRecognitionEvent() {
+ if (getState() != ModelState.ACTIVE) {
+ // This call is idempotent in order to avoid races.
+ return;
+ }
+ mHalService.getModelState(mHandle);
+ }
+
+
+ private void setParameter(int modelParam, int value) {
+ mHalService.setModelParameter(mHandle,
+ ConversionUtil.aidl2hidlModelParameter(modelParam), value);
+ }
+
+ private int getParameter(int modelParam) {
+ return mHalService.getModelParameter(mHandle,
+ ConversionUtil.aidl2hidlModelParameter(modelParam));
+ }
+
+ @Nullable
+ private ModelParameterRange queryModelParameterSupport(int modelParam) {
+ return ConversionUtil.hidl2aidlModelParameterRange(
+ mHalService.queryParameter(mHandle,
+ ConversionUtil.aidl2hidlModelParameter(modelParam)));
+ }
+
+ /** Abort the recognition, if active. */
+ private void abortActiveRecognition() {
+ // If we're inactive, do nothing.
+ if (getState() != ModelState.ACTIVE) {
+ return;
+ }
+ // Stop recognition.
+ stopRecognition();
+
+ // Notify the client that recognition has been aborted.
+ notifyAbort();
+ }
+
+ /** Notify the client that recognition has been aborted. */
+ private void notifyAbort() {
+ try {
+ switch (mModelType) {
+ case SoundModelType.GENERIC: {
+ android.media.soundtrigger_middleware.RecognitionEvent event =
+ new android.media.soundtrigger_middleware.RecognitionEvent();
+ event.status =
+ android.media.soundtrigger_middleware.RecognitionStatus.ABORTED;
+ mCallback.onRecognition(mHandle, event);
+ }
+ break;
+
+ case SoundModelType.KEYPHRASE: {
+ android.media.soundtrigger_middleware.PhraseRecognitionEvent event =
+ new android.media.soundtrigger_middleware.PhraseRecognitionEvent();
+ event.common =
+ new android.media.soundtrigger_middleware.RecognitionEvent();
+ event.common.status =
+ android.media.soundtrigger_middleware.RecognitionStatus.ABORTED;
+ mCallback.onPhraseRecognition(mHandle, event);
+ }
+ break;
+
+ default:
+ Log.e(TAG, "Unknown model type: " + mModelType);
+
+ }
+ } catch (RemoteException e) {
+ // Dead client will be handled by binderDied() - no need to handle here.
+ // In any case, client callbacks are considered best effort.
+ Log.e(TAG, "Client callback execption.", e);
+ }
+ }
+
+ @Override
+ public void recognitionCallback(
+ @NonNull ISoundTriggerHwCallback.RecognitionEvent recognitionEvent,
+ int cookie) {
+ Log.d(TAG, String.format("recognitionCallback_2_1(event=%s, cookie=%d)",
+ recognitionEvent, cookie));
+ synchronized (SoundTriggerModule.this) {
+ android.media.soundtrigger_middleware.RecognitionEvent aidlEvent =
+ ConversionUtil.hidl2aidlRecognitionEvent(recognitionEvent);
+ aidlEvent.captureSession = mSession.mSessionHandle;
+ try {
+ mCallback.onRecognition(mHandle, aidlEvent);
+ } catch (RemoteException e) {
+ // Dead client will be handled by binderDied() - no need to handle here.
+ // In any case, client callbacks are considered best effort.
+ Log.e(TAG, "Client callback execption.", e);
+ }
+ if (aidlEvent.status
+ != android.media.soundtrigger_middleware.RecognitionStatus.FORCED) {
+ setState(ModelState.LOADED);
+ }
+ }
+ }
+
+ @Override
+ public void phraseRecognitionCallback(
+ @NonNull ISoundTriggerHwCallback.PhraseRecognitionEvent phraseRecognitionEvent,
+ int cookie) {
+ Log.d(TAG, String.format("phraseRecognitionCallback_2_1(event=%s, cookie=%d)",
+ phraseRecognitionEvent, cookie));
+ synchronized (SoundTriggerModule.this) {
+ android.media.soundtrigger_middleware.PhraseRecognitionEvent aidlEvent =
+ ConversionUtil.hidl2aidlPhraseRecognitionEvent(phraseRecognitionEvent);
+ aidlEvent.common.captureSession = mSession.mSessionHandle;
+ try {
+ mCallback.onPhraseRecognition(mHandle, aidlEvent);
+ } catch (RemoteException e) {
+ // Dead client will be handled by binderDied() - no need to handle here.
+ // In any case, client callbacks are considered best effort.
+ Log.e(TAG, "Client callback execption.", e);
+ }
+ if (aidlEvent.common.status
+ != android.media.soundtrigger_middleware.RecognitionStatus.FORCED) {
+ setState(ModelState.LOADED);
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/services/core/java/com/android/server/soundtrigger_middleware/TEST_MAPPING b/services/core/java/com/android/server/soundtrigger_middleware/TEST_MAPPING
new file mode 100644
index 000000000000..9ed894bc1ca9
--- /dev/null
+++ b/services/core/java/com/android/server/soundtrigger_middleware/TEST_MAPPING
@@ -0,0 +1,12 @@
+{
+ "presubmit": [
+ {
+ "name": "FrameworksServicesTests",
+ "options": [
+ {
+ "include-filter": "com.android.server.soundtrigger_middleware"
+ }
+ ]
+ }
+ ]
+}
diff --git a/services/core/java/com/android/server/soundtrigger_middleware/UuidUtil.java b/services/core/java/com/android/server/soundtrigger_middleware/UuidUtil.java
new file mode 100644
index 000000000000..80f69d08c089
--- /dev/null
+++ b/services/core/java/com/android/server/soundtrigger_middleware/UuidUtil.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.soundtrigger_middleware;
+
+import java.util.regex.Pattern;
+
+/**
+ * Utilities for representing UUIDs as strings.
+ *
+ * @hide
+ */
+public class UuidUtil {
+ /**
+ * Regex pattern that can be used to validate / extract the various fields of a string-formatted
+ * UUID.
+ */
+ static final Pattern PATTERN = Pattern.compile("^([a-fA-F0-9]{8})-" +
+ "([a-fA-F0-9]{4})-" +
+ "([a-fA-F0-9]{4})-" +
+ "([a-fA-F0-9]{4})-" +
+ "([a-fA-F0-9]{2})" +
+ "([a-fA-F0-9]{2})" +
+ "([a-fA-F0-9]{2})" +
+ "([a-fA-F0-9]{2})" +
+ "([a-fA-F0-9]{2})" +
+ "([a-fA-F0-9]{2})$");
+
+ /** Printf-style pattern for formatting the various fields of a UUID as a string. */
+ static final String FORMAT = "%08x-%04x-%04x-%04x-%02x%02x%02x%02x%02x%02x";
+}
diff --git a/services/core/java/com/android/server/soundtrigger_middleware/ValidationUtil.java b/services/core/java/com/android/server/soundtrigger_middleware/ValidationUtil.java
new file mode 100644
index 000000000000..4898e6b59ab2
--- /dev/null
+++ b/services/core/java/com/android/server/soundtrigger_middleware/ValidationUtil.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.soundtrigger_middleware;
+
+import android.annotation.Nullable;
+import android.media.soundtrigger_middleware.ConfidenceLevel;
+import android.media.soundtrigger_middleware.ModelParameter;
+import android.media.soundtrigger_middleware.Phrase;
+import android.media.soundtrigger_middleware.PhraseRecognitionExtra;
+import android.media.soundtrigger_middleware.PhraseSoundModel;
+import android.media.soundtrigger_middleware.RecognitionConfig;
+import android.media.soundtrigger_middleware.RecognitionMode;
+import android.media.soundtrigger_middleware.SoundModel;
+import android.media.soundtrigger_middleware.SoundModelType;
+
+import com.android.internal.util.Preconditions;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Utilities for asserting the validity of various data types used by this module.
+ * Each of the methods below would throw an {@link IllegalArgumentException} if its input is
+ * invalid. The input's validity is determined irrespective of any context. In cases where the valid
+ * value space is further limited by state, it is the caller's responsibility to assert.
+ *
+ * @hide
+ */
+public class ValidationUtil {
+ static void validateUuid(@Nullable String uuid) {
+ Preconditions.checkNotNull(uuid);
+ Matcher matcher = UuidUtil.PATTERN.matcher(uuid);
+ if (!matcher.matches()) {
+ throw new IllegalArgumentException(
+ "Illegal format for UUID: " + uuid);
+ }
+ }
+
+ static void validateGenericModel(@Nullable SoundModel model) {
+ validateModel(model, SoundModelType.GENERIC);
+ }
+
+ static void validateModel(@Nullable SoundModel model, int expectedType) {
+ Preconditions.checkNotNull(model);
+ if (model.type != expectedType) {
+ throw new IllegalArgumentException("Invalid type");
+ }
+ validateUuid(model.uuid);
+ validateUuid(model.vendorUuid);
+ Preconditions.checkNotNull(model.data);
+ }
+
+ static void validatePhraseModel(@Nullable PhraseSoundModel model) {
+ Preconditions.checkNotNull(model);
+ validateModel(model.common, SoundModelType.KEYPHRASE);
+ Preconditions.checkNotNull(model.phrases);
+ for (Phrase phrase : model.phrases) {
+ Preconditions.checkNotNull(phrase);
+ if ((phrase.recognitionModes & ~(RecognitionMode.VOICE_TRIGGER
+ | RecognitionMode.USER_IDENTIFICATION | RecognitionMode.USER_AUTHENTICATION
+ | RecognitionMode.GENERIC_TRIGGER)) != 0) {
+ throw new IllegalArgumentException("Invalid recognitionModes");
+ }
+ Preconditions.checkNotNull(phrase.users);
+ Preconditions.checkNotNull(phrase.locale);
+ Preconditions.checkNotNull(phrase.text);
+ }
+ }
+
+ static void validateRecognitionConfig(@Nullable RecognitionConfig config) {
+ Preconditions.checkNotNull(config);
+ Preconditions.checkNotNull(config.phraseRecognitionExtras);
+ for (PhraseRecognitionExtra extra : config.phraseRecognitionExtras) {
+ Preconditions.checkNotNull(extra);
+ if ((extra.recognitionModes & ~(RecognitionMode.VOICE_TRIGGER
+ | RecognitionMode.USER_IDENTIFICATION | RecognitionMode.USER_AUTHENTICATION
+ | RecognitionMode.GENERIC_TRIGGER)) != 0) {
+ throw new IllegalArgumentException("Invalid recognitionModes");
+ }
+ if (extra.confidenceLevel < 0 || extra.confidenceLevel > 100) {
+ throw new IllegalArgumentException("Invalid confidenceLevel");
+ }
+ Preconditions.checkNotNull(extra.levels);
+ for (ConfidenceLevel level : extra.levels) {
+ Preconditions.checkNotNull(level);
+ if (level.levelPercent < 0 || level.levelPercent > 100) {
+ throw new IllegalArgumentException("Invalid confidenceLevel");
+ }
+ }
+ }
+ Preconditions.checkNotNull(config.data);
+ }
+
+ static void validateModelParameter(int modelParam) {
+ switch (modelParam) {
+ case ModelParameter.THRESHOLD_FACTOR:
+ return;
+
+ default:
+ throw new IllegalArgumentException("Invalid model parameter");
+ }
+ }
+}
diff --git a/services/core/java/com/android/server/storage/StorageSessionController.java b/services/core/java/com/android/server/storage/StorageSessionController.java
index d76836f90e6b..aa3ab63a32bb 100644
--- a/services/core/java/com/android/server/storage/StorageSessionController.java
+++ b/services/core/java/com/android/server/storage/StorageSessionController.java
@@ -43,7 +43,6 @@ import com.android.internal.annotations.GuardedBy;
import com.android.internal.util.Preconditions;
import java.io.FileDescriptor;
-import java.io.IOException;
/**
* Controls storage sessions for users initiated by the {@link StorageManagerService}.
@@ -101,18 +100,10 @@ public final class StorageSessionController {
connection = new StorageUserConnection(mContext, userId, this);
mConnections.put(userId, connection);
}
- Slog.i(TAG, "Creating session with id: " + sessionId);
- connection.createSession(sessionId, new ParcelFileDescriptor(deviceFd),
+ Slog.i(TAG, "Creating and starting session with id: " + sessionId);
+ connection.startSession(sessionId, new ParcelFileDescriptor(deviceFd),
vol.getPath().getPath(), vol.getInternalPath().getPath());
}
-
- // At boot, a volume can be mounted before user is unlocked, in that case, we create it
- // above and save it so that we can restart all sessions when the user is unlocked
- if (mExternalStorageServiceComponent != null) {
- connection.startSession(sessionId);
- } else {
- Slog.i(TAG, "Controller not initialised, session not started " + sessionId);
- }
}
/**
@@ -179,23 +170,32 @@ public final class StorageSessionController {
* a session will be ignored.
*/
public void onUnlockUser(int userId) throws ExternalStorageServiceException {
- if (!shouldHandle(null)) {
- return;
- }
-
Slog.i(TAG, "On user unlock " + userId);
- if (userId == 0) {
+ if (shouldHandle(null) && userId == 0) {
initExternalStorageServiceComponent();
}
+ }
+ /**
+ * Called when a user is in the process is being stopped.
+ *
+ * Does nothing if {@link #shouldHandle} is {@code false}
+ *
+ * This call removes all sessions for the user that is being stopped;
+ * this will make sure that we don't rebind to the service needlessly.
+ */
+ public void onUserStopping(int userId) throws ExternalStorageServiceException {
+ if (!shouldHandle(null)) {
+ return;
+ }
StorageUserConnection connection = null;
synchronized (mLock) {
connection = mConnections.get(userId);
}
if (connection != null) {
- Slog.i(TAG, "Restarting all sessions for user: " + userId);
- connection.startAllSessions();
+ Slog.i(TAG, "Removing all sessions for user: " + userId);
+ connection.removeAllSessions();
} else {
Slog.w(TAG, "No connection found for user: " + userId);
}
@@ -308,34 +308,6 @@ public final class StorageSessionController {
}
/**
- * Throws an {@link IllegalStateException} if {@code path} is not ready to be accessed by
- * {@code userId}.
- */
- // TODO(b/144332951): This is not used because it is racy. Right after checking a path
- // we can call into vold with that path and the FUSE daemon can go down. Improve or remove
- public void checkPathReadyForUser(int userId, String path) {
- if (!mIsFuseEnabled) {
- return;
- }
-
- if (mIsResetting) {
- throw new IllegalStateException("Connection resetting for user " + userId
- + " with path " + path);
- }
-
- StorageUserConnection connection = null;
- synchronized (mLock) {
- connection = mConnections.get(userId);
- }
-
- if (connection == null) {
- throw new IllegalStateException("Connection not ready for user " + userId
- + " with path " + path);
- }
- connection.checkPathReady(path);
- }
-
- /**
* Returns {@code true} if {@code vol} is an emulated or public volume,
* {@code false} otherwise
**/
diff --git a/services/core/java/com/android/server/storage/StorageUserConnection.java b/services/core/java/com/android/server/storage/StorageUserConnection.java
index 7c4773033518..10514ad7edcb 100644
--- a/services/core/java/com/android/server/storage/StorageUserConnection.java
+++ b/services/core/java/com/android/server/storage/StorageUserConnection.java
@@ -34,6 +34,7 @@ import android.os.ParcelFileDescriptor;
import android.os.ParcelableException;
import android.os.RemoteCallback;
import android.os.UserHandle;
+import android.os.storage.StorageManagerInternal;
import android.service.storage.ExternalStorageService;
import android.service.storage.IExternalStorageService;
import android.text.TextUtils;
@@ -41,6 +42,7 @@ import android.util.Slog;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.util.Preconditions;
+import com.android.server.LocalServices;
import java.io.IOException;
import java.util.HashMap;
@@ -73,42 +75,25 @@ public final class StorageUserConnection {
}
/**
- * Creates and stores a storage {@link Session}.
+ * Creates and starts a storage {@link Session}.
*
* They must also be cleaned up with {@link #removeSession}.
*
* @throws IllegalArgumentException if a {@code Session} with {@code sessionId} already exists
*/
- public void createSession(String sessionId, ParcelFileDescriptor pfd, String upperPath,
- String lowerPath) {
+ public void startSession(String sessionId, ParcelFileDescriptor pfd, String upperPath,
+ String lowerPath) throws ExternalStorageServiceException {
Preconditions.checkNotNull(sessionId);
Preconditions.checkNotNull(pfd);
Preconditions.checkNotNull(upperPath);
Preconditions.checkNotNull(lowerPath);
- synchronized (mLock) {
- Preconditions.checkArgument(!mSessions.containsKey(sessionId));
- mSessions.put(sessionId, new Session(sessionId, pfd, upperPath, lowerPath));
- }
- }
-
- /**
- * Starts an already created storage {@link Session} for {@code sessionId}.
- *
- * It is safe to call this multiple times, however if the session is already started,
- * subsequent calls will be ignored.
- *
- * @throws ExternalStorageServiceException if the session failed to start
- **/
- public void startSession(String sessionId) throws ExternalStorageServiceException {
- Session session;
- synchronized (mLock) {
- session = mSessions.get(sessionId);
- }
-
prepareRemote();
synchronized (mLock) {
- mActiveConnection.startSessionLocked(session);
+ Preconditions.checkArgument(!mSessions.containsKey(sessionId));
+ Session session = new Session(sessionId, upperPath, lowerPath);
+ mSessions.put(sessionId, session);
+ mActiveConnection.startSessionLocked(session, pfd);
}
}
@@ -121,16 +106,10 @@ public final class StorageUserConnection {
**/
public Session removeSession(String sessionId) {
synchronized (mLock) {
- Session session = mSessions.remove(sessionId);
- if (session != null) {
- session.close();
- return session;
- }
- return null;
+ return mSessions.remove(sessionId);
}
}
-
/**
* Removes a session and waits for exit
*
@@ -150,25 +129,29 @@ public final class StorageUserConnection {
}
}
- /** Starts all available sessions for a user without blocking. Any failures will be ignored. */
- public void startAllSessions() {
- try {
- prepareRemote();
- } catch (ExternalStorageServiceException e) {
- Slog.e(TAG, "Failed to start all sessions for user: " + mUserId, e);
- return;
+ /** Restarts all available sessions for a user without blocking.
+ *
+ * Any failures will be ignored.
+ **/
+ public void resetUserSessions() {
+ synchronized (mLock) {
+ if (mSessions.isEmpty()) {
+ // Nothing to reset if we have no sessions to restart; we typically
+ // hit this path if the user was consciously shut down.
+ return;
+ }
}
+ StorageManagerInternal sm = LocalServices.getService(StorageManagerInternal.class);
+ sm.resetUser(mUserId);
+ }
+ /**
+ * Removes all sessions, without waiting.
+ */
+ public void removeAllSessions() {
synchronized (mLock) {
- Slog.i(TAG, "Starting " + mSessions.size() + " sessions for user: " + mUserId + "...");
- for (Session session : mSessions.values()) {
- try {
- mActiveConnection.startSessionLocked(session);
- } catch (IllegalStateException | ExternalStorageServiceException e) {
- // TODO: Don't crash process? We could get into process crash loop
- Slog.e(TAG, "Failed to start " + session, e);
- }
- }
+ Slog.i(TAG, "Removing " + mSessions.size() + " sessions for user: " + mUserId + "...");
+ mSessions.clear();
}
}
@@ -180,20 +163,6 @@ public final class StorageUserConnection {
mActiveConnection.close();
}
- /** Throws an {@link IllegalArgumentException} if {@code path} is not ready for access */
- public void checkPathReady(String path) {
- synchronized (mLock) {
- for (Session session : mSessions.values()) {
- if (session.upperPath != null && path.startsWith(session.upperPath)) {
- if (mActiveConnection.isActiveLocked(session)) {
- return;
- }
- }
- }
- throw new IllegalStateException("Path not ready " + path);
- }
- }
-
/** Returns all created sessions. */
public Set<String> getAllSessionIds() {
synchronized (mLock) {
@@ -269,26 +238,37 @@ public final class StorageUserConnection {
return true;
}
- public void startSessionLocked(Session session) throws ExternalStorageServiceException {
+ public void startSessionLocked(Session session, ParcelFileDescriptor fd)
+ throws ExternalStorageServiceException {
if (!isActiveLocked(session)) {
+ try {
+ fd.close();
+ } catch (IOException e) {
+ // ignore
+ }
return;
}
CountDownLatch latch = new CountDownLatch(1);
- try (ParcelFileDescriptor dupedPfd = session.pfd.dup()) {
+ try {
mRemote.startSession(session.sessionId,
FLAG_SESSION_TYPE_FUSE | FLAG_SESSION_ATTRIBUTE_INDEXABLE,
- dupedPfd, session.upperPath, session.lowerPath, new RemoteCallback(result ->
+ fd, session.upperPath, session.lowerPath, new RemoteCallback(result ->
setResultLocked(latch, result)));
waitForLatch(latch, "start_session " + session);
maybeThrowExceptionLocked();
} catch (Exception e) {
throw new ExternalStorageServiceException("Failed to start session: " + session, e);
+ } finally {
+ try {
+ fd.close();
+ } catch (IOException e) {
+ // Ignore
+ }
}
}
public void endSessionLocked(Session session) throws ExternalStorageServiceException {
- session.close();
if (!isActiveLocked(session)) {
// Nothing to end, not started yet
return;
@@ -390,7 +370,7 @@ public final class StorageUserConnection {
// will be called for any required mounts.
// Notify StorageManagerService so it can restart all necessary sessions
close();
- new Thread(StorageUserConnection.this::startAllSessions).start();
+ resetUserSessions();
}
};
}
@@ -411,29 +391,18 @@ public final class StorageUserConnection {
}
}
- private static final class Session implements AutoCloseable {
+ private static final class Session {
public final String sessionId;
- public final ParcelFileDescriptor pfd;
public final String lowerPath;
public final String upperPath;
- Session(String sessionId, ParcelFileDescriptor pfd, String upperPath, String lowerPath) {
+ Session(String sessionId, String upperPath, String lowerPath) {
this.sessionId = sessionId;
- this.pfd = pfd;
this.upperPath = upperPath;
this.lowerPath = lowerPath;
}
@Override
- public void close() {
- try {
- pfd.close();
- } catch (IOException e) {
- Slog.i(TAG, "Failed to close session: " + this);
- }
- }
-
- @Override
public String toString() {
return "[SessionId: " + sessionId + ". UpperPath: " + upperPath + ". LowerPath: "
+ lowerPath + "]";
diff --git a/services/core/java/com/android/server/textclassifier/TextClassificationManagerService.java b/services/core/java/com/android/server/textclassifier/TextClassificationManagerService.java
index 7d905bae4491..6a986b9da515 100644
--- a/services/core/java/com/android/server/textclassifier/TextClassificationManagerService.java
+++ b/services/core/java/com/android/server/textclassifier/TextClassificationManagerService.java
@@ -24,15 +24,12 @@ import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
-import android.database.ContentObserver;
-import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.Process;
import android.os.RemoteException;
import android.os.UserHandle;
import android.provider.DeviceConfig;
-import android.provider.Settings;
import android.service.textclassifier.ITextClassifierCallback;
import android.service.textclassifier.ITextClassifierService;
import android.service.textclassifier.TextClassifierService;
@@ -41,7 +38,6 @@ import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Slog;
import android.util.SparseArray;
-import android.view.textclassifier.ConfigParser;
import android.view.textclassifier.ConversationActions;
import android.view.textclassifier.SelectionEvent;
import android.view.textclassifier.TextClassification;
@@ -143,7 +139,7 @@ public final class TextClassificationManagerService extends ITextClassifierServi
private TextClassificationManagerService(Context context) {
mContext = Preconditions.checkNotNull(context);
mLock = new Object();
- mSettingsListener = new TextClassifierSettingsListener(mContext, this);
+ mSettingsListener = new TextClassifierSettingsListener(mContext);
}
private void startListenSettings() {
@@ -171,10 +167,8 @@ public final class TextClassificationManagerService extends ITextClassifierServi
Slog.d(LOG_TAG, "Unable to bind TextClassifierService at suggestSelection.");
callback.onFailure();
} else if (userState.isBoundLocked()) {
- if (!userState.isRequestAcceptedLocked(Binder.getCallingUid())) {
- Slog.d(LOG_TAG,
- "Only allow to see own content for non-default service at "
- + "suggestSelection.");
+ if (!userState.checkRequestAcceptedLocked(Binder.getCallingUid(),
+ "suggestSelection")) {
return;
}
userState.mService.onSuggestSelection(sessionId, request, callback);
@@ -203,10 +197,7 @@ public final class TextClassificationManagerService extends ITextClassifierServi
Slog.d(LOG_TAG, "Unable to bind TextClassifierService at classifyText.");
callback.onFailure();
} else if (userState.isBoundLocked()) {
- if (!userState.isRequestAcceptedLocked(Binder.getCallingUid())) {
- Slog.d(LOG_TAG,
- "Only allow to see own content for non-default service at "
- + "classifyText.");
+ if (!userState.checkRequestAcceptedLocked(Binder.getCallingUid(), "classifyText")) {
return;
}
userState.mService.onClassifyText(sessionId, request, callback);
@@ -235,10 +226,8 @@ public final class TextClassificationManagerService extends ITextClassifierServi
Slog.d(LOG_TAG, "Unable to bind TextClassifierService at generateLinks.");
callback.onFailure();
} else if (userState.isBoundLocked()) {
- if (!userState.isRequestAcceptedLocked(Binder.getCallingUid())) {
- Slog.d(LOG_TAG,
- "Only allow to see own content for non-default service at "
- + "generateLinks.");
+ if (!userState.checkRequestAcceptedLocked(Binder.getCallingUid(),
+ "generateLinks")) {
return;
}
userState.mService.onGenerateLinks(sessionId, request, callback);
@@ -262,10 +251,8 @@ public final class TextClassificationManagerService extends ITextClassifierServi
synchronized (mLock) {
UserState userState = getUserStateLocked(userId);
if (userState.isBoundLocked()) {
- if (!userState.isRequestAcceptedLocked(Binder.getCallingUid())) {
- Slog.d(LOG_TAG,
- "Only allow to see own content for non-default service at "
- + "selectionEvent.");
+ if (!userState.checkRequestAcceptedLocked(Binder.getCallingUid(),
+ "selectionEvent")) {
return;
}
userState.mService.onSelectionEvent(sessionId, event);
@@ -293,10 +280,8 @@ public final class TextClassificationManagerService extends ITextClassifierServi
synchronized (mLock) {
UserState userState = getUserStateLocked(userId);
if (userState.isBoundLocked()) {
- if (!userState.isRequestAcceptedLocked(Binder.getCallingUid())) {
- Slog.d(LOG_TAG,
- "Only allow to see own content for non-default service at "
- + "textClassifierEvent.");
+ if (!userState.checkRequestAcceptedLocked(Binder.getCallingUid(),
+ "textClassifierEvent")) {
return;
}
userState.mService.onTextClassifierEvent(sessionId, event);
@@ -325,10 +310,8 @@ public final class TextClassificationManagerService extends ITextClassifierServi
Slog.d(LOG_TAG, "Unable to bind TextClassifierService at detectLanguage.");
callback.onFailure();
} else if (userState.isBoundLocked()) {
- if (!userState.isRequestAcceptedLocked(Binder.getCallingUid())) {
- Slog.d(LOG_TAG,
- "Only allow to see own content for non-default service at "
- + "detectLanguage.");
+ if (!userState.checkRequestAcceptedLocked(Binder.getCallingUid(),
+ "detectLanguage")) {
return;
}
userState.mService.onDetectLanguage(sessionId, request, callback);
@@ -358,10 +341,8 @@ public final class TextClassificationManagerService extends ITextClassifierServi
"Unable to bind TextClassifierService at suggestConversationActions.");
callback.onFailure();
} else if (userState.isBoundLocked()) {
- if (!userState.isRequestAcceptedLocked(Binder.getCallingUid())) {
- Slog.d(LOG_TAG,
- "Only allow to see own content for non-default service at "
- + "suggestConversationActions.");
+ if (!userState.checkRequestAcceptedLocked(Binder.getCallingUid(),
+ "suggestConversationActions")) {
return;
}
userState.mService.onSuggestConversationActions(sessionId, request, callback);
@@ -387,10 +368,8 @@ public final class TextClassificationManagerService extends ITextClassifierServi
synchronized (mLock) {
UserState userState = getUserStateLocked(userId);
if (userState.isBoundLocked()) {
- if (!userState.isRequestAcceptedLocked(Binder.getCallingUid())) {
- Slog.d(LOG_TAG,
- "Only allow to see own content for non-default service at "
- + "createTextClassificationSession.");
+ if (!userState.checkRequestAcceptedLocked(Binder.getCallingUid(),
+ "createTextClassificationSession")) {
return;
}
userState.mService.onCreateTextClassificationSession(
@@ -422,10 +401,8 @@ public final class TextClassificationManagerService extends ITextClassifierServi
UserState userState = getUserStateLocked(userId);
if (userState.isBoundLocked()) {
- if (!userState.isRequestAcceptedLocked(Binder.getCallingUid())) {
- Slog.d(LOG_TAG,
- "Only allow to see own content for non-default service at "
- + "destroyTextClassificationSession.");
+ if (!userState.checkRequestAcceptedLocked(Binder.getCallingUid(),
+ "destroyTextClassificationSession")) {
return;
}
userState.mService.onDestroyTextClassificationSession(sessionId);
@@ -488,6 +465,29 @@ public final class TextClassificationManagerService extends ITextClassifierServi
}
}
+ private void unbindServiceIfNecessary() {
+ final ComponentName serviceComponentName =
+ TextClassifierService.getServiceComponentName(mContext);
+ if (serviceComponentName == null) {
+ // It should not occur if we had defined default service names in config.xml
+ Slog.w(LOG_TAG, "No default configured system TextClassifierService.");
+ return;
+ }
+ synchronized (mLock) {
+ final int size = mUserStates.size();
+ for (int i = 0; i < size; i++) {
+ UserState userState = mUserStates.valueAt(i);
+ // Only unbind for a new service
+ if (userState.isCurrentlyBoundToComponentLocked(serviceComponentName)) {
+ return;
+ }
+ if (userState.isBoundLocked()) {
+ userState.unbindLocked();
+ }
+ }
+ }
+ }
+
private static final class PendingRequest implements IBinder.DeathRecipient {
private final int mUid;
@@ -582,48 +582,6 @@ public final class TextClassificationManagerService extends ITextClassifierServi
}
}
- private TextClassificationConstants getTextClassifierSettings(Context context) {
- synchronized (mLock) {
- if (mSettings == null) {
- mSettings = new TextClassificationConstants(
- () -> Settings.Global.getString(
- context.getContentResolver(),
- Settings.Global.TEXT_CLASSIFIER_CONSTANTS));
- }
- return mSettings;
- }
- }
-
- private void invalidateSettings() {
- synchronized (mLock) {
- mSettings = null;
- }
- }
-
- private void unbindServiceIfNeeded() {
- final ComponentName serviceComponentName =
- TextClassifierService.getServiceComponentName(mContext,
- getTextClassifierSettings(mContext));
- if (serviceComponentName == null) {
- // It should not occur if we had defined default service name in config
- Slog.w(LOG_TAG, "No default configured system TextClassifierService.");
- return;
- }
- synchronized (mLock) {
- final int size = mUserStates.size();
- for (int i = 0; i < size; i++) {
- UserState userState = mUserStates.valueAt(i);
- // Only unbind for a new service
- if (userState.isServiceCurrentBoundLocked(serviceComponentName)) {
- return;
- }
- if (userState.isBoundLocked()) {
- userState.unbindLocked();
- }
- }
- }
- }
-
private final class UserState {
@UserIdInt final int mUserId;
@GuardedBy("mLock")
@@ -635,9 +593,9 @@ public final class TextClassificationManagerService extends ITextClassifierServi
@GuardedBy("mLock")
boolean mBinding;
@GuardedBy("mLock")
- ComponentName mBoundServiceComponent = null;
+ ComponentName mBoundComponentName = null;
@GuardedBy("mLock")
- boolean mIsBoundToDefaultService;
+ boolean mBoundToDefaultTrustService;
@GuardedBy("mLock")
int mBoundServiceUid;
@@ -660,10 +618,7 @@ public final class TextClassificationManagerService extends ITextClassifierServi
PendingRequest request;
while ((request = mPendingRequests.poll()) != null) {
if (isBoundLocked()) {
- if (!isRequestAcceptedLocked(request.mUid)) {
- Slog.d(LOG_TAG,
- "Only allow to see own content for non-default service at "
- + request.mName);
+ if (!checkRequestAcceptedLocked(request.mUid, request.mName)) {
return;
}
request.mRequest.run();
@@ -687,15 +642,15 @@ public final class TextClassificationManagerService extends ITextClassifierServi
}
@GuardedBy("mLock")
- private boolean isServiceCurrentBoundLocked(@NonNull ComponentName componentName) {
- return (mBoundServiceComponent != null
- && mBoundServiceComponent.getPackageName().equals(
+ private boolean isCurrentlyBoundToComponentLocked(@NonNull ComponentName componentName) {
+ return (mBoundComponentName != null
+ && mBoundComponentName.getPackageName().equals(
componentName.getPackageName()));
}
@GuardedBy("mLock")
private void unbindLocked() {
- Slog.d(LOG_TAG, "unbinding to " + mBoundServiceComponent + " for " + mUserId);
+ Slog.v(LOG_TAG, "unbinding from " + mBoundComponentName + " for " + mUserId);
mContext.unbindService(mConnection);
mConnection.cleanupService();
mConnection = null;
@@ -716,8 +671,7 @@ public final class TextClassificationManagerService extends ITextClassifierServi
final long identity = Binder.clearCallingIdentity();
try {
final ComponentName componentName =
- TextClassifierService.getServiceComponentName(mContext,
- getTextClassifierSettings(mContext));
+ TextClassifierService.getServiceComponentName(mContext);
if (componentName == null) {
// Might happen if the storage is encrypted and the user is not unlocked
return false;
@@ -742,8 +696,8 @@ public final class TextClassificationManagerService extends ITextClassifierServi
pw.printPair("context", mContext);
pw.printPair("userId", mUserId);
synchronized (mLock) {
- pw.printPair("BoundServiceComponent", mBoundServiceComponent);
- pw.printPair("isBoundToDefaultService", mIsBoundToDefaultService);
+ pw.printPair("boundComponentName", mBoundComponentName);
+ pw.printPair("boundToDefaultTrustService", mBoundToDefaultTrustService);
pw.printPair("boundServiceUid", mBoundServiceUid);
pw.printPair("binding", mBinding);
pw.printPair("numberRequests", mPendingRequests.size());
@@ -751,14 +705,17 @@ public final class TextClassificationManagerService extends ITextClassifierServi
}
@GuardedBy("mLock")
- private boolean isRequestAcceptedLocked(int requestUid) {
- if (mIsBoundToDefaultService) {
+ private boolean checkRequestAcceptedLocked(int requestUid, @NonNull String methodName) {
+ if (mBoundToDefaultTrustService || (requestUid == mBoundServiceUid)) {
return true;
}
- return (requestUid == mBoundServiceUid);
+ Slog.w(LOG_TAG, String.format(
+ "[%s] Non-default TextClassifierServices may only see text from the same uid.",
+ methodName));
+ return false;
}
- private boolean isDefaultService(@NonNull ComponentName currentService) {
+ private boolean isDefaultTrustService(@NonNull ComponentName currentService) {
final String[] defaultServiceNames =
mContext.getPackageManager().getSystemTextClassifierPackages();
final String servicePackageName = currentService.getPackageName();
@@ -789,16 +746,16 @@ public final class TextClassificationManagerService extends ITextClassifierServi
}
@GuardedBy("mLock")
- private void updateServiceInfoLocked(@Nullable ComponentName componentName, int userId) {
- mBoundServiceComponent = componentName;
- mIsBoundToDefaultService = (mBoundServiceComponent != null && isDefaultService(
- mBoundServiceComponent));
- mBoundServiceUid = getServiceUid(mBoundServiceComponent, userId);
+ private void updateServiceInfoLocked(int userId, @Nullable ComponentName componentName) {
+ mBoundComponentName = componentName;
+ mBoundToDefaultTrustService = (mBoundComponentName != null && isDefaultTrustService(
+ mBoundComponentName));
+ mBoundServiceUid = getServiceUid(mBoundComponentName, userId);
}
private final class TextClassifierServiceConnection implements ServiceConnection {
- @UserIdInt final int mUserId;
+ @UserIdInt private final int mUserId;
TextClassifierServiceConnection(int userId) {
mUserId = userId;
@@ -840,60 +797,42 @@ public final class TextClassificationManagerService extends ITextClassifierServi
synchronized (mLock) {
mService = service;
mBinding = false;
- updateServiceInfoLocked(name, mUserId);
+ updateServiceInfoLocked(mUserId, name);
handlePendingRequestsLocked();
}
}
}
}
- private final class TextClassifierSettingsListener extends ContentObserver
- implements DeviceConfig.OnPropertiesChangedListener {
+ private final class TextClassifierSettingsListener implements
+ DeviceConfig.OnPropertiesChangedListener {
@NonNull private final Context mContext;
+ @NonNull private final TextClassificationConstants mSettings;
@Nullable private String mServicePackageName;
- TextClassifierSettingsListener(Context context, TextClassificationManagerService service) {
- super(null);
+ TextClassifierSettingsListener(Context context) {
mContext = context;
- mServicePackageName =
- getTextClassifierSettings(mContext).getTextClassifierServiceName();
+ mSettings = TextClassificationManager.getSettings(mContext);
+ mServicePackageName = mSettings.getTextClassifierServicePackageOverride();
}
public void registerObserver() {
- mContext.getContentResolver().registerContentObserver(
- Settings.Global.getUriFor(Settings.Global.TEXT_CLASSIFIER_CONSTANTS),
- false /* notifyForDescendants */,
+ DeviceConfig.addOnPropertiesChangedListener(
+ DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
+ mContext.getMainExecutor(),
this);
- if (ConfigParser.ENABLE_DEVICE_CONFIG) {
- DeviceConfig.addOnPropertiesChangedListener(
- DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- mContext.getMainExecutor(),
- this);
- }
}
- private void updateChange() {
- final String overrideServiceName = getTextClassifierSettings(
- mContext).getTextClassifierServiceName();
+ @Override
+ public void onPropertiesChanged(DeviceConfig.Properties properties) {
+ final String overrideServiceName = mSettings.getTextClassifierServicePackageOverride();
+
if (TextUtils.equals(overrideServiceName, mServicePackageName)) {
return;
}
mServicePackageName = overrideServiceName;
- unbindServiceIfNeeded();
- }
-
- @Override
- public void onChange(boolean selfChange, Uri uri) {
- super.onChange(selfChange, uri);
- invalidateSettings();
- updateChange();
- }
-
- @Override
- public void onPropertiesChanged(DeviceConfig.Properties properties) {
- invalidateSettings();
- updateChange();
+ unbindServiceIfNecessary();
}
}
}
diff --git a/services/core/java/com/android/server/timedetector/SimpleTimeDetectorStrategy.java b/services/core/java/com/android/server/timedetector/SimpleTimeDetectorStrategy.java
deleted file mode 100644
index 4e8ba078a73c..000000000000
--- a/services/core/java/com/android/server/timedetector/SimpleTimeDetectorStrategy.java
+++ /dev/null
@@ -1,305 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.timedetector;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.app.AlarmManager;
-import android.app.timedetector.ManualTimeSuggestion;
-import android.app.timedetector.PhoneTimeSuggestion;
-import android.content.Intent;
-import android.util.LocalLog;
-import android.util.Slog;
-import android.util.TimestampedValue;
-
-import com.android.internal.annotations.GuardedBy;
-import com.android.internal.telephony.TelephonyIntents;
-import com.android.internal.util.IndentingPrintWriter;
-
-import java.io.PrintWriter;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-
-/**
- * An implementation of TimeDetectorStrategy that passes only NITZ suggestions to
- * {@link AlarmManager}.
- *
- * <p>Most public methods are marked synchronized to ensure thread safety around internal state.
- */
-public final class SimpleTimeDetectorStrategy implements TimeDetectorStrategy {
-
- private static final boolean DBG = false;
- private static final String LOG_TAG = "SimpleTimeDetectorStrategy";
-
- @IntDef({ ORIGIN_PHONE, ORIGIN_MANUAL })
- @Retention(RetentionPolicy.SOURCE)
- public @interface Origin {}
-
- /** Used when a time value originated from a telephony signal. */
- @Origin
- private static final int ORIGIN_PHONE = 1;
-
- /** Used when a time value originated from a user / manual settings. */
- @Origin
- private static final int ORIGIN_MANUAL = 2;
-
- /**
- * CLOCK_PARANOIA: The maximum difference allowed between the expected system clock time and the
- * actual system clock time before a warning is logged. Used to help identify situations where
- * there is something other than this class setting the system clock automatically.
- */
- private static final long SYSTEM_CLOCK_PARANOIA_THRESHOLD_MILLIS = 2 * 1000;
-
- // A log for changes made to the system clock and why.
- @NonNull
- private final LocalLog mTimeChangesLog = new LocalLog(30, false /* useLocalTimestamps */);
-
- // @NonNull after initialize()
- private Callback mCallback;
-
- // Last phone suggestion.
- @Nullable private PhoneTimeSuggestion mLastPhoneSuggestion;
-
- // Information about the last time signal received: Used when toggling auto-time.
- @Nullable private TimestampedValue<Long> mLastAutoSystemClockTime;
- private boolean mLastAutoSystemClockTimeSendNetworkBroadcast;
-
- // System clock state.
- @Nullable private TimestampedValue<Long> mLastAutoSystemClockTimeSet;
-
- @Override
- public void initialize(@NonNull Callback callback) {
- mCallback = callback;
- }
-
- @Override
- public synchronized void suggestPhoneTime(@NonNull PhoneTimeSuggestion timeSuggestion) {
- // NITZ logic
-
- // Empty suggestions are just ignored as we don't currently keep track of suggestion origin.
- if (timeSuggestion.getUtcTime() == null) {
- return;
- }
-
- boolean timeSuggestionIsValid =
- validateNewPhoneSuggestion(timeSuggestion, mLastPhoneSuggestion);
- if (!timeSuggestionIsValid) {
- return;
- }
- // Always store the last NITZ value received, regardless of whether we go on to use it to
- // update the system clock. This is so that we can validate future phone suggestions.
- mLastPhoneSuggestion = timeSuggestion;
-
- // System clock update logic.
- final TimestampedValue<Long> newUtcTime = timeSuggestion.getUtcTime();
- setSystemClockIfRequired(ORIGIN_PHONE, newUtcTime, timeSuggestion);
- }
-
- @Override
- public synchronized void suggestManualTime(ManualTimeSuggestion timeSuggestion) {
- final TimestampedValue<Long> newUtcTime = timeSuggestion.getUtcTime();
- setSystemClockIfRequired(ORIGIN_MANUAL, newUtcTime, timeSuggestion);
- }
-
- private static boolean validateNewPhoneSuggestion(@NonNull PhoneTimeSuggestion newSuggestion,
- @Nullable PhoneTimeSuggestion lastSuggestion) {
-
- if (lastSuggestion != null) {
- long referenceTimeDifference = TimestampedValue.referenceTimeDifference(
- newSuggestion.getUtcTime(), lastSuggestion.getUtcTime());
- if (referenceTimeDifference < 0 || referenceTimeDifference > Integer.MAX_VALUE) {
- // Out of order or bogus.
- Slog.w(LOG_TAG, "Bad NITZ signal received."
- + " referenceTimeDifference=" + referenceTimeDifference
- + " lastSuggestion=" + lastSuggestion
- + " newSuggestion=" + newSuggestion);
- return false;
- }
- }
- return true;
- }
-
- @GuardedBy("this")
- private void setSystemClockIfRequired(
- @Origin int origin, TimestampedValue<Long> time, Object cause) {
- // Historically, Android has sent a TelephonyIntents.ACTION_NETWORK_SET_TIME broadcast only
- // when setting the time using NITZ.
- boolean sendNetworkBroadcast = origin == ORIGIN_PHONE;
-
- boolean isOriginAutomatic = isOriginAutomatic(origin);
- if (isOriginAutomatic) {
- // Store the last auto time candidate we've seen in all cases so we can set the system
- // clock when/if time detection is off but later enabled.
- mLastAutoSystemClockTime = time;
- mLastAutoSystemClockTimeSendNetworkBroadcast = sendNetworkBroadcast;
-
- if (!mCallback.isAutoTimeDetectionEnabled()) {
- if (DBG) {
- Slog.d(LOG_TAG, "Auto time detection is not enabled."
- + " origin=" + origin
- + ", time=" + time
- + ", cause=" + cause);
- }
- return;
- }
- } else {
- if (mCallback.isAutoTimeDetectionEnabled()) {
- if (DBG) {
- Slog.d(LOG_TAG, "Auto time detection is enabled."
- + " origin=" + origin
- + ", time=" + time
- + ", cause=" + cause);
- }
- return;
- }
- }
-
- mCallback.acquireWakeLock();
- try {
- long elapsedRealtimeMillis = mCallback.elapsedRealtimeMillis();
- long actualTimeMillis = mCallback.systemClockMillis();
-
- if (isOriginAutomatic) {
- // CLOCK_PARANOIA : Check to see if this class owns the clock or if something else
- // may be setting the clock.
- if (mLastAutoSystemClockTimeSet != null) {
- long expectedTimeMillis = TimeDetectorStrategy.getTimeAt(
- mLastAutoSystemClockTimeSet, elapsedRealtimeMillis);
- long absSystemClockDifference = Math.abs(expectedTimeMillis - actualTimeMillis);
- if (absSystemClockDifference > SYSTEM_CLOCK_PARANOIA_THRESHOLD_MILLIS) {
- Slog.w(LOG_TAG,
- "System clock has not tracked elapsed real time clock. A clock may"
- + " be inaccurate or something unexpectedly set the system"
- + " clock."
- + " elapsedRealtimeMillis=" + elapsedRealtimeMillis
- + " expectedTimeMillis=" + expectedTimeMillis
- + " actualTimeMillis=" + actualTimeMillis);
- }
- }
- }
-
- adjustAndSetDeviceSystemClock(
- time, sendNetworkBroadcast, elapsedRealtimeMillis, actualTimeMillis, cause);
- } finally {
- mCallback.releaseWakeLock();
- }
- }
-
- private static boolean isOriginAutomatic(@Origin int origin) {
- return origin == ORIGIN_PHONE;
- }
-
- @Override
- public synchronized void handleAutoTimeDetectionChanged() {
- // If automatic time detection is enabled we update the system clock instantly if we can.
- // Conversely, if automatic time detection is disabled we leave the clock as it is.
- boolean enabled = mCallback.isAutoTimeDetectionEnabled();
- if (enabled) {
- if (mLastAutoSystemClockTime != null) {
- // Only send the network broadcast if the last candidate would have caused one.
- final boolean sendNetworkBroadcast = mLastAutoSystemClockTimeSendNetworkBroadcast;
-
- mCallback.acquireWakeLock();
- try {
- long elapsedRealtimeMillis = mCallback.elapsedRealtimeMillis();
- long actualTimeMillis = mCallback.systemClockMillis();
-
- final String reason = "Automatic time detection enabled.";
- adjustAndSetDeviceSystemClock(mLastAutoSystemClockTime, sendNetworkBroadcast,
- elapsedRealtimeMillis, actualTimeMillis, reason);
- } finally {
- mCallback.releaseWakeLock();
- }
- }
- } else {
- // CLOCK_PARANOIA: We are losing "control" of the system clock so we cannot predict what
- // it should be in future.
- mLastAutoSystemClockTimeSet = null;
- }
- }
-
- @Override
- public synchronized void dump(@NonNull PrintWriter pw, @Nullable String[] args) {
- IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ");
- ipw.println("TimeDetectorStrategy:");
- ipw.increaseIndent(); // level 1
-
- ipw.println("mLastPhoneSuggestion=" + mLastPhoneSuggestion);
- ipw.println("mLastAutoSystemClockTimeSet=" + mLastAutoSystemClockTimeSet);
- ipw.println("mLastAutoSystemClockTime=" + mLastAutoSystemClockTime);
- ipw.println("mLastAutoSystemClockTimeSendNetworkBroadcast="
- + mLastAutoSystemClockTimeSendNetworkBroadcast);
-
-
- ipw.println("Time change log:");
- ipw.increaseIndent(); // level 2
- mTimeChangesLog.dump(ipw);
- ipw.decreaseIndent(); // level 2
-
- ipw.decreaseIndent(); // level 1
- ipw.flush();
- }
-
- @GuardedBy("this")
- private void adjustAndSetDeviceSystemClock(
- TimestampedValue<Long> newTime, boolean sendNetworkBroadcast,
- long elapsedRealtimeMillis, long actualSystemClockMillis, Object cause) {
-
- // Adjust for the time that has elapsed since the signal was received.
- long newSystemClockMillis = TimeDetectorStrategy.getTimeAt(newTime, elapsedRealtimeMillis);
-
- // Check if the new signal would make sufficient difference to the system clock. If it's
- // below the threshold then ignore it.
- long absTimeDifference = Math.abs(newSystemClockMillis - actualSystemClockMillis);
- long systemClockUpdateThreshold = mCallback.systemClockUpdateThresholdMillis();
- if (absTimeDifference < systemClockUpdateThreshold) {
- if (DBG) {
- Slog.d(LOG_TAG, "Not setting system clock. New time and"
- + " system clock are close enough."
- + " elapsedRealtimeMillis=" + elapsedRealtimeMillis
- + " newTime=" + newTime
- + " cause=" + cause
- + " systemClockUpdateThreshold=" + systemClockUpdateThreshold
- + " absTimeDifference=" + absTimeDifference);
- }
- return;
- }
-
- mCallback.setSystemClock(newSystemClockMillis);
- String logMsg = "Set system clock using time=" + newTime
- + " cause=" + cause
- + " elapsedRealtimeMillis=" + elapsedRealtimeMillis
- + " newSystemClockMillis=" + newSystemClockMillis;
- if (DBG) {
- Slog.d(LOG_TAG, logMsg);
- }
- mTimeChangesLog.log(logMsg);
-
- // CLOCK_PARANOIA : Record the last time this class set the system clock.
- mLastAutoSystemClockTimeSet = newTime;
-
- if (sendNetworkBroadcast) {
- // Send a broadcast that telephony code used to send after setting the clock.
- // TODO Remove this broadcast as soon as there are no remaining listeners.
- Intent intent = new Intent(TelephonyIntents.ACTION_NETWORK_SET_TIME);
- intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
- intent.putExtra("time", newSystemClockMillis);
- mCallback.sendStickyBroadcast(intent);
- }
- }
-}
diff --git a/services/core/java/com/android/server/timedetector/TimeDetectorService.java b/services/core/java/com/android/server/timedetector/TimeDetectorService.java
index 34400ff6b484..172367a128cc 100644
--- a/services/core/java/com/android/server/timedetector/TimeDetectorService.java
+++ b/services/core/java/com/android/server/timedetector/TimeDetectorService.java
@@ -31,7 +31,6 @@ import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.DumpUtils;
import com.android.server.FgThread;
import com.android.server.SystemService;
-import com.android.server.timedetector.TimeDetectorStrategy.Callback;
import java.io.FileDescriptor;
import java.io.PrintWriter;
@@ -58,17 +57,16 @@ public final class TimeDetectorService extends ITimeDetectorService.Stub {
@NonNull private final Handler mHandler;
@NonNull private final Context mContext;
- @NonNull private final Callback mCallback;
@NonNull private final TimeDetectorStrategy mTimeDetectorStrategy;
private static TimeDetectorService create(@NonNull Context context) {
- TimeDetectorStrategy timeDetector = new SimpleTimeDetectorStrategy();
+ TimeDetectorStrategy timeDetectorStrategy = new TimeDetectorStrategyImpl();
TimeDetectorStrategyCallbackImpl callback = new TimeDetectorStrategyCallbackImpl(context);
- timeDetector.initialize(callback);
+ timeDetectorStrategy.initialize(callback);
Handler handler = FgThread.getHandler();
TimeDetectorService timeDetectorService =
- new TimeDetectorService(context, handler, callback, timeDetector);
+ new TimeDetectorService(context, handler, timeDetectorStrategy);
// Wire up event listening.
ContentResolver contentResolver = context.getContentResolver();
@@ -85,10 +83,9 @@ public final class TimeDetectorService extends ITimeDetectorService.Stub {
@VisibleForTesting
public TimeDetectorService(@NonNull Context context, @NonNull Handler handler,
- @NonNull Callback callback, @NonNull TimeDetectorStrategy timeDetectorStrategy) {
+ @NonNull TimeDetectorStrategy timeDetectorStrategy) {
mContext = Objects.requireNonNull(context);
mHandler = Objects.requireNonNull(handler);
- mCallback = Objects.requireNonNull(callback);
mTimeDetectorStrategy = Objects.requireNonNull(timeDetectorStrategy);
}
diff --git a/services/core/java/com/android/server/timedetector/TimeDetectorStrategyImpl.java b/services/core/java/com/android/server/timedetector/TimeDetectorStrategyImpl.java
new file mode 100644
index 000000000000..d99e03b091a3
--- /dev/null
+++ b/services/core/java/com/android/server/timedetector/TimeDetectorStrategyImpl.java
@@ -0,0 +1,549 @@
+/*
+ * Copyright (C) 2018 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 com.android.server.timedetector;
+
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.app.AlarmManager;
+import android.app.timedetector.ManualTimeSuggestion;
+import android.app.timedetector.PhoneTimeSuggestion;
+import android.content.Intent;
+import android.telephony.TelephonyManager;
+import android.util.ArrayMap;
+import android.util.LocalLog;
+import android.util.Slog;
+import android.util.TimestampedValue;
+
+import com.android.internal.annotations.GuardedBy;
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.util.IndentingPrintWriter;
+
+import java.io.PrintWriter;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.util.LinkedList;
+import java.util.Map;
+
+/**
+ * An implementation of TimeDetectorStrategy that passes phone and manual suggestions to
+ * {@link AlarmManager}. When there are multiple phone sources, the one with the lowest ID is used
+ * unless the data becomes too stale.
+ *
+ * <p>Most public methods are marked synchronized to ensure thread safety around internal state.
+ */
+public final class TimeDetectorStrategyImpl implements TimeDetectorStrategy {
+
+ private static final boolean DBG = false;
+ private static final String LOG_TAG = "SimpleTimeDetectorStrategy";
+
+ /** A score value used to indicate "no score", either due to validation failure or age. */
+ private static final int PHONE_INVALID_SCORE = -1;
+ /** The number of buckets phone suggestions can be put in by age. */
+ private static final int PHONE_BUCKET_COUNT = 24;
+ /** Each bucket is this size. All buckets are equally sized. */
+ @VisibleForTesting
+ static final int PHONE_BUCKET_SIZE_MILLIS = 60 * 60 * 1000;
+ /** Phone suggestions older than this value are considered too old. */
+ @VisibleForTesting
+ static final long PHONE_MAX_AGE_MILLIS = PHONE_BUCKET_COUNT * PHONE_BUCKET_SIZE_MILLIS;
+
+ @IntDef({ ORIGIN_PHONE, ORIGIN_MANUAL })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface Origin {}
+
+ /** Used when a time value originated from a telephony signal. */
+ @Origin
+ private static final int ORIGIN_PHONE = 1;
+
+ /** Used when a time value originated from a user / manual settings. */
+ @Origin
+ private static final int ORIGIN_MANUAL = 2;
+
+ /**
+ * CLOCK_PARANOIA: The maximum difference allowed between the expected system clock time and the
+ * actual system clock time before a warning is logged. Used to help identify situations where
+ * there is something other than this class setting the system clock.
+ */
+ private static final long SYSTEM_CLOCK_PARANOIA_THRESHOLD_MILLIS = 2 * 1000;
+
+ /** The number of previous phone suggestions to keep for each ID (for use during debugging). */
+ private static final int KEEP_SUGGESTION_HISTORY_SIZE = 30;
+
+ // A log for changes made to the system clock and why.
+ @NonNull
+ private final LocalLog mTimeChangesLog = new LocalLog(30, false /* useLocalTimestamps */);
+
+ // @NonNull after initialize()
+ private Callback mCallback;
+
+ // Used to store the last time the system clock state was set automatically. It is used to
+ // detect (and log) issues with the realtime clock or whether the clock is being set without
+ // going through this strategy code.
+ @GuardedBy("this")
+ @Nullable
+ private TimestampedValue<Long> mLastAutoSystemClockTimeSet;
+
+ /**
+ * A mapping from phoneId to a linked list of time suggestions (the "first" being the latest).
+ * We typically expect one or two entries in this Map: devices will have a small number
+ * of telephony devices and phoneIds are assumed to be stable. The LinkedList associated with
+ * the ID will not exceed {@link #KEEP_SUGGESTION_HISTORY_SIZE} in size.
+ */
+ @GuardedBy("this")
+ private ArrayMap<Integer, LinkedList<PhoneTimeSuggestion>> mSuggestionByPhoneId =
+ new ArrayMap<>();
+
+ @Override
+ public void initialize(@NonNull Callback callback) {
+ mCallback = callback;
+ }
+
+ @Override
+ public synchronized void suggestManualTime(@NonNull ManualTimeSuggestion suggestion) {
+ final TimestampedValue<Long> newUtcTime = suggestion.getUtcTime();
+
+ if (!validateSuggestionTime(newUtcTime, suggestion)) {
+ return;
+ }
+
+ String cause = "Manual time suggestion received: suggestion=" + suggestion;
+ setSystemClockIfRequired(ORIGIN_MANUAL, newUtcTime, cause);
+ }
+
+ @Override
+ public synchronized void suggestPhoneTime(@NonNull PhoneTimeSuggestion timeSuggestion) {
+ // Empty time suggestion means that telephony network connectivity has been lost.
+ // The passage of time is relentless, and we don't expect our users to use a time machine,
+ // so we can continue relying on previous suggestions when we lose connectivity. This is
+ // unlike time zone, where a user may lose connectivity when boarding a flight and where we
+ // do want to "forget" old signals. Suggestions that are too old are discarded later in the
+ // detection algorithm.
+ if (timeSuggestion.getUtcTime() == null) {
+ return;
+ }
+
+ // Perform validation / input filtering and record the validated suggestion against the
+ // phoneId.
+ if (!validateAndStorePhoneSuggestion(timeSuggestion)) {
+ return;
+ }
+
+ // Now perform auto time detection. The new suggestion may be used to modify the system
+ // clock.
+ String reason = "New phone time suggested. timeSuggestion=" + timeSuggestion;
+ doAutoTimeDetection(reason);
+ }
+
+ @Override
+ public synchronized void handleAutoTimeDetectionChanged() {
+ boolean enabled = mCallback.isAutoTimeDetectionEnabled();
+ // When automatic time detection is enabled we update the system clock instantly if we can.
+ // Conversely, when automatic time detection is disabled we leave the clock as it is.
+ if (enabled) {
+ String reason = "Auto time zone detection setting enabled.";
+ doAutoTimeDetection(reason);
+ } else {
+ // CLOCK_PARANOIA: We are losing "control" of the system clock so we cannot predict what
+ // it should be in future.
+ mLastAutoSystemClockTimeSet = null;
+ }
+ }
+
+ @Override
+ public synchronized void dump(@NonNull PrintWriter pw, @Nullable String[] args) {
+ IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ");
+ ipw.println("TimeDetectorStrategy:");
+ ipw.increaseIndent(); // level 1
+
+ ipw.println("mLastAutoSystemClockTimeSet=" + mLastAutoSystemClockTimeSet);
+
+ ipw.println("Time change log:");
+ ipw.increaseIndent(); // level 2
+ mTimeChangesLog.dump(ipw);
+ ipw.decreaseIndent(); // level 2
+
+ ipw.println("Phone suggestion history:");
+ ipw.increaseIndent(); // level 2
+ for (Map.Entry<Integer, LinkedList<PhoneTimeSuggestion>> entry
+ : mSuggestionByPhoneId.entrySet()) {
+ ipw.println("Phone " + entry.getKey());
+
+ ipw.increaseIndent(); // level 3
+ for (PhoneTimeSuggestion suggestion : entry.getValue()) {
+ ipw.println(suggestion);
+ }
+ ipw.decreaseIndent(); // level 3
+ }
+ ipw.decreaseIndent(); // level 2
+
+ ipw.decreaseIndent(); // level 1
+ ipw.flush();
+ }
+
+ @GuardedBy("this")
+ private boolean validateAndStorePhoneSuggestion(@NonNull PhoneTimeSuggestion suggestion) {
+ TimestampedValue<Long> newUtcTime = suggestion.getUtcTime();
+ if (!validateSuggestionTime(newUtcTime, suggestion)) {
+ // There's probably nothing useful we can do: elsewhere we assume that reference
+ // times are in the past so just stop here.
+ return false;
+ }
+
+ int phoneId = suggestion.getPhoneId();
+ LinkedList<PhoneTimeSuggestion> phoneSuggestions = mSuggestionByPhoneId.get(phoneId);
+ if (phoneSuggestions == null) {
+ // The first time we've seen this phoneId.
+ phoneSuggestions = new LinkedList<>();
+ mSuggestionByPhoneId.put(phoneId, phoneSuggestions);
+ } else if (phoneSuggestions.isEmpty()) {
+ Slog.w(LOG_TAG, "Suggestions unexpectedly empty when adding suggestion=" + suggestion);
+ }
+
+ if (!phoneSuggestions.isEmpty()) {
+ // We can log / discard suggestions with obvious issues with the reference time clock.
+ PhoneTimeSuggestion previousSuggestion = phoneSuggestions.getFirst();
+ if (previousSuggestion == null
+ || previousSuggestion.getUtcTime() == null
+ || previousSuggestion.getUtcTime().getValue() == null) {
+ // This should be impossible given we only store validated suggestions.
+ Slog.w(LOG_TAG, "Previous suggestion is null or has a null time."
+ + " previousSuggestion=" + previousSuggestion
+ + ", suggestion=" + suggestion);
+ return false;
+ }
+
+ long referenceTimeDifference = TimestampedValue.referenceTimeDifference(
+ newUtcTime, previousSuggestion.getUtcTime());
+ if (referenceTimeDifference < 0) {
+ // The reference time is before the previously received suggestion. Ignore it.
+ Slog.w(LOG_TAG, "Out of order phone suggestion received."
+ + " referenceTimeDifference=" + referenceTimeDifference
+ + " previousSuggestion=" + previousSuggestion
+ + " suggestion=" + suggestion);
+ return false;
+ }
+ }
+
+ // Store the latest suggestion.
+ phoneSuggestions.addFirst(suggestion);
+ if (phoneSuggestions.size() > KEEP_SUGGESTION_HISTORY_SIZE) {
+ phoneSuggestions.removeLast();
+ }
+ return true;
+ }
+
+ private boolean validateSuggestionTime(
+ @NonNull TimestampedValue<Long> newUtcTime, @NonNull Object suggestion) {
+ if (newUtcTime.getValue() == null) {
+ Slog.w(LOG_TAG, "Suggested time value is null. suggestion=" + suggestion);
+ return false;
+ }
+
+ // We can validate the suggestion against the reference time clock.
+ long elapsedRealtimeMillis = mCallback.elapsedRealtimeMillis();
+ if (elapsedRealtimeMillis < newUtcTime.getReferenceTimeMillis()) {
+ // elapsedRealtime clock went backwards?
+ Slog.w(LOG_TAG, "New reference time is in the future? Ignoring."
+ + " elapsedRealtimeMillis=" + elapsedRealtimeMillis
+ + ", suggestion=" + suggestion);
+ return false;
+ }
+ return true;
+ }
+
+ @GuardedBy("this")
+ private void doAutoTimeDetection(@NonNull String detectionReason) {
+ if (!mCallback.isAutoTimeDetectionEnabled()) {
+ // Avoid doing unnecessary work with this (race-prone) check.
+ return;
+ }
+
+ PhoneTimeSuggestion bestPhoneSuggestion = findBestPhoneSuggestion();
+
+ // Work out what to do with the best suggestion.
+ if (bestPhoneSuggestion == null) {
+ // There is no good phone suggestion.
+ if (DBG) {
+ Slog.d(LOG_TAG, "Could not determine time: No best phone suggestion."
+ + " detectionReason=" + detectionReason);
+ }
+ return;
+ }
+
+ final TimestampedValue<Long> newUtcTime = bestPhoneSuggestion.getUtcTime();
+ String cause = "Found good suggestion."
+ + ", bestPhoneSuggestion=" + bestPhoneSuggestion
+ + ", detectionReason=" + detectionReason;
+ setSystemClockIfRequired(ORIGIN_PHONE, newUtcTime, cause);
+ }
+
+ @GuardedBy("this")
+ @Nullable
+ private PhoneTimeSuggestion findBestPhoneSuggestion() {
+ long elapsedRealtimeMillis = mCallback.elapsedRealtimeMillis();
+
+ // Phone time suggestions are assumed to be derived from NITZ or NITZ-like signals. These
+ // have a number of limitations:
+ // 1) No guarantee of accuracy ("accuracy of the time information is in the order of
+ // minutes") [1]
+ // 2) No guarantee of regular signals ("dependent on the handset crossing radio network
+ // boundaries") [1]
+ //
+ // [1] https://en.wikipedia.org/wiki/NITZ
+ //
+ // Generally, when there are suggestions from multiple phoneIds they should usually
+ // approximately agree. In cases where signals *are* inaccurate we don't want to vacillate
+ // between signals from two phoneIds. However, it is known for NITZ signals to be incorrect
+ // occasionally, which means we also don't want to stick forever with one phoneId. Without
+ // cross-referencing across sources (e.g. the current device time, NTP), or doing some kind
+ // of statistical analysis of consistency within and across phoneIds, we can't know which
+ // suggestions are more correct.
+ //
+ // For simplicity, we try to value recency, then consistency of phoneId.
+ //
+ // The heuristic works as follows:
+ // Recency: The most recent suggestion from each phone is scored. The score is based on a
+ // discrete age bucket, i.e. so signals received around the same time will be in the same
+ // bucket, thus applying a loose reference time ordering. The suggestion with the highest
+ // score is used.
+ // Consistency: If there a multiple suggestions with the same score, the suggestion with the
+ // lowest phoneId is always taken.
+ //
+ // In the trivial case with a single ID this will just mean that the latest received
+ // suggestion is used.
+
+ PhoneTimeSuggestion bestSuggestion = null;
+ int bestScore = PHONE_INVALID_SCORE;
+ for (int i = 0; i < mSuggestionByPhoneId.size(); i++) {
+ Integer phoneId = mSuggestionByPhoneId.keyAt(i);
+ LinkedList<PhoneTimeSuggestion> phoneSuggestions = mSuggestionByPhoneId.valueAt(i);
+ if (phoneSuggestions == null) {
+ // Unexpected - map is missing a value.
+ Slog.w(LOG_TAG, "Suggestions unexpectedly missing for phoneId."
+ + " phoneId=" + phoneId);
+ continue;
+ }
+
+ PhoneTimeSuggestion candidateSuggestion = phoneSuggestions.getFirst();
+ if (candidateSuggestion == null) {
+ // Unexpected - null suggestions should never be stored.
+ Slog.w(LOG_TAG, "Latest suggestion unexpectedly null for phoneId."
+ + " phoneId=" + phoneId);
+ continue;
+ } else if (candidateSuggestion.getUtcTime() == null) {
+ // Unexpected - we do not store empty suggestions.
+ Slog.w(LOG_TAG, "Latest suggestion unexpectedly empty. "
+ + " candidateSuggestion=" + candidateSuggestion);
+ continue;
+ }
+
+ int candidateScore = scorePhoneSuggestion(elapsedRealtimeMillis, candidateSuggestion);
+ if (candidateScore == PHONE_INVALID_SCORE) {
+ // Expected: This means the suggestion is obviously invalid or just too old.
+ continue;
+ }
+
+ // Higher scores are better.
+ if (bestSuggestion == null || bestScore < candidateScore) {
+ bestSuggestion = candidateSuggestion;
+ bestScore = candidateScore;
+ } else if (bestScore == candidateScore) {
+ // Tie! Use the suggestion with the lowest phoneId.
+ int candidatePhoneId = candidateSuggestion.getPhoneId();
+ int bestPhoneId = bestSuggestion.getPhoneId();
+ if (candidatePhoneId < bestPhoneId) {
+ bestSuggestion = candidateSuggestion;
+ }
+ }
+ }
+ return bestSuggestion;
+ }
+
+ private static int scorePhoneSuggestion(
+ long elapsedRealtimeMillis, @NonNull PhoneTimeSuggestion timeSuggestion) {
+ // The score is based on the age since receipt. Suggestions are bucketed so two
+ // suggestions in the same bucket from different phoneIds are scored the same.
+ TimestampedValue<Long> utcTime = timeSuggestion.getUtcTime();
+ long referenceTimeMillis = utcTime.getReferenceTimeMillis();
+ if (referenceTimeMillis > elapsedRealtimeMillis) {
+ // Future times are ignored. They imply the reference time was wrong, or the elapsed
+ // realtime clock has gone backwards, neither of which are supportable situations.
+ Slog.w(LOG_TAG, "Existing suggestion found to be in the future. "
+ + " elapsedRealtimeMillis=" + elapsedRealtimeMillis
+ + ", timeSuggestion=" + timeSuggestion);
+ return PHONE_INVALID_SCORE;
+ }
+
+ long ageMillis = elapsedRealtimeMillis - referenceTimeMillis;
+
+ // Any suggestion > MAX_AGE_MILLIS is treated as too old. Although time is relentless and
+ // predictable, the accuracy of the reference time clock may be poor over long periods which
+ // would lead to errors creeping in. Also, in edge cases where a bad suggestion has been
+ // made and never replaced, it could also mean that the time detection code remains
+ // opinionated using a bad invalid suggestion. This caps that edge case at MAX_AGE_MILLIS.
+ if (ageMillis > PHONE_MAX_AGE_MILLIS) {
+ return PHONE_INVALID_SCORE;
+ }
+
+ // Turn the age into a discrete value: 0 <= bucketIndex < MAX_AGE_HOURS.
+ int bucketIndex = (int) (ageMillis / PHONE_BUCKET_SIZE_MILLIS);
+
+ // We want the lowest bucket index to have the highest score. 0 > score >= BUCKET_COUNT.
+ return PHONE_BUCKET_COUNT - bucketIndex;
+ }
+
+ @GuardedBy("this")
+ private void setSystemClockIfRequired(
+ @Origin int origin, @NonNull TimestampedValue<Long> time, @NonNull String cause) {
+
+ boolean isOriginAutomatic = isOriginAutomatic(origin);
+ if (isOriginAutomatic) {
+ if (!mCallback.isAutoTimeDetectionEnabled()) {
+ if (DBG) {
+ Slog.d(LOG_TAG, "Auto time detection is not enabled."
+ + " origin=" + origin
+ + ", time=" + time
+ + ", cause=" + cause);
+ }
+ return;
+ }
+ } else {
+ if (mCallback.isAutoTimeDetectionEnabled()) {
+ if (DBG) {
+ Slog.d(LOG_TAG, "Auto time detection is enabled."
+ + " origin=" + origin
+ + ", time=" + time
+ + ", cause=" + cause);
+ }
+ return;
+ }
+ }
+
+ mCallback.acquireWakeLock();
+ try {
+ setSystemClockUnderWakeLock(origin, time, cause);
+ } finally {
+ mCallback.releaseWakeLock();
+ }
+ }
+
+ private static boolean isOriginAutomatic(@Origin int origin) {
+ return origin == ORIGIN_PHONE;
+ }
+
+ @GuardedBy("this")
+ private void setSystemClockUnderWakeLock(
+ int origin, @NonNull TimestampedValue<Long> newTime, @NonNull Object cause) {
+
+ long elapsedRealtimeMillis = mCallback.elapsedRealtimeMillis();
+ boolean isOriginAutomatic = isOriginAutomatic(origin);
+ long actualSystemClockMillis = mCallback.systemClockMillis();
+ if (isOriginAutomatic) {
+ // CLOCK_PARANOIA : Check to see if this class owns the clock or if something else
+ // may be setting the clock.
+ if (mLastAutoSystemClockTimeSet != null) {
+ long expectedTimeMillis = TimeDetectorStrategy.getTimeAt(
+ mLastAutoSystemClockTimeSet, elapsedRealtimeMillis);
+ long absSystemClockDifference =
+ Math.abs(expectedTimeMillis - actualSystemClockMillis);
+ if (absSystemClockDifference > SYSTEM_CLOCK_PARANOIA_THRESHOLD_MILLIS) {
+ Slog.w(LOG_TAG,
+ "System clock has not tracked elapsed real time clock. A clock may"
+ + " be inaccurate or something unexpectedly set the system"
+ + " clock."
+ + " elapsedRealtimeMillis=" + elapsedRealtimeMillis
+ + " expectedTimeMillis=" + expectedTimeMillis
+ + " actualTimeMillis=" + actualSystemClockMillis
+ + " cause=" + cause);
+ }
+ }
+ }
+
+ // Adjust for the time that has elapsed since the signal was received.
+ long newSystemClockMillis = TimeDetectorStrategy.getTimeAt(newTime, elapsedRealtimeMillis);
+
+ // Check if the new signal would make sufficient difference to the system clock. If it's
+ // below the threshold then ignore it.
+ long absTimeDifference = Math.abs(newSystemClockMillis - actualSystemClockMillis);
+ long systemClockUpdateThreshold = mCallback.systemClockUpdateThresholdMillis();
+ if (absTimeDifference < systemClockUpdateThreshold) {
+ if (DBG) {
+ Slog.d(LOG_TAG, "Not setting system clock. New time and"
+ + " system clock are close enough."
+ + " elapsedRealtimeMillis=" + elapsedRealtimeMillis
+ + " newTime=" + newTime
+ + " cause=" + cause
+ + " systemClockUpdateThreshold=" + systemClockUpdateThreshold
+ + " absTimeDifference=" + absTimeDifference);
+ }
+ return;
+ }
+
+ mCallback.setSystemClock(newSystemClockMillis);
+ String logMsg = "Set system clock using time=" + newTime
+ + " cause=" + cause
+ + " elapsedRealtimeMillis=" + elapsedRealtimeMillis
+ + " newSystemClockMillis=" + newSystemClockMillis;
+ if (DBG) {
+ Slog.d(LOG_TAG, logMsg);
+ }
+ mTimeChangesLog.log(logMsg);
+
+ // CLOCK_PARANOIA : Record the last time this class set the system clock due to an auto-time
+ // signal, or clear the record it is being done manually.
+ if (isOriginAutomatic(origin)) {
+ mLastAutoSystemClockTimeSet = newTime;
+ } else {
+ mLastAutoSystemClockTimeSet = null;
+ }
+
+ // Historically, Android has sent a TelephonyManager.ACTION_NETWORK_SET_TIME broadcast only
+ // when setting the time using NITZ.
+ if (origin == ORIGIN_PHONE) {
+ // Send a broadcast that telephony code used to send after setting the clock.
+ // TODO Remove this broadcast as soon as there are no remaining listeners.
+ Intent intent = new Intent(TelephonyManager.ACTION_NETWORK_SET_TIME);
+ intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
+ intent.putExtra("time", newSystemClockMillis);
+ mCallback.sendStickyBroadcast(intent);
+ }
+ }
+
+ /**
+ * Returns the current best phone suggestion. Not intended for general use: it is used during
+ * tests to check strategy behavior.
+ */
+ @VisibleForTesting
+ @Nullable
+ public synchronized PhoneTimeSuggestion findBestPhoneSuggestionForTests() {
+ return findBestPhoneSuggestion();
+ }
+
+ /**
+ * A method used to inspect state during tests. Not intended for general use.
+ */
+ @VisibleForTesting
+ @Nullable
+ public synchronized PhoneTimeSuggestion getLatestPhoneSuggestion(int phoneId) {
+ LinkedList<PhoneTimeSuggestion> suggestions = mSuggestionByPhoneId.get(phoneId);
+ if (suggestions == null) {
+ return null;
+ }
+ return suggestions.getFirst();
+ }
+}
diff --git a/services/core/java/com/android/server/timezonedetector/TimeZoneDetectorCallbackImpl.java b/services/core/java/com/android/server/timezonedetector/TimeZoneDetectorCallbackImpl.java
index e034ad437555..adf6d7e51f4f 100644
--- a/services/core/java/com/android/server/timezonedetector/TimeZoneDetectorCallbackImpl.java
+++ b/services/core/java/com/android/server/timezonedetector/TimeZoneDetectorCallbackImpl.java
@@ -20,13 +20,9 @@ import android.annotation.Nullable;
import android.app.AlarmManager;
import android.content.ContentResolver;
import android.content.Context;
-import android.content.Intent;
import android.os.SystemProperties;
-import android.os.UserHandle;
import android.provider.Settings;
-import com.android.internal.telephony.TelephonyIntents;
-
/**
* The real implementation of {@link TimeZoneDetectorStrategy.Callback}.
*/
@@ -66,16 +62,8 @@ public final class TimeZoneDetectorCallbackImpl implements TimeZoneDetectorStrat
}
@Override
- public void setDeviceTimeZone(String zoneId, boolean sendNetworkBroadcast) {
+ public void setDeviceTimeZone(String zoneId) {
AlarmManager alarmManager = mContext.getSystemService(AlarmManager.class);
alarmManager.setTimeZone(zoneId);
-
- if (sendNetworkBroadcast) {
- // TODO Nothing in the platform appears to listen for this. Remove it.
- Intent intent = new Intent(TelephonyIntents.ACTION_NETWORK_SET_TIMEZONE);
- intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
- intent.putExtra("time-zone", zoneId);
- mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
- }
}
}
diff --git a/services/core/java/com/android/server/timezonedetector/TimeZoneDetectorStrategy.java b/services/core/java/com/android/server/timezonedetector/TimeZoneDetectorStrategy.java
index 6d7e05d044b4..b3013c7e0a5f 100644
--- a/services/core/java/com/android/server/timezonedetector/TimeZoneDetectorStrategy.java
+++ b/services/core/java/com/android/server/timezonedetector/TimeZoneDetectorStrategy.java
@@ -86,7 +86,7 @@ public class TimeZoneDetectorStrategy {
/**
* Sets the device's time zone.
*/
- void setDeviceTimeZone(@NonNull String zoneId, boolean sendNetworkBroadcast);
+ void setDeviceTimeZone(@NonNull String zoneId);
}
private static final String LOG_TAG = "TimeZoneDetectorStrategy";
@@ -333,7 +333,6 @@ public class TimeZoneDetectorStrategy {
Objects.requireNonNull(newZoneId);
Objects.requireNonNull(cause);
- boolean sendNetworkBroadcast = (origin == ORIGIN_PHONE);
boolean isOriginAutomatic = isOriginAutomatic(origin);
if (isOriginAutomatic) {
if (!mCallback.isAutoTimeZoneDetectionEnabled()) {
@@ -373,12 +372,11 @@ public class TimeZoneDetectorStrategy {
return;
}
- mCallback.setDeviceTimeZone(newZoneId, sendNetworkBroadcast);
+ mCallback.setDeviceTimeZone(newZoneId);
String msg = "Set device time zone."
+ " origin=" + origin
+ ", currentZoneId=" + currentZoneId
+ ", newZoneId=" + newZoneId
- + ", sendNetworkBroadcast" + sendNetworkBroadcast
+ ", cause=" + cause;
if (DBG) {
Slog.d(LOG_TAG, msg);
@@ -387,7 +385,7 @@ public class TimeZoneDetectorStrategy {
}
private static boolean isOriginAutomatic(@Origin int origin) {
- return origin == ORIGIN_PHONE;
+ return origin != ORIGIN_MANUAL;
}
@GuardedBy("this")
@@ -458,15 +456,17 @@ public class TimeZoneDetectorStrategy {
* Dumps internal state such as field values.
*/
public synchronized void dumpState(PrintWriter pw, String[] args) {
- pw.println("TimeZoneDetectorStrategy:");
- pw.println("mCallback.isTimeZoneDetectionEnabled()="
+ IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ");
+ ipw.println("TimeZoneDetectorStrategy:");
+
+ ipw.increaseIndent(); // level 1
+ ipw.println("mCallback.isTimeZoneDetectionEnabled()="
+ mCallback.isAutoTimeZoneDetectionEnabled());
- pw.println("mCallback.isDeviceTimeZoneInitialized()="
+ ipw.println("mCallback.isDeviceTimeZoneInitialized()="
+ mCallback.isDeviceTimeZoneInitialized());
- pw.println("mCallback.getDeviceTimeZone()="
+ ipw.println("mCallback.getDeviceTimeZone()="
+ mCallback.getDeviceTimeZone());
- IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ");
ipw.println("Time zone change log:");
ipw.increaseIndent(); // level 2
mTimeZoneChangesLog.dump(ipw);
@@ -487,8 +487,6 @@ public class TimeZoneDetectorStrategy {
ipw.decreaseIndent(); // level 2
ipw.decreaseIndent(); // level 1
ipw.flush();
-
- pw.flush();
}
/**
diff --git a/services/core/java/com/android/server/tv/TvInputManagerService.java b/services/core/java/com/android/server/tv/TvInputManagerService.java
index 8e66b149d344..18ed51a6cd5e 100644..100755
--- a/services/core/java/com/android/server/tv/TvInputManagerService.java
+++ b/services/core/java/com/android/server/tv/TvInputManagerService.java
@@ -2943,6 +2943,16 @@ public final class TvInputManagerService extends SystemService {
if (state != null) {
setStateLocked(inputId, state, mCurrentUserId);
}
+ UserState userState = getOrCreateUserStateLocked(mCurrentUserId);
+ // Broadcast the event to all hardware inputs.
+ for (ServiceState serviceState : userState.serviceStateMap.values()) {
+ if (!serviceState.isHardware || serviceState.service == null) continue;
+ try {
+ serviceState.service.notifyHdmiDeviceUpdated(deviceInfo);
+ } catch (RemoteException e) {
+ Slog.e(TAG, "error in notifyHdmiDeviceUpdated", e);
+ }
+ }
}
}
}
diff --git a/services/core/java/com/android/server/utils/TEST_MAPPING b/services/core/java/com/android/server/utils/TEST_MAPPING
new file mode 100644
index 000000000000..bb7cea98eda0
--- /dev/null
+++ b/services/core/java/com/android/server/utils/TEST_MAPPING
@@ -0,0 +1,12 @@
+{
+ "presubmit": [
+ {
+ "name": "FrameworksMockingServicesTests",
+ "options": [
+ {
+ "include-filter": "com.android.server.utils"
+ }
+ ]
+ }
+ ]
+} \ No newline at end of file
diff --git a/core/java/android/hardware/biometrics/Authenticator.java b/services/core/java/com/android/server/utils/quota/Categorizer.java
index 6d7e7488f2d0..bf2499114783 100644
--- a/core/java/android/hardware/biometrics/Authenticator.java
+++ b/services/core/java/com/android/server/utils/quota/Categorizer.java
@@ -14,22 +14,22 @@
* limitations under the License.
*/
-package android.hardware.biometrics;
+package com.android.server.utils.quota;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
/**
- * Type of authenticators defined on a granularity that the BiometricManager / BiometricPrompt
- * supports.
- * @hide
+ * Identifies the {@link Category} that each UPTC belongs in.
+ *
+ * @see Uptc
*/
-public class Authenticator {
-
+public interface Categorizer {
/**
- * Device credential, e.g. Pin/Pattern/Password.
+ * Return the {@link Category} that this UPTC belongs to.
+ *
+ * @see Uptc
*/
- public static final int TYPE_CREDENTIAL = 1 << 0;
- /**
- * Encompasses all biometrics on the device, e.g. Fingerprint/Iris/Face.
- */
- public static final int TYPE_BIOMETRIC = 1 << 1;
-
+ @NonNull
+ Category getCategory(int userId, @NonNull String packageName, @Nullable String tag);
}
diff --git a/services/core/java/com/android/server/utils/quota/Category.java b/services/core/java/com/android/server/utils/quota/Category.java
new file mode 100644
index 000000000000..d8459d7d806a
--- /dev/null
+++ b/services/core/java/com/android/server/utils/quota/Category.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.utils.quota;
+
+import android.annotation.NonNull;
+import android.util.proto.ProtoOutputStream;
+import android.util.quota.CategoryProto;
+
+/**
+ * A category as defined by the (system) client. Categories are used to put UPTCs in different
+ * groups. A sample group of Categories could be the various App Standby buckets or foreground vs
+ * background.
+ *
+ * @see Uptc
+ */
+public final class Category {
+ @NonNull
+ private final String mName;
+
+ private final int mHash;
+
+ /** Construct a new Category with the specified name. */
+ public Category(@NonNull String name) {
+ mName = name;
+ mHash = name.hashCode();
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean equals(Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (other instanceof Category) {
+ return this.mName.equals(((Category) other).mName);
+ }
+ return false;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public int hashCode() {
+ return mHash;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public String toString() {
+ return "Category{" + mName + "}";
+ }
+
+ void dumpDebug(ProtoOutputStream proto, long fieldId) {
+ final long token = proto.start(fieldId);
+ proto.write(CategoryProto.NAME, mName);
+ proto.end(token);
+ }
+}
diff --git a/services/core/java/com/android/server/utils/quota/QuotaChangeListener.java b/services/core/java/com/android/server/utils/quota/QuotaChangeListener.java
new file mode 100644
index 000000000000..b6730505f6f7
--- /dev/null
+++ b/services/core/java/com/android/server/utils/quota/QuotaChangeListener.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.utils.quota;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+
+/**
+ * Listener that is notified when a UPTC goes in and out of quota.
+ *
+ * @see Uptc
+ */
+public interface QuotaChangeListener {
+ /**
+ * Called when the UPTC reaches its quota or comes back into quota.
+ *
+ * @see Uptc
+ */
+ void onQuotaStateChanged(int userId, @NonNull String packageName, @Nullable String tag);
+}
diff --git a/services/core/java/com/android/server/utils/quota/Uptc.java b/services/core/java/com/android/server/utils/quota/Uptc.java
new file mode 100644
index 000000000000..40775441ef67
--- /dev/null
+++ b/services/core/java/com/android/server/utils/quota/Uptc.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.utils.quota;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.util.proto.ProtoOutputStream;
+import android.util.quota.UptcProto;
+
+import java.util.Objects;
+
+/**
+ * A data object that represents a userId-packageName-tag combination (UPTC). The tag can be any
+ * desired String.
+ */
+final class Uptc {
+ public final int userId;
+ @NonNull
+ public final String packageName;
+ @Nullable
+ public final String tag;
+
+ private final int mHash;
+
+ /** Construct a new Uptc with the specified values. */
+ Uptc(int userId, @NonNull String packageName, @Nullable String tag) {
+ this.userId = userId;
+ this.packageName = packageName;
+ this.tag = tag;
+
+ mHash = 31 * userId
+ + 31 * packageName.hashCode()
+ + tag == null ? 0 : (31 * tag.hashCode());
+ }
+
+ @Override
+ public String toString() {
+ return string(userId, packageName, tag);
+ }
+
+ void dumpDebug(ProtoOutputStream proto, long fieldId) {
+ final long token = proto.start(fieldId);
+
+ proto.write(UptcProto.USER_ID, userId);
+ proto.write(UptcProto.NAME, packageName);
+ proto.write(UptcProto.TAG, tag);
+
+ proto.end(token);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof Uptc) {
+ final Uptc other = (Uptc) obj;
+ return userId == other.userId
+ && Objects.equals(packageName, other.packageName)
+ && Objects.equals(tag, other.tag);
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ return mHash;
+ }
+
+ /** Standardize the output of a UPTC. */
+ static String string(int userId, @NonNull String packageName, @Nullable String tag) {
+ return "<" + userId + ">" + packageName + (tag == null ? "" : ("::" + tag));
+ }
+}
diff --git a/services/core/java/com/android/server/utils/quota/UptcMap.java b/services/core/java/com/android/server/utils/quota/UptcMap.java
new file mode 100644
index 000000000000..7b499139aa7c
--- /dev/null
+++ b/services/core/java/com/android/server/utils/quota/UptcMap.java
@@ -0,0 +1,163 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.utils.quota;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.util.ArrayMap;
+import android.util.SparseArrayMap;
+
+import java.util.function.Consumer;
+
+/**
+ * A SparseArrayMap of ArrayMaps, which is suitable for holding userId-packageName-tag combination
+ * (UPTC)->object associations. Tags are any desired String.
+ *
+ * @see Uptc
+ */
+class UptcMap<T> {
+ private final SparseArrayMap<ArrayMap<String, T>> mData = new SparseArrayMap<>();
+
+ public void add(int userId, @NonNull String packageName, @Nullable String tag,
+ @Nullable T obj) {
+ ArrayMap<String, T> data = mData.get(userId, packageName);
+ if (data == null) {
+ data = new ArrayMap<>();
+ mData.add(userId, packageName, data);
+ }
+ data.put(tag, obj);
+ }
+
+ public void clear() {
+ mData.clear();
+ }
+
+ public boolean contains(int userId, @NonNull String packageName) {
+ return mData.contains(userId, packageName);
+ }
+
+ public boolean contains(int userId, @NonNull String packageName, @Nullable String tag) {
+ // This structure never inserts a null ArrayMap, so if get(userId, packageName) returns
+ // null, the UPTC was never inserted.
+ ArrayMap<String, T> data = mData.get(userId, packageName);
+ return data != null && data.containsKey(tag);
+ }
+
+ /** Removes all the data for the user, if there was any. */
+ public void delete(int userId) {
+ mData.delete(userId);
+ }
+
+ /** Removes the data for the user, package, and tag, if there was any. */
+ public void delete(int userId, @NonNull String packageName, @Nullable String tag) {
+ final ArrayMap<String, T> data = mData.get(userId, packageName);
+ if (data != null) {
+ data.remove(tag);
+ if (data.size() == 0) {
+ mData.delete(userId, packageName);
+ }
+ }
+ }
+
+ /** Removes the data for the user and package, if there was any. */
+ public ArrayMap<String, T> delete(int userId, @NonNull String packageName) {
+ return mData.delete(userId, packageName);
+ }
+
+ /**
+ * Returns the set of tag -> object mappings for the given userId and packageName
+ * combination.
+ */
+ @Nullable
+ public ArrayMap<String, T> get(int userId, @NonNull String packageName) {
+ return mData.get(userId, packageName);
+ }
+
+ /** Returns the saved object for the given UPTC. */
+ @Nullable
+ public T get(int userId, @NonNull String packageName, @Nullable String tag) {
+ final ArrayMap<String, T> data = mData.get(userId, packageName);
+ return data != null ? data.get(tag) : null;
+ }
+
+ /**
+ * Returns the index for which {@link #getUserIdAtIndex(int)} would return the specified userId,
+ * or a negative number if the specified userId is not mapped.
+ */
+ public int indexOfUserId(int userId) {
+ return mData.indexOfKey(userId);
+ }
+
+ /**
+ * Returns the index for which {@link #getPackageNameAtIndex(int, int)} would return the
+ * specified userId, or a negative number if the specified userId and packageName are not mapped
+ * together.
+ */
+ public int indexOfUserIdAndPackage(int userId, @NonNull String packageName) {
+ return mData.indexOfKey(userId, packageName);
+ }
+
+ /** Returns the userId at the given index. */
+ public int getUserIdAtIndex(int index) {
+ return mData.keyAt(index);
+ }
+
+ /** Returns the package name at the given index. */
+ @NonNull
+ public String getPackageNameAtIndex(int userIndex, int packageIndex) {
+ return mData.keyAt(userIndex, packageIndex);
+ }
+
+ /** Returns the tag at the given index. */
+ @NonNull
+ public String getTagAtIndex(int userIndex, int packageIndex, int tagIndex) {
+ // This structure never inserts a null ArrayMap, so if the indices are valid, valueAt()
+ // won't return null.
+ return mData.valueAt(userIndex, packageIndex).keyAt(tagIndex);
+ }
+
+ /** Returns the size of the outer (userId) array. */
+ public int userCount() {
+ return mData.numMaps();
+ }
+
+ /** Returns the number of packages saved for a given userId. */
+ public int packageCountForUser(int userId) {
+ return mData.numElementsForKey(userId);
+ }
+
+ /** Returns the number of tags saved for a given userId-packageName combination. */
+ public int tagCountForUserAndPackage(int userId, @NonNull String packageName) {
+ final ArrayMap data = mData.get(userId, packageName);
+ return data != null ? data.size() : 0;
+ }
+
+ /** Returns the value T at the given user, package, and tag indices. */
+ @Nullable
+ public T valueAt(int userIndex, int packageIndex, int tagIndex) {
+ final ArrayMap<String, T> data = mData.valueAt(userIndex, packageIndex);
+ return data != null ? data.valueAt(tagIndex) : null;
+ }
+
+ public void forEach(Consumer<T> consumer) {
+ mData.forEach((tagMap) -> {
+ for (int i = tagMap.size() - 1; i >= 0; --i) {
+ consumer.accept(tagMap.valueAt(i));
+ }
+ });
+ }
+}
diff --git a/services/core/java/com/android/server/wm/ActivityDisplay.java b/services/core/java/com/android/server/wm/ActivityDisplay.java
deleted file mode 100644
index 84152e830c3f..000000000000
--- a/services/core/java/com/android/server/wm/ActivityDisplay.java
+++ /dev/null
@@ -1,1396 +0,0 @@
-/*
- * Copyright (C) 2017 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 com.android.server.wm;
-
-import static android.app.ActivityTaskManager.INVALID_STACK_ID;
-import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
-import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
-import static android.app.WindowConfiguration.ROTATION_UNDEFINED;
-import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
-import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
-import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN_OR_SPLIT_SCREEN_SECONDARY;
-import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
-import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
-import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
-import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
-import static android.os.Build.VERSION_CODES.N;
-import static android.view.Display.DEFAULT_DISPLAY;
-import static android.view.Display.FLAG_PRIVATE;
-import static android.view.Display.REMOVE_MODE_DESTROY_CONTENT;
-
-import static com.android.server.am.ActivityDisplayProto.DISPLAY;
-import static com.android.server.am.ActivityDisplayProto.FOCUSED_STACK_ID;
-import static com.android.server.am.ActivityDisplayProto.ID;
-import static com.android.server.am.ActivityDisplayProto.RESUMED_ACTIVITY;
-import static com.android.server.am.ActivityDisplayProto.SINGLE_TASK_INSTANCE;
-import static com.android.server.am.ActivityDisplayProto.STACKS;
-import static com.android.server.wm.ActivityStack.ActivityState.RESUMED;
-import static com.android.server.wm.ActivityStack.STACK_VISIBILITY_VISIBLE;
-import static com.android.server.wm.ActivityStackSupervisor.TAG_TASKS;
-import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
-import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STATES;
-import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
-import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
-import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
-import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
-import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_FOCUS_LIGHT;
-import static com.android.server.wm.RootActivityContainer.FindTaskResult;
-import static com.android.server.wm.RootActivityContainer.TAG_STATES;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_DISPLAY;
-import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
-import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_NORMAL;
-
-import android.annotation.Nullable;
-import android.app.ActivityManager;
-import android.app.ActivityManagerInternal;
-import android.app.ActivityOptions;
-import android.app.WindowConfiguration;
-import android.content.pm.ActivityInfo;
-import android.content.res.Configuration;
-import android.graphics.Point;
-import android.os.IBinder;
-import android.os.Message;
-import android.os.UserHandle;
-import android.provider.Settings;
-import android.util.IntArray;
-import android.util.Slog;
-import android.util.proto.ProtoOutputStream;
-import android.view.Display;
-
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.util.function.pooled.PooledConsumer;
-import com.android.internal.util.function.pooled.PooledLambda;
-import com.android.internal.util.function.pooled.PooledPredicate;
-import com.android.server.protolog.common.ProtoLog;
-
-import java.io.PrintWriter;
-import java.util.ArrayList;
-
-/**
- * Exactly one of these classes per Display in the system. Capable of holding zero or more
- * attached {@link ActivityStack}s.
- */
-class ActivityDisplay extends DisplayContent {
- private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityDisplay" : TAG_ATM;
- private static final String TAG_STACK = TAG + POSTFIX_STACK;
-
- static final int POSITION_TOP = Integer.MAX_VALUE;
- static final int POSITION_BOTTOM = Integer.MIN_VALUE;
-
- /**
- * Counter for next free stack ID to use for dynamic activity stacks. Unique across displays.
- */
- private static int sNextFreeStackId = 0;
-
- private RootActivityContainer mRootActivityContainer;
- /** Actual Display this object tracks. */
- int mDisplayId;
- Display mDisplay;
-
- /**
- * All of the stacks on this display. Order matters, topmost stack is in front of all other
- * stacks, bottommost behind. Accessed directly by ActivityManager package classes. Any calls
- * changing the list should also call {@link #onStackOrderChanged()}.
- */
- private ArrayList<OnStackOrderChangedListener> mStackOrderChangedCallbacks = new ArrayList<>();
-
- /** Array of all UIDs that are present on the display. */
- private IntArray mDisplayAccessUIDs = new IntArray();
-
- /** All tokens used to put activities on this stack to sleep (including mOffToken) */
- final ArrayList<ActivityTaskManagerInternal.SleepToken> mAllSleepTokens = new ArrayList<>();
- /** The token acquired by ActivityStackSupervisor to put stacks on the display to sleep */
- ActivityTaskManagerInternal.SleepToken mOffToken;
-
- private boolean mSleeping;
-
- /** We started the process of removing the display from the system. */
- private boolean mRemoving;
-
- /**
- * The display is removed from the system and we are just waiting for all activities on it to be
- * finished before removing this object.
- */
- private boolean mRemoved;
-
- /** The display can only contain one task. */
- private boolean mSingleTaskInstance;
-
- /**
- * Non-null if the last size compatibility mode activity is using non-native screen
- * configuration. The activity is not able to put in multi-window mode, so it exists only one
- * per display.
- */
- private ActivityRecord mLastCompatModeActivity;
-
- /**
- * A focusable stack that is purposely to be positioned at the top. Although the stack may not
- * have the topmost index, it is used as a preferred candidate to prevent being unable to resume
- * target stack properly when there are other focusable always-on-top stacks.
- */
- private ActivityStack mPreferredTopFocusableStack;
-
- /**
- * If this is the same as {@link #getFocusedStack} then the activity on the top of the focused
- * stack has been resumed. If stacks are changing position this will hold the old stack until
- * the new stack becomes resumed after which it will be set to current focused stack.
- */
- private ActivityStack mLastFocusedStack;
-
- // Used in updating the display size
- private Point mTmpDisplaySize = new Point();
-
- // Used in updating override configurations
- private final Configuration mTempConfig = new Configuration();
-
- private final FindTaskResult mTmpFindTaskResult = new FindTaskResult();
-
- ActivityDisplay(RootActivityContainer root, Display display) {
- super(display, root.mWindowManager);
- mRootActivityContainer = root;
- mDisplayId = display.getDisplayId();
- mDisplay = display;
-
- if (DEBUG_DISPLAY) Slog.v(TAG_WM, "Adding display=" + display);
-
- mWmService.mDisplayWindowSettings.applySettingsToDisplayLocked(this);
-
- if (mWmService.mDisplayManagerInternal != null) {
- mWmService.mDisplayManagerInternal
- .setDisplayInfoOverrideFromWindowManager(mDisplayId, getDisplayInfo());
- configureDisplayPolicy();
- }
-
- reconfigureDisplayLocked();
- onRequestedOverrideConfigurationChanged(getRequestedOverrideConfiguration());
- mWmService.mDisplayNotificationController.dispatchDisplayAdded(this);
- }
-
- void onDisplayChanged() {
- // The window policy is responsible for stopping activities on the default display.
- final int displayId = mDisplay.getDisplayId();
- if (displayId != DEFAULT_DISPLAY) {
- final int displayState = mDisplay.getState();
- if (displayState == Display.STATE_OFF && mOffToken == null) {
- mOffToken = mAtmService.acquireSleepToken("Display-off", displayId);
- } else if (displayState == Display.STATE_ON && mOffToken != null) {
- mOffToken.release();
- mOffToken = null;
- }
- }
-
- mDisplay.getRealSize(mTmpDisplaySize);
- setBounds(0, 0, mTmpDisplaySize.x, mTmpDisplaySize.y);
- updateDisplayInfo();
- mWmService.requestTraversal();
- }
-
- void addStack(ActivityStack stack, int position) {
- setStackOnDisplay(stack, position);
- positionStackAt(stack, position);
- mAtmService.updateSleepIfNeededLocked();
- }
-
- void onStackRemoved(ActivityStack stack) {
- if (DEBUG_STACK) {
- Slog.v(TAG_STACK, "removeStack: detaching " + stack + " from displayId=" + mDisplayId);
- }
- if (mPreferredTopFocusableStack == stack) {
- mPreferredTopFocusableStack = null;
- }
- releaseSelfIfNeeded();
- mAtmService.updateSleepIfNeededLocked();
- onStackOrderChanged(stack);
- }
-
- void positionStackAtTop(ActivityStack stack, boolean includingParents) {
- positionStackAtTop(stack, includingParents, null /* updateLastFocusedStackReason */);
- }
-
- void positionStackAtTop(ActivityStack stack, boolean includingParents,
- String updateLastFocusedStackReason) {
- positionStackAt(stack, getStackCount(), includingParents, updateLastFocusedStackReason);
- }
-
- void positionStackAtBottom(ActivityStack stack) {
- positionStackAtBottom(stack, null /* updateLastFocusedStackReason */);
- }
-
- void positionStackAtBottom(ActivityStack stack, String updateLastFocusedStackReason) {
- positionStackAt(stack, 0, false /* includingParents */, updateLastFocusedStackReason);
- }
-
- private void positionStackAt(ActivityStack stack, int position) {
- positionStackAt(stack, position, false /* includingParents */,
- null /* updateLastFocusedStackReason */);
- }
-
- private void positionStackAt(ActivityStack stack, int position, boolean includingParents,
- String updateLastFocusedStackReason) {
- // TODO: Keep in sync with WindowContainer.positionChildAt(), once we change that to adjust
- // the position internally, also update the logic here
- final ActivityStack prevFocusedStack = updateLastFocusedStackReason != null
- ? getFocusedStack() : null;
- final boolean wasContained = getIndexOf(stack) >= 0;
- if (mSingleTaskInstance && getStackCount() == 1 && !wasContained) {
- throw new IllegalStateException(
- "positionStackAt: Can only have one task on display=" + this);
- }
-
- // Since positionChildAt() is called during the creation process of pinned stacks,
- // ActivityStack#getStack() can be null.
- positionStackAt(position, stack, includingParents);
-
- // The insert position may be adjusted to non-top when there is always-on-top stack. Since
- // the original position is preferred to be top, the stack should have higher priority when
- // we are looking for top focusable stack. The condition {@code wasContained} restricts the
- // preferred stack is set only when moving an existing stack to top instead of adding a new
- // stack that may be too early (e.g. in the middle of launching or reparenting).
- if (wasContained && position >= getStackCount() - 1 && stack.isFocusableAndVisible()) {
- mPreferredTopFocusableStack = stack;
- } else if (mPreferredTopFocusableStack == stack) {
- mPreferredTopFocusableStack = null;
- }
-
- if (updateLastFocusedStackReason != null) {
- final ActivityStack currentFocusedStack = getFocusedStack();
- if (currentFocusedStack != prevFocusedStack) {
- mLastFocusedStack = prevFocusedStack;
- EventLogTags.writeWmFocusedStack(mRootActivityContainer.mCurrentUser, mDisplayId,
- currentFocusedStack == null ? -1 : currentFocusedStack.getStackId(),
- mLastFocusedStack == null ? -1 : mLastFocusedStack.getStackId(),
- updateLastFocusedStackReason);
- }
- }
-
- onStackOrderChanged(stack);
- }
-
- ActivityStack getStack(int stackId) {
- for (int i = getStackCount() - 1; i >= 0; --i) {
- final ActivityStack stack = getStackAt(i);
- if (stack.mStackId == stackId) {
- return stack;
- }
- }
- return null;
- }
-
- boolean alwaysCreateStack(int windowingMode, int activityType) {
- // Always create a stack for fullscreen, freeform, and split-screen-secondary windowing
- // modes so that we can manage visual ordering and return types correctly.
- return activityType == ACTIVITY_TYPE_STANDARD
- && (windowingMode == WINDOWING_MODE_FULLSCREEN
- || windowingMode == WINDOWING_MODE_FREEFORM
- || windowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
- }
-
- /**
- * Returns an existing stack compatible with the windowing mode and activity type or creates one
- * if a compatible stack doesn't exist.
- * @see #getStack(int, int)
- * @see #createStack(int, int, boolean)
- */
- ActivityStack getOrCreateStack(int windowingMode, int activityType,
- boolean onTop) {
- if (!alwaysCreateStack(windowingMode, activityType)) {
- ActivityStack stack = getStack(windowingMode, activityType);
- if (stack != null) {
- return stack;
- }
- }
- return createStack(windowingMode, activityType, onTop);
- }
-
- /**
- * Returns an existing stack compatible with the input params or creates one
- * if a compatible stack doesn't exist.
- * @see #getOrCreateStack(int, int, boolean)
- */
- ActivityStack getOrCreateStack(@Nullable ActivityRecord r,
- @Nullable ActivityOptions options, @Nullable Task candidateTask, int activityType,
- boolean onTop) {
- // First preference is the windowing mode in the activity options if set.
- int windowingMode = (options != null)
- ? options.getLaunchWindowingMode() : WINDOWING_MODE_UNDEFINED;
- // Validate that our desired windowingMode will work under the current conditions.
- // UNDEFINED windowing mode is a valid result and means that the new stack will inherit
- // it's display's windowing mode.
- windowingMode = validateWindowingMode(windowingMode, r, candidateTask, activityType);
- return getOrCreateStack(windowingMode, activityType, onTop);
- }
-
- @VisibleForTesting
- int getNextStackId() {
- return sNextFreeStackId++;
- }
-
- /**
- * Creates a stack matching the input windowing mode and activity type on this display.
- * @param windowingMode The windowing mode the stack should be created in. If
- * {@link WindowConfiguration#WINDOWING_MODE_UNDEFINED} then the stack will
- * inherit it's parent's windowing mode.
- * @param activityType The activityType the stack should be created in. If
- * {@link WindowConfiguration#ACTIVITY_TYPE_UNDEFINED} then the stack will
- * be created in {@link WindowConfiguration#ACTIVITY_TYPE_STANDARD}.
- * @param onTop If true the stack will be created at the top of the display, else at the bottom.
- * @return The newly created stack.
- */
- ActivityStack createStack(int windowingMode, int activityType, boolean onTop) {
-
- if (mSingleTaskInstance && getStackCount() > 0) {
- // Create stack on default display instead since this display can only contain 1 stack.
- // TODO: Kinda a hack, but better that having the decision at each call point. Hoping
- // this goes away once ActivityView is no longer using virtual displays.
- return mRootActivityContainer.getDefaultDisplay().createStack(
- windowingMode, activityType, onTop);
- }
-
- if (activityType == ACTIVITY_TYPE_UNDEFINED) {
- // Can't have an undefined stack type yet...so re-map to standard. Anyone that wants
- // anything else should be passing it in anyways...
- activityType = ACTIVITY_TYPE_STANDARD;
- }
-
- if (activityType != ACTIVITY_TYPE_STANDARD) {
- // For now there can be only one stack of a particular non-standard activity type on a
- // display. So, get that ignoring whatever windowing mode it is currently in.
- ActivityStack stack = getStack(WINDOWING_MODE_UNDEFINED, activityType);
- if (stack != null) {
- throw new IllegalArgumentException("Stack=" + stack + " of activityType="
- + activityType + " already on display=" + this + ". Can't have multiple.");
- }
- }
-
- if (!isWindowingModeSupported(windowingMode, mAtmService.mSupportsMultiWindow,
- mAtmService.mSupportsSplitScreenMultiWindow,
- mAtmService.mSupportsFreeformWindowManagement,
- mAtmService.mSupportsPictureInPicture, activityType)) {
- throw new IllegalArgumentException("Can't create stack for unsupported windowingMode="
- + windowingMode);
- }
-
- final int stackId = getNextStackId();
- return createStackUnchecked(windowingMode, activityType, stackId, onTop);
- }
-
- @VisibleForTesting
- ActivityStack createStackUnchecked(int windowingMode, int activityType,
- int stackId, boolean onTop) {
- if (windowingMode == WINDOWING_MODE_PINNED && activityType != ACTIVITY_TYPE_STANDARD) {
- throw new IllegalArgumentException("Stack with windowing mode cannot with non standard "
- + "activity type.");
- }
- return new ActivityStack(this, stackId,
- mRootActivityContainer.mStackSupervisor, windowingMode, activityType, onTop);
- }
-
- /**
- * Get the preferred focusable stack in priority. If the preferred stack does not exist, find a
- * focusable and visible stack from the top of stacks in this display.
- */
- ActivityStack getFocusedStack() {
- if (mPreferredTopFocusableStack != null) {
- return mPreferredTopFocusableStack;
- }
-
- for (int i = getStackCount() - 1; i >= 0; --i) {
- final ActivityStack stack = getStackAt(i);
- if (stack.isFocusableAndVisible()) {
- return stack;
- }
- }
-
- return null;
- }
-
- ActivityStack getNextFocusableStack(ActivityStack currentFocus, boolean ignoreCurrent) {
- final int currentWindowingMode = currentFocus != null
- ? currentFocus.getWindowingMode() : WINDOWING_MODE_UNDEFINED;
-
- ActivityStack candidate = null;
- for (int i = getStackCount() - 1; i >= 0; --i) {
- final ActivityStack stack = getStackAt(i);
- if (ignoreCurrent && stack == currentFocus) {
- continue;
- }
- if (!stack.isFocusableAndVisible()) {
- continue;
- }
-
- if (currentWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY
- && candidate == null && stack.inSplitScreenPrimaryWindowingMode()) {
- // If the currently focused stack is in split-screen secondary we save off the
- // top primary split-screen stack as a candidate for focus because we might
- // prefer focus to move to an other stack to avoid primary split-screen stack
- // overlapping with a fullscreen stack when a fullscreen stack is higher in z
- // than the next split-screen stack. Assistant stack, I am looking at you...
- // We only move the focus to the primary-split screen stack if there isn't a
- // better alternative.
- candidate = stack;
- continue;
- }
- if (candidate != null && stack.inSplitScreenSecondaryWindowingMode()) {
- // Use the candidate stack since we are now at the secondary split-screen.
- return candidate;
- }
- return stack;
- }
- return candidate;
- }
-
- ActivityRecord getResumedActivity() {
- final ActivityStack focusedStack = getFocusedStack();
- if (focusedStack == null) {
- return null;
- }
- // TODO(b/111541062): Move this into ActivityStack#getResumedActivity()
- // Check if the focused stack has the resumed activity
- ActivityRecord resumedActivity = focusedStack.getResumedActivity();
- if (resumedActivity == null || resumedActivity.app == null) {
- // If there is no registered resumed activity in the stack or it is not running -
- // try to use previously resumed one.
- resumedActivity = focusedStack.mPausingActivity;
- if (resumedActivity == null || resumedActivity.app == null) {
- // If previously resumed activity doesn't work either - find the topmost running
- // activity that can be focused.
- resumedActivity = focusedStack.topRunningActivityLocked(true /* focusableOnly */);
- }
- }
- return resumedActivity;
- }
-
- ActivityStack getLastFocusedStack() {
- return mLastFocusedStack;
- }
-
- boolean allResumedActivitiesComplete() {
- for (int stackNdx = getStackCount() - 1; stackNdx >= 0; --stackNdx) {
- final ActivityRecord r = getStackAt(stackNdx).getResumedActivity();
- if (r != null && !r.isState(RESUMED)) {
- return false;
- }
- }
- final ActivityStack currentFocusedStack = getFocusedStack();
- if (DEBUG_STACK) {
- Slog.d(TAG_STACK, "allResumedActivitiesComplete: mLastFocusedStack changing from="
- + mLastFocusedStack + " to=" + currentFocusedStack);
- }
- mLastFocusedStack = currentFocusedStack;
- return true;
- }
-
- /**
- * Pause all activities in either all of the stacks or just the back stacks. This is done before
- * resuming a new activity and to make sure that previously active activities are
- * paused in stacks that are no longer visible or in pinned windowing mode. This does not
- * pause activities in visible stacks, so if an activity is launched within the same stack/task,
- * then we should explicitly pause that stack's top activity.
- * @param userLeaving Passed to pauseActivity() to indicate whether to call onUserLeaving().
- * @param resuming The resuming activity.
- * @return {@code true} if any activity was paused as a result of this call.
- */
- boolean pauseBackStacks(boolean userLeaving, ActivityRecord resuming) {
- boolean someActivityPaused = false;
- for (int stackNdx = getStackCount() - 1; stackNdx >= 0; --stackNdx) {
- final ActivityStack stack = getStackAt(stackNdx);
- final ActivityRecord resumedActivity = stack.getResumedActivity();
- if (resumedActivity != null
- && (stack.getVisibility(resuming) != STACK_VISIBILITY_VISIBLE
- || !stack.isFocusable())) {
- if (DEBUG_STATES) Slog.d(TAG_STATES, "pauseBackStacks: stack=" + stack +
- " mResumedActivity=" + resumedActivity);
- someActivityPaused |= stack.startPausingLocked(userLeaving, false /* uiSleeping*/,
- resuming);
- }
- }
- return someActivityPaused;
- }
-
- /**
- * Find task for putting the Activity in.
- */
- void findTaskLocked(final ActivityRecord r, final boolean isPreferredDisplay,
- FindTaskResult result) {
- mTmpFindTaskResult.clear();
- for (int stackNdx = getStackCount() - 1; stackNdx >= 0; --stackNdx) {
- final ActivityStack stack = getStackAt(stackNdx);
- if (!r.hasCompatibleActivityType(stack)) {
- if (DEBUG_TASKS) {
- Slog.d(TAG_TASKS, "Skipping stack: (mismatch activity/stack) " + stack);
- }
- continue;
- }
-
- mTmpFindTaskResult.process(r, stack);
- // It is possible to have tasks in multiple stacks with the same root affinity, so
- // we should keep looking after finding an affinity match to see if there is a
- // better match in another stack. Also, task affinity isn't a good enough reason
- // to target a display which isn't the source of the intent, so skip any affinity
- // matches not on the specified display.
- if (mTmpFindTaskResult.mRecord != null) {
- if (mTmpFindTaskResult.mIdealMatch) {
- result.setTo(mTmpFindTaskResult);
- return;
- } else if (isPreferredDisplay) {
- // Note: since the traversing through the stacks is top down, the floating
- // tasks should always have lower priority than any affinity-matching tasks
- // in the fullscreen stacks
- result.setTo(mTmpFindTaskResult);
- }
- }
- }
- }
-
- /**
- * Removes stacks in the input windowing modes from the system if they are of activity type
- * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
- */
- void removeStacksInWindowingModes(int... windowingModes) {
- if (windowingModes == null || windowingModes.length == 0) {
- return;
- }
-
- // Collect the stacks that are necessary to be removed instead of performing the removal
- // by looping mStacks, so that we don't miss any stacks after the stack size changed or
- // stacks reordered.
- final ArrayList<ActivityStack> stacks = new ArrayList<>();
- for (int j = windowingModes.length - 1 ; j >= 0; --j) {
- final int windowingMode = windowingModes[j];
- for (int i = getStackCount() - 1; i >= 0; --i) {
- final ActivityStack stack = getStackAt(i);
- if (!stack.isActivityTypeStandardOrUndefined()) {
- continue;
- }
- if (stack.getWindowingMode() != windowingMode) {
- continue;
- }
- stacks.add(stack);
- }
- }
-
- for (int i = stacks.size() - 1; i >= 0; --i) {
- mRootActivityContainer.mStackSupervisor.removeStack(stacks.get(i));
- }
- }
-
- void removeStacksWithActivityTypes(int... activityTypes) {
- if (activityTypes == null || activityTypes.length == 0) {
- return;
- }
-
- // Collect the stacks that are necessary to be removed instead of performing the removal
- // by looping mStacks, so that we don't miss any stacks after the stack size changed or
- // stacks reordered.
- final ArrayList<ActivityStack> stacks = new ArrayList<>();
- for (int j = activityTypes.length - 1 ; j >= 0; --j) {
- final int activityType = activityTypes[j];
- for (int i = getStackCount() - 1; i >= 0; --i) {
- final ActivityStack stack = getStackAt(i);
- if (stack.getActivityType() == activityType) {
- stacks.add(stack);
- }
- }
- }
-
- for (int i = stacks.size() - 1; i >= 0; --i) {
- mRootActivityContainer.mStackSupervisor.removeStack(stacks.get(i));
- }
- }
-
- void onSplitScreenModeDismissed() {
- mAtmService.deferWindowLayout();
- try {
- // Adjust the windowing mode of any stack in secondary split-screen to fullscreen.
- for (int i = getStackCount() - 1; i >= 0; --i) {
- final ActivityStack otherStack = getStackAt(i);
- if (!otherStack.inSplitScreenSecondaryWindowingMode()) {
- continue;
- }
- otherStack.setWindowingMode(WINDOWING_MODE_UNDEFINED, false /* animate */,
- false /* showRecents */, false /* enteringSplitScreenMode */,
- true /* deferEnsuringVisibility */, false /* creating */);
- }
- } finally {
- final ActivityStack topFullscreenStack =
- getTopStackInWindowingMode(WINDOWING_MODE_FULLSCREEN);
- final ActivityStack homeStack = getHomeStack();
- if (topFullscreenStack != null && homeStack != null && !isTopStack(homeStack)) {
- // Whenever split-screen is dismissed we want the home stack directly behind the
- // current top fullscreen stack so it shows up when the top stack is finished.
- // TODO: Would be better to use ActivityDisplay.positionChildAt() for this, however
- // ActivityDisplay doesn't have a direct controller to WM side yet. We can switch
- // once we have that.
- homeStack.moveToFront("onSplitScreenModeDismissed");
- topFullscreenStack.moveToFront("onSplitScreenModeDismissed");
- }
- mAtmService.continueWindowLayout();
- }
- }
-
- void onSplitScreenModeActivated() {
- mAtmService.deferWindowLayout();
- try {
- // Adjust the windowing mode of any affected by split-screen to split-screen secondary.
- final ActivityStack splitScreenPrimaryStack = getSplitScreenPrimaryStack();
- for (int i = getStackCount() - 1; i >= 0; --i) {
- final ActivityStack otherStack = getStackAt(i);
- if (otherStack == splitScreenPrimaryStack
- || !otherStack.affectedBySplitScreenResize()) {
- continue;
- }
- otherStack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_SECONDARY,
- false /* animate */, false /* showRecents */,
- true /* enteringSplitScreenMode */, true /* deferEnsuringVisibility */,
- false /* creating */);
- }
- } finally {
- mAtmService.continueWindowLayout();
- }
- }
-
- /**
- * Returns true if the {@param windowingMode} is supported based on other parameters passed in.
- * @param windowingMode The windowing mode we are checking support for.
- * @param supportsMultiWindow If we should consider support for multi-window mode in general.
- * @param supportsSplitScreen If we should consider support for split-screen multi-window.
- * @param supportsFreeform If we should consider support for freeform multi-window.
- * @param supportsPip If we should consider support for picture-in-picture mutli-window.
- * @param activityType The activity type under consideration.
- * @return true if the windowing mode is supported.
- */
- private boolean isWindowingModeSupported(int windowingMode, boolean supportsMultiWindow,
- boolean supportsSplitScreen, boolean supportsFreeform, boolean supportsPip,
- int activityType) {
-
- if (windowingMode == WINDOWING_MODE_UNDEFINED
- || windowingMode == WINDOWING_MODE_FULLSCREEN) {
- return true;
- }
- if (!supportsMultiWindow) {
- return false;
- }
-
- final int displayWindowingMode = getWindowingMode();
- if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY
- || windowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY) {
- return supportsSplitScreen
- && WindowConfiguration.supportSplitScreenWindowingMode(activityType)
- // Freeform windows and split-screen windows don't mix well, so prevent
- // split windowing modes on freeform displays.
- && displayWindowingMode != WINDOWING_MODE_FREEFORM;
- }
-
- if (!supportsFreeform && windowingMode == WINDOWING_MODE_FREEFORM) {
- return false;
- }
-
- if (!supportsPip && windowingMode == WINDOWING_MODE_PINNED) {
- return false;
- }
- return true;
- }
-
- /**
- * Resolves the windowing mode that an {@link ActivityRecord} would be in if started on this
- * display with the provided parameters.
- *
- * @param r The ActivityRecord in question.
- * @param options Options to start with.
- * @param task The task within-which the activity would start.
- * @param activityType The type of activity to start.
- * @return The resolved (not UNDEFINED) windowing-mode that the activity would be in.
- */
- int resolveWindowingMode(@Nullable ActivityRecord r, @Nullable ActivityOptions options,
- @Nullable Task task, int activityType) {
-
- // First preference if the windowing mode in the activity options if set.
- int windowingMode = (options != null)
- ? options.getLaunchWindowingMode() : WINDOWING_MODE_UNDEFINED;
-
- // If windowing mode is unset, then next preference is the candidate task, then the
- // activity record.
- if (windowingMode == WINDOWING_MODE_UNDEFINED) {
- if (task != null) {
- windowingMode = task.getWindowingMode();
- }
- if (windowingMode == WINDOWING_MODE_UNDEFINED && r != null) {
- windowingMode = r.getWindowingMode();
- }
- if (windowingMode == WINDOWING_MODE_UNDEFINED) {
- // Use the display's windowing mode.
- windowingMode = getWindowingMode();
- }
- }
- windowingMode = validateWindowingMode(windowingMode, r, task, activityType);
- return windowingMode != WINDOWING_MODE_UNDEFINED
- ? windowingMode : WINDOWING_MODE_FULLSCREEN;
- }
-
- /**
- * Check that the requested windowing-mode is appropriate for the specified task and/or activity
- * on this display.
- *
- * @param windowingMode The windowing-mode to validate.
- * @param r The {@link ActivityRecord} to check against.
- * @param task The {@link Task} to check against.
- * @param activityType An activity type.
- * @return The provided windowingMode or the closest valid mode which is appropriate.
- */
- int validateWindowingMode(int windowingMode, @Nullable ActivityRecord r, @Nullable Task task,
- int activityType) {
- // Make sure the windowing mode we are trying to use makes sense for what is supported.
- boolean supportsMultiWindow = mAtmService.mSupportsMultiWindow;
- boolean supportsSplitScreen = mAtmService.mSupportsSplitScreenMultiWindow;
- boolean supportsFreeform = mAtmService.mSupportsFreeformWindowManagement;
- boolean supportsPip = mAtmService.mSupportsPictureInPicture;
- if (supportsMultiWindow) {
- if (task != null) {
- supportsMultiWindow = task.isResizeable();
- supportsSplitScreen = task.supportsSplitScreenWindowingMode();
- // TODO: Do we need to check for freeform and Pip support here?
- } else if (r != null) {
- supportsMultiWindow = r.isResizeable();
- supportsSplitScreen = r.supportsSplitScreenWindowingMode();
- supportsFreeform = r.supportsFreeform();
- supportsPip = r.supportsPictureInPicture();
- }
- }
-
- final boolean inSplitScreenMode = hasSplitScreenPrimaryStack();
- if (!inSplitScreenMode
- && windowingMode == WINDOWING_MODE_FULLSCREEN_OR_SPLIT_SCREEN_SECONDARY) {
- // Switch to the display's windowing mode if we are not in split-screen mode and we are
- // trying to launch in split-screen secondary.
- windowingMode = WINDOWING_MODE_UNDEFINED;
- } else if (inSplitScreenMode && (windowingMode == WINDOWING_MODE_FULLSCREEN
- || windowingMode == WINDOWING_MODE_UNDEFINED)
- && supportsSplitScreen) {
- windowingMode = WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
- }
-
- if (windowingMode != WINDOWING_MODE_UNDEFINED
- && isWindowingModeSupported(windowingMode, supportsMultiWindow, supportsSplitScreen,
- supportsFreeform, supportsPip, activityType)) {
- return windowingMode;
- }
- return WINDOWING_MODE_UNDEFINED;
- }
-
- boolean isTopStack(ActivityStack stack) {
- return stack == getTopStack();
- }
-
- boolean isTopNotPinnedStack(ActivityStack stack) {
- for (int i = getStackCount() - 1; i >= 0; --i) {
- final ActivityStack current = getStackAt(i);
- if (!current.inPinnedWindowingMode()) {
- return current == stack;
- }
- }
- return false;
- }
-
- ActivityStack getTopStackInWindowingMode(int windowingMode) {
- for (int i = getStackCount() - 1; i >= 0; --i) {
- final ActivityStack current = getStackAt(i);
- if (windowingMode == current.getWindowingMode()) {
- return current;
- }
- }
- return null;
- }
-
- ActivityRecord topRunningActivity() {
- return topRunningActivity(false /* considerKeyguardState */);
- }
-
- /**
- * Returns the top running activity in the focused stack. In the case the focused stack has no
- * such activity, the next focusable stack on this display is returned.
- *
- * @param considerKeyguardState Indicates whether the locked state should be considered. if
- * {@code true} and the keyguard is locked, only activities that
- * can be shown on top of the keyguard will be considered.
- * @return The top running activity. {@code null} if none is available.
- */
- ActivityRecord topRunningActivity(boolean considerKeyguardState) {
- ActivityRecord topRunning = null;
- final ActivityStack focusedStack = getFocusedStack();
- if (focusedStack != null) {
- topRunning = focusedStack.topRunningActivityLocked();
- }
-
- // Look in other focusable stacks.
- if (topRunning == null) {
- for (int i = getStackCount() - 1; i >= 0; --i) {
- final ActivityStack stack = getStackAt(i);
- // Only consider focusable stacks other than the current focused one.
- if (stack == focusedStack || !stack.isFocusable()) {
- continue;
- }
- topRunning = stack.topRunningActivityLocked();
- if (topRunning != null) {
- break;
- }
- }
- }
-
- // This activity can be considered the top running activity if we are not considering
- // the locked state, the keyguard isn't locked, or we can show when locked.
- if (topRunning != null && considerKeyguardState
- && mRootActivityContainer.mStackSupervisor.getKeyguardController().isKeyguardLocked()
- && !topRunning.canShowWhenLocked()) {
- return null;
- }
-
- return topRunning;
- }
-
- boolean updateDisplayOverrideConfigurationLocked() {
- Configuration values = new Configuration();
- computeScreenConfiguration(values);
-
- mAtmService.mH.sendMessage(PooledLambda.obtainMessage(
- ActivityManagerInternal::updateOomLevelsForDisplay, mAtmService.mAmInternal,
- mDisplayId));
-
- Settings.System.clearConfiguration(values);
- updateDisplayOverrideConfigurationLocked(values, null /* starting */,
- false /* deferResume */, mAtmService.mTmpUpdateConfigurationResult);
- return mAtmService.mTmpUpdateConfigurationResult.changes != 0;
- }
-
- /**
- * Updates override configuration specific for the selected display. If no config is provided,
- * new one will be computed in WM based on current display info.
- */
- boolean updateDisplayOverrideConfigurationLocked(Configuration values,
- ActivityRecord starting, boolean deferResume,
- ActivityTaskManagerService.UpdateConfigurationResult result) {
-
- int changes = 0;
- boolean kept = true;
-
- mAtmService.deferWindowLayout();
- try {
- if (values != null) {
- if (mDisplayId == DEFAULT_DISPLAY) {
- // Override configuration of the default display duplicates global config, so
- // we're calling global config update instead for default display. It will also
- // apply the correct override config.
- changes = mAtmService.updateGlobalConfigurationLocked(values,
- false /* initLocale */, false /* persistent */,
- UserHandle.USER_NULL /* userId */, deferResume);
- } else {
- changes = performDisplayOverrideConfigUpdate(values, deferResume);
- }
- }
-
- kept = mAtmService.ensureConfigAndVisibilityAfterUpdate(starting, changes);
- } finally {
- mAtmService.continueWindowLayout();
- }
-
- if (result != null) {
- result.changes = changes;
- result.activityRelaunched = !kept;
- }
- return kept;
- }
-
- int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume) {
- mTempConfig.setTo(getRequestedOverrideConfiguration());
- final int changes = mTempConfig.updateFrom(values);
- if (changes != 0) {
- Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
- + mTempConfig + " for displayId=" + mDisplayId);
- onRequestedOverrideConfigurationChanged(mTempConfig);
-
- final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
- if (isDensityChange && mDisplayId == DEFAULT_DISPLAY) {
- mAtmService.mAppWarnings.onDensityChanged();
-
- // Post message to start process to avoid possible deadlock of calling into AMS with
- // the ATMS lock held.
- final Message msg = PooledLambda.obtainMessage(
- ActivityManagerInternal::killAllBackgroundProcessesExcept,
- mAtmService.mAmInternal, N,
- ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
- mAtmService.mH.sendMessage(msg);
- }
- mWmService.mDisplayNotificationController.dispatchDisplayChanged(
- this, getConfiguration());
- }
- return changes;
- }
-
- @Override
- public void onRequestedOverrideConfigurationChanged(Configuration overrideConfiguration) {
- final int currRotation =
- getRequestedOverrideConfiguration().windowConfiguration.getRotation();
- if (currRotation != ROTATION_UNDEFINED
- && currRotation != overrideConfiguration.windowConfiguration.getRotation()) {
- applyRotationLocked(currRotation,
- overrideConfiguration.windowConfiguration.getRotation());
- }
- super.onRequestedOverrideConfigurationChanged(overrideConfiguration);
- mWmService.setNewDisplayOverrideConfiguration(overrideConfiguration, this);
- mAtmService.addWindowLayoutReasons(
- ActivityTaskManagerService.LAYOUT_REASON_CONFIG_CHANGED);
- }
-
- @Override
- public void onConfigurationChanged(Configuration newParentConfig) {
- // update resources before cascade so that docked/pinned stacks use the correct info
- preOnConfigurationChanged();
- super.onConfigurationChanged(newParentConfig);
- }
-
- void onLockTaskPackagesUpdated() {
- for (int i = getStackCount() - 1; i >= 0; --i) {
- getStackAt(i).onLockTaskPackagesUpdated();
- }
- }
-
- /** Checks whether the given activity is in size compatibility mode and notifies the change. */
- void handleActivitySizeCompatModeIfNeeded(ActivityRecord r) {
- if (!r.isState(RESUMED) || r.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
- // The callback is only interested in the foreground changes of fullscreen activity.
- return;
- }
- if (!r.inSizeCompatMode()) {
- if (mLastCompatModeActivity != null) {
- mAtmService.getTaskChangeNotificationController()
- .notifySizeCompatModeActivityChanged(mDisplayId, null /* activityToken */);
- }
- mLastCompatModeActivity = null;
- return;
- }
- if (mLastCompatModeActivity == r) {
- return;
- }
- mLastCompatModeActivity = r;
- mAtmService.getTaskChangeNotificationController()
- .notifySizeCompatModeActivityChanged(mDisplayId, r.appToken);
- }
-
- @Override
- public String toString() {
- return "ActivityDisplay={" + mDisplayId + " numStacks=" + getStackCount() + "}";
- }
-
- boolean isPrivate() {
- return (mDisplay.getFlags() & FLAG_PRIVATE) != 0;
- }
-
- boolean isUidPresent(int uid) {
- final PooledPredicate p = PooledLambda.obtainPredicate(
- ActivityRecord::isUid, PooledLambda.__(ActivityRecord.class), uid);
- final boolean isUidPresent = mDisplayContent.getActivity(p) != null;
- p.recycle();
- return isUidPresent;
- }
-
- /**
- * @see #mRemoved
- */
- boolean isRemoved() {
- return mRemoved;
- }
-
- /**
- * @see #mRemoving
- */
- boolean isRemoving() {
- return mRemoving;
- }
-
- void remove() {
- mRemoving = true;
- final boolean destroyContentOnRemoval = shouldDestroyContentOnRemove();
- ActivityStack lastReparentedStack = null;
- mPreferredTopFocusableStack = null;
-
- // Stacks could be reparented from the removed display to other display. While
- // reparenting the last stack of the removed display, the remove display is ready to be
- // released (no more ActivityStack). But, we cannot release it at that moment or the
- // related WindowContainer will also be removed. So, we set display as removed after
- // reparenting stack finished.
- final ActivityDisplay toDisplay = mRootActivityContainer.getDefaultDisplay();
- mRootActivityContainer.mStackSupervisor.beginDeferResume();
- try {
- int numStacks = getStackCount();
- // Keep the order from bottom to top.
- for (int stackNdx = 0; stackNdx < numStacks; stackNdx++) {
- final ActivityStack stack = getStackAt(stackNdx);
- // Always finish non-standard type stacks.
- if (destroyContentOnRemoval || !stack.isActivityTypeStandardOrUndefined()) {
- stack.finishAllActivitiesImmediately();
- } else {
- // If default display is in split-window mode, set windowing mode of the stack
- // to split-screen secondary. Otherwise, set the windowing mode to undefined by
- // default to let stack inherited the windowing mode from the new display.
- final int windowingMode = toDisplay.hasSplitScreenPrimaryStack()
- ? WINDOWING_MODE_SPLIT_SCREEN_SECONDARY
- : WINDOWING_MODE_UNDEFINED;
- stack.reparent(toDisplay, true /* onTop */);
- stack.setWindowingMode(windowingMode);
- lastReparentedStack = stack;
- }
- // Stacks may be removed from this display. Ensure each stack will be processed and
- // the loop will end.
- stackNdx -= numStacks - getStackCount();
- numStacks = getStackCount();
- }
- } finally {
- mRootActivityContainer.mStackSupervisor.endDeferResume();
- }
- mRemoved = true;
-
- // Only update focus/visibility for the last one because there may be many stacks are
- // reparented and the intermediate states are unnecessary.
- if (lastReparentedStack != null) {
- lastReparentedStack.postReparent();
- }
- releaseSelfIfNeeded();
-
- if (!mAllSleepTokens.isEmpty()) {
- mRootActivityContainer.mSleepTokens.removeAll(mAllSleepTokens);
- mAllSleepTokens.clear();
- mAtmService.updateSleepIfNeededLocked();
- }
- }
-
- private void releaseSelfIfNeeded() {
- if (!mRemoved) {
- return;
- }
-
- final ActivityStack stack = getStackCount() == 1 ? getStackAt(0) : null;
- if (stack != null && stack.isActivityTypeHome() && stack.getAllTasks().isEmpty()) {
- // Release this display if an empty home stack is the only thing left.
- // Since it is the last stack, this display will be released along with the stack
- // removal.
- stack.removeIfPossible();
- } else if (getTopStack() == null) {
- removeIfPossible();
- mRootActivityContainer.removeChild(this);
- mRootActivityContainer.mStackSupervisor
- .getKeyguardController().onDisplayRemoved(mDisplayId);
- }
- }
-
- /** Update and get all UIDs that are present on the display and have access to it. */
- IntArray getPresentUIDs() {
- mDisplayAccessUIDs.clear();
- final PooledConsumer c = PooledLambda.obtainConsumer(ActivityDisplay::addActivityUid,
- PooledLambda.__(ActivityRecord.class), mDisplayAccessUIDs);
- mDisplayContent.forAllActivities(c);
- c.recycle();
- return mDisplayAccessUIDs;
- }
-
- private static void addActivityUid(ActivityRecord r, IntArray uids) {
- uids.add(r.getUid());
- }
-
- @VisibleForTesting
- boolean shouldDestroyContentOnRemove() {
- return mDisplay.getRemoveMode() == REMOVE_MODE_DESTROY_CONTENT;
- }
-
- boolean shouldSleep() {
- return (getStackCount() == 0 || !mAllSleepTokens.isEmpty())
- && (mAtmService.mRunningVoice == null);
- }
-
- void setFocusedApp(ActivityRecord r, boolean moveFocusNow) {
- final ActivityRecord newFocus;
- final IBinder token = r.appToken;
- if (token == null) {
- ProtoLog.v(WM_DEBUG_FOCUS_LIGHT, "Clearing focused app, displayId=%d",
- mDisplayId);
- newFocus = null;
- } else {
- newFocus = mWmService.mRoot.getActivityRecord(token);
- if (newFocus == null) {
- Slog.w(TAG_WM, "Attempted to set focus to non-existing app token: " + token
- + ", displayId=" + mDisplayId);
- }
- ProtoLog.v(WM_DEBUG_FOCUS_LIGHT,
- "Set focused app to: %s moveFocusNow=%b displayId=%d", newFocus,
- moveFocusNow, mDisplayId);
- }
-
- final boolean changed = setFocusedApp(newFocus);
- if (moveFocusNow && changed) {
- mWmService.updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL,
- true /*updateInputWindows*/);
- }
- }
-
- /**
- * @return the stack currently above the {@param stack}. Can be null if the {@param stack} is
- * already top-most.
- */
- ActivityStack getStackAbove(ActivityStack stack) {
- final int stackIndex = getIndexOf(stack) + 1;
- return (stackIndex < getStackCount()) ? getStackAt(stackIndex) : null;
- }
-
- /**
- * Adjusts the {@param stack} behind the last visible stack in the display if necessary.
- * Generally used in conjunction with {@link #moveStackBehindStack}.
- */
- void moveStackBehindBottomMostVisibleStack(ActivityStack stack) {
- if (stack.shouldBeVisible(null)) {
- // Skip if the stack is already visible
- return;
- }
-
- // Move the stack to the bottom to not affect the following visibility checks
- positionStackAtBottom(stack);
-
- // Find the next position where the stack should be placed
- final int numStacks = getStackCount();
- for (int stackNdx = 0; stackNdx < numStacks; stackNdx++) {
- final ActivityStack s = getStackAt(stackNdx);
- if (s == stack) {
- continue;
- }
- final int winMode = s.getWindowingMode();
- final boolean isValidWindowingMode = winMode == WINDOWING_MODE_FULLSCREEN ||
- winMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
- if (s.shouldBeVisible(null) && isValidWindowingMode) {
- // Move the provided stack to behind this stack
- positionStackAt(stack, Math.max(0, stackNdx - 1));
- break;
- }
- }
- }
-
- /**
- * Moves the {@param stack} behind the given {@param behindStack} if possible. If
- * {@param behindStack} is not currently in the display, then then the stack is moved to the
- * back. Generally used in conjunction with {@link #moveStackBehindBottomMostVisibleStack}.
- */
- void moveStackBehindStack(ActivityStack stack, ActivityStack behindStack) {
- if (behindStack == null || behindStack == stack) {
- return;
- }
-
- // Note that positionChildAt will first remove the given stack before inserting into the
- // list, so we need to adjust the insertion index to account for the removed index
- // TODO: Remove this logic when WindowContainer.positionChildAt() is updated to adjust the
- // position internally
- final int stackIndex = getIndexOf(stack);
- final int behindStackIndex = getIndexOf(behindStack);
- final int insertIndex = stackIndex <= behindStackIndex
- ? behindStackIndex - 1 : behindStackIndex;
- positionStackAt(stack, Math.max(0, insertIndex));
- }
-
- void ensureActivitiesVisible(ActivityRecord starting, int configChanges,
- boolean preserveWindows, boolean notifyClients) {
- for (int stackNdx = getStackCount() - 1; stackNdx >= 0; --stackNdx) {
- final ActivityStack stack = getStackAt(stackNdx);
- stack.ensureActivitiesVisible(starting, configChanges, preserveWindows,
- notifyClients);
- }
- }
-
- void moveHomeStackToFront(String reason) {
- final ActivityStack homeStack = getHomeStack();
- if (homeStack != null) {
- homeStack.moveToFront(reason);
- }
- }
-
- /**
- * Moves the focusable home activity to top. If there is no such activity, the home stack will
- * still move to top.
- */
- void moveHomeActivityToTop(String reason) {
- final ActivityRecord top = getHomeActivity();
- if (top == null) {
- moveHomeStackToFront(reason);
- return;
- }
- top.moveFocusableActivityToTop(reason);
- }
-
- @Nullable
- ActivityRecord getHomeActivity() {
- return getHomeActivityForUser(mRootActivityContainer.mCurrentUser);
- }
-
- @Nullable
- ActivityRecord getHomeActivityForUser(int userId) {
- final ActivityStack homeStack = getHomeStack();
- if (homeStack == null) {
- return null;
- }
-
- final PooledPredicate p = PooledLambda.obtainPredicate(
- ActivityDisplay::isHomeActivityForUser, PooledLambda.__(ActivityRecord.class),
- userId);
- final ActivityRecord r = homeStack.getActivity(p);
- p.recycle();
- return r;
- }
-
- private static boolean isHomeActivityForUser(ActivityRecord r, int userId) {
- return r.isActivityTypeHome() && (userId == UserHandle.USER_ALL || r.mUserId == userId);
- }
-
- boolean isSleeping() {
- return mSleeping;
- }
-
- void setIsSleeping(boolean asleep) {
- mSleeping = asleep;
- }
-
- /**
- * Adds a listener to be notified whenever the stack order in the display changes. Currently
- * only used by the {@link RecentsAnimation} to determine whether to interrupt and cancel the
- * current animation when the system state changes.
- */
- void registerStackOrderChangedListener(OnStackOrderChangedListener listener) {
- if (!mStackOrderChangedCallbacks.contains(listener)) {
- mStackOrderChangedCallbacks.add(listener);
- }
- }
-
- /**
- * Removes a previously registered stack order change listener.
- */
- void unregisterStackOrderChangedListener(OnStackOrderChangedListener listener) {
- mStackOrderChangedCallbacks.remove(listener);
- }
-
- /**
- * Notifies of a stack order change
- * @param stack The stack which triggered the order change
- */
- private void onStackOrderChanged(ActivityStack stack) {
- for (int i = mStackOrderChangedCallbacks.size() - 1; i >= 0; i--) {
- mStackOrderChangedCallbacks.get(i).onStackOrderChanged(stack);
- }
- }
-
- void setDisplayToSingleTaskInstance() {
- final int childCount = getStackCount();
- if (childCount > 1) {
- throw new IllegalArgumentException("Display already has multiple stacks. display="
- + this);
- }
- if (childCount > 0) {
- final ActivityStack stack = getStackAt(0);
- if (stack.getChildCount() > 1) {
- throw new IllegalArgumentException("Display stack already has multiple tasks."
- + " display=" + this + " stack=" + stack);
- }
- }
-
- mSingleTaskInstance = true;
- }
-
- /** Returns true if the display can only contain one task */
- boolean isSingleTaskInstance() {
- return mSingleTaskInstance;
- }
-
- @VisibleForTesting
- void removeAllTasks() {
- for (int i = getStackCount() - 1; i >= 0; --i) {
- final ActivityStack stack = getStackAt(i);
- final ArrayList<Task> tasks = stack.getAllTasks();
- for (int j = tasks.size() - 1; j >= 0; --j) {
- stack.removeChild(tasks.get(j), "removeAllTasks");
- }
- }
- }
-
- public void dump(PrintWriter pw, String prefix) {
- pw.println(prefix + "displayId=" + mDisplayId + " stacks=" + getStackCount()
- + (mSingleTaskInstance ? " mSingleTaskInstance" : ""));
- final String myPrefix = prefix + " ";
- ActivityStack stack = getHomeStack();
- if (stack != null) {
- pw.println(myPrefix + "mHomeStack=" + stack);
- }
- stack = getRecentsStack();
- if (stack != null) {
- pw.println(myPrefix + "mRecentsStack=" + stack);
- }
- stack = getPinnedStack();
- if (stack != null) {
- pw.println(myPrefix + "mPinnedStack=" + stack);
- }
- stack = getSplitScreenPrimaryStack();
- if (stack != null) {
- pw.println(myPrefix + "mSplitScreenPrimaryStack=" + stack);
- }
- if (mPreferredTopFocusableStack != null) {
- pw.println(myPrefix + "mPreferredTopFocusableStack=" + mPreferredTopFocusableStack);
- }
- if (mLastFocusedStack != null) {
- pw.println(myPrefix + "mLastFocusedStack=" + mLastFocusedStack);
- }
- }
-
- public void dumpStacks(PrintWriter pw) {
- for (int i = getStackCount() - 1; i >= 0; --i) {
- pw.print(getStackAt(i).mStackId);
- if (i > 0) {
- pw.print(",");
- }
- }
- }
-
- public void dumpDebug(ProtoOutputStream proto, long fieldId,
- @WindowTraceLogLevel int logLevel) {
- final long token = proto.start(fieldId);
- dumpDebugInner(proto, DISPLAY, logLevel);
- proto.write(ID, mDisplayId);
- proto.write(SINGLE_TASK_INSTANCE, mSingleTaskInstance);
- final ActivityStack focusedStack = getFocusedStack();
- if (focusedStack != null) {
- proto.write(FOCUSED_STACK_ID, focusedStack.mStackId);
- final ActivityRecord focusedActivity = focusedStack.getDisplay().getResumedActivity();
- if (focusedActivity != null) {
- focusedActivity.writeIdentifierToProto(proto, RESUMED_ACTIVITY);
- }
- } else {
- proto.write(FOCUSED_STACK_ID, INVALID_STACK_ID);
- }
- for (int stackNdx = getStackCount() - 1; stackNdx >= 0; --stackNdx) {
- final ActivityStack stack = getStackAt(stackNdx);
- stack.dumpDebug(proto, STACKS, logLevel);
- }
- proto.end(token);
- }
-
- /**
- * Callback for when the order of the stacks in the display changes.
- */
- interface OnStackOrderChangedListener {
- void onStackOrderChanged(ActivityStack stack);
- }
-}
diff --git a/services/core/java/com/android/server/wm/ActivityMetricsLogger.java b/services/core/java/com/android/server/wm/ActivityMetricsLogger.java
index 20d1d1c1cf67..c8357e29d9c1 100644
--- a/services/core/java/com/android/server/wm/ActivityMetricsLogger.java
+++ b/services/core/java/com/android/server/wm/ActivityMetricsLogger.java
@@ -190,6 +190,8 @@ class ActivityMetricsLogger {
final int mTransitionType;
/** Whether the process was already running when the transition started. */
final boolean mProcessRunning;
+ /** whether the process of the launching activity didn't have any active activity. */
+ final boolean mProcessSwitch;
/** The activities that should be drawn. */
final LinkedList<ActivityRecord> mPendingDrawActivities = new LinkedList<>();
/** The latest activity to have been launched. */
@@ -218,7 +220,8 @@ class ActivityMetricsLogger {
/** @return Non-null if there will be a window drawn event for the launch. */
@Nullable
static TransitionInfo create(@NonNull ActivityRecord r,
- @NonNull LaunchingState launchingState, boolean processRunning, int startResult) {
+ @NonNull LaunchingState launchingState, boolean processRunning,
+ boolean processSwitch, int startResult) {
int transitionType = INVALID_TRANSITION_TYPE;
if (processRunning) {
if (startResult == START_SUCCESS) {
@@ -235,16 +238,18 @@ class ActivityMetricsLogger {
// That means the startResult is neither START_SUCCESS nor START_TASK_TO_FRONT.
return null;
}
- return new TransitionInfo(r, launchingState, transitionType, processRunning);
+ return new TransitionInfo(r, launchingState, transitionType, processRunning,
+ processSwitch);
}
/** Use {@link TransitionInfo#create} instead to ensure the transition type is valid. */
private TransitionInfo(ActivityRecord r, LaunchingState launchingState, int transitionType,
- boolean processRunning) {
+ boolean processRunning, boolean processSwitch) {
mLaunchingState = launchingState;
mTransitionStartTimeNs = launchingState.mCurrentTransitionStartTimeNs;
mTransitionType = transitionType;
mProcessRunning = processRunning;
+ mProcessSwitch = processSwitch;
mCurrentTransitionDeviceUptime =
(int) TimeUnit.MILLISECONDS.toSeconds(SystemClock.uptimeMillis());
setLatestLaunchedActivity(r);
@@ -282,6 +287,14 @@ class ActivityMetricsLogger {
return mPendingDrawActivities.isEmpty();
}
+ /**
+ * @return {@code true} if the transition info should be sent to MetricsLogger, StatsLog, or
+ * LaunchObserver.
+ */
+ boolean isInterestingToLoggerAndObserver() {
+ return mProcessSwitch;
+ }
+
int calculateCurrentDelay() {
return calculateDelay(SystemClock.elapsedRealtimeNanos());
}
@@ -540,13 +553,8 @@ class ActivityMetricsLogger {
return;
}
- if (!processSwitch) {
- abort(info, "not a process switch");
- return;
- }
-
final TransitionInfo newInfo = TransitionInfo.create(launchedActivity, launchingState,
- processRunning, resultCode);
+ processRunning, processSwitch, resultCode);
if (newInfo == null) {
abort(info, "unrecognized launch");
return;
@@ -557,7 +565,12 @@ class ActivityMetricsLogger {
mTransitionInfoList.add(newInfo);
mLastTransitionInfo.put(launchedActivity, newInfo);
startLaunchTrace(newInfo);
- launchObserverNotifyActivityLaunched(newInfo);
+ if (newInfo.isInterestingToLoggerAndObserver()) {
+ launchObserverNotifyActivityLaunched(newInfo);
+ } else {
+ // As abort for no process switch.
+ launchObserverNotifyIntentFailed();
+ }
}
/**
@@ -733,7 +746,9 @@ class ActivityMetricsLogger {
launchObserverNotifyActivityLaunchCancelled(info);
} else {
logAppTransitionFinished(info);
- launchObserverNotifyActivityLaunchFinished(info, timestampNs);
+ if (info.isInterestingToLoggerAndObserver()) {
+ launchObserverNotifyActivityLaunchFinished(info, timestampNs);
+ }
}
info.mPendingDrawActivities.clear();
mTransitionInfoList.remove(info);
@@ -768,8 +783,11 @@ class ActivityMetricsLogger {
// Take a snapshot of the transition info before sending it to the handler for logging.
// This will avoid any races with other operations that modify the ActivityRecord.
final TransitionInfoSnapshot infoSnapshot = new TransitionInfoSnapshot(info);
- BackgroundThread.getHandler().post(() -> logAppTransition(
- info.mCurrentTransitionDeviceUptime, info.mCurrentTransitionDelayMs, infoSnapshot));
+ if (info.isInterestingToLoggerAndObserver()) {
+ BackgroundThread.getHandler().post(() -> logAppTransition(
+ info.mCurrentTransitionDeviceUptime, info.mCurrentTransitionDelayMs,
+ infoSnapshot));
+ }
BackgroundThread.getHandler().post(() -> logAppDisplayed(infoSnapshot));
if (info.mPendingFullyDrawn != null) {
info.mPendingFullyDrawn.run();
@@ -905,6 +923,18 @@ class ActivityMetricsLogger {
return null;
}
+ final long currentTimestampNs = SystemClock.elapsedRealtimeNanos();
+ final long startupTimeMs = info.mPendingFullyDrawn != null
+ ? info.mWindowsDrawnDelayMs
+ : TimeUnit.NANOSECONDS.toMillis(currentTimestampNs - info.mTransitionStartTimeNs);
+ final TransitionInfoSnapshot infoSnapshot =
+ new TransitionInfoSnapshot(info, r, (int) startupTimeMs);
+ BackgroundThread.getHandler().post(() -> logAppFullyDrawn(infoSnapshot));
+
+ if (!info.isInterestingToLoggerAndObserver()) {
+ return infoSnapshot;
+ }
+
// Record the handling of the reportFullyDrawn callback in the trace system. This is not
// actually used to trace this function, but instead the logical task that this function
// fullfils (handling reportFullyDrawn() callbacks).
@@ -914,10 +944,6 @@ class ActivityMetricsLogger {
final LogMaker builder = new LogMaker(APP_TRANSITION_REPORTED_DRAWN);
builder.setPackageName(r.packageName);
builder.addTaggedData(FIELD_CLASS_NAME, r.info.name);
- final long currentTimestampNs = SystemClock.elapsedRealtimeNanos();
- final long startupTimeMs = info.mPendingFullyDrawn != null
- ? info.mWindowsDrawnDelayMs
- : TimeUnit.NANOSECONDS.toMillis(currentTimestampNs - info.mTransitionStartTimeNs);
builder.addTaggedData(APP_TRANSITION_REPORTED_DRAWN_MS, startupTimeMs);
builder.setType(restoredFromBundle
? TYPE_TRANSITION_REPORTED_DRAWN_WITH_BUNDLE
@@ -940,10 +966,6 @@ class ActivityMetricsLogger {
// the trace slice to have a noticable duration.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
- final TransitionInfoSnapshot infoSnapshot =
- new TransitionInfoSnapshot(info, r, (int) startupTimeMs);
- BackgroundThread.getHandler().post(() -> logAppFullyDrawn(infoSnapshot));
-
// Notify reportFullyDrawn event.
launchObserverNotifyReportFullyDrawn(r, currentTimestampNs);
@@ -1069,7 +1091,8 @@ class ActivityMetricsLogger {
return;
}
info.mLaunchTraceName = "launching: " + info.mLastLaunchedActivity.packageName;
- Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, info.mLaunchTraceName, 0);
+ Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, info.mLaunchTraceName,
+ (int) info.mTransitionStartTimeNs /* cookie */);
}
/** Stops trace for the launch is completed or cancelled. */
@@ -1078,7 +1101,8 @@ class ActivityMetricsLogger {
if (info.mLaunchTraceName == null) {
return;
}
- Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, info.mLaunchTraceName, 0);
+ Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, info.mLaunchTraceName,
+ (int) info.mTransitionStartTimeNs /* cookie */);
info.mLaunchTraceName = null;
}
diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java
index 83c854bae4b5..bfc626828fa0 100644
--- a/services/core/java/com/android/server/wm/ActivityRecord.java
+++ b/services/core/java/com/android/server/wm/ActivityRecord.java
@@ -547,7 +547,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
private final WindowState.UpdateReportedVisibilityResults mReportedVisibilityResults =
new WindowState.UpdateReportedVisibilityResults();
- private boolean mUseTransferredAnimation;
+ boolean mUseTransferredAnimation;
/**
* @see #currentLaunchCanTurnScreenOn()
@@ -1640,6 +1640,17 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
allowTaskSnapshot, activityCreated, fromRecents, snapshot);
if (type == STARTING_WINDOW_TYPE_SNAPSHOT) {
+ if (isActivityTypeHome()) {
+ // The snapshot of home is only used once because it won't be updated while screen
+ // is on (see {@link TaskSnapshotController#screenTurningOff}).
+ mWmService.mTaskSnapshotController.removeSnapshotCache(task.mTaskId);
+ // TODO(b/9684093): Use more general condition to specify the case.
+ if (mDisplayContent.mAppTransition
+ .getAppTransition() != WindowManager.TRANSIT_KEYGUARD_GOING_AWAY) {
+ // Only use snapshot of home as starting window when unlocking.
+ return false;
+ }
+ }
return createSnapshot(snapshot);
}
@@ -1800,12 +1811,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
} else if (newTask || !processRunning || (taskSwitch && !activityCreated)) {
return STARTING_WINDOW_TYPE_SPLASH_SCREEN;
} else if (taskSwitch && allowTaskSnapshot) {
- if (mWmService.mLowRamTaskSnapshotsAndRecents) {
- // For low RAM devices, we use the splash screen starting window instead of the
- // task snapshot starting window.
- return STARTING_WINDOW_TYPE_SPLASH_SCREEN;
- }
- return snapshot == null ? STARTING_WINDOW_TYPE_NONE
+ return snapshot == null ? STARTING_WINDOW_TYPE_SPLASH_SCREEN
: snapshotOrientationSameAsTask(snapshot) || fromRecents
? STARTING_WINDOW_TYPE_SNAPSHOT : STARTING_WINDOW_TYPE_SPLASH_SCREEN;
} else {
@@ -1996,7 +2002,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
return getActivityStack() != null ? getActivityStack().mStackId : INVALID_STACK_ID;
}
- ActivityDisplay getDisplay() {
+ DisplayContent getDisplay() {
final ActivityStack stack = getActivityStack();
return stack != null ? stack.getDisplay() : null;
}
@@ -2153,7 +2159,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
boolean isKeyguardLocked = mAtmService.isKeyguardLocked();
boolean isCurrentAppLocked =
mAtmService.getLockTaskModeState() != LOCK_TASK_MODE_NONE;
- final ActivityDisplay display = getDisplay();
+ final DisplayContent display = getDisplay();
boolean hasPinnedStack = display != null && display.hasPinnedStack();
// Don't return early if !isNotLocked, since we want to throw an exception if the activity
// is in an incorrect state
@@ -2190,7 +2196,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
}
/**
- * Sets if this AWT is in the process of closing or entering PIP.
+ * Sets if this {@link ActivityRecord} is in the process of closing or entering PIP.
* {@link #mWillCloseOrEnterPip}}
*/
void setWillCloseOrEnterPip(boolean willCloseOrEnterPip) {
@@ -2198,7 +2204,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
}
/**
- * Returns whether this AWT is considered closing. Conditions are either
+ * Returns whether this {@link ActivityRecord} is considered closing. Conditions are either
* 1. Is this app animating and was requested to be hidden
* 2. App is delayed closing since it might enter PIP.
*/
@@ -2217,11 +2223,15 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
return (info.flags & FLAG_ALWAYS_FOCUSABLE) != 0;
}
+ boolean windowsAreFocusable() {
+ return windowsAreFocusable(false /* fromUserTouch */);
+ }
+
// TODO: Does this really need to be different from isAlwaysFocusable()? For the activity side
// focusable means resumeable. I guess with that in mind maybe we should rename the other
// method to isResumeable() or something like that.
- boolean windowsAreFocusable() {
- if (mTargetSdk < Build.VERSION_CODES.Q) {
+ boolean windowsAreFocusable(boolean fromUserTouch) {
+ if (!fromUserTouch && mTargetSdk < Build.VERSION_CODES.Q) {
final int pid = getPid();
final ActivityRecord topFocusedAppOfMyProcess =
mWmService.mRoot.mTopFocusedAppByProcess.get(pid);
@@ -2235,7 +2245,12 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
&& getDisplay() != null;
}
- /** Move activity with its stack to front and make the stack focused. */
+ /**
+ * Move activity with its stack to front and make the stack focused.
+ * @param reason the reason to move to top
+ * @return {@code true} if the stack is focusable and has been moved to top or the activity
+ * is not yet resumed while the stack is already on top, {@code false} otherwise.
+ */
boolean moveFocusableActivityToTop(String reason) {
if (!isFocusable()) {
if (DEBUG_FOCUS) {
@@ -2256,7 +2271,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
if (DEBUG_FOCUS) {
Slog.d(TAG_FOCUS, "moveActivityStackToFront: already on top, activity=" + this);
}
- return false;
+ return !isState(RESUMED);
}
if (DEBUG_FOCUS) {
@@ -2406,14 +2421,14 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
// We are finishing the top focused activity and its stack has nothing to be focused so
// the next focusable stack should be focused.
if (mayAdjustTop
- && (stack.topRunningActivityLocked() == null || !stack.isFocusable())) {
+ && (stack.topRunningActivity() == null || !stack.isFocusable())) {
if (shouldAdjustGlobalFocus) {
// Move the entire hierarchy to top with updating global top resumed activity
// and focused application if needed.
stack.adjustFocusToNextFocusableStack("finish-top");
} else {
// Only move the next stack to top in its display.
- final ActivityDisplay display = stack.getDisplay();
+ final DisplayContent display = stack.getDisplay();
next = display.topRunningActivity();
if (next != null) {
display.positionStackAtTop(next.getActivityStack(),
@@ -2587,9 +2602,9 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
mStackSupervisor.mGoingToSleepActivities.remove(this);
final ActivityStack stack = getActivityStack();
- final ActivityDisplay display = getDisplay();
+ final DisplayContent display = getDisplay();
// TODO(b/137329632): Exclude current activity when looking for the next one with
- // ActivityDisplay#topRunningActivity().
+ // DisplayContent#topRunningActivity().
final ActivityRecord next = display.topRunningActivity();
final boolean isLastStackOverEmptyHome =
next == null && stack.isFocusedStackOnDisplay() && display.getHomeStack() != null;
@@ -3000,7 +3015,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
ProtoLog.v(WM_DEBUG_APP_TRANSITIONS, "Removing app token: %s", this);
- boolean delayed = commitVisibility(null, false, TRANSIT_UNSET, true, mVoiceInteraction);
+ commitVisibility(false /* visible */, true /* performLayout */);
getDisplayContent().mOpeningApps.remove(this);
getDisplayContent().mChangingApps.remove(this);
@@ -3008,6 +3023,8 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
mWmService.mTaskSnapshotController.onAppRemoved(this);
mStackSupervisor.getActivityMetricsLogger().notifyActivityRemoved(this);
waitingToShow = false;
+
+ boolean delayed = isAnimating(TRANSITION | CHILDREN);
if (getDisplayContent().mClosingApps.contains(this)) {
delayed = true;
} else if (getDisplayContent().mAppTransition.isTransitionSet()) {
@@ -3152,16 +3169,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
updateLetterboxSurface(child);
}
- private boolean waitingForReplacement() {
- for (int i = mChildren.size() - 1; i >= 0; i--) {
- final WindowState candidate = mChildren.get(i);
- if (candidate.waitingForReplacement()) {
- return true;
- }
- }
- return false;
- }
-
void onWindowReplacementTimeout() {
for (int i = mChildren.size() - 1; i >= 0; --i) {
(mChildren.get(i)).onWindowReplacementTimeout();
@@ -3417,7 +3424,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
// before the non-exiting app tokens. So, we skip the exiting app tokens here.
// TODO: Investigate if we need to continue to do this or if we can just process them
// in-order.
- if (mIsExiting && !waitingForReplacement()) {
+ if (mIsExiting && !forAllWindowsUnchecked(WindowState::waitingForReplacement, true)) {
return false;
}
return forAllWindowsUnchecked(callback, traverseTopToBottom);
@@ -3440,7 +3447,8 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
}
@Override
- ActivityRecord getActivity(Predicate<ActivityRecord> callback, boolean traverseTopToBottom) {
+ ActivityRecord getActivity(Predicate<ActivityRecord> callback, boolean traverseTopToBottom,
+ WindowContainer boundary) {
return callback.test(this) ? this : null;
}
@@ -3861,6 +3869,17 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
}
}
+ /**
+ * Set visibility on this {@link ActivityRecord}
+ *
+ * <p class="note"><strong>Note: </strong>This function might not update the visibility of
+ * this {@link ActivityRecord} immediately. In case we are preparing an app transition, we
+ * delay changing the visibility of this {@link ActivityRecord} until we execute that
+ * transition.</p>
+ *
+ * @param visible {@code true} if the {@link ActivityRecord} should become visible, otherwise
+ * this should become invisible.
+ */
void setVisibility(boolean visible) {
if (getParent() == null) {
Slog.w(TAG_WM, "Attempted to set visibility of non-existing app token: "
@@ -3997,153 +4016,169 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
return;
}
- commitVisibility(null, visible, TRANSIT_UNSET, true, mVoiceInteraction);
+ commitVisibility(visible, true /* performLayout */);
updateReportedVisibilityLocked();
}
- boolean commitVisibility(WindowManager.LayoutParams lp,
- boolean visible, int transit, boolean performLayout, boolean isVoiceInteraction) {
+ @Override
+ boolean applyAnimation(WindowManager.LayoutParams lp, int transit, boolean enter,
+ boolean isVoiceInteraction) {
+ if (mUseTransferredAnimation) {
+ return false;
+ }
+ return super.applyAnimation(lp, transit, enter, isVoiceInteraction);
+ }
- boolean delayed = false;
- // Reset the state of mVisibleSetFromTransferredStartingWindow since visibility is actually
+ /**
+ * Update visibility to this {@link ActivityRecord}.
+ *
+ * <p class="note"><strong>Note: </strong> Unlike {@link #setVisibility}, this immediately
+ * updates the visibility without starting an app transition. Since this function may start
+ * animation on {@link WindowState} depending on app transition animation status, an app
+ * transition animation must be started before calling this function if necessary.</p>
+ *
+ * @param visible {@code true} if this {@link ActivityRecord} should become visible, otherwise
+ * this should become invisible.
+ * @param performLayout if {@code true}, perform surface placement after committing visibility.
+ */
+ void commitVisibility(boolean visible, boolean performLayout) {
+ // Reset the state of mHiddenSetFromTransferredStartingWindow since visibility is actually
// been set by the app now.
mVisibleSetFromTransferredStartingWindow = false;
+ if (visible == isVisible()) {
+ return;
+ }
- // Allow for state changes and animation to be applied if:
- // * token is transitioning visibility state
- // * or the token was marked as hidden and is exiting before we had a chance to play the
- // transition animation
- // * or this is an opening app and windows are being replaced
- // * or the token is the opening app and visible while opening task behind existing one.
- final DisplayContent displayContent = getDisplayContent();
- boolean visibilityChanged = false;
- if (isVisible() != visible || (!isVisible() && mIsExiting)
- || (visible && waitingForReplacement())
- || (visible && displayContent.mOpeningApps.contains(this)
- && displayContent.mAppTransition.getAppTransition() == TRANSIT_TASK_OPEN_BEHIND)) {
- final AccessibilityController accessibilityController =
- mWmService.mAccessibilityController;
- boolean changed = false;
- ProtoLog.v(WM_DEBUG_APP_TRANSITIONS,
- "Changing app %s visible=%b performLayout=%b", this, isVisible(),
- performLayout);
-
- boolean runningAppAnimation = false;
-
- if (transit != WindowManager.TRANSIT_UNSET) {
- if (mUseTransferredAnimation) {
- runningAppAnimation = isAnimating();
- } else if (applyAnimation(lp, transit, visible, isVoiceInteraction)) {
- runningAppAnimation = true;
- }
- delayed = runningAppAnimation;
- final WindowState window = findMainWindow();
- if (window != null && accessibilityController != null) {
- accessibilityController.onAppWindowTransitionLocked(window, transit);
- }
- changed = true;
- }
-
- final int windowsCount = mChildren.size();
- for (int i = 0; i < windowsCount; i++) {
- final WindowState win = mChildren.get(i);
- changed |= win.onAppVisibilityChanged(visible, runningAppAnimation);
- }
-
- setVisible(visible);
- mVisibleRequested = visible;
- visibilityChanged = true;
- if (!visible) {
- stopFreezingScreen(true, true);
- } else {
- // If we are being set visible, and the starting window is not yet displayed,
- // then make sure it doesn't get displayed.
- if (startingWindow != null && !startingWindow.isDrawnLw()) {
- startingWindow.clearPolicyVisibilityFlag(LEGACY_POLICY_VISIBILITY);
- startingWindow.mLegacyPolicyVisibilityAfterAnim = false;
- }
-
- // We are becoming visible, so better freeze the screen with the windows that are
- // getting visible so we also wait for them.
- forAllWindows(mWmService::makeWindowFreezingScreenIfNeededLocked, true);
- }
-
- ProtoLog.v(WM_DEBUG_APP_TRANSITIONS,
- "commitVisibility: %s: visible=%b visibleRequested=%b", this,
- isVisible(), mVisibleRequested);
-
- if (changed) {
- displayContent.getInputMonitor().setUpdateInputWindowsNeededLw();
- if (performLayout) {
- mWmService.updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES,
- false /*updateInputWindows*/);
- mWmService.mWindowPlacerLocked.performSurfacePlacement();
- }
- displayContent.getInputMonitor().updateInputWindowsLw(false /*force*/);
+ final int windowsCount = mChildren.size();
+ for (int i = 0; i < windowsCount; i++) {
+ mChildren.get(i).onAppVisibilityChanged(visible, isAnimating(PARENTS));
+ }
+ setVisible(visible);
+ mVisibleRequested = visible;
+ if (!visible) {
+ stopFreezingScreen(true, true);
+ } else {
+ // If we are being set visible, and the starting window is not yet displayed,
+ // then make sure it doesn't get displayed.
+ if (startingWindow != null && !startingWindow.isDrawnLw()) {
+ startingWindow.clearPolicyVisibilityFlag(LEGACY_POLICY_VISIBILITY);
+ startingWindow.mLegacyPolicyVisibilityAfterAnim = false;
}
+ // We are becoming visible, so better freeze the screen with the windows that are
+ // getting visible so we also wait for them.
+ forAllWindows(mWmService::makeWindowFreezingScreenIfNeededLocked, true);
+ }
+ ProtoLog.v(WM_DEBUG_APP_TRANSITIONS,
+ "commitVisibility: %s: visible=%b mVisibleRequested=%b", this,
+ isVisible(), mVisibleRequested);
+ final DisplayContent displayContent = getDisplayContent();
+ displayContent.getInputMonitor().setUpdateInputWindowsNeededLw();
+ if (performLayout) {
+ mWmService.updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES,
+ false /*updateInputWindows*/);
+ mWmService.mWindowPlacerLocked.performSurfacePlacement();
}
+ displayContent.getInputMonitor().updateInputWindowsLw(false /*force*/);
mUseTransferredAnimation = false;
- delayed = isAnimating(CHILDREN);
+ postApplyAnimation(visible);
+ }
+
+ /**
+ * Post process after applying an app transition animation.
+ *
+ * <p class="note"><strong>Note: </strong> This function must be called after the animations
+ * have been applied and {@link #commitVisibility}.</p>
+ *
+ * @param visible {@code true} if this {@link ActivityRecord} has become visible, otherwise
+ * this has become invisible.
+ */
+ private void postApplyAnimation(boolean visible) {
+ final boolean delayed = isAnimating(PARENTS | CHILDREN);
if (!delayed) {
- // We aren't animating anything, but exiting windows rely on the animation finished
- // callback being called in case the ActivityRecord was pretending to be animating,
+ // We aren't delayed anything, but exiting windows rely on the animation finished
+ // callback being called in case the ActivityRecord was pretending to be delayed,
// which we might have done because we were in closing/opening apps list.
onAnimationFinished();
- }
-
- if (visibilityChanged) {
- if (visible && !delayed) {
+ if (visible) {
// The token was made immediately visible, there will be no entrance animation.
// We need to inform the client the enter animation was finished.
mEnteringAnimation = true;
mWmService.mActivityManagerAppTransitionNotifier.onAppTransitionFinishedLocked(
token);
}
+ }
- // If we're becoming visible, immediately change client visibility as well. there seem
- // to be some edge cases where we change our visibility but client visibility never gets
- // updated.
- // If we're becoming invisible, update the client visibility if we are not running an
- // animation. Otherwise, we'll update client visibility in onAnimationFinished.
- if (visible || !isAnimating()) {
- setClientVisible(visible);
- }
-
- if (!displayContent.mClosingApps.contains(this)
- && !displayContent.mOpeningApps.contains(this)) {
- // The token is not closing nor opening, so even if there is an animation set, that
- // doesn't mean that it goes through the normal app transition cycle so we have
- // to inform the docked controller about visibility change.
- // TODO(multi-display): notify docked divider on all displays where visibility was
- // affected.
- displayContent.getDockedDividerController().notifyAppVisibilityChanged();
-
- // Take the screenshot before possibly hiding the WSA, otherwise the screenshot
- // will not be taken.
- mWmService.mTaskSnapshotController.notifyAppVisibilityChanged(this, visible);
- }
-
- // If we are hidden but there is no delay needed we immediately
- // apply the Surface transaction so that the ActivityManager
- // can have some guarantee on the Surface state following
- // setting the visibility. This captures cases like dismissing
- // the docked or pinned stack where there is no app transition.
- //
- // In the case of a "Null" animation, there will be
- // no animation but there will still be a transition set.
- // We still need to delay hiding the surface such that it
- // can be synchronized with showing the next surface in the transition.
- if (!isVisible() && !delayed && !displayContent.mAppTransition.isTransitionSet()) {
- SurfaceControl.openTransaction();
- for (int i = mChildren.size() - 1; i >= 0; i--) {
- mChildren.get(i).mWinAnimator.hide("immediately hidden");
- }
+ // If we're becoming visible, immediately change client visibility as well. there seem
+ // to be some edge cases where we change our visibility but client visibility never gets
+ // updated.
+ // If we're becoming invisible, update the client visibility if we are not running an
+ // animation. Otherwise, we'll update client visibility in onAnimationFinished.
+ if (visible || !isAnimating(PARENTS)) {
+ setClientVisible(visible);
+ }
+
+ final DisplayContent displayContent = getDisplayContent();
+ if (!displayContent.mClosingApps.contains(this)
+ && !displayContent.mOpeningApps.contains(this)) {
+ // The token is not closing nor opening, so even if there is an animation set, that
+ // doesn't mean that it goes through the normal app transition cycle so we have
+ // to inform the docked controller about visibility change.
+ // TODO(multi-display): notify docked divider on all displays where visibility was
+ // affected.
+ displayContent.getDockedDividerController().notifyAppVisibilityChanged();
+
+ // Take the screenshot before possibly hiding the WSA, otherwise the screenshot
+ // will not be taken.
+ mWmService.mTaskSnapshotController.notifyAppVisibilityChanged(this, visible);
+ }
+
+ // If we are hidden but there is no delay needed we immediately
+ // apply the Surface transaction so that the ActivityManager
+ // can have some guarantee on the Surface state following
+ // setting the visibility. This captures cases like dismissing
+ // the docked or pinned stack where there is no app transition.
+ //
+ // In the case of a "Null" animation, there will be
+ // no animation but there will still be a transition set.
+ // We still need to delay hiding the surface such that it
+ // can be synchronized with showing the next surface in the transition.
+ if (!isVisible() && !delayed && !displayContent.mAppTransition.isTransitionSet()) {
+ SurfaceControl.openTransaction();
+ try {
+ forAllWindows(win -> {
+ win.mWinAnimator.hide("immediately hidden"); }, true);
+ } finally {
SurfaceControl.closeTransaction();
}
}
+ }
- return delayed;
+ /**
+ * Check if visibility of this {@link ActivityRecord} should be updated as part of an app
+ * transition.
+ *
+ * <p class="note><strong>Note:</strong> If the visibility of this {@link ActivityRecord} is
+ * already set to {@link #visible}, we don't need to update the visibility. So {@code false} is
+ * returned.</p>
+ *
+ * @param visible {@code true} if this {@link ActivityRecord} should become visible,
+ * {@code false} if this should become invisible.
+ * @return {@code true} if visibility of this {@link ActivityRecord} should be updated, and
+ * an app transition animation should be run.
+ */
+ boolean shouldApplyAnimation(boolean visible) {
+ // Allow for state update and animation to be applied if:
+ // * token is transitioning visibility state
+ // * or the token was marked as hidden and is exiting before we had a chance to play the
+ // transition animation
+ // * or this is an opening app and windows are being replaced
+ // * or the token is the opening app and visible while opening task behind existing one.
+ final DisplayContent displayContent = getDisplayContent();
+ return isVisible() != visible || (!isVisible() && mIsExiting)
+ || (visible && forAllWindows(WindowState::waitingForReplacement, true))
+ || (visible && displayContent.mOpeningApps.contains(this)
+ && displayContent.mAppTransition.getAppTransition() == TRANSIT_TASK_OPEN_BEHIND);
}
/**
@@ -4636,7 +4671,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
}
r.setSavedState(null /* savedState */);
- final ActivityDisplay display = r.getDisplay();
+ final DisplayContent display = r.getDisplay();
if (display != null) {
display.handleActivitySizeCompatModeIfNeeded(r);
}
@@ -5541,12 +5576,12 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
/**
* @return The to top most child window for which {@link LayoutParams#isFullscreen()} returns
- * true.
+ * true and isn't fully transparent.
*/
- WindowState getTopFullscreenWindow() {
+ WindowState getTopFullscreenOpaqueWindow() {
for (int i = mChildren.size() - 1; i >= 0; i--) {
final WindowState win = mChildren.get(i);
- if (win != null && win.mAttrs.isFullscreen()) {
+ if (win != null && win.mAttrs.isFullscreen() && !win.isFullyTransparent()) {
return win;
}
}
@@ -5634,19 +5669,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
return task != null ? task.isChangingAppTransition() : super.isChangingAppTransition();
}
- @Override
- boolean applyAnimation(WindowManager.LayoutParams lp, int transit, boolean enter,
- boolean isVoiceInteraction) {
- if (mWmService.mDisableTransitionAnimation || !shouldAnimate(transit)) {
- ProtoLog.v(WM_DEBUG_APP_TRANSITIONS_ANIM,
- "applyAnimation: transition animation is disabled or skipped. "
- + "container=%s", this);
- cancelAnimation();
- return false;
- }
- return super.applyAnimation(lp, transit, enter, isVoiceInteraction);
- }
-
/**
* Creates a layer to apply crop to an animation.
*/
@@ -5913,14 +5935,14 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
protected void onAnimationFinished() {
super.onAnimationFinished();
- Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "AWT#onAnimationFinished");
+ Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "AR#onAnimationFinished");
mTransit = TRANSIT_UNSET;
mTransitFlags = 0;
mNeedsZBoost = false;
mNeedsAnimationBoundsLayer = false;
setAppLayoutChanges(FINISH_LAYOUT_REDO_ANIM | FINISH_LAYOUT_REDO_WALLPAPER,
- "AppWindowToken");
+ "ActivityRecord");
clearThumbnail();
setClientVisible(isVisible() || mVisibleRequested);
@@ -6138,10 +6160,9 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
if (mCompatDisplayInsets == null || !shouldUseSizeCompatMode()) {
return false;
}
- final Configuration resolvedConfig = getResolvedOverrideConfiguration();
- final Rect resolvedAppBounds = resolvedConfig.windowConfiguration.getAppBounds();
- if (resolvedAppBounds == null) {
- // The override configuration has not been resolved yet.
+ final Rect appBounds = getConfiguration().windowConfiguration.getAppBounds();
+ if (appBounds == null) {
+ // The app bounds hasn't been computed yet.
return false;
}
@@ -6149,13 +6170,13 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
// Although colorMode, screenLayout, smallestScreenWidthDp are also fixed, generally these
// fields should be changed with density and bounds, so here only compares the most
// significant field.
- if (parentConfig.densityDpi != resolvedConfig.densityDpi) {
+ if (parentConfig.densityDpi != getConfiguration().densityDpi) {
return true;
}
final Rect parentAppBounds = parentConfig.windowConfiguration.getAppBounds();
- final int appWidth = resolvedAppBounds.width();
- final int appHeight = resolvedAppBounds.height();
+ final int appWidth = appBounds.width();
+ final int appHeight = appBounds.height();
final int parentAppWidth = parentAppBounds.width();
final int parentAppHeight = parentAppBounds.height();
if (parentAppWidth == appWidth && parentAppHeight == appHeight) {
@@ -6174,7 +6195,8 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
// The rest of the condition is that only one side is smaller than the parent, but it still
// needs to exclude the cases where the size is limited by the fixed aspect ratio.
if (info.maxAspectRatio > 0) {
- final float aspectRatio = Math.max(appWidth, appHeight) / Math.min(appWidth, appHeight);
+ final float aspectRatio =
+ (float) Math.max(appWidth, appHeight) / Math.min(appWidth, appHeight);
if (aspectRatio >= info.maxAspectRatio) {
// The current size has reached the max aspect ratio.
return false;
@@ -6246,7 +6268,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
}
// The role of CompatDisplayInsets is like the override bounds.
- final ActivityDisplay display = getDisplay();
+ final DisplayContent display = getDisplay();
if (display != null) {
mCompatDisplayInsets = new CompatDisplayInsets(display.mDisplayContent,
getWindowConfiguration().getBounds(),
@@ -6516,7 +6538,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
onMergedOverrideConfigurationChanged();
}
- final ActivityDisplay display = getDisplay();
+ final DisplayContent display = getDisplay();
if (display == null) {
return;
}
@@ -6526,7 +6548,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
} else if (mCompatDisplayInsets != null) {
// The override changes can only be obtained from display, because we don't have the
// difference of full configuration in each hierarchy.
- final int displayChanges = display.getLastOverrideConfigurationChanges();
+ final int displayChanges = display.getCurrentOverrideConfigurationChanges();
final int orientationChanges = CONFIG_WINDOW_CONFIGURATION
| CONFIG_SCREEN_SIZE | CONFIG_ORIENTATION;
final boolean hasNonOrienSizeChanged = hasResizeChange(displayChanges)
@@ -7265,7 +7287,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
* otherwise.
*/
boolean isResumedActivityOnDisplay() {
- final ActivityDisplay display = getDisplay();
+ final DisplayContent display = getDisplay();
return display != null && this == display.getResumedActivity();
}
diff --git a/services/core/java/com/android/server/wm/ActivityStack.java b/services/core/java/com/android/server/wm/ActivityStack.java
index cc456717a0b2..a741d45011d2 100644
--- a/services/core/java/com/android/server/wm/ActivityStack.java
+++ b/services/core/java/com/android/server/wm/ActivityStack.java
@@ -16,6 +16,7 @@
package com.android.server.wm;
+import static android.app.ActivityTaskManager.INVALID_TASK_ID;
import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT;
import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
@@ -130,8 +131,6 @@ import android.app.AppGlobals;
import android.app.IActivityController;
import android.app.RemoteAction;
import android.app.ResultInfo;
-import android.app.WindowConfiguration.ActivityType;
-import android.app.WindowConfiguration.WindowingMode;
import android.app.servertransaction.ActivityResultItem;
import android.app.servertransaction.ClientTransaction;
import android.app.servertransaction.NewIntentItem;
@@ -143,7 +142,6 @@ import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Point;
import android.graphics.Rect;
-import android.graphics.Region;
import android.os.Binder;
import android.os.Debug;
import android.os.Handler;
@@ -153,9 +151,7 @@ import android.os.Message;
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.Trace;
-import android.os.UserHandle;
import android.service.voice.IVoiceInteractionSession;
-import android.util.ArraySet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Slog;
@@ -191,7 +187,7 @@ import java.util.function.Consumer;
/**
* State and management of a single stack of activities.
*/
-class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarget {
+class ActivityStack extends WindowContainer<WindowContainer> implements BoundsAnimationTarget {
private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityStack" : TAG_ATM;
static final String TAG_ADD_REMOVE = TAG + POSTFIX_ADD_REMOVE;
private static final String TAG_APP = TAG + POSTFIX_APP;
@@ -583,7 +579,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
return true;
}
- final ActivityRecord topActivity = topRunningActivityLocked();
+ final ActivityRecord topActivity = topRunningActivity();
final PooledFunction f = PooledLambda.obtainFunction(
CheckBehindFullscreenActivityHelper::processActivity, this,
PooledLambda.__(ActivityRecord.class), topActivity);
@@ -731,7 +727,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
}
}
- ActivityStack(ActivityDisplay display, int stackId, ActivityStackSupervisor supervisor,
+ ActivityStack(DisplayContent display, int stackId, ActivityStackSupervisor supervisor,
int windowingMode, int activityType, boolean onTop) {
super(supervisor.mService.mWindowManager);
mStackId = stackId;
@@ -815,7 +811,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
}
}
- final ActivityDisplay display = getDisplay();
+ final DisplayContent display = getDisplay();
if (display == null ) {
return;
}
@@ -870,7 +866,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
final boolean isMinimizedDock =
display.mDisplayContent.getDockedDividerController().isMinimizedDock();
if (isMinimizedDock) {
- Task topTask = display.getSplitScreenPrimaryStack().topTask();
+ Task topTask = display.getSplitScreenPrimaryStack().getTopMostTask();
if (topTask != null) {
dockedBounds = topTask.getBounds();
}
@@ -945,8 +941,8 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
boolean creating) {
final int currentMode = getWindowingMode();
final int currentOverrideMode = getRequestedOverrideWindowingMode();
- final ActivityDisplay display = getDisplay();
- final Task topTask = topTask();
+ final DisplayContent display = getDisplay();
+ final Task topTask = getTopMostTask();
final ActivityStack splitScreenStack = display.getSplitScreenPrimaryStack();
int windowingMode = preferredWindowingMode;
if (preferredWindowingMode == WINDOWING_MODE_UNDEFINED
@@ -1115,8 +1111,8 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
!PRESERVE_WINDOWS);
}
- ActivityDisplay getDisplay() {
- return mRootActivityContainer.getActivityDisplay(mDisplayId);
+ DisplayContent getDisplay() {
+ return getDisplayContent();
}
/**
@@ -1174,11 +1170,11 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
return false;
}
- ActivityRecord topRunningActivityLocked() {
- return topRunningActivityLocked(false /* focusableOnly */);
+ ActivityRecord topRunningActivity() {
+ return topRunningActivity(false /* focusableOnly */);
}
- ActivityRecord topRunningActivityLocked(boolean focusableOnly) {
+ ActivityRecord topRunningActivity(boolean focusableOnly) {
// Split into 2 to avoid object creation due to variable capture.
if (focusableOnly) {
return getActivity((r) -> r.canBeTopRunning() && r.isFocusable());
@@ -1212,7 +1208,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
*
* @return Returns the HistoryRecord of the next activity on the stack.
*/
- final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
+ ActivityRecord topRunningActivity(IBinder token, int taskId) {
final PooledPredicate p = PooledLambda.obtainPredicate(ActivityStack::isTopRunning,
PooledLambda.__(ActivityRecord.class), taskId, token);
final ActivityRecord r = getActivity(p);
@@ -1221,31 +1217,13 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
}
private static boolean isTopRunning(ActivityRecord r, int taskId, IBinder notTop) {
- return r.getTask().mTaskId == taskId && r.appToken != notTop && r.canBeTopRunning();
+ return r.getTask().mTaskId != taskId && r.appToken != notTop && r.canBeTopRunning();
}
ActivityRecord getTopNonFinishingActivity() {
return getTopActivity(false /*includeFinishing*/, true /*includeOverlays*/);
}
- final Task topTask() {
- final int size = getChildCount();
- if (size > 0) {
- return getChildAt(size - 1);
- }
- return null;
- }
-
- Task taskForIdLocked(int id) {
- for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
- final Task task = getChildAt(taskNdx);
- if (task.mTaskId == id) {
- return task;
- }
- }
- return null;
- }
-
ActivityRecord isInStackLocked(IBinder token) {
final ActivityRecord r = ActivityRecord.forTokenLocked(token);
return isInStackLocked(r);
@@ -1267,7 +1245,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
/** @return true if the stack can only contain one task */
boolean isSingleTaskInstance() {
- final ActivityDisplay display = getDisplay();
+ final DisplayContent display = getDisplay();
return display != null && display.isSingleTaskInstance();
}
@@ -1292,9 +1270,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
}
private boolean returnsToHomeStack() {
- return !inMultiWindowMode()
- && hasChild()
- && getChildAt(0).returnsToHomeStack();
+ return !inMultiWindowMode() && hasChild() && getBottomMostTask().returnsToHomeStack();
}
void moveToFront(String reason) {
@@ -1310,7 +1286,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
return;
}
- final ActivityDisplay display = getDisplay();
+ final DisplayContent display = getDisplay();
if (inSplitScreenSecondaryWindowingMode()) {
// If the stack is in split-screen seconardy mode, we need to make sure we move the
@@ -1367,7 +1343,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
}
boolean isFocusable() {
- final ActivityRecord r = topRunningActivityLocked();
+ final ActivityRecord r = topRunningActivity();
return mRootActivityContainer.isFocusable(this, r != null && r.isFocusable());
}
@@ -1377,7 +1353,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
@Override
public boolean isAttached() {
- final ActivityDisplay display = getDisplay();
+ final DisplayContent display = getDisplay();
return display != null && !display.isRemoved();
}
@@ -1390,15 +1366,12 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
mCurrentUser = userId;
super.switchUser(userId);
- int top = mChildren.size();
- for (int taskNdx = 0; taskNdx < top; ++taskNdx) {
- Task task = mChildren.get(taskNdx);
- if (mWmService.isCurrentProfileLocked(task.mUserId) || task.showForAllUsers()) {
- mChildren.remove(taskNdx);
- mChildren.add(task);
- --top;
+ forAllTasks((t) -> {
+ if (t.mWmService.isCurrentProfileLocked(t.mUserId) || t.showForAllUsers()) {
+ mChildren.remove(t);
+ mChildren.add(t);
}
- }
+ });
}
void minimalResumeActivityLocked(ActivityRecord r) {
@@ -1719,7 +1692,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
mRootActivityContainer.resumeFocusedStacksTopActivities(topStack, prev, null);
} else {
checkReadyForSleep();
- ActivityRecord top = topStack.topRunningActivityLocked();
+ ActivityRecord top = topStack.topRunningActivity();
if (top == null || (prev != null && top != prev)) {
// If there are no more activities available to run, do resume anyway to start
// something. Also if the top activity on the stack is not the just paused
@@ -1799,7 +1772,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
}
boolean isTopStackOnDisplay() {
- final ActivityDisplay display = getDisplay();
+ final DisplayContent display = getDisplay();
return display != null && display.isTopStack(this);
}
@@ -1808,7 +1781,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
* otherwise.
*/
boolean isFocusedStackOnDisplay() {
- final ActivityDisplay display = getDisplay();
+ final DisplayContent display = getDisplay();
return display != null && this == display.getFocusedStack();
}
@@ -1837,7 +1810,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
return STACK_VISIBILITY_INVISIBLE;
}
- final ActivityDisplay display = getDisplay();
+ final DisplayContent display = getDisplay();
boolean gotSplitScreenStack = false;
boolean gotOpaqueSplitScreenPrimary = false;
boolean gotOpaqueSplitScreenSecondary = false;
@@ -1849,7 +1822,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
final boolean isAssistantType = isActivityTypeAssistant();
for (int i = display.getStackCount() - 1; i >= 0; --i) {
final ActivityStack other = display.getStackAt(i);
- final boolean hasRunningActivities = other.topRunningActivityLocked() != null;
+ final boolean hasRunningActivities = other.topRunningActivity() != null;
if (other == this) {
// Should be visible if there is no other stack occluding it, unless it doesn't
// have any running activities, not starting one and not home stack.
@@ -2001,7 +1974,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
@Override
public boolean supportsSplitScreenWindowingMode() {
- final Task topTask = topTask();
+ final Task topTask = getTopMostTask();
return super.supportsSplitScreenWindowingMode()
&& (topTask == null || topTask.supportsSplitScreenWindowingMode());
}
@@ -2071,13 +2044,13 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
* {@link Display#FLAG_CAN_SHOW_WITH_INSECURE_KEYGUARD} applied.
*/
boolean canShowWithInsecureKeyguard() {
- final ActivityDisplay activityDisplay = getDisplay();
- if (activityDisplay == null) {
+ final DisplayContent displayContent = getDisplay();
+ if (displayContent == null) {
throw new IllegalStateException("Stack is not attached to any display, stackId="
+ mStackId);
}
- final int flags = activityDisplay.mDisplay.getFlags();
+ final int flags = displayContent.mDisplay.getFlags();
return (flags & FLAG_CAN_SHOW_WITH_INSECURE_KEYGUARD) != 0;
}
@@ -2185,7 +2158,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
// to ensure any necessary pause logic occurs. In the case where the Activity will be
// shown regardless of the lock screen, the call to
// {@link ActivityStackSupervisor#checkReadyForSleepLocked} is skipped.
- final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
+ final ActivityRecord next = topRunningActivity(true /* focusableOnly */);
if (next == null || !next.canTurnScreenOn()) {
checkReadyForSleep();
}
@@ -2224,7 +2197,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
// Find the next top-most activity to resume in this stack that is not finishing and is
// focusable. If it is not focusable, we will fall into the case below to resume the
// top activity in the next focusable task.
- ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
+ ActivityRecord next = topRunningActivity(true /* focusableOnly */);
final boolean hasRunningActivity = next != null;
@@ -2246,7 +2219,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
}
next.delayedResume = false;
- final ActivityDisplay display = getDisplay();
+ final DisplayContent display = getDisplay();
// If the top activity is the resumed one, nothing to do.
if (mResumedActivity == next && next.isState(RESUMED)
@@ -2535,7 +2508,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
// We should be all done, but let's just make sure our activity
// is still at the top and schedule another run if something
// weird happened.
- ActivityRecord nextNext = topRunningActivityLocked();
+ ActivityRecord nextNext = topRunningActivity();
if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG_STATES,
"Activity config changed during resume: " + next
+ ", new next: " + nextNext);
@@ -2672,41 +2645,28 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
void startActivityLocked(ActivityRecord r, ActivityRecord focusedTopActivity,
boolean newTask, boolean keepCurTransition, ActivityOptions options) {
Task rTask = r.getTask();
- final int taskId = rTask.mTaskId;
final boolean allowMoveToFront = options == null || !options.getAvoidMoveToFront();
+ final boolean hasTask = hasChild(rTask);
// mLaunchTaskBehind tasks get placed at the back of the task stack.
- if (!r.mLaunchTaskBehind && allowMoveToFront
- && (taskForIdLocked(taskId) == null || newTask)) {
+ if (!r.mLaunchTaskBehind && allowMoveToFront && (!hasTask || newTask)) {
// Last activity in task had been removed or ActivityManagerService is reusing task.
// Insert or replace.
// Might not even be in.
positionChildAtTop(rTask);
}
Task task = null;
- if (!newTask) {
- // If starting in an existing task, find where that is...
- boolean isOccluded = false;
- for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
- task = getChildAt(taskNdx);
- if (task.getTopNonFinishingActivity() == null) {
- // All activities in task are finishing.
- continue;
- }
- if (task == rTask) {
- // Here it is! Now, if this is not yet visible (occluded by another task) to
- // the user, then just add it without starting; it will get started when the
- // user navigates back to it.
- if (isOccluded) {
- if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task "
- + task, new RuntimeException("here").fillInStackTrace());
- rTask.positionChildAtTop(r);
- ActivityOptions.abort(options);
- return;
- }
- break;
- } else if (!isOccluded) {
- isOccluded = task.getActivity(ActivityRecord::occludesParent) != null;
- }
+ if (!newTask && hasTask) {
+ final ActivityRecord occludingActivity = getActivity(
+ (ar) -> !ar.finishing && ar.occludesParent(), true, rTask);
+ if (occludingActivity != null) {
+ // Here it is! Now, if this is not yet visible (occluded by another task) to the
+ // user, then just add it without starting; it will get started when the user
+ // navigates back to it.
+ if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task " + task,
+ new RuntimeException("here").fillInStackTrace());
+ rTask.positionChildAtTop(r);
+ ActivityOptions.abort(options);
+ return;
}
}
@@ -2892,7 +2852,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
return null;
}
- final ActivityRecord top = stack.topRunningActivityLocked();
+ final ActivityRecord top = stack.topRunningActivity();
if (stack.isActivityTypeHome() && (top == null || !top.mVisibleRequested)) {
// If we will be focusing on the home stack next and its current top activity isn't
@@ -2922,7 +2882,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
* not belong to the crashed app.
*/
final Task finishTopCrashedActivityLocked(WindowProcessController app, String reason) {
- ActivityRecord r = topRunningActivityLocked();
+ final ActivityRecord r = topRunningActivity();
if (r == null || r.app != app) {
return null;
}
@@ -3001,7 +2961,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
/** @return true if the stack behind this one is a standard activity type. */
private boolean inFrontOfStandardStack() {
- final ActivityDisplay display = getDisplay();
+ final DisplayContent display = getDisplay();
if (display == null) {
return false;
}
@@ -3033,12 +2993,11 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
return true;
}
// We now need to get the task below it to determine what to do.
- int taskIdx = mChildren.indexOf(task);
- if (taskIdx <= 0) {
+ final Task prevTask = getTaskBelow(task);
+ if (prevTask == null) {
Slog.w(TAG, "shouldUpRecreateTask: task not in history for " + srec);
return false;
}
- final Task prevTask = getChildAt(taskIdx);
if (!task.affinity.equals(prevTask.affinity)) {
// These are different apps, so need to recreate.
return true;
@@ -3073,7 +3032,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
// We should consolidate.
IActivityController controller = mService.mController;
if (controller != null) {
- ActivityRecord next = topRunningActivityLocked(srec.appToken, 0);
+ ActivityRecord next = topRunningActivity(srec.appToken, INVALID_TASK_ID);
if (next != null) {
// ask watcher if this is allowed
boolean resumeOK = true;
@@ -3287,7 +3246,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
private void updateTransitLocked(int transit, ActivityOptions options) {
if (options != null) {
- ActivityRecord r = topRunningActivityLocked();
+ ActivityRecord r = topRunningActivity();
if (r != null && !r.isState(RESUMED)) {
r.updateOptionsLocked(options);
} else {
@@ -3344,7 +3303,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
}
// Set focus to the top running activity of this stack.
- final ActivityRecord r = topRunningActivityLocked();
+ final ActivityRecord r = topRunningActivity();
if (r != null) {
r.moveFocusableActivityToTop(reason);
}
@@ -3386,15 +3345,10 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
* If a watcher is installed, the action is preflighted and the watcher has an opportunity
* to premeptively cancel the move.
*
- * @param taskId The taskId to collect and move to the bottom.
+ * @param tr The task to collect and move to the bottom.
* @return Returns true if the move completed, false if not.
*/
- final boolean moveTaskToBackLocked(int taskId) {
- final Task tr = taskForIdLocked(taskId);
- if (tr == null) {
- Slog.i(TAG, "moveTaskToBack: bad taskId=" + taskId);
- return false;
- }
+ boolean moveTaskToBack(Task tr) {
Slog.i(TAG, "moveTaskToBack: " + tr);
// In LockTask mode, moving a locked task to the back of the stack may expose unlocked
@@ -3407,9 +3361,9 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
// for *other* available tasks, but if none are available, then try again allowing the
// current task to be selected.
if (isTopStackOnDisplay() && mService.mController != null) {
- ActivityRecord next = topRunningActivityLocked(null, taskId);
+ ActivityRecord next = topRunningActivity(null, tr.mTaskId);
if (next == null) {
- next = topRunningActivityLocked(null, 0);
+ next = topRunningActivity(null, INVALID_TASK_ID);
}
if (next != null) {
// ask watcher if this is allowed
@@ -3426,7 +3380,8 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
}
}
- if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, "Prepare to back transition: task=" + taskId);
+ if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, "Prepare to back transition: task="
+ + tr.mTaskId);
getDisplay().mDisplayContent.prepareAppTransition(TRANSIT_TASK_TO_BACK, false);
moveToBack("moveTaskToBackLocked", tr);
@@ -3471,24 +3426,16 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
try {
// Update override configurations of all tasks in the stack.
final Rect taskBounds = tempTaskBounds != null ? tempTaskBounds : bounds;
- for (int i = getChildCount() - 1; i >= 0; i--) {
- final Task task = getChildAt(i);
- if (task.isResizeable()) {
- if (tempTaskInsetBounds != null && !tempTaskInsetBounds.isEmpty()) {
- task.setOverrideDisplayedBounds(taskBounds);
- task.setBounds(tempTaskInsetBounds);
- } else {
- task.setOverrideDisplayedBounds(null);
- task.setBounds(taskBounds);
- }
- }
- }
+ final PooledConsumer c = PooledLambda.obtainConsumer(
+ ActivityStack::processTaskResizeBounds, PooledLambda.__(Task.class),
+ taskBounds, tempTaskInsetBounds);
+ forAllTasks(c);
+ c.recycle();
setBounds(bounds);
if (!deferResume) {
- ensureVisibleActivitiesConfiguration(
- topRunningActivityLocked(), preserveWindows);
+ ensureVisibleActivitiesConfiguration(topRunningActivity(), preserveWindows);
}
} finally {
mService.continueWindowLayout();
@@ -3496,39 +3443,51 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
}
}
+ private static void processTaskResizeBounds(Task task, Rect bounds, Rect insetBounds) {
+ if (!task.isResizeable()) return;
+
+ if (insetBounds != null && !insetBounds.isEmpty()) {
+ task.setOverrideDisplayedBounds(bounds);
+ task.setBounds(insetBounds);
+ } else {
+ task.setOverrideDisplayedBounds(null);
+ task.setBounds(bounds);
+ }
+ }
+
/**
* Until we can break this "set task bounds to same as stack bounds" behavior, this
* basically resizes both stack and task bounds to the same bounds.
*/
- void setTaskBounds(Rect bounds) {
+ private void setTaskBounds(Rect bounds) {
if (!updateBoundsAllowed(bounds)) {
return;
}
- for (int i = getChildCount() - 1; i >= 0; i--) {
- final Task task = getChildAt(i);
- if (task.isResizeable()) {
- task.setBounds(bounds);
- } else {
- task.setBounds(null);
- }
- }
+ final PooledConsumer c = PooledLambda.obtainConsumer(ActivityStack::setTaskBounds,
+ PooledLambda.__(Task.class), bounds);
+ forAllTasks(c);
+ c.recycle();
+ }
+
+ private static void setTaskBounds(Task task, Rect bounds) {
+ task.setBounds(task.isResizeable() ? bounds : null);
}
/** Helper to setDisplayedBounds on all child tasks */
- void setTaskDisplayedBounds(Rect bounds) {
+ private void setTaskDisplayedBounds(Rect bounds) {
if (!updateDisplayedBoundsAllowed(bounds)) {
return;
}
- for (int i = getChildCount() - 1; i >= 0; i--) {
- final Task task = getChildAt(i);
- if (bounds == null || bounds.isEmpty()) {
- task.setOverrideDisplayedBounds(null);
- } else if (task.isResizeable()) {
- task.setOverrideDisplayedBounds(bounds);
- }
- }
+ final PooledConsumer c = PooledLambda.obtainConsumer(ActivityStack::setTaskDisplayedBounds,
+ PooledLambda.__(Task.class), bounds);
+ forAllTasks(c);
+ c.recycle();
+ }
+
+ private static void setTaskDisplayedBounds(Task task, Rect bounds) {
+ task.setOverrideDisplayedBounds(bounds == null || bounds.isEmpty() ? null : bounds);
}
boolean willActivityBeVisible(IBinder token) {
@@ -3548,56 +3507,6 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
return !r.finishing;
}
- /**
- * @return The set of running tasks through {@param tasksOut} that are available to the caller.
- * If {@param ignoreActivityType} or {@param ignoreWindowingMode} are not undefined,
- * then skip running tasks that match those types.
- */
- void getRunningTasks(List<Task> tasksOut, @ActivityType int ignoreActivityType,
- @WindowingMode int ignoreWindowingMode, int callingUid, boolean allowed,
- boolean crossUser, ArraySet<Integer> profileIds) {
- boolean focusedStack = mRootActivityContainer.getTopDisplayFocusedStack() == this;
- boolean topTask = true;
- int userId = UserHandle.getUserId(callingUid);
- for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
- final Task task = getChildAt(taskNdx);
- if (task.getTopNonFinishingActivity() == null) {
- // Skip if there are no activities in the task
- continue;
- }
- if (task.effectiveUid != callingUid) {
- if (task.mUserId != userId && !crossUser && !profileIds.contains(task.mUserId)) {
- // Skip if the caller does not have cross user permission or cannot access
- // the task's profile
- continue;
- }
- if (!allowed && !task.isActivityTypeHome()) {
- // Skip if the caller isn't allowed to fetch this task, except for the home
- // task which we always return.
- continue;
- }
- }
- if (ignoreActivityType != ACTIVITY_TYPE_UNDEFINED
- && task.getActivityType() == ignoreActivityType) {
- // Skip ignored activity type
- continue;
- }
- if (ignoreWindowingMode != WINDOWING_MODE_UNDEFINED
- && task.getWindowingMode() == ignoreWindowingMode) {
- // Skip ignored windowing mode
- continue;
- }
- if (focusedStack && topTask) {
- // For the focused stack top task, update the last stack active time so that it can
- // be used to determine the order of the tasks (it may not be set for newly created
- // tasks)
- task.touchActiveTime();
- topTask = false;
- }
- tasksOut.add(task);
- }
- }
-
void unhandledBackLocked() {
final ActivityRecord topActivity = getTopMostActivity();
if (DEBUG_SWITCH) Slog.d(TAG_SWITCH,
@@ -3685,7 +3594,10 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
pw.println(prefix + "* " + task);
task.dump(pw, prefix + " ");
final ArrayList<ActivityRecord> activities = new ArrayList<>();
- forAllActivities((Consumer<ActivityRecord>) activities::add);
+ // Add activities by traversing the hierarchy from bottom to top, since activities
+ // are dumped in reverse order in {@link ActivityStackSupervisor#dumpHistoryList()}.
+ forAllActivities((Consumer<ActivityRecord>) activities::add,
+ false /* traverseTopToBottom */);
dumpHistoryList(fd, pw, activities, prefix, "Hist", true, !dumpAll, dumpClient,
dumpPackage, false, null, task);
});
@@ -3717,7 +3629,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
}
ActivityRecord restartPackage(String packageName) {
- ActivityRecord starting = topRunningActivityLocked();
+ ActivityRecord starting = topRunningActivity();
// All activities that came from the package must be
// restarted as if there was a config change.
@@ -3745,19 +3657,20 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
* @param child to remove.
* @param reason for removal.
*/
- void removeChild(Task child, String reason) {
+ void removeChild(WindowContainer child, String reason) {
if (!mChildren.contains(child)) {
// Not really in this stack anymore...
return;
}
- final ActivityDisplay display = getDisplay();
- final boolean topFocused = mRootActivityContainer.isTopDisplayFocusedStack(this);
- if (DEBUG_TASK_MOVEMENT) Slog.d(TAG_WM, "removeChild: task=" + child);
+ final DisplayContent display = getDisplay();
+ if (DEBUG_TASK_MOVEMENT) {
+ Slog.d(TAG_WM, "removeChild: task=" + child + " reason=" + reason);
+ }
super.removeChild(child);
- EventLogTags.writeWmRemoveTask(child.mTaskId, mStackId);
+ EventLogTags.writeWmRemoveTask(((Task) child).mTaskId, mStackId);
if (display.isSingleTaskInstance()) {
mService.notifySingleTaskDisplayEmpty(display.mDisplayId);
@@ -3767,27 +3680,13 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
if (!hasChild()) {
// Stack is now empty...
- removeIfPossible();
+ removeIfPossible();
}
-
- moveHomeStackToFrontIfNeeded(topFocused, display, reason);
}
@Override
- void removeChild(Task task) {
- removeChild(task, "removeChild");
- }
-
- void moveHomeStackToFrontIfNeeded(
- boolean wasTopFocusedStack, ActivityDisplay display, String reason) {
- if (!hasChild() && wasTopFocusedStack) {
- // We only need to adjust focused stack if this stack is in focus and we are not in the
- // process of moving the task to the top of the stack that will be focused.
- String myReason = reason + " leftTaskHistoryEmpty";
- if (!inMultiWindowMode() || adjustFocusToNextFocusableStack(myReason) == null) {
- display.moveHomeStackToFront(myReason);
- }
- }
+ void removeChild(WindowContainer child) {
+ removeChild(child, "removeChild");
}
Task createTask(int taskId, ActivityInfo info, Intent intent,
@@ -3816,10 +3715,6 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
return task;
}
- ArrayList<Task> getAllTasks() {
- return new ArrayList<>(mChildren);
- }
-
void addChild(final Task task, final boolean toTop, boolean showForAllUsers) {
if (isSingleTaskInstance() && hasChild()) {
throw new IllegalStateException("Can only have one child on stack=" + this);
@@ -3880,11 +3775,11 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
return;
}
super.setAlwaysOnTop(alwaysOnTop);
- final ActivityDisplay display = getDisplay();
+ final DisplayContent display = getDisplay();
// positionChildAtTop() must be called even when always on top gets turned off because we
// need to make sure that the stack is moved from among always on top windows to below other
// always on top windows. Since the position the stack should be inserted into is calculated
- // properly in {@link ActivityDisplay#getTopInsertPosition()} in both cases, we can just
+ // properly in {@link DisplayContent#getTopInsertPosition()} in both cases, we can just
// request that the stack is put at top here.
display.positionStackAtTop(this, false /* includingParents */);
}
@@ -4015,7 +3910,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
}
mWindowManager.inSurfaceTransaction(() -> {
- final Task task = mChildren.get(0);
+ final Task task = getBottomMostTask();
setWindowingMode(WINDOWING_MODE_UNDEFINED);
getDisplay().positionStackAtTop(this, false /* includingParents */);
@@ -4026,7 +3921,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
});
}
- void updatePictureInPictureModeForPinnedStackAnimation(Rect targetStackBounds,
+ private void updatePictureInPictureModeForPinnedStackAnimation(Rect targetStackBounds,
boolean forceUpdate) {
// It is guaranteed that the activities requiring the update will be in the pinned stack at
// this point (either reparented before the animation into PiP, or before reparenting after
@@ -4034,29 +3929,19 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
if (!isAttached()) {
return;
}
- ArrayList<Task> tasks = getAllTasks();
- for (int i = 0; i < tasks.size(); i++) {
- mStackSupervisor.updatePictureInPictureMode(tasks.get(i), targetStackBounds,
- forceUpdate);
- }
+ final PooledConsumer c = PooledLambda.obtainConsumer(
+ ActivityStackSupervisor::updatePictureInPictureMode, mStackSupervisor,
+ PooledLambda.__(Task.class), targetStackBounds, forceUpdate);
+ forAllTasks(c);
+ c.recycle();
}
public int getStackId() {
return mStackId;
}
- Task findHomeTask() {
- if (!isActivityTypeHome() || mChildren.isEmpty()) {
- return null;
- }
- return mChildren.get(mChildren.size() - 1);
- }
-
void prepareFreezingTaskBounds() {
- for (int taskNdx = mChildren.size() - 1; taskNdx >= 0; --taskNdx) {
- final Task task = mChildren.get(taskNdx);
- task.prepareFreezingBounds();
- }
+ forAllTasks(Task::prepareFreezingBounds);
}
/**
@@ -4082,24 +3967,18 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
insetBounds = mFullyAdjustedImeBounds;
}
}
- alignTasksToAdjustedBounds(adjusted ? mAdjustedBounds : getRawBounds(), insetBounds);
- mDisplayContent.setLayoutNeeded();
-
- updateSurfaceBounds();
- }
- private void alignTasksToAdjustedBounds(Rect adjustedBounds, Rect tempInsetBounds) {
- if (matchParentBounds()) {
- return;
+ if (!matchParentBounds()) {
+ final boolean alignBottom = mAdjustedForIme && getDockSide() == DOCKED_TOP;
+ final PooledConsumer c = PooledLambda.obtainConsumer(Task::alignToAdjustedBounds,
+ PooledLambda.__(Task.class), adjusted ? mAdjustedBounds : getRawBounds(),
+ insetBounds, alignBottom);
+ forAllTasks(c);
+ c.recycle();
}
- final boolean alignBottom = mAdjustedForIme && getDockSide() == DOCKED_TOP;
-
- // Update bounds of containing tasks.
- for (int taskNdx = mChildren.size() - 1; taskNdx >= 0; --taskNdx) {
- final Task task = mChildren.get(taskNdx);
- task.alignToAdjustedBounds(adjustedBounds, tempInsetBounds, alignBottom);
- }
+ mDisplayContent.setLayoutNeeded();
+ updateSurfaceBounds();
}
@Override
@@ -4366,17 +4245,17 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
* @param position Target position to add the task to.
* @param showForAllUsers Whether to show the task regardless of the current user.
*/
- void addChild(Task task, int position, boolean showForAllUsers, boolean moveParents) {
+ private void addChild(Task task, int position, boolean showForAllUsers, boolean moveParents) {
// Add child task.
addChild(task, null);
// Move child to a proper position, as some restriction for position might apply.
- position = positionChildAt(
- position, task, moveParents /* includingParents */, showForAllUsers);
+ positionChildAt(position, task, moveParents /* includingParents */, showForAllUsers);
}
@Override
- void addChild(Task task, int position) {
+ void addChild(WindowContainer child, int position) {
+ final Task task = (Task) child;
addChild(task, position, task.showForAllUsers(), false /* includingParents */);
}
@@ -4415,14 +4294,15 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
}
@Override
- void positionChildAt(int position, Task child, boolean includingParents) {
- positionChildAt(position, child, includingParents, child.showForAllUsers());
+ void positionChildAt(int position, WindowContainer child, boolean includingParents) {
+ final Task task = (Task) child;
+ positionChildAt(position, task, includingParents, task.showForAllUsers());
}
/**
- * Overridden version of {@link ActivityStack#positionChildAt(int, Task, boolean)}. Used in
- * {@link ActivityStack#addChild(Task, int, boolean showForAllUsers, boolean)}, as it can
- * receive showForAllUsers param from {@link ActivityRecord} instead of
+ * Overridden version of {@link ActivityStack#positionChildAt(int, WindowContainer, boolean)}.
+ * Used in {@link ActivityStack#addChild(Task, int, boolean showForAllUsers, boolean)}, as it
+ * can receive showForAllUsers param from {@link ActivityRecord} instead of
* {@link Task#showForAllUsers()}.
*/
private int positionChildAt(int position, Task child, boolean includingParents,
@@ -4458,11 +4338,10 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
@Override
protected void onParentChanged(
ConfigurationContainer newParent, ConfigurationContainer oldParent) {
- // TODO(display-merge): Remove cast
- final ActivityDisplay display = newParent != null
- ? (ActivityDisplay) ((WindowContainer) newParent).getDisplayContent() : null;
- final ActivityDisplay oldDisplay = oldParent != null
- ? (ActivityDisplay) ((WindowContainer) oldParent).getDisplayContent() : null;
+ final DisplayContent display = newParent != null
+ ? ((WindowContainer) newParent).getDisplayContent() : null;
+ final DisplayContent oldDisplay = oldParent != null
+ ? ((WindowContainer) oldParent).getDisplayContent() : null;
mDisplayId = (display != null) ? display.mDisplayId : INVALID_DISPLAY;
mPrevDisplayId = (oldDisplay != null) ? oldDisplay.mDisplayId : INVALID_DISPLAY;
@@ -4538,9 +4417,10 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
* We will start adjusting up from here.
* @param size The size of the current task list.
*/
+ // TODO(task-hierarchy): Move user to their own window container.
private int computeMinPosition(int minPosition, int size) {
while (minPosition < size) {
- final Task tmpTask = mChildren.get(minPosition);
+ final Task tmpTask = (Task) mChildren.get(minPosition);
final boolean canShowTmpTask =
tmpTask.showForAllUsers()
|| mWmService.isCurrentProfileLocked(tmpTask.mUserId);
@@ -4557,9 +4437,10 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
* @param maxPosition The maximum position the caller is suggesting.
* We will start adjusting down from here.
*/
+ // TODO(task-hierarchy): Move user to their own window container.
private int computeMaxPosition(int maxPosition) {
while (maxPosition > 0) {
- final Task tmpTask = mChildren.get(maxPosition);
+ final Task tmpTask = (Task) mChildren.get(maxPosition);
final boolean canShowTmpTask =
tmpTask.showForAllUsers()
|| mWmService.isCurrentProfileLocked(tmpTask.mUserId);
@@ -4664,7 +4545,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
// When the home stack is resizable, should always have the same stack and task bounds
if (isActivityTypeHome()) {
- final Task homeTask = findHomeTask();
+ final Task homeTask = getTopMostTask();
if (homeTask == null || homeTask.isResizeable()) {
// Calculate the home stack bounds when in docked mode and the home stack is
// resizeable.
@@ -4894,25 +4775,20 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
* to the list of to be drawn windows the service is waiting for.
*/
void beginImeAdjustAnimation() {
- for (int j = mChildren.size() - 1; j >= 0; j--) {
- final Task task = mChildren.get(j);
- if (task.hasContentToDisplay()) {
- task.setDragResizing(true, DRAG_RESIZE_MODE_DOCKED_DIVIDER);
- task.setWaitingForDrawnIfResizingChanged();
+ forAllTasks((t) -> {
+ if (t.hasContentToDisplay()) {
+ t.setDragResizing(true, DRAG_RESIZE_MODE_DOCKED_DIVIDER);
+ t.setWaitingForDrawnIfResizingChanged();
}
- }
+ });
}
- /**
- * Resets the resizing state of all windows.
- */
+ /** Resets the resizing state of all windows. */
void endImeAdjustAnimation() {
- for (int j = mChildren.size() - 1; j >= 0; j--) {
- mChildren.get(j).setDragResizing(false, DRAG_RESIZE_MODE_DOCKED_DIVIDER);
- }
+ forAllTasks((t) -> { t.setDragResizing(false, DRAG_RESIZE_MODE_DOCKED_DIVIDER); });
}
- int getMinTopStackBottom(final Rect displayContentRect, int originalStackBottom) {
+ private int getMinTopStackBottom(final Rect displayContentRect, int originalStackBottom) {
return displayContentRect.top + (int)
((originalStackBottom - displayContentRect.top) * ADJUSTED_STACK_FRACTION_MIN);
}
@@ -5024,7 +4900,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
return true;
}
- private boolean isMinimizedDockAndHomeStackResizable() {
+ boolean isMinimizedDockAndHomeStackResizable() {
return mDisplayContent.mDividerControllerLocked.isMinimizedDock()
&& mDisplayContent.mDividerControllerLocked.isHomeStackResizable();
}
@@ -5092,13 +4968,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
* recents animation); {@code false} otherwise.
*/
boolean isTaskAnimating() {
- for (int j = mChildren.size() - 1; j >= 0; j--) {
- final Task task = mChildren.get(j);
- if (task.isTaskAnimating()) {
- return true;
- }
- }
- return false;
+ return getTask(Task::isTaskAnimating) != null;
}
@Override
@@ -5173,102 +5043,11 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
}
boolean hasTaskForUser(int userId) {
- for (int i = mChildren.size() - 1; i >= 0; i--) {
- final Task task = mChildren.get(i);
- if (task.mUserId == userId) {
- return true;
- }
- }
- return false;
- }
-
- void findTaskForResizePoint(int x, int y, int delta,
- DisplayContent.TaskForResizePointSearchResult results) {
- if (!getWindowConfiguration().canResizeTask()) {
- results.searchDone = true;
- return;
- }
-
- for (int i = mChildren.size() - 1; i >= 0; --i) {
- final Task task = mChildren.get(i);
- if (task.getWindowingMode() == WINDOWING_MODE_FULLSCREEN) {
- results.searchDone = true;
- return;
- }
-
- // We need to use the task's dim bounds (which is derived from the visible bounds of
- // its apps windows) for any touch-related tests. Can't use the task's original
- // bounds because it might be adjusted to fit the content frame. One example is when
- // the task is put to top-left quadrant, the actual visible area would not start at
- // (0,0) after it's adjusted for the status bar.
- task.getDimBounds(mTmpRect);
- mTmpRect.inset(-delta, -delta);
- if (mTmpRect.contains(x, y)) {
- mTmpRect.inset(delta, delta);
-
- results.searchDone = true;
-
- if (!mTmpRect.contains(x, y)) {
- results.taskForResize = task;
- return;
- }
- // User touched inside the task. No need to look further,
- // focus transfer will be handled in ACTION_UP.
- return;
- }
- }
- }
-
- void setTouchExcludeRegion(Task focusedTask, int delta, Region touchExcludeRegion,
- Rect contentRect, Rect postExclude) {
- for (int i = mChildren.size() - 1; i >= 0; --i) {
- final Task task = mChildren.get(i);
- ActivityRecord topVisibleActivity = task.getTopVisibleActivity();
- if (topVisibleActivity == null || !topVisibleActivity.hasContentToDisplay()) {
- continue;
- }
-
- /**
- * Exclusion region is the region that TapDetector doesn't care about.
- * Here we want to remove all non-focused tasks from the exclusion region.
- * We also remove the outside touch area for resizing for all freeform
- * tasks (including the focused).
- *
- * We save the focused task region once we find it, and add it back at the end.
- *
- * If the task is home stack and it is resizable in the minimized state, we want to
- * exclude the docked stack from touch so we need the entire screen area and not just a
- * small portion which the home stack currently is resized to.
- */
-
- if (task.isActivityTypeHome() && isMinimizedDockAndHomeStackResizable()) {
- mDisplayContent.getBounds(mTmpRect);
- } else {
- task.getDimBounds(mTmpRect);
- }
-
- if (task == focusedTask) {
- // Add the focused task rect back into the exclude region once we are done
- // processing stacks.
- postExclude.set(mTmpRect);
- }
-
- final boolean isFreeformed = task.inFreeformWindowingMode();
- if (task != focusedTask || isFreeformed) {
- if (isFreeformed) {
- // If the task is freeformed, enlarge the area to account for outside
- // touch area for resize.
- mTmpRect.inset(-delta, -delta);
- // Intersect with display content rect. If we have system decor (status bar/
- // navigation bar), we want to exclude that from the tap detection.
- // Otherwise, if the app is partially placed under some system button (eg.
- // Recents, Home), pressing that button would cause a full series of
- // unwanted transfer focus/resume/pause, before we could go home.
- mTmpRect.intersect(contentRect);
- }
- touchExcludeRegion.op(mTmpRect, Region.Op.DIFFERENCE);
- }
- }
+ final PooledPredicate p = PooledLambda.obtainPredicate(
+ Task::isTaskForUser, PooledLambda.__(Task.class), userId);
+ final Task task = getTask(p);
+ p.recycle();
+ return task != null;
}
public boolean setPinnedStackSize(Rect stackBounds, Rect tempTaskBounds) {
@@ -5429,10 +5208,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
/** Called immediately prior to resizing the tasks at the end of the pinned stack animation. */
void onPipAnimationEndResize() {
mBoundsAnimating = false;
- for (int i = 0; i < mChildren.size(); i++) {
- final Task t = mChildren.get(i);
- t.clearPreserveNonFloatingState();
- }
+ forAllTasks(Task::clearPreserveNonFloatingState, false);
mWmService.requestTraversal();
}
@@ -5453,7 +5229,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
if (homeStack == null) {
return true;
}
- final Task homeTask = homeStack.getTopChild();
+ final Task homeTask = homeStack.getTopMostTask();
if (homeTask == null) {
return true;
}
@@ -5585,7 +5361,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
@Override
void getAnimationFrames(Rect outFrame, Rect outInsets, Rect outStableInsets,
Rect outSurfaceInsets) {
- final Task task = getTopChild();
+ final Task task = getTopMostTask();
if (task != null) {
task.getAnimationFrames(outFrame, outInsets, outStableInsets, outSurfaceInsets);
} else {
@@ -5596,7 +5372,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
@Override
RemoteAnimationTarget createRemoteAnimationTarget(
RemoteAnimationController.RemoteAnimationRecord record) {
- final Task task = getTopChild();
+ final Task task = getTopMostTask();
return task != null ? task.createRemoteAnimationTarget(record) : null;
}
@@ -5611,19 +5387,13 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
+ getChildCount() + " tasks}";
}
- void onLockTaskPackagesUpdated() {
- for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
- getChildAt(taskNdx).setLockTaskAuth();
- }
- }
-
void executeAppTransition(ActivityOptions options) {
getDisplay().mDisplayContent.executeAppTransition();
ActivityOptions.abort(options);
}
boolean shouldSleepActivities() {
- final ActivityDisplay display = getDisplay();
+ final DisplayContent display = getDisplay();
// Do not sleep activities in this stack if we're marked as focused and the keyguard
// is in the process of going away.
@@ -5644,10 +5414,10 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
final long token = proto.start(fieldId);
dumpDebugInnerStackOnly(proto, STACK, logLevel);
proto.write(com.android.server.am.ActivityStackProto.ID, mStackId);
- for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
- final Task task = getChildAt(taskNdx);
- task.dumpDebug(proto, com.android.server.am.ActivityStackProto.TASKS, logLevel);
- }
+
+ forAllTasks((t) -> {
+ t.dumpDebug(proto, com.android.server.am.ActivityStackProto.TASKS, logLevel);
+ });
if (mResumedActivity != null) {
mResumedActivity.writeIdentifierToProto(proto, RESUMED_ACTIVITY);
}
@@ -5672,9 +5442,7 @@ class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarg
final long token = proto.start(fieldId);
super.dumpDebug(proto, WINDOW_CONTAINER, logLevel);
proto.write(StackProto.ID, mStackId);
- for (int taskNdx = mChildren.size() - 1; taskNdx >= 0; taskNdx--) {
- mChildren.get(taskNdx).dumpDebugInnerTaskOnly(proto, StackProto.TASKS, logLevel);
- }
+ forAllTasks((t) -> { t.dumpDebugInnerTaskOnly(proto, StackProto.TASKS, logLevel); });
proto.write(FILLS_PARENT, matchParentBounds());
getRawBounds().dumpDebug(proto, StackProto.BOUNDS);
proto.write(DEFER_REMOVAL, mDeferRemoval);
diff --git a/services/core/java/com/android/server/wm/ActivityStackSupervisor.java b/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
index 735636867d09..26d9dbce4a69 100644
--- a/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
@@ -165,28 +165,28 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
static final String TAG_TASKS = TAG + POSTFIX_TASKS;
/** How long we wait until giving up on the last activity telling us it is idle. */
- static final int IDLE_TIMEOUT = 10 * 1000;
+ private static final int IDLE_TIMEOUT = 10 * 1000;
/** How long we can hold the sleep wake lock before giving up. */
- static final int SLEEP_TIMEOUT = 5 * 1000;
+ private static final int SLEEP_TIMEOUT = 5 * 1000;
// How long we can hold the launch wake lock before giving up.
- static final int LAUNCH_TIMEOUT = 10 * 1000;
+ private static final int LAUNCH_TIMEOUT = 10 * 1000;
/** How long we wait until giving up on the activity telling us it released the top state. */
- static final int TOP_RESUMED_STATE_LOSS_TIMEOUT = 500;
-
- static final int IDLE_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG;
- static final int IDLE_NOW_MSG = FIRST_SUPERVISOR_STACK_MSG + 1;
- static final int RESUME_TOP_ACTIVITY_MSG = FIRST_SUPERVISOR_STACK_MSG + 2;
- static final int SLEEP_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 3;
- static final int LAUNCH_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 4;
- static final int LAUNCH_TASK_BEHIND_COMPLETE = FIRST_SUPERVISOR_STACK_MSG + 12;
- static final int RESTART_ACTIVITY_PROCESS_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 13;
- static final int REPORT_MULTI_WINDOW_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 14;
- static final int REPORT_PIP_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 15;
- static final int REPORT_HOME_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 16;
- static final int TOP_RESUMED_STATE_LOSS_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 17;
+ private static final int TOP_RESUMED_STATE_LOSS_TIMEOUT = 500;
+
+ private static final int IDLE_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG;
+ private static final int IDLE_NOW_MSG = FIRST_SUPERVISOR_STACK_MSG + 1;
+ private static final int RESUME_TOP_ACTIVITY_MSG = FIRST_SUPERVISOR_STACK_MSG + 2;
+ private static final int SLEEP_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 3;
+ private static final int LAUNCH_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 4;
+ private static final int LAUNCH_TASK_BEHIND_COMPLETE = FIRST_SUPERVISOR_STACK_MSG + 12;
+ private static final int RESTART_ACTIVITY_PROCESS_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 13;
+ private static final int REPORT_MULTI_WINDOW_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 14;
+ private static final int REPORT_PIP_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 15;
+ private static final int REPORT_HOME_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 16;
+ private static final int TOP_RESUMED_STATE_LOSS_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 17;
// Used to indicate that windows of activities should be preserved during the resize.
static final boolean PRESERVE_WINDOWS = true;
@@ -237,7 +237,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
// For debugging to make sure the caller when acquiring/releasing our
// wake lock is the system process.
- static final boolean VALIDATE_WAKE_LOCK_CALLER = false;
+ private static final boolean VALIDATE_WAKE_LOCK_CALLER = false;
/** The number of distinct task ids that can be assigned to the tasks of a single user */
private static final int MAX_TASK_IDS_PER_USER = UserHandle.PER_USER_RANGE;
@@ -250,11 +250,11 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
/** Helper class to abstract out logic for fetching the set of currently running tasks */
private RunningTasks mRunningTasks;
- final ActivityStackSupervisorHandler mHandler;
+ private final ActivityStackSupervisorHandler mHandler;
final Looper mLooper;
/** Short cut */
- WindowManagerService mWindowManager;
+ private WindowManagerService mWindowManager;
/** Common synchronization logic used to save things to disks. */
PersisterQueue mPersisterQueue;
@@ -286,11 +286,11 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
/** List of activities whose multi-window mode changed that we need to report to the
* application */
- final ArrayList<ActivityRecord> mMultiWindowModeChangedActivities = new ArrayList<>();
+ private final ArrayList<ActivityRecord> mMultiWindowModeChangedActivities = new ArrayList<>();
/** List of activities whose picture-in-picture mode changed that we need to report to the
* application */
- final ArrayList<ActivityRecord> mPipModeChangedActivities = new ArrayList<>();
+ private final ArrayList<ActivityRecord> mPipModeChangedActivities = new ArrayList<>();
/**
* Animations that for the current transition have requested not to
@@ -312,7 +312,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
/** The target stack bounds for the picture-in-picture mode changed that we need to report to
* the application */
- Rect mPipModeChangedTargetStackBounds;
+ private Rect mPipModeChangedTargetStackBounds;
/** Used on user changes */
final ArrayList<UserState> mStartingUsers = new ArrayList<>();
@@ -398,6 +398,52 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
private boolean mInitialized;
+ private final MoveTaskToFullscreenHelper mMoveTaskToFullscreenHelper =
+ new MoveTaskToFullscreenHelper();
+ private class MoveTaskToFullscreenHelper {
+ private DisplayContent mToDisplay;
+ private boolean mOnTop;
+ private Task mTopTask;
+ private boolean mSchedulePictureInPictureModeChange;
+
+ void process(ActivityStack fromStack, DisplayContent toDisplay, boolean onTop,
+ boolean schedulePictureInPictureModeChange) {
+ mSchedulePictureInPictureModeChange = schedulePictureInPictureModeChange;
+ mToDisplay = toDisplay;
+ mOnTop = onTop;
+ mTopTask = fromStack.getTopMostTask();
+
+ final PooledConsumer c = PooledLambda.obtainConsumer(
+ MoveTaskToFullscreenHelper::processTask, this, PooledLambda.__(Task.class));
+ fromStack.forAllTasks(c, false);
+ c.recycle();
+ mToDisplay = null;
+ mTopTask = null;
+ }
+
+ private void processTask(Task task) {
+ final ActivityStack toStack = mToDisplay.getOrCreateStack(
+ null, mTmpOptions, task, task.getActivityType(), mOnTop);
+
+ if (mOnTop) {
+ final boolean isTopTask = task == mTopTask;
+ // Defer resume until all the tasks have been moved to the fullscreen stack
+ task.reparent(toStack, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, isTopTask /*animate*/,
+ DEFER_RESUME, mSchedulePictureInPictureModeChange,
+ "moveTasksToFullscreenStack - onTop");
+ MetricsLoggerWrapper.logPictureInPictureFullScreen(mService.mContext,
+ task.effectiveUid, task.realActivity.flattenToString());
+ } else {
+ // Position the tasks in the fullscreen stack in order at the bottom of the
+ // stack. Also defer resume until all the tasks have been moved to the
+ // fullscreen stack.
+ task.reparent(toStack, ON_TOP, REPARENT_LEAVE_STACK_IN_PLACE,
+ !ANIMATE, DEFER_RESUME, mSchedulePictureInPictureModeChange,
+ "moveTasksToFullscreenStack - NOT_onTop");
+ }
+ }
+ }
+
/**
* Description of a request to start a new activity, which has been held
* due to app switches being disabled.
@@ -1076,9 +1122,9 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
return true;
}
- final ActivityDisplay activityDisplay =
- mRootActivityContainer.getActivityDisplayOrCreate(launchDisplayId);
- if (activityDisplay == null || activityDisplay.isRemoved()) {
+ final DisplayContent displayContent =
+ mRootActivityContainer.getDisplayContentOrCreate(launchDisplayId);
+ if (displayContent == null || displayContent.isRemoved()) {
Slog.w(TAG, "Launch on display check: display not found");
return false;
}
@@ -1094,10 +1140,10 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
}
// Check if caller is already present on display
- final boolean uidPresentOnDisplay = activityDisplay.isUidPresent(callingUid);
+ final boolean uidPresentOnDisplay = displayContent.isUidPresent(callingUid);
- final int displayOwnerUid = activityDisplay.mDisplay.getOwnerUid();
- if (activityDisplay.mDisplay.getType() == TYPE_VIRTUAL && displayOwnerUid != SYSTEM_UID
+ final int displayOwnerUid = displayContent.mDisplay.getOwnerUid();
+ if (displayContent.mDisplay.getType() == TYPE_VIRTUAL && displayOwnerUid != SYSTEM_UID
&& displayOwnerUid != aInfo.applicationInfo.uid) {
// Limit launching on virtual displays, because their contents can be read from Surface
// by apps that created them.
@@ -1115,7 +1161,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
}
}
- if (!activityDisplay.isPrivate()) {
+ if (!displayContent.isPrivate()) {
// Anyone can launch on a public display.
if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:"
+ " allow launch on public display");
@@ -1436,7 +1482,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
currentStack, forceNonResizeable);
}
- private void moveHomeStackToFrontIfNeeded(int flags, ActivityDisplay display, String reason) {
+ private void moveHomeStackToFrontIfNeeded(int flags, DisplayContent display, String reason) {
final ActivityStack focusedStack = display.getFocusedStack();
if ((display.getWindowingMode() == WINDOWING_MODE_FULLSCREEN
@@ -1496,8 +1542,8 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
mService.deferWindowLayout();
try {
final int windowingMode = fromStack.getWindowingMode();
- final ActivityDisplay toDisplay =
- mRootActivityContainer.getActivityDisplay(toDisplayId);
+ final DisplayContent toDisplay =
+ mRootActivityContainer.getDisplayContent(toDisplayId);
if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
// We are moving all tasks from the docked stack to the fullscreen stack,
@@ -1522,35 +1568,11 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
// the picture-in-picture mode.
final boolean schedulePictureInPictureModeChange =
windowingMode == WINDOWING_MODE_PINNED;
- final ArrayList<Task> tasks = fromStack.getAllTasks();
- if (!tasks.isEmpty()) {
+ if (fromStack.hasChild()) {
mTmpOptions.setLaunchWindowingMode(WINDOWING_MODE_FULLSCREEN);
- final int size = tasks.size();
- for (int i = 0; i < size; ++i) {
- final Task task = tasks.get(i);
- final ActivityStack toStack = toDisplay.getOrCreateStack(
- null, mTmpOptions, task, task.getActivityType(), onTop);
-
- if (onTop) {
- final boolean isTopTask = i == (size - 1);
- // Defer resume until all the tasks have been moved to the fullscreen stack
- task.reparent(toStack, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT,
- isTopTask /* animate */, DEFER_RESUME,
- schedulePictureInPictureModeChange,
- "moveTasksToFullscreenStack - onTop");
- MetricsLoggerWrapper.logPictureInPictureFullScreen(mService.mContext,
- task.effectiveUid, task.realActivity.flattenToString());
- } else {
- // Position the tasks in the fullscreen stack in order at the bottom of the
- // stack. Also defer resume until all the tasks have been moved to the
- // fullscreen stack.
- task.reparent(toStack, ON_TOP,
- REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE, DEFER_RESUME,
- schedulePictureInPictureModeChange,
- "moveTasksToFullscreenStack - NOT_onTop");
- }
- }
+ mMoveTaskToFullscreenHelper.process(
+ fromStack, toDisplay, onTop, schedulePictureInPictureModeChange);
}
mRootActivityContainer.ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS);
@@ -1562,12 +1584,8 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
}
void moveTasksToFullscreenStackLocked(ActivityStack fromStack, boolean onTop) {
- moveTasksToFullscreenStackLocked(fromStack, DEFAULT_DISPLAY, onTop);
- }
-
- void moveTasksToFullscreenStackLocked(ActivityStack fromStack, int toDisplayId, boolean onTop) {
mWindowManager.inSurfaceTransaction(() ->
- moveTasksToFullscreenStackInSurfaceTransaction(fromStack, toDisplayId, onTop));
+ moveTasksToFullscreenStackInSurfaceTransaction(fromStack, DEFAULT_DISPLAY, onTop));
}
void setSplitScreenResizing(boolean resizing) {
@@ -1630,7 +1648,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
try {
// Don't allow re-entry while resizing. E.g. due to docked stack detaching.
mAllowDockedStackResize = false;
- ActivityRecord r = stack.topRunningActivityLocked();
+ ActivityRecord r = stack.topRunningActivity();
stack.resize(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds,
!PRESERVE_WINDOWS, DEFER_RESUME);
@@ -1650,7 +1668,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
// static stacks need to be adjusted so they don't overlap with the docked stack.
// We get the bounds to use from window manager which has been adjusted for any
// screen controls and is also the same for all stacks.
- final ActivityDisplay display = mRootActivityContainer.getDefaultDisplay();
+ final DisplayContent display = mRootActivityContainer.getDefaultDisplay();
final Rect otherTaskRect = new Rect();
for (int i = display.getStackCount() - 1; i >= 0; --i) {
final ActivityStack current = display.getStackAt(i);
@@ -1731,7 +1749,6 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
}
private void removeStackInSurfaceTransaction(ActivityStack stack) {
- final ArrayList<Task> tasks = stack.getAllTasks();
if (stack.getWindowingMode() == WINDOWING_MODE_PINNED) {
/**
* Workaround: Force-stop all the activities in the pinned stack before we reparent them
@@ -1746,18 +1763,22 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
stack.ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS);
stack.mForceHidden = false;
activityIdleInternalLocked(null, false /* fromTimeout */,
- true /* processPausingActivites */, null /* configuration */);
+ true /* processPausingActivities */, null /* configuration */);
// Move all the tasks to the bottom of the fullscreen stack
moveTasksToFullscreenStackLocked(stack, !ON_TOP);
} else {
- for (int i = tasks.size() - 1; i >= 0; i--) {
- removeTaskByIdLocked(tasks.get(i).mTaskId, true /* killProcess */,
- REMOVE_FROM_RECENTS, "remove-stack");
- }
+ final PooledConsumer c = PooledLambda.obtainConsumer(
+ ActivityStackSupervisor::processRemoveTask, this, PooledLambda.__(Task.class));
+ stack.forAllTasks(c);
+ c.recycle();
}
}
+ private void processRemoveTask(Task task) {
+ removeTask(task, true /* killProcess */, REMOVE_FROM_RECENTS, "remove-stack");
+ }
+
/**
* Removes the stack associated with the given {@param stack}. If the {@param stack} is the
* pinned stack, then its tasks are not explicitly removed when the stack is destroyed, but
@@ -1775,24 +1796,28 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
* @param removeFromRecents Whether to also remove the task from recents.
* @return Returns true if the given task was found and removed.
*/
- boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents,
+ boolean removeTaskById(int taskId, boolean killProcess, boolean removeFromRecents,
String reason) {
final Task task =
mRootActivityContainer.anyTaskForId(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
if (task != null) {
- task.removeTaskActivitiesLocked(reason);
- cleanUpRemovedTaskLocked(task, killProcess, removeFromRecents);
- mService.getLockTaskController().clearLockedTask(task);
- mService.getTaskChangeNotificationController().notifyTaskStackChanged();
- if (task.isPersistable) {
- mService.notifyTaskPersisterLocked(null, true);
- }
+ removeTask(task, killProcess, removeFromRecents, reason);
return true;
}
Slog.w(TAG, "Request to remove task ignored for non-existent task " + taskId);
return false;
}
+ void removeTask(Task task, boolean killProcess, boolean removeFromRecents, String reason) {
+ task.removeTaskActivitiesLocked(reason);
+ cleanUpRemovedTaskLocked(task, killProcess, removeFromRecents);
+ mService.getLockTaskController().clearLockedTask(task);
+ mService.getTaskChangeNotificationController().notifyTaskStackChanged();
+ if (task.isPersistable) {
+ mService.notifyTaskPersisterLocked(null, true);
+ }
+ }
+
void cleanUpRemovedTaskLocked(Task task, boolean killProcess, boolean removeFromRecents) {
if (removeFromRecents) {
mRecentTasks.remove(task);
@@ -1899,7 +1924,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
if (wasTrimmed) {
// Task was trimmed from the recent tasks list -- remove the active task record as well
// since the user won't really be able to go back to it
- removeTaskByIdLocked(task.mTaskId, killProcess, false /* removeFromRecents */,
+ removeTaskById(task.mTaskId, killProcess, false /* removeFromRecents */,
"recent-task-trimmed");
}
task.removedFromRecents();
@@ -1909,7 +1934,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
* Returns the reparent target stack, creating the stack if necessary. This call also enforces
* the various checks on tasks that are going to be reparented from one stack to another.
*/
- // TODO: Look into changing users to this method to ActivityDisplay.resolveWindowingMode()
+ // TODO: Look into changing users to this method to DisplayContent.resolveWindowingMode()
ActivityStack getReparentTargetStack(Task task, ActivityStack stack, boolean toTop) {
final ActivityStack prevStack = task.getStack();
final int stackId = stack.mStackId;
@@ -2401,8 +2426,8 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
throw new IllegalStateException("Task resolved to incompatible display");
}
- final ActivityDisplay preferredDisplay =
- mRootActivityContainer.getActivityDisplay(preferredDisplayId);
+ final DisplayContent preferredDisplay =
+ mRootActivityContainer.getDisplayContent(preferredDisplayId);
final boolean singleTaskInstance = preferredDisplay != null
&& preferredDisplay.isSingleTaskInstance();
@@ -2502,8 +2527,8 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
void scheduleUpdatePictureInPictureModeIfNeeded(Task task, ActivityStack prevStack) {
final ActivityStack stack = task.getStack();
- if (prevStack == null || prevStack == stack
- || (!prevStack.inPinnedWindowingMode() && !stack.inPinnedWindowingMode())) {
+ if ((prevStack == null || (prevStack != stack
+ && !prevStack.inPinnedWindowingMode() && !stack.inPinnedWindowingMode()))) {
return;
}
@@ -2793,7 +2818,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks {
// call this at the end to make sure that tasks exists on the window manager side.
setResizingDuringAnimation(task);
- final ActivityDisplay display = task.getStack().getDisplay();
+ final DisplayContent display = task.getStack().getDisplay();
final ActivityStack topSecondaryStack =
display.getTopStackInWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
if (topSecondaryStack.isActivityTypeHome()) {
diff --git a/services/core/java/com/android/server/wm/ActivityStartController.java b/services/core/java/com/android/server/wm/ActivityStartController.java
index 695f58c22e7d..4c165df0ed4c 100644
--- a/services/core/java/com/android/server/wm/ActivityStartController.java
+++ b/services/core/java/com/android/server/wm/ActivityStartController.java
@@ -43,6 +43,7 @@ import android.os.Message;
import android.os.UserHandle;
import android.provider.Settings;
import android.util.Slog;
+import android.util.SparseArray;
import android.util.proto.ProtoOutputStream;
import android.view.RemoteAnimationAdapter;
@@ -180,8 +181,8 @@ public class ActivityStartController {
}
options.setLaunchDisplayId(displayId);
- final ActivityDisplay display =
- mService.mRootActivityContainer.getActivityDisplay(displayId);
+ final DisplayContent display =
+ mService.mRootActivityContainer.getDisplayContent(displayId);
// The home activity will be started later, defer resuming to avoid unneccerary operations
// (e.g. start home recursively) when creating home stack.
mSupervisor.beginDeferResume();
@@ -385,6 +386,7 @@ public class ActivityStartController {
} else {
callingPid = callingUid = -1;
}
+ final SparseArray<String> startingUidPkgs = new SparseArray<>();
final long origId = Binder.clearCallingIdentity();
try {
intents = ArrayUtils.filterNotNull(intents, Intent[]::new);
@@ -411,9 +413,14 @@ public class ActivityStartController {
callingUid, realCallingUid, UserHandle.USER_NULL));
aInfo = mService.mAmInternal.getActivityInfoForUser(aInfo, userId);
- if (aInfo != null && (aInfo.applicationInfo.privateFlags
- & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) {
- throw new IllegalArgumentException("FLAG_CANT_SAVE_STATE not supported here");
+ if (aInfo != null) {
+ if ((aInfo.applicationInfo.privateFlags
+ & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) {
+ throw new IllegalArgumentException(
+ "FLAG_CANT_SAVE_STATE not supported here");
+ }
+ startingUidPkgs.put(aInfo.applicationInfo.uid,
+ aInfo.applicationInfo.packageName);
}
final boolean top = i == intents.length - 1;
@@ -439,6 +446,16 @@ public class ActivityStartController {
.setOriginatingPendingIntent(originatingPendingIntent)
.setAllowBackgroundActivityStart(allowBackgroundActivityStart);
}
+ // Log if the activities to be started have different uids.
+ if (startingUidPkgs.size() > 1) {
+ final StringBuilder sb = new StringBuilder("startActivities: different apps [");
+ final int size = startingUidPkgs.size();
+ for (int i = 0; i < size; i++) {
+ sb.append(startingUidPkgs.valueAt(i)).append(i == size - 1 ? "]" : ", ");
+ }
+ sb.append(" from ").append(callingPackage);
+ Slog.wtf(TAG, sb.toString());
+ }
final ActivityRecord[] outActivity = new ActivityRecord[1];
// Lock the loop to ensure the activities launched in a sequence.
diff --git a/services/core/java/com/android/server/wm/ActivityStarter.java b/services/core/java/com/android/server/wm/ActivityStarter.java
index baa295518c2d..674955e20859 100644
--- a/services/core/java/com/android/server/wm/ActivityStarter.java
+++ b/services/core/java/com/android/server/wm/ActivityStarter.java
@@ -98,6 +98,7 @@ import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.AuxiliaryResolveInfo;
import android.content.pm.PackageManager;
+import android.content.pm.PackageManagerInternal;
import android.content.pm.ResolveInfo;
import android.content.pm.UserInfo;
import android.content.res.Configuration;
@@ -1309,9 +1310,11 @@ class ActivityStarter {
String resolvedType, int userId) {
if (auxiliaryResponse != null && auxiliaryResponse.needsPhaseTwo) {
// request phase two resolution
- mService.getPackageManagerInternalLocked().requestInstantAppResolutionPhaseTwo(
+ PackageManagerInternal packageManager = mService.getPackageManagerInternalLocked();
+ boolean isRequesterInstantApp = packageManager.isInstantApp(callingPackage, userId);
+ packageManager.requestInstantAppResolutionPhaseTwo(
auxiliaryResponse, originalIntent, resolvedType, callingPackage,
- verificationBundle, userId);
+ isRequesterInstantApp, verificationBundle, userId);
}
return InstantAppResolver.buildEphemeralInstallerIntent(
originalIntent,
@@ -1434,7 +1437,7 @@ class ActivityStarter {
// If there is no state change (e.g. a resumed activity is reparented to top of
// another display) to trigger a visibility/configuration checking, we have to
// update the configuration for changing to different display.
- final ActivityRecord currentTop = startedActivityStack.topRunningActivityLocked();
+ final ActivityRecord currentTop = startedActivityStack.topRunningActivity();
if (currentTop != null && currentTop.shouldUpdateConfigForDisplayChanged()) {
mRootActivityContainer.ensureVisibilityAndConfig(
currentTop, currentTop.getDisplayId(),
@@ -2307,7 +2310,7 @@ class ActivityStarter {
? null : focusStack.topRunningNonDelayedActivityLocked(mNotTop);
final Task topTask = curTop != null ? curTop.getTask() : null;
differentTopTask = topTask != intentActivity.getTask()
- || (focusStack != null && topTask != focusStack.topTask());
+ || (focusStack != null && topTask != focusStack.getTopMostTask());
} else {
// The existing task should always be different from those in other displays.
differentTopTask = true;
@@ -2371,7 +2374,7 @@ class ActivityStarter {
mMovedToFront = true;
}
- if (launchStack != null && launchStack.topTask() == null) {
+ if (launchStack != null && launchStack.getTopMostTask() == null) {
// The task does not need to be reparented to the launch stack. Remove the
// launch stack if there is no activity in it.
Slog.w(TAG, "Removing an empty stack: " + launchStack);
@@ -2588,7 +2591,7 @@ class ActivityStarter {
// If task's parent stack is not focused - use it during adjacent launch.
return parentStack;
} else {
- if (focusedStack != null && task == focusedStack.topTask()) {
+ if (focusedStack != null && task == focusedStack.getTopMostTask()) {
// If task is already on top of focused stack - use it. We don't want to move the
// existing focused task to adjacent stack, just deliver new intent in this case.
return focusedStack;
diff --git a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
index efd21ec83924..e02456e81822 100644
--- a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
+++ b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
@@ -698,7 +698,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
private final Runnable mUpdateOomAdjRunnable = new Runnable() {
@Override
- public void run() {
+ public void run() {
mAmInternal.updateOomAdj();
}
};
@@ -1591,7 +1591,8 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
// We should consolidate.
if (mController != null) {
// Find the first activity that is not finishing.
- final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
+ final ActivityRecord next =
+ r.getActivityStack().topRunningActivity(token, INVALID_TASK_ID);
if (next != null) {
// ask watcher if this is allowed
boolean resumeOK = true;
@@ -1628,11 +1629,9 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
// because we don't support returning them across task boundaries. Also, to
// keep backwards compatibility we remove the task from recents when finishing
// task with root activity.
- res = mStackSupervisor.removeTaskByIdLocked(tr.mTaskId, false /* killProcess */,
+ mStackSupervisor.removeTask(tr, false /*killProcess*/,
finishWithRootActivity, "finish-activity");
- if (!res) {
- Slog.i(TAG, "Removing task failed to finish activity");
- }
+ res = true;
// Explicitly dismissing the activity so reset its relaunch flag.
r.mRelaunchReason = RELAUNCH_REASON_NONE;
} else {
@@ -1901,7 +1900,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
public boolean isTopActivityImmersive() {
enforceNotIsolatedCaller("isTopActivityImmersive");
synchronized (mGlobalLock) {
- final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
+ final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
return (r != null) ? r.immersive : false;
}
}
@@ -1931,7 +1930,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
public int getFrontActivityScreenCompatMode() {
enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
synchronized (mGlobalLock) {
- final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
+ final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
if (r == null) {
return ActivityManager.COMPAT_MODE_UNKNOWN;
}
@@ -1945,7 +1944,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
"setFrontActivityScreenCompatMode");
ApplicationInfo ai;
synchronized (mGlobalLock) {
- final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
+ final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
if (r == null) {
Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
return;
@@ -2039,7 +2038,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
}
@Override
- public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
+ public int getDisplayId(IBinder activityToken) throws RemoteException {
synchronized (mGlobalLock) {
final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
@@ -2078,7 +2077,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
return;
}
- final ActivityRecord r = stack.topRunningActivityLocked();
+ final ActivityRecord r = stack.topRunningActivity();
if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
mRootActivityContainer.resumeFocusedStacksTopActivities();
}
@@ -2133,7 +2132,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
synchronized (mGlobalLock) {
final long ident = Binder.clearCallingIdentity();
try {
- return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
+ return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
"remove-task");
} finally {
Binder.restoreCallingIdentity(ident);
@@ -2207,7 +2206,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
final Task task = mRootActivityContainer.anyTaskForId(taskId);
if (task != null) {
- return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
+ return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
}
} finally {
Binder.restoreCallingIdentity(origId);
@@ -2918,7 +2917,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
}
final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
- if (stack == null || task != stack.topTask()) {
+ if (stack == null || task != stack.getTopMostTask()) {
throw new IllegalArgumentException("Invalid task, not in foreground");
}
@@ -4177,6 +4176,10 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
final Runnable enterPipRunnable = () -> {
synchronized (mGlobalLock) {
+ if (r.getParent() == null) {
+ Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
+ return;
+ }
// Only update the saved args from the args that are set
r.pictureInPictureArgs.copyOnlySet(params);
final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
@@ -4573,6 +4576,17 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
}
}
+ @Override
+ public void invalidateHomeTaskSnapshot(IBinder token) {
+ synchronized (mGlobalLock) {
+ final ActivityRecord r = ActivityRecord.isInStackLocked(token);
+ if (r == null || !r.isActivityTypeHome()) {
+ return;
+ }
+ mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
+ }
+ }
+
/** Return the user id of the last resumed activity. */
@Override
public @UserIdInt
@@ -4692,7 +4706,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
"registerRemoteAnimations");
definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
synchronized (mGlobalLock) {
- final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
+ final DisplayContent display = mRootActivityContainer.getDisplayContent(displayId);
if (display == null) {
Slog.e(TAG, "Couldn't find display with id: " + displayId);
return;
@@ -4900,8 +4914,8 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
"setDisplayToSingleTaskInstance");
final long origId = Binder.clearCallingIdentity();
try {
- final ActivityDisplay display =
- mRootActivityContainer.getActivityDisplayOrCreate(displayId);
+ final DisplayContent display =
+ mRootActivityContainer.getDisplayContentOrCreate(displayId);
if (display != null) {
display.setDisplayToSingleTaskInstance();
}
@@ -5199,8 +5213,8 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
boolean persistent, int userId, boolean deferResume) {
- final ActivityDisplay defaultDisplay =
- mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
+ final DisplayContent defaultDisplay =
+ mRootActivityContainer.getDisplayContent(DEFAULT_DISPLAY);
mTempConfig.setTo(getGlobalConfiguration());
final int changes = mTempConfig.updateFrom(values);
@@ -5787,7 +5801,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
// If the configuration changed, and the caller is not already
// in the process of starting an activity, then find the top
// activity to check if its configuration needs to change.
- starting = mainStack.topRunningActivityLocked();
+ starting = mainStack.topRunningActivity();
}
if (starting != null) {
@@ -6206,12 +6220,12 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
// We might change the visibilities here, so prepare an empty app transition which
// might be overridden later if we actually change visibilities.
- final ActivityDisplay activityDisplay =
- mRootActivityContainer.getActivityDisplay(displayId);
- if (activityDisplay == null) {
+ final DisplayContent displayContent =
+ mRootActivityContainer.getDisplayContent(displayId);
+ if (displayContent == null) {
return;
}
- final DisplayContent dc = activityDisplay.mDisplayContent;
+ final DisplayContent dc = displayContent.mDisplayContent;
final boolean wasTransitionSet =
dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
if (!wasTransitionSet) {
@@ -6558,9 +6572,9 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
return;
}
synchronized (mGlobalLock) {
- final ActivityDisplay activityDisplay =
- mRootActivityContainer.getActivityDisplay(displayId);
- if (activityDisplay == null) {
+ final DisplayContent displayContent =
+ mRootActivityContainer.getDisplayContent(displayId);
+ if (displayContent == null) {
// Call might come when display is not yet added or has been removed.
if (DEBUG_CONFIGURATION) {
Slog.w(TAG, "Trying to update display configuration for non-existing "
@@ -6577,7 +6591,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
return;
}
process.mIsImeProcess = true;
- process.registerDisplayConfigurationListenerLocked(activityDisplay);
+ process.registerDisplayConfigurationListenerLocked(displayContent);
}
}
diff --git a/services/core/java/com/android/server/wm/AppTaskImpl.java b/services/core/java/com/android/server/wm/AppTaskImpl.java
index 93a22caa2757..6d9584c50b9c 100644
--- a/services/core/java/com/android/server/wm/AppTaskImpl.java
+++ b/services/core/java/com/android/server/wm/AppTaskImpl.java
@@ -62,7 +62,7 @@ class AppTaskImpl extends IAppTask.Stub {
long origId = Binder.clearCallingIdentity();
try {
// We remove the task from recents to preserve backwards
- if (!mService.mStackSupervisor.removeTaskByIdLocked(mTaskId, false,
+ if (!mService.mStackSupervisor.removeTaskById(mTaskId, false,
REMOVE_FROM_RECENTS, "finish-and-remove-task")) {
throw new IllegalArgumentException("Unable to find task ID " + mTaskId);
}
diff --git a/services/core/java/com/android/server/wm/AppTransition.java b/services/core/java/com/android/server/wm/AppTransition.java
index e0c5fd055e7e..3a33a3d24433 100644
--- a/services/core/java/com/android/server/wm/AppTransition.java
+++ b/services/core/java/com/android/server/wm/AppTransition.java
@@ -130,6 +130,7 @@ import com.android.internal.R;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.DumpUtils.Dump;
import com.android.internal.util.function.pooled.PooledLambda;
+import com.android.internal.util.function.pooled.PooledPredicate;
import com.android.server.AttributeCache;
import com.android.server.protolog.common.ProtoLog;
import com.android.server.wm.animation.ClipRectLRAnimation;
@@ -1897,7 +1898,10 @@ public class AppTransition implements Dump {
for (int i = 0; i < specs.length; i++) {
AppTransitionAnimationSpec spec = specs[i];
if (spec != null) {
- final WindowContainer container = findTask(spec.taskId);
+ final PooledPredicate p = PooledLambda.obtainPredicate(
+ Task::isTaskId, PooledLambda.__(Task.class), spec.taskId);
+ final WindowContainer container = mDisplayContent.getTask(p);
+ p.recycle();
if (container == null) {
continue;
}
@@ -1918,21 +1922,6 @@ public class AppTransition implements Dump {
}
}
- private Task findTask(int taskId) {
- if (taskId < 0) {
- return null;
- }
- final ArrayList<Task> tasks = new ArrayList<>();
- mDisplayContent.forAllTasks(task -> {
- if (task.mTaskId == taskId) {
- tasks.add(task);
- return true;
- }
- return false;
- });
- return tasks.size() == 1 ? tasks.get(0) : null;
- }
-
void overridePendingAppTransitionMultiThumbFuture(
IAppTransitionAnimationSpecsFuture specsFuture, IRemoteCallback callback,
boolean scaleUp) {
diff --git a/services/core/java/com/android/server/wm/AppTransitionController.java b/services/core/java/com/android/server/wm/AppTransitionController.java
index d7f4b34ba56d..6ea0650df37a 100644
--- a/services/core/java/com/android/server/wm/AppTransitionController.java
+++ b/services/core/java/com/android/server/wm/AppTransitionController.java
@@ -48,6 +48,8 @@ import static com.android.server.wm.ActivityTaskManagerInternal.APP_TRANSITION_S
import static com.android.server.wm.ActivityTaskManagerInternal.APP_TRANSITION_WINDOWS_DRAWN;
import static com.android.server.wm.AppTransition.isKeyguardGoingAwayTransit;
import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_APP_TRANSITIONS;
+import static com.android.server.wm.WindowContainer.AnimationFlags.CHILDREN;
+import static com.android.server.wm.WindowContainer.AnimationFlags.PARENTS;
import static com.android.server.wm.WindowManagerDebugConfig.SHOW_LIGHT_TRANSACTIONS;
import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
@@ -61,6 +63,7 @@ import android.view.RemoteAnimationAdapter;
import android.view.RemoteAnimationDefinition;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
+import android.view.WindowManager.TransitionType;
import android.view.animation.Animation;
import com.android.internal.annotations.VisibleForTesting;
@@ -177,9 +180,15 @@ public class AppTransitionController {
final int layoutRedo;
mService.mSurfaceAnimationRunner.deferStartingAnimations();
try {
- handleClosingApps(transit, animLp, voiceInteraction);
- handleOpeningApps(transit, animLp, voiceInteraction);
- handleChangingApps(transit, animLp, voiceInteraction);
+ // TODO: Apply an app transition animation on TaskStack instead of ActivityRecord when
+ // appropriate.
+ applyAnimations(mDisplayContent.mClosingApps, transit, false /* visible */,
+ animLp, voiceInteraction);
+ applyAnimations(mDisplayContent.mOpeningApps, transit, true /* visible */,
+ animLp, voiceInteraction);
+ handleClosingApps();
+ handleOpeningApps();
+ handleChangingApps(transit);
appTransition.setLastAppTransition(transit, topOpeningApp,
topClosingApp, topChangingApp);
@@ -227,8 +236,8 @@ public class AppTransitionController {
return mainWindow != null ? mainWindow.mAttrs : null;
}
- RemoteAnimationAdapter getRemoteAnimationOverride(ActivityRecord animLpActivity, int transit,
- ArraySet<Integer> activityTypes) {
+ RemoteAnimationAdapter getRemoteAnimationOverride(ActivityRecord animLpActivity,
+ @TransitionType int transit, ArraySet<Integer> activityTypes) {
final RemoteAnimationDefinition definition = animLpActivity.getRemoteAnimationDefinition();
if (definition != null) {
final RemoteAnimationAdapter adapter = definition.getAdapter(transit, activityTypes);
@@ -246,8 +255,8 @@ public class AppTransitionController {
* Overrides the pending transition with the remote animation defined for the transition in the
* set of defined remote animations in the app window token.
*/
- private void overrideWithRemoteAnimationIfSet(ActivityRecord animLpActivity, int transit,
- ArraySet<Integer> activityTypes) {
+ private void overrideWithRemoteAnimationIfSet(ActivityRecord animLpActivity,
+ @TransitionType int transit, ArraySet<Integer> activityTypes) {
if (transit == TRANSIT_CRASHING_ACTIVITY_CLOSE) {
// The crash transition has higher priority than any involved remote animations.
return;
@@ -266,7 +275,7 @@ public class AppTransitionController {
/**
* @return The window token that determines the animation theme.
*/
- private ActivityRecord findAnimLayoutParamsToken(@WindowManager.TransitionType int transit,
+ private ActivityRecord findAnimLayoutParamsToken(@TransitionType int transit,
ArraySet<Integer> activityTypes) {
ActivityRecord result;
final ArraySet<ActivityRecord> closingApps = mDisplayContent.mClosingApps;
@@ -340,26 +349,60 @@ public class AppTransitionController {
return false;
}
- private void handleOpeningApps(int transit, LayoutParams animLp, boolean voiceInteraction) {
+ /**
+ * Apply an app transition animation on a set of {@link ActivityRecord}
+ *
+ * @param apps The list of apps to which an app transition animation applies.
+ * @param transit The current transition type.
+ * @param visible {@code true} if the apps becomes visible, {@code false} if the apps becomes
+ * invisible.
+ * @param animLp Layout parameters in which an app transition animation runs.
+ * @param voiceInteraction {@code true} if one of the apps in this transition belongs to a voice
+ * interaction session driving task.
+ */
+ private void applyAnimations(ArraySet<ActivityRecord> apps, @TransitionType int transit,
+ boolean visible, LayoutParams animLp, boolean voiceInteraction) {
+ final int appsCount = apps.size();
+ for (int i = 0; i < appsCount; i++) {
+ final ActivityRecord app = apps.valueAt(i);
+ if (transit != WindowManager.TRANSIT_UNSET && app.shouldApplyAnimation(visible)) {
+ ProtoLog.v(WM_DEBUG_APP_TRANSITIONS, "Changing app %s visible=%b performLayout=%b",
+ app, app.isVisible(), false);
+ if (!app.mUseTransferredAnimation) {
+ app.applyAnimation(animLp, transit, visible, voiceInteraction);
+ }
+ final WindowState window = app.findMainWindow();
+ final AccessibilityController accessibilityController =
+ app.mWmService.mAccessibilityController;
+ if (window != null && accessibilityController != null) {
+ accessibilityController.onAppWindowTransitionLocked(window, transit);
+ }
+ }
+ }
+ }
+
+ private void handleOpeningApps() {
final ArraySet<ActivityRecord> openingApps = mDisplayContent.mOpeningApps;
final int appsCount = openingApps.size();
+
for (int i = 0; i < appsCount; i++) {
- ActivityRecord wtoken = openingApps.valueAt(i);
- ProtoLog.v(WM_DEBUG_APP_TRANSITIONS, "Now opening app %s", wtoken);
+ final ActivityRecord app = openingApps.valueAt(i);
+ ProtoLog.v(WM_DEBUG_APP_TRANSITIONS, "Now opening app %s", app);
- if (!wtoken.commitVisibility(animLp, true, transit, false, voiceInteraction)) {
+ app.commitVisibility(true /* visible */, false /* performLayout */);
+ if (!app.isAnimating(PARENTS | CHILDREN)) {
// This token isn't going to be animating. Add it to the list of tokens to
// be notified of app transition complete since the notification will not be
// sent be the app window animator.
- mDisplayContent.mNoAnimationNotifyOnTransitionFinished.add(wtoken.token);
+ mDisplayContent.mNoAnimationNotifyOnTransitionFinished.add(app.token);
}
- wtoken.updateReportedVisibilityLocked();
- wtoken.waitingToShow = false;
+ app.updateReportedVisibilityLocked();
+ app.waitingToShow = false;
if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
">>> OPEN TRANSACTION handleAppTransitionReady()");
mService.openSurfaceTransaction();
try {
- wtoken.showAllWindowsLocked();
+ app.showAllWindowsLocked();
} finally {
mService.closeSurfaceTransaction("handleAppTransitionReady");
if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
@@ -367,41 +410,40 @@ public class AppTransitionController {
}
if (mDisplayContent.mAppTransition.isNextAppTransitionThumbnailUp()) {
- wtoken.attachThumbnailAnimation();
+ app.attachThumbnailAnimation();
} else if (mDisplayContent.mAppTransition.isNextAppTransitionOpenCrossProfileApps()) {
- wtoken.attachCrossProfileAppsThumbnailAnimation();
+ app.attachCrossProfileAppsThumbnailAnimation();
}
}
}
- private void handleClosingApps(int transit, LayoutParams animLp, boolean voiceInteraction) {
+ private void handleClosingApps() {
final ArraySet<ActivityRecord> closingApps = mDisplayContent.mClosingApps;
final int appsCount = closingApps.size();
+
for (int i = 0; i < appsCount; i++) {
- ActivityRecord wtoken = closingApps.valueAt(i);
+ final ActivityRecord app = closingApps.valueAt(i);
+ ProtoLog.v(WM_DEBUG_APP_TRANSITIONS, "Now closing app %s", app);
- ProtoLog.v(WM_DEBUG_APP_TRANSITIONS, "Now closing app %s", wtoken);
- // TODO: Do we need to add to mNoAnimationNotifyOnTransitionFinished like above if not
- // animating?
- wtoken.commitVisibility(animLp, false, transit, false, voiceInteraction);
- wtoken.updateReportedVisibilityLocked();
+ app.commitVisibility(false /* visible */, false /* performLayout */);
+ app.updateReportedVisibilityLocked();
// Force the allDrawn flag, because we want to start
// this guy's animations regardless of whether it's
// gotten drawn.
- wtoken.allDrawn = true;
+ app.allDrawn = true;
// Ensure that apps that are mid-starting are also scheduled to have their
// starting windows removed after the animation is complete
- if (wtoken.startingWindow != null && !wtoken.startingWindow.mAnimatingExit) {
- wtoken.removeStartingWindow();
+ if (app.startingWindow != null && !app.startingWindow.mAnimatingExit) {
+ app.removeStartingWindow();
}
if (mDisplayContent.mAppTransition.isNextAppTransitionThumbnailDown()) {
- wtoken.attachThumbnailAnimation();
+ app.attachThumbnailAnimation();
}
}
}
- private void handleChangingApps(int transit, LayoutParams animLp, boolean voiceInteraction) {
+ private void handleChangingApps(@TransitionType int transit) {
final ArraySet<ActivityRecord> apps = mDisplayContent.mChangingApps;
final int appsCount = apps.size();
for (int i = 0; i < appsCount; i++) {
@@ -419,7 +461,7 @@ public class AppTransitionController {
}
}
- private void handleNonAppWindowsInTransition(int transit, int flags) {
+ private void handleNonAppWindowsInTransition(@TransitionType int transit, int flags) {
if (transit == TRANSIT_KEYGUARD_GOING_AWAY) {
if ((flags & TRANSIT_FLAG_KEYGUARD_GOING_AWAY_WITH_WALLPAPER) != 0
&& (flags & TRANSIT_FLAG_KEYGUARD_GOING_AWAY_NO_ANIMATION) == 0
@@ -510,8 +552,8 @@ public class AppTransitionController {
return true;
}
- private int maybeUpdateTransitToWallpaper(int transit, boolean openingAppHasWallpaper,
- boolean closingAppHasWallpaper) {
+ private int maybeUpdateTransitToWallpaper(@TransitionType int transit,
+ boolean openingAppHasWallpaper, boolean closingAppHasWallpaper) {
// Given no app transition pass it through instead of a wallpaper transition.
// Never convert the crashing transition.
// Never update the transition for the wallpaper if we are just docking from recents
@@ -604,7 +646,7 @@ public class AppTransitionController {
* situation.
*/
@VisibleForTesting
- int maybeUpdateTransitToTranslucentAnim(int transit) {
+ int maybeUpdateTransitToTranslucentAnim(@TransitionType int transit) {
if (AppTransition.isChangeTransit(transit)) {
// There's no special animation to handle change animations with translucent apps
return transit;
@@ -644,7 +686,7 @@ public class AppTransitionController {
* to determine whether animations should be clipped to the task bounds instead of stack bounds.
*/
@VisibleForTesting
- boolean isTransitWithinTask(int transit, Task task) {
+ boolean isTransitWithinTask(@TransitionType int transit, Task task) {
if (task == null
|| !mDisplayContent.mChangingApps.isEmpty()) {
// if there is no task, then we can't constrain to the task.
diff --git a/services/core/java/com/android/server/wm/ConfigurationContainer.java b/services/core/java/com/android/server/wm/ConfigurationContainer.java
index bfa72e0eff78..dd3365c900d7 100644
--- a/services/core/java/com/android/server/wm/ConfigurationContainer.java
+++ b/services/core/java/com/android/server/wm/ConfigurationContainer.java
@@ -81,9 +81,6 @@ public abstract class ConfigurationContainer<E extends ConfigurationContainer> {
*/
private Configuration mFullConfiguration = new Configuration();
- /** The bit mask of the last override fields of full configuration. */
- private int mLastOverrideConfigurationChanges;
-
/**
* Contains merged override configuration settings from the top of the hierarchy down to this
* particular instance. It is different from {@link #mFullConfiguration} because it starts from
@@ -121,11 +118,6 @@ public abstract class ConfigurationContainer<E extends ConfigurationContainer> {
return mFullConfiguration;
}
- /** Returns the last changes from applying override configuration. */
- int getLastOverrideConfigurationChanges() {
- return mLastOverrideConfigurationChanges;
- }
-
/**
* Notify that parent config changed and we need to update full configuration.
* @see #mFullConfiguration
@@ -141,8 +133,7 @@ public abstract class ConfigurationContainer<E extends ConfigurationContainer> {
mResolvedTmpConfig.setTo(mResolvedOverrideConfiguration);
resolveOverrideConfiguration(newParentConfig);
mFullConfiguration.setTo(newParentConfig);
- mLastOverrideConfigurationChanges =
- mFullConfiguration.updateFrom(mResolvedOverrideConfiguration);
+ mFullConfiguration.updateFrom(mResolvedOverrideConfiguration);
if (!mResolvedTmpConfig.equals(mResolvedOverrideConfiguration)) {
onMergedOverrideConfigurationChanged();
// This depends on the assumption that change-listeners don't do
@@ -393,7 +384,6 @@ public abstract class ConfigurationContainer<E extends ConfigurationContainer> {
* When you call this function, make sure that the following functions are called as well to
* keep proper z-order.
* - {@Link DisplayContent#positionStackAt(POSITION_TOP, TaskStack)};
- * - {@Link ActivityDisplay#positionChildAtTop(ActivityStack)};
* */
public void setAlwaysOnTop(boolean alwaysOnTop) {
mRequestsTmpConfig.setTo(getRequestedOverrideConfiguration());
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index 8e126b56a736..4667eab1f55b 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -16,24 +16,33 @@
package com.android.server.wm;
+import static android.app.ActivityTaskManager.INVALID_STACK_ID;
import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
+import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
+import static android.app.WindowConfiguration.ROTATION_UNDEFINED;
+import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
+import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN_OR_SPLIT_SCREEN_SECONDARY;
import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
+import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
+import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_BEHIND;
import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSET;
import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER;
import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
+import static android.os.Build.VERSION_CODES.N;
import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
import static android.util.DisplayMetrics.DENSITY_DEFAULT;
import static android.view.Display.DEFAULT_DISPLAY;
import static android.view.Display.FLAG_PRIVATE;
import static android.view.Display.FLAG_SHOULD_SHOW_SYSTEM_DECORATIONS;
import static android.view.Display.INVALID_DISPLAY;
+import static android.view.Display.REMOVE_MODE_DESTROY_CONTENT;
import static android.view.InsetsState.ITYPE_IME;
import static android.view.InsetsState.ITYPE_LEFT_GESTURES;
import static android.view.InsetsState.ITYPE_RIGHT_GESTURES;
@@ -55,9 +64,8 @@ import static android.view.WindowManager.LayoutParams.FLAG_SECURE;
import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
import static android.view.WindowManager.LayoutParams.FLAG_SPLIT_TOUCH;
import static android.view.WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
-import static android.view.WindowManager.LayoutParams.NEEDS_MENU_SET_TRUE;
-import static android.view.WindowManager.LayoutParams.NEEDS_MENU_UNSET;
import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_KEYGUARD;
+import static android.view.WindowManager.LayoutParams.TYPE_ACCESSIBILITY_MAGNIFICATION_OVERLAY;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
import static android.view.WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
import static android.view.WindowManager.LayoutParams.TYPE_BOOT_PROGRESS;
@@ -76,10 +84,20 @@ import static android.view.WindowManager.TRANSIT_KEYGUARD_UNOCCLUDE;
import static android.view.WindowManager.TRANSIT_TASK_OPEN;
import static android.view.WindowManager.TRANSIT_TASK_TO_FRONT;
+import static com.android.server.am.ActivityDisplayProto.DISPLAY;
+import static com.android.server.am.ActivityDisplayProto.FOCUSED_STACK_ID;
+import static com.android.server.am.ActivityDisplayProto.RESUMED_ACTIVITY;
+import static com.android.server.am.ActivityDisplayProto.SINGLE_TASK_INSTANCE;
import static com.android.server.policy.WindowManagerPolicy.FINISH_LAYOUT_REDO_ANIM;
import static com.android.server.policy.WindowManagerPolicy.FINISH_LAYOUT_REDO_CONFIG;
import static com.android.server.policy.WindowManagerPolicy.FINISH_LAYOUT_REDO_LAYOUT;
import static com.android.server.policy.WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER;
+import static com.android.server.wm.ActivityStack.ActivityState.RESUMED;
+import static com.android.server.wm.ActivityStack.STACK_VISIBILITY_VISIBLE;
+import static com.android.server.wm.ActivityStackSupervisor.TAG_TASKS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STATES;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
import static com.android.server.wm.DisplayContentProto.ABOVE_APP_WINDOWS;
import static com.android.server.wm.DisplayContentProto.APP_TRANSITION;
import static com.android.server.wm.DisplayContentProto.BELOW_APP_WINDOWS;
@@ -93,6 +111,7 @@ import static com.android.server.wm.DisplayContentProto.FOCUSED_APP;
import static com.android.server.wm.DisplayContentProto.ID;
import static com.android.server.wm.DisplayContentProto.IME_WINDOWS;
import static com.android.server.wm.DisplayContentProto.OPENING_APPS;
+import static com.android.server.wm.DisplayContentProto.OVERLAY_WINDOWS;
import static com.android.server.wm.DisplayContentProto.PINNED_STACK_CONTROLLER;
import static com.android.server.wm.DisplayContentProto.ROTATION;
import static com.android.server.wm.DisplayContentProto.SCREEN_ROTATION_ANIMATION;
@@ -105,6 +124,7 @@ import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_FOCUS_LIGHT;
import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ORIENTATION;
import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_SCREEN_ON;
import static com.android.server.wm.ProtoLogGroup.WM_SHOW_TRANSACTIONS;
+import static com.android.server.wm.RootActivityContainer.TAG_STATES;
import static com.android.server.wm.WindowContainer.AnimationFlags.PARENTS;
import static com.android.server.wm.WindowContainer.AnimationFlags.TRANSITION;
import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_DISPLAY;
@@ -124,6 +144,7 @@ import static com.android.server.wm.WindowManagerService.H.UPDATE_DOCKED_STACK_D
import static com.android.server.wm.WindowManagerService.H.WINDOW_HIDE_TIMEOUT;
import static com.android.server.wm.WindowManagerService.LAYOUT_REPEAT_THRESHOLD;
import static com.android.server.wm.WindowManagerService.SEAMLESS_ROTATION_TIMEOUT_DURATION;
+import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_NORMAL;
import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_PLACING_SURFACES;
import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_REMOVING_FOCUS;
import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_WILL_ASSIGN_LAYERS;
@@ -141,6 +162,11 @@ import android.animation.AnimationHandler;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.app.ActivityManager;
+import android.app.ActivityManagerInternal;
+import android.app.ActivityOptions;
+import android.app.WindowConfiguration;
+import android.content.pm.ActivityInfo;
import android.content.pm.ActivityInfo.ScreenOrientation;
import android.content.res.CompatibilityInfo;
import android.content.res.Configuration;
@@ -158,15 +184,19 @@ import android.os.Binder;
import android.os.Debug;
import android.os.Handler;
import android.os.IBinder;
+import android.os.Message;
import android.os.Process;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.Trace;
import android.os.UserHandle;
+import android.provider.Settings;
import android.util.ArraySet;
import android.util.DisplayMetrics;
+import android.util.IntArray;
import android.util.Slog;
+import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.util.proto.ProtoOutputStream;
import android.view.Display;
@@ -174,6 +204,7 @@ import android.view.DisplayCutout;
import android.view.DisplayInfo;
import android.view.Gravity;
import android.view.ISystemGestureExclusionListener;
+import android.view.IWindow;
import android.view.InputChannel;
import android.view.InputDevice;
import android.view.InputWindowHandle;
@@ -194,7 +225,9 @@ import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.internal.util.ToBooleanFunction;
import com.android.internal.util.function.TriConsumer;
import com.android.internal.util.function.pooled.PooledConsumer;
+import com.android.internal.util.function.pooled.PooledFunction;
import com.android.internal.util.function.pooled.PooledLambda;
+import com.android.internal.util.function.pooled.PooledPredicate;
import com.android.server.AnimationThread;
import com.android.server.policy.WindowManagerPolicy;
import com.android.server.protolog.common.ProtoLog;
@@ -222,6 +255,7 @@ import java.util.function.Predicate;
class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowContainer>
implements WindowManagerPolicy.DisplayContentInfo {
private static final String TAG = TAG_WITH_CLASS_NAME ? "DisplayContent" : TAG_WM;
+ private static final String TAG_STACK = TAG + POSTFIX_STACK;
/** The default scaling mode that scales content automatically. */
static final int FORCE_SCALING_MODE_AUTO = 0;
@@ -238,9 +272,23 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
ActivityTaskManagerService mAtmService;
/** Unique identifier of this display. */
- private final int mDisplayId;
+ final int mDisplayId;
- /** The containers below are the only child containers the display can have. */
+ /**
+ * Most surfaces will be a child of this window. There are some special layers and windows
+ * which are always on top of others and omitted from Screen-Magnification, for example the
+ * strict mode flash or the magnification overlay itself. Those layers will be children of
+ * {@link #mOverlayContainers} where mWindowContainers contains everything else.
+ */
+ private final WindowContainers mWindowContainers =
+ new WindowContainers("mWindowContainers", mWmService);
+
+ // Contains some special windows which are always on top of others and omitted from
+ // Screen-Magnification, for example the WindowMagnification windows.
+ private final NonAppWindowContainers mOverlayContainers =
+ new NonAppWindowContainers("mOverlayContainers", mWmService);
+
+ /** The containers below are the only child containers {@link #mWindowContainers} can have. */
// Contains all window containers that are related to apps (Activities)
private final TaskStackContainers mTaskStackContainers = new TaskStackContainers(mWmService);
// Contains all non-app window containers that should be displayed above the app containers
@@ -260,7 +308,6 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
private WindowState mTmpWindow;
private WindowState mTmpWindow2;
- private boolean mTmpRecoveringMemory;
private boolean mUpdateImeTarget;
private boolean mTmpInitial;
private int mMaxUiWidth;
@@ -314,8 +361,8 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
* @see WindowManagerService#setForcedDisplayScalingMode(int, int)
*/
boolean mDisplayScalingDisabled;
+ final Display mDisplay;
private final DisplayInfo mDisplayInfo = new DisplayInfo();
- private final Display mDisplay;
private final DisplayMetrics mDisplayMetrics = new DisplayMetrics();
private final DisplayPolicy mDisplayPolicy;
private final DisplayRotation mDisplayRotation;
@@ -346,6 +393,9 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
/** The desired scaling factor for compatible apps. */
float mCompatibleScreenScale;
+ /** @see #getCurrentOverrideConfigurationChanges */
+ private int mCurrentOverrideConfigurationChanges;
+
/**
* Orientation forced by some window. If there is no visible window that specifies orientation
* it is set to {@link android.content.pm.ActivityInfo#SCREEN_ORIENTATION_UNSPECIFIED}.
@@ -490,20 +540,6 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
private ScreenRotationAnimation mScreenRotationAnimation;
/**
- * We organize all top-level Surfaces in to the following layers.
- * mOverlayLayer contains a few Surfaces which are always on top of others
- * and omitted from Screen-Magnification, for example the strict mode flash or
- * the magnification overlay itself.
- * {@link #mWindowingLayer} contains everything else.
- */
- private SurfaceControl mOverlayLayer;
-
- /**
- * See {@link #mOverlayLayer}
- */
- private SurfaceControl mWindowingLayer;
-
- /**
* Sequence number for the current layout pass.
*/
int mLayoutSeq = 0;
@@ -560,6 +596,74 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
/** Corner radius that windows should have in order to match the display. */
private final float mWindowCornerRadius;
+ private final SparseArray<ShellRoot> mShellRoots = new SparseArray<>();
+
+ /**
+ * Counter for next free stack ID to use for dynamic activity stacks. Unique across displays.
+ */
+ private static int sNextFreeStackId = 0;
+
+ private RootActivityContainer mRootActivityContainer;
+
+ /**
+ * All of the stacks on this display. Order matters, topmost stack is in front of all other
+ * stacks, bottommost behind. Accessed directly by ActivityManager package classes. Any calls
+ * changing the list should also call {@link #onStackOrderChanged()}.
+ */
+ private ArrayList<OnStackOrderChangedListener> mStackOrderChangedCallbacks = new ArrayList<>();
+
+ /** Array of all UIDs that are present on the display. */
+ private IntArray mDisplayAccessUIDs = new IntArray();
+
+ /** All tokens used to put activities on this stack to sleep (including mOffToken) */
+ final ArrayList<ActivityTaskManagerInternal.SleepToken> mAllSleepTokens = new ArrayList<>();
+ /** The token acquired by ActivityStackSupervisor to put stacks on the display to sleep */
+ ActivityTaskManagerInternal.SleepToken mOffToken;
+
+ private boolean mSleeping;
+
+ /** We started the process of removing the display from the system. */
+ private boolean mRemoving;
+
+ /**
+ * The display is removed from the system and we are just waiting for all activities on it to be
+ * finished before removing this object.
+ */
+ private boolean mRemoved;
+
+ /** The display can only contain one task. */
+ private boolean mSingleTaskInstance;
+
+ /**
+ * Non-null if the last size compatibility mode activity is using non-native screen
+ * configuration. The activity is not able to put in multi-window mode, so it exists only one
+ * per display.
+ */
+ private ActivityRecord mLastCompatModeActivity;
+
+ /**
+ * A focusable stack that is purposely to be positioned at the top. Although the stack may not
+ * have the topmost index, it is used as a preferred candidate to prevent being unable to resume
+ * target stack properly when there are other focusable always-on-top stacks.
+ */
+ private ActivityStack mPreferredTopFocusableStack;
+
+ /**
+ * If this is the same as {@link #getFocusedStack} then the activity on the top of the focused
+ * stack has been resumed. If stacks are changing position this will hold the old stack until
+ * the new stack becomes resumed after which it will be set to current focused stack.
+ */
+ private ActivityStack mLastFocusedStack;
+
+ // Used in updating the display size
+ private Point mTmpDisplaySize = new Point();
+
+ // Used in updating override configurations
+ private final Configuration mTempConfig = new Configuration();
+
+ private final RootActivityContainer.FindTaskResult
+ mTmpFindTaskResult = new RootActivityContainer.FindTaskResult();
+
private final Consumer<WindowState> mUpdateWindowsForAnimator = w -> {
WindowStateAnimator winAnimator = w.mWinAnimator;
final ActivityRecord activity = w.mActivityRecord;
@@ -839,17 +943,18 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
* Create new {@link DisplayContent} instance, add itself to the root window container and
* initialize direct children.
* @param display May not be null.
- * @param service You know.
- * @param activityDisplay The ActivityDisplay for the display container.
+ * @param root {@link RootActivityContainer}
*/
- DisplayContent(Display display, WindowManagerService service) {
- super(service);
- if (service.mRoot.getDisplayContent(display.getDisplayId()) != null) {
+ DisplayContent(Display display, RootActivityContainer root) {
+ super(root.mWindowManager);
+ if (mWmService.mRoot.getDisplayContent(display.getDisplayId()) != null) {
throw new IllegalArgumentException("Display with ID=" + display.getDisplayId()
- + " already exists=" + service.mRoot.getDisplayContent(display.getDisplayId())
+ + " already exists="
+ + mWmService.mRoot.getDisplayContent(display.getDisplayId())
+ " new=" + display);
}
+ mRootActivityContainer = root;
mAtmService = mWmService.mAtmService;
mDisplay = display;
mDisplayId = display.getDisplayId();
@@ -863,13 +968,13 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
calculateDisplayCutoutForRotation(mDisplayInfo.rotation));
initializeDisplayBaseInfo();
- mAppTransition = new AppTransition(service.mContext, service, this);
- mAppTransition.registerListenerLocked(service.mActivityManagerAppTransitionNotifier);
- mAppTransitionController = new AppTransitionController(service, this);
- mUnknownAppVisibilityController = new UnknownAppVisibilityController(service, this);
+ mAppTransition = new AppTransition(mWmService.mContext, mWmService, this);
+ mAppTransition.registerListenerLocked(mWmService.mActivityManagerAppTransitionNotifier);
+ mAppTransitionController = new AppTransitionController(mWmService, this);
+ mUnknownAppVisibilityController = new UnknownAppVisibilityController(mWmService, this);
AnimationHandler animationHandler = new AnimationHandler();
- mBoundsAnimationController = new BoundsAnimationController(service.mContext,
+ mBoundsAnimationController = new BoundsAnimationController(mWmService.mContext,
mAppTransition, AnimationThread.getHandler(), animationHandler);
final InputChannel inputChannel = mWmService.mInputManager.monitorInput(
@@ -887,9 +992,9 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
mWmService.mAtmService.getRecentTasks().getInputListener());
}
- mDisplayPolicy = new DisplayPolicy(service, this);
- mDisplayRotation = new DisplayRotation(service, this);
- mCloseToSquareMaxAspectRatio = service.mContext.getResources().getFloat(
+ mDisplayPolicy = new DisplayPolicy(mWmService, this);
+ mDisplayRotation = new DisplayRotation(mWmService, this);
+ mCloseToSquareMaxAspectRatio = mWmService.mContext.getResources().getFloat(
com.android.internal.R.dimen.config_closeToSquareDisplayMaxAspectRatio);
if (isDefaultDisplay) {
// The policy may be invoked right after here, so it requires the necessary default
@@ -903,31 +1008,26 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
mDisplayPolicy.systemReady();
}
mWindowCornerRadius = mDisplayPolicy.getWindowCornerRadius();
- mDividerControllerLocked = new DockedStackDividerController(service, this);
- mPinnedStackControllerLocked = new PinnedStackController(service, this);
+ mDividerControllerLocked = new DockedStackDividerController(mWmService, this);
+ mPinnedStackControllerLocked = new PinnedStackController(mWmService, this);
final SurfaceControl.Builder b = mWmService.makeSurfaceBuilder(mSession)
.setOpaque(true)
.setContainerLayer();
mSurfaceControl = b.setName("Root").setContainerLayer().build();
- mWindowingLayer = b.setName("Display Windows").setParent(mSurfaceControl).build();
- mOverlayLayer = b.setName("Display Overlays").setParent(mSurfaceControl).build();
getPendingTransaction()
.setLayer(mSurfaceControl, 0)
.setLayerStack(mSurfaceControl, mDisplayId)
- .show(mSurfaceControl)
- .setLayer(mWindowingLayer, 0)
- .show(mWindowingLayer)
- .setLayer(mOverlayLayer, 1)
- .show(mOverlayLayer);
+ .show(mSurfaceControl);
getPendingTransaction().apply();
// These are the only direct children we should ever have and they are permanent.
- super.addChild(mBelowAppWindowsContainers, null);
- super.addChild(mTaskStackContainers, null);
- super.addChild(mAboveAppWindowsContainers, null);
- super.addChild(mImeWindowsContainers, null);
+ super.addChild(mWindowContainers, null);
+ super.addChild(mOverlayContainers, null);
+
+ mWindowContainers.addChildren();
+
// Sets the display content for the children.
onDisplayChanged(this);
@@ -939,9 +1039,23 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
mDisplayReady = true;
mWmService.mAnimator.addDisplayLocked(mDisplayId);
- mInputMonitor = new InputMonitor(service, mDisplayId);
+ mInputMonitor = new InputMonitor(mWmService, mDisplayId);
mInsetsStateController = new InsetsStateController(this);
mInsetsPolicy = new InsetsPolicy(mInsetsStateController, this);
+
+ if (DEBUG_DISPLAY) Slog.v(TAG_WM, "Adding display=" + display);
+
+ mWmService.mDisplayWindowSettings.applySettingsToDisplayLocked(this);
+
+ if (mWmService.mDisplayManagerInternal != null) {
+ mWmService.mDisplayManagerInternal
+ .setDisplayInfoOverrideFromWindowManager(mDisplayId, getDisplayInfo());
+ configureDisplayPolicy();
+ }
+
+ reconfigureDisplayLocked();
+ onRequestedOverrideConfigurationChanged(getRequestedOverrideConfiguration());
+ mWmService.mDisplayNotificationController.dispatchDisplayAdded(this);
}
boolean isReady() {
@@ -1001,6 +1115,9 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
case TYPE_INPUT_METHOD_DIALOG:
mImeWindowsContainers.addChild(token);
break;
+ case TYPE_ACCESSIBILITY_MAGNIFICATION_OVERLAY:
+ mOverlayContainers.addChild(token);
+ break;
default:
mAboveAppWindowsContainers.addChild(token);
break;
@@ -1016,6 +1133,37 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
return token;
}
+ SurfaceControl addShellRoot(@NonNull IWindow client, int windowType) {
+ ShellRoot root = mShellRoots.get(windowType);
+ if (root != null) {
+ if (root.getClient() == client) {
+ return root.getSurfaceControl();
+ }
+ root.clear();
+ mShellRoots.remove(windowType);
+ }
+ root = new ShellRoot(client, this, windowType);
+ SurfaceControl rootLeash = root.getSurfaceControl();
+ if (rootLeash == null) {
+ // Root didn't finish initializing, so don't add it.
+ root.clear();
+ return null;
+ }
+ mShellRoots.put(windowType, root);
+ SurfaceControl out = new SurfaceControl();
+ out.copyFrom(rootLeash);
+ return out;
+ }
+
+ void removeShellRoot(int windowType) {
+ ShellRoot root = mShellRoots.get(windowType);
+ if (root == null) {
+ return;
+ }
+ root.clear();
+ mShellRoots.remove(windowType);
+ }
+
/** Changes the display the input window token is housed on to this one. */
void reParentWindowToken(WindowToken token) {
final DisplayContent prevDc = token.getDisplayContent();
@@ -1153,9 +1301,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
if (mDisplayRotation.isWaitingForRemoteRotation()) {
return;
}
- // TODO(display-merge): Remove cast
- final boolean configUpdated =
- ((ActivityDisplay) this).updateDisplayOverrideConfigurationLocked();
+ final boolean configUpdated = updateDisplayOverrideConfigurationLocked();
if (configUpdated) {
return;
}
@@ -1186,9 +1332,8 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
if (handled && requestingContainer instanceof ActivityRecord) {
final ActivityRecord activityRecord = (ActivityRecord) requestingContainer;
- // TODO(display-merge): Remove cast
- final boolean kept = ((ActivityDisplay) this).updateDisplayOverrideConfigurationLocked(
- config, activityRecord, false /* deferResume */, null /* result */);
+ final boolean kept = updateDisplayOverrideConfigurationLocked(config, activityRecord,
+ false /* deferResume */, null /* result */);
activityRecord.frozenBeforeDestroy = true;
if (!kept) {
mWmService.mAtmService.mRootActivityContainer.resumeFocusedStacksTopActivities();
@@ -1196,9 +1341,8 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
} else {
// We have a new configuration to push so we need to update ATMS for now.
// TODO: Clean up display configuration push between ATMS and WMS after unification.
- // TODO(display-merge): Remove cast
- ((ActivityDisplay) this.mDisplayContent).updateDisplayOverrideConfigurationLocked(
- config, null /* starting */, false /* deferResume */, null);
+ updateDisplayOverrideConfigurationLocked(config, null /* starting */,
+ false /* deferResume */, null);
}
return handled;
}
@@ -1867,8 +2011,21 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
mTaskStackContainers.onStackWindowingModeChanged(stack);
}
+ /**
+ * The value is only valid in the scope {@link #onRequestedOverrideConfigurationChanged} of the
+ * changing hierarchy and the {@link #onConfigurationChanged} of its children.
+ *
+ * @return The current changes ({@link android.content.pm.ActivityInfo.Config}) of requested
+ * override configuration.
+ */
+ int getCurrentOverrideConfigurationChanges() {
+ return mCurrentOverrideConfigurationChanges;
+ }
+
@Override
public void onConfigurationChanged(Configuration newParentConfig) {
+ // update resources before cascade so that docked/pinned stacks use the correct info
+ preOnConfigurationChanged();
final int lastOrientation = getConfiguration().orientation;
super.onConfigurationChanged(newParentConfig);
if (mDisplayPolicy != null) {
@@ -1878,8 +2035,8 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
if (lastOrientation != getConfiguration().orientation) {
getMetricsLogger().write(
new LogMaker(MetricsEvent.ACTION_PHONE_ORIENTATION_CHANGED)
- .setSubtype(getConfiguration().orientation)
- .addTaggedData(MetricsEvent.FIELD_DISPLAY_ID, getDisplayId()));
+ .setSubtype(getConfiguration().orientation)
+ .addTaggedData(MetricsEvent.FIELD_DISPLAY_ID, getDisplayId()));
}
// If there was no pinned stack, we still need to notify the controller of the display info
@@ -1892,8 +2049,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
/**
* Updates the resources used by docked/pinned controllers. This needs to be called at the
* beginning of a configuration update cascade since the metrics from these resources are used
- * for bounds calculations. Since ActivityDisplay initiates the configuration update, this
- * should be called from there instead of DisplayContent's onConfigurationChanged.
+ * for bounds calculations.
*/
void preOnConfigurationChanged() {
final DockedStackDividerController dividerController = getDockedDividerController();
@@ -1936,49 +2092,6 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
setWindowingMode(windowingMode);
}
- /**
- * In split-screen mode we process the IME containers above the docked divider
- * rather than directly above their target.
- */
- private boolean skipTraverseChild(WindowContainer child) {
- if (child == mImeWindowsContainers && mInputMethodTarget != null
- && !hasSplitScreenPrimaryStack()) {
- return true;
- }
- return false;
- }
-
- @Override
- boolean forAllWindows(ToBooleanFunction<WindowState> callback, boolean traverseTopToBottom) {
- // Special handling so we can process IME windows with #forAllImeWindows above their IME
- // target, or here in order if there isn't an IME target.
- if (traverseTopToBottom) {
- for (int i = mChildren.size() - 1; i >= 0; --i) {
- final DisplayChildWindowContainer child = mChildren.get(i);
- if (skipTraverseChild(child)) {
- continue;
- }
-
- if (child.forAllWindows(callback, traverseTopToBottom)) {
- return true;
- }
- }
- } else {
- final int count = mChildren.size();
- for (int i = 0; i < count; i++) {
- final DisplayChildWindowContainer child = mChildren.get(i);
- if (skipTraverseChild(child)) {
- continue;
- }
-
- if (child.forAllWindows(callback, traverseTopToBottom)) {
- return true;
- }
- }
- }
- return false;
- }
-
boolean forAllImeWindows(ToBooleanFunction<WindowState> callback, boolean traverseTopToBottom) {
return mImeWindowsContainers.forAllWindows(callback, traverseTopToBottom);
}
@@ -2000,7 +2113,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
if (mLastWindowForcedOrientation != SCREEN_ORIENTATION_UNSPECIFIED) {
ProtoLog.v(WM_DEBUG_ORIENTATION,
"Display id=%d is frozen, return %d", mDisplayId,
- mLastWindowForcedOrientation);
+ mLastWindowForcedOrientation);
// If the display is frozen, some activities may be in the middle of restarting, and
// thus have removed their old window. If the window has the flag to hide the lock
// screen, then the lock screen can re-appear and inflict its own orientation on us.
@@ -2014,7 +2127,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
// momentarily unavailable due to activity relaunch.
ProtoLog.v(WM_DEBUG_ORIENTATION,
"Display id=%d is frozen while keyguard locked, return %d",
- mDisplayId, getLastOrientation());
+ mDisplayId, getLastOrientation());
return getLastOrientation();
}
} else {
@@ -2268,7 +2381,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
forAllWindows(fn, true /* traverseTopToBottom */);
fn.recycle();
return FIRST_APPLICATION_WINDOW <= targetWindowType[0]
- && targetWindowType[0] <= LAST_APPLICATION_WINDOW;
+ && targetWindowType[0] <= LAST_APPLICATION_WINDOW;
}
/**
@@ -2277,19 +2390,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
*/
Task findTaskForResizePoint(int x, int y) {
final int delta = dipToPixel(RESIZE_HANDLE_WIDTH_IN_DP, mDisplayMetrics);
- mTmpTaskForResizePointSearchResult.reset();
- for (int stackNdx = mTaskStackContainers.getChildCount() - 1; stackNdx >= 0; --stackNdx) {
- final ActivityStack stack = mTaskStackContainers.getChildAt(stackNdx);
- if (!stack.getWindowConfiguration().canResizeTask()) {
- return null;
- }
-
- stack.findTaskForResizePoint(x, y, delta, mTmpTaskForResizePointSearchResult);
- if (mTmpTaskForResizePointSearchResult.searchDone) {
- return mTmpTaskForResizePointSearchResult.taskForResize;
- }
- }
- return null;
+ return mTmpTaskForResizePointSearchResult.process(mTaskStackContainers, x, y, delta);
}
void updateTouchExcludeRegion() {
@@ -2299,13 +2400,15 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
} else {
mTouchExcludeRegion.set(mBaseDisplayRect);
final int delta = dipToPixel(RESIZE_HANDLE_WIDTH_IN_DP, mDisplayMetrics);
+ mTmpRect.setEmpty();
mTmpRect2.setEmpty();
- for (int stackNdx = mTaskStackContainers.getChildCount() - 1; stackNdx >= 0;
- --stackNdx) {
- final ActivityStack stack = mTaskStackContainers.getChildAt(stackNdx);
- stack.setTouchExcludeRegion(focusedTask, delta, mTouchExcludeRegion,
- mDisplayFrames.mContent, mTmpRect2);
- }
+
+ final PooledConsumer c = PooledLambda.obtainConsumer(
+ DisplayContent::processTaskForTouchExcludeRegion, this,
+ PooledLambda.__(Task.class), focusedTask, delta);
+ mTaskStackContainers.forAllTasks(c);
+ c.recycle();
+
// If we removed the focused task above, add it back and only leave its
// outside touch area in the exclusion. TapDetector is not interested in
// any touch inside the focused task itself.
@@ -2335,12 +2438,56 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
mTapDetector.setTouchExcludeRegion(mTouchExcludeRegion);
}
+ private void processTaskForTouchExcludeRegion(Task task, Task focusedTask, int delta) {
+ final ActivityRecord topVisibleActivity = task.getTopVisibleActivity();
+
+ if (topVisibleActivity == null || !topVisibleActivity.hasContentToDisplay()) {
+ return;
+ }
+
+ // Exclusion region is the region that TapDetector doesn't care about.
+ // Here we want to remove all non-focused tasks from the exclusion region.
+ // We also remove the outside touch area for resizing for all freeform
+ // tasks (including the focused).
+ // We save the focused task region once we find it, and add it back at the end.
+ // If the task is home stack and it is resizable in the minimized state, we want to
+ // exclude the docked stack from touch so we need the entire screen area and not just a
+ // small portion which the home stack currently is resized to.
+ if (task.isActivityTypeHome() && task.getStack().isMinimizedDockAndHomeStackResizable()) {
+ mDisplayContent.getBounds(mTmpRect);
+ } else {
+ task.getDimBounds(mTmpRect);
+ }
+
+ if (task == focusedTask) {
+ // Add the focused task rect back into the exclude region once we are done
+ // processing stacks.
+ mTmpRect2.set(mTmpRect);
+ }
+
+ final boolean isFreeformed = task.inFreeformWindowingMode();
+ if (task != focusedTask || isFreeformed) {
+ if (isFreeformed) {
+ // If the task is freeformed, enlarge the area to account for outside
+ // touch area for resize.
+ mTmpRect.inset(-delta, -delta);
+ // Intersect with display content rect. If we have system decor (status bar/
+ // navigation bar), we want to exclude that from the tap detection.
+ // Otherwise, if the app is partially placed under some system button (eg.
+ // Recents, Home), pressing that button would cause a full series of
+ // unwanted transfer focus/resume/pause, before we could go home.
+ mTmpRect.intersect(mDisplayFrames.mContent);
+ }
+ mTouchExcludeRegion.op(mTmpRect, Region.Op.DIFFERENCE);
+ }
+ }
+
/**
* Union the region with all the tap exclude region provided by windows on this display.
*
* @param inOutRegion The region to be amended.
*/
- void amendWindowTapExcludeRegion(Region inOutRegion) {
+ private void amendWindowTapExcludeRegion(Region inOutRegion) {
for (int i = mTapExcludeProvidingWindows.size() - 1; i >= 0; i--) {
final WindowState win = mTapExcludeProvidingWindows.valueAt(i);
win.amendTapExcludeRegion(inOutRegion);
@@ -2383,12 +2530,8 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
mPointerEventDispatcher.dispose();
setRotationAnimation(null);
mWmService.mAnimator.removeDisplayLocked(mDisplayId);
- mWindowingLayer.release();
- mOverlayLayer.release();
mInputMonitor.onDisplayRemoved();
- // TODO(display-merge): Remove cast
- mWmService.mDisplayNotificationController
- .dispatchDisplayRemoved((ActivityDisplay) this);
+ mWmService.mDisplayNotificationController.dispatchDisplayRemoved(this);
} finally {
mDisplayReady = false;
mRemovingDisplay = false;
@@ -2499,7 +2642,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
// the minimized docked stack bounds.
final boolean dockMinimized = mDividerControllerLocked.isMinimizedDock()
|| (topDockedTask != null && imeOnBottom && !dockedStack.isAdjustedForIme()
- && dockedStack.getBounds().height() < topDockedTask.getBounds().height());
+ && dockedStack.getBounds().height() < topDockedTask.getBounds().height());
// The divider could be adjusted for IME position, or be thinner than usual,
// or both. There are three possible cases:
@@ -2601,6 +2744,29 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
}
}
+ public void dumpDebug(ProtoOutputStream proto, long fieldId,
+ @WindowTraceLogLevel int logLevel) {
+ final long token = proto.start(fieldId);
+ dumpDebugInner(proto, DISPLAY, logLevel);
+ proto.write(com.android.server.am.ActivityDisplayProto.ID, mDisplayId);
+ proto.write(SINGLE_TASK_INSTANCE, mSingleTaskInstance);
+ final ActivityStack focusedStack = getFocusedStack();
+ if (focusedStack != null) {
+ proto.write(FOCUSED_STACK_ID, focusedStack.mStackId);
+ final ActivityRecord focusedActivity = focusedStack.getDisplay().getResumedActivity();
+ if (focusedActivity != null) {
+ focusedActivity.writeIdentifierToProto(proto, RESUMED_ACTIVITY);
+ }
+ } else {
+ proto.write(FOCUSED_STACK_ID, INVALID_STACK_ID);
+ }
+ for (int stackNdx = getStackCount() - 1; stackNdx >= 0; --stackNdx) {
+ final ActivityStack stack = getStackAt(stackNdx);
+ stack.dumpDebug(proto, com.android.server.am.ActivityDisplayProto.STACKS, logLevel);
+ }
+ proto.end(token);
+ }
+
// TODO(proto-merge): Remove once protos for ActivityDisplay and DisplayContent are merged.
public void dumpDebugInner(ProtoOutputStream proto, long fieldId,
@WindowTraceLogLevel int logLevel) {
@@ -2630,6 +2796,10 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
final WindowToken windowToken = mImeWindowsContainers.getChildAt(i);
windowToken.dumpDebug(proto, IME_WINDOWS, logLevel);
}
+ for (int i = mOverlayContainers.getChildCount() - 1; i >= 0; --i) {
+ final WindowToken windowToken = mOverlayContainers.getChildAt(i);
+ windowToken.dumpDebug(proto, OVERLAY_WINDOWS, logLevel);
+ }
proto.write(DPI, mBaseDisplayDensity);
mDisplayInfo.dumpDebug(proto, DISPLAY_INFO);
proto.write(ROTATION, getRotation());
@@ -2657,34 +2827,36 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
@Override
public void dump(PrintWriter pw, String prefix, boolean dumpAll) {
super.dump(pw, prefix, dumpAll);
- pw.print(prefix); pw.print("Display: mDisplayId="); pw.println(mDisplayId);
+ pw.print(prefix);
+ pw.println("Display: mDisplayId=" + mDisplayId + " stacks=" + getStackCount() + (
+ mSingleTaskInstance ? " mSingleTaskInstance" : ""));
final String subPrefix = " " + prefix;
pw.print(subPrefix); pw.print("init="); pw.print(mInitialDisplayWidth); pw.print("x");
- pw.print(mInitialDisplayHeight); pw.print(" "); pw.print(mInitialDisplayDensity);
- pw.print("dpi");
- if (mInitialDisplayWidth != mBaseDisplayWidth
- || mInitialDisplayHeight != mBaseDisplayHeight
- || mInitialDisplayDensity != mBaseDisplayDensity) {
- pw.print(" base=");
- pw.print(mBaseDisplayWidth); pw.print("x"); pw.print(mBaseDisplayHeight);
- pw.print(" "); pw.print(mBaseDisplayDensity); pw.print("dpi");
- }
- if (mDisplayScalingDisabled) {
- pw.println(" noscale");
- }
- pw.print(" cur=");
- pw.print(mDisplayInfo.logicalWidth);
- pw.print("x"); pw.print(mDisplayInfo.logicalHeight);
- pw.print(" app=");
- pw.print(mDisplayInfo.appWidth);
- pw.print("x"); pw.print(mDisplayInfo.appHeight);
- pw.print(" rng="); pw.print(mDisplayInfo.smallestNominalAppWidth);
- pw.print("x"); pw.print(mDisplayInfo.smallestNominalAppHeight);
- pw.print("-"); pw.print(mDisplayInfo.largestNominalAppWidth);
- pw.print("x"); pw.println(mDisplayInfo.largestNominalAppHeight);
- pw.print(subPrefix + "deferred=" + mDeferredRemoval
- + " mLayoutNeeded=" + mLayoutNeeded);
- pw.println(" mTouchExcludeRegion=" + mTouchExcludeRegion);
+ pw.print(mInitialDisplayHeight); pw.print(" "); pw.print(mInitialDisplayDensity);
+ pw.print("dpi");
+ if (mInitialDisplayWidth != mBaseDisplayWidth
+ || mInitialDisplayHeight != mBaseDisplayHeight
+ || mInitialDisplayDensity != mBaseDisplayDensity) {
+ pw.print(" base=");
+ pw.print(mBaseDisplayWidth); pw.print("x"); pw.print(mBaseDisplayHeight);
+ pw.print(" "); pw.print(mBaseDisplayDensity); pw.print("dpi");
+ }
+ if (mDisplayScalingDisabled) {
+ pw.println(" noscale");
+ }
+ pw.print(" cur=");
+ pw.print(mDisplayInfo.logicalWidth);
+ pw.print("x"); pw.print(mDisplayInfo.logicalHeight);
+ pw.print(" app=");
+ pw.print(mDisplayInfo.appWidth);
+ pw.print("x"); pw.print(mDisplayInfo.appHeight);
+ pw.print(" rng="); pw.print(mDisplayInfo.smallestNominalAppWidth);
+ pw.print("x"); pw.print(mDisplayInfo.smallestNominalAppHeight);
+ pw.print("-"); pw.print(mDisplayInfo.largestNominalAppWidth);
+ pw.print("x"); pw.println(mDisplayInfo.largestNominalAppHeight);
+ pw.print(subPrefix + "deferred=" + mDeferredRemoval
+ + " mLayoutNeeded=" + mLayoutNeeded);
+ pw.println(" mTouchExcludeRegion=" + mTouchExcludeRegion);
pw.println();
pw.print(prefix); pw.print("mLayoutSeq="); pw.println(mLayoutSeq);
@@ -2693,6 +2865,12 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
if (mLastFocus != mCurrentFocus) {
pw.print(" mLastFocus="); pw.println(mLastFocus);
}
+ if (mPreferredTopFocusableStack != null) {
+ pw.println(prefix + "mPreferredTopFocusableStack=" + mPreferredTopFocusableStack);
+ }
+ if (mLastFocusedStack != null) {
+ pw.println(prefix + "mLastFocusedStack=" + mLastFocusedStack);
+ }
if (mLosingFocus.size() > 0) {
pw.println();
pw.println(" Windows losing focus:");
@@ -2770,6 +2948,10 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
if (splitScreenPrimaryStack != null) {
pw.println(prefix + "splitScreenPrimaryStack=" + splitScreenPrimaryStack.getName());
}
+ final ActivityStack recentsStack = getRecentsStack();
+ if (recentsStack != null) {
+ pw.println(prefix + "recentsStack=" + recentsStack.getName());
+ }
pw.println();
mDividerControllerLocked.dump(prefix, pw);
@@ -2841,7 +3023,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
}
final WindowState win = getWindow(w ->
w.mAttrs.type == TYPE_TOAST && w.mOwnerUid == uid && !w.mPermanentlyHidden
- && !w.mWindowRemovalAllowed);
+ && !w.mWindowRemovalAllowed);
return win == null;
}
@@ -2921,7 +3103,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
}
ProtoLog.v(WM_DEBUG_FOCUS_LIGHT, "Changing focus from %s to %s displayId=%d Callers=%s",
- mCurrentFocus, newFocus, getDisplayId(), Debug.getCallers(4));
+ mCurrentFocus, newFocus, getDisplayId(), Debug.getCallers(4));
final WindowState oldFocus = mCurrentFocus;
mCurrentFocus = newFocus;
mLosingFocus.remove(newFocus);
@@ -3223,7 +3405,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
// target app together.
final boolean shouldAttachToDisplay = (mMagnificationSpec != null);
final SurfaceControl newParent =
- shouldAttachToDisplay ? mWindowingLayer : computeImeParent();
+ shouldAttachToDisplay ? mWindowContainers.getSurfaceControl() : computeImeParent();
if (newParent != null) {
getPendingTransaction().reparent(mImeWindowsContainers.mSurfaceControl, newParent);
scheduleAnimation();
@@ -3248,39 +3430,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
}
// Otherwise, we just attach it to the display.
- return mWindowingLayer;
- }
-
- boolean getNeedsMenu(WindowState top, WindowManagerPolicy.WindowState bottom) {
- if (top.mAttrs.needsMenuKey != NEEDS_MENU_UNSET) {
- return top.mAttrs.needsMenuKey == NEEDS_MENU_SET_TRUE;
- }
-
- // Used to indicate we have reached the first window in the range we are interested in.
- mTmpWindow = null;
-
- // TODO: Figure-out a more efficient way to do this.
- final WindowState candidate = getWindow(w -> {
- if (w == top) {
- // Reached the first window in the range we are interested in.
- mTmpWindow = w;
- }
- if (mTmpWindow == null) {
- return false;
- }
-
- if (w.mAttrs.needsMenuKey != NEEDS_MENU_UNSET) {
- return true;
- }
- // If we reached the bottom of the range of windows we are considering,
- // assume no menu is needed.
- if (w == bottom) {
- return true;
- }
- return false;
- });
-
- return candidate != null && candidate.mAttrs.needsMenuKey == NEEDS_MENU_SET_TRUE;
+ return mWindowContainers.getSurfaceControl();
}
void setLayoutNeeded() {
@@ -3395,7 +3545,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
boolean wallpaperEnabled = mWmService.mContext.getResources().getBoolean(
com.android.internal.R.bool.config_enableWallpaperService)
&& mWmService.mContext.getResources().getBoolean(
- com.android.internal.R.bool.config_checkWallpaperAtBoot)
+ com.android.internal.R.bool.config_checkWallpaperAtBoot)
&& !mWmService.mOnlyCore;
final boolean haveBootMsg = drawnWindowTypes.get(TYPE_BOOT_PROGRESS);
@@ -3586,13 +3736,11 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
}
if (DEBUG_LAYOUT_REPEATS) surfacePlacer.debugLayoutRepeats(
"after finishPostLayoutPolicyLw", pendingLayoutChanges);
- mInsetsStateController.onPostLayout();
+ mInsetsStateController.onPostLayout();
} while (pendingLayoutChanges != 0);
mTmpApplySurfaceChangesTransactionState.reset();
- mTmpRecoveringMemory = recoveringMemory;
-
Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "applyWindowSurfaceChanges");
try {
forAllWindows(mApplySurfaceChangesTransaction, true /* traverseTopToBottom */);
@@ -3852,12 +4000,56 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
}
static final class TaskForResizePointSearchResult {
- boolean searchDone;
- Task taskForResize;
+ private Task taskForResize;
+ private int x;
+ private int y;
+ private int delta;
+ private Rect mTmpRect = new Rect();
- void reset() {
- searchDone = false;
+ Task process(WindowContainer root, int x, int y, int delta) {
taskForResize = null;
+ this.x = x;
+ this.y = y;
+ this.delta = delta;
+ mTmpRect.setEmpty();
+
+ final PooledFunction f = PooledLambda.obtainFunction(
+ TaskForResizePointSearchResult::processTask, this, PooledLambda.__(Task.class));
+ root.forAllTasks(f);
+ f.recycle();
+
+ return taskForResize;
+ }
+
+ private boolean processTask(Task task) {
+ if (!task.getStack().getWindowConfiguration().canResizeTask()) {
+ return true;
+ }
+
+ if (task.getWindowingMode() == WINDOWING_MODE_FULLSCREEN) {
+ return true;
+ }
+
+ // We need to use the task's dim bounds (which is derived from the visible bounds of
+ // its apps windows) for any touch-related tests. Can't use the task's original
+ // bounds because it might be adjusted to fit the content frame. One example is when
+ // the task is put to top-left quadrant, the actual visible area would not start at
+ // (0,0) after it's adjusted for the status bar.
+ task.getDimBounds(mTmpRect);
+ mTmpRect.inset(-delta, -delta);
+ if (mTmpRect.contains(x, y)) {
+ mTmpRect.inset(delta, delta);
+
+ if (!mTmpRect.contains(x, y)) {
+ taskForResize = task;
+ return true;
+ }
+ // User touched inside the task. No need to look further,
+ // focus transfer will be handled in ACTION_UP.
+ return true;
+ }
+
+ return false;
}
}
@@ -4045,8 +4237,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
+ " already exist on display=" + this + " stack=" + stack);
}
mSplitScreenPrimaryStack = stack;
- // TODO(display-merge): Remove cast
- ((ActivityDisplay) this.mDisplayContent).onSplitScreenModeActivated();
+ mDisplayContent.onSplitScreenModeActivated();
mDividerControllerLocked.notifyDockedStackExistsChanged(true);
}
}
@@ -4060,8 +4251,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
mPinnedStack = null;
} else if (stack == mSplitScreenPrimaryStack) {
mSplitScreenPrimaryStack = null;
- // TODO(display-merge): Remove cast
- ((ActivityDisplay) this.mDisplayContent).onSplitScreenModeDismissed();
+ mDisplayContent.onSplitScreenModeDismissed();
// Re-set the split-screen create mode whenever the split-screen stack is removed.
mWmService.setDockedStackCreateStateLocked(
SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
@@ -4086,8 +4276,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
@Override
protected void removeChild(ActivityStack stack) {
super.removeChild(stack);
- // TODO(display-merge): Remove cast
- ((ActivityDisplay) this.mDisplayContent).onStackRemoved(stack);
+ mDisplayContent.onStackRemoved(stack);
removeStackReferenceIfNeeded(stack);
}
@@ -4297,7 +4486,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
if (mHomeStack != null && mHomeStack.isVisible()
&& mDividerControllerLocked.isMinimizedDock()
&& !(mDividerControllerLocked.isHomeStackResizable()
- && mHomeStack.matchParentBounds())) {
+ && mHomeStack.matchParentBounds())) {
final int orientation = mHomeStack.getOrientation();
if (orientation != SCREEN_ORIENTATION_UNSET) {
return orientation;
@@ -4310,14 +4499,14 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
if (orientation != SCREEN_ORIENTATION_UNSET
&& orientation != SCREEN_ORIENTATION_BEHIND) {
ProtoLog.v(WM_DEBUG_ORIENTATION,
- "App is requesting an orientation, return %d for display id=%d",
- orientation, mDisplayId);
+ "App is requesting an orientation, return %d for display id=%d",
+ orientation, mDisplayId);
return orientation;
}
ProtoLog.v(WM_DEBUG_ORIENTATION,
- "No app is requesting an orientation, return %d for display id=%d",
- getLastOrientation(), mDisplayId);
+ "No app is requesting an orientation, return %d for display id=%d",
+ getLastOrientation(), mDisplayId);
// The next app has not been requested to be visible, so we keep the current orientation
// to prevent freezing/unfreezing the display too early.
return getLastOrientation();
@@ -4486,7 +4675,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
wt.windowType, wt.mOwnerCanManageAppTokens);
if (needAssignIme && layer >= mWmService.mPolicy.getWindowLayerFromTypeLw(
- TYPE_INPUT_METHOD_DIALOG, true)) {
+ TYPE_INPUT_METHOD_DIALOG, true)) {
imeContainer.assignRelativeLayer(t, wt.getSurfaceControl(), -1);
needAssignIme = false;
}
@@ -4497,6 +4686,126 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
}
}
+ private class WindowContainers extends DisplayChildWindowContainer<WindowContainer> {
+ private final String mName;
+
+ WindowContainers(String name, WindowManagerService service) {
+ super(service);
+ mName = name;
+ }
+
+ @Override
+ void assignChildLayers(SurfaceControl.Transaction t) {
+ mBelowAppWindowsContainers.assignLayer(t, 0);
+ mTaskStackContainers.assignLayer(t, 1);
+ mAboveAppWindowsContainers.assignLayer(t, 2);
+
+ final WindowState imeTarget = mInputMethodTarget;
+ boolean needAssignIme = true;
+
+ // In the case where we have an IME target that is not in split-screen mode IME
+ // assignment is easy. We just need the IME to go directly above the target. This way
+ // children of the target will naturally go above the IME and everyone is happy.
+ //
+ // In the case of split-screen windowing mode, we need to elevate the IME above the
+ // docked divider while keeping the app itself below the docked divider, so instead
+ // we use relative layering of the IME targets child windows, and place the IME in
+ // the non-app layer (see {@link AboveAppWindowContainers#assignChildLayers}).
+ //
+ // In the case the IME target is animating, the animation Z order may be different
+ // than the WindowContainer Z order, so it's difficult to be sure we have the correct
+ // IME target. In this case we just layer the IME over all transitions by placing it
+ // in the above applications layer.
+ //
+ // In the case where we have no IME target we assign it where its base layer would
+ // place it in the AboveAppWindowContainers.
+ //
+ // Keep IME window in mAboveAppWindowsContainers as long as app's starting window
+ // exists so it get's layered above the starting window.
+ if (imeTarget != null && !(imeTarget.mActivityRecord != null
+ && imeTarget.mActivityRecord.hasStartingWindow()) && (
+ !(imeTarget.inSplitScreenWindowingMode()
+ || imeTarget.mToken.isAppTransitioning()) && (
+ imeTarget.getSurfaceControl() != null))) {
+ mImeWindowsContainers.assignRelativeLayer(t, imeTarget.getSurfaceControl(),
+ // TODO: We need to use an extra level on the app surface to ensure
+ // this is always above SurfaceView but always below attached window.
+ 1);
+ needAssignIme = false;
+ }
+
+ // Above we have assigned layers to our children, now we ask them to assign
+ // layers to their children.
+ mBelowAppWindowsContainers.assignChildLayers(t);
+ mTaskStackContainers.assignChildLayers(t);
+ mAboveAppWindowsContainers.assignChildLayers(t,
+ needAssignIme ? mImeWindowsContainers : null);
+ mImeWindowsContainers.assignChildLayers(t);
+ }
+
+ @Override
+ String getName() {
+ return mName;
+ }
+
+ void addChildren() {
+ addChild(mBelowAppWindowsContainers, null);
+ addChild(mTaskStackContainers, null);
+ addChild(mAboveAppWindowsContainers, null);
+ addChild(mImeWindowsContainers, null);
+ }
+
+ /**
+ * In split-screen mode we process the IME containers above the docked divider
+ * rather than directly above their target.
+ */
+ private boolean skipTraverseChild(WindowContainer child) {
+ return child == mImeWindowsContainers && mInputMethodTarget != null
+ && !hasSplitScreenPrimaryStack();
+ }
+
+ @Override
+ boolean forAllWindows(ToBooleanFunction<WindowState> callback,
+ boolean traverseTopToBottom) {
+ // Special handling so we can process IME windows with #forAllImeWindows above their IME
+ // target, or here in order if there isn't an IME target.
+ if (traverseTopToBottom) {
+ for (int i = mChildren.size() - 1; i >= 0; --i) {
+ final WindowContainer child = mChildren.get(i);
+ if (skipTraverseChild(child)) {
+ continue;
+ }
+
+ if (child.forAllWindows(callback, traverseTopToBottom)) {
+ return true;
+ }
+ }
+ } else {
+ final int count = mChildren.size();
+ for (int i = 0; i < count; i++) {
+ Slog.d(TAG, "child " + mChildren.get(i));
+ final WindowContainer child = mChildren.get(i);
+ if (skipTraverseChild(child)) {
+ Slog.d(TAG, "child skipped");
+ continue;
+ }
+
+ if (child.forAllWindows(callback, traverseTopToBottom)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ @Override
+ void positionChildAt(int position, WindowContainer child, boolean includingParents) {
+ // Children of the WindowContainers are statically ordered, so the real intention here
+ // is to perform the operation on the display and not the static direct children.
+ getParent().positionChildAt(position, this, includingParents);
+ }
+ }
+
/**
* Window container class that contains all containers on this display that are not related to
* Apps. E.g. status bar.
@@ -4510,7 +4819,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
// Tokens with higher base layer are z-ordered on-top.
mWmService.mPolicy.getWindowLayerFromTypeLw(token1.windowType,
token1.mOwnerCanManageAppTokens)
- < mWmService.mPolicy.getWindowLayerFromTypeLw(token2.windowType,
+ < mWmService.mPolicy.getWindowLayerFromTypeLw(token2.windowType,
token2.mOwnerCanManageAppTokens) ? -1 : 1;
private final Predicate<WindowState> mGetOrientingWindow = w -> {
@@ -4562,7 +4871,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
}
ProtoLog.v(WM_DEBUG_ORIENTATION,
"%s forcing orientation to %d for display id=%d", win, req,
- mDisplayId);
+ mDisplayId);
return (mLastWindowForcedOrientation = req);
}
@@ -4602,11 +4911,6 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
}
}
- SurfaceControl.Builder makeSurface(SurfaceSession s) {
- return mWmService.makeSurfaceBuilder(s)
- .setParent(mWindowingLayer);
- }
-
@Override
SurfaceSession getSession() {
return mSession;
@@ -4621,7 +4925,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
}
return b.setName(child.getName())
- .setParent(mWindowingLayer);
+ .setParent(mSurfaceControl);
}
/**
@@ -4632,14 +4936,14 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
*/
SurfaceControl.Builder makeOverlay() {
return mWmService.makeSurfaceBuilder(mSession)
- .setParent(mOverlayLayer);
+ .setParent(mOverlayContainers.getSurfaceControl());
}
/**
- * Reparents the given surface to mOverlayLayer.
+ * Reparents the given surface to {@link #mOverlayContainers}' SurfaceControl.
*/
void reparentToOverlay(Transaction transaction, SurfaceControl surface) {
- transaction.reparent(surface, mOverlayLayer);
+ transaction.reparent(surface, mOverlayContainers.getSurfaceControl());
}
void applyMagnificationSpec(MagnificationSpec spec) {
@@ -4651,7 +4955,11 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
// Re-parent IME's SurfaceControl when MagnificationSpec changed.
updateImeParent();
- applyMagnificationSpec(getPendingTransaction(), spec);
+ if (spec.scale != 1.0) {
+ applyMagnificationSpec(getPendingTransaction(), spec);
+ } else {
+ clearMagnificationSpec(getPendingTransaction());
+ }
getPendingTransaction().apply();
}
@@ -4671,54 +4979,11 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
@Override
void assignChildLayers(SurfaceControl.Transaction t) {
+ mWindowContainers.assignLayer(t, 0);
+ mOverlayContainers.assignLayer(t, 1);
- // These are layers as children of "mWindowingLayer"
- mBelowAppWindowsContainers.assignLayer(t, 0);
- mTaskStackContainers.assignLayer(t, 1);
- mAboveAppWindowsContainers.assignLayer(t, 2);
-
- final WindowState imeTarget = mInputMethodTarget;
- boolean needAssignIme = true;
-
- // In the case where we have an IME target that is not in split-screen
- // mode IME assignment is easy. We just need the IME to go directly above
- // the target. This way children of the target will naturally go above the IME
- // and everyone is happy.
- //
- // In the case of split-screen windowing mode, we need to elevate the IME above the
- // docked divider while keeping the app itself below the docked divider, so instead
- // we use relative layering of the IME targets child windows, and place the
- // IME in the non-app layer (see {@link AboveAppWindowContainers#assignChildLayers}).
- //
- // In the case the IME target is animating, the animation Z order may be different
- // than the WindowContainer Z order, so it's difficult to be sure we have the correct
- // IME target. In this case we just layer the IME over all transitions by placing it in the
- // above applications layer.
- //
- // In the case where we have no IME target we assign it where it's base layer would
- // place it in the AboveAppWindowContainers.
- //
- // Keep IME window in mAboveAppWindowsContainers as long as app's starting window exists
- // so it get's layered above the starting window.
- if (imeTarget != null
- && !(imeTarget.mActivityRecord != null && imeTarget.mActivityRecord.hasStartingWindow())
- && (!(imeTarget.inSplitScreenWindowingMode()
- || imeTarget.mToken.isAppTransitioning())
- && (imeTarget.getSurfaceControl() != null))) {
- mImeWindowsContainers.assignRelativeLayer(t, imeTarget.getSurfaceControl(),
- // TODO: We need to use an extra level on the app surface to ensure
- // this is always above SurfaceView but always below attached window.
- 1);
- needAssignIme = false;
- }
-
- // Above we have assigned layers to our children, now we ask them to assign
- // layers to their children.
- mBelowAppWindowsContainers.assignChildLayers(t);
- mTaskStackContainers.assignChildLayers(t);
- mAboveAppWindowsContainers.assignChildLayers(t,
- needAssignIme == true ? mImeWindowsContainers : null);
- mImeWindowsContainers.assignChildLayers(t);
+ mWindowContainers.assignChildLayers(t);
+ mOverlayContainers.assignChildLayers(t);
}
/**
@@ -4820,7 +5085,7 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
if (mAppTransition.isTransitionSet()) {
ProtoLog.w(WM_DEBUG_APP_TRANSITIONS,
"Execute app transition: %s, displayId: %d Callers=%s",
- mAppTransition, mDisplayId, Debug.getCallers(5));
+ mAppTransition, mDisplayId, Debug.getCallers(5));
mAppTransition.setReady();
mWmService.mWindowPlacerLocked.requestTraversal();
}
@@ -4885,8 +5150,8 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
}
/**
- * Re-parent the DisplayContent's top surfaces, {@link #mWindowingLayer} and
- * {@link #mOverlayLayer} to the specified SurfaceControl.
+ * Re-parent the DisplayContent's top surface, {@link #mSurfaceControl} to the specified
+ * SurfaceControl.
*
* @param win The window which owns the SurfaceControl. This indicates the z-order of the
* windows of this display against the windows on the parent display.
@@ -4964,11 +5229,11 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
@VisibleForTesting
SurfaceControl getWindowingLayer() {
- return mWindowingLayer;
+ return mWindowContainers.getSurfaceControl();
}
SurfaceControl getOverlayLayer() {
- return mOverlayLayer;
+ return mOverlayContainers.getSurfaceControl();
}
/**
@@ -5247,4 +5512,1132 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo
}
return mMetricsLogger;
}
+
+ void onDisplayChanged() {
+ // The window policy is responsible for stopping activities on the default display.
+ final int displayId = mDisplay.getDisplayId();
+ if (displayId != DEFAULT_DISPLAY) {
+ final int displayState = mDisplay.getState();
+ if (displayState == Display.STATE_OFF && mOffToken == null) {
+ mOffToken = mAtmService.acquireSleepToken("Display-off", displayId);
+ } else if (displayState == Display.STATE_ON && mOffToken != null) {
+ mOffToken.release();
+ mOffToken = null;
+ }
+ }
+
+ mDisplay.getRealSize(mTmpDisplaySize);
+ setBounds(0, 0, mTmpDisplaySize.x, mTmpDisplaySize.y);
+ updateDisplayInfo();
+ mWmService.requestTraversal();
+ }
+
+ void addStack(ActivityStack stack, int position) {
+ setStackOnDisplay(stack, position);
+ positionStackAt(stack, position);
+ mAtmService.updateSleepIfNeededLocked();
+ }
+
+ void onStackRemoved(ActivityStack stack) {
+ if (ActivityTaskManagerDebugConfig.DEBUG_STACK) {
+ Slog.v(TAG_STACK, "removeStack: detaching " + stack + " from displayId=" + mDisplayId);
+ }
+ if (mPreferredTopFocusableStack == stack) {
+ mPreferredTopFocusableStack = null;
+ }
+ releaseSelfIfNeeded();
+ mAtmService.updateSleepIfNeededLocked();
+ onStackOrderChanged(stack);
+ }
+
+ void positionStackAtTop(ActivityStack stack, boolean includingParents) {
+ positionStackAtTop(stack, includingParents, null /* updateLastFocusedStackReason */);
+ }
+
+ void positionStackAtTop(ActivityStack stack, boolean includingParents,
+ String updateLastFocusedStackReason) {
+ positionStackAt(stack, getStackCount(), includingParents, updateLastFocusedStackReason);
+ }
+
+ void positionStackAtBottom(ActivityStack stack) {
+ positionStackAtBottom(stack, null /* updateLastFocusedStackReason */);
+ }
+
+ void positionStackAtBottom(ActivityStack stack, String updateLastFocusedStackReason) {
+ positionStackAt(stack, 0, false /* includingParents */, updateLastFocusedStackReason);
+ }
+
+ private void positionStackAt(ActivityStack stack, int position) {
+ positionStackAt(stack, position, false /* includingParents */,
+ null /* updateLastFocusedStackReason */);
+ }
+
+ private void positionStackAt(ActivityStack stack, int position, boolean includingParents,
+ String updateLastFocusedStackReason) {
+ // TODO: Keep in sync with WindowContainer.positionChildAt(), once we change that to adjust
+ // the position internally, also update the logic here
+ final ActivityStack prevFocusedStack = updateLastFocusedStackReason != null
+ ? getFocusedStack() : null;
+ final boolean wasContained = getIndexOf(stack) >= 0;
+ if (mSingleTaskInstance && getStackCount() == 1 && !wasContained) {
+ throw new IllegalStateException(
+ "positionStackAt: Can only have one task on display=" + this);
+ }
+
+ // Since positionChildAt() is called during the creation process of pinned stacks,
+ // ActivityStack#getStack() can be null.
+ positionStackAt(position, stack, includingParents);
+
+ // The insert position may be adjusted to non-top when there is always-on-top stack. Since
+ // the original position is preferred to be top, the stack should have higher priority when
+ // we are looking for top focusable stack. The condition {@code wasContained} restricts the
+ // preferred stack is set only when moving an existing stack to top instead of adding a new
+ // stack that may be too early (e.g. in the middle of launching or reparenting).
+ if (wasContained && position >= getStackCount() - 1 && stack.isFocusableAndVisible()) {
+ mPreferredTopFocusableStack = stack;
+ } else if (mPreferredTopFocusableStack == stack) {
+ mPreferredTopFocusableStack = null;
+ }
+
+ if (updateLastFocusedStackReason != null) {
+ final ActivityStack currentFocusedStack = getFocusedStack();
+ if (currentFocusedStack != prevFocusedStack) {
+ mLastFocusedStack = prevFocusedStack;
+ EventLogTags.writeWmFocusedStack(mRootActivityContainer.mCurrentUser, mDisplayId,
+ currentFocusedStack == null ? -1 : currentFocusedStack.getStackId(),
+ mLastFocusedStack == null ? -1 : mLastFocusedStack.getStackId(),
+ updateLastFocusedStackReason);
+ }
+ }
+
+ onStackOrderChanged(stack);
+ }
+
+ ActivityStack getStack(int stackId) {
+ for (int i = getStackCount() - 1; i >= 0; --i) {
+ final ActivityStack stack = getStackAt(i);
+ if (stack.mStackId == stackId) {
+ return stack;
+ }
+ }
+ return null;
+ }
+
+ boolean alwaysCreateStack(int windowingMode, int activityType) {
+ // Always create a stack for fullscreen, freeform, and split-screen-secondary windowing
+ // modes so that we can manage visual ordering and return types correctly.
+ return activityType == ACTIVITY_TYPE_STANDARD
+ && (windowingMode == WINDOWING_MODE_FULLSCREEN
+ || windowingMode == WINDOWING_MODE_FREEFORM
+ || windowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
+ }
+
+ /**
+ * Returns an existing stack compatible with the windowing mode and activity type or creates one
+ * if a compatible stack doesn't exist.
+ * @see #getStack(int, int)
+ * @see #createStack(int, int, boolean)
+ */
+ ActivityStack getOrCreateStack(int windowingMode, int activityType,
+ boolean onTop) {
+ if (!alwaysCreateStack(windowingMode, activityType)) {
+ ActivityStack stack = getStack(windowingMode, activityType);
+ if (stack != null) {
+ return stack;
+ }
+ }
+ return createStack(windowingMode, activityType, onTop);
+ }
+
+ /**
+ * Returns an existing stack compatible with the input params or creates one
+ * if a compatible stack doesn't exist.
+ * @see #getOrCreateStack(int, int, boolean)
+ */
+ ActivityStack getOrCreateStack(@Nullable ActivityRecord r,
+ @Nullable ActivityOptions options, @Nullable Task candidateTask, int activityType,
+ boolean onTop) {
+ // First preference is the windowing mode in the activity options if set.
+ int windowingMode = (options != null)
+ ? options.getLaunchWindowingMode() : WINDOWING_MODE_UNDEFINED;
+ // Validate that our desired windowingMode will work under the current conditions.
+ // UNDEFINED windowing mode is a valid result and means that the new stack will inherit
+ // it's display's windowing mode.
+ windowingMode = validateWindowingMode(windowingMode, r, candidateTask, activityType);
+ return getOrCreateStack(windowingMode, activityType, onTop);
+ }
+
+ @VisibleForTesting
+ int getNextStackId() {
+ return sNextFreeStackId++;
+ }
+
+ /**
+ * Creates a stack matching the input windowing mode and activity type on this display.
+ * @param windowingMode The windowing mode the stack should be created in. If
+ * {@link WindowConfiguration#WINDOWING_MODE_UNDEFINED} then the stack will
+ * inherit its parent's windowing mode.
+ * @param activityType The activityType the stack should be created in. If
+ * {@link WindowConfiguration#ACTIVITY_TYPE_UNDEFINED} then the stack will
+ * be created in {@link WindowConfiguration#ACTIVITY_TYPE_STANDARD}.
+ * @param onTop If true the stack will be created at the top of the display, else at the bottom.
+ * @return The newly created stack.
+ */
+ ActivityStack createStack(int windowingMode, int activityType, boolean onTop) {
+ if (mSingleTaskInstance && getStackCount() > 0) {
+ // Create stack on default display instead since this display can only contain 1 stack.
+ // TODO: Kinda a hack, but better that having the decision at each call point. Hoping
+ // this goes away once ActivityView is no longer using virtual displays.
+ return mRootActivityContainer.getDefaultDisplay().createStack(
+ windowingMode, activityType, onTop);
+ }
+
+ if (activityType == ACTIVITY_TYPE_UNDEFINED) {
+ // Can't have an undefined stack type yet...so re-map to standard. Anyone that wants
+ // anything else should be passing it in anyways...
+ activityType = ACTIVITY_TYPE_STANDARD;
+ }
+
+ if (activityType != ACTIVITY_TYPE_STANDARD) {
+ // For now there can be only one stack of a particular non-standard activity type on a
+ // display. So, get that ignoring whatever windowing mode it is currently in.
+ ActivityStack stack = getStack(WINDOWING_MODE_UNDEFINED, activityType);
+ if (stack != null) {
+ throw new IllegalArgumentException("Stack=" + stack + " of activityType="
+ + activityType + " already on display=" + this + ". Can't have multiple.");
+ }
+ }
+
+ if (!isWindowingModeSupported(windowingMode, mAtmService.mSupportsMultiWindow,
+ mAtmService.mSupportsSplitScreenMultiWindow,
+ mAtmService.mSupportsFreeformWindowManagement,
+ mAtmService.mSupportsPictureInPicture, activityType)) {
+ throw new IllegalArgumentException("Can't create stack for unsupported windowingMode="
+ + windowingMode);
+ }
+
+ final int stackId = getNextStackId();
+ return createStackUnchecked(windowingMode, activityType, stackId, onTop);
+ }
+
+ @VisibleForTesting
+ ActivityStack createStackUnchecked(int windowingMode, int activityType,
+ int stackId, boolean onTop) {
+ if (windowingMode == WINDOWING_MODE_PINNED && activityType != ACTIVITY_TYPE_STANDARD) {
+ throw new IllegalArgumentException("Stack with windowing mode cannot with non standard "
+ + "activity type.");
+ }
+ return new ActivityStack(this, stackId, mRootActivityContainer.mStackSupervisor,
+ windowingMode, activityType, onTop);
+ }
+
+ /**
+ * Get the preferred focusable stack in priority. If the preferred stack does not exist, find a
+ * focusable and visible stack from the top of stacks in this display.
+ */
+ ActivityStack getFocusedStack() {
+ if (mPreferredTopFocusableStack != null) {
+ return mPreferredTopFocusableStack;
+ }
+
+ for (int i = getStackCount() - 1; i >= 0; --i) {
+ final ActivityStack stack = getStackAt(i);
+ if (stack.isFocusableAndVisible()) {
+ return stack;
+ }
+ }
+
+ return null;
+ }
+
+ ActivityStack getNextFocusableStack(ActivityStack currentFocus, boolean ignoreCurrent) {
+ final int currentWindowingMode = currentFocus != null
+ ? currentFocus.getWindowingMode() : WINDOWING_MODE_UNDEFINED;
+
+ ActivityStack candidate = null;
+ for (int i = getStackCount() - 1; i >= 0; --i) {
+ final ActivityStack stack = getStackAt(i);
+ if (ignoreCurrent && stack == currentFocus) {
+ continue;
+ }
+ if (!stack.isFocusableAndVisible()) {
+ continue;
+ }
+
+ if (currentWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY
+ && candidate == null && stack.inSplitScreenPrimaryWindowingMode()) {
+ // If the currently focused stack is in split-screen secondary we save off the
+ // top primary split-screen stack as a candidate for focus because we might
+ // prefer focus to move to an other stack to avoid primary split-screen stack
+ // overlapping with a fullscreen stack when a fullscreen stack is higher in z
+ // than the next split-screen stack. Assistant stack, I am looking at you...
+ // We only move the focus to the primary-split screen stack if there isn't a
+ // better alternative.
+ candidate = stack;
+ continue;
+ }
+ if (candidate != null && stack.inSplitScreenSecondaryWindowingMode()) {
+ // Use the candidate stack since we are now at the secondary split-screen.
+ return candidate;
+ }
+ return stack;
+ }
+ return candidate;
+ }
+
+ ActivityRecord getResumedActivity() {
+ final ActivityStack focusedStack = getFocusedStack();
+ if (focusedStack == null) {
+ return null;
+ }
+ // TODO(b/111541062): Move this into ActivityStack#getResumedActivity()
+ // Check if the focused stack has the resumed activity
+ ActivityRecord resumedActivity = focusedStack.getResumedActivity();
+ if (resumedActivity == null || resumedActivity.app == null) {
+ // If there is no registered resumed activity in the stack or it is not running -
+ // try to use previously resumed one.
+ resumedActivity = focusedStack.mPausingActivity;
+ if (resumedActivity == null || resumedActivity.app == null) {
+ // If previously resumed activity doesn't work either - find the topmost running
+ // activity that can be focused.
+ resumedActivity = focusedStack.topRunningActivity(true /* focusableOnly */);
+ }
+ }
+ return resumedActivity;
+ }
+
+ ActivityStack getLastFocusedStack() {
+ return mLastFocusedStack;
+ }
+
+ boolean allResumedActivitiesComplete() {
+ for (int stackNdx = getStackCount() - 1; stackNdx >= 0; --stackNdx) {
+ final ActivityRecord r = getStackAt(stackNdx).getResumedActivity();
+ if (r != null && !r.isState(RESUMED)) {
+ return false;
+ }
+ }
+ final ActivityStack currentFocusedStack = getFocusedStack();
+ if (ActivityTaskManagerDebugConfig.DEBUG_STACK) {
+ Slog.d(TAG_STACK, "allResumedActivitiesComplete: mLastFocusedStack changing from="
+ + mLastFocusedStack + " to=" + currentFocusedStack);
+ }
+ mLastFocusedStack = currentFocusedStack;
+ return true;
+ }
+
+ /**
+ * Pause all activities in either all of the stacks or just the back stacks. This is done before
+ * resuming a new activity and to make sure that previously active activities are
+ * paused in stacks that are no longer visible or in pinned windowing mode. This does not
+ * pause activities in visible stacks, so if an activity is launched within the same stack/task,
+ * then we should explicitly pause that stack's top activity.
+ * @param userLeaving Passed to pauseActivity() to indicate whether to call onUserLeaving().
+ * @param resuming The resuming activity.
+ * @return {@code true} if any activity was paused as a result of this call.
+ */
+ boolean pauseBackStacks(boolean userLeaving, ActivityRecord resuming) {
+ boolean someActivityPaused = false;
+ for (int stackNdx = getStackCount() - 1; stackNdx >= 0; --stackNdx) {
+ final ActivityStack stack = getStackAt(stackNdx);
+ final ActivityRecord resumedActivity = stack.getResumedActivity();
+ if (resumedActivity != null
+ && (stack.getVisibility(resuming) != STACK_VISIBILITY_VISIBLE
+ || !stack.isFocusable())) {
+ if (DEBUG_STATES) Slog.d(TAG_STATES, "pauseBackStacks: stack=" + stack
+ + " mResumedActivity=" + resumedActivity);
+ someActivityPaused |= stack.startPausingLocked(userLeaving, false /* uiSleeping*/,
+ resuming);
+ }
+ }
+ return someActivityPaused;
+ }
+
+ /**
+ * Find task for putting the Activity in.
+ */
+ void findTaskLocked(final ActivityRecord r, final boolean isPreferredDisplay,
+ RootActivityContainer.FindTaskResult result) {
+ mTmpFindTaskResult.clear();
+ for (int stackNdx = getStackCount() - 1; stackNdx >= 0; --stackNdx) {
+ final ActivityStack stack = getStackAt(stackNdx);
+ if (!r.hasCompatibleActivityType(stack)) {
+ if (DEBUG_TASKS) {
+ Slog.d(TAG_TASKS, "Skipping stack: (mismatch activity/stack) " + stack);
+ }
+ continue;
+ }
+
+ mTmpFindTaskResult.process(r, stack);
+ // It is possible to have tasks in multiple stacks with the same root affinity, so
+ // we should keep looking after finding an affinity match to see if there is a
+ // better match in another stack. Also, task affinity isn't a good enough reason
+ // to target a display which isn't the source of the intent, so skip any affinity
+ // matches not on the specified display.
+ if (mTmpFindTaskResult.mRecord != null) {
+ if (mTmpFindTaskResult.mIdealMatch) {
+ result.setTo(mTmpFindTaskResult);
+ return;
+ } else if (isPreferredDisplay) {
+ // Note: since the traversing through the stacks is top down, the floating
+ // tasks should always have lower priority than any affinity-matching tasks
+ // in the fullscreen stacks
+ result.setTo(mTmpFindTaskResult);
+ }
+ }
+ }
+ }
+
+ /**
+ * Removes stacks in the input windowing modes from the system if they are of activity type
+ * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
+ */
+ void removeStacksInWindowingModes(int... windowingModes) {
+ if (windowingModes == null || windowingModes.length == 0) {
+ return;
+ }
+
+ // Collect the stacks that are necessary to be removed instead of performing the removal
+ // by looping mStacks, so that we don't miss any stacks after the stack size changed or
+ // stacks reordered.
+ final ArrayList<ActivityStack> stacks = new ArrayList<>();
+ for (int j = windowingModes.length - 1; j >= 0; --j) {
+ final int windowingMode = windowingModes[j];
+ for (int i = getStackCount() - 1; i >= 0; --i) {
+ final ActivityStack stack = getStackAt(i);
+ if (!stack.isActivityTypeStandardOrUndefined()) {
+ continue;
+ }
+ if (stack.getWindowingMode() != windowingMode) {
+ continue;
+ }
+ stacks.add(stack);
+ }
+ }
+
+ for (int i = stacks.size() - 1; i >= 0; --i) {
+ mRootActivityContainer.mStackSupervisor.removeStack(stacks.get(i));
+ }
+ }
+
+ void removeStacksWithActivityTypes(int... activityTypes) {
+ if (activityTypes == null || activityTypes.length == 0) {
+ return;
+ }
+
+ // Collect the stacks that are necessary to be removed instead of performing the removal
+ // by looping mStacks, so that we don't miss any stacks after the stack size changed or
+ // stacks reordered.
+ final ArrayList<ActivityStack> stacks = new ArrayList<>();
+ for (int j = activityTypes.length - 1; j >= 0; --j) {
+ final int activityType = activityTypes[j];
+ for (int i = getStackCount() - 1; i >= 0; --i) {
+ final ActivityStack stack = getStackAt(i);
+ if (stack.getActivityType() == activityType) {
+ stacks.add(stack);
+ }
+ }
+ }
+
+ for (int i = stacks.size() - 1; i >= 0; --i) {
+ mRootActivityContainer.mStackSupervisor.removeStack(stacks.get(i));
+ }
+ }
+
+ void onSplitScreenModeDismissed() {
+ mAtmService.deferWindowLayout();
+ try {
+ // Adjust the windowing mode of any stack in secondary split-screen to fullscreen.
+ for (int i = getStackCount() - 1; i >= 0; --i) {
+ final ActivityStack otherStack = getStackAt(i);
+ if (!otherStack.inSplitScreenSecondaryWindowingMode()) {
+ continue;
+ }
+ otherStack.setWindowingMode(WINDOWING_MODE_UNDEFINED, false /* animate */,
+ false /* showRecents */, false /* enteringSplitScreenMode */,
+ true /* deferEnsuringVisibility */, false /* creating */);
+ }
+ } finally {
+ final ActivityStack topFullscreenStack =
+ getTopStackInWindowingMode(WINDOWING_MODE_FULLSCREEN);
+ final ActivityStack homeStack = getHomeStack();
+ if (topFullscreenStack != null && homeStack != null && !isTopStack(homeStack)) {
+ // Whenever split-screen is dismissed we want the home stack directly behind the
+ // current top fullscreen stack so it shows up when the top stack is finished.
+ // TODO: Would be better to use ActivityDisplay.positionChildAt() for this, however
+ // ActivityDisplay doesn't have a direct controller to WM side yet. We can switch
+ // once we have that.
+ homeStack.moveToFront("onSplitScreenModeDismissed");
+ topFullscreenStack.moveToFront("onSplitScreenModeDismissed");
+ }
+ mAtmService.continueWindowLayout();
+ }
+ }
+
+ void onSplitScreenModeActivated() {
+ mAtmService.deferWindowLayout();
+ try {
+ // Adjust the windowing mode of any affected by split-screen to split-screen secondary.
+ final ActivityStack splitScreenPrimaryStack = getSplitScreenPrimaryStack();
+ for (int i = getStackCount() - 1; i >= 0; --i) {
+ final ActivityStack otherStack = getStackAt(i);
+ if (otherStack == splitScreenPrimaryStack
+ || !otherStack.affectedBySplitScreenResize()) {
+ continue;
+ }
+ otherStack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_SECONDARY,
+ false /* animate */, false /* showRecents */,
+ true /* enteringSplitScreenMode */, true /* deferEnsuringVisibility */,
+ false /* creating */);
+ }
+ } finally {
+ mAtmService.continueWindowLayout();
+ }
+ }
+
+ /**
+ * Returns true if the {@param windowingMode} is supported based on other parameters passed in.
+ * @param windowingMode The windowing mode we are checking support for.
+ * @param supportsMultiWindow If we should consider support for multi-window mode in general.
+ * @param supportsSplitScreen If we should consider support for split-screen multi-window.
+ * @param supportsFreeform If we should consider support for freeform multi-window.
+ * @param supportsPip If we should consider support for picture-in-picture mutli-window.
+ * @param activityType The activity type under consideration.
+ * @return true if the windowing mode is supported.
+ */
+ private boolean isWindowingModeSupported(int windowingMode, boolean supportsMultiWindow,
+ boolean supportsSplitScreen, boolean supportsFreeform, boolean supportsPip,
+ int activityType) {
+
+ if (windowingMode == WINDOWING_MODE_UNDEFINED
+ || windowingMode == WINDOWING_MODE_FULLSCREEN) {
+ return true;
+ }
+ if (!supportsMultiWindow) {
+ return false;
+ }
+
+ final int displayWindowingMode = getWindowingMode();
+ if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY
+ || windowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY) {
+ return supportsSplitScreen
+ && WindowConfiguration.supportSplitScreenWindowingMode(activityType)
+ // Freeform windows and split-screen windows don't mix well, so prevent
+ // split windowing modes on freeform displays.
+ && displayWindowingMode != WINDOWING_MODE_FREEFORM;
+ }
+
+ if (!supportsFreeform && windowingMode == WINDOWING_MODE_FREEFORM) {
+ return false;
+ }
+
+ if (!supportsPip && windowingMode == WINDOWING_MODE_PINNED) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Resolves the windowing mode that an {@link ActivityRecord} would be in if started on this
+ * display with the provided parameters.
+ *
+ * @param r The ActivityRecord in question.
+ * @param options Options to start with.
+ * @param task The task within-which the activity would start.
+ * @param activityType The type of activity to start.
+ * @return The resolved (not UNDEFINED) windowing-mode that the activity would be in.
+ */
+ int resolveWindowingMode(@Nullable ActivityRecord r, @Nullable ActivityOptions options,
+ @Nullable Task task, int activityType) {
+
+ // First preference if the windowing mode in the activity options if set.
+ int windowingMode = (options != null)
+ ? options.getLaunchWindowingMode() : WINDOWING_MODE_UNDEFINED;
+
+ // If windowing mode is unset, then next preference is the candidate task, then the
+ // activity record.
+ if (windowingMode == WINDOWING_MODE_UNDEFINED) {
+ if (task != null) {
+ windowingMode = task.getWindowingMode();
+ }
+ if (windowingMode == WINDOWING_MODE_UNDEFINED && r != null) {
+ windowingMode = r.getWindowingMode();
+ }
+ if (windowingMode == WINDOWING_MODE_UNDEFINED) {
+ // Use the display's windowing mode.
+ windowingMode = getWindowingMode();
+ }
+ }
+ windowingMode = validateWindowingMode(windowingMode, r, task, activityType);
+ return windowingMode != WINDOWING_MODE_UNDEFINED
+ ? windowingMode : WINDOWING_MODE_FULLSCREEN;
+ }
+
+ /**
+ * Check that the requested windowing-mode is appropriate for the specified task and/or activity
+ * on this display.
+ *
+ * @param windowingMode The windowing-mode to validate.
+ * @param r The {@link ActivityRecord} to check against.
+ * @param task The {@link Task} to check against.
+ * @param activityType An activity type.
+ * @return The provided windowingMode or the closest valid mode which is appropriate.
+ */
+ int validateWindowingMode(int windowingMode, @Nullable ActivityRecord r, @Nullable Task task,
+ int activityType) {
+ // Make sure the windowing mode we are trying to use makes sense for what is supported.
+ boolean supportsMultiWindow = mAtmService.mSupportsMultiWindow;
+ boolean supportsSplitScreen = mAtmService.mSupportsSplitScreenMultiWindow;
+ boolean supportsFreeform = mAtmService.mSupportsFreeformWindowManagement;
+ boolean supportsPip = mAtmService.mSupportsPictureInPicture;
+ if (supportsMultiWindow) {
+ if (task != null) {
+ supportsMultiWindow = task.isResizeable();
+ supportsSplitScreen = task.supportsSplitScreenWindowingMode();
+ // TODO: Do we need to check for freeform and Pip support here?
+ } else if (r != null) {
+ supportsMultiWindow = r.isResizeable();
+ supportsSplitScreen = r.supportsSplitScreenWindowingMode();
+ supportsFreeform = r.supportsFreeform();
+ supportsPip = r.supportsPictureInPicture();
+ }
+ }
+
+ final boolean inSplitScreenMode = hasSplitScreenPrimaryStack();
+ if (!inSplitScreenMode
+ && windowingMode == WINDOWING_MODE_FULLSCREEN_OR_SPLIT_SCREEN_SECONDARY) {
+ // Switch to the display's windowing mode if we are not in split-screen mode and we are
+ // trying to launch in split-screen secondary.
+ windowingMode = WINDOWING_MODE_UNDEFINED;
+ } else if (inSplitScreenMode && (windowingMode == WINDOWING_MODE_FULLSCREEN
+ || windowingMode == WINDOWING_MODE_UNDEFINED)
+ && supportsSplitScreen) {
+ windowingMode = WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
+ }
+
+ if (windowingMode != WINDOWING_MODE_UNDEFINED
+ && isWindowingModeSupported(windowingMode, supportsMultiWindow, supportsSplitScreen,
+ supportsFreeform, supportsPip, activityType)) {
+ return windowingMode;
+ }
+ return WINDOWING_MODE_UNDEFINED;
+ }
+
+ boolean isTopStack(ActivityStack stack) {
+ return stack == getTopStack();
+ }
+
+ boolean isTopNotPinnedStack(ActivityStack stack) {
+ for (int i = getStackCount() - 1; i >= 0; --i) {
+ final ActivityStack current = getStackAt(i);
+ if (!current.inPinnedWindowingMode()) {
+ return current == stack;
+ }
+ }
+ return false;
+ }
+
+ ActivityRecord topRunningActivity() {
+ return topRunningActivity(false /* considerKeyguardState */);
+ }
+
+ /**
+ * Returns the top running activity in the focused stack. In the case the focused stack has no
+ * such activity, the next focusable stack on this display is returned.
+ *
+ * @param considerKeyguardState Indicates whether the locked state should be considered. if
+ * {@code true} and the keyguard is locked, only activities that
+ * can be shown on top of the keyguard will be considered.
+ * @return The top running activity. {@code null} if none is available.
+ */
+ ActivityRecord topRunningActivity(boolean considerKeyguardState) {
+ ActivityRecord topRunning = null;
+ final ActivityStack focusedStack = getFocusedStack();
+ if (focusedStack != null) {
+ topRunning = focusedStack.topRunningActivity();
+ }
+
+ // Look in other focusable stacks.
+ if (topRunning == null) {
+ for (int i = getStackCount() - 1; i >= 0; --i) {
+ final ActivityStack stack = getStackAt(i);
+ // Only consider focusable stacks other than the current focused one.
+ if (stack == focusedStack || !stack.isFocusable()) {
+ continue;
+ }
+ topRunning = stack.topRunningActivity();
+ if (topRunning != null) {
+ break;
+ }
+ }
+ }
+
+ // This activity can be considered the top running activity if we are not considering
+ // the locked state, the keyguard isn't locked, or we can show when locked.
+ if (topRunning != null && considerKeyguardState
+ && mRootActivityContainer.mStackSupervisor.getKeyguardController()
+ .isKeyguardLocked()
+ && !topRunning.canShowWhenLocked()) {
+ return null;
+ }
+
+ return topRunning;
+ }
+
+ boolean updateDisplayOverrideConfigurationLocked() {
+ Configuration values = new Configuration();
+ computeScreenConfiguration(values);
+
+ mAtmService.mH.sendMessage(PooledLambda.obtainMessage(
+ ActivityManagerInternal::updateOomLevelsForDisplay, mAtmService.mAmInternal,
+ mDisplayId));
+
+ Settings.System.clearConfiguration(values);
+ updateDisplayOverrideConfigurationLocked(values, null /* starting */,
+ false /* deferResume */, mAtmService.mTmpUpdateConfigurationResult);
+ return mAtmService.mTmpUpdateConfigurationResult.changes != 0;
+ }
+
+ /**
+ * Updates override configuration specific for the selected display. If no config is provided,
+ * new one will be computed in WM based on current display info.
+ */
+ boolean updateDisplayOverrideConfigurationLocked(Configuration values,
+ ActivityRecord starting, boolean deferResume,
+ ActivityTaskManagerService.UpdateConfigurationResult result) {
+
+ int changes = 0;
+ boolean kept = true;
+
+ mAtmService.deferWindowLayout();
+ try {
+ if (values != null) {
+ if (mDisplayId == DEFAULT_DISPLAY) {
+ // Override configuration of the default display duplicates global config, so
+ // we're calling global config update instead for default display. It will also
+ // apply the correct override config.
+ changes = mAtmService.updateGlobalConfigurationLocked(values,
+ false /* initLocale */, false /* persistent */,
+ UserHandle.USER_NULL /* userId */, deferResume);
+ } else {
+ changes = performDisplayOverrideConfigUpdate(values, deferResume);
+ }
+ }
+
+ kept = mAtmService.ensureConfigAndVisibilityAfterUpdate(starting, changes);
+ } finally {
+ mAtmService.continueWindowLayout();
+ }
+
+ if (result != null) {
+ result.changes = changes;
+ result.activityRelaunched = !kept;
+ }
+ return kept;
+ }
+
+ int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume) {
+ mTempConfig.setTo(getRequestedOverrideConfiguration());
+ final int changes = mTempConfig.updateFrom(values);
+ if (changes != 0) {
+ Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
+ + mTempConfig + " for displayId=" + mDisplayId);
+ onRequestedOverrideConfigurationChanged(mTempConfig);
+
+ final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
+ if (isDensityChange && mDisplayId == DEFAULT_DISPLAY) {
+ mAtmService.mAppWarnings.onDensityChanged();
+
+ // Post message to start process to avoid possible deadlock of calling into AMS with
+ // the ATMS lock held.
+ final Message msg = PooledLambda.obtainMessage(
+ ActivityManagerInternal::killAllBackgroundProcessesExcept,
+ mAtmService.mAmInternal, N,
+ ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
+ mAtmService.mH.sendMessage(msg);
+ }
+ mWmService.mDisplayNotificationController.dispatchDisplayChanged(
+ this, getConfiguration());
+ }
+ return changes;
+ }
+
+ @Override
+ public void onRequestedOverrideConfigurationChanged(Configuration overrideConfiguration) {
+ final int currRotation =
+ getRequestedOverrideConfiguration().windowConfiguration.getRotation();
+ if (currRotation != ROTATION_UNDEFINED
+ && currRotation != overrideConfiguration.windowConfiguration.getRotation()) {
+ applyRotationLocked(currRotation,
+ overrideConfiguration.windowConfiguration.getRotation());
+ }
+ mCurrentOverrideConfigurationChanges =
+ getRequestedOverrideConfiguration().diff(overrideConfiguration);
+ super.onRequestedOverrideConfigurationChanged(overrideConfiguration);
+ mCurrentOverrideConfigurationChanges = 0;
+ mWmService.setNewDisplayOverrideConfiguration(overrideConfiguration, this);
+ mAtmService.addWindowLayoutReasons(
+ ActivityTaskManagerService.LAYOUT_REASON_CONFIG_CHANGED);
+ }
+
+ /** Checks whether the given activity is in size compatibility mode and notifies the change. */
+ void handleActivitySizeCompatModeIfNeeded(ActivityRecord r) {
+ if (!r.isState(RESUMED) || r.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
+ // The callback is only interested in the foreground changes of fullscreen activity.
+ return;
+ }
+ if (!r.inSizeCompatMode()) {
+ if (mLastCompatModeActivity != null) {
+ mAtmService.getTaskChangeNotificationController()
+ .notifySizeCompatModeActivityChanged(mDisplayId, null /* activityToken */);
+ }
+ mLastCompatModeActivity = null;
+ return;
+ }
+ if (mLastCompatModeActivity == r) {
+ return;
+ }
+ mLastCompatModeActivity = r;
+ mAtmService.getTaskChangeNotificationController()
+ .notifySizeCompatModeActivityChanged(mDisplayId, r.appToken);
+ }
+
+ boolean isUidPresent(int uid) {
+ final PooledPredicate p = PooledLambda.obtainPredicate(
+ ActivityRecord::isUid, PooledLambda.__(ActivityRecord.class), uid);
+ final boolean isUidPresent = mDisplayContent.getActivity(p) != null;
+ p.recycle();
+ return isUidPresent;
+ }
+
+ /**
+ * @see #mRemoved
+ */
+ boolean isRemoved() {
+ return mRemoved;
+ }
+
+ /**
+ * @see #mRemoving
+ */
+ boolean isRemoving() {
+ return mRemoving;
+ }
+
+ void remove() {
+ mRemoving = true;
+ final boolean destroyContentOnRemoval = shouldDestroyContentOnRemove();
+ ActivityStack lastReparentedStack = null;
+ mPreferredTopFocusableStack = null;
+
+ // Stacks could be reparented from the removed display to other display. While
+ // reparenting the last stack of the removed display, the remove display is ready to be
+ // released (no more ActivityStack). But, we cannot release it at that moment or the
+ // related WindowContainer will also be removed. So, we set display as removed after
+ // reparenting stack finished.
+ final DisplayContent toDisplay = mRootActivityContainer.getDefaultDisplay();
+ mRootActivityContainer.mStackSupervisor.beginDeferResume();
+ try {
+ int numStacks = getStackCount();
+ // Keep the order from bottom to top.
+ for (int stackNdx = 0; stackNdx < numStacks; stackNdx++) {
+ final ActivityStack stack = getStackAt(stackNdx);
+ // Always finish non-standard type stacks.
+ if (destroyContentOnRemoval || !stack.isActivityTypeStandardOrUndefined()) {
+ stack.finishAllActivitiesImmediately();
+ } else {
+ // If default display is in split-window mode, set windowing mode of the stack
+ // to split-screen secondary. Otherwise, set the windowing mode to undefined by
+ // default to let stack inherited the windowing mode from the new display.
+ final int windowingMode = toDisplay.hasSplitScreenPrimaryStack()
+ ? WINDOWING_MODE_SPLIT_SCREEN_SECONDARY
+ : WINDOWING_MODE_UNDEFINED;
+ stack.reparent(toDisplay, true /* onTop */);
+ stack.setWindowingMode(windowingMode);
+ lastReparentedStack = stack;
+ }
+ // Stacks may be removed from this display. Ensure each stack will be processed and
+ // the loop will end.
+ stackNdx -= numStacks - getStackCount();
+ numStacks = getStackCount();
+ }
+ } finally {
+ mRootActivityContainer.mStackSupervisor.endDeferResume();
+ }
+ mRemoved = true;
+
+ // Only update focus/visibility for the last one because there may be many stacks are
+ // reparented and the intermediate states are unnecessary.
+ if (lastReparentedStack != null) {
+ lastReparentedStack.postReparent();
+ }
+ releaseSelfIfNeeded();
+
+ if (!mAllSleepTokens.isEmpty()) {
+ mRootActivityContainer.mSleepTokens.removeAll(mAllSleepTokens);
+ mAllSleepTokens.clear();
+ mAtmService.updateSleepIfNeededLocked();
+ }
+ }
+
+ private void releaseSelfIfNeeded() {
+ if (!mRemoved) {
+ return;
+ }
+
+ final ActivityStack stack = getStackCount() == 1 ? getStackAt(0) : null;
+ if (stack != null && stack.isActivityTypeHome() && !stack.hasChild()) {
+ // Release this display if an empty home stack is the only thing left.
+ // Since it is the last stack, this display will be released along with the stack
+ // removal.
+ stack.removeIfPossible();
+ } else if (getTopStack() == null) {
+ removeIfPossible();
+ mRootActivityContainer.removeChild(this);
+ mRootActivityContainer.mStackSupervisor
+ .getKeyguardController().onDisplayRemoved(mDisplayId);
+ }
+ }
+
+ /** Update and get all UIDs that are present on the display and have access to it. */
+ IntArray getPresentUIDs() {
+ mDisplayAccessUIDs.clear();
+ final PooledConsumer c = PooledLambda.obtainConsumer(DisplayContent::addActivityUid,
+ PooledLambda.__(ActivityRecord.class), mDisplayAccessUIDs);
+ mDisplayContent.forAllActivities(c);
+ c.recycle();
+ return mDisplayAccessUIDs;
+ }
+
+ private static void addActivityUid(ActivityRecord r, IntArray uids) {
+ uids.add(r.getUid());
+ }
+
+ @VisibleForTesting
+ boolean shouldDestroyContentOnRemove() {
+ return mDisplay.getRemoveMode() == REMOVE_MODE_DESTROY_CONTENT;
+ }
+
+ boolean shouldSleep() {
+ return (getStackCount() == 0 || !mAllSleepTokens.isEmpty())
+ && (mAtmService.mRunningVoice == null);
+ }
+
+ void setFocusedApp(ActivityRecord r, boolean moveFocusNow) {
+ final ActivityRecord newFocus;
+ final IBinder token = r.appToken;
+ if (token == null) {
+ ProtoLog.v(WM_DEBUG_FOCUS_LIGHT, "Clearing focused app, displayId=%d",
+ mDisplayId);
+ newFocus = null;
+ } else {
+ newFocus = mWmService.mRoot.getActivityRecord(token);
+ if (newFocus == null) {
+ Slog.w(TAG_WM, "Attempted to set focus to non-existing app token: " + token
+ + ", displayId=" + mDisplayId);
+ }
+ ProtoLog.v(WM_DEBUG_FOCUS_LIGHT,
+ "Set focused app to: %s moveFocusNow=%b displayId=%d", newFocus,
+ moveFocusNow, mDisplayId);
+ }
+
+ final boolean changed = setFocusedApp(newFocus);
+ if (moveFocusNow && changed) {
+ mWmService.updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL,
+ true /*updateInputWindows*/);
+ }
+ }
+
+ /**
+ * @return the stack currently above the {@param stack}. Can be null if the {@param stack} is
+ * already top-most.
+ */
+ ActivityStack getStackAbove(ActivityStack stack) {
+ final int stackIndex = getIndexOf(stack) + 1;
+ return (stackIndex < getStackCount()) ? getStackAt(stackIndex) : null;
+ }
+
+ /**
+ * Adjusts the {@param stack} behind the last visible stack in the display if necessary.
+ * Generally used in conjunction with {@link #moveStackBehindStack}.
+ */
+ void moveStackBehindBottomMostVisibleStack(ActivityStack stack) {
+ if (stack.shouldBeVisible(null)) {
+ // Skip if the stack is already visible
+ return;
+ }
+
+ // Move the stack to the bottom to not affect the following visibility checks
+ positionStackAtBottom(stack);
+
+ // Find the next position where the stack should be placed
+ final int numStacks = getStackCount();
+ for (int stackNdx = 0; stackNdx < numStacks; stackNdx++) {
+ final ActivityStack s = getStackAt(stackNdx);
+ if (s == stack) {
+ continue;
+ }
+ final int winMode = s.getWindowingMode();
+ final boolean isValidWindowingMode = winMode == WINDOWING_MODE_FULLSCREEN
+ || winMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
+ if (s.shouldBeVisible(null) && isValidWindowingMode) {
+ // Move the provided stack to behind this stack
+ positionStackAt(stack, Math.max(0, stackNdx - 1));
+ break;
+ }
+ }
+ }
+
+ /**
+ * Moves the {@param stack} behind the given {@param behindStack} if possible. If
+ * {@param behindStack} is not currently in the display, then then the stack is moved to the
+ * back. Generally used in conjunction with {@link #moveStackBehindBottomMostVisibleStack}.
+ */
+ void moveStackBehindStack(ActivityStack stack, ActivityStack behindStack) {
+ if (behindStack == null || behindStack == stack) {
+ return;
+ }
+
+ // Note that positionChildAt will first remove the given stack before inserting into the
+ // list, so we need to adjust the insertion index to account for the removed index
+ // TODO: Remove this logic when WindowContainer.positionChildAt() is updated to adjust the
+ // position internally
+ final int stackIndex = getIndexOf(stack);
+ final int behindStackIndex = getIndexOf(behindStack);
+ final int insertIndex = stackIndex <= behindStackIndex
+ ? behindStackIndex - 1 : behindStackIndex;
+ positionStackAt(stack, Math.max(0, insertIndex));
+ }
+
+ void ensureActivitiesVisible(ActivityRecord starting, int configChanges,
+ boolean preserveWindows, boolean notifyClients) {
+ for (int stackNdx = getStackCount() - 1; stackNdx >= 0; --stackNdx) {
+ final ActivityStack stack = getStackAt(stackNdx);
+ stack.ensureActivitiesVisible(starting, configChanges, preserveWindows,
+ notifyClients);
+ }
+ }
+
+ void moveHomeStackToFront(String reason) {
+ final ActivityStack homeStack = getHomeStack();
+ if (homeStack != null) {
+ homeStack.moveToFront(reason);
+ }
+ }
+
+ /**
+ * Moves the focusable home activity to top. If there is no such activity, the home stack will
+ * still move to top.
+ */
+ void moveHomeActivityToTop(String reason) {
+ final ActivityRecord top = getHomeActivity();
+ if (top == null) {
+ moveHomeStackToFront(reason);
+ return;
+ }
+ top.moveFocusableActivityToTop(reason);
+ }
+
+ @Nullable
+ ActivityRecord getHomeActivity() {
+ return getHomeActivityForUser(mRootActivityContainer.mCurrentUser);
+ }
+
+ @Nullable
+ ActivityRecord getHomeActivityForUser(int userId) {
+ final ActivityStack homeStack = getHomeStack();
+ if (homeStack == null) {
+ return null;
+ }
+
+ final PooledPredicate p = PooledLambda.obtainPredicate(
+ DisplayContent::isHomeActivityForUser, PooledLambda.__(ActivityRecord.class),
+ userId);
+ final ActivityRecord r = homeStack.getActivity(p);
+ p.recycle();
+ return r;
+ }
+
+ private static boolean isHomeActivityForUser(ActivityRecord r, int userId) {
+ return r.isActivityTypeHome() && (userId == UserHandle.USER_ALL || r.mUserId == userId);
+ }
+
+ boolean isSleeping() {
+ return mSleeping;
+ }
+
+ void setIsSleeping(boolean asleep) {
+ mSleeping = asleep;
+ }
+
+ /**
+ * Adds a listener to be notified whenever the stack order in the display changes. Currently
+ * only used by the {@link RecentsAnimation} to determine whether to interrupt and cancel the
+ * current animation when the system state changes.
+ */
+ void registerStackOrderChangedListener(OnStackOrderChangedListener listener) {
+ if (!mStackOrderChangedCallbacks.contains(listener)) {
+ mStackOrderChangedCallbacks.add(listener);
+ }
+ }
+
+ /**
+ * Removes a previously registered stack order change listener.
+ */
+ void unregisterStackOrderChangedListener(OnStackOrderChangedListener listener) {
+ mStackOrderChangedCallbacks.remove(listener);
+ }
+
+ /**
+ * Notifies of a stack order change
+ * @param stack The stack which triggered the order change
+ */
+ private void onStackOrderChanged(ActivityStack stack) {
+ for (int i = mStackOrderChangedCallbacks.size() - 1; i >= 0; i--) {
+ mStackOrderChangedCallbacks.get(i).onStackOrderChanged(stack);
+ }
+ }
+
+ void setDisplayToSingleTaskInstance() {
+ final int childCount = getStackCount();
+ if (childCount > 1) {
+ throw new IllegalArgumentException("Display already has multiple stacks. display="
+ + this);
+ }
+ if (childCount > 0) {
+ final ActivityStack stack = getStackAt(0);
+ if (stack.getChildCount() > 1) {
+ throw new IllegalArgumentException("Display stack already has multiple tasks."
+ + " display=" + this + " stack=" + stack);
+ }
+ }
+
+ mSingleTaskInstance = true;
+ }
+
+ /** Returns true if the display can only contain one task */
+ boolean isSingleTaskInstance() {
+ return mSingleTaskInstance;
+ }
+
+ @VisibleForTesting
+ void removeAllTasks() {
+ forAllTasks((t) -> { t.getStack().removeChild(t, "removeAllTasks"); });
+ }
+
+ /**
+ * Callback for when the order of the stacks in the display changes.
+ */
+ interface OnStackOrderChangedListener {
+ void onStackOrderChanged(ActivityStack stack);
+ }
+
+ public void dumpStacks(PrintWriter pw) {
+ for (int i = getStackCount() - 1; i >= 0; --i) {
+ pw.print(getStackAt(i).mStackId);
+ if (i > 0) {
+ pw.print(",");
+ }
+ }
+ }
}
diff --git a/services/core/java/com/android/server/wm/DisplayPolicy.java b/services/core/java/com/android/server/wm/DisplayPolicy.java
index 2283041367ef..667e713d0b39 100644
--- a/services/core/java/com/android/server/wm/DisplayPolicy.java
+++ b/services/core/java/com/android/server/wm/DisplayPolicy.java
@@ -33,6 +33,7 @@ import static android.view.InsetsState.ITYPE_RIGHT_GESTURES;
import static android.view.InsetsState.ITYPE_STATUS_BAR;
import static android.view.InsetsState.ITYPE_TOP_GESTURES;
import static android.view.InsetsState.ITYPE_TOP_TAPPABLE_ELEMENT;
+import static android.view.View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
import static android.view.View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewRootImpl.NEW_INSETS_MODE_FULL;
@@ -49,7 +50,6 @@ import static android.view.WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN;
import static android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_ATTACHED_IN_DECOR;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
-import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
import static android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
@@ -63,6 +63,7 @@ import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_DRAW_BA
import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_STATUS_BAR_VISIBLE_TRANSPARENT;
import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_IS_SCREEN_DECOR;
import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_KEYGUARD;
+import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_ONLY_DRAW_BOTTOM_BAR_BACKGROUND;
import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_STATUS_FORCE_SHOW_NAVIGATION;
import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
@@ -149,13 +150,17 @@ import android.view.InputDevice;
import android.view.InputEvent;
import android.view.InputEventReceiver;
import android.view.InsetsFlags;
+import android.view.InsetsState;
import android.view.InsetsState.InternalInsetsType;
import android.view.MotionEvent;
import android.view.PointerIcon;
import android.view.Surface;
import android.view.View;
import android.view.ViewRootImpl;
-import android.view.WindowInsets;
+import android.view.WindowInsets.Side;
+import android.view.WindowInsets.Side.InsetsSide;
+import android.view.WindowInsets.Type;
+import android.view.WindowInsets.Type.InsetsType;
import android.view.WindowInsetsController.Appearance;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
@@ -337,6 +342,7 @@ public class DisplayPolicy {
private int mLastAppearance;
private int mLastFullscreenAppearance;
private int mLastDockedAppearance;
+ private int mLastBehavior;
private final Rect mNonDockedStackBounds = new Rect();
private final Rect mDockedStackBounds = new Rect();
private final Rect mLastNonDockedStackBounds = new Rect();
@@ -353,6 +359,7 @@ public class DisplayPolicy {
private static final Rect sTmpRect = new Rect();
private static final Rect sTmpNavFrame = new Rect();
private static final Rect sTmpLastParentFrame = new Rect();
+ private static final int[] sTmpTypesAndSides = new int[2];
private WindowState mTopFullscreenOpaqueWindowState;
private WindowState mTopFullscreenOpaqueOrDimmingWindowState;
@@ -1228,7 +1235,8 @@ public class DisplayPolicy {
final boolean screenDecor = (pfl & PRIVATE_FLAG_IS_SCREEN_DECOR) != 0;
if (layoutInScreenAndInsetDecor && !screenDecor) {
- if ((sysUiVis & SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0) {
+ if ((sysUiVis & SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
+ || (attrs.getFitWindowInsetsTypes() & Type.navigationBars()) == 0) {
outFrame.set(displayFrames.mUnrestricted);
} else {
outFrame.set(displayFrames.mRestricted);
@@ -1281,11 +1289,27 @@ public class DisplayPolicy {
}
}
+ private static void getImpliedTypesAndSidesToFit(LayoutParams attrs, int[] typesAndSides) {
+ typesAndSides[0] = attrs.getFitWindowInsetsTypes();
+ typesAndSides[1] = attrs.getFitWindowInsetsSides();
+ final boolean forceDrawsBarBackgrounds =
+ (attrs.privateFlags & PRIVATE_FLAG_FORCE_DRAW_BAR_BACKGROUNDS) != 0
+ && attrs.height == MATCH_PARENT && attrs.width == MATCH_PARENT;
+ if ((attrs.flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0 || forceDrawsBarBackgrounds) {
+ if ((attrs.privateFlags & PRIVATE_FLAG_ONLY_DRAW_BOTTOM_BAR_BACKGROUND) != 0) {
+ typesAndSides[1] &= ~Side.BOTTOM;
+ } else {
+ typesAndSides[0] &= ~Type.systemBars();
+ }
+ }
+ }
+
+ // TODO(b/118118435): remove after migration
private static int getImpliedSysUiFlagsForLayout(LayoutParams attrs) {
int impliedFlags = 0;
final boolean forceWindowDrawsBarBackgrounds =
(attrs.privateFlags & PRIVATE_FLAG_FORCE_DRAW_BAR_BACKGROUNDS) != 0
- && attrs.height == MATCH_PARENT && attrs.width == MATCH_PARENT;
+ && attrs.height == MATCH_PARENT && attrs.width == MATCH_PARENT;
if ((attrs.flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0
|| forceWindowDrawsBarBackgrounds) {
impliedFlags |= SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
@@ -1300,6 +1324,13 @@ public class DisplayPolicy {
synchronized (mLock) {
mForceClearedSystemUiFlags &= ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
mDisplayContent.reevaluateStatusBarVisibility();
+ if (ViewRootImpl.sNewInsetsMode == NEW_INSETS_MODE_FULL && mNavigationBar != null) {
+ final InsetsControlTarget target =
+ mNavigationBar.getControllableInsetProvider().getControlTarget();
+ if (target != null) {
+ target.showInsets(Type.navigationBars(), false /* fromIme */);
+ }
+ }
}
}
};
@@ -1376,11 +1407,18 @@ public class DisplayPolicy {
// For purposes of putting out fake window up to steal focus, we will
// drive nav being hidden only by whether it is requested.
final int sysui = mLastSystemUiFlags;
- boolean navVisible = (sysui & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
+ final int behavior = mLastBehavior;
+ boolean navVisible = ViewRootImpl.sNewInsetsMode != ViewRootImpl.NEW_INSETS_MODE_FULL
+ ? (sysui & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0
+ : mNavigationBar != null && mNavigationBar.getControllableInsetProvider() != null
+ && mNavigationBar.getControllableInsetProvider().isClientVisible()
+ && !mDisplayContent.getInsetsPolicy().isTransient(ITYPE_NAVIGATION_BAR);
boolean navTranslucent = (sysui
& (View.NAVIGATION_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSPARENT)) != 0;
- boolean immersive = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
- boolean immersiveSticky = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
+ boolean immersive = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0
+ || (behavior & BEHAVIOR_SHOW_BARS_BY_SWIPE) != 0;
+ boolean immersiveSticky = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0
+ || (behavior & BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE) != 0;
boolean navAllowedHidden = immersive || immersiveSticky;
navTranslucent &= !immersiveSticky; // transient trumps translucent
boolean isKeyguardShowing = isStatusBarKeyguard()
@@ -1464,6 +1502,9 @@ public class DisplayPolicy {
displayFrames.mUnrestricted /* stableFrame */);
w.getWindowFrames().setDisplayCutout(displayFrames.mDisplayCutout);
w.computeFrameLw();
+ if (w.getControllableInsetProvider() != null) {
+ w.getControllableInsetProvider().updateSourceFrame();
+ }
final Rect frame = w.getFrameLw();
if (frame.left <= 0 && frame.top <= 0) {
@@ -1526,6 +1567,11 @@ public class DisplayPolicy {
// Let the status bar determine its size.
mStatusBar.computeFrameLw();
+ // Update the source frame to provide insets to other windows during layout.
+ if (mStatusBar.getControllableInsetProvider() != null) {
+ mStatusBar.getControllableInsetProvider().updateSourceFrame();
+ }
+
// For layout, the status bar is always at the top with our fixed height.
displayFrames.mStable.top = displayFrames.mUnrestricted.top
+ mStatusBarHeightForRotation[displayFrames.mRotation];
@@ -1540,7 +1586,8 @@ public class DisplayPolicy {
sTmpRect.bottom = displayFrames.mStable.top; // Use collapsed status bar size
mStatusBarController.setContentFrame(sTmpRect);
- boolean statusBarTransient = (sysui & View.STATUS_BAR_TRANSIENT) != 0;
+ boolean statusBarTransient = (sysui & View.STATUS_BAR_TRANSIENT) != 0
+ || mDisplayContent.getInsetsPolicy().isTransient(ITYPE_STATUS_BAR);
boolean statusBarTranslucent = (sysui
& (View.STATUS_BAR_TRANSLUCENT | View.STATUS_BAR_TRANSPARENT)) != 0;
@@ -1676,6 +1723,9 @@ public class DisplayPolicy {
navigationFrame /* stableFrame */);
mNavigationBar.getWindowFrames().setDisplayCutout(displayFrames.mDisplayCutout);
mNavigationBar.computeFrameLw();
+ if (mNavigationBar.getControllableInsetProvider() != null) {
+ mNavigationBar.getControllableInsetProvider().updateSourceFrame();
+ }
mNavigationBarController.setContentFrame(mNavigationBar.getContentFrameLw());
if (DEBUG_LAYOUT) Slog.i(TAG, "mNavigationBar frame: " + navigationFrame);
@@ -1811,19 +1861,44 @@ public class DisplayPolicy {
final int adjust = sim & SOFT_INPUT_MASK_ADJUST;
- final boolean requestedFullscreen = (fl & FLAG_FULLSCREEN) != 0
- || (requestedSysUiFl & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
-
final boolean layoutInScreen = (fl & FLAG_LAYOUT_IN_SCREEN) == FLAG_LAYOUT_IN_SCREEN;
final boolean layoutInsetDecor = (fl & FLAG_LAYOUT_INSET_DECOR) == FLAG_LAYOUT_INSET_DECOR;
sf.set(displayFrames.mStable);
- if (type == TYPE_INPUT_METHOD) {
+ if (ViewRootImpl.sNewInsetsMode == NEW_INSETS_MODE_FULL) {
+ getImpliedTypesAndSidesToFit(attrs, sTmpTypesAndSides);
+ final @InsetsType int typesToFit = sTmpTypesAndSides[0];
+ final @InsetsSide int sidesToFit = sTmpTypesAndSides[1];
+ final ArraySet<Integer> types = InsetsState.toInternalType(typesToFit);
+ final Rect dfu = displayFrames.mUnrestricted;
+ Insets insets = Insets.of(0, 0, 0, 0);
+ for (int i = types.size() - 1; i >= 0; i--) {
+ insets = Insets.max(insets, mDisplayContent.getInsetsStateController()
+ .getInsetsForDispatch(win).getSource(types.valueAt(i))
+ .calculateInsets(dfu, attrs.getFitIgnoreVisibility()));
+ }
+ final int left = (sidesToFit & Side.LEFT) != 0 ? insets.left : 0;
+ final int top = (sidesToFit & Side.TOP) != 0 ? insets.top : 0;
+ final int right = (sidesToFit & Side.RIGHT) != 0 ? insets.right : 0;
+ final int bottom = (sidesToFit & Side.BOTTOM) != 0 ? insets.bottom : 0;
+ df.set(left, top, dfu.right - right, dfu.bottom - bottom);
+ if (attached == null) {
+ pf.set(df);
+ vf.set(adjust != SOFT_INPUT_ADJUST_NOTHING
+ ? displayFrames.mCurrent : displayFrames.mDock);
+ } else {
+ pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0 ? attached.getFrameLw() : df);
+ vf.set(attached.getVisibleFrameLw());
+ }
+ cf.set(adjust != SOFT_INPUT_ADJUST_RESIZE
+ ? displayFrames.mDock : displayFrames.mContent);
+ dcf.set(displayFrames.mSystem);
+ } else if (type == TYPE_INPUT_METHOD) {
vf.set(displayFrames.mDock);
cf.set(displayFrames.mDock);
df.set(displayFrames.mDock);
- windowFrames.mParentFrame.set(displayFrames.mDock);
+ pf.set(displayFrames.mDock);
// IM dock windows layout below the nav bar...
pf.bottom = df.bottom = displayFrames.mUnrestricted.bottom;
// ...with content insets above the nav bar
@@ -1989,7 +2064,7 @@ public class DisplayPolicy {
}
}
} else if (layoutInScreen || (sysUiFl
- & (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
+ & (SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)) != 0) {
if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle()
+ "): IN_SCREEN");
@@ -2039,7 +2114,7 @@ public class DisplayPolicy {
cf.set(displayFrames.mUnrestricted);
df.set(displayFrames.mUnrestricted);
pf.set(displayFrames.mUnrestricted);
- } else if ((sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) != 0) {
+ } else if ((sysUiFl & SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) != 0) {
df.set(displayFrames.mRestricted);
pf.set(displayFrames.mRestricted);
@@ -2111,8 +2186,12 @@ public class DisplayPolicy {
final int cutoutMode = attrs.layoutInDisplayCutoutMode;
final boolean attachedInParent = attached != null && !layoutInScreen;
+ final boolean requestedFullscreen = (fl & FLAG_FULLSCREEN) != 0
+ || (requestedSysUiFl & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0
+ || !win.getClientInsetsState().getSource(ITYPE_STATUS_BAR).isVisible();
final boolean requestedHideNavigation =
- (requestedSysUiFl & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0;
+ (requestedSysUiFl & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0
+ || !win.getClientInsetsState().getSource(ITYPE_NAVIGATION_BAR).isVisible();
// TYPE_BASE_APPLICATION windows are never considered floating here because they don't get
// cropped / shifted to the displayFrame in WindowState.
@@ -2195,6 +2274,9 @@ public class DisplayPolicy {
}
win.computeFrameLw();
+ if (win.getControllableInsetProvider() != null) {
+ win.getControllableInsetProvider().updateSourceFrame();
+ }
// Dock windows carve out the bottom of the screen, so normal windows
// can't appear underneath them.
if (type == TYPE_INPUT_METHOD && win.isVisibleLw()
@@ -2985,7 +3067,7 @@ public class DisplayPolicy {
mDisplayContent.getInsetsPolicy().showTransient(IntArray.wrap(
new int[]{ITYPE_STATUS_BAR, ITYPE_NAVIGATION_BAR}));
} else {
- controlTarget.showInsets(WindowInsets.Type.systemBars(), false);
+ controlTarget.showInsets(Type.systemBars(), false);
}
} else {
boolean sb = mStatusBarController.checkShowTransientBarLw();
@@ -3109,6 +3191,7 @@ public class DisplayPolicy {
&& mLastAppearance == appearance
&& mLastFullscreenAppearance == fullscreenAppearance
&& mLastDockedAppearance == dockedAppearance
+ && mLastBehavior == behavior
&& mLastFocusIsFullscreen == isFullscreen
&& mLastFocusIsImmersive == isImmersive
&& mFocusedApp == win.getAppToken()
@@ -3125,6 +3208,7 @@ public class DisplayPolicy {
mLastAppearance = appearance;
mLastFullscreenAppearance = fullscreenAppearance;
mLastDockedAppearance = dockedAppearance;
+ mLastBehavior = behavior;
mLastFocusIsFullscreen = isFullscreen;
mLastFocusIsImmersive = isImmersive;
mFocusedApp = win.getAppToken();
diff --git a/services/core/java/com/android/server/wm/DisplayRotation.java b/services/core/java/com/android/server/wm/DisplayRotation.java
index c7c3f8ad54a2..b59c4e38214b 100644
--- a/services/core/java/com/android/server/wm/DisplayRotation.java
+++ b/services/core/java/com/android/server/wm/DisplayRotation.java
@@ -442,13 +442,17 @@ public class DisplayRotation {
final int lastOrientation = mLastOrientation;
final int rotation = rotationForOrientation(lastOrientation, oldRotation);
ProtoLog.v(WM_DEBUG_ORIENTATION,
- "Computed rotation=%d for display id=%d based on lastOrientation=%d and "
- + "oldRotation=%d",
- rotation, displayId, lastOrientation, oldRotation);
+ "Computed rotation=%s (%d) for display id=%d based on lastOrientation=%s (%d) and "
+ + "oldRotation=%s (%d)",
+ Surface.rotationToString(rotation), rotation,
+ displayId,
+ ActivityInfo.screenOrientationToString(lastOrientation), lastOrientation,
+ Surface.rotationToString(oldRotation), oldRotation);
ProtoLog.v(WM_DEBUG_ORIENTATION,
- "Display id=%d selected orientation %d, got rotation %d", displayId,
- lastOrientation, rotation);
+ "Display id=%d selected orientation %s (%d), got rotation %s (%d)", displayId,
+ ActivityInfo.screenOrientationToString(lastOrientation), lastOrientation,
+ Surface.rotationToString(rotation), rotation);
if (oldRotation == rotation) {
// No change.
diff --git a/services/core/java/com/android/server/wm/DisplayWindowListenerController.java b/services/core/java/com/android/server/wm/DisplayWindowListenerController.java
index 78fea74da811..bb31d4522890 100644
--- a/services/core/java/com/android/server/wm/DisplayWindowListenerController.java
+++ b/services/core/java/com/android/server/wm/DisplayWindowListenerController.java
@@ -41,7 +41,7 @@ class DisplayWindowListenerController {
try {
for (int i = 0; i < mService.mAtmService.mRootActivityContainer.getChildCount();
++i) {
- ActivityDisplay d = mService.mAtmService.mRootActivityContainer.getChildAt(i);
+ DisplayContent d = mService.mAtmService.mRootActivityContainer.getChildAt(i);
listener.onDisplayAdded(d.mDisplayId);
}
} catch (RemoteException e) { }
@@ -52,7 +52,7 @@ class DisplayWindowListenerController {
mDisplayListeners.unregister(listener);
}
- void dispatchDisplayAdded(ActivityDisplay display) {
+ void dispatchDisplayAdded(DisplayContent display) {
int count = mDisplayListeners.beginBroadcast();
for (int i = 0; i < count; ++i) {
try {
@@ -85,7 +85,7 @@ class DisplayWindowListenerController {
mDisplayListeners.finishBroadcast();
}
- void dispatchDisplayRemoved(ActivityDisplay display) {
+ void dispatchDisplayRemoved(DisplayContent display) {
int count = mDisplayListeners.beginBroadcast();
for (int i = 0; i < count; ++i) {
try {
diff --git a/services/core/java/com/android/server/wm/DockedStackDividerController.java b/services/core/java/com/android/server/wm/DockedStackDividerController.java
index 1a1a7d4d8e0c..6b5859d418ec 100644
--- a/services/core/java/com/android/server/wm/DockedStackDividerController.java
+++ b/services/core/java/com/android/server/wm/DockedStackDividerController.java
@@ -259,7 +259,7 @@ public class DockedStackDividerController {
if (homeStack == null) {
return false;
}
- final Task homeTask = homeStack.findHomeTask();
+ final Task homeTask = homeStack.getTopMostTask();
return homeTask != null && homeTask.isResizeable();
}
@@ -708,7 +708,7 @@ public class DockedStackDividerController {
if (homeStack == null) {
return;
}
- final Task homeTask = homeStack.findHomeTask();
+ final Task homeTask = homeStack.getTopMostTask();
if (homeTask == null || !isWithinDisplay(homeTask)) {
return;
}
diff --git a/services/core/java/com/android/server/wm/EnsureActivitiesVisibleHelper.java b/services/core/java/com/android/server/wm/EnsureActivitiesVisibleHelper.java
index 3aae1b1d7c8f..949ff195d731 100644
--- a/services/core/java/com/android/server/wm/EnsureActivitiesVisibleHelper.java
+++ b/services/core/java/com/android/server/wm/EnsureActivitiesVisibleHelper.java
@@ -45,7 +45,7 @@ class EnsureActivitiesVisibleHelper {
void reset(ActivityRecord starting, int configChanges, boolean preserveWindows,
boolean notifyClients) {
mStarting = starting;
- mTop = mContiner.topRunningActivityLocked();
+ mTop = mContiner.topRunningActivity();
// If the top activity is not fullscreen, then we need to make sure any activities under it
// are now visible.
mAboveTop = mTop != null;
diff --git a/services/core/java/com/android/server/wm/ImmersiveModeConfirmation.java b/services/core/java/com/android/server/wm/ImmersiveModeConfirmation.java
index 82ac6b897a8f..bef1442c73c5 100644
--- a/services/core/java/com/android/server/wm/ImmersiveModeConfirmation.java
+++ b/services/core/java/com/android/server/wm/ImmersiveModeConfirmation.java
@@ -46,6 +46,7 @@ import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
+import android.view.WindowInsets.Type;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
@@ -189,6 +190,7 @@ public class ImmersiveModeConfirmation {
| WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
PixelFormat.TRANSLUCENT);
+ lp.setFitWindowInsetsTypes(lp.getFitWindowInsetsTypes() & ~Type.statusBars());
lp.privateFlags |= WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS;
lp.setTitle("ImmersiveModeConfirmation");
lp.windowAnimations = com.android.internal.R.style.Animation_ImmersiveModeConfirmation;
diff --git a/services/core/java/com/android/server/wm/InsetsPolicy.java b/services/core/java/com/android/server/wm/InsetsPolicy.java
index d50bcc4c23ac..af84836b433e 100644
--- a/services/core/java/com/android/server/wm/InsetsPolicy.java
+++ b/services/core/java/com/android/server/wm/InsetsPolicy.java
@@ -45,7 +45,7 @@ class InsetsPolicy {
private final IntArray mShowingTransientTypes = new IntArray();
private WindowState mFocusedWin;
- private BarWindow mTopBar = new BarWindow(StatusBarManager.WINDOW_STATUS_BAR);
+ private BarWindow mStatusBar = new BarWindow(StatusBarManager.WINDOW_STATUS_BAR);
private BarWindow mNavBar = new BarWindow(StatusBarManager.WINDOW_NAVIGATION_BAR);
InsetsPolicy(InsetsStateController stateController, DisplayContent displayContent) {
@@ -57,15 +57,15 @@ class InsetsPolicy {
/** Updates the target which can control system bars. */
void updateBarControlTarget(@Nullable WindowState focusedWin) {
mFocusedWin = focusedWin;
- mStateController.onBarControlTargetChanged(getTopControlTarget(focusedWin),
- getFakeTopControlTarget(focusedWin),
+ mStateController.onBarControlTargetChanged(getStatusControlTarget(focusedWin),
+ getFakeStatusControlTarget(focusedWin),
getNavControlTarget(focusedWin),
getFakeNavControlTarget(focusedWin));
if (ViewRootImpl.sNewInsetsMode != ViewRootImpl.NEW_INSETS_MODE_FULL) {
return;
}
- mTopBar.setVisible(focusedWin == null
- || focusedWin != getTopControlTarget(focusedWin)
+ mStatusBar.setVisible(focusedWin == null
+ || focusedWin != getStatusControlTarget(focusedWin)
|| focusedWin.getClientInsetsState().getSource(ITYPE_STATUS_BAR).isVisible());
mNavBar.setVisible(focusedWin == null
|| focusedWin != getNavControlTarget(focusedWin)
@@ -110,6 +110,10 @@ class InsetsPolicy {
mStateController.notifyInsetsChanged();
}
+ boolean isTransient(@InternalInsetsType int type) {
+ return mShowingTransientTypes.indexOf(type) != -1;
+ }
+
/**
* @see InsetsStateController#getInsetsForDispatch
*/
@@ -130,8 +134,8 @@ class InsetsPolicy {
if (ViewRootImpl.sNewInsetsMode != ViewRootImpl.NEW_INSETS_MODE_FULL) {
return;
}
- if (windowState == getTopControlTarget(mFocusedWin)) {
- mTopBar.setVisible(state.getSource(ITYPE_STATUS_BAR).isVisible());
+ if (windowState == getStatusControlTarget(mFocusedWin)) {
+ mStatusBar.setVisible(state.getSource(ITYPE_STATUS_BAR).isVisible());
}
if (windowState == getNavControlTarget(mFocusedWin)) {
mNavBar.setVisible(state.getSource(ITYPE_NAVIGATION_BAR).isVisible());
@@ -164,7 +168,8 @@ class InsetsPolicy {
}
}
- private @Nullable InsetsControlTarget getFakeTopControlTarget(@Nullable WindowState focused) {
+ private @Nullable InsetsControlTarget getFakeStatusControlTarget(
+ @Nullable WindowState focused) {
if (mShowingTransientTypes.indexOf(ITYPE_STATUS_BAR) != -1) {
return focused;
}
@@ -178,7 +183,7 @@ class InsetsPolicy {
return null;
}
- private @Nullable InsetsControlTarget getTopControlTarget(@Nullable WindowState focusedWin) {
+ private @Nullable InsetsControlTarget getStatusControlTarget(@Nullable WindowState focusedWin) {
if (mShowingTransientTypes.indexOf(ITYPE_STATUS_BAR) != -1) {
return mTransientControlTarget;
}
diff --git a/services/core/java/com/android/server/wm/InsetsSourceProvider.java b/services/core/java/com/android/server/wm/InsetsSourceProvider.java
index 69e8fdc3229e..184e7d61c355 100644
--- a/services/core/java/com/android/server/wm/InsetsSourceProvider.java
+++ b/services/core/java/com/android/server/wm/InsetsSourceProvider.java
@@ -24,6 +24,8 @@ import static android.view.ViewRootImpl.NEW_INSETS_MODE_IME;
import static android.view.ViewRootImpl.NEW_INSETS_MODE_NONE;
import static android.view.ViewRootImpl.sNewInsetsMode;
+import static com.android.server.wm.WindowManagerService.H.LAYOUT_AND_ASSIGN_WINDOW_LAYERS_IF_NEEDED;
+
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.graphics.Point;
@@ -36,7 +38,6 @@ import android.view.SurfaceControl;
import android.view.SurfaceControl.Transaction;
import com.android.internal.util.function.TriConsumer;
-import com.android.internal.util.function.pooled.PooledLambda;
import com.android.server.wm.SurfaceAnimator.OnAnimationFinishedCallback;
import java.io.PrintWriter;
@@ -141,9 +142,10 @@ class InsetsSourceProvider {
}
/**
- * Called when a layout pass has occurred.
+ * The source frame can affect the layout of other windows, so this should be called once the
+ * window gets laid out.
*/
- void onPostLayout() {
+ void updateSourceFrame() {
if (mWin == null) {
return;
}
@@ -155,6 +157,17 @@ class InsetsSourceProvider {
mTmpRect.inset(mWin.mGivenContentInsets);
}
mSource.setFrame(mTmpRect);
+ }
+
+ /**
+ * Called when a layout pass has occurred.
+ */
+ void onPostLayout() {
+ if (mWin == null) {
+ return;
+ }
+
+ updateSourceFrame();
if (mControl != null) {
final Rect frame = mWin.getWindowFrames().mFrame;
if (mControl.setSurfacePosition(frame.left, frame.top)) {
@@ -210,8 +223,8 @@ class InsetsSourceProvider {
return;
}
mClientVisible = clientVisible;
- mDisplayContent.mWmService.mH.sendMessage(PooledLambda.obtainMessage(
- DisplayContent::layoutAndAssignWindowLayersIfNeeded, mDisplayContent));
+ mDisplayContent.mWmService.mH.obtainMessage(
+ LAYOUT_AND_ASSIGN_WINDOW_LAYERS_IF_NEEDED, mDisplayContent).sendToTarget();
updateVisibility();
}
diff --git a/services/core/java/com/android/server/wm/KeyguardController.java b/services/core/java/com/android/server/wm/KeyguardController.java
index ac5c96b83e56..6f8195712337 100644
--- a/services/core/java/com/android/server/wm/KeyguardController.java
+++ b/services/core/java/com/android/server/wm/KeyguardController.java
@@ -296,7 +296,7 @@ class KeyguardController {
boolean requestDismissKeyguard = false;
for (int displayNdx = mRootActivityContainer.getChildCount() - 1;
displayNdx >= 0; displayNdx--) {
- final ActivityDisplay display = mRootActivityContainer.getChildAt(displayNdx);
+ final DisplayContent display = mRootActivityContainer.getChildAt(displayNdx);
final KeyguardDisplayState state = getDisplay(display.mDisplayId);
state.visibilitiesUpdated(this, display);
requestDismissKeyguard |= state.mRequestDismissKeyguard;
@@ -420,7 +420,7 @@ class KeyguardController {
private void updateKeyguardSleepToken() {
for (int displayNdx = mRootActivityContainer.getChildCount() - 1;
displayNdx >= 0; displayNdx--) {
- final ActivityDisplay display = mRootActivityContainer.getChildAt(displayNdx);
+ final DisplayContent display = mRootActivityContainer.getChildAt(displayNdx);
updateKeyguardSleepToken(display.mDisplayId);
}
}
@@ -483,7 +483,7 @@ class KeyguardController {
}
}
- void visibilitiesUpdated(KeyguardController controller, ActivityDisplay display) {
+ void visibilitiesUpdated(KeyguardController controller, DisplayContent display) {
final boolean lastOccluded = mOccluded;
final ActivityRecord lastDismissActivity = mDismissingKeyguardActivity;
mRequestDismissKeyguard = false;
@@ -494,7 +494,7 @@ class KeyguardController {
if (stack != null) {
final ActivityRecord topDismissing = stack.getTopDismissingKeyguardActivity();
mOccluded = stack.topActivityOccludesKeyguard() || (topDismissing != null
- && stack.topRunningActivityLocked() == topDismissing
+ && stack.topRunningActivity() == topDismissing
&& controller.canShowWhileOccluded(
true /* dismissKeyguard */,
false /* showWhenLocked */));
@@ -530,7 +530,7 @@ class KeyguardController {
* Only the top non-pinned activity of the focusable stack on each display can control its
* occlusion state.
*/
- private ActivityStack getStackForControllingOccluding(ActivityDisplay display) {
+ private ActivityStack getStackForControllingOccluding(DisplayContent display) {
for (int stackNdx = display.getStackCount() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = display.getStackAt(stackNdx);
if (stack != null && stack.isFocusableAndVisible()
diff --git a/services/core/java/com/android/server/wm/LaunchParamsPersister.java b/services/core/java/com/android/server/wm/LaunchParamsPersister.java
index c3bcc740a065..8cf3dc8ff970 100644
--- a/services/core/java/com/android/server/wm/LaunchParamsPersister.java
+++ b/services/core/java/com/android/server/wm/LaunchParamsPersister.java
@@ -223,8 +223,8 @@ class LaunchParamsPersister {
private boolean saveTaskToLaunchParam(Task task, PersistableLaunchParams params) {
final ActivityStack stack = task.getStack();
final int displayId = stack.mDisplayId;
- final ActivityDisplay display =
- mSupervisor.mRootActivityContainer.getActivityDisplay(displayId);
+ final DisplayContent display =
+ mSupervisor.mRootActivityContainer.getDisplayContent(displayId);
final DisplayInfo info = new DisplayInfo();
display.mDisplay.getDisplayInfo(info);
@@ -260,7 +260,7 @@ class LaunchParamsPersister {
return;
}
- final ActivityDisplay display = mSupervisor.mRootActivityContainer.getActivityDisplay(
+ final DisplayContent display = mSupervisor.mRootActivityContainer.getDisplayContent(
persistableParams.mDisplayUniqueId);
if (display != null) {
outParams.mPreferredDisplayId = display.mDisplayId;
diff --git a/services/core/java/com/android/server/wm/LockTaskController.java b/services/core/java/com/android/server/wm/LockTaskController.java
index 2ece6e21b2c5..7a72b435ac8a 100644
--- a/services/core/java/com/android/server/wm/LockTaskController.java
+++ b/services/core/java/com/android/server/wm/LockTaskController.java
@@ -150,7 +150,7 @@ public class LockTaskController {
* The first task in the list, which started the current LockTask session, is called the root
* task. It coincides with the Home task in a typical multi-app kiosk deployment. When there are
* more than one locked tasks, the root task can't be finished. Nor can it be moved to the back
- * of the stack by {@link ActivityStack#moveTaskToBackLocked(int)};
+ * of the stack by {@link ActivityStack#moveTaskToBack(Task)};
*
* Calling {@link Activity#stopLockTask()} on the root task will finish all tasks but itself in
* this list, and the device will exit LockTask mode.
@@ -251,7 +251,7 @@ public class LockTaskController {
/**
* @return whether the given task can be moved to the back of the stack with
- * {@link ActivityStack#moveTaskToBackLocked(int)}
+ * {@link ActivityStack#moveTaskToBack(Task)}
* @see #mLockTaskModeTasks
*/
boolean canMoveTaskToBack(Task task) {
@@ -653,10 +653,7 @@ public class LockTaskController {
taskChanged = true;
}
- for (int displayNdx = mSupervisor.mRootActivityContainer.getChildCount() - 1;
- displayNdx >= 0; --displayNdx) {
- mSupervisor.mRootActivityContainer.getChildAt(displayNdx).onLockTaskPackagesUpdated();
- }
+ mSupervisor.mRootActivityContainer.mRootWindowContainer.forAllTasks(Task::setLockTaskAuth);
final ActivityRecord r = mSupervisor.mRootActivityContainer.topRunningActivity();
final Task task = (r != null) ? r.getTask() : null;
diff --git a/services/core/java/com/android/server/wm/RecentTasks.java b/services/core/java/com/android/server/wm/RecentTasks.java
index f0e441fe77b1..71bbb70956f5 100644
--- a/services/core/java/com/android/server/wm/RecentTasks.java
+++ b/services/core/java/com/android/server/wm/RecentTasks.java
@@ -208,10 +208,10 @@ class RecentTasks {
synchronized (mService.mGlobalLock) {
// Unfreeze the task list once we touch down in a task
final RootActivityContainer rac = mService.mRootActivityContainer;
- final DisplayContent dc = rac.getActivityDisplay(displayId).mDisplayContent;
+ final DisplayContent dc = rac.getDisplayContent(displayId).mDisplayContent;
if (dc.pointWithinAppWindow(x, y)) {
final ActivityStack stack = mService.getTopDisplayFocusedStack();
- final Task topTask = stack != null ? stack.topTask() : null;
+ final Task topTask = stack != null ? stack.getTopMostTask() : null;
resetFreezeTaskListReordering(topTask);
}
}
@@ -319,7 +319,7 @@ class RecentTasks {
void resetFreezeTaskListReorderingOnTimeout() {
synchronized (mService.mGlobalLock) {
final ActivityStack focusedStack = mService.getTopDisplayFocusedStack();
- final Task topTask = focusedStack != null ? focusedStack.topTask() : null;
+ final Task topTask = focusedStack != null ? focusedStack.getTopMostTask() : null;
resetFreezeTaskListReordering(topTask);
}
}
@@ -630,8 +630,7 @@ class RecentTasks {
&& task.realActivitySuspended != suspended) {
task.realActivitySuspended = suspended;
if (suspended) {
- mSupervisor.removeTaskByIdLocked(task.mTaskId, false,
- REMOVE_FROM_RECENTS, "suspended-package");
+ mSupervisor.removeTask(task, false, REMOVE_FROM_RECENTS, "suspended-package");
}
notifyTaskPersisterLocked(task, false);
}
@@ -658,8 +657,7 @@ class RecentTasks {
if (task.mUserId != userId) continue;
if (!taskPackageName.equals(packageName)) continue;
- mSupervisor.removeTaskByIdLocked(task.mTaskId, true, REMOVE_FROM_RECENTS,
- "remove-package-task");
+ mSupervisor.removeTask(task, true, REMOVE_FROM_RECENTS, "remove-package-task");
}
}
@@ -687,8 +685,7 @@ class RecentTasks {
final boolean sameComponent = cn != null && cn.getPackageName().equals(packageName)
&& (filterByClasses == null || filterByClasses.contains(cn.getClassName()));
if (sameComponent) {
- mSupervisor.removeTaskByIdLocked(task.mTaskId, false,
- REMOVE_FROM_RECENTS, "disabled-package");
+ mSupervisor.removeTask(task, false, REMOVE_FROM_RECENTS, "disabled-package");
}
}
}
@@ -1147,6 +1144,7 @@ class RecentTasks {
// Trim the set of tasks to the active set
trimInactiveRecentTasks();
+ notifyTaskPersisterLocked(task, false /* flush */);
}
/**
@@ -1306,9 +1304,9 @@ class RecentTasks {
case WINDOWING_MODE_PINNED:
return false;
case WINDOWING_MODE_SPLIT_SCREEN_PRIMARY:
- if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "\ttop=" + task.getStack().topTask());
+ if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "\ttop=" + task.getStack().getTopMostTask());
final ActivityStack stack = task.getStack();
- if (stack != null && stack.topTask() == task) {
+ if (stack != null && stack.getTopMostTask() == task) {
// Only the non-top task of the primary split screen mode is visible
return false;
}
@@ -1319,7 +1317,7 @@ class RecentTasks {
// TODO(b/126185105): Find a different signal to use besides isSingleTaskInstance
final ActivityStack stack = task.getStack();
if (stack != null) {
- ActivityDisplay display = stack.getDisplay();
+ DisplayContent display = stack.getDisplay();
if (display != null && display.isSingleTaskInstance()) {
return false;
}
@@ -1389,7 +1387,7 @@ class RecentTasks {
}
// Trim tasks that are in stacks that are behind the home stack
- final ActivityDisplay display = stack.getDisplay();
+ final DisplayContent display = stack.getDisplay();
return display.getIndexOf(stack) < display.getIndexOf(display.getHomeStack());
}
diff --git a/services/core/java/com/android/server/wm/RecentsAnimation.java b/services/core/java/com/android/server/wm/RecentsAnimation.java
index d5bbe6bb8b9c..0a8e7471af81 100644
--- a/services/core/java/com/android/server/wm/RecentsAnimation.java
+++ b/services/core/java/com/android/server/wm/RecentsAnimation.java
@@ -53,14 +53,14 @@ import com.android.server.wm.RecentsAnimationController.RecentsAnimationCallback
* cleanup. See {@link com.android.server.wm.RecentsAnimationController}.
*/
class RecentsAnimation implements RecentsAnimationCallbacks,
- ActivityDisplay.OnStackOrderChangedListener {
+ DisplayContent.OnStackOrderChangedListener {
private static final String TAG = RecentsAnimation.class.getSimpleName();
private final ActivityTaskManagerService mService;
private final ActivityStackSupervisor mStackSupervisor;
private final ActivityStartController mActivityStartController;
private final WindowManagerService mWindowManager;
- private final ActivityDisplay mDefaultDisplay;
+ private final DisplayContent mDefaultDisplay;
private final Intent mTargetIntent;
private final ComponentName mRecentsComponent;
private final int mRecentsUid;
@@ -180,7 +180,7 @@ class RecentsAnimation implements RecentsAnimationCallbacks,
ActivityRecord targetActivity = getTargetActivity(targetStack);
final boolean hasExistingActivity = targetActivity != null;
if (hasExistingActivity) {
- final ActivityDisplay display = targetActivity.getDisplay();
+ final DisplayContent display = targetActivity.getDisplay();
mRestoreTargetBehindStack = display.getStackAbove(targetStack);
if (mRestoreTargetBehindStack == null) {
notifyAnimationCancelBeforeStart(recentsAnimationRunner);
@@ -216,7 +216,7 @@ class RecentsAnimation implements RecentsAnimationCallbacks,
// and default launchers coexisting), then move the task to the top as a part of
// moving the stack to the front
final Task task = targetActivity.getTask();
- if (targetStack.topTask() != task) {
+ if (targetStack.getTopMostTask() != task) {
targetStack.positionChildAtTop(task);
}
} else {
@@ -250,7 +250,7 @@ class RecentsAnimation implements RecentsAnimationCallbacks,
mWindowManager.cancelRecentsAnimation(REORDER_MOVE_TO_ORIGINAL_POSITION,
"startRecentsActivity");
mWindowManager.initializeRecentsAnimation(mTargetActivityType, recentsAnimationRunner,
- this, mDefaultDisplay.mDisplayId,
+ this, mDefaultDisplay.getDisplayId(),
mStackSupervisor.mRecentTasks.getRecentTaskIds(), targetActivity);
// If we updated the launch-behind state, update the visibility of the activities after
@@ -351,7 +351,7 @@ class RecentsAnimation implements RecentsAnimationCallbacks,
}
} else if (reorderMode == REORDER_MOVE_TO_ORIGINAL_POSITION){
// Restore the target stack to its previous position
- final ActivityDisplay display = targetActivity.getDisplay();
+ final DisplayContent display = targetActivity.getDisplay();
display.moveStackBehindStack(targetStack, mRestoreTargetBehindStack);
if (WM_DEBUG_RECENTS_ANIMATIONS.isLogToAny()) {
final ActivityStack aboveTargetStack =
@@ -432,7 +432,7 @@ class RecentsAnimation implements RecentsAnimationCallbacks,
// cases:
// 1) The next launching task is not being animated by the recents animation
// 2) The next task is home activity. (i.e. pressing home key to back home in recents).
- if ((!controller.isAnimatingTask(stack.getTopChild())
+ if ((!controller.isAnimatingTask(stack.getTopMostTask())
|| controller.isTargetApp(stack.getTopNonFinishingActivity()))
&& controller.shouldDeferCancelUntilNextTransition()) {
// Always prepare an app transition since we rely on the transition callbacks to cleanup
diff --git a/services/core/java/com/android/server/wm/ResetTargetTaskHelper.java b/services/core/java/com/android/server/wm/ResetTargetTaskHelper.java
index 3aa91d52a47d..d787cbc7cb6b 100644
--- a/services/core/java/com/android/server/wm/ResetTargetTaskHelper.java
+++ b/services/core/java/com/android/server/wm/ResetTargetTaskHelper.java
@@ -258,7 +258,7 @@ class ResetTargetTaskHelper {
private void processCreatedTasks() {
if (mCreatedTasks.isEmpty()) return;
- ActivityDisplay display = mParent.getDisplay();
+ DisplayContent display = mParent.getDisplay();
final boolean singleTaskInstanceDisplay = display.isSingleTaskInstance();
if (singleTaskInstanceDisplay) {
display = mParent.mRootActivityContainer.getDefaultDisplay();
diff --git a/services/core/java/com/android/server/wm/RootActivityContainer.java b/services/core/java/com/android/server/wm/RootActivityContainer.java
index 5653ec07a340..7dd9790403fc 100644
--- a/services/core/java/com/android/server/wm/RootActivityContainer.java
+++ b/services/core/java/com/android/server/wm/RootActivityContainer.java
@@ -109,7 +109,6 @@ import android.view.DisplayInfo;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.app.ResolverActivity;
-import com.android.internal.util.ToBooleanFunction;
import com.android.internal.util.function.pooled.PooledConsumer;
import com.android.internal.util.function.pooled.PooledFunction;
import com.android.internal.util.function.pooled.PooledLambda;
@@ -129,6 +128,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Set;
+import java.util.function.Function;
/**
* Root node for activity containers.
@@ -168,17 +168,17 @@ class RootActivityContainer extends ConfigurationContainer
WindowManagerService mWindowManager;
DisplayManager mDisplayManager;
private DisplayManagerInternal mDisplayManagerInternal;
- // TODO: Remove after object merge with RootWindowContainer.
- private RootWindowContainer mRootWindowContainer;
+ // TODO(root-unify): Remove after object merge with RootWindowContainer.
+ RootWindowContainer mRootWindowContainer;
/**
* List of displays which contain activities, sorted by z-order.
* The last entry in the list is the topmost.
*/
- private final ArrayList<ActivityDisplay> mActivityDisplays = new ArrayList<>();
+ private final ArrayList<DisplayContent> mDisplayContents = new ArrayList<>();
/** Reference to default display so we can quickly look it up. */
- private ActivityDisplay mDefaultDisplay;
+ private DisplayContent mDefaultDisplay;
private final SparseArray<IntArray> mDisplayAccessUIDs = new SparseArray<>();
/** The current user */
@@ -214,7 +214,7 @@ class RootActivityContainer extends ConfigurationContainer
private RemoteException mTmpRemoteException;
private final FindTaskResult mTmpFindTaskResult = new FindTaskResult();
- static class FindTaskResult implements ToBooleanFunction<Task> {
+ static class FindTaskResult implements Function<Task, Boolean> {
ActivityRecord mRecord;
boolean mIdealMatch;
@@ -259,7 +259,7 @@ class RootActivityContainer extends ConfigurationContainer
}
@Override
- public boolean apply(Task task) {
+ public Boolean apply(Task task) {
if (task.voiceSession != null) {
// We never match voice sessions; those always run independently.
if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": voice session");
@@ -354,35 +354,35 @@ class RootActivityContainer extends ConfigurationContainer
final Display[] displays = mDisplayManager.getDisplays();
for (int displayNdx = 0; displayNdx < displays.length; ++displayNdx) {
final Display display = displays[displayNdx];
- final ActivityDisplay activityDisplay = new ActivityDisplay(this, display);
- if (activityDisplay.mDisplayId == DEFAULT_DISPLAY) {
- mDefaultDisplay = activityDisplay;
+ final DisplayContent displayContent = new DisplayContent(display, this);
+ if (displayContent.mDisplayId == DEFAULT_DISPLAY) {
+ mDefaultDisplay = displayContent;
}
- addChild(activityDisplay, ActivityDisplay.POSITION_TOP);
+ addChild(displayContent, DisplayContent.POSITION_TOP);
}
calculateDefaultMinimalSizeOfResizeableTasks();
- final ActivityDisplay defaultDisplay = getDefaultDisplay();
+ final DisplayContent defaultDisplay = getDefaultDisplay();
defaultDisplay.getOrCreateStack(WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, ON_TOP);
- positionChildAt(defaultDisplay, ActivityDisplay.POSITION_TOP);
+ positionChildAt(defaultDisplay, DisplayContent.POSITION_TOP);
}
// TODO(multi-display): Look at all callpoints to make sure they make sense in multi-display.
- ActivityDisplay getDefaultDisplay() {
+ DisplayContent getDefaultDisplay() {
return mDefaultDisplay;
}
/**
- * Get an existing instance of {@link ActivityDisplay} that has the given uniqueId. Unique ID is
+ * Get an existing instance of {@link DisplayContent} that has the given uniqueId. Unique ID is
* defined in {@link DisplayInfo#uniqueId}.
*
* @param uniqueId the unique ID of the display
- * @return the {@link ActivityDisplay} or {@code null} if nothing is found.
+ * @return the {@link DisplayContent} or {@code null} if nothing is found.
*/
- ActivityDisplay getActivityDisplay(String uniqueId) {
- for (int i = mActivityDisplays.size() - 1; i >= 0; --i) {
- final ActivityDisplay display = mActivityDisplays.get(i);
+ DisplayContent getDisplayContent(String uniqueId) {
+ for (int i = mDisplayContents.size() - 1; i >= 0; --i) {
+ final DisplayContent display = mDisplayContents.get(i);
final boolean isValid = display.mDisplay.isValid();
if (isValid && display.mDisplay.getUniqueId().equals(uniqueId)) {
return display;
@@ -392,26 +392,26 @@ class RootActivityContainer extends ConfigurationContainer
return null;
}
- // TODO: Look into consolidating with getActivityDisplayOrCreate()
- ActivityDisplay getActivityDisplay(int displayId) {
- for (int i = mActivityDisplays.size() - 1; i >= 0; --i) {
- final ActivityDisplay activityDisplay = mActivityDisplays.get(i);
- if (activityDisplay.mDisplayId == displayId) {
- return activityDisplay;
+ // TODO: Look into consolidating with getDisplayContentOrCreate()
+ DisplayContent getDisplayContent(int displayId) {
+ for (int i = mDisplayContents.size() - 1; i >= 0; --i) {
+ final DisplayContent displayContent = mDisplayContents.get(i);
+ if (displayContent.mDisplayId == displayId) {
+ return displayContent;
}
}
return null;
}
/**
- * Get an existing instance of {@link ActivityDisplay} or create new if there is a
+ * Get an existing instance of {@link DisplayContent} or create new if there is a
* corresponding record in display manager.
*/
- // TODO: Look into consolidating with getActivityDisplay()
- @Nullable ActivityDisplay getActivityDisplayOrCreate(int displayId) {
- ActivityDisplay activityDisplay = getActivityDisplay(displayId);
- if (activityDisplay != null) {
- return activityDisplay;
+ // TODO: Look into consolidating with getDisplayContent()
+ @Nullable DisplayContent getDisplayContentOrCreate(int displayId) {
+ DisplayContent displayContent = getDisplayContent(displayId);
+ if (displayContent != null) {
+ return displayContent;
}
if (mDisplayManager == null) {
// The system isn't fully initialized yet.
@@ -423,9 +423,9 @@ class RootActivityContainer extends ConfigurationContainer
return null;
}
// The display hasn't been added to ActivityManager yet, create a new record now.
- activityDisplay = new ActivityDisplay(this, display);
- addChild(activityDisplay, ActivityDisplay.POSITION_BOTTOM);
- return activityDisplay;
+ displayContent = new DisplayContent(display, this);
+ addChild(displayContent, DisplayContent.POSITION_BOTTOM);
+ return displayContent;
}
ActivityRecord getDefaultDisplayHomeActivity() {
@@ -433,21 +433,21 @@ class RootActivityContainer extends ConfigurationContainer
}
ActivityRecord getDefaultDisplayHomeActivityForUser(int userId) {
- return getActivityDisplay(DEFAULT_DISPLAY).getHomeActivityForUser(userId);
+ return getDisplayContent(DEFAULT_DISPLAY).getHomeActivityForUser(userId);
}
boolean startHomeOnAllDisplays(int userId, String reason) {
boolean homeStarted = false;
- for (int i = mActivityDisplays.size() - 1; i >= 0; i--) {
- final int displayId = mActivityDisplays.get(i).mDisplayId;
+ for (int i = mDisplayContents.size() - 1; i >= 0; i--) {
+ final int displayId = mDisplayContents.get(i).mDisplayId;
homeStarted |= startHomeOnDisplay(userId, reason, displayId);
}
return homeStarted;
}
void startHomeOnEmptyDisplays(String reason) {
- for (int i = mActivityDisplays.size() - 1; i >= 0; i--) {
- final ActivityDisplay display = mActivityDisplays.get(i);
+ for (int i = mDisplayContents.size() - 1; i >= 0; i--) {
+ final DisplayContent display = mDisplayContents.get(i);
if (display.topRunningActivity() == null) {
startHomeOnDisplay(mCurrentUser, reason, display.mDisplayId);
}
@@ -629,7 +629,7 @@ class RootActivityContainer extends ConfigurationContainer
displayId = DEFAULT_DISPLAY;
}
- final ActivityRecord r = getActivityDisplay(displayId).getHomeActivity();
+ final ActivityRecord r = getDisplayContent(displayId).getHomeActivity();
final String myReason = reason + " resumeHomeActivity";
// Only resume home activity if isn't finishing.
@@ -671,7 +671,7 @@ class RootActivityContainer extends ConfigurationContainer
return false;
}
- final ActivityDisplay display = getActivityDisplay(displayId);
+ final DisplayContent display = getDisplayContent(displayId);
if (display == null || display.isRemoved() || !display.supportsSystemDecorations()) {
// Can't launch home on display that doesn't support system decorations.
return false;
@@ -771,10 +771,8 @@ class RootActivityContainer extends ConfigurationContainer
if (displayContent != null) {
// Update the configuration of the activities on the display.
- // TODO(display-merge): Remove cast
- return ((ActivityDisplay) displayContent)
- .updateDisplayOverrideConfigurationLocked(config, starting, deferResume,
- null /* result */);
+ return displayContent.updateDisplayOverrideConfigurationLocked(config, starting,
+ deferResume, null /* result */);
} else {
return true;
}
@@ -788,8 +786,8 @@ class RootActivityContainer extends ConfigurationContainer
final ArrayList<IBinder> topActivityTokens = new ArrayList<>();
final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
// Traverse all displays.
- for (int i = mActivityDisplays.size() - 1; i >= 0; i--) {
- final ActivityDisplay display = mActivityDisplays.get(i);
+ for (int i = mDisplayContents.size() - 1; i >= 0; i--) {
+ final DisplayContent display = mDisplayContents.get(i);
// Traverse all stacks on a display.
for (int j = display.getStackCount() - 1; j >= 0; --j) {
final ActivityStack stack = display.getStackAt(j);
@@ -810,8 +808,8 @@ class RootActivityContainer extends ConfigurationContainer
}
ActivityStack getTopDisplayFocusedStack() {
- for (int i = mActivityDisplays.size() - 1; i >= 0; --i) {
- final ActivityStack focusedStack = mActivityDisplays.get(i).getFocusedStack();
+ for (int i = mDisplayContents.size() - 1; i >= 0; --i) {
+ final ActivityStack focusedStack = mDisplayContents.get(i).getFocusedStack();
if (focusedStack != null) {
return focusedStack;
}
@@ -830,8 +828,8 @@ class RootActivityContainer extends ConfigurationContainer
}
// The top focused stack might not have a resumed activity yet - look on all displays in
// focus order.
- for (int i = mActivityDisplays.size() - 1; i >= 0; --i) {
- final ActivityDisplay display = mActivityDisplays.get(i);
+ for (int i = mDisplayContents.size() - 1; i >= 0; --i) {
+ final DisplayContent display = mDisplayContents.get(i);
final ActivityRecord resumedActivityOnDisplay = display.getResumedActivity();
if (resumedActivityOnDisplay != null) {
return resumedActivityOnDisplay;
@@ -860,8 +858,8 @@ class RootActivityContainer extends ConfigurationContainer
// previous app if this activity is being hosted by the process that is actually still the
// foreground.
WindowProcessController fgApp = null;
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
+ final DisplayContent display = mDisplayContents.get(displayNdx);
for (int stackNdx = display.getStackCount() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = display.getStackAt(stackNdx);
if (isTopDisplayFocusedStack(stack)) {
@@ -888,8 +886,8 @@ class RootActivityContainer extends ConfigurationContainer
boolean attachApplication(WindowProcessController app) throws RemoteException {
final String processName = app.mName;
boolean didSomething = false;
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
+ final DisplayContent display = mDisplayContents.get(displayNdx);
final ActivityStack stack = display.getFocusedStack();
if (stack == null) {
continue;
@@ -899,7 +897,7 @@ class RootActivityContainer extends ConfigurationContainer
mTmpBoolean = false; // Set to true if an activity was started.
final PooledFunction c = PooledLambda.obtainFunction(
RootActivityContainer::startActivityForAttachedApplicationIfNeeded, this,
- PooledLambda.__(ActivityRecord.class), app, stack.topRunningActivityLocked());
+ PooledLambda.__(ActivityRecord.class), app, stack.topRunningActivity());
stack.forAllActivities(c);
c.recycle();
if (mTmpRemoteException != null) {
@@ -957,8 +955,8 @@ class RootActivityContainer extends ConfigurationContainer
try {
mStackSupervisor.getKeyguardController().beginActivityVisibilityUpdate();
// First the front stacks. In case any are not fullscreen and are in front of home.
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
+ final DisplayContent display = mDisplayContents.get(displayNdx);
display.ensureActivitiesVisible(starting, configChanges, preserveWindows,
notifyClients);
}
@@ -987,12 +985,12 @@ class RootActivityContainer extends ConfigurationContainer
mCurrentUser = userId;
mStackSupervisor.mStartingUsers.add(uss);
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
+ final DisplayContent display = mDisplayContents.get(displayNdx);
for (int stackNdx = display.getStackCount() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = display.getStackAt(stackNdx);
stack.switchUser(userId);
- Task task = stack.topTask();
+ Task task = stack.getTopMostTask();
if (task != null) {
stack.positionChildAtTop(task);
}
@@ -1035,8 +1033,8 @@ class RootActivityContainer extends ConfigurationContainer
* @param onTop Indicates whether container should be place on top or on bottom.
*/
void moveStackToDisplay(int stackId, int displayId, boolean onTop) {
- final ActivityDisplay activityDisplay = getActivityDisplayOrCreate(displayId);
- if (activityDisplay == null) {
+ final DisplayContent displayContent = getDisplayContentOrCreate(displayId);
+ if (displayContent == null) {
throw new IllegalArgumentException("moveStackToDisplay: Unknown displayId="
+ displayId);
}
@@ -1046,7 +1044,7 @@ class RootActivityContainer extends ConfigurationContainer
+ stackId);
}
- final ActivityDisplay currentDisplay = stack.getDisplay();
+ final DisplayContent currentDisplay = stack.getDisplay();
if (currentDisplay == null) {
throw new IllegalStateException("moveStackToDisplay: Stack with stack=" + stack
+ " is not attached to any display.");
@@ -1057,14 +1055,14 @@ class RootActivityContainer extends ConfigurationContainer
+ " to its current displayId=" + displayId);
}
- if (activityDisplay.isSingleTaskInstance() && activityDisplay.getStackCount() > 0) {
+ if (displayContent.isSingleTaskInstance() && displayContent.getStackCount() > 0) {
// We don't allow moving stacks to single instance display that already has a child.
Slog.e(TAG, "Can not move stack=" + stack
- + " to single task instance display=" + activityDisplay);
+ + " to single task instance display=" + displayContent);
return;
}
- stack.reparent(activityDisplay.mDisplayContent, onTop);
+ stack.reparent(displayContent.mDisplayContent, onTop);
// TODO(multi-display): resize stacks properly if moved from split-screen.
}
@@ -1075,7 +1073,7 @@ class RootActivityContainer extends ConfigurationContainer
"moveTopStackActivityToPinnedStack: Unknown stackId=" + stackId);
}
- final ActivityRecord r = stack.topRunningActivityLocked();
+ final ActivityRecord r = stack.topRunningActivity();
if (r == null) {
Slog.w(TAG, "moveTopStackActivityToPinnedStack: No top running activity"
+ " in stack=" + stack);
@@ -1097,7 +1095,7 @@ class RootActivityContainer extends ConfigurationContainer
String reason) {
mService.deferWindowLayout();
- final ActivityDisplay display = r.getActivityStack().getDisplay();
+ final DisplayContent display = r.getActivityStack().getDisplay();
try {
final Task task = r.getTask();
@@ -1167,8 +1165,8 @@ class RootActivityContainer extends ConfigurationContainer
}
void executeAppTransitionForAllDisplay() {
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
+ final DisplayContent display = mDisplayContents.get(displayNdx);
display.mDisplayContent.executeAppTransition();
}
}
@@ -1193,7 +1191,7 @@ class RootActivityContainer extends ConfigurationContainer
mTmpFindTaskResult.clear();
// Looking up task on preferred display first
- final ActivityDisplay preferredDisplay = getActivityDisplay(preferredDisplayId);
+ final DisplayContent preferredDisplay = getDisplayContent(preferredDisplayId);
if (preferredDisplay != null) {
preferredDisplay.findTaskLocked(r, true /* isPreferredDisplay */, mTmpFindTaskResult);
if (mTmpFindTaskResult.mIdealMatch) {
@@ -1201,8 +1199,8 @@ class RootActivityContainer extends ConfigurationContainer
}
}
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
+ final DisplayContent display = mDisplayContents.get(displayNdx);
if (display.mDisplayId == preferredDisplayId) {
continue;
}
@@ -1226,8 +1224,8 @@ class RootActivityContainer extends ConfigurationContainer
int finishTopCrashedActivities(WindowProcessController app, String reason) {
Task finishedTask = null;
ActivityStack focusedStack = getTopDisplayFocusedStack();
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
+ final DisplayContent display = mDisplayContents.get(displayNdx);
// It is possible that request to finish activity might also remove its task and stack,
// so we need to be careful with indexes in the loop and check child count every time.
for (int stackNdx = 0; stackNdx < display.getStackCount(); ++stackNdx) {
@@ -1258,12 +1256,12 @@ class RootActivityContainer extends ConfigurationContainer
result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
boolean resumedOnDisplay = false;
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ final DisplayContent display = mDisplayContents.get(displayNdx);
for (int stackNdx = display.getStackCount() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = display.getStackAt(stackNdx);
- final ActivityRecord topRunningActivity = stack.topRunningActivityLocked();
+ final ActivityRecord topRunningActivity = stack.topRunningActivity();
if (!stack.isFocusableAndVisible() || topRunningActivity == null) {
continue;
}
@@ -1290,7 +1288,7 @@ class RootActivityContainer extends ConfigurationContainer
final ActivityStack focusedStack = display.getFocusedStack();
if (focusedStack != null) {
result |= focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);
- } else if (targetStack == null && !display.hasChild()) {
+ } else if (targetStack == null && display.getStackCount() == 0) {
result |= resumeHomeActivity(null /* prev */, "empty-display",
display.mDisplayId);
}
@@ -1301,9 +1299,9 @@ class RootActivityContainer extends ConfigurationContainer
}
void applySleepTokens(boolean applyToStacks) {
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
// Set the sleeping state of the display.
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ final DisplayContent display = mDisplayContents.get(displayNdx);
final boolean displayShouldSleep = display.shouldSleep();
if (displayShouldSleep == display.isSleeping()) {
continue;
@@ -1357,8 +1355,8 @@ class RootActivityContainer extends ConfigurationContainer
}
protected ActivityStack getStack(int stackId) {
- for (int i = mActivityDisplays.size() - 1; i >= 0; --i) {
- final ActivityStack stack = mActivityDisplays.get(i).getStack(stackId);
+ for (int i = mDisplayContents.size() - 1; i >= 0; --i) {
+ final ActivityStack stack = mDisplayContents.get(i).getStack(stackId);
if (stack != null) {
return stack;
}
@@ -1366,11 +1364,11 @@ class RootActivityContainer extends ConfigurationContainer
return null;
}
- /** @see ActivityDisplay#getStack(int, int) */
+ /** @see DisplayContent#getStack(int, int) */
ActivityStack getStack(int windowingMode, int activityType) {
- for (int i = mActivityDisplays.size() - 1; i >= 0; --i) {
+ for (int i = mDisplayContents.size() - 1; i >= 0; --i) {
final ActivityStack stack =
- mActivityDisplays.get(i).getStack(windowingMode, activityType);
+ mDisplayContents.get(i).getStack(windowingMode, activityType);
if (stack != null) {
return stack;
}
@@ -1380,7 +1378,7 @@ class RootActivityContainer extends ConfigurationContainer
private ActivityStack getStack(int windowingMode, int activityType,
int displayId) {
- ActivityDisplay display = getActivityDisplay(displayId);
+ DisplayContent display = getDisplayContent(displayId);
if (display == null) {
return null;
}
@@ -1389,7 +1387,7 @@ class RootActivityContainer extends ConfigurationContainer
private ActivityManager.StackInfo getStackInfo(ActivityStack stack) {
final int displayId = stack.mDisplayId;
- final ActivityDisplay display = getActivityDisplay(displayId);
+ final DisplayContent display = getDisplayContent(displayId);
ActivityManager.StackInfo info = new ActivityManager.StackInfo();
stack.getBounds(info.bounds);
info.displayId = displayId;
@@ -1401,32 +1399,37 @@ class RootActivityContainer extends ConfigurationContainer
info.position = display != null ? display.getIndexOf(stack) : 0;
info.configuration.setTo(stack.getConfiguration());
- ArrayList<Task> tasks = stack.getAllTasks();
- final int numTasks = tasks.size();
- int[] taskIds = new int[numTasks];
- String[] taskNames = new String[numTasks];
- Rect[] taskBounds = new Rect[numTasks];
- int[] taskUserIds = new int[numTasks];
- for (int i = 0; i < numTasks; ++i) {
- final Task task = tasks.get(i);
- taskIds[i] = task.mTaskId;
- taskNames[i] = task.origActivity != null ? task.origActivity.flattenToString()
- : task.realActivity != null ? task.realActivity.flattenToString()
- : task.getTopNonFinishingActivity() != null
- ? task.getTopNonFinishingActivity().packageName : "unknown";
- taskBounds[i] = mService.getTaskBounds(task.mTaskId);
- taskUserIds[i] = task.mUserId;
- }
- info.taskIds = taskIds;
- info.taskNames = taskNames;
- info.taskBounds = taskBounds;
- info.taskUserIds = taskUserIds;
-
- final ActivityRecord top = stack.topRunningActivityLocked();
+ final int numTasks = stack.getChildCount();
+ info.taskIds = new int[numTasks];
+ info.taskNames = new String[numTasks];
+ info.taskBounds = new Rect[numTasks];
+ info.taskUserIds = new int[numTasks];
+ final int[] currenIndex = {0};
+
+ final PooledConsumer c = PooledLambda.obtainConsumer(
+ RootActivityContainer::processTaskForStackInfo, PooledLambda.__(Task.class), info,
+ currenIndex);
+ stack.forAllTasks(c, false);
+ c.recycle();
+
+ final ActivityRecord top = stack.topRunningActivity();
info.topActivity = top != null ? top.intent.getComponent() : null;
return info;
}
+ private static void processTaskForStackInfo(
+ Task task, ActivityManager.StackInfo info, int[] currentIndex) {
+ int i = currentIndex[0];
+ info.taskIds[i] = task.mTaskId;
+ info.taskNames[i] = task.origActivity != null ? task.origActivity.flattenToString()
+ : task.realActivity != null ? task.realActivity.flattenToString()
+ : task.getTopNonFinishingActivity() != null
+ ? task.getTopNonFinishingActivity().packageName : "unknown";
+ info.taskBounds[i] = task.mAtmService.getTaskBounds(task.mTaskId);
+ info.taskUserIds[i] = task.mUserId;
+ currentIndex[0] = ++i;
+ }
+
ActivityManager.StackInfo getStackInfo(int stackId) {
ActivityStack stack = getStack(stackId);
if (stack != null) {
@@ -1449,8 +1452,8 @@ class RootActivityContainer extends ConfigurationContainer
ArrayList<ActivityManager.StackInfo> getAllStackInfos(int displayId) {
ArrayList<ActivityManager.StackInfo> list = new ArrayList<>();
if (displayId == INVALID_DISPLAY) {
- for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ for (int displayNdx = 0; displayNdx < mDisplayContents.size(); ++displayNdx) {
+ final DisplayContent display = mDisplayContents.get(displayNdx);
for (int stackNdx = display.getStackCount() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = display.getStackAt(stackNdx);
list.add(getStackInfo(stack));
@@ -1458,7 +1461,7 @@ class RootActivityContainer extends ConfigurationContainer
}
return list;
}
- final ActivityDisplay display = getActivityDisplay(displayId);
+ final DisplayContent display = getDisplayContent(displayId);
if (display == null) {
return list;
}
@@ -1487,7 +1490,7 @@ class RootActivityContainer extends ConfigurationContainer
public void onDisplayAdded(int displayId) {
if (DEBUG_STACK) Slog.v(TAG, "Display added displayId=" + displayId);
synchronized (mService.mGlobalLock) {
- final ActivityDisplay display = getActivityDisplayOrCreate(displayId);
+ final DisplayContent display = getDisplayContentOrCreate(displayId);
if (display == null) {
return;
}
@@ -1513,12 +1516,12 @@ class RootActivityContainer extends ConfigurationContainer
}
synchronized (mService.mGlobalLock) {
- final ActivityDisplay activityDisplay = getActivityDisplay(displayId);
- if (activityDisplay == null) {
+ final DisplayContent displayContent = getDisplayContent(displayId);
+ if (displayContent == null) {
return;
}
- activityDisplay.remove();
+ displayContent.remove();
}
}
@@ -1526,9 +1529,9 @@ class RootActivityContainer extends ConfigurationContainer
public void onDisplayChanged(int displayId) {
if (DEBUG_STACK) Slog.v(TAG, "Display changed displayId=" + displayId);
synchronized (mService.mGlobalLock) {
- final ActivityDisplay activityDisplay = getActivityDisplay(displayId);
- if (activityDisplay != null) {
- activityDisplay.onDisplayChanged();
+ final DisplayContent displayContent = getDisplayContent(displayId);
+ if (displayContent != null) {
+ displayContent.onDisplayChanged();
}
}
}
@@ -1536,12 +1539,12 @@ class RootActivityContainer extends ConfigurationContainer
/** Update lists of UIDs that are present on displays and have access to them. */
void updateUIDsPresentOnDisplay() {
mDisplayAccessUIDs.clear();
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
- final ActivityDisplay activityDisplay = mActivityDisplays.get(displayNdx);
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
+ final DisplayContent displayContent = mDisplayContents.get(displayNdx);
// Only bother calculating the whitelist for private displays
- if (activityDisplay.isPrivate()) {
+ if (displayContent.isPrivate()) {
mDisplayAccessUIDs.append(
- activityDisplay.mDisplayId, activityDisplay.getPresentUIDs());
+ displayContent.mDisplayId, displayContent.getPresentUIDs());
}
}
// Store updated lists in DisplayManager. Callers from outside of AM should get them there.
@@ -1549,7 +1552,7 @@ class RootActivityContainer extends ConfigurationContainer
}
ActivityStack findStackBehind(ActivityStack stack) {
- final ActivityDisplay display = getActivityDisplay(stack.mDisplayId);
+ final DisplayContent display = getDisplayContent(stack.mDisplayId);
if (display != null) {
for (int i = display.getStackCount() - 1; i >= 0; i--) {
if (display.getStackAt(i) == stack && i > 0) {
@@ -1563,12 +1566,12 @@ class RootActivityContainer extends ConfigurationContainer
@Override
protected int getChildCount() {
- return mActivityDisplays.size();
+ return mDisplayContents.size();
}
@Override
- protected ActivityDisplay getChildAt(int index) {
- return mActivityDisplays.get(index);
+ protected DisplayContent getChildAt(int index) {
+ return mDisplayContents.get(index);
}
@Override
@@ -1586,61 +1589,59 @@ class RootActivityContainer extends ConfigurationContainer
/** Change the z-order of the given display. */
private void positionChildAt(DisplayContent display, int position) {
- if (position >= mActivityDisplays.size()) {
- position = mActivityDisplays.size() - 1;
+ if (position >= mDisplayContents.size()) {
+ position = mDisplayContents.size() - 1;
} else if (position < 0) {
position = 0;
}
- // TODO(display-merge): Remove cast
- final ActivityDisplay activityDisplay = (ActivityDisplay) display;
- if (mActivityDisplays.isEmpty()) {
- mActivityDisplays.add(activityDisplay);
- } else if (mActivityDisplays.get(position) != display) {
- mActivityDisplays.remove(display);
- mActivityDisplays.add(position, activityDisplay);
+ if (mDisplayContents.isEmpty()) {
+ mDisplayContents.add(display);
+ } else if (mDisplayContents.get(position) != display) {
+ mDisplayContents.remove(display);
+ mDisplayContents.add(position, display);
}
mStackSupervisor.updateTopResumedActivityIfNeeded();
}
@VisibleForTesting
- void addChild(ActivityDisplay activityDisplay, int position) {
- positionChildAt(activityDisplay, position);
- mRootWindowContainer.positionChildAt(position, activityDisplay.mDisplayContent);
+ void addChild(DisplayContent displayContent, int position) {
+ positionChildAt(displayContent, position);
+ mRootWindowContainer.positionChildAt(position, displayContent);
}
- void removeChild(ActivityDisplay activityDisplay) {
- // The caller must tell the controller of {@link ActivityDisplay} to release its container
- // {@link DisplayContent}. That is done in {@link ActivityDisplay#releaseSelfIfNeeded}).
- mActivityDisplays.remove(activityDisplay);
+ void removeChild(DisplayContent displayContent) {
+ // The caller must tell the controller of {@link DisplayContent} to release its container
+ // {@link DisplayContent}. That is done in {@link DisplayContent#releaseSelfIfNeeded}).
+ mDisplayContents.remove(displayContent);
}
Configuration getDisplayOverrideConfiguration(int displayId) {
- final ActivityDisplay activityDisplay = getActivityDisplayOrCreate(displayId);
- if (activityDisplay == null) {
+ final DisplayContent displayContent = getDisplayContentOrCreate(displayId);
+ if (displayContent == null) {
throw new IllegalArgumentException("No display found with id: " + displayId);
}
- return activityDisplay.getRequestedOverrideConfiguration();
+ return displayContent.getRequestedOverrideConfiguration();
}
void setDisplayOverrideConfiguration(Configuration overrideConfiguration, int displayId) {
- final ActivityDisplay activityDisplay = getActivityDisplayOrCreate(displayId);
- if (activityDisplay == null) {
+ final DisplayContent displayContent = getDisplayContentOrCreate(displayId);
+ if (displayContent == null) {
throw new IllegalArgumentException("No display found with id: " + displayId);
}
- activityDisplay.onRequestedOverrideConfigurationChanged(overrideConfiguration);
+ displayContent.onRequestedOverrideConfigurationChanged(overrideConfiguration);
}
void prepareForShutdown() {
- for (int i = 0; i < mActivityDisplays.size(); i++) {
- createSleepToken("shutdown", mActivityDisplays.get(i).mDisplayId);
+ for (int i = 0; i < mDisplayContents.size(); i++) {
+ createSleepToken("shutdown", mDisplayContents.get(i).mDisplayId);
}
}
ActivityTaskManagerInternal.SleepToken createSleepToken(String tag, int displayId) {
- final ActivityDisplay display = getActivityDisplay(displayId);
+ final DisplayContent display = getDisplayContent(displayId);
if (display == null) {
throw new IllegalArgumentException("Invalid display: " + displayId);
}
@@ -1654,7 +1655,7 @@ class RootActivityContainer extends ConfigurationContainer
private void removeSleepToken(SleepTokenImpl token) {
mSleepTokens.remove(token);
- final ActivityDisplay display = getActivityDisplay(token.mDisplayId);
+ final DisplayContent display = getDisplayContent(token.mDisplayId);
if (display != null) {
display.mAllSleepTokens.remove(token);
if (display.mAllSleepTokens.isEmpty()) {
@@ -1711,8 +1712,8 @@ class RootActivityContainer extends ConfigurationContainer
}
void scheduleDestroyAllActivities(WindowProcessController app, String reason) {
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
+ final DisplayContent display = mDisplayContents.get(displayNdx);
for (int stackNdx = display.getStackCount() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = display.getStackAt(stackNdx);
stack.scheduleDestroyActivities(app, reason);
@@ -1724,8 +1725,8 @@ class RootActivityContainer extends ConfigurationContainer
// successfully put to sleep.
boolean putStacksToSleep(boolean allowDelay, boolean shuttingDown) {
boolean allSleep = true;
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
+ final DisplayContent display = mDisplayContents.get(displayNdx);
for (int stackNdx = display.getStackCount() - 1; stackNdx >= 0; --stackNdx) {
// Stacks and activities could be removed while putting activities to sleep if
// the app process was gone. This prevents us getting exception by accessing an
@@ -1795,8 +1796,8 @@ class RootActivityContainer extends ConfigurationContainer
}
boolean hasAwakeDisplay() {
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
+ final DisplayContent display = mDisplayContents.get(displayNdx);
if (!display.shouldSleep()) {
return true;
}
@@ -1872,7 +1873,7 @@ class RootActivityContainer extends ConfigurationContainer
return stack;
}
}
- final ActivityDisplay display = getActivityDisplayOrCreate(displayId);
+ final DisplayContent display = getDisplayContentOrCreate(displayId);
if (display != null) {
stack = display.getOrCreateStack(r, options, candidateTask, activityType, onTop);
if (stack != null) {
@@ -1884,7 +1885,7 @@ class RootActivityContainer extends ConfigurationContainer
// Give preference to the stack and display of the input task and activity if they match the
// mode we want to launch into.
stack = null;
- ActivityDisplay display = null;
+ DisplayContent display = null;
if (candidateTask != null) {
stack = candidateTask.getStack();
}
@@ -1905,7 +1906,7 @@ class RootActivityContainer extends ConfigurationContainer
}
if (windowingMode == WINDOWING_MODE_FULLSCREEN_OR_SPLIT_SCREEN_SECONDARY
&& display.getSplitScreenPrimaryStack() == stack
- && candidateTask == stack.topTask()) {
+ && candidateTask == stack.getTopMostTask()) {
// This is a special case when we try to launch an activity that is currently on
// top of split-screen primary stack, but is targeting split-screen secondary.
// In this case we don't want to move it to another stack.
@@ -1942,8 +1943,8 @@ class RootActivityContainer extends ConfigurationContainer
private ActivityStack getValidLaunchStackOnDisplay(int displayId, @NonNull ActivityRecord r,
@Nullable Task candidateTask, @Nullable ActivityOptions options,
@Nullable LaunchParamsController.LaunchParams launchParams) {
- final ActivityDisplay activityDisplay = getActivityDisplayOrCreate(displayId);
- if (activityDisplay == null) {
+ final DisplayContent displayContent = getDisplayContentOrCreate(displayId);
+ if (displayContent == null) {
throw new IllegalArgumentException(
"Display with displayId=" + displayId + " not found.");
}
@@ -1972,12 +1973,12 @@ class RootActivityContainer extends ConfigurationContainer
windowingMode = options != null ? options.getLaunchWindowingMode()
: r.getWindowingMode();
}
- windowingMode = activityDisplay.validateWindowingMode(windowingMode, r, candidateTask,
+ windowingMode = displayContent.validateWindowingMode(windowingMode, r, candidateTask,
r.getActivityType());
// Return the topmost valid stack on the display.
- for (int i = activityDisplay.getStackCount() - 1; i >= 0; --i) {
- final ActivityStack stack = activityDisplay.getStackAt(i);
+ for (int i = displayContent.getStackCount() - 1; i >= 0; --i) {
+ final ActivityStack stack = displayContent.getStackAt(i);
if (isValidLaunchStack(stack, r, windowingMode)) {
return stack;
}
@@ -1988,7 +1989,7 @@ class RootActivityContainer extends ConfigurationContainer
final int activityType =
options != null && options.getLaunchActivityType() != ACTIVITY_TYPE_UNDEFINED
? options.getLaunchActivityType() : r.getActivityType();
- return activityDisplay.createStack(windowingMode, activityType, true /*onTop*/);
+ return displayContent.createStack(windowingMode, activityType, true /*onTop*/);
}
return null;
@@ -2050,11 +2051,11 @@ class RootActivityContainer extends ConfigurationContainer
ActivityStack getNextFocusableStack(@NonNull ActivityStack currentFocus,
boolean ignoreCurrent) {
// First look for next focusable stack on the same display
- ActivityDisplay preferredDisplay = currentFocus.getDisplay();
+ DisplayContent preferredDisplay = currentFocus.getDisplay();
if (preferredDisplay == null) {
// Stack is currently detached because it is being removed. Use the previous display it
// was on.
- preferredDisplay = getActivityDisplay(currentFocus.mPrevDisplayId);
+ preferredDisplay = getDisplayContent(currentFocus.mPrevDisplayId);
}
final ActivityStack preferredFocusableStack = preferredDisplay.getNextFocusableStack(
currentFocus, ignoreCurrent);
@@ -2069,8 +2070,8 @@ class RootActivityContainer extends ConfigurationContainer
}
// Now look through all displays
- for (int i = mActivityDisplays.size() - 1; i >= 0; --i) {
- final ActivityDisplay display = mActivityDisplays.get(i);
+ for (int i = mDisplayContents.size() - 1; i >= 0; --i) {
+ final DisplayContent display = mDisplayContents.get(i);
if (display == preferredDisplay) {
// We've already checked this one
continue;
@@ -2096,8 +2097,8 @@ class RootActivityContainer extends ConfigurationContainer
* @return Next valid {@link ActivityStack}, null if not found.
*/
ActivityStack getNextValidLaunchStack(@NonNull ActivityRecord r, int currentFocus) {
- for (int i = mActivityDisplays.size() - 1; i >= 0; --i) {
- final ActivityDisplay display = mActivityDisplays.get(i);
+ for (int i = mDisplayContents.size() - 1; i >= 0; --i) {
+ final DisplayContent display = mDisplayContents.get(i);
if (display.mDisplayId == currentFocus) {
continue;
}
@@ -2112,8 +2113,8 @@ class RootActivityContainer extends ConfigurationContainer
boolean handleAppDied(WindowProcessController app) {
boolean hasVisibleActivities = false;
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
+ final DisplayContent display = mDisplayContents.get(displayNdx);
for (int stackNdx = display.getStackCount() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = display.getStackAt(stackNdx);
hasVisibleActivities |= stack.handleAppDiedLocked(app);
@@ -2225,8 +2226,8 @@ class RootActivityContainer extends ConfigurationContainer
}
void finishVoiceTask(IVoiceInteractionSession session) {
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
+ final DisplayContent display = mDisplayContents.get(displayNdx);
final int numStacks = display.getStackCount();
for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
final ActivityStack stack = display.getStackAt(stackNdx);
@@ -2240,20 +2241,20 @@ class RootActivityContainer extends ConfigurationContainer
* ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
*/
void removeStacksInWindowingModes(int... windowingModes) {
- for (int i = mActivityDisplays.size() - 1; i >= 0; --i) {
- mActivityDisplays.get(i).removeStacksInWindowingModes(windowingModes);
+ for (int i = mDisplayContents.size() - 1; i >= 0; --i) {
+ mDisplayContents.get(i).removeStacksInWindowingModes(windowingModes);
}
}
void removeStacksWithActivityTypes(int... activityTypes) {
- for (int i = mActivityDisplays.size() - 1; i >= 0; --i) {
- mActivityDisplays.get(i).removeStacksWithActivityTypes(activityTypes);
+ for (int i = mDisplayContents.size() - 1; i >= 0; --i) {
+ mDisplayContents.get(i).removeStacksWithActivityTypes(activityTypes);
}
}
ActivityRecord topRunningActivity() {
- for (int i = mActivityDisplays.size() - 1; i >= 0; --i) {
- final ActivityRecord topActivity = mActivityDisplays.get(i).topRunningActivity();
+ for (int i = mDisplayContents.size() - 1; i >= 0; --i) {
+ final ActivityRecord topActivity = mDisplayContents.get(i).topRunningActivity();
if (topActivity != null) {
return topActivity;
}
@@ -2262,9 +2263,9 @@ class RootActivityContainer extends ConfigurationContainer
}
boolean allResumedActivitiesIdle() {
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
// TODO(b/117135575): Check resumed activities on all visible stacks.
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ final DisplayContent display = mDisplayContents.get(displayNdx);
if (display.isSleeping()) {
// No resumed activities while display is sleeping.
continue;
@@ -2292,8 +2293,8 @@ class RootActivityContainer extends ConfigurationContainer
boolean allResumedActivitiesVisible() {
boolean foundResumed = false;
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
+ final DisplayContent display = mDisplayContents.get(displayNdx);
for (int stackNdx = display.getStackCount() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = display.getStackAt(stackNdx);
final ActivityRecord r = stack.getResumedActivity();
@@ -2310,8 +2311,8 @@ class RootActivityContainer extends ConfigurationContainer
boolean allPausedActivitiesComplete() {
boolean pausing = true;
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
+ final DisplayContent display = mDisplayContents.get(displayNdx);
for (int stackNdx = display.getStackCount() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = display.getStackAt(stackNdx);
final ActivityRecord r = stack.mPausingActivity;
@@ -2338,24 +2339,11 @@ class RootActivityContainer extends ConfigurationContainer
void lockAllProfileTasks(@UserIdInt int userId) {
mService.deferWindowLayout();
try {
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
- for (int stackNdx = display.getStackCount() - 1; stackNdx >= 0; --stackNdx) {
- final ActivityStack stack = display.getStackAt(stackNdx);
- final List<Task> tasks = stack.getAllTasks();
- for (int taskNdx = tasks.size() - 1; taskNdx >= 0; taskNdx--) {
- final Task task = tasks.get(taskNdx);
-
- // Check the task for a top activity belonging to userId, or returning a
- // result to an activity belonging to userId. Example case: a document
- // picker for personal files, opened by a work app, should still get locked.
- if (taskTopActivityIsUser(task, userId)) {
- mService.getTaskChangeNotificationController().notifyTaskProfileLocked(
- task.mTaskId, userId);
- }
- }
- }
- }
+ final PooledConsumer c = PooledLambda.obtainConsumer(
+ RootActivityContainer::taskTopActivityIsUser, this, PooledLambda.__(Task.class),
+ userId);
+ mRootWindowContainer.forAllTasks(c);
+ c.recycle();
} finally {
mService.continueWindowLayout();
}
@@ -2372,18 +2360,24 @@ class RootActivityContainer extends ConfigurationContainer
*
* @return {@code true} if the top activity looks like it belongs to {@param userId}.
*/
- private boolean taskTopActivityIsUser(Task task, @UserIdInt int userId) {
+ private void taskTopActivityIsUser(Task task, @UserIdInt int userId) {
// To handle the case that work app is in the task but just is not the top one.
final ActivityRecord activityRecord = task.getTopNonFinishingActivity();
final ActivityRecord resultTo = (activityRecord != null ? activityRecord.resultTo : null);
- return (activityRecord != null && activityRecord.mUserId == userId)
- || (resultTo != null && resultTo.mUserId == userId);
+ // Check the task for a top activity belonging to userId, or returning a
+ // result to an activity belonging to userId. Example case: a document
+ // picker for personal files, opened by a work app, should still get locked.
+ if ((activityRecord != null && activityRecord.mUserId == userId)
+ || (resultTo != null && resultTo.mUserId == userId)) {
+ mService.getTaskChangeNotificationController().notifyTaskProfileLocked(
+ task.mTaskId, userId);
+ }
}
void cancelInitializingActivities() {
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
+ final DisplayContent display = mDisplayContents.get(displayNdx);
for (int stackNdx = display.getStackCount() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = display.getStackAt(stackNdx);
stack.cancelInitializingActivities();
@@ -2414,29 +2408,25 @@ class RootActivityContainer extends ConfigurationContainer
+ " lookup");
}
- int numDisplays = mActivityDisplays.size();
- for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
- for (int stackNdx = display.getStackCount() - 1; stackNdx >= 0; --stackNdx) {
- final ActivityStack stack = display.getStackAt(stackNdx);
- final Task task = stack.taskForIdLocked(id);
- if (task == null) {
- continue;
- }
- if (aOptions != null) {
- // Resolve the stack the task should be placed in now based on options
- // and reparent if needed.
- final ActivityStack launchStack =
- getLaunchStack(null, aOptions, task, onTop);
- if (launchStack != null && stack != launchStack) {
- final int reparentMode = onTop
- ? REPARENT_MOVE_STACK_TO_FRONT : REPARENT_LEAVE_STACK_IN_PLACE;
- task.reparent(launchStack, onTop, reparentMode, ANIMATE, DEFER_RESUME,
- "anyTaskForId");
- }
+ final PooledPredicate p = PooledLambda.obtainPredicate(
+ Task::isTaskId, PooledLambda.__(Task.class), id);
+ Task task = mRootWindowContainer.getTask(p);
+ p.recycle();
+
+ if (task != null) {
+ if (aOptions != null) {
+ // Resolve the stack the task should be placed in now based on options
+ // and reparent if needed.
+ final ActivityStack launchStack =
+ getLaunchStack(null, aOptions, task, onTop);
+ if (launchStack != null && task.getStack() != launchStack) {
+ final int reparentMode = onTop
+ ? REPARENT_MOVE_STACK_TO_FRONT : REPARENT_LEAVE_STACK_IN_PLACE;
+ task.reparent(launchStack, onTop, reparentMode, ANIMATE, DEFER_RESUME,
+ "anyTaskForId");
}
- return task;
}
+ return task;
}
// If we are matching stack tasks only, return now
@@ -2447,7 +2437,7 @@ class RootActivityContainer extends ConfigurationContainer
// Otherwise, check the recent tasks and return if we find it there and we are not restoring
// the task from recents
if (DEBUG_RECENTS) Slog.v(TAG_RECENTS, "Looking for task id=" + id + " in recents");
- final Task task = mStackSupervisor.mRecentTasks.getTask(id);
+ task = mStackSupervisor.mRecentTasks.getTask(id);
if (task == null) {
if (DEBUG_RECENTS) {
@@ -2472,9 +2462,9 @@ class RootActivityContainer extends ConfigurationContainer
}
ActivityRecord isInAnyStack(IBinder token) {
- int numDisplays = mActivityDisplays.size();
+ int numDisplays = mDisplayContents.size();
for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ final DisplayContent display = mDisplayContents.get(displayNdx);
for (int stackNdx = display.getStackCount() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = display.getStackAt(stackNdx);
final ActivityRecord r = stack.isInStackLocked(token);
@@ -2492,7 +2482,7 @@ class RootActivityContainer extends ConfigurationContainer
@WindowConfiguration.WindowingMode int ignoreWindowingMode, int callingUid,
boolean allowed, boolean crossUser, ArraySet<Integer> profileIds) {
mStackSupervisor.getRunningTasks().getTasks(maxNum, list, ignoreActivityType,
- ignoreWindowingMode, mActivityDisplays, callingUid, allowed, crossUser, profileIds);
+ ignoreWindowingMode, this, callingUid, allowed, crossUser, profileIds);
}
void sendPowerHintForLaunchStartIfNeeded(boolean forceSend, ActivityRecord targetActivity) {
@@ -2508,9 +2498,9 @@ class RootActivityContainer extends ConfigurationContainer
// activity on all displays, or if there are no resumed activities in the system.
boolean noResumedActivities = true;
boolean allFocusedProcessesDiffer = true;
- for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
- final ActivityDisplay activityDisplay = mActivityDisplays.get(displayNdx);
- final ActivityRecord resumedActivity = activityDisplay.getResumedActivity();
+ for (int displayNdx = 0; displayNdx < mDisplayContents.size(); ++displayNdx) {
+ final DisplayContent displayContent = mDisplayContents.get(displayNdx);
+ final ActivityRecord resumedActivity = displayContent.getResumedActivity();
final WindowProcessController resumedActivityProcess =
resumedActivity == null ? null : resumedActivity.app;
@@ -2555,9 +2545,9 @@ class RootActivityContainer extends ConfigurationContainer
return getTopDisplayFocusedStack().getDumpActivitiesLocked(name);
} else {
ArrayList<ActivityRecord> activities = new ArrayList<>();
- int numDisplays = mActivityDisplays.size();
+ int numDisplays = mDisplayContents.size();
for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ final DisplayContent display = mDisplayContents.get(displayNdx);
for (int stackNdx = display.getStackCount() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = display.getStackAt(stackNdx);
if (!dumpVisibleStacksOnly || stack.shouldBeVisible(null)) {
@@ -2572,9 +2562,9 @@ class RootActivityContainer extends ConfigurationContainer
public void dump(PrintWriter pw, String prefix) {
pw.print(prefix);
pw.println("topDisplayFocusedStack=" + getTopDisplayFocusedStack());
- for (int i = mActivityDisplays.size() - 1; i >= 0; --i) {
- final ActivityDisplay display = mActivityDisplays.get(i);
- display.dump(pw, prefix);
+ for (int i = mDisplayContents.size() - 1; i >= 0; --i) {
+ final DisplayContent display = mDisplayContents.get(i);
+ display.dump(pw, prefix, true /* dumpAll */);
}
}
@@ -2584,17 +2574,17 @@ class RootActivityContainer extends ConfigurationContainer
*/
void dumpDisplayConfigs(PrintWriter pw, String prefix) {
pw.print(prefix); pw.println("Display override configurations:");
- final int displayCount = mActivityDisplays.size();
+ final int displayCount = mDisplayContents.size();
for (int i = 0; i < displayCount; i++) {
- final ActivityDisplay activityDisplay = mActivityDisplays.get(i);
- pw.print(prefix); pw.print(" "); pw.print(activityDisplay.mDisplayId); pw.print(": ");
- pw.println(activityDisplay.getRequestedOverrideConfiguration());
+ final DisplayContent displayContent = mDisplayContents.get(i);
+ pw.print(prefix); pw.print(" "); pw.print(displayContent.mDisplayId); pw.print(": ");
+ pw.println(displayContent.getRequestedOverrideConfiguration());
}
}
public void dumpDisplays(PrintWriter pw) {
- for (int i = mActivityDisplays.size() - 1; i >= 0; --i) {
- final ActivityDisplay display = mActivityDisplays.get(i);
+ for (int i = mDisplayContents.size() - 1; i >= 0; --i) {
+ final DisplayContent display = mDisplayContents.get(i);
pw.print("[id:" + display.mDisplayId + " stacks:");
display.dumpStacks(pw);
pw.print("]");
@@ -2605,18 +2595,18 @@ class RootActivityContainer extends ConfigurationContainer
String dumpPackage) {
boolean printed = false;
boolean needSep = false;
- for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
- ActivityDisplay activityDisplay = mActivityDisplays.get(displayNdx);
- pw.print("Display #"); pw.print(activityDisplay.mDisplayId);
+ for (int displayNdx = mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
+ DisplayContent displayContent = mDisplayContents.get(displayNdx);
+ pw.print("Display #"); pw.print(displayContent.mDisplayId);
pw.println(" (activities from top to bottom):");
- final ActivityDisplay display = mActivityDisplays.get(displayNdx);
+ final DisplayContent display = mDisplayContents.get(displayNdx);
for (int stackNdx = display.getStackCount() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = display.getStackAt(stackNdx);
pw.println();
printed = stack.dump(fd, pw, dumpAll, dumpClient, dumpPackage, needSep);
needSep = printed;
}
- printThisActivity(pw, activityDisplay.getResumedActivity(), dumpPackage, needSep,
+ printThisActivity(pw, displayContent.getResumedActivity(), dumpPackage, needSep,
" ResumedActivity:");
}
@@ -2637,9 +2627,9 @@ class RootActivityContainer extends ConfigurationContainer
@WindowTraceLogLevel int logLevel) {
final long token = proto.start(fieldId);
super.dumpDebug(proto, CONFIGURATION_CONTAINER, logLevel);
- for (int displayNdx = 0; displayNdx < mActivityDisplays.size(); ++displayNdx) {
- final ActivityDisplay activityDisplay = mActivityDisplays.get(displayNdx);
- activityDisplay.dumpDebug(proto, DISPLAYS, logLevel);
+ for (int displayNdx = 0; displayNdx < mDisplayContents.size(); ++displayNdx) {
+ final DisplayContent displayContent = mDisplayContents.get(displayNdx);
+ displayContent.dumpDebug(proto, DISPLAYS, logLevel);
}
mStackSupervisor.getKeyguardController().dumpDebug(proto, KEYGUARD_CONTROLLER);
// TODO(b/111541062): Update tests to look for resumed activities on all displays
diff --git a/services/core/java/com/android/server/wm/RunningTasks.java b/services/core/java/com/android/server/wm/RunningTasks.java
index ca9d91e9bcab..5783713b17b1 100644
--- a/services/core/java/com/android/server/wm/RunningTasks.java
+++ b/services/core/java/com/android/server/wm/RunningTasks.java
@@ -16,11 +16,18 @@
package com.android.server.wm;
+import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
+import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
+
import android.app.ActivityManager.RunningTaskInfo;
import android.app.WindowConfiguration.ActivityType;
import android.app.WindowConfiguration.WindowingMode;
+import android.os.UserHandle;
import android.util.ArraySet;
+import com.android.internal.util.function.pooled.PooledConsumer;
+import com.android.internal.util.function.pooled.PooledLambda;
+
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
@@ -39,8 +46,17 @@ class RunningTasks {
private final TreeSet<Task> mTmpSortedSet = new TreeSet<>(LAST_ACTIVE_TIME_COMPARATOR);
private final ArrayList<Task> mTmpStackTasks = new ArrayList<>();
+ private int mCallingUid;
+ private int mUserId;
+ private boolean mCrossUser;
+ private ArraySet<Integer> mProfileIds;
+ private boolean mAllowed;
+ private int mIgnoreActivityType;
+ private int mIgnoreWindowingMode;
+ private ActivityStack mTopDisplayFocusStack;
+
void getTasks(int maxNum, List<RunningTaskInfo> list, @ActivityType int ignoreActivityType,
- @WindowingMode int ignoreWindowingMode, ArrayList<ActivityDisplay> activityDisplays,
+ @WindowingMode int ignoreWindowingMode, RootActivityContainer root,
int callingUid, boolean allowed, boolean crossUser, ArraySet<Integer> profileIds) {
// Return early if there are no tasks to fetch
if (maxNum <= 0) {
@@ -49,17 +65,19 @@ class RunningTasks {
// Gather all of the tasks across all of the tasks, and add them to the sorted set
mTmpSortedSet.clear();
- final int numDisplays = activityDisplays.size();
- for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
- final ActivityDisplay display = activityDisplays.get(displayNdx);
- for (int stackNdx = display.getStackCount() - 1; stackNdx >= 0; --stackNdx) {
- final ActivityStack stack = display.getStackAt(stackNdx);
- mTmpStackTasks.clear();
- stack.getRunningTasks(mTmpStackTasks, ignoreActivityType, ignoreWindowingMode,
- callingUid, allowed, crossUser, profileIds);
- mTmpSortedSet.addAll(mTmpStackTasks);
- }
- }
+ mCallingUid = callingUid;
+ mUserId = UserHandle.getUserId(callingUid);
+ mCrossUser = crossUser;
+ mProfileIds = profileIds;
+ mAllowed = allowed;
+ mIgnoreActivityType = ignoreActivityType;
+ mIgnoreWindowingMode = ignoreWindowingMode;
+ mTopDisplayFocusStack = root.getTopDisplayFocusedStack();
+
+ final PooledConsumer c = PooledLambda.obtainConsumer(RunningTasks::processTask, this,
+ PooledLambda.__(Task.class));
+ root.mRootWindowContainer.forAllTasks(c, false);
+ c.recycle();
// Take the first {@param maxNum} tasks and create running task infos for them
final Iterator<Task> iter = mTmpSortedSet.iterator();
@@ -74,9 +92,45 @@ class RunningTasks {
}
}
- /**
- * Constructs a {@link RunningTaskInfo} from a given {@param task}.
- */
+ private void processTask(Task task) {
+ if (task.getTopNonFinishingActivity() == null) {
+ // Skip if there are no activities in the task
+ return;
+ }
+ if (task.effectiveUid != mCallingUid) {
+ if (task.mUserId != mUserId && !mCrossUser && !mProfileIds.contains(task.mUserId)) {
+ // Skip if the caller does not have cross user permission or cannot access
+ // the task's profile
+ return;
+ }
+ if (!mAllowed && !task.isActivityTypeHome()) {
+ // Skip if the caller isn't allowed to fetch this task, except for the home
+ // task which we always return.
+ return;
+ }
+ }
+ if (mIgnoreActivityType != ACTIVITY_TYPE_UNDEFINED
+ && task.getActivityType() == mIgnoreActivityType) {
+ // Skip ignored activity type
+ return;
+ }
+ if (mIgnoreWindowingMode != WINDOWING_MODE_UNDEFINED
+ && task.getWindowingMode() == mIgnoreWindowingMode) {
+ // Skip ignored windowing mode
+ return;
+ }
+
+ final ActivityStack stack = task.getStack();
+ if (stack == mTopDisplayFocusStack && stack.getTopMostTask() == task) {
+ // For the focused stack top task, update the last stack active time so that it can be
+ // used to determine the order of the tasks (it may not be set for newly created tasks)
+ task.touchActiveTime();
+ }
+
+ mTmpSortedSet.add(task);
+ }
+
+ /** Constructs a {@link RunningTaskInfo} from a given {@param task}. */
private RunningTaskInfo createRunningTaskInfo(Task task) {
final RunningTaskInfo rti = new RunningTaskInfo();
task.fillTaskInfo(rti);
diff --git a/services/core/java/com/android/server/wm/ScreenRotationAnimation.java b/services/core/java/com/android/server/wm/ScreenRotationAnimation.java
index 1a7d21406e55..399c5d3ae45f 100644
--- a/services/core/java/com/android/server/wm/ScreenRotationAnimation.java
+++ b/services/core/java/com/android/server/wm/ScreenRotationAnimation.java
@@ -172,7 +172,7 @@ class ScreenRotationAnimation {
.setContainerLayer()
.build();
- mSurfaceControl = displayContent.makeSurface(null)
+ mSurfaceControl = mService.makeSurfaceBuilder(null)
.setName("ScreenshotSurface")
.setParent(mRotationLayer)
.setBufferSize(mWidth, mHeight)
diff --git a/services/core/java/com/android/server/wm/ShellRoot.java b/services/core/java/com/android/server/wm/ShellRoot.java
new file mode 100644
index 000000000000..9732637fdd4d
--- /dev/null
+++ b/services/core/java/com/android/server/wm/ShellRoot.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.wm;
+
+import android.annotation.NonNull;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.util.Slog;
+import android.view.IWindow;
+import android.view.SurfaceControl;
+
+/**
+ * Represents a piece of the hierarchy under which a client Shell can manage sub-windows.
+ */
+public class ShellRoot {
+ private static final String TAG = "ShellRoot";
+ private final DisplayContent mDisplayContent;
+ private IWindow mClient;
+ private WindowToken mToken;
+ private final IBinder.DeathRecipient mDeathRecipient;
+ private SurfaceControl mSurfaceControl = null;
+
+ ShellRoot(@NonNull IWindow client, @NonNull DisplayContent dc, final int windowType) {
+ mDisplayContent = dc;
+ mDeathRecipient = () -> mDisplayContent.removeShellRoot(windowType);
+ try {
+ client.asBinder().linkToDeath(mDeathRecipient, 0);
+ } catch (RemoteException e) {
+ Slog.e(TAG, "Unable to add shell root for layer " + windowType + " on display "
+ + dc.getDisplayId(), e);
+ return;
+ }
+ mClient = client;
+ mToken = new WindowToken(
+ dc.mWmService, client.asBinder(), windowType, true, dc, true, false);
+ mSurfaceControl = mToken.makeChildSurface(null)
+ .setContainerLayer().setName("Shell Root Leash " + dc.getDisplayId()).build();
+ mToken.getPendingTransaction().show(mSurfaceControl);
+ }
+
+ void clear() {
+ if (mClient != null) {
+ mClient.asBinder().unlinkToDeath(mDeathRecipient, 0);
+ mClient = null;
+ }
+ if (mToken != null) {
+ mToken.removeImmediately();
+ mToken = null;
+ }
+ }
+
+ SurfaceControl getSurfaceControl() {
+ return mSurfaceControl;
+ }
+
+ IWindow getClient() {
+ return mClient;
+ }
+}
+
diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java
index b1d06923fd2f..fd95ac500370 100644
--- a/services/core/java/com/android/server/wm/Task.java
+++ b/services/core/java/com/android/server/wm/Task.java
@@ -135,7 +135,6 @@ import android.view.SurfaceControl;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.app.IVoiceInteractor;
-import com.android.internal.util.ToBooleanFunction;
import com.android.internal.util.XmlUtils;
import com.android.internal.util.function.pooled.PooledConsumer;
import com.android.internal.util.function.pooled.PooledFunction;
@@ -155,6 +154,7 @@ import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Objects;
import java.util.function.Consumer;
+import java.util.function.Function;
import java.util.function.Predicate;
class Task extends WindowContainer<WindowContainer> {
@@ -684,7 +684,7 @@ class Task extends WindowContainer<WindowContainer> {
final boolean toTopOfStack = position == MAX_VALUE;
if (toTopOfStack && toStack.getResumedActivity() != null
- && toStack.topRunningActivityLocked() != null) {
+ && toStack.topRunningActivity() != null) {
// Pause the resumed activity on the target stack while re-parenting task on top of it.
toStack.startPausingLocked(false /* userLeaving */, false /* uiSleeping */,
null /* resuming */);
@@ -720,7 +720,7 @@ class Task extends WindowContainer<WindowContainer> {
// Whenever we are moving the top activity from the front stack we want to make sure to
// move the stack to the front.
final boolean wasFront = r != null && sourceStack.isTopStackOnDisplay()
- && (sourceStack.topRunningActivityLocked() == r);
+ && (sourceStack.topRunningActivity() == r);
final boolean moveStackToFront = moveStackMode == REPARENT_MOVE_STACK_TO_FRONT
|| (moveStackMode == REPARENT_KEEP_STACK_AT_FRONT && (wasFocused || wasFront));
@@ -1256,7 +1256,7 @@ class Task extends WindowContainer<WindowContainer> {
// work.
// TODO: If the callers to removeChild() changes such that we have multiple places
// where we are destroying the task, move this back into removeChild()
- mAtmService.mStackSupervisor.removeTaskByIdLocked(mTaskId, false /* killProcess */,
+ mAtmService.mStackSupervisor.removeTask(this, false /* killProcess */,
!REMOVE_FROM_RECENTS, reason);
}
} else if (!mReuseTask) {
@@ -1582,8 +1582,8 @@ class Task extends WindowContainer<WindowContainer> {
if (!inPinnedWindowingMode() && mStack != null) {
final int defaultMinSizeDp =
mAtmService.mRootActivityContainer.mDefaultMinSizeOfResizeableTaskDp;
- final ActivityDisplay display =
- mAtmService.mRootActivityContainer.getActivityDisplay(mStack.mDisplayId);
+ final DisplayContent display =
+ mAtmService.mRootActivityContainer.getDisplayContent(mStack.mDisplayId);
final float density =
(float) display.getConfiguration().densityDpi / DisplayMetrics.DENSITY_DEFAULT;
final int defaultMinSize = (int) (defaultMinSizeDp * density);
@@ -1994,7 +1994,7 @@ class Task extends WindowContainer<WindowContainer> {
((float) newParentConfig.densityDpi) / DisplayMetrics.DENSITY_DEFAULT;
final Rect parentBounds =
new Rect(newParentConfig.windowConfiguration.getBounds());
- final ActivityDisplay display = mStack.getDisplay();
+ final DisplayContent display = mStack.getDisplay();
if (display != null && display.mDisplayContent != null) {
// If a freeform window moves below system bar, there is no way to move it again
// by touch. Because its caption is covered by system bar. So we exclude them
@@ -2182,22 +2182,12 @@ class Task extends WindowContainer<WindowContainer> {
void reparent(ActivityStack stack, int position, boolean moveParents, String reason) {
if (DEBUG_STACK) Slog.i(TAG, "reParentTask: removing taskId=" + mTaskId
+ " from stack=" + getTaskStack());
- EventLogTags.writeWmTaskRemoved(mTaskId, "reParentTask");
-
- final ActivityStack prevStack = getTaskStack();
- final boolean wasTopFocusedStack =
- mAtmService.mRootActivityContainer.isTopDisplayFocusedStack(prevStack);
- final ActivityDisplay prevStackDisplay = prevStack.getDisplay();
+ EventLogTags.writeWmTaskRemoved(mTaskId, "reParentTask:" + reason);
position = stack.findPositionForTask(this, position, showForAllUsers());
reparent(stack, position);
- if (!moveParents) {
- // Only move home stack forward if we are not going to move the new parent forward.
- prevStack.moveHomeStackToFrontIfNeeded(wasTopFocusedStack, prevStackDisplay, reason);
- }
-
stack.positionChildAt(position, this, moveParents);
// If we are moving from the fullscreen stack to the pinned stack then we want to preserve
@@ -2659,12 +2649,13 @@ class Task extends WindowContainer<WindowContainer> {
}
@Override
- void forAllTasks(Consumer<Task> callback) {
+ void forAllTasks(Consumer<Task> callback, boolean traverseTopToBottom) {
+ // TODO(task-hierarchy): Change to traverse children when tasks can contain other tasks.
callback.accept(this);
}
@Override
- boolean forAllTasks(ToBooleanFunction<Task> callback) {
+ boolean forAllTasks(Function<Task, Boolean> callback) {
return callback.apply(this);
}
@@ -2707,6 +2698,10 @@ class Task extends WindowContainer<WindowContainer> {
return mDimmer;
}
+ boolean isTaskForUser(int userId) {
+ return mUserId == userId;
+ }
+
@Override
void prepareSurfaces() {
mDimmer.resetDimStates();
@@ -2800,6 +2795,10 @@ class Task extends WindowContainer<WindowContainer> {
return info;
}
+ boolean isTaskId(int taskId) {
+ return mTaskId == taskId;
+ }
+
void dump(PrintWriter pw, String prefix) {
pw.print(prefix); pw.print("userId="); pw.print(mUserId);
pw.print(" effectiveUid="); UserHandle.formatUid(pw, effectiveUid);
diff --git a/services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java b/services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java
index 9d19cfe95f26..4de61f04af5c 100644
--- a/services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java
+++ b/services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java
@@ -137,7 +137,7 @@ class TaskLaunchParamsModifier implements LaunchParamsModifier {
// STEP 1: Determine the display to launch the activity/task.
final int displayId = getPreferredLaunchDisplay(task, options, source, currentParams);
outParams.mPreferredDisplayId = displayId;
- ActivityDisplay display = mSupervisor.mRootActivityContainer.getActivityDisplay(displayId);
+ DisplayContent display = mSupervisor.mRootActivityContainer.getDisplayContent(displayId);
if (DEBUG) {
appendLog("display-id=" + outParams.mPreferredDisplayId + " display-windowing-mode="
+ display.getWindowingMode());
@@ -282,7 +282,7 @@ class TaskLaunchParamsModifier implements LaunchParamsModifier {
if (source != null && source.inFreeformWindowingMode()
&& resolvedMode == WINDOWING_MODE_FREEFORM
&& outParams.mBounds.isEmpty()
- && source.getDisplayId() == display.mDisplayId) {
+ && source.getDisplayId() == display.getDisplayId()) {
// Set bounds to be not very far from source activity.
cascadeBounds(source.getConfiguration().windowConfiguration.getBounds(),
display, outParams.mBounds);
@@ -333,17 +333,17 @@ class TaskLaunchParamsModifier implements LaunchParamsModifier {
}
if (displayId != INVALID_DISPLAY
- && mSupervisor.mRootActivityContainer.getActivityDisplay(displayId) == null) {
+ && mSupervisor.mRootActivityContainer.getDisplayContent(displayId) == null) {
displayId = currentParams.mPreferredDisplayId;
}
displayId = (displayId == INVALID_DISPLAY) ? currentParams.mPreferredDisplayId : displayId;
return (displayId != INVALID_DISPLAY
- && mSupervisor.mRootActivityContainer.getActivityDisplay(displayId) != null)
+ && mSupervisor.mRootActivityContainer.getDisplayContent(displayId) != null)
? displayId : DEFAULT_DISPLAY;
}
- private boolean canInheritWindowingModeFromSource(@NonNull ActivityDisplay display,
+ private boolean canInheritWindowingModeFromSource(@NonNull DisplayContent display,
@Nullable ActivityRecord source) {
if (source == null) {
return false;
@@ -365,10 +365,10 @@ class TaskLaunchParamsModifier implements LaunchParamsModifier {
// Only inherit windowing mode if both source and target activities are on the same display.
// Otherwise we may have unintended freeform windows showing up if an activity in freeform
// window launches an activity on a fullscreen display by specifying display ID.
- return display.mDisplayId == source.getDisplayId();
+ return display.getDisplayId() == source.getDisplayId();
}
- private boolean canApplyFreeformWindowPolicy(@NonNull ActivityDisplay display, int launchMode) {
+ private boolean canApplyFreeformWindowPolicy(@NonNull DisplayContent display, int launchMode) {
return mSupervisor.mService.mSupportsFreeformWindowManagement
&& (display.inFreeformWindowingMode() || launchMode == WINDOWING_MODE_FREEFORM);
}
@@ -378,7 +378,7 @@ class TaskLaunchParamsModifier implements LaunchParamsModifier {
&& launchMode == WINDOWING_MODE_PINNED;
}
- private void getLayoutBounds(@NonNull ActivityDisplay display, @NonNull ActivityRecord root,
+ private void getLayoutBounds(@NonNull DisplayContent display, @NonNull ActivityRecord root,
@NonNull ActivityInfo.WindowLayout windowLayout, @NonNull Rect outBounds) {
final int verticalGravity = windowLayout.gravity & Gravity.VERTICAL_GRAVITY_MASK;
final int horizontalGravity = windowLayout.gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
@@ -488,7 +488,7 @@ class TaskLaunchParamsModifier implements LaunchParamsModifier {
return orientation;
}
- private void cascadeBounds(@NonNull Rect srcBounds, @NonNull ActivityDisplay display,
+ private void cascadeBounds(@NonNull Rect srcBounds, @NonNull DisplayContent display,
@NonNull Rect outBounds) {
outBounds.set(srcBounds);
float density = (float) display.getConfiguration().densityDpi / DENSITY_DEFAULT;
@@ -500,7 +500,7 @@ class TaskLaunchParamsModifier implements LaunchParamsModifier {
outBounds.offset(dx, dy);
}
- private void getTaskBounds(@NonNull ActivityRecord root, @NonNull ActivityDisplay display,
+ private void getTaskBounds(@NonNull ActivityRecord root, @NonNull DisplayContent display,
@NonNull ActivityInfo.WindowLayout layout, int resolvedMode, boolean hasInitialBounds,
@NonNull Rect inOutBounds) {
if (resolvedMode == WINDOWING_MODE_FULLSCREEN) {
@@ -567,7 +567,7 @@ class TaskLaunchParamsModifier implements LaunchParamsModifier {
}
}
- private int resolveOrientation(@NonNull ActivityRecord root, @NonNull ActivityDisplay display,
+ private int resolveOrientation(@NonNull ActivityRecord root, @NonNull DisplayContent display,
@NonNull Rect bounds) {
int orientation = resolveOrientation(root);
@@ -593,7 +593,7 @@ class TaskLaunchParamsModifier implements LaunchParamsModifier {
return orientation;
}
- private void getDefaultFreeformSize(@NonNull ActivityDisplay display,
+ private void getDefaultFreeformSize(@NonNull DisplayContent display,
@NonNull ActivityInfo.WindowLayout layout, int orientation, @NonNull Rect bounds) {
// Default size, which is letterboxing/pillarboxing in display. That's to say the large
// dimension of default size is the small dimension of display size, and the small dimension
@@ -637,7 +637,7 @@ class TaskLaunchParamsModifier implements LaunchParamsModifier {
* Gets centered bounds of width x height. If inOutBounds is not empty, the result bounds
* centers at its center or display's app bounds center if inOutBounds is empty.
*/
- private void centerBounds(@NonNull ActivityDisplay display, int width, int height,
+ private void centerBounds(@NonNull DisplayContent display, int width, int height,
@NonNull Rect inOutBounds) {
if (inOutBounds.isEmpty()) {
inOutBounds.set(display.mDisplayContent.mDisplayFrames.mStable);
@@ -647,7 +647,7 @@ class TaskLaunchParamsModifier implements LaunchParamsModifier {
inOutBounds.set(left, top, left + width, top + height);
}
- private void adjustBoundsToFitInDisplay(@NonNull ActivityDisplay display,
+ private void adjustBoundsToFitInDisplay(@NonNull DisplayContent display,
@NonNull Rect inOutBounds) {
final Rect displayStableBounds = display.mDisplayContent.mDisplayFrames.mStable;
@@ -702,7 +702,7 @@ class TaskLaunchParamsModifier implements LaunchParamsModifier {
* @param display the display which tasks are to check
* @param inOutBounds the bounds used to input initial bounds and output result bounds
*/
- private void adjustBoundsToAvoidConflictInDisplay(@NonNull ActivityDisplay display,
+ private void adjustBoundsToAvoidConflictInDisplay(@NonNull DisplayContent display,
@NonNull Rect inOutBounds) {
final List<Rect> taskBoundsToCheck = new ArrayList<>();
for (int i = 0; i < display.getStackCount(); ++i) {
diff --git a/services/core/java/com/android/server/wm/TaskSnapshotCache.java b/services/core/java/com/android/server/wm/TaskSnapshotCache.java
index 5cbab5d1b1f5..7b0d841483bb 100644
--- a/services/core/java/com/android/server/wm/TaskSnapshotCache.java
+++ b/services/core/java/com/android/server/wm/TaskSnapshotCache.java
@@ -109,7 +109,7 @@ class TaskSnapshotCache {
removeRunningEntry(taskId);
}
- private void removeRunningEntry(int taskId) {
+ void removeRunningEntry(int taskId) {
final CacheEntry entry = mRunningCache.get(taskId);
if (entry != null) {
mAppTaskMap.remove(entry.topApp);
diff --git a/services/core/java/com/android/server/wm/TaskSnapshotController.java b/services/core/java/com/android/server/wm/TaskSnapshotController.java
index c1a36c49fc1a..456068c788b7 100644
--- a/services/core/java/com/android/server/wm/TaskSnapshotController.java
+++ b/services/core/java/com/android/server/wm/TaskSnapshotController.java
@@ -89,6 +89,14 @@ class TaskSnapshotController {
@VisibleForTesting
static final int SNAPSHOT_MODE_NONE = 2;
+ /**
+ * Constant for <code>scaleFactor</code> when calling {@link #snapshotTask} which is
+ * interpreted as using the most appropriate scale ratio for the system.
+ * This may yield a smaller ratio on low memory devices.
+ */
+ @VisibleForTesting
+ static final float SNAPSHOT_SCALE_AUTO = -1f;
+
private final WindowManagerService mService;
private final TaskSnapshotCache mCache;
@@ -171,22 +179,30 @@ class TaskSnapshotController {
}
void snapshotTasks(ArraySet<Task> tasks) {
+ snapshotTasks(mTmpTasks, false /* allowSnapshotHome */);
+ }
+
+ private void snapshotTasks(ArraySet<Task> tasks, boolean allowSnapshotHome) {
for (int i = tasks.size() - 1; i >= 0; i--) {
final Task task = tasks.valueAt(i);
- final int mode = getSnapshotMode(task);
final TaskSnapshot snapshot;
- switch (mode) {
- case SNAPSHOT_MODE_NONE:
- continue;
- case SNAPSHOT_MODE_APP_THEME:
- snapshot = drawAppThemeSnapshot(task);
- break;
- case SNAPSHOT_MODE_REAL:
- snapshot = snapshotTask(task);
- break;
- default:
- snapshot = null;
- break;
+ final boolean snapshotHome = allowSnapshotHome && task.isActivityTypeHome();
+ if (snapshotHome) {
+ snapshot = snapshotTask(task);
+ } else {
+ switch (getSnapshotMode(task)) {
+ case SNAPSHOT_MODE_NONE:
+ continue;
+ case SNAPSHOT_MODE_APP_THEME:
+ snapshot = drawAppThemeSnapshot(task);
+ break;
+ case SNAPSHOT_MODE_REAL:
+ snapshot = snapshotTask(task);
+ break;
+ default:
+ snapshot = null;
+ break;
+ }
}
if (snapshot != null) {
final GraphicBuffer buffer = snapshot.getSnapshot();
@@ -196,8 +212,11 @@ class TaskSnapshotController {
+ buffer.getHeight());
} else {
mCache.putSnapshot(task, snapshot);
- mPersister.persistSnapshot(task.mTaskId, task.mUserId, snapshot);
- task.onSnapshotChanged(snapshot);
+ // Don't persist or notify the change for the temporal snapshot.
+ if (!snapshotHome) {
+ mPersister.persistSnapshot(task.mTaskId, task.mUserId, snapshot);
+ task.onSnapshotChanged(snapshot);
+ }
}
}
}
@@ -249,6 +268,84 @@ class TaskSnapshotController {
});
}
+ /**
+ * Validates the state of the Task is appropriate to capture a snapshot, collects
+ * information from the task and populates the builder.
+ *
+ * @param task the task to capture
+ * @param scaleFraction the scale fraction between 0-1.0, or {@link #SNAPSHOT_SCALE_AUTO}
+ * to automatically select
+ * @param pixelFormat the desired pixel format, or {@link PixelFormat#UNKNOWN} to
+ * automatically select
+ * @param builder the snapshot builder to populate
+ *
+ * @return true if the state of the task is ok to proceed
+ */
+ private boolean prepareTaskSnapshot(Task task, float scaleFraction, int pixelFormat,
+ TaskSnapshot.Builder builder) {
+ if (!mService.mPolicy.isScreenOn()) {
+ if (DEBUG_SCREENSHOT) {
+ Slog.i(TAG_WM, "Attempted to take screenshot while display was off.");
+ }
+ return false;
+ }
+ final ActivityRecord activity = findAppTokenForSnapshot(task);
+ if (activity == null) {
+ if (DEBUG_SCREENSHOT) {
+ Slog.w(TAG_WM, "Failed to take screenshot. No visible windows for " + task);
+ }
+ return false;
+ }
+ if (activity.hasCommittedReparentToAnimationLeash()) {
+ if (DEBUG_SCREENSHOT) {
+ Slog.w(TAG_WM, "Failed to take screenshot. App is animating " + activity);
+ }
+ return false;
+ }
+
+ final WindowState mainWindow = activity.findMainWindow();
+ if (mainWindow == null) {
+ Slog.w(TAG_WM, "Failed to take screenshot. No main window for " + task);
+ return false;
+ }
+
+ builder.setIsRealSnapshot(true);
+ builder.setId(System.currentTimeMillis());
+ builder.setContentInsets(getInsets(mainWindow));
+
+ final boolean isLowRamDevice = ActivityManager.isLowRamDeviceStatic();
+
+ if (scaleFraction == SNAPSHOT_SCALE_AUTO) {
+ builder.setScaleFraction(isLowRamDevice
+ ? mPersister.getReducedScale()
+ : mFullSnapshotScale);
+ builder.setReducedResolution(isLowRamDevice);
+ } else {
+ builder.setScaleFraction(scaleFraction);
+ builder.setReducedResolution(scaleFraction < 1.0f);
+ }
+
+ final boolean isWindowTranslucent = mainWindow.getAttrs().format != PixelFormat.OPAQUE;
+ final boolean isShowWallpaper = (mainWindow.getAttrs().flags & FLAG_SHOW_WALLPAPER) != 0;
+
+ if (pixelFormat == PixelFormat.UNKNOWN) {
+ pixelFormat = mPersister.use16BitFormat() && activity.fillsParent()
+ && !(isWindowTranslucent && isShowWallpaper)
+ ? PixelFormat.RGB_565
+ : PixelFormat.RGBA_8888;
+ }
+
+ final boolean isTranslucent = PixelFormat.formatHasAlpha(pixelFormat)
+ && (!activity.fillsParent() || isWindowTranslucent);
+
+ builder.setTopActivityComponent(activity.mActivityComponent);
+ builder.setIsTranslucent(isTranslucent);
+ builder.setOrientation(activity.getTask().getConfiguration().orientation);
+ builder.setWindowingMode(task.getWindowingMode());
+ builder.setSystemUiVisibility(getSystemUiVisibility(task));
+ return true;
+ }
+
@Nullable
SurfaceControl.ScreenshotGraphicBuffer createTaskSnapshot(@NonNull Task task,
float scaleFraction) {
@@ -277,63 +374,31 @@ class TaskSnapshotController {
return screenshotBuffer;
}
- @Nullable private TaskSnapshot snapshotTask(Task task) {
- if (!mService.mPolicy.isScreenOn()) {
- if (DEBUG_SCREENSHOT) {
- Slog.i(TAG_WM, "Attempted to take screenshot while display was off.");
- }
- return null;
- }
-
- final ActivityRecord activity = findAppTokenForSnapshot(task);
- if (activity == null) {
- if (DEBUG_SCREENSHOT) {
- Slog.w(TAG_WM, "Failed to take screenshot. No visible windows for " + task);
- }
- return null;
- }
- if (activity.hasCommittedReparentToAnimationLeash()) {
- if (DEBUG_SCREENSHOT) {
- Slog.w(TAG_WM, "Failed to take screenshot. App is animating " + activity);
- }
- return null;
- }
+ @Nullable
+ TaskSnapshot snapshotTask(Task task) {
+ return snapshotTask(task, SNAPSHOT_SCALE_AUTO, PixelFormat.UNKNOWN);
+ }
- final boolean isLowRamDevice = ActivityManager.isLowRamDeviceStatic();
- final float scaleFraction = isLowRamDevice
- ? mPersister.getReducedScale()
- : mFullSnapshotScale;
+ @Nullable
+ TaskSnapshot snapshotTask(Task task, float scaleFraction, int pixelFormat) {
+ TaskSnapshot.Builder builder = new TaskSnapshot.Builder();
- final WindowState mainWindow = activity.findMainWindow();
- if (mainWindow == null) {
- Slog.w(TAG_WM, "Failed to take screenshot. No main window for " + task);
+ if (!prepareTaskSnapshot(task, scaleFraction, pixelFormat, builder)) {
+ // Failed some pre-req. Has been logged.
return null;
}
- final boolean isWindowTranslucent = mainWindow.getAttrs().format != PixelFormat.OPAQUE;
- final boolean isShowWallpaper = (mainWindow.getAttrs().flags & FLAG_SHOW_WALLPAPER) != 0;
- final int pixelFormat = mPersister.use16BitFormat() && activity.fillsParent()
- && !(isWindowTranslucent && isShowWallpaper)
- ? PixelFormat.RGB_565
- : PixelFormat.RGBA_8888;
+
final SurfaceControl.ScreenshotGraphicBuffer screenshotBuffer =
- createTaskSnapshot(task, scaleFraction, pixelFormat);
+ createTaskSnapshot(task, builder.getScaleFraction(),
+ builder.getPixelFormat());
if (screenshotBuffer == null) {
- if (DEBUG_SCREENSHOT) {
- Slog.w(TAG_WM, "Failed to take screenshot for " + task);
- }
+ // Failed to acquire image. Has been logged.
return null;
}
- final boolean isTranslucent = PixelFormat.formatHasAlpha(pixelFormat)
- && (!activity.fillsParent() || isWindowTranslucent);
- return new TaskSnapshot(
- System.currentTimeMillis() /* id */,
- activity.mActivityComponent, screenshotBuffer.getGraphicBuffer(),
- screenshotBuffer.getColorSpace(),
- activity.getTask().getConfiguration().orientation,
- getInsets(mainWindow), isLowRamDevice /* reduced */, scaleFraction /* scale */,
- true /* isRealSnapshot */, task.getWindowingMode(), getSystemUiVisibility(task),
- isTranslucent);
+ builder.setSnapshot(screenshotBuffer.getGraphicBuffer());
+ builder.setColorSpace(screenshotBuffer.getColorSpace());
+ return builder.build();
}
private boolean shouldDisableSnapshots() {
@@ -403,7 +468,7 @@ class TaskSnapshotController {
final LayoutParams attrs = mainWindow.getAttrs();
final SystemBarBackgroundPainter decorPainter = new SystemBarBackgroundPainter(attrs.flags,
attrs.privateFlags, attrs.systemUiVisibility, task.getTaskDescription(),
- mFullSnapshotScale);
+ mFullSnapshotScale, mainWindow.getClientInsetsState());
final int width = (int) (task.getBounds().width() * mFullSnapshotScale);
final int height = (int) (task.getBounds().height() * mFullSnapshotScale);
@@ -450,6 +515,10 @@ class TaskSnapshotController {
mPersister.onTaskRemovedFromRecents(taskId, userId);
}
+ void removeSnapshotCache(int taskId) {
+ mCache.removeRunningEntry(taskId);
+ }
+
/**
* See {@link TaskSnapshotPersister#removeObsoleteFiles}
*/
@@ -485,7 +554,9 @@ class TaskSnapshotController {
mTmpTasks.add(task);
}
});
- snapshotTasks(mTmpTasks);
+ // Allow taking snapshot of home when turning screen off to reduce the delay of
+ // unlocking/waking to home.
+ snapshotTasks(mTmpTasks, true /* allowSnapshotHome */);
}
} finally {
listener.onScreenOff();
@@ -494,16 +565,16 @@ class TaskSnapshotController {
}
/**
- * @return The SystemUI visibility flags for the top fullscreen window in the given
+ * @return The SystemUI visibility flags for the top fullscreen opaque window in the given
* {@param task}.
*/
private int getSystemUiVisibility(Task task) {
final ActivityRecord topFullscreenActivity = task.getTopFullscreenActivity();
- final WindowState topFullscreenWindow = topFullscreenActivity != null
- ? topFullscreenActivity.getTopFullscreenWindow()
+ final WindowState topFullscreenOpaqueWindow = topFullscreenActivity != null
+ ? topFullscreenActivity.getTopFullscreenOpaqueWindow()
: null;
- if (topFullscreenWindow != null) {
- return topFullscreenWindow.getSystemUiVisibility();
+ if (topFullscreenOpaqueWindow != null) {
+ return topFullscreenOpaqueWindow.getSystemUiVisibility();
}
return 0;
}
diff --git a/services/core/java/com/android/server/wm/TaskSnapshotPersister.java b/services/core/java/com/android/server/wm/TaskSnapshotPersister.java
index 59155907823b..10f29960081e 100644
--- a/services/core/java/com/android/server/wm/TaskSnapshotPersister.java
+++ b/services/core/java/com/android/server/wm/TaskSnapshotPersister.java
@@ -54,7 +54,6 @@ class TaskSnapshotPersister {
private static final String REDUCED_POSTFIX = "_reduced";
private static final float REDUCED_SCALE = .5f;
private static final float LOW_RAM_REDUCED_SCALE = .6f;
- private static final float LOW_RAM_RECENTS_REDUCED_SCALE = .1f;
static final boolean DISABLE_FULL_SIZED_BITMAPS = ActivityManager.isLowRamDeviceStatic();
private static final long DELAY_MS = 100;
private static final int QUALITY = 95;
@@ -85,14 +84,8 @@ class TaskSnapshotPersister {
TaskSnapshotPersister(WindowManagerService service, DirectoryResolver resolver) {
mDirectoryResolver = resolver;
- if (service.mLowRamTaskSnapshotsAndRecents) {
- // Use very low res snapshots if we are using Go version of recents.
- mReducedScale = LOW_RAM_RECENTS_REDUCED_SCALE;
- } else {
- // TODO(122671846) Replace the low RAM value scale with the above when it is fully built
- mReducedScale = ActivityManager.isLowRamDeviceStatic()
- ? LOW_RAM_REDUCED_SCALE : REDUCED_SCALE;
- }
+ mReducedScale = ActivityManager.isLowRamDeviceStatic()
+ ? LOW_RAM_REDUCED_SCALE : REDUCED_SCALE;
mUse16BitFormat = service.mContext.getResources().getBoolean(
com.android.internal.R.bool.config_use16BitTaskSnapshotPixelFormat);
}
diff --git a/services/core/java/com/android/server/wm/TaskSnapshotSurface.java b/services/core/java/com/android/server/wm/TaskSnapshotSurface.java
index b3750e95fb36..5b458d894430 100644
--- a/services/core/java/com/android/server/wm/TaskSnapshotSurface.java
+++ b/services/core/java/com/android/server/wm/TaskSnapshotSurface.java
@@ -71,6 +71,7 @@ import android.view.SurfaceControl;
import android.view.SurfaceSession;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
+import android.view.ViewRootImpl;
import android.view.WindowManager;
import android.view.WindowManagerGlobal;
@@ -154,6 +155,7 @@ class TaskSnapshotSurface implements StartingSurface {
final MergedConfiguration tmpMergedConfiguration = new MergedConfiguration();
final TaskDescription taskDescription = new TaskDescription();
taskDescription.setBackgroundColor(WHITE);
+ final WindowState topFullscreenOpaqueWindow;
final int sysUiVis;
final int windowFlags;
final int windowPrivateFlags;
@@ -173,15 +175,15 @@ class TaskSnapshotSurface implements StartingSurface {
+ task);
return null;
}
- final WindowState topFullscreenWindow = topFullscreenActivity.getTopFullscreenWindow();
- if (mainWindow == null || topFullscreenWindow == null) {
+ topFullscreenOpaqueWindow = topFullscreenActivity.getTopFullscreenOpaqueWindow();
+ if (mainWindow == null || topFullscreenOpaqueWindow == null) {
Slog.w(TAG, "TaskSnapshotSurface.create: Failed to find main window for activity="
+ activity);
return null;
}
- sysUiVis = topFullscreenWindow.getSystemUiVisibility();
- windowFlags = topFullscreenWindow.getAttrs().flags;
- windowPrivateFlags = topFullscreenWindow.getAttrs().privateFlags;
+ sysUiVis = topFullscreenOpaqueWindow.getSystemUiVisibility();
+ windowFlags = topFullscreenOpaqueWindow.getAttrs().flags;
+ windowPrivateFlags = topFullscreenOpaqueWindow.getAttrs().privateFlags;
layoutParams.packageName = mainWindow.getAttrs().packageName;
layoutParams.windowAnimations = mainWindow.getAttrs().windowAnimations;
@@ -200,11 +202,11 @@ class TaskSnapshotSurface implements StartingSurface {
final TaskDescription td = task.getTaskDescription();
if (td != null) {
- taskDescription.copyFrom(td);
+ taskDescription.copyFromPreserveHiddenFields(td);
}
taskBounds = new Rect();
task.getBounds(taskBounds);
- currentOrientation = topFullscreenWindow.getConfiguration().orientation;
+ currentOrientation = topFullscreenOpaqueWindow.getConfiguration().orientation;
}
try {
final int res = session.addToDisplay(window, window.mSeq, layoutParams,
@@ -220,7 +222,7 @@ class TaskSnapshotSurface implements StartingSurface {
final TaskSnapshotSurface snapshotSurface = new TaskSnapshotSurface(service, window,
surfaceControl, snapshot, layoutParams.getTitle(), taskDescription, sysUiVis,
windowFlags, windowPrivateFlags, taskBounds,
- currentOrientation);
+ currentOrientation, topFullscreenOpaqueWindow.getClientInsetsState());
window.setOuter(snapshotSurface);
try {
session.relayout(window, window.mSeq, layoutParams, -1, -1, View.VISIBLE, 0, -1,
@@ -238,7 +240,7 @@ class TaskSnapshotSurface implements StartingSurface {
TaskSnapshotSurface(WindowManagerService service, Window window, SurfaceControl surfaceControl,
TaskSnapshot snapshot, CharSequence title, TaskDescription taskDescription,
int sysUiVis, int windowFlags, int windowPrivateFlags, Rect taskBounds,
- int currentOrientation) {
+ int currentOrientation, InsetsState insetsState) {
mService = service;
mSurface = service.mSurfaceFactory.get();
mHandler = new Handler(mService.mH.getLooper());
@@ -251,7 +253,7 @@ class TaskSnapshotSurface implements StartingSurface {
mBackgroundPaint.setColor(backgroundColor != 0 ? backgroundColor : WHITE);
mTaskBounds = taskBounds;
mSystemBarBackgroundPainter = new SystemBarBackgroundPainter(windowFlags,
- windowPrivateFlags, sysUiVis, taskDescription, 1f);
+ windowPrivateFlags, sysUiVis, taskDescription, 1f, insetsState);
mStatusBarColor = taskDescription.getStatusBarColor();
mOrientationOnCreation = currentOrientation;
mTransaction = mService.mTransactionFactory.get();
@@ -502,9 +504,10 @@ class TaskSnapshotSurface implements StartingSurface {
private final int mWindowPrivateFlags;
private final int mSysUiVis;
private final float mScale;
+ private final InsetsState mInsetsState;
SystemBarBackgroundPainter(int windowFlags, int windowPrivateFlags, int sysUiVis,
- TaskDescription taskDescription, float scale) {
+ TaskDescription taskDescription, float scale, InsetsState insetsState) {
mWindowFlags = windowFlags;
mWindowPrivateFlags = windowPrivateFlags;
mSysUiVis = sysUiVis;
@@ -524,6 +527,7 @@ class TaskSnapshotSurface implements StartingSurface {
&& context.getResources().getBoolean(R.bool.config_navBarNeedsScrim));
mStatusBarPaint.setColor(mStatusBarColor);
mNavigationBarPaint.setColor(mNavigationBarColor);
+ mInsetsState = insetsState;
}
void setInsets(Rect contentInsets, Rect stableInsets) {
@@ -534,8 +538,11 @@ class TaskSnapshotSurface implements StartingSurface {
int getStatusBarColorViewHeight() {
final boolean forceBarBackground =
(mWindowPrivateFlags & PRIVATE_FLAG_FORCE_DRAW_BAR_BACKGROUNDS) != 0;
- if (STATUS_BAR_COLOR_VIEW_ATTRIBUTES.isVisible(
- mSysUiVis, mStatusBarColor, mWindowFlags, forceBarBackground)) {
+ if (ViewRootImpl.sNewInsetsMode != ViewRootImpl.NEW_INSETS_MODE_FULL
+ ? STATUS_BAR_COLOR_VIEW_ATTRIBUTES.isVisible(
+ mSysUiVis, mStatusBarColor, mWindowFlags, forceBarBackground)
+ : STATUS_BAR_COLOR_VIEW_ATTRIBUTES.isVisible(
+ mInsetsState, mStatusBarColor, mWindowFlags, forceBarBackground)) {
return (int) (getColorViewTopInset(mStableInsets.top, mContentInsets.top) * mScale);
} else {
return 0;
@@ -545,8 +552,11 @@ class TaskSnapshotSurface implements StartingSurface {
private boolean isNavigationBarColorViewVisible() {
final boolean forceBarBackground =
(mWindowPrivateFlags & PRIVATE_FLAG_FORCE_DRAW_BAR_BACKGROUNDS) != 0;
- return NAVIGATION_BAR_COLOR_VIEW_ATTRIBUTES.isVisible(
- mSysUiVis, mNavigationBarColor, mWindowFlags, forceBarBackground);
+ return ViewRootImpl.sNewInsetsMode != ViewRootImpl.NEW_INSETS_MODE_FULL
+ ? NAVIGATION_BAR_COLOR_VIEW_ATTRIBUTES.isVisible(
+ mSysUiVis, mNavigationBarColor, mWindowFlags, forceBarBackground)
+ : NAVIGATION_BAR_COLOR_VIEW_ATTRIBUTES.isVisible(
+ mInsetsState, mNavigationBarColor, mWindowFlags, forceBarBackground);
}
void drawDecors(Canvas c, @Nullable Rect alreadyDrawnFrame) {
diff --git a/services/core/java/com/android/server/wm/WindowContainer.java b/services/core/java/com/android/server/wm/WindowContainer.java
index e80f3b8577d3..ce8e6ddc7115 100644
--- a/services/core/java/com/android/server/wm/WindowContainer.java
+++ b/services/core/java/com/android/server/wm/WindowContainer.java
@@ -30,6 +30,7 @@ import static android.view.SurfaceControl.Transaction;
import static com.android.server.policy.WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER;
import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_APP_TRANSITIONS;
import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_APP_TRANSITIONS_ANIM;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ORIENTATION;
import static com.android.server.wm.WindowContainer.AnimationFlags.CHILDREN;
import static com.android.server.wm.WindowContainer.AnimationFlags.PARENTS;
import static com.android.server.wm.WindowContainer.AnimationFlags.TRANSITION;
@@ -41,7 +42,6 @@ import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ANIM;
import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
import static com.android.server.wm.WindowManagerService.logWithStack;
-import static com.android.server.wm.WindowStateAnimator.DRAW_PENDING;
import static com.android.server.wm.WindowStateAnimator.STACK_CLIP_AFTER_ANIM;
import android.annotation.CallSuper;
@@ -70,7 +70,6 @@ import android.view.animation.Animation;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.ToBooleanFunction;
-import com.android.server.policy.WindowManagerPolicy;
import com.android.server.protolog.common.ProtoLog;
import com.android.server.wm.SurfaceAnimator.Animatable;
@@ -132,6 +131,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
protected final WindowList<E> mChildren = new WindowList<E>();
// The specified orientation for this window container.
+ @ActivityInfo.ScreenOrientation
protected int mOrientation = SCREEN_ORIENTATION_UNSPECIFIED;
private final Pools.SynchronizedPool<ForAllWindowsConsumerWrapper> mConsumerWrapperPool =
@@ -244,6 +244,8 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
protected final Rect mTmpRect = new Rect();
final Rect mTmpPrevBounds = new Rect();
+ private MagnificationSpec mLastMagnificationSpec;
+
WindowContainer(WindowManagerService wms) {
mWmService = wms;
mPendingTransaction = wms.mTransactionFactory.get();
@@ -984,6 +986,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
}
}
+ @ActivityInfo.ScreenOrientation
int getOrientation() {
return getOrientation(mOrientation);
}
@@ -1036,6 +1039,8 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
if (wc.fillsParent() || orientation != SCREEN_ORIENTATION_UNSPECIFIED) {
// Use the orientation if the container fills its parent or requested an explicit
// orientation that isn't SCREEN_ORIENTATION_UNSPECIFIED.
+ ProtoLog.v(WM_DEBUG_ORIENTATION, "%s is requesting orientation %d (%s)", toString(),
+ orientation, ActivityInfo.screenOrientationToString(orientation));
return orientation;
}
}
@@ -1202,9 +1207,17 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
}
ActivityRecord getActivity(Predicate<ActivityRecord> callback, boolean traverseTopToBottom) {
+ return getActivity(callback, traverseTopToBottom, null /*boundary*/);
+ }
+
+ ActivityRecord getActivity(Predicate<ActivityRecord> callback, boolean traverseTopToBottom,
+ WindowContainer boundary) {
if (traverseTopToBottom) {
for (int i = mChildren.size() - 1; i >= 0; --i) {
- final ActivityRecord r = mChildren.get(i).getActivity(callback, traverseTopToBottom);
+ final WindowContainer wc = mChildren.get(i);
+ if (wc == boundary) return null;
+
+ final ActivityRecord r = wc.getActivity(callback, traverseTopToBottom, boundary);
if (r != null) {
return r;
}
@@ -1212,7 +1225,10 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
} else {
final int count = mChildren.size();
for (int i = 0; i < count; i++) {
- final ActivityRecord r = mChildren.get(i).getActivity(callback, traverseTopToBottom);
+ final WindowContainer wc = mChildren.get(i);
+ if (wc == boundary) return null;
+
+ final ActivityRecord r = wc.getActivity(callback, traverseTopToBottom, boundary);
if (r != null) {
return r;
}
@@ -1320,14 +1336,57 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
/**
* For all tasks at or below this container call the callback.
*
+ * @param callback Calls the {@link ToBooleanFunction#apply} method for each task found and
+ * stops the search if {@link ToBooleanFunction#apply} returns {@code true}.
+ */
+ boolean forAllTasks(Function<Task, Boolean> callback) {
+ for (int i = mChildren.size() - 1; i >= 0; --i) {
+ if (mChildren.get(i).forAllTasks(callback)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * For all tasks at or below this container call the callback.
+ *
* @param callback Callback to be called for every task.
*/
void forAllTasks(Consumer<Task> callback) {
- for (int i = mChildren.size() - 1; i >= 0; --i) {
- mChildren.get(i).forAllTasks(callback);
+ forAllTasks(callback, true /*traverseTopToBottom*/);
+ }
+
+ void forAllTasks(Consumer<Task> callback, boolean traverseTopToBottom) {
+ final int count = mChildren.size();
+ if (traverseTopToBottom) {
+ for (int i = count - 1; i >= 0; --i) {
+ mChildren.get(i).forAllTasks(callback, traverseTopToBottom);
+ }
+ } else {
+ for (int i = 0; i < count; i++) {
+ mChildren.get(i).forAllTasks(callback, traverseTopToBottom);
+ }
}
}
+ Task getTaskAbove(Task t) {
+ return getTask(
+ (above) -> true, t, false /*includeBoundary*/, false /*traverseTopToBottom*/);
+ }
+
+ Task getTaskBelow(Task t) {
+ return getTask((below) -> true, t, false /*includeBoundary*/, true /*traverseTopToBottom*/);
+ }
+
+ Task getBottomMostTask() {
+ return getTask((t) -> true, false /*traverseTopToBottom*/);
+ }
+
+ Task getTopMostTask() {
+ return getTask((t) -> true, true /*traverseTopToBottom*/);
+ }
+
Task getTask(Predicate<Task> callback) {
return getTask(callback, true /*traverseTopToBottom*/);
}
@@ -1354,18 +1413,59 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
}
/**
- * For all tasks at or below this container call the callback.
+ * Gets an task in a branch of the tree.
*
- * @param callback Calls the {@link ToBooleanFunction#apply} method for each task found and
- * stops the search if {@link ToBooleanFunction#apply} returns {@code true}.
+ * @param callback called to test if this is the task that should be returned.
+ * @param boundary We don't return tasks via {@param callback} until we get to this node in
+ * the tree.
+ * @param includeBoundary If the boundary from be processed to return tasks.
+ * @param traverseTopToBottom direction to traverse the tree.
+ * @return The task if found or null.
*/
- boolean forAllTasks(ToBooleanFunction<Task> callback) {
- for (int i = mChildren.size() - 1; i >= 0; --i) {
- if (mChildren.get(i).forAllTasks(callback)) {
- return true;
+ final Task getTask(Predicate<Task> callback, WindowContainer boundary, boolean includeBoundary,
+ boolean traverseTopToBottom) {
+ return getTask(callback, boundary, includeBoundary, traverseTopToBottom, new boolean[1]);
+ }
+
+ private Task getTask(Predicate<Task> callback,
+ WindowContainer boundary, boolean includeBoundary, boolean traverseTopToBottom,
+ boolean[] boundaryFound) {
+ if (traverseTopToBottom) {
+ for (int i = mChildren.size() - 1; i >= 0; --i) {
+ final Task t = processGetTaskWithBoundary(callback, boundary,
+ includeBoundary, traverseTopToBottom, boundaryFound, mChildren.get(i));
+ if (t != null) {
+ return t;
+ }
+ }
+ } else {
+ final int count = mChildren.size();
+ for (int i = 0; i < count; i++) {
+ final Task t = processGetTaskWithBoundary(callback, boundary,
+ includeBoundary, traverseTopToBottom, boundaryFound, mChildren.get(i));
+ if (t != null) {
+ return t;
+ }
}
}
- return false;
+
+ return null;
+ }
+
+ private Task processGetTaskWithBoundary(Predicate<Task> callback,
+ WindowContainer boundary, boolean includeBoundary, boolean traverseTopToBottom,
+ boolean[] boundaryFound, WindowContainer wc) {
+ if (wc == boundary || boundary == null) {
+ boundaryFound[0] = true;
+ if (!includeBoundary) return null;
+ }
+
+ if (boundaryFound[0]) {
+ return wc.getTask(callback, traverseTopToBottom);
+ }
+
+ return wc.getTask(
+ callback, boundary, includeBoundary, traverseTopToBottom, boundaryFound);
}
WindowState getWindow(Predicate<WindowState> callback) {
@@ -1631,13 +1731,26 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
if (shouldMagnify()) {
t.setMatrix(mSurfaceControl, spec.scale, 0, 0, spec.scale)
.setPosition(mSurfaceControl, spec.offsetX, spec.offsetY);
+ mLastMagnificationSpec = spec;
} else {
+ clearMagnificationSpec(t);
for (int i = 0; i < mChildren.size(); i++) {
mChildren.get(i).applyMagnificationSpec(t, spec);
}
}
}
+ void clearMagnificationSpec(Transaction t) {
+ if (mLastMagnificationSpec != null) {
+ t.setMatrix(mSurfaceControl, 1, 0, 0, 1)
+ .setPosition(mSurfaceControl, 0, 0);
+ }
+ mLastMagnificationSpec = null;
+ for (int i = 0; i < mChildren.size(); i++) {
+ mChildren.get(i).clearMagnificationSpec(t);
+ }
+ }
+
void prepareSurfaces() {
// If a leash has been set when the transaction was committed, then the leash reparent has
// been committed.
@@ -2056,15 +2169,8 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
}
void waitForAllWindowsDrawn() {
- final WindowManagerPolicy policy = mWmService.mPolicy;
forAllWindows(w -> {
- final boolean keyguard = policy.isKeyguardHostWindow(w.mAttrs);
- if (w.isVisibleLw() && (w.mActivityRecord != null || keyguard)) {
- w.mWinAnimator.mDrawState = DRAW_PENDING;
- // Force add to mResizingWindows.
- w.resetLastContentInsets();
- mWaitingForDrawn.add(w);
- }
+ w.requestDrawIfNeeded(mWaitingForDrawn);
}, true /* traverseTopToBottom */);
}
diff --git a/services/core/java/com/android/server/wm/WindowFrames.java b/services/core/java/com/android/server/wm/WindowFrames.java
index 0490baca713d..97186b4e9cda 100644
--- a/services/core/java/com/android/server/wm/WindowFrames.java
+++ b/services/core/java/com/android/server/wm/WindowFrames.java
@@ -207,6 +207,7 @@ public class WindowFrames {
return (mLastFrame.width() != mFrame.width()) || (mLastFrame.height() != mFrame.height());
}
+ // TODO(b/118118435): Remove after migration.
/**
* Calculate the insets for the type
* {@link android.view.WindowManager.LayoutParams#TYPE_DOCK_DIVIDER}
diff --git a/services/core/java/com/android/server/wm/WindowManagerConstants.java b/services/core/java/com/android/server/wm/WindowManagerConstants.java
index 10c8ef0eaee8..74d5c049746d 100644
--- a/services/core/java/com/android/server/wm/WindowManagerConstants.java
+++ b/services/core/java/com/android/server/wm/WindowManagerConstants.java
@@ -19,6 +19,8 @@ package com.android.server.wm;
import static android.provider.AndroidDeviceConfig.KEY_SYSTEM_GESTURES_EXCLUDED_BY_PRE_Q_STICKY_IMMERSIVE;
import static android.provider.AndroidDeviceConfig.KEY_SYSTEM_GESTURE_EXCLUSION_LIMIT_DP;
+import static com.android.internal.util.Preconditions.checkNotNull;
+
import android.provider.AndroidDeviceConfig;
import android.provider.DeviceConfig;
@@ -72,8 +74,8 @@ final class WindowManagerConstants {
WindowManagerConstants(WindowManagerGlobalLock globalLock,
Runnable updateSystemGestureExclusionCallback,
DeviceConfigInterface deviceConfig) {
- mGlobalLock = globalLock;
- mUpdateSystemGestureExclusionCallback = updateSystemGestureExclusionCallback;
+ mGlobalLock = checkNotNull(globalLock);
+ mUpdateSystemGestureExclusionCallback = checkNotNull(updateSystemGestureExclusionCallback);
mDeviceConfig = deviceConfig;
mListenerAndroid = this::onAndroidPropertiesChanged;
mListenerWindowManager = this::onWindowPropertiesChanged;
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 95eb4ddceb45..68de4cd84bbf 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -16,7 +16,6 @@
package com.android.server.wm;
-import static android.Manifest.permission.ACCESS_SURFACE_FLINGER;
import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
@@ -80,7 +79,6 @@ import static com.android.internal.util.LatencyTracker.ACTION_ROTATE_SCREEN;
import static com.android.server.LockGuard.INDEX_WINDOW;
import static com.android.server.LockGuard.installLock;
import static com.android.server.policy.WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER;
-import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ADD_REMOVE;
import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_BOOT;
import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_FOCUS;
@@ -407,8 +405,7 @@ public class WindowManagerService extends IWindowManager.Stub
private static final int ANIMATION_COMPLETED_TIMEOUT_MS = 5000;
- final WindowManagerConstants mConstants = new WindowManagerConstants(this,
- DeviceConfigInterface.REAL);
+ final WindowManagerConstants mConstants;
final WindowTracing mWindowTracing;
@@ -492,13 +489,6 @@ public class WindowManagerService extends IWindowManager.Stub
final long mDrawLockTimeoutMillis;
final boolean mAllowAnimationsInLowPowerMode;
- // TODO(b/122671846) Remove the flag below in favor of isLowRam once feature is stable
- /**
- * Use very low resolution task snapshots. Replaces task snapshot starting windows with
- * splashscreen starting windows. Used on low RAM devices to save memory.
- */
- final boolean mLowRamTaskSnapshotsAndRecents;
-
final boolean mAllowBootMessages;
final boolean mLimitedAlphaCompositing;
@@ -1115,8 +1105,6 @@ public class WindowManagerService extends IWindowManager.Stub
com.android.internal.R.bool.config_disableTransitionAnimation);
mPerDisplayFocusEnabled = context.getResources().getBoolean(
com.android.internal.R.bool.config_perDisplayFocusEnabled);
- mLowRamTaskSnapshotsAndRecents = context.getResources().getBoolean(
- com.android.internal.R.bool.config_lowRamTaskSnapshotsAndRecents);
mInputManager = inputManager; // Must be before createDisplayContentLocked.
mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class);
@@ -1243,6 +1231,7 @@ public class WindowManagerService extends IWindowManager.Stub
mHighRefreshRateBlacklist = HighRefreshRateBlacklist.create(context.getResources());
+ mConstants = new WindowManagerConstants(this, DeviceConfigInterface.REAL);
mConstants.start(new HandlerExecutor(mH));
LocalServices.addService(WindowManagerInternal.class, new LocalService());
@@ -1732,7 +1721,7 @@ public class WindowManagerService extends IWindowManager.Stub
}
}
- return mAtmService.mRootActivityContainer.getActivityDisplayOrCreate(displayId);
+ return mAtmService.mRootActivityContainer.getDisplayContentOrCreate(displayId);
}
private boolean doesAddToastWindowRequireToken(String packageName, int callingUid,
@@ -3722,6 +3711,26 @@ public class WindowManagerService extends IWindowManager.Stub
}
@Override
+ public SurfaceControl addShellRoot(int displayId, IWindow client, int windowType) {
+ if (mContext.checkCallingOrSelfPermission(MANAGE_APP_TOKENS)
+ != PackageManager.PERMISSION_GRANTED) {
+ throw new SecurityException("Must hold permission " + MANAGE_APP_TOKENS);
+ }
+ final long origId = Binder.clearCallingIdentity();
+ try {
+ synchronized (mGlobalLock) {
+ final DisplayContent dc = mRoot.getDisplayContent(displayId);
+ if (dc == null) {
+ return null;
+ }
+ return dc.addShellRoot(client, windowType);
+ }
+ } finally {
+ Binder.restoreCallingIdentity(origId);
+ }
+ }
+
+ @Override
public int watchRotation(IRotationWatcher watcher, int displayId) {
final DisplayContent displayContent;
synchronized (mGlobalLock) {
@@ -4502,6 +4511,7 @@ public class WindowManagerService extends IWindowManager.Stub
public static final int ANIMATION_FAILSAFE = 60;
public static final int RECOMPUTE_FOCUS = 61;
public static final int ON_POINTER_DOWN_OUTSIDE_FOCUS = 62;
+ public static final int LAYOUT_AND_ASSIGN_WINDOW_LAYERS_IF_NEEDED = 63;
/**
* Used to denote that an integer field in a message will not be used.
@@ -4876,6 +4886,13 @@ public class WindowManagerService extends IWindowManager.Stub
}
break;
}
+ case LAYOUT_AND_ASSIGN_WINDOW_LAYERS_IF_NEEDED: {
+ synchronized (mGlobalLock) {
+ final DisplayContent displayContent = (DisplayContent) msg.obj;
+ displayContent.layoutAndAssignWindowLayersIfNeeded();
+ }
+ break;
+ }
}
if (DEBUG_WINDOW_TRACE) {
Slog.v(TAG_WM, "handleMessage: exit");
@@ -7640,7 +7657,11 @@ public class WindowManagerService extends IWindowManager.Stub
return;
}
- handleDisplayFocusChange(touchedWindow);
+ final DisplayContent displayContent = touchedWindow.getDisplayContent();
+ if (!displayContent.isOnTop()) {
+ displayContent.getParent().positionChildAt(WindowContainer.POSITION_TOP, displayContent,
+ true /* includingParents */);
+ }
handleTaskFocusChange(touchedWindow.getTask());
}
@@ -7663,29 +7684,6 @@ public class WindowManagerService extends IWindowManager.Stub
}
}
- private void handleDisplayFocusChange(WindowState window) {
- final DisplayContent displayContent = window.getDisplayContent();
- if (displayContent == null) {
- return;
- }
-
- final WindowContainer parent = displayContent.getParent();
- if (parent != null && parent.getTopChild() != displayContent) {
- parent.positionChildAt(WindowContainer.POSITION_TOP, displayContent,
- true /* includingParents */);
- // For compatibility, only the topmost activity is allowed to be resumed for pre-Q
- // app. Ensure the topmost activities are resumed whenever a display is moved to top.
- // TODO(b/123761773): Investigate whether we can move this into
- // RootActivityContainer#updateTopResumedActivityIfNeeded(). Currently, it is risky
- // to do so because it seems possible to resume activities as part of a larger
- // transaction and it's too early to resume based on current order when performing
- // updateTopResumedActivityIfNeeded().
- // TODO(display-merge): Remove cast
- ((ActivityDisplay) displayContent).ensureActivitiesVisible(null /* starting */,
- 0 /* configChanges */, !PRESERVE_WINDOWS, true /* notifyClients */);
- }
- }
-
/**
* Assigns an InputChannel to a SurfaceControl and configures it to receive
* touch input according to it's on-screen geometry.
@@ -7815,8 +7813,8 @@ public class WindowManagerService extends IWindowManager.Stub
@Override
public boolean mirrorDisplay(int displayId, SurfaceControl outSurfaceControl) {
- if (!checkCallingPermission(ACCESS_SURFACE_FLINGER, "mirrorDisplay()")) {
- throw new SecurityException("Requires ACCESS_SURFACE_FLINGER permission");
+ if (!checkCallingPermission(READ_FRAME_BUFFER, "mirrorDisplay()")) {
+ throw new SecurityException("Requires READ_FRAME_BUFFER permission");
}
final SurfaceControl displaySc;
@@ -7827,7 +7825,7 @@ public class WindowManagerService extends IWindowManager.Stub
return false;
}
- displaySc = displayContent.getSurfaceControl();
+ displaySc = displayContent.getWindowingLayer();
}
final SurfaceControl mirror = SurfaceControl.mirrorSurface(displaySc);
diff --git a/services/core/java/com/android/server/wm/WindowProcessController.java b/services/core/java/com/android/server/wm/WindowProcessController.java
index ddf8e9bb221d..1a41006b7954 100644
--- a/services/core/java/com/android/server/wm/WindowProcessController.java
+++ b/services/core/java/com/android/server/wm/WindowProcessController.java
@@ -575,14 +575,14 @@ public class WindowProcessController extends ConfigurationContainer<Configuratio
return true;
}
- final ActivityDisplay display = activity.getDisplay();
+ final DisplayContent display = activity.getDisplay();
if (display == null) {
// No need to update if the activity hasn't attach to any display.
return false;
}
boolean canUpdate = false;
- final ActivityDisplay topDisplay =
+ final DisplayContent topDisplay =
mPreQTopResumedActivity != null ? mPreQTopResumedActivity.getDisplay() : null;
// Update the topmost activity if current top activity is
// - not on any display OR
@@ -938,15 +938,15 @@ public class WindowProcessController extends ConfigurationContainer<Configuratio
mAtm.mH.sendMessage(m);
}
- void registerDisplayConfigurationListenerLocked(ActivityDisplay activityDisplay) {
- if (activityDisplay == null) {
+ void registerDisplayConfigurationListenerLocked(DisplayContent displayContent) {
+ if (displayContent == null) {
return;
}
// A process can only register to one display to listener to the override configuration
// change. Unregister existing listener if it has one before register the new one.
unregisterDisplayConfigurationListenerLocked();
- mDisplayId = activityDisplay.mDisplayId;
- activityDisplay.registerConfigurationChangeListener(this);
+ mDisplayId = displayContent.mDisplayId;
+ displayContent.registerConfigurationChangeListener(this);
}
@VisibleForTesting
@@ -954,10 +954,10 @@ public class WindowProcessController extends ConfigurationContainer<Configuratio
if (mDisplayId == INVALID_DISPLAY) {
return;
}
- final ActivityDisplay activityDisplay =
- mAtm.mRootActivityContainer.getActivityDisplay(mDisplayId);
- if (activityDisplay != null) {
- activityDisplay.unregisterConfigurationChangeListener(this);
+ final DisplayContent displayContent =
+ mAtm.mRootActivityContainer.getDisplayContent(mDisplayId);
+ if (displayContent != null) {
+ displayContent.unregisterConfigurationChangeListener(this);
}
mDisplayId = INVALID_DISPLAY;
}
diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java
index 6a1aa02a6c79..4a5c2975ab16 100644
--- a/services/core/java/com/android/server/wm/WindowState.java
+++ b/services/core/java/com/android/server/wm/WindowState.java
@@ -1239,11 +1239,6 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP
}
@Override
- public boolean getNeedsMenuLw(WindowManagerPolicy.WindowState bottom) {
- return getDisplayContent().getNeedsMenu(this, bottom);
- }
-
- @Override
public int getSystemUiVisibility() {
return mSystemUiVisibility;
}
@@ -1647,11 +1642,17 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP
&& (parentAndClientVisible || isAnimating(TRANSITION | PARENTS));
}
- // TODO: Another visibility method that was added late in the release to minimize risk.
- @Override
- public boolean canAffectSystemUiFlags() {
- final boolean translucent = mAttrs.alpha == 0.0f;
- if (translucent) {
+ boolean isFullyTransparent() {
+ return mAttrs.alpha == 0f;
+ }
+
+ /**
+ * @return Whether the window can affect SystemUI flags, meaning that SystemUI (system bars,
+ * for example) will be affected by the flags specified in this window. This is the
+ * case when the surface is on screen but not exiting.
+ */
+ boolean canAffectSystemUiFlags() {
+ if (isFullyTransparent()) {
return false;
}
if (mActivityRecord == null) {
@@ -1731,6 +1732,39 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP
&& isDrawnLw() && !isAnimating(TRANSITION | PARENTS);
}
+ /** @see WindowManagerInternal#waitForAllWindowsDrawn */
+ void requestDrawIfNeeded(List<WindowState> outWaitingForDrawn) {
+ if (!isVisible()) {
+ return;
+ }
+ if (mActivityRecord != null) {
+ if (mActivityRecord.allDrawn) {
+ // The allDrawn of activity is reset when the visibility is changed to visible, so
+ // the content should be ready if allDrawn is set.
+ return;
+ }
+ if (mAttrs.type == TYPE_APPLICATION_STARTING) {
+ if (isDrawnLw()) {
+ // Unnecessary to redraw a drawn starting window.
+ return;
+ }
+ } else if (mActivityRecord.startingWindow != null) {
+ // If the activity has an active starting window, there is no need to wait for the
+ // main window.
+ return;
+ }
+ } else if (!mPolicy.isKeyguardHostWindow(mAttrs)) {
+ return;
+ // Always invalidate keyguard host window to make sure it shows the latest content
+ // because its visibility may not be changed.
+ }
+
+ mWinAnimator.mDrawState = DRAW_PENDING;
+ // Force add to {@link WindowManagerService#mResizingWindows}.
+ resetLastContentInsets();
+ outWaitingForDrawn.add(this);
+ }
+
@Override
void onMovedByResize() {
ProtoLog.d(WM_DEBUG_RESIZE, "onMovedByResize: Moving %s", this);
@@ -1738,28 +1772,22 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP
super.onMovedByResize();
}
- boolean onAppVisibilityChanged(boolean visible, boolean runningAppAnimation) {
- boolean changed = false;
-
+ void onAppVisibilityChanged(boolean visible, boolean runningAppAnimation) {
for (int i = mChildren.size() - 1; i >= 0; --i) {
- final WindowState c = mChildren.get(i);
- changed |= c.onAppVisibilityChanged(visible, runningAppAnimation);
+ mChildren.get(i).onAppVisibilityChanged(visible, runningAppAnimation);
}
+ final boolean isVisibleNow = isVisibleNow();
if (mAttrs.type == TYPE_APPLICATION_STARTING) {
// Starting window that's exiting will be removed when the animation finishes.
// Mark all relevant flags for that onExitAnimationDone will proceed all the way
// to actually remove it.
- if (!visible && isVisibleNow() && mActivityRecord.isAnimating(TRANSITION)) {
+ if (!visible && isVisibleNow && mActivityRecord.isAnimating(TRANSITION)) {
mAnimatingExit = true;
mRemoveOnExit = true;
mWindowRemovalAllowed = true;
}
- return changed;
- }
-
- final boolean isVisibleNow = isVisibleNow();
- if (visible != isVisibleNow) {
+ } else if (visible != isVisibleNow) {
// Run exit animation if:
// 1. App visibility and WS visibility are different
// 2. App is not running an animation
@@ -1773,11 +1801,8 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP
accessibilityController.onWindowTransitionLocked(this, winTransit);
}
}
- changed = true;
setDisplayLayoutNeeded();
}
-
- return changed;
}
boolean onSetAppExiting() {
@@ -2163,13 +2188,27 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP
return false;
}
- final int fl = mAttrs.flags & (FLAG_NOT_FOCUSABLE | FLAG_ALT_FOCUSABLE_IM);
- final int type = mAttrs.type;
+ if (PixelFormat.formatHasAlpha(mAttrs.format)) {
+ // Support legacy use cases where transparent windows can still be ime target with
+ // FLAG_NOT_FOCUSABLE and ALT_FOCUSABLE_IM set.
+ // Certain apps listen for IME insets using transparent windows and ADJUST_NOTHING to
+ // manually synchronize app content to IME animation b/144619551.
+ // TODO(b/145812508): remove this once new focus management is complete b/141738570
+ final int fl = mAttrs.flags & (FLAG_NOT_FOCUSABLE | FLAG_ALT_FOCUSABLE_IM);
+ final int type = mAttrs.type;
- // Can only be an IME target if both FLAG_NOT_FOCUSABLE and FLAG_ALT_FOCUSABLE_IM are set or
- // both are cleared...and not a starting window.
- if (fl != 0 && fl != (FLAG_NOT_FOCUSABLE | FLAG_ALT_FOCUSABLE_IM)
- && type != TYPE_APPLICATION_STARTING) {
+ // Can only be an IME target if both FLAG_NOT_FOCUSABLE and FLAG_ALT_FOCUSABLE_IM are
+ // set or both are cleared...and not a starting window.
+ if (fl != 0 && fl != (FLAG_NOT_FOCUSABLE | FLAG_ALT_FOCUSABLE_IM)
+ && type != TYPE_APPLICATION_STARTING) {
+ return false;
+ }
+ } else if (!WindowManager.LayoutParams.mayUseInputMethod(mAttrs.flags)
+ || mAttrs.type == TYPE_APPLICATION_STARTING) {
+ // Can be an IME target only if:
+ // 1. FLAG_NOT_FOCUSABLE is not set
+ // 2. FLAG_ALT_FOCUSABLE_IM is not set
+ // 3. not a starting window.
return false;
}
@@ -2625,7 +2664,7 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP
final boolean canReceiveKeys = isVisibleOrAdding()
&& (mViewVisibility == View.VISIBLE) && !mRemoveOnExit
&& ((mAttrs.flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) == 0)
- && (mActivityRecord == null || mActivityRecord.windowsAreFocusable())
+ && (mActivityRecord == null || mActivityRecord.windowsAreFocusable(fromUserTouch))
&& !cantReceiveTouchInput();
if (!canReceiveKeys) {
return false;
diff --git a/services/core/jni/Android.bp b/services/core/jni/Android.bp
index fd8094cc43dd..a34b7fdb911c 100644
--- a/services/core/jni/Android.bp
+++ b/services/core/jni/Android.bp
@@ -35,6 +35,7 @@ cc_library_static {
"com_android_server_power_PowerManagerService.cpp",
"com_android_server_security_VerityUtils.cpp",
"com_android_server_SerialService.cpp",
+ "com_android_server_soundtrigger_middleware_AudioSessionProviderImpl.cpp",
"com_android_server_storage_AppFuseBridge.cpp",
"com_android_server_SystemServer.cpp",
"com_android_server_TestNetworkService.cpp",
diff --git a/services/core/jni/com_android_server_VibratorService.cpp b/services/core/jni/com_android_server_VibratorService.cpp
index dcff5a11aca0..6811e6d0e6f2 100644
--- a/services/core/jni/com_android_server_VibratorService.cpp
+++ b/services/core/jni/com_android_server_VibratorService.cpp
@@ -410,6 +410,21 @@ static jlong vibratorGetCapabilities(JNIEnv*, jclass) {
return 0;
}
+static void vibratorAlwaysOnEnable(JNIEnv* env, jclass, jlong id, jlong effect, jlong strength) {
+ auto status = halCall(&aidl::IVibrator::alwaysOnEnable, id,
+ static_cast<aidl::Effect>(effect), static_cast<aidl::EffectStrength>(strength));
+ if (!status.isOk()) {
+ ALOGE("vibratortAlwaysOnEnable command failed (%s).", status.toString8().string());
+ }
+}
+
+static void vibratorAlwaysOnDisable(JNIEnv* env, jclass, jlong id) {
+ auto status = halCall(&aidl::IVibrator::alwaysOnDisable, id);
+ if (!status.isOk()) {
+ ALOGE("vibratorAlwaysOnDisable command failed (%s).", status.toString8().string());
+ }
+}
+
static const JNINativeMethod method_table[] = {
{ "vibratorExists", "()Z", (void*)vibratorExists },
{ "vibratorInit", "()V", (void*)vibratorInit },
@@ -422,6 +437,8 @@ static const JNINativeMethod method_table[] = {
{ "vibratorSupportsExternalControl", "()Z", (void*)vibratorSupportsExternalControl},
{ "vibratorSetExternalControl", "(Z)V", (void*)vibratorSetExternalControl},
{ "vibratorGetCapabilities", "()J", (void*)vibratorGetCapabilities},
+ { "vibratorAlwaysOnEnable", "(JJJ)V", (void*)vibratorAlwaysOnEnable},
+ { "vibratorAlwaysOnDisable", "(J)V", (void*)vibratorAlwaysOnDisable},
};
int register_android_server_VibratorService(JNIEnv *env)
diff --git a/services/core/jni/com_android_server_input_InputManagerService.cpp b/services/core/jni/com_android_server_input_InputManagerService.cpp
index 9344a9b7c849..2e8e5e7b706a 100644
--- a/services/core/jni/com_android_server_input_InputManagerService.cpp
+++ b/services/core/jni/com_android_server_input_InputManagerService.cpp
@@ -485,8 +485,8 @@ void NativeInputManager::getReaderConfiguration(InputReaderConfiguration* outCon
// Received data: ['inputPort1', '1', 'inputPort2', '2']
// So we unpack accordingly here.
outConfig->portAssociations.clear();
- jobjectArray portAssociations = jobjectArray(env->CallStaticObjectMethod(
- gServiceClassInfo.clazz, gServiceClassInfo.getInputPortAssociations));
+ jobjectArray portAssociations = jobjectArray(env->CallObjectMethod(mServiceObj,
+ gServiceClassInfo.getInputPortAssociations));
if (!checkAndClearExceptionFromCallback(env, "getInputPortAssociations") && portAssociations) {
jsize length = env->GetArrayLength(portAssociations);
for (jsize i = 0; i < length / 2; i++) {
@@ -1920,7 +1920,7 @@ int register_android_server_InputManager(JNIEnv* env) {
GET_STATIC_METHOD_ID(gServiceClassInfo.getExcludedDeviceNames, clazz,
"getExcludedDeviceNames", "()[Ljava/lang/String;");
- GET_STATIC_METHOD_ID(gServiceClassInfo.getInputPortAssociations, clazz,
+ GET_METHOD_ID(gServiceClassInfo.getInputPortAssociations, clazz,
"getInputPortAssociations", "()[Ljava/lang/String;");
GET_METHOD_ID(gServiceClassInfo.getKeyRepeatTimeout, clazz,
diff --git a/services/core/jni/com_android_server_security_VerityUtils.cpp b/services/core/jni/com_android_server_security_VerityUtils.cpp
index 906b5688d51f..be11b8620bda 100644
--- a/services/core/jni/com_android_server_security_VerityUtils.cpp
+++ b/services/core/jni/com_android_server_security_VerityUtils.cpp
@@ -24,6 +24,7 @@
#include <errno.h>
#include <fcntl.h>
+#include <linux/fsverity.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
@@ -33,40 +34,6 @@
#include <android-base/unique_fd.h>
-// TODO(112037636): Always include once fsverity.h is upstreamed.
-#if __has_include(<linux/fsverity.h>)
-#include <linux/fsverity.h>
-#else
-
-#include <linux/limits.h>
-#include <linux/ioctl.h>
-#include <linux/types.h>
-
-#define FS_VERITY_HASH_ALG_SHA256 1
-
-struct fsverity_enable_arg {
- __u32 version;
- __u32 hash_algorithm;
- __u32 block_size;
- __u32 salt_size;
- __u64 salt_ptr;
- __u32 sig_size;
- __u32 __reserved1;
- __u64 sig_ptr;
- __u64 __reserved2[11];
-};
-
-struct fsverity_digest {
- __u16 digest_algorithm;
- __u16 digest_size; /* input/output */
- __u8 digest[];
-};
-
-#define FS_IOC_ENABLE_VERITY _IOW('f', 133, struct fsverity_enable_arg)
-#define FS_IOC_MEASURE_VERITY _IOWR('f', 134, struct fsverity_digest)
-
-#endif
-
const int kSha256Bytes = 32;
namespace android {
diff --git a/services/core/jni/com_android_server_soundtrigger_middleware_AudioSessionProviderImpl.cpp b/services/core/jni/com_android_server_soundtrigger_middleware_AudioSessionProviderImpl.cpp
new file mode 100644
index 000000000000..774534f23b8c
--- /dev/null
+++ b/services/core/jni/com_android_server_soundtrigger_middleware_AudioSessionProviderImpl.cpp
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#include <sstream>
+
+#include "core_jni_helpers.h"
+#include <media/AudioSystem.h>
+
+namespace android {
+
+namespace {
+
+#define PACKAGE "com/android/server/soundtrigger_middleware"
+#define CLASSNAME PACKAGE "/AudioSessionProviderImpl"
+#define SESSION_CLASSNAME PACKAGE "/SoundTriggerMiddlewareImpl$AudioSessionProvider$AudioSession"
+
+jobject acquireAudioSession(
+ JNIEnv* env,
+ jobject clazz) {
+
+ audio_session_t session;
+ audio_io_handle_t ioHandle;
+ audio_devices_t device;
+
+ status_t status = AudioSystem::acquireSoundTriggerSession(&session,
+ &ioHandle,
+ &device);
+ if (status != 0) {
+ std::ostringstream message;
+ message
+ << "AudioSystem::acquireSoundTriggerSession returned an error code: "
+ << status;
+ env->ThrowNew(FindClassOrDie(env, "java/lang/RuntimeException"),
+ message.str().c_str());
+ return nullptr;
+ }
+
+ jclass cls = FindClassOrDie(env, SESSION_CLASSNAME);
+ jmethodID ctor = GetMethodIDOrDie(env, cls, "<init>", "(III)V");
+ return env->NewObject(cls,
+ ctor,
+ static_cast<int>(session),
+ static_cast<int>(ioHandle),
+ static_cast<int>(device));
+}
+
+void releaseAudioSession(JNIEnv* env, jobject clazz, jint handle) {
+ status_t status =
+ AudioSystem::releaseSoundTriggerSession(static_cast<audio_session_t>(handle));
+
+ if (status != 0) {
+ std::ostringstream message;
+ message
+ << "AudioSystem::releaseAudioSystemSession returned an error code: "
+ << status;
+ env->ThrowNew(FindClassOrDie(env, "java/lang/RuntimeException"),
+ message.str().c_str());
+ }
+}
+
+const JNINativeMethod g_methods[] = {
+ {"acquireSession", "()L" SESSION_CLASSNAME ";",
+ reinterpret_cast<void*>(acquireAudioSession)},
+ {"releaseSession", "(I)V",
+ reinterpret_cast<void*>(releaseAudioSession)},
+};
+
+} // namespace
+
+int register_com_android_server_soundtrigger_middleware_AudioSessionProviderImpl(
+ JNIEnv* env) {
+ return RegisterMethodsOrDie(env,
+ CLASSNAME,
+ g_methods,
+ NELEM(g_methods));
+}
+
+} // namespace android
diff --git a/services/core/jni/onload.cpp b/services/core/jni/onload.cpp
index 692c9d25baa9..165edf15ca23 100644
--- a/services/core/jni/onload.cpp
+++ b/services/core/jni/onload.cpp
@@ -56,6 +56,8 @@ int register_android_server_net_NetworkStatsService(JNIEnv* env);
int register_android_server_security_VerityUtils(JNIEnv* env);
int register_android_server_am_AppCompactor(JNIEnv* env);
int register_android_server_am_LowMemDetector(JNIEnv* env);
+int register_com_android_server_soundtrigger_middleware_AudioSessionProviderImpl(
+ JNIEnv* env);
};
using namespace android;
@@ -105,5 +107,7 @@ extern "C" jint JNI_OnLoad(JavaVM* vm, void* /* reserved */)
register_android_server_security_VerityUtils(env);
register_android_server_am_AppCompactor(env);
register_android_server_am_LowMemDetector(env);
+ register_com_android_server_soundtrigger_middleware_AudioSessionProviderImpl(
+ env);
return JNI_VERSION_1_4;
}
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index ee0449d95e00..94338c8f34e4 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -430,6 +430,8 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
private static final Set<String> SYSTEM_SETTINGS_WHITELIST;
private static final Set<Integer> DA_DISALLOWED_POLICIES;
+ // A collection of user restrictions that are deprecated and should simply be ignored.
+ private static final Set<String> DEPRECATED_USER_RESTRICTIONS;
private static final String AB_DEVICE_KEY = "ro.build.ab_update";
static {
@@ -471,6 +473,10 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD);
DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
+
+ DEPRECATED_USER_RESTRICTIONS = Sets.newHashSet(
+ UserManager.DISALLOW_ADD_MANAGED_PROFILE,
+ UserManager.DISALLOW_REMOVE_MANAGED_PROFILE);
}
/**
@@ -990,6 +996,7 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
"cross-profile-calendar-packages";
private static final String TAG_CROSS_PROFILE_CALENDAR_PACKAGES_NULL =
"cross-profile-calendar-packages-null";
+ private static final String TAG_CROSS_PROFILE_PACKAGES = "cross-profile-packages";
DeviceAdminInfo info;
@@ -1104,6 +1111,11 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
// is whitelisted.
List<String> mCrossProfileCalendarPackages = Collections.emptyList();
+ // The whitelist of packages that the admin has enabled to be able to request consent from
+ // the user to communicate cross-profile. By default, no packages are whitelisted, which is
+ // represented as an empty list.
+ List<String> mCrossProfilePackages = Collections.emptyList();
+
ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
info = _info;
isParent = parent;
@@ -1329,6 +1341,7 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
writePackageListToXml(out, TAG_CROSS_PROFILE_CALENDAR_PACKAGES,
mCrossProfileCalendarPackages);
}
+ writePackageListToXml(out, TAG_CROSS_PROFILE_PACKAGES, mCrossProfilePackages);
}
void writeTextToXml(XmlSerializer out, String tag, String text) throws IOException {
@@ -1560,6 +1573,8 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
mCrossProfileCalendarPackages = readPackageList(parser, tag);
} else if (TAG_CROSS_PROFILE_CALENDAR_PACKAGES_NULL.equals(tag)) {
mCrossProfileCalendarPackages = null;
+ } else if (TAG_CROSS_PROFILE_PACKAGES.equals(tag)) {
+ mCrossProfilePackages = readPackageList(parser, tag);
} else {
Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
XmlUtils.skipCurrentTag(parser);
@@ -1783,6 +1798,8 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
pw.print("mCrossProfileCalendarPackages=");
pw.println(mCrossProfileCalendarPackages);
}
+ pw.print("mCrossProfilePackages=");
+ pw.println(mCrossProfilePackages);
}
}
@@ -2389,7 +2406,6 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
setDeviceOwnerSystemPropertyLocked();
findOwnerComponentIfNecessaryLocked();
migrateUserRestrictionsIfNecessaryLocked();
- maybeSetDefaultDeviceOwnerUserRestrictionsLocked();
// TODO PO may not have a class name either due to b/17652534. Address that too.
@@ -2397,15 +2413,6 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
}
}
- /** Apply default restrictions that haven't been applied to device owners yet. */
- private void maybeSetDefaultDeviceOwnerUserRestrictionsLocked() {
- final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
- if (deviceOwner != null) {
- maybeSetDefaultRestrictionsForAdminLocked(mOwners.getDeviceOwnerUserId(),
- deviceOwner, UserRestrictionsUtils.getDefaultEnabledForDeviceOwner());
- }
- }
-
/** Apply default restrictions that haven't been applied to profile owners yet. */
private void maybeSetDefaultProfileOwnerUserRestrictions() {
synchronized (getLockObject()) {
@@ -2436,7 +2443,7 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId) != 0) {
profileOwner.ensureUserRestrictions().putBoolean(
UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
- saveUserRestrictionsLocked(userId);
+ saveUserRestrictionsLocked(userId, /* parent = */ false);
mInjector.settingsSecurePutIntForUser(
Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId);
}
@@ -2467,7 +2474,7 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
}
admin.defaultEnabledRestrictionsAlreadySet.addAll(restrictionsToSet);
Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictionsToSet);
- saveUserRestrictionsLocked(userId);
+ saveUserRestrictionsLocked(userId, /* parent = */ false);
}
}
@@ -7429,7 +7436,7 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
}
/**
- * Returns whether or auto time is used on the device or not.
+ * Returns whether auto time is used on the device or not.
*/
@Override
public boolean getAutoTime(ComponentName who) {
@@ -7442,6 +7449,42 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
return mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) > 0;
}
+ /**
+ * Set whether auto time zone is enabled on the device.
+ */
+ @Override
+ public void setAutoTimeZone(ComponentName who, boolean enabled) {
+ if (!mHasFeature) {
+ return;
+ }
+ Preconditions.checkNotNull(who, "ComponentName is null");
+ // TODO (b/145286957) Refactor security checks
+ enforceDeviceOwnerOrProfileOwnerOnUser0OrProfileOwnerOrganizationOwned();
+
+ mInjector.binderWithCleanCallingIdentity(() ->
+ mInjector.settingsGlobalPutInt(Global.AUTO_TIME_ZONE, enabled ? 1 : 0));
+
+ DevicePolicyEventLogger
+ .createEvent(DevicePolicyEnums.SET_AUTO_TIME_ZONE)
+ .setAdmin(who)
+ .setBoolean(enabled)
+ .write();
+ }
+
+ /**
+ * Returns whether auto time zone is used on the device or not.
+ */
+ @Override
+ public boolean getAutoTimeZone(ComponentName who) {
+ if (!mHasFeature) {
+ return false;
+ }
+ Preconditions.checkNotNull(who, "ComponentName is null");
+ enforceDeviceOwnerOrProfileOwnerOnUser0OrProfileOwnerOrganizationOwned();
+
+ return mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) > 0;
+ }
+
@Override
public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
if (!mHasFeature) {
@@ -7983,18 +8026,6 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
updateDeviceOwnerLocked();
setDeviceOwnerSystemPropertyLocked();
- final Set<String> restrictions =
- UserRestrictionsUtils.getDefaultEnabledForDeviceOwner();
- if (!restrictions.isEmpty()) {
- for (String restriction : restrictions) {
- activeAdmin.ensureUserRestrictions().putBoolean(restriction, true);
- }
- activeAdmin.defaultEnabledRestrictionsAlreadySet.addAll(restrictions);
- Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictions);
-
- saveUserRestrictionsLocked(userId);
- }
-
long ident = mInjector.binderClearCallingIdentity();
try {
// TODO Send to system too?
@@ -10263,24 +10294,33 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
}
@Override
- public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
+ public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner,
+ boolean parent) {
Preconditions.checkNotNull(who, "ComponentName is null");
if (!UserRestrictionsUtils.isValidRestriction(key)) {
return;
}
- final int userHandle = mInjector.userHandleGetCallingUserId();
+ int userHandle = mInjector.userHandleGetCallingUserId();
synchronized (getLockObject()) {
final ActiveAdmin activeAdmin =
getActiveAdminForCallerLocked(who,
- DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
+ DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
+
if (isDeviceOwner) {
if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
throw new SecurityException("Device owner cannot set user restriction " + key);
}
- } else { // profile owner
- if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
+ if (parent) {
+ throw new IllegalArgumentException(
+ "Cannot use the parent instance in Device Owner mode");
+ }
+ } else {
+ if (!(UserRestrictionsUtils.canProfileOwnerChange(key, userHandle) || (
+ isProfileOwnerOfOrganizationOwnedDevice(activeAdmin) && parent
+ && UserRestrictionsUtils.canProfileOwnerOfOrganizationOwnedDeviceChange(
+ key)))) {
throw new SecurityException("Profile owner cannot set user restriction " + key);
}
}
@@ -10292,7 +10332,7 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
} else {
restrictions.remove(key);
}
- saveUserRestrictionsLocked(userHandle);
+ saveUserRestrictionsLocked(userHandle, parent);
}
final int eventId = enabledFromThisOwner
? DevicePolicyEnums.ADD_USER_RESTRICTION
@@ -10310,9 +10350,9 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
}
}
- private void saveUserRestrictionsLocked(int userId) {
+ private void saveUserRestrictionsLocked(int userId, boolean parent) {
saveSettingsLocked(userId);
- pushUserRestrictions(userId);
+ pushUserRestrictions(parent ? getProfileParentId(userId) : userId);
sendChangedNotification(userId);
}
@@ -10321,15 +10361,17 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
final boolean isDeviceOwner = mOwners.isDeviceOwnerUserId(userId);
Bundle userRestrictions = null;
final int restrictionOwnerType;
+ final int originatingUserId;
if (isDeviceOwner) {
final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
if (deviceOwner == null) {
return; // Shouldn't happen.
}
- userRestrictions = deviceOwner.userRestrictions;
- addOrRemoveDisableCameraRestriction(userRestrictions, deviceOwner);
+ userRestrictions = addOrRemoveDisableCameraRestriction(
+ deviceOwner.userRestrictions, deviceOwner);
restrictionOwnerType = UserManagerInternal.OWNER_TYPE_DEVICE_OWNER;
+ originatingUserId = deviceOwner.getUserHandle().getIdentifier();
} else {
final ActiveAdmin profileOwnerOfOrganizationOwnedDevice =
getProfileOwnerOfOrganizationOwnedDeviceLocked(userId);
@@ -10344,21 +10386,29 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
userRestrictions = parent.userRestrictions;
userRestrictions = addOrRemoveDisableCameraRestriction(userRestrictions,
parent);
+ originatingUserId =
+ profileOwnerOfOrganizationOwnedDevice.getUserHandle().getIdentifier();
} else {
final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
if (profileOwner != null) {
userRestrictions = profileOwner.userRestrictions;
restrictionOwnerType = UserManagerInternal.OWNER_TYPE_PROFILE_OWNER;
+ originatingUserId = profileOwner.getUserHandle().getIdentifier();
} else {
restrictionOwnerType = UserManagerInternal.OWNER_TYPE_NO_OWNER;
+ originatingUserId = userId;
}
userRestrictions = addOrRemoveDisableCameraRestriction(
userRestrictions, userId);
}
}
- mUserManagerInternal.setDevicePolicyUserRestrictions(userId, userRestrictions,
- restrictionOwnerType);
+ // Remove deprecated restrictions.
+ for (String deprecatedRestriction: DEPRECATED_USER_RESTRICTIONS) {
+ userRestrictions.remove(deprecatedRestriction);
+ }
+ mUserManagerInternal.setDevicePolicyUserRestrictions(originatingUserId,
+ userRestrictions, restrictionOwnerType);
}
}
@@ -10388,14 +10438,18 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
}
@Override
- public Bundle getUserRestrictions(ComponentName who) {
+ public Bundle getUserRestrictions(ComponentName who, boolean parent) {
if (!mHasFeature) {
return null;
}
Preconditions.checkNotNull(who, "ComponentName is null");
+
synchronized (getLockObject()) {
final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
- DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
+ DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
+ if (parent) {
+ enforceProfileOwnerOfOrganizationOwnedDevice(activeAdmin);
+ }
return activeAdmin.userRestrictions;
}
}
@@ -11194,7 +11248,7 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
} else {
try {
setUserRestriction(who, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
- (Integer.parseInt(value) == 0) ? true : false);
+ (Integer.parseInt(value) == 0) ? true : false, /* parent */ false);
DevicePolicyEventLogger
.createEvent(DevicePolicyEnums.SET_SECURE_SETTING)
.setAdmin(who)
@@ -11239,7 +11293,7 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
Preconditions.checkNotNull(who, "ComponentName is null");
synchronized (getLockObject()) {
getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
- setUserRestriction(who, UserManager.DISALLOW_UNMUTE_DEVICE, on);
+ setUserRestriction(who, UserManager.DISALLOW_UNMUTE_DEVICE, on, /* parent */ false);
DevicePolicyEventLogger
.createEvent(DevicePolicyEnums.SET_MASTER_VOLUME_MUTED)
.setAdmin(who)
@@ -13726,8 +13780,9 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
} else {
deviceOwner.lastNetworkLoggingNotificationTimeMs = now;
}
+ final PackageManagerInternal pm = mInjector.getPackageManagerInternal();
final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
- intent.setPackage("com.android.systemui");
+ intent.setPackage(pm.getSystemUiServiceComponent().getPackageName());
final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0,
UserHandle.CURRENT);
Notification notification =
@@ -14645,6 +14700,35 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
}
@Override
+ public void setCrossProfilePackages(ComponentName who, List<String> packageNames) {
+ if (!mHasFeature) {
+ return;
+ }
+ Preconditions.checkNotNull(who, "ComponentName is null");
+ Preconditions.checkNotNull(packageNames, "Package names is null");
+ synchronized (getLockObject()) {
+ final ActiveAdmin admin =
+ getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
+ admin.mCrossProfilePackages = packageNames;
+ saveSettingsLocked(mInjector.userHandleGetCallingUserId());
+ }
+ }
+
+ @Override
+ public List<String> getCrossProfilePackages(ComponentName who) {
+ if (!mHasFeature) {
+ return Collections.emptyList();
+ }
+ Preconditions.checkNotNull(who, "ComponentName is null");
+
+ synchronized (getLockObject()) {
+ final ActiveAdmin admin = getActiveAdminForCallerLocked(
+ who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
+ return admin.mCrossProfilePackages;
+ }
+ }
+
+ @Override
public boolean isManagedKiosk() {
if (!mHasFeature) {
return false;
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 21cacd45dcb5..f05bbe215b78 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -30,12 +30,12 @@ import android.app.ActivityThread;
import android.app.AppCompatCallbacks;
import android.app.INotificationManager;
import android.app.usage.UsageStatsManagerInternal;
-import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageItemInfo;
import android.content.pm.PackageManager;
+import android.content.pm.PackageManagerInternal;
import android.content.res.Configuration;
import android.content.res.Resources.Theme;
import android.database.sqlite.SQLiteCompatibilityWalFlags;
@@ -105,10 +105,12 @@ import com.android.server.emergency.EmergencyAffordanceService;
import com.android.server.gpu.GpuService;
import com.android.server.hdmi.HdmiControlService;
import com.android.server.incident.IncidentCompanionService;
+import com.android.server.incremental.IncrementalManagerService;
import com.android.server.input.InputManagerService;
import com.android.server.inputmethod.InputMethodManagerService;
import com.android.server.inputmethod.InputMethodSystemProperty;
import com.android.server.inputmethod.MultiClientInputMethodManagerService;
+import com.android.server.integrity.AppIntegrityManagerService;
import com.android.server.lights.LightsService;
import com.android.server.media.MediaResourceMonitorService;
import com.android.server.media.MediaRouterService;
@@ -125,6 +127,7 @@ import com.android.server.os.DeviceIdentifiersPolicyService;
import com.android.server.os.SchedulingPolicyService;
import com.android.server.pm.BackgroundDexOptService;
import com.android.server.pm.CrossProfileAppsService;
+import com.android.server.pm.DataLoaderManagerService;
import com.android.server.pm.DynamicCodeLoggingService;
import com.android.server.pm.Installer;
import com.android.server.pm.LauncherAppsService;
@@ -146,6 +149,7 @@ import com.android.server.security.KeyAttestationApplicationIdProviderService;
import com.android.server.security.KeyChainSystemService;
import com.android.server.signedconfig.SignedConfigService;
import com.android.server.soundtrigger.SoundTriggerService;
+import com.android.server.soundtrigger_middleware.SoundTriggerMiddlewareService;
import com.android.server.statusbar.StatusBarManagerService;
import com.android.server.storage.DeviceStorageMonitorService;
import com.android.server.telecom.TelecomLoaderService;
@@ -206,8 +210,8 @@ public final class SystemServer {
"com.android.server.print.PrintManagerService";
private static final String COMPANION_DEVICE_MANAGER_SERVICE_CLASS =
"com.android.server.companion.CompanionDeviceManagerService";
- private static final String STATS_COMPANION_SERVICE_LIFECYCLE_CLASS =
- "com.android.server.stats.StatsCompanionService$Lifecycle";
+ private static final String STATS_COMPANION_LIFECYCLE_CLASS =
+ "com.android.server.stats.StatsCompanion$Lifecycle";
private static final String USB_SERVICE_CLASS =
"com.android.server.usb.UsbService$Lifecycle";
private static final String MIDI_SERVICE_CLASS =
@@ -320,6 +324,8 @@ public final class SystemServer {
private PackageManager mPackageManager;
private ContentResolver mContentResolver;
private EntropyMixer mEntropyMixer;
+ private DataLoaderManagerService mDataLoaderManagerService;
+ private IncrementalManagerService mIncrementalManagerService;
private boolean mOnlyCore;
private boolean mFirstBoot;
@@ -492,6 +498,9 @@ public final class SystemServer {
// Initialize the system context.
createSystemContext();
+ // Call per-process mainline module initialization.
+ ActivityThread.initializeMainlineModules();
+
// Create the system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
@@ -693,6 +702,17 @@ public final class SystemServer {
mWindowManagerGlobalLock = atm.getGlobalLock();
t.traceEnd();
+ // Data loader manager service needs to be started before package manager
+ t.traceBegin("StartDataLoaderManagerService");
+ mDataLoaderManagerService = mSystemServiceManager.startService(
+ DataLoaderManagerService.class);
+ t.traceEnd();
+
+ // Incremental service needs to be started before package manager
+ t.traceBegin("StartIncrementalManagerService");
+ mIncrementalManagerService = IncrementalManagerService.start(mSystemContext);
+ t.traceEnd();
+
// Power manager needs to be started early because other services need it.
// Native daemons may be watching for it to be registered so it must be ready
// to handle incoming binder calls immediately (including being able to verify
@@ -1129,6 +1149,10 @@ public final class SystemServer {
SignedConfigService.registerUpdateReceiver(mSystemContext);
t.traceEnd();
+ t.traceBegin("AppIntegrityService");
+ mSystemServiceManager.startService(AppIntegrityManagerService.class);
+ t.traceEnd();
+
} catch (Throwable e) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting core service");
@@ -1539,6 +1563,10 @@ public final class SystemServer {
}
t.traceEnd();
+ t.traceBegin("StartSoundTriggerMiddlewareService");
+ mSystemServiceManager.startService(SoundTriggerMiddlewareService.Lifecycle.class);
+ t.traceEnd();
+
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BROADCAST_RADIO)) {
t.traceBegin("StartBroadcastRadioService");
mSystemServiceManager.startService(BroadcastRadioService.class);
@@ -1934,8 +1962,8 @@ public final class SystemServer {
}
// Statsd helper
- t.traceBegin("StartStatsCompanionService");
- mSystemServiceManager.startService(STATS_COMPANION_SERVICE_LIFECYCLE_CLASS);
+ t.traceBegin("StartStatsCompanion");
+ mSystemServiceManager.startService(STATS_COMPANION_LIFECYCLE_CLASS);
t.traceEnd();
// Incidentd and dumpstated helper
@@ -2045,6 +2073,12 @@ public final class SystemServer {
mPackageManagerService.systemReady();
t.traceEnd();
+ if (mIncrementalManagerService != null) {
+ t.traceBegin("MakeIncrementalManagerServiceReady");
+ mIncrementalManagerService.systemReady();
+ t.traceEnd();
+ }
+
t.traceBegin("MakeDisplayManagerServiceReady");
try {
// TODO: use boot phase and communicate these flags some other way
@@ -2379,9 +2413,9 @@ public final class SystemServer {
}
private static void startSystemUi(Context context, WindowManagerService windowManager) {
+ PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
Intent intent = new Intent();
- intent.setComponent(new ComponentName("com.android.systemui",
- "com.android.systemui.SystemUIService"));
+ intent.setComponent(pm.getSystemUiServiceComponent());
intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
//Slog.d(TAG, "Starting service: " + intent);
context.startServiceAsUser(intent, UserHandle.SYSTEM);
diff --git a/services/net/java/android/net/NetworkMonitorManager.java b/services/net/java/android/net/NetworkMonitorManager.java
index 0f41302c0b15..0f669817f52e 100644
--- a/services/net/java/android/net/NetworkMonitorManager.java
+++ b/services/net/java/android/net/NetworkMonitorManager.java
@@ -16,6 +16,7 @@
package android.net;
+import android.annotation.Hide;
import android.annotation.NonNull;
import android.os.Binder;
import android.os.RemoteException;
@@ -33,6 +34,7 @@ import android.util.Log;
* wrapper methods in this class return a boolean that callers can use to determine whether
* RemoteException was thrown.
*/
+@Hide
public class NetworkMonitorManager {
@NonNull private final INetworkMonitor mNetworkMonitor;
diff --git a/services/net/java/android/net/TcpKeepalivePacketData.java b/services/net/java/android/net/TcpKeepalivePacketData.java
index 7f2f499ab21f..aad75ae16aa9 100644
--- a/services/net/java/android/net/TcpKeepalivePacketData.java
+++ b/services/net/java/android/net/TcpKeepalivePacketData.java
@@ -19,7 +19,6 @@ import static android.net.SocketKeepalive.ERROR_INVALID_IP_ADDRESS;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.net.SocketKeepalive.InvalidPacketException;
import android.net.util.IpUtils;
import android.os.Parcel;
import android.os.Parcelable;
diff --git a/services/net/java/android/net/ip/IpClientManager.java b/services/net/java/android/net/ip/IpClientManager.java
index 4b7ed3c7b72f..09e333ee3471 100644
--- a/services/net/java/android/net/ip/IpClientManager.java
+++ b/services/net/java/android/net/ip/IpClientManager.java
@@ -16,6 +16,7 @@
package android.net.ip;
+import android.annotation.Hide;
import android.annotation.NonNull;
import android.net.NattKeepalivePacketData;
import android.net.ProxyInfo;
@@ -38,6 +39,7 @@ import android.util.Log;
* wrapper methods in this class return a boolean that callers can use to determine whether
* RemoteException was thrown.
*/
+@Hide
public class IpClientManager {
@NonNull private final IIpClient mIpClient;
@NonNull private final String mTag;
diff --git a/services/tests/mockingservicestests/src/com/android/server/am/MockingOomAdjusterTests.java b/services/tests/mockingservicestests/src/com/android/server/am/MockingOomAdjusterTests.java
index 8e6114aaeffe..4635c08b36c2 100644
--- a/services/tests/mockingservicestests/src/com/android/server/am/MockingOomAdjusterTests.java
+++ b/services/tests/mockingservicestests/src/com/android/server/am/MockingOomAdjusterTests.java
@@ -142,7 +142,7 @@ public class MockingOomAdjusterTests {
sService.mConstants = new ActivityManagerConstants(sContext, sService,
sContext.getMainThreadHandler());
ProcessList pr = new ProcessList();
- pr.init(sService, new ActiveUids(sService, false));
+ pr.init(sService, new ActiveUids(sService, false), null);
setFieldValue(ActivityManagerService.class, sService, "mProcessList",
pr);
setFieldValue(ActivityManagerService.class, sService, "mHandler",
diff --git a/services/tests/mockingservicestests/src/com/android/server/display/LocalDisplayAdapterTest.java b/services/tests/mockingservicestests/src/com/android/server/display/LocalDisplayAdapterTest.java
index 3518dc599cef..05b655af65ed 100644
--- a/services/tests/mockingservicestests/src/com/android/server/display/LocalDisplayAdapterTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/display/LocalDisplayAdapterTest.java
@@ -120,11 +120,14 @@ public class LocalDisplayAdapterTest {
waitForHandlerToComplete(mHandler, HANDLER_WAIT_MS);
// This should be public
- assertDisplay(mListener.addedDisplays.get(0).getDisplayDeviceInfoLocked(), PORT_A, false);
- // This should be private
- assertDisplay(mListener.addedDisplays.get(1).getDisplayDeviceInfoLocked(), PORT_B, true);
+ assertDisplayPrivateFlag(mListener.addedDisplays.get(0).getDisplayDeviceInfoLocked(),
+ PORT_A, false);
// This should be public
- assertDisplay(mListener.addedDisplays.get(2).getDisplayDeviceInfoLocked(), PORT_C, false);
+ assertDisplayPrivateFlag(mListener.addedDisplays.get(1).getDisplayDeviceInfoLocked(),
+ PORT_B, true);
+ // This should be public
+ assertDisplayPrivateFlag(mListener.addedDisplays.get(2).getDisplayDeviceInfoLocked(),
+ PORT_C, false);
}
/**
@@ -141,12 +144,14 @@ public class LocalDisplayAdapterTest {
waitForHandlerToComplete(mHandler, HANDLER_WAIT_MS);
// This should be public
- assertDisplay(mListener.addedDisplays.get(0).getDisplayDeviceInfoLocked(), PORT_A, false);
+ assertDisplayPrivateFlag(mListener.addedDisplays.get(0).getDisplayDeviceInfoLocked(),
+ PORT_A, false);
// This should be public
- assertDisplay(mListener.addedDisplays.get(1).getDisplayDeviceInfoLocked(), PORT_C, false);
+ assertDisplayPrivateFlag(mListener.addedDisplays.get(1).getDisplayDeviceInfoLocked(),
+ PORT_C, false);
}
- private static void assertDisplay(
+ private static void assertDisplayPrivateFlag(
DisplayDeviceInfo info, int expectedPort, boolean shouldBePrivate) {
final DisplayAddress.Physical address = (DisplayAddress.Physical) info.address;
assertNotNull(address);
@@ -155,6 +160,39 @@ public class LocalDisplayAdapterTest {
assertEquals(shouldBePrivate, (info.flags & DisplayDeviceInfo.FLAG_PRIVATE) != 0);
}
+ /**
+ * Confirm that external display uses physical density.
+ */
+ @Test
+ public void testDpiValues() throws Exception {
+ // needs default one always
+ setUpDisplay(new DisplayConfig(createDisplayAddress(PORT_A), createDummyDisplayInfo()));
+ setUpDisplay(new DisplayConfig(createDisplayAddress(PORT_B), createDummyDisplayInfo()));
+ updateAvailableDisplays();
+ mAdapter.registerLocked();
+
+ waitForHandlerToComplete(mHandler, HANDLER_WAIT_MS);
+
+ assertDisplayDpi(
+ mListener.addedDisplays.get(0).getDisplayDeviceInfoLocked(), PORT_A, 100, 100,
+ 16000);
+ assertDisplayDpi(
+ mListener.addedDisplays.get(1).getDisplayDeviceInfoLocked(), PORT_B, 100, 100,
+ 16000);
+ }
+
+ private void assertDisplayDpi(DisplayDeviceInfo info, int expectedPort,
+ float expectedXdpi,
+ float expectedYDpi,
+ int expectedDensityDpi) {
+ final DisplayAddress.Physical physical = (DisplayAddress.Physical) info.address;
+ assertNotNull(physical);
+ assertEquals((byte) expectedPort, physical.getPort());
+ assertEquals(expectedXdpi, info.xDpi, 0.01);
+ assertEquals(expectedYDpi, info.yDpi, 0.01);
+ assertEquals(expectedDensityDpi, info.densityDpi);
+ }
+
private class DisplayConfig {
public final DisplayAddress.Physical address;
public final IBinder displayToken = new Binder();
diff --git a/services/tests/servicestests/Android.bp b/services/tests/servicestests/Android.bp
index cf7919b38f2e..015e574f2309 100644
--- a/services/tests/servicestests/Android.bp
+++ b/services/tests/servicestests/Android.bp
@@ -28,6 +28,7 @@ android_test {
"services.net",
"services.usage",
"guava",
+ "androidx.test.core",
"androidx.test.runner",
"androidx.test.rules",
"mockito-target-minus-junit4",
@@ -40,7 +41,6 @@ android_test {
"platformprotosnano",
"hamcrest-library",
"servicestests-utils",
- "xml-writer-device-lib",
"service-appsearch",
"service-jobscheduler",
],
diff --git a/services/tests/servicestests/res/xml/usertypes_test_eraseArray.xml b/services/tests/servicestests/res/xml/usertypes_test_eraseArray.xml
new file mode 100644
index 000000000000..02ac48e9dc58
--- /dev/null
+++ b/services/tests/servicestests/res/xml/usertypes_test_eraseArray.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+<user-types>
+ <profile-type
+ name='android.test'
+ max-allowed-per-parent='2' >
+ <badge-colors>
+ </badge-colors>
+ <default-restrictions />
+ </profile-type>
+</user-types> \ No newline at end of file
diff --git a/services/tests/servicestests/res/xml/usertypes_test_full.xml b/services/tests/servicestests/res/xml/usertypes_test_full.xml
new file mode 100644
index 000000000000..a281dcaafb3d
--- /dev/null
+++ b/services/tests/servicestests/res/xml/usertypes_test_full.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+<user-types>
+ <full-type
+ name='android.test.1'
+ max-allowed-per-parent='12' >
+ <default-restrictions no_remove_user='true' no_bluetooth='true' />
+ <badge-colors>
+ <item res='@*android:color/profile_badge_1' />
+ </badge-colors>
+ </full-type>
+</user-types>
diff --git a/services/tests/servicestests/res/xml/usertypes_test_illegalOemName.xml b/services/tests/servicestests/res/xml/usertypes_test_illegalOemName.xml
new file mode 100644
index 000000000000..f91df1f76fe1
--- /dev/null
+++ b/services/tests/servicestests/res/xml/usertypes_test_illegalOemName.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+<user-types>
+ <profile-type name='android.aosp.legal' max-allowed-per-parent='12' />
+ <profile-type name='android.oem.illegal.name' max-allowed-per-parent='14' />
+</user-types>
diff --git a/services/tests/servicestests/res/xml/usertypes_test_illegalUserBaseType.xml b/services/tests/servicestests/res/xml/usertypes_test_illegalUserBaseType.xml
new file mode 100644
index 000000000000..0785655d1457
--- /dev/null
+++ b/services/tests/servicestests/res/xml/usertypes_test_illegalUserBaseType.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+<user-types>
+ <profile-type name='android.test' max-allowed-per-parent='12' />
+</user-types>
diff --git a/services/tests/servicestests/res/xml/usertypes_test_profile.xml b/services/tests/servicestests/res/xml/usertypes_test_profile.xml
new file mode 100644
index 000000000000..b6c8fbdcdd20
--- /dev/null
+++ b/services/tests/servicestests/res/xml/usertypes_test_profile.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+<user-types>
+ <profile-type
+ name='android.test.2'
+ max-allowed-per-parent='12'
+ icon-badge='@*android:drawable/ic_corp_icon_badge_case'
+ badge-plain='garbage'
+ badge-no-background='@*android:drawable/ic_corp_badge_no_background'
+ >
+ <badge-labels>
+ <item res='@*android:string/managed_profile_label_badge' />
+ <item res='@*android:string/managed_profile_label_badge_2' />
+ </badge-labels>
+ <badge-colors>
+ <item res='@*android:color/profile_badge_1' />
+ <item res='@*android:color/profile_badge_2' />
+ </badge-colors>
+ <default-restrictions no_remove_user='true' no_bluetooth='true' />
+ </profile-type>
+ <profile-type name='custom.test.1' max-allowed-per-parent='14' />
+</user-types>
diff --git a/services/tests/servicestests/src/com/android/server/CountryDetectorServiceTest.java b/services/tests/servicestests/src/com/android/server/CountryDetectorServiceTest.java
index 192c50c7dc19..e9c5ce7127de 100644
--- a/services/tests/servicestests/src/com/android/server/CountryDetectorServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/CountryDetectorServiceTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010 The Android Open Source Project
+ * Copyright (C) 2019 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.
@@ -11,28 +11,48 @@
* 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
+ * limitations under the License.
*/
package com.android.server;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.doAnswer;
+
import android.content.Context;
import android.location.Country;
import android.location.CountryListener;
import android.location.ICountryListener;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.Message;
import android.os.RemoteException;
-import android.test.AndroidTestCase;
-public class CountryDetectorServiceTest extends AndroidTestCase {
- private class CountryListenerTester extends ICountryListener.Stub {
+import androidx.test.core.app.ApplicationProvider;
+
+import com.google.common.truth.Expect;
+
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Spy;
+import org.mockito.junit.MockitoJUnitRunner;
+
+@RunWith(MockitoJUnitRunner.class)
+public class CountryDetectorServiceTest {
+
+ private static class CountryListenerTester extends ICountryListener.Stub {
private Country mCountry;
@Override
- public void onCountryDetected(Country country) throws RemoteException {
+ public void onCountryDetected(Country country) {
mCountry = country;
}
- public Country getCountry() {
+ Country getCountry() {
return mCountry;
}
@@ -41,12 +61,11 @@ public class CountryDetectorServiceTest extends AndroidTestCase {
}
}
- private class CountryDetectorServiceTester extends CountryDetectorService {
-
+ private static class CountryDetectorServiceTester extends CountryDetectorService {
private CountryListener mListener;
- public CountryDetectorServiceTester(Context context) {
- super(context);
+ CountryDetectorServiceTester(Context context, Handler handler) {
+ super(context, handler);
}
@Override
@@ -59,51 +78,77 @@ public class CountryDetectorServiceTest extends AndroidTestCase {
mListener = listener;
}
- public boolean isListenerSet() {
+ boolean isListenerSet() {
return mListener != null;
}
}
- public void testAddRemoveListener() throws RemoteException {
- CountryDetectorServiceTester serviceTester = new CountryDetectorServiceTester(getContext());
- serviceTester.systemRunning();
- waitForSystemReady(serviceTester);
- CountryListenerTester listenerTester = new CountryListenerTester();
- serviceTester.addCountryListener(listenerTester);
- assertTrue(serviceTester.isListenerSet());
- serviceTester.removeCountryListener(listenerTester);
- assertFalse(serviceTester.isListenerSet());
+ @Rule
+ public final Expect expect = Expect.create();
+ @Spy
+ private Context mContext = ApplicationProvider.getApplicationContext();
+ @Spy
+ private Handler mHandler = new Handler(Looper.myLooper());
+ private CountryDetectorServiceTester mCountryDetectorService;
+
+ @BeforeClass
+ public static void oneTimeInitialization() {
+ if (Looper.myLooper() == null) {
+ Looper.prepare();
+ }
}
- public void testNotifyListeners() throws RemoteException {
- CountryDetectorServiceTester serviceTester = new CountryDetectorServiceTester(getContext());
- CountryListenerTester listenerTesterA = new CountryListenerTester();
- CountryListenerTester listenerTesterB = new CountryListenerTester();
- Country country = new Country("US", Country.COUNTRY_SOURCE_NETWORK);
- serviceTester.systemRunning();
- waitForSystemReady(serviceTester);
- serviceTester.addCountryListener(listenerTesterA);
- serviceTester.addCountryListener(listenerTesterB);
- serviceTester.notifyReceivers(country);
- assertTrue(serviceTester.isListenerSet());
- assertTrue(listenerTesterA.isNotified());
- assertTrue(listenerTesterB.isNotified());
- serviceTester.removeCountryListener(listenerTesterA);
- serviceTester.removeCountryListener(listenerTesterB);
- assertFalse(serviceTester.isListenerSet());
+ @Before
+ public void setUp() {
+ mCountryDetectorService = new CountryDetectorServiceTester(mContext, mHandler);
+
+ // Immediately invoke run on the Runnable posted to the handler
+ doAnswer(invocation -> {
+ Message message = invocation.getArgument(0);
+ message.getCallback().run();
+ return true;
+ }).when(mHandler).sendMessageAtTime(any(Message.class), anyLong());
}
- private void waitForSystemReady(CountryDetectorService service) {
- int count = 5;
- while (count-- > 0) {
- try {
- Thread.sleep(500);
- } catch (Exception e) {
- }
- if (service.isSystemReady()) {
- return;
- }
- }
- throw new RuntimeException("Wait System Ready timeout");
+ @Test
+ public void countryListener_add_successful() throws RemoteException {
+ CountryListenerTester countryListener = new CountryListenerTester();
+
+ mCountryDetectorService.systemRunning();
+ expect.that(mCountryDetectorService.isListenerSet()).isFalse();
+ mCountryDetectorService.addCountryListener(countryListener);
+
+ expect.that(mCountryDetectorService.isListenerSet()).isTrue();
+ }
+
+ @Test
+ public void countryListener_remove_successful() throws RemoteException {
+ CountryListenerTester countryListener = new CountryListenerTester();
+
+ mCountryDetectorService.systemRunning();
+ mCountryDetectorService.addCountryListener(countryListener);
+ expect.that(mCountryDetectorService.isListenerSet()).isTrue();
+ mCountryDetectorService.removeCountryListener(countryListener);
+
+ expect.that(mCountryDetectorService.isListenerSet()).isFalse();
+ }
+
+ @Test
+ public void countryListener_notify_successful() throws RemoteException {
+ CountryListenerTester countryListenerA = new CountryListenerTester();
+ CountryListenerTester countryListenerB = new CountryListenerTester();
+ Country country = new Country("US", Country.COUNTRY_SOURCE_NETWORK);
+
+ mCountryDetectorService.systemRunning();
+ mCountryDetectorService.addCountryListener(countryListenerA);
+ mCountryDetectorService.addCountryListener(countryListenerB);
+ expect.that(countryListenerA.isNotified()).isFalse();
+ expect.that(countryListenerB.isNotified()).isFalse();
+ mCountryDetectorService.notifyReceivers(country);
+
+ expect.that(countryListenerA.isNotified()).isTrue();
+ expect.that(countryListenerB.isNotified()).isTrue();
+ expect.that(countryListenerA.getCountry().equalsIgnoreSource(country)).isTrue();
+ expect.that(countryListenerB.getCountry().equalsIgnoreSource(country)).isTrue();
}
}
diff --git a/services/tests/servicestests/src/com/android/server/GnssManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/GnssManagerServiceTest.java
index 9692c257079d..8b5444c2c55c 100644
--- a/services/tests/servicestests/src/com/android/server/GnssManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/GnssManagerServiceTest.java
@@ -61,6 +61,7 @@ import com.android.server.location.GnssMeasurementsProvider.GnssMeasurementProvi
import com.android.server.location.GnssNavigationMessageProvider;
import com.android.server.location.GnssNavigationMessageProvider.GnssNavigationMessageProviderNative;
import com.android.server.location.GnssStatusListenerHelper;
+import com.android.server.location.LocationUsageLogger;
import org.junit.Before;
import org.junit.Test;
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityUserStateTest.java b/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityUserStateTest.java
index d70e1648f719..96d9c476bcde 100644
--- a/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityUserStateTest.java
+++ b/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityUserStateTest.java
@@ -73,7 +73,7 @@ public class AccessibilityUserStateTest {
@Mock private AccessibilityUserState.ServiceInfoChangeListener mMockListener;
- @Mock private Context mContext;
+ @Mock private Context mMockContext;
private MockContentResolver mMockResolver;
@@ -85,11 +85,11 @@ public class AccessibilityUserStateTest {
FakeSettingsProvider.clearSettingsProvider();
mMockResolver = new MockContentResolver();
mMockResolver.addProvider(Settings.AUTHORITY, new FakeSettingsProvider());
- when(mContext.getContentResolver()).thenReturn(mMockResolver);
+ when(mMockContext.getContentResolver()).thenReturn(mMockResolver);
when(mMockServiceInfo.getComponentName()).thenReturn(COMPONENT_NAME);
when(mMockConnection.getServiceInfo()).thenReturn(mMockServiceInfo);
- mUserState = new AccessibilityUserState(USER_ID, mContext, mMockListener);
+ mUserState = new AccessibilityUserState(USER_ID, mMockContext, mMockListener);
}
@After
@@ -109,11 +109,11 @@ public class AccessibilityUserStateTest {
mUserState.setInteractiveUiTimeoutLocked(30);
mUserState.mEnabledServices.add(COMPONENT_NAME);
mUserState.mTouchExplorationGrantedServices.add(COMPONENT_NAME);
+ mUserState.mAccessibilityShortcutKeyTargets.add(COMPONENT_NAME.flattenToString());
+ mUserState.mAccessibilityButtonTargets.add(COMPONENT_NAME.flattenToString());
mUserState.setTouchExplorationEnabledLocked(true);
mUserState.setDisplayMagnificationEnabledLocked(true);
mUserState.setNavBarMagnificationEnabledLocked(true);
- mUserState.setServiceAssignedToAccessibilityButtonLocked(COMPONENT_NAME);
- mUserState.setNavBarMagnificationAssignedToAccessibilityButtonLocked(true);
mUserState.setAutoclickEnabledLocked(true);
mUserState.setUserNonInteractiveUiTimeoutLocked(30);
mUserState.setUserInteractiveUiTimeoutLocked(30);
@@ -128,11 +128,11 @@ public class AccessibilityUserStateTest {
assertEquals(0, mUserState.getInteractiveUiTimeoutLocked());
assertTrue(mUserState.mEnabledServices.isEmpty());
assertTrue(mUserState.mTouchExplorationGrantedServices.isEmpty());
+ assertTrue(mUserState.mAccessibilityShortcutKeyTargets.isEmpty());
+ assertTrue(mUserState.mAccessibilityButtonTargets.isEmpty());
assertFalse(mUserState.isTouchExplorationEnabledLocked());
assertFalse(mUserState.isDisplayMagnificationEnabledLocked());
assertFalse(mUserState.isNavBarMagnificationEnabledLocked());
- assertNull(mUserState.getServiceAssignedToAccessibilityButtonLocked());
- assertFalse(mUserState.isNavBarMagnificationAssignedToAccessibilityButtonLocked());
assertFalse(mUserState.isAutoclickEnabledLocked());
assertEquals(0, mUserState.getUserNonInteractiveUiTimeoutLocked());
assertEquals(0, mUserState.getUserInteractiveUiTimeoutLocked());
@@ -287,6 +287,19 @@ public class AccessibilityUserStateTest {
verify(mMockConnection).notifySoftKeyboardShowModeChangedLocked(eq(SHOW_MODE_HIDDEN));
}
+ @Test
+ public void isShortcutTargetInstalledLocked_returnTrue() {
+ mUserState.mInstalledServices.add(mMockServiceInfo);
+ assertTrue(mUserState.isShortcutTargetInstalledLocked(COMPONENT_NAME.flattenToString()));
+ }
+
+ @Test
+ public void isShortcutTargetInstalledLocked_invalidTarget_returnFalse() {
+ final ComponentName invalidTarget =
+ new ComponentName("com.android.server.accessibility", "InvalidTarget");
+ assertFalse(mUserState.isShortcutTargetInstalledLocked(invalidTarget.flattenToString()));
+ }
+
private int getSecureIntForUser(String key, int userId) {
return Settings.Secure.getIntForUser(mMockResolver, key, -1, userId);
}
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityWindowManagerTest.java b/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityWindowManagerTest.java
index b5e5deb9ff59..67075edb0143 100644
--- a/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityWindowManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityWindowManagerTest.java
@@ -705,6 +705,26 @@ public class AccessibilityWindowManagerTest {
assertTrue(displayList.equals(mExpectedDisplayList));
}
+ @Test
+ public void setAccessibilityWindowIdToSurfaceMetadata()
+ throws RemoteException {
+ final IWindow token = addAccessibilityInteractionConnection(Display.DEFAULT_DISPLAY,
+ true, USER_SYSTEM_ID);
+ int windowId = -1;
+ for (int i = 0; i < mA11yWindowTokens.size(); i++) {
+ if (mA11yWindowTokens.valueAt(i).equals(token)) {
+ windowId = mA11yWindowTokens.keyAt(i);
+ }
+ }
+ assertNotEquals("Returned token is not found in mA11yWindowTokens", -1, windowId);
+ verify(mMockWindowManagerInternal, times(1)).setAccessibilityIdToSurfaceMetadata(
+ token.asBinder(), windowId);
+
+ mA11yWindowManager.removeAccessibilityInteractionConnection(token);
+ verify(mMockWindowManagerInternal, times(1)).setAccessibilityIdToSurfaceMetadata(
+ token.asBinder(), -1);
+ }
+
private void startTrackingPerDisplay(int displayId) throws RemoteException {
ArrayList<WindowInfo> windowInfosForDisplay = new ArrayList<>();
// Adds RemoteAccessibilityConnection into AccessibilityWindowManager, and copy
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/gestures/AccessibilityGestureDetectorTest.java b/services/tests/servicestests/src/com/android/server/accessibility/gestures/GestureManifoldTest.java
index b7079124fb79..538e2d51e88f 100644
--- a/services/tests/servicestests/src/com/android/server/accessibility/gestures/AccessibilityGestureDetectorTest.java
+++ b/services/tests/servicestests/src/com/android/server/accessibility/gestures/GestureManifoldTest.java
@@ -24,22 +24,21 @@ import static org.mockito.Mockito.when;
import android.accessibilityservice.AccessibilityService;
import android.content.Context;
-import android.content.res.Resources;
import android.graphics.Point;
import android.graphics.PointF;
-import android.util.DisplayMetrics;
-import android.view.GestureDetector;
import android.view.MotionEvent;
+import androidx.test.InstrumentationRegistry;
+
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
/**
- * Tests for AccessibilityGestureDetector
+ * Tests for GestureManifold
*/
-public class AccessibilityGestureDetectorTest {
+public class GestureManifoldTest {
// Constants for testRecognizeGesturePath()
private static final PointF PATH_START = new PointF(300f, 300f);
@@ -47,24 +46,21 @@ public class AccessibilityGestureDetectorTest {
private static final long PATH_STEP_MILLISEC = 100;
// Data used by all tests
- private AccessibilityGestureDetector mDetector;
- private AccessibilityGestureDetector.Listener mResultListener;
+ private GestureManifold mManifold;
+ private TouchState mState;
+ private GestureManifold.Listener mResultListener;
@Before
public void setUp() {
- // Construct a mock Context.
- DisplayMetrics displayMetricsMock = mock(DisplayMetrics.class);
- displayMetricsMock.xdpi = 500;
- displayMetricsMock.ydpi = 500;
- Resources mockResources = mock(Resources.class);
- when(mockResources.getDisplayMetrics()).thenReturn(displayMetricsMock);
- Context contextMock = mock(Context.class);
- when(contextMock.getResources()).thenReturn(mockResources);
-
- // Construct a testable AccessibilityGestureDetector.
- mResultListener = mock(AccessibilityGestureDetector.Listener.class);
- GestureDetector doubleTapDetectorMock = mock(GestureDetector.class);
- mDetector = new AccessibilityGestureDetector(contextMock, mResultListener, doubleTapDetectorMock);
+ Context context = InstrumentationRegistry.getContext();
+ // Construct a testable GestureManifold.
+ mResultListener = mock(GestureManifold.Listener.class);
+ mState = new TouchState();
+ mManifold = new GestureManifold(context, mResultListener, mState);
+ // Play the role of touch explorer in updating the shared state.
+ when(mResultListener.onGestureStarted()).thenReturn(onGestureStarted());
+
+
}
@@ -141,8 +137,8 @@ public class AccessibilityGestureDetectorTest {
// For each path step from start (non-inclusive) to end ... add a motion point.
for (int step = 1; step < numSteps; ++step) {
path.add(new PointF(
- (start.x + (stepX * (float) step)),
- (start.y + (stepY * (float) step))));
+ (start.x + (stepX * (float) step)),
+ (start.y + (stepY * (float) step))));
}
}
@@ -170,12 +166,22 @@ public class AccessibilityGestureDetectorTest {
point.x, point.y, 0);
// Send event.
- mDetector.onMotionEvent(event, event, policyFlags);
+ mState.onReceivedMotionEvent(event);
+ mManifold.onMotionEvent(event, event, policyFlags);
eventTimeMs += PATH_STEP_MILLISEC;
+ if (mState.isClear()) {
+ mState.startTouchInteracting();
+ }
}
+ mState.clear();
// Check that correct gesture was recognized.
verify(mResultListener).onGestureCompleted(
argThat(gestureEvent -> gestureEvent.getGestureId() == gestureId));
}
+
+ private boolean onGestureStarted() {
+ mState.startGestureDetecting();
+ return false;
+ }
}
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/gestures/TouchExplorerTest.java b/services/tests/servicestests/src/com/android/server/accessibility/gestures/TouchExplorerTest.java
index 4b1ec6fe032b..a4ceadb3028b 100644
--- a/services/tests/servicestests/src/com/android/server/accessibility/gestures/TouchExplorerTest.java
+++ b/services/tests/servicestests/src/com/android/server/accessibility/gestures/TouchExplorerTest.java
@@ -74,7 +74,7 @@ public class TouchExplorerTest {
private TouchExplorer mTouchExplorer;
private long mLastDownTime = Integer.MIN_VALUE;
- // mock package-private AccessibilityGestureDetector class
+ // mock package-private GestureManifold class
@Rule
public final DexmakerShareClassLoaderRule mDexmakerShareClassLoaderRule =
new DexmakerShareClassLoaderRule();
@@ -108,7 +108,7 @@ public class TouchExplorerTest {
public void setUp() {
Context context = InstrumentationRegistry.getContext();
AccessibilityManagerService ams = new AccessibilityManagerService(context);
- AccessibilityGestureDetector detector = mock(AccessibilityGestureDetector.class);
+ GestureManifold detector = mock(GestureManifold.class);
mCaptor = new EventCaptor();
mTouchExplorer = new TouchExplorer(context, ams, detector);
mTouchExplorer.setNext(mCaptor);
diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/am/ActivityManagerServiceTest.java
index 49412bc0c559..2ce17a1d0cea 100644
--- a/services/tests/servicestests/src/com/android/server/am/ActivityManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/am/ActivityManagerServiceTest.java
@@ -349,10 +349,21 @@ public class ActivityManagerServiceTest {
verifyUidRangesNoOverlap(range, range2);
verifyIsolatedUidAllocator(range2);
- // Free both, then try to allocate the maximum number of UID ranges
+ // Free both
allocator.freeUidRangeLocked(appInfo);
allocator.freeUidRangeLocked(appInfo2);
+ // Verify for a secondary user
+ ApplicationInfo appInfo3 = new ApplicationInfo();
+ appInfo3.processName = "com.android.test.app";
+ appInfo3.uid = 1010000;
+ final IsolatedUidRange range3 = allocator.getOrCreateIsolatedUidRangeLocked(
+ appInfo3.processName, appInfo3.uid);
+ validateAppZygoteIsolatedUidRange(range3);
+ verifyIsolatedUidAllocator(range3);
+
+ allocator.freeUidRangeLocked(appInfo3);
+ // Try to allocate the maximum number of UID ranges
int maxNumUidRanges = (Process.LAST_APP_ZYGOTE_ISOLATED_UID
- Process.FIRST_APP_ZYGOTE_ISOLATED_UID + 1) / Process.NUM_UIDS_PER_APP_ZYGOTE;
for (int i = 0; i < maxNumUidRanges; i++) {
diff --git a/services/tests/servicestests/src/com/android/server/attention/AttentionManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/attention/AttentionManagerServiceTest.java
index a47a5671ccb3..e90cb4641752 100644
--- a/services/tests/servicestests/src/com/android/server/attention/AttentionManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/attention/AttentionManagerServiceTest.java
@@ -16,7 +16,11 @@
package com.android.server.attention;
+import static android.provider.DeviceConfig.NAMESPACE_ATTENTION_MANAGER_SERVICE;
+
import static com.android.server.attention.AttentionManagerService.ATTENTION_CACHE_BUFFER_SIZE;
+import static com.android.server.attention.AttentionManagerService.DEFAULT_STALE_AFTER_MILLIS;
+import static com.android.server.attention.AttentionManagerService.KEY_STALE_AFTER_MILLIS;
import static com.google.common.truth.Truth.assertThat;
@@ -35,6 +39,7 @@ import android.os.IBinder;
import android.os.IPowerManager;
import android.os.PowerManager;
import android.os.RemoteException;
+import android.provider.DeviceConfig;
import android.service.attention.IAttentionCallback;
import android.service.attention.IAttentionService;
@@ -180,6 +185,45 @@ public class AttentionManagerServiceTest {
assertThat(buffer.get(0)).isEqualTo(cache);
}
+ @Test
+ public void testGetStaleAfterMillis_handlesGoodFlagValue() {
+ DeviceConfig.setProperty(NAMESPACE_ATTENTION_MANAGER_SERVICE,
+ KEY_STALE_AFTER_MILLIS, "123", false);
+ assertThat(mSpyAttentionManager.getStaleAfterMillis()).isEqualTo(123);
+ }
+
+ @Test
+ public void testGetStaleAfterMillis_handlesBadFlagValue_1() {
+ DeviceConfig.setProperty(NAMESPACE_ATTENTION_MANAGER_SERVICE,
+ KEY_STALE_AFTER_MILLIS, "-123", false);
+ assertThat(mSpyAttentionManager.getStaleAfterMillis()).isEqualTo(
+ DEFAULT_STALE_AFTER_MILLIS);
+ }
+
+ @Test
+ public void testGetStaleAfterMillis_handlesBadFlagValue_2() {
+ DeviceConfig.setProperty(NAMESPACE_ATTENTION_MANAGER_SERVICE,
+ KEY_STALE_AFTER_MILLIS, "15000", false);
+ assertThat(mSpyAttentionManager.getStaleAfterMillis()).isEqualTo(
+ DEFAULT_STALE_AFTER_MILLIS);
+ }
+
+ @Test
+ public void testGetStaleAfterMillis_handlesBadFlagValue_3() {
+ DeviceConfig.setProperty(NAMESPACE_ATTENTION_MANAGER_SERVICE,
+ KEY_STALE_AFTER_MILLIS, "abracadabra", false);
+ assertThat(mSpyAttentionManager.getStaleAfterMillis()).isEqualTo(
+ DEFAULT_STALE_AFTER_MILLIS);
+ }
+
+ @Test
+ public void testGetStaleAfterMillis_handlesBadFlagValue_4() {
+ DeviceConfig.setProperty(NAMESPACE_ATTENTION_MANAGER_SERVICE,
+ KEY_STALE_AFTER_MILLIS, "15_000L", false);
+ assertThat(mSpyAttentionManager.getStaleAfterMillis()).isEqualTo(
+ DEFAULT_STALE_AFTER_MILLIS);
+ }
+
private class MockIAttentionService implements IAttentionService {
public void checkAttention(IAttentionCallback callback) throws RemoteException {
callback.onSuccess(0, 0);
diff --git a/services/tests/servicestests/src/com/android/server/biometrics/AuthServiceTest.java b/services/tests/servicestests/src/com/android/server/biometrics/AuthServiceTest.java
index 106a7238e399..d38c80cdabe0 100644
--- a/services/tests/servicestests/src/com/android/server/biometrics/AuthServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/biometrics/AuthServiceTest.java
@@ -20,6 +20,7 @@ import static android.hardware.biometrics.BiometricConstants.BIOMETRIC_SUCCESS;
import static junit.framework.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@@ -65,8 +66,16 @@ public class AuthServiceTest {
public void setUp() {
MockitoAnnotations.initMocks(this);
+ // Dummy test config
+ final String[] config = {
+ "0:2:15", // ID0:Fingerprint:Strong
+ "1:4:15", // ID1:Iris:Strong
+ "2:8:15", // ID2:Face:Strong
+ };
+
when(mContext.getPackageManager()).thenReturn(mPackageManager);
when(mInjector.getBiometricService()).thenReturn(mBiometricService);
+ when(mInjector.getConfiguration(any())).thenReturn(config);
when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT))
.thenReturn(true);
when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_IRIS)).thenReturn(true);
@@ -76,8 +85,7 @@ public class AuthServiceTest {
// TODO(b/141025588): Check that an exception is thrown when the userId != callingUserId
@Test
- public void testAuthenticate_callsBiometricServiceAuthenticate() throws
- Exception {
+ public void testAuthenticate_callsBiometricServiceAuthenticate() throws Exception {
mAuthService = new AuthService(mContext, mInjector);
mAuthService.onStart();
@@ -104,22 +112,25 @@ public class AuthServiceTest {
}
@Test
- public void testCanAuthenticate_callsBiometricServiceCanAuthenticate() throws
- Exception {
+ public void testCanAuthenticate_callsBiometricServiceCanAuthenticate() throws Exception {
mAuthService = new AuthService(mContext, mInjector);
mAuthService.onStart();
final int userId = 0;
final int expectedResult = BIOMETRIC_SUCCESS;
- when(mBiometricService.canAuthenticate(anyString(), anyInt())).thenReturn(expectedResult);
+ final int authenticators = 0;
+ when(mBiometricService.canAuthenticate(anyString(), anyInt(), anyInt()))
+ .thenReturn(expectedResult);
- final int result = mAuthService.mImpl.canAuthenticate(TEST_OP_PACKAGE_NAME, userId);
+ final int result = mAuthService.mImpl
+ .canAuthenticate(TEST_OP_PACKAGE_NAME, userId, authenticators);
assertEquals(expectedResult, result);
waitForIdle();
verify(mBiometricService).canAuthenticate(
eq(TEST_OP_PACKAGE_NAME),
- eq(userId));
+ eq(userId),
+ eq(authenticators));
}
diff --git a/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java b/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java
index 4ced421be63a..211fc4db6211 100644
--- a/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java
@@ -16,12 +16,14 @@
package com.android.server.biometrics;
+import static android.hardware.biometrics.BiometricManager.Authenticators;
+
import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertTrue;
import static junit.framework.TestCase.assertNotNull;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -34,12 +36,13 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.IActivityManager;
+import android.app.trust.ITrustManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
-import android.hardware.biometrics.Authenticator;
import android.hardware.biometrics.BiometricAuthenticator;
import android.hardware.biometrics.BiometricConstants;
+import android.hardware.biometrics.BiometricManager;
import android.hardware.biometrics.BiometricPrompt;
import android.hardware.biometrics.IBiometricAuthenticator;
import android.hardware.biometrics.IBiometricService;
@@ -81,8 +84,6 @@ public class BiometricServiceTest {
private static final String FINGERPRINT_ACQUIRED_SENSOR_DIRTY = "sensor_dirty";
- private static final int STRENGTH_STRONG = 1;
-
private BiometricService mBiometricService;
@Mock
@@ -101,6 +102,8 @@ public class BiometricServiceTest {
IBiometricAuthenticator mFingerprintAuthenticator;
@Mock
IBiometricAuthenticator mFaceAuthenticator;
+ @Mock
+ ITrustManager mTrustManager;
@Before
public void setUp() {
@@ -111,10 +114,13 @@ public class BiometricServiceTest {
when(mInjector.getActivityManagerService()).thenReturn(mock(IActivityManager.class));
when(mInjector.getStatusBarService()).thenReturn(mock(IStatusBarService.class));
- when(mInjector.getSettingObserver(any(), any(), any())).thenReturn(
- mock(BiometricService.SettingObserver.class));
+ when(mInjector.getSettingObserver(any(), any(), any()))
+ .thenReturn(mock(BiometricService.SettingObserver.class));
when(mInjector.getKeyStore()).thenReturn(mock(KeyStore.class));
when(mInjector.isDebugEnabled(any(), anyInt())).thenReturn(false);
+ when(mInjector.getBiometricStrengthController(any()))
+ .thenReturn(mock(BiometricStrengthController.class));
+ when(mInjector.getTrustManager()).thenReturn(mTrustManager);
when(mResources.getString(R.string.biometric_error_hw_unavailable))
.thenReturn(ERROR_HW_UNAVAILABLE);
@@ -122,6 +128,56 @@ public class BiometricServiceTest {
.thenReturn(ERROR_NOT_RECOGNIZED);
when(mResources.getString(R.string.biometric_error_user_canceled))
.thenReturn(ERROR_USER_CANCELED);
+
+ final String[] config = {
+ "0:2:15", // ID0:Fingerprint:Strong
+ "1:8:15", // ID1:Face:Strong
+ "2:4:255", // ID2:Iris:Weak
+ };
+
+ when(mInjector.getConfiguration(any())).thenReturn(config);
+ }
+
+ @Test
+ public void testAuthenticate_credentialAllowedButNotSetup_returnsNoDeviceCredential()
+ throws Exception {
+ when(mTrustManager.isDeviceSecure(anyInt())).thenReturn(false);
+
+ mBiometricService = new BiometricService(mContext, mInjector);
+ mBiometricService.onStart();
+
+ invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
+ Authenticators.DEVICE_CREDENTIAL);
+ waitForIdle();
+ verify(mReceiver1).onError(
+ eq(BiometricAuthenticator.TYPE_NONE),
+ eq(BiometricConstants.BIOMETRIC_ERROR_NO_DEVICE_CREDENTIAL),
+ eq(0 /* vendorCode */));
+ }
+
+ @Test
+ public void testAuthenticate_credentialAllowedAndSetup_callsSystemUI() throws Exception {
+ // When no biometrics are enrolled, but credentials are set up, status bar should be
+ // invoked right away with showAuthenticationDialog
+
+ when(mTrustManager.isDeviceSecure(anyInt())).thenReturn(true);
+
+ mBiometricService = new BiometricService(mContext, mInjector);
+ mBiometricService.onStart();
+
+ invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
+ Authenticators.DEVICE_CREDENTIAL);
+ waitForIdle();
+
+ assertNull(mBiometricService.mPendingAuthSession);
+ // StatusBar showBiometricDialog invoked
+ verify(mBiometricService.mStatusBarService).showAuthenticationDialog(
+ eq(mBiometricService.mCurrentAuthSession.mBundle),
+ any(IBiometricServiceReceiverInternal.class),
+ eq(0),
+ anyBoolean() /* requireConfirmation */,
+ anyInt() /* userId */,
+ eq(TEST_PACKAGE_NAME));
}
@Test
@@ -131,7 +187,7 @@ public class BiometricServiceTest {
mBiometricService.onStart();
invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
- false /* allowDeviceCredential */);
+ null /* authenticators */);
waitForIdle();
verify(mReceiver1).onError(
eq(BiometricAuthenticator.TYPE_NONE),
@@ -145,12 +201,12 @@ public class BiometricServiceTest {
mBiometricService = new BiometricService(mContext, mInjector);
mBiometricService.onStart();
- mBiometricService.mImpl.registerAuthenticator(0 /* id */, STRENGTH_STRONG,
- BiometricAuthenticator.TYPE_FINGERPRINT, mFingerprintAuthenticator);
-
+ mBiometricService.mImpl.registerAuthenticator(0 /* id */,
+ BiometricAuthenticator.TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG,
+ mFingerprintAuthenticator);
invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
- false /* allowDeviceCredential */);
+ null /* authenticators */);
waitForIdle();
verify(mReceiver1).onError(
eq(BiometricAuthenticator.TYPE_FINGERPRINT),
@@ -159,6 +215,54 @@ public class BiometricServiceTest {
}
@Test
+ public void testAuthenticate_notStrongEnough_returnsHardwareNotPresent() throws Exception {
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT, Authenticators.BIOMETRIC_WEAK);
+
+ invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
+ Authenticators.BIOMETRIC_STRONG);
+ waitForIdle();
+ verify(mReceiver1).onError(
+ eq(BiometricAuthenticator.TYPE_NONE),
+ eq(BiometricConstants.BIOMETRIC_ERROR_HW_NOT_PRESENT),
+ eq(0 /* vendorCode */));
+ }
+
+ @Test
+ public void testAuthenticate_picksStrongIfAvailable() throws Exception {
+ // If both strong and weak are available, and the caller requires STRONG, authentication
+ // is able to proceed.
+
+ final int[] modalities = new int[] {
+ BiometricAuthenticator.TYPE_FINGERPRINT,
+ BiometricAuthenticator.TYPE_FACE,
+ };
+
+ final int[] strengths = new int[] {
+ Authenticators.BIOMETRIC_WEAK,
+ Authenticators.BIOMETRIC_STRONG,
+ };
+
+ setupAuthForMultiple(modalities, strengths);
+
+ invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
+ false /* requireConfirmation */, Authenticators.BIOMETRIC_STRONG);
+ waitForIdle();
+ verify(mReceiver1, never()).onError(
+ anyInt(),
+ anyInt(),
+ anyInt() /* vendorCode */);
+
+ // StatusBar showBiometricDialog invoked with face, which was set up to be STRONG
+ verify(mBiometricService.mStatusBarService).showAuthenticationDialog(
+ eq(mBiometricService.mCurrentAuthSession.mBundle),
+ any(IBiometricServiceReceiverInternal.class),
+ eq(BiometricAuthenticator.TYPE_FACE),
+ eq(false) /* requireConfirmation */,
+ anyInt() /* userId */,
+ eq(TEST_PACKAGE_NAME));
+ }
+
+ @Test
public void testAuthenticate_whenHalIsDead_returnsErrorHardwareUnavailable() throws
Exception {
when(mFingerprintAuthenticator.hasEnrolledTemplates(anyInt(), any())).thenReturn(true);
@@ -166,11 +270,12 @@ public class BiometricServiceTest {
mBiometricService = new BiometricService(mContext, mInjector);
mBiometricService.onStart();
- mBiometricService.mImpl.registerAuthenticator(0 /* id */, STRENGTH_STRONG,
- BiometricAuthenticator.TYPE_FINGERPRINT, mFingerprintAuthenticator);
+ mBiometricService.mImpl.registerAuthenticator(0 /* id */,
+ BiometricAuthenticator.TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG,
+ mFingerprintAuthenticator);
invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
- false /* allowDeviceCredential */);
+ null /* authenticators */);
waitForIdle();
verify(mReceiver1).onError(
eq(BiometricAuthenticator.TYPE_NONE),
@@ -181,18 +286,12 @@ public class BiometricServiceTest {
@Test
public void testAuthenticateFace_respectsUserSetting()
throws Exception {
- when(mFaceAuthenticator.hasEnrolledTemplates(anyInt(), any())).thenReturn(true);
- when(mFaceAuthenticator.isHardwareDetected(any())).thenReturn(true);
-
- mBiometricService = new BiometricService(mContext, mInjector);
- mBiometricService.onStart();
- mBiometricService.mImpl.registerAuthenticator(0 /* id */, STRENGTH_STRONG,
- BiometricAuthenticator.TYPE_FACE, mFaceAuthenticator);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FACE, Authenticators.BIOMETRIC_STRONG);
// Disabled in user settings receives onError
when(mBiometricService.mSettingObserver.getFaceEnabledForApps(anyInt())).thenReturn(false);
invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
- false /* allowDeviceCredential */);
+ null /* authenticators */);
waitForIdle();
verify(mReceiver1).onError(
eq(BiometricAuthenticator.TYPE_NONE),
@@ -205,7 +304,7 @@ public class BiometricServiceTest {
when(mBiometricService.mSettingObserver.getFaceAlwaysRequireConfirmation(anyInt()))
.thenReturn(true);
invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
- false /* allowDeviceCredential */);
+ null /* authenticators */);
waitForIdle();
verify(mReceiver1, never()).onError(anyInt(), anyInt(), anyInt());
verify(mBiometricService.mAuthenticators.get(0).impl).prepareForAuthentication(
@@ -225,7 +324,7 @@ public class BiometricServiceTest {
when(mBiometricService.mSettingObserver.getFaceAlwaysRequireConfirmation(anyInt()))
.thenReturn(false);
invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
- false /* allowDeviceCredential */);
+ null /* authenticators */);
waitForIdle();
verify(mBiometricService.mAuthenticators.get(0).impl).prepareForAuthentication(
eq(false) /* requireConfirmation */,
@@ -242,11 +341,11 @@ public class BiometricServiceTest {
@Test
public void testAuthenticate_happyPathWithoutConfirmation() throws Exception {
- setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG);
// Start testing the happy path
invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
- false /* allowDeviceCredential */);
+ null /* authenticators */);
waitForIdle();
// Creates a pending auth session with the correct initial states
@@ -314,15 +413,16 @@ public class BiometricServiceTest {
@Test
public void testAuthenticate_noBiometrics_credentialAllowed() throws Exception {
- setupAuthForOnly(BiometricAuthenticator.TYPE_FACE);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FACE, Authenticators.BIOMETRIC_STRONG);
when(mFaceAuthenticator.hasEnrolledTemplates(anyInt(), any())).thenReturn(false);
invokeAuthenticate(mBiometricService.mImpl, mReceiver1,
- true /* requireConfirmation */, true /* allowDeviceCredential */);
+ true /* requireConfirmation */,
+ Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_WEAK);
waitForIdle();
assertEquals(BiometricService.STATE_SHOWING_DEVICE_CREDENTIAL,
mBiometricService.mCurrentAuthSession.mState);
- assertEquals(Authenticator.TYPE_CREDENTIAL,
+ assertEquals(Authenticators.DEVICE_CREDENTIAL,
mBiometricService.mCurrentAuthSession.mBundle
.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED));
verify(mBiometricService.mStatusBarService).showAuthenticationDialog(
@@ -336,9 +436,9 @@ public class BiometricServiceTest {
@Test
public void testAuthenticate_happyPathWithConfirmation() throws Exception {
- setupAuthForOnly(BiometricAuthenticator.TYPE_FACE);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FACE, Authenticators.BIOMETRIC_STRONG);
invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
- true /* requireConfirmation */, false /* allowDeviceCredential */);
+ true /* requireConfirmation */, null /* authenticators */);
// Test authentication succeeded goes to PENDING_CONFIRMATION and that the HAT is not
// sent to KeyStore yet
@@ -362,9 +462,9 @@ public class BiometricServiceTest {
@Test
public void testRejectFace_whenAuthenticating_notifiesSystemUIAndClient_thenPaused()
throws Exception {
- setupAuthForOnly(BiometricAuthenticator.TYPE_FACE);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FACE, Authenticators.BIOMETRIC_STRONG);
invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
- false /* requireConfirmation */, false /* allowDeviceCredential */);
+ false /* requireConfirmation */, null /* authenticators */);
mBiometricService.mInternalReceiver.onAuthenticationFailed();
waitForIdle();
@@ -381,9 +481,9 @@ public class BiometricServiceTest {
@Test
public void testRejectFingerprint_whenAuthenticating_notifiesAndKeepsAuthenticating()
throws Exception {
- setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG);
invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
- false /* requireConfirmation */, false /* allowDeviceCredential */);
+ false /* requireConfirmation */, null /* authenticators */);
mBiometricService.mInternalReceiver.onAuthenticationFailed();
waitForIdle();
@@ -398,53 +498,10 @@ public class BiometricServiceTest {
}
@Test
- public void testErrorCanceled_whenAuthenticating_notifiesSystemUIAndClient() throws
- Exception {
- setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
- invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
- false /* requireConfirmation */, false /* allowDeviceCredential */);
-
- // Create a new pending auth session but don't start it yet. HAL contract is that previous
- // one must get ERROR_CANCELED. Simulate that here by creating the pending auth session,
- // sending ERROR_CANCELED to the current auth session, and then having the second one
- // onReadyForAuthentication.
- invokeAuthenticate(mBiometricService.mImpl, mReceiver2, false /* requireConfirmation */,
- false /* allowDeviceCredential */);
- waitForIdle();
-
- assertEquals(mBiometricService.mCurrentAuthSession.mState,
- BiometricService.STATE_AUTH_STARTED);
- mBiometricService.mInternalReceiver.onError(
- getCookieForCurrentSession(mBiometricService.mCurrentAuthSession),
- BiometricAuthenticator.TYPE_FINGERPRINT,
- BiometricConstants.BIOMETRIC_ERROR_CANCELED, 0 /* vendorCode */);
- waitForIdle();
-
- // Auth session doesn't become null until SystemUI responds that the animation is completed
- assertNotNull(mBiometricService.mCurrentAuthSession);
- // ERROR_CANCELED is not sent until SystemUI responded that animation is completed
- verify(mReceiver1, never()).onError(anyInt(), anyInt(), anyInt());
- verify(mReceiver2, never()).onError(anyInt(), anyInt(), anyInt());
-
- // SystemUI dialog closed
- verify(mBiometricService.mStatusBarService).hideAuthenticationDialog();
-
- // After SystemUI notifies that the animation has completed
- mBiometricService.mInternalReceiver
- .onDialogDismissed(BiometricPrompt.DISMISSED_REASON_SERVER_REQUESTED);
- waitForIdle();
- verify(mReceiver1).onError(
- eq(BiometricAuthenticator.TYPE_FINGERPRINT),
- eq(BiometricConstants.BIOMETRIC_ERROR_CANCELED),
- eq(0 /* vendorCode */));
- assertNull(mBiometricService.mCurrentAuthSession);
- }
-
- @Test
public void testErrorHalTimeout_whenAuthenticating_entersPausedState() throws Exception {
- setupAuthForOnly(BiometricAuthenticator.TYPE_FACE);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FACE, Authenticators.BIOMETRIC_STRONG);
invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
- false /* requireConfirmation */, false /* allowDeviceCredential */);
+ false /* requireConfirmation */, null /* authenticators */);
mBiometricService.mInternalReceiver.onError(
getCookieForCurrentSession(mBiometricService.mCurrentAuthSession),
@@ -491,9 +548,9 @@ public class BiometricServiceTest {
@Test
public void testErrorFromHal_whenPaused_notifiesSystemUIAndClient() throws Exception {
- setupAuthForOnly(BiometricAuthenticator.TYPE_FACE);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FACE, Authenticators.BIOMETRIC_STRONG);
invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
- false /* requireConfirmation */, false /* allowDeviceCredential */);
+ false /* requireConfirmation */, null /* authenticators */);
mBiometricService.mInternalReceiver.onError(
getCookieForCurrentSession(mBiometricService.mCurrentAuthSession),
@@ -524,9 +581,9 @@ public class BiometricServiceTest {
// For errors that show in SystemUI, BiometricService stays in STATE_ERROR_PENDING_SYSUI
// until SystemUI notifies us that the dialog is dismissed at which point the current
// session is done.
- setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG);
invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
- false /* requireConfirmation */, false /* allowDeviceCredential */);
+ false /* requireConfirmation */, null /* authenticators */);
mBiometricService.mInternalReceiver.onError(
getCookieForCurrentSession(mBiometricService.mCurrentAuthSession),
@@ -558,9 +615,10 @@ public class BiometricServiceTest {
@Test
public void testErrorFromHal_whilePreparingAuthentication_credentialAllowed() throws Exception {
- setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG);
invokeAuthenticate(mBiometricService.mImpl, mReceiver1,
- false /* requireConfirmation */, true /* allowDeviceCredential */);
+ false /* requireConfirmation */,
+ Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_WEAK);
waitForIdle();
mBiometricService.mInternalReceiver.onError(
@@ -576,7 +634,7 @@ public class BiometricServiceTest {
assertNotNull(mBiometricService.mCurrentAuthSession);
assertEquals(BiometricService.STATE_SHOWING_DEVICE_CREDENTIAL,
mBiometricService.mCurrentAuthSession.mState);
- assertEquals(Authenticator.TYPE_CREDENTIAL,
+ assertEquals(Authenticators.DEVICE_CREDENTIAL,
mBiometricService.mCurrentAuthSession.mBundle.getInt(
BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED));
verify(mBiometricService.mStatusBarService).showAuthenticationDialog(
@@ -591,9 +649,9 @@ public class BiometricServiceTest {
@Test
public void testErrorFromHal_whilePreparingAuthentication_credentialNotAllowed()
throws Exception {
- setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG);
invokeAuthenticate(mBiometricService.mImpl, mReceiver1,
- false /* requireConfirmation */, false /* allowDeviceCredential */);
+ false /* requireConfirmation */, null /* authenticators */);
waitForIdle();
mBiometricService.mInternalReceiver.onError(
@@ -609,58 +667,64 @@ public class BiometricServiceTest {
}
@Test
- public void testCombineAuthenticatorBundle_keyAllowDeviceCredentialAlwaysRemoved() {
- Bundle bundle;
- int authenticators;
+ public void testCombineAuthenticatorBundles_withKeyDeviceCredential_andKeyAuthenticators() {
+ final boolean allowDeviceCredential = false;
+ final @Authenticators.Types int authenticators =
+ Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_WEAK;
+ final Bundle bundle = new Bundle();
- // In:
- // KEY_ALLOW_DEVICE_CREDENTIAL = true
- // KEY_AUTHENTICATORS_ALLOWED = TYPE_BIOMETRIC | TYPE_CREDENTIAL
- // Out:
- // KEY_ALLOW_DEVICE_CREDENTIAL = null
- // KEY_AUTHENTICATORS_ALLOWED = TYPE_BIOMETRIC | TYPE_CREDENTIAL
- bundle = new Bundle();
- bundle.putBoolean(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL, true);
- authenticators = Authenticator.TYPE_CREDENTIAL | Authenticator.TYPE_BIOMETRIC;
+ bundle.putBoolean(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL, allowDeviceCredential);
bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
Utils.combineAuthenticatorBundles(bundle);
+
assertNull(bundle.get(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL));
- assertEquals(authenticators, bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED));
-
- // In:
- // KEY_ALLOW_DEVICE_CREDENTIAL = true
- // KEY_AUTHENTICATORS_ALLOWED = TYPE_BIOMETRIC
- // Out:
- // KEY_ALLOW_DEVICE_CREDENTIAL = null
- // KEY_AUTHENTICATORS_ALLOWED = TYPE_BIOMETRIC | TYPE_CREDENTIAL
- bundle = new Bundle();
- bundle.putBoolean(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL, true);
- authenticators = Authenticator.TYPE_BIOMETRIC;
+ assertEquals(bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED), authenticators);
+ }
+
+ @Test
+ public void testCombineAuthenticatorBundles_withNoKeyDeviceCredential_andKeyAuthenticators() {
+ final @Authenticators.Types int authenticators =
+ Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_WEAK;
+ final Bundle bundle = new Bundle();
+
bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
Utils.combineAuthenticatorBundles(bundle);
+
assertNull(bundle.get(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL));
- assertEquals(authenticators, bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED));
-
- // In:
- // KEY_ALLOW_DEVICE_CREDENTIAL = null
- // KEY_AUTHENTICATORS_ALLOWED = TYPE_BIOMETRIC | TYPE_CREDENTIAL
- // Out:
- // KEY_ALLOW_DEVICE_CREDENTIAL = null
- // KEY_AUTHENTICATORS_ALLOWED = TYPE_BIOMETRIC | TYPE_CREDENTIAL
- bundle = new Bundle();
- authenticators = Authenticator.TYPE_BIOMETRIC | Authenticator.TYPE_CREDENTIAL;
- bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
+ assertEquals(bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED), authenticators);
+ }
+
+ @Test
+ public void testCombineAuthenticatorBundles_withKeyDeviceCredential_andNoKeyAuthenticators() {
+ final boolean allowDeviceCredential = true;
+ final Bundle bundle = new Bundle();
+
+ bundle.putBoolean(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL, allowDeviceCredential);
+ Utils.combineAuthenticatorBundles(bundle);
+
+ assertNull(bundle.get(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL));
+ assertEquals(bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED),
+ Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_WEAK);
+ }
+
+ @Test
+ public void testCombineAuthenticatorBundles_withNoKeyDeviceCredential_andNoKeyAuthenticators() {
+ final Bundle bundle = new Bundle();
+
Utils.combineAuthenticatorBundles(bundle);
+
assertNull(bundle.get(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL));
- assertEquals(authenticators, bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED));
+ assertEquals(bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED),
+ Authenticators.BIOMETRIC_WEAK);
}
@Test
public void testErrorFromHal_whileShowingDeviceCredential_doesntNotifySystemUI()
throws Exception {
- setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG);
invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
- false /* requireConfirmation */, true /* allowDeviceCredential */);
+ false /* requireConfirmation */,
+ Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_WEAK);
mBiometricService.mInternalReceiver.onDeviceCredentialPressed();
waitForIdle();
@@ -683,9 +747,10 @@ public class BiometricServiceTest {
@Test
public void testLockout_whileAuthenticating_credentialAllowed() throws Exception {
- setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG);
invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
- false /* requireConfirmation */, true /* allowDeviceCredential */);
+ false /* requireConfirmation */,
+ Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_WEAK);
assertEquals(BiometricService.STATE_AUTH_STARTED,
mBiometricService.mCurrentAuthSession.mState);
@@ -707,9 +772,9 @@ public class BiometricServiceTest {
@Test
public void testLockout_whenAuthenticating_credentialNotAllowed() throws Exception {
- setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG);
invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
- false /* requireConfirmation */, false /* allowDeviceCredential */);
+ false /* requireConfirmation */, null /* authenticators */);
assertEquals(BiometricService.STATE_AUTH_STARTED,
mBiometricService.mCurrentAuthSession.mState);
@@ -732,9 +797,9 @@ public class BiometricServiceTest {
@Test
public void testDismissedReasonUserCancel_whileAuthenticating_cancelsHalAuthentication()
throws Exception {
- setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG);
invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
- false /* requireConfirmation */, false /* allowDeviceCredential */);
+ false /* requireConfirmation */, null /* authenticators */);
mBiometricService.mInternalReceiver
.onDialogDismissed(BiometricPrompt.DISMISSED_REASON_USER_CANCEL);
@@ -755,9 +820,9 @@ public class BiometricServiceTest {
@Test
public void testDismissedReasonNegative_whilePaused_doesntInvokeHalCancel() throws Exception {
- setupAuthForOnly(BiometricAuthenticator.TYPE_FACE);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FACE, Authenticators.BIOMETRIC_STRONG);
invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
- false /* requireConfirmation */, false /* allowDeviceCredential */);
+ false /* requireConfirmation */, null /* authenticators */);
mBiometricService.mInternalReceiver.onError(
getCookieForCurrentSession(mBiometricService.mCurrentAuthSession),
@@ -781,9 +846,9 @@ public class BiometricServiceTest {
@Test
public void testDismissedReasonUserCancel_whilePaused_doesntInvokeHalCancel() throws
Exception {
- setupAuthForOnly(BiometricAuthenticator.TYPE_FACE);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FACE, Authenticators.BIOMETRIC_STRONG);
invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
- false /* requireConfirmation */, false /* allowDeviceCredential */);
+ false /* requireConfirmation */, null /* authenticators */);
mBiometricService.mInternalReceiver.onError(
getCookieForCurrentSession(mBiometricService.mCurrentAuthSession),
@@ -806,9 +871,9 @@ public class BiometricServiceTest {
@Test
public void testDismissedReasonUserCancel_whenPendingConfirmation() throws Exception {
- setupAuthForOnly(BiometricAuthenticator.TYPE_FACE);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FACE, Authenticators.BIOMETRIC_STRONG);
invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
- true /* requireConfirmation */, false /* allowDeviceCredential */);
+ true /* requireConfirmation */, null /* authenticators */);
mBiometricService.mInternalReceiver.onAuthenticationSucceeded(
true /* requireConfirmation */,
@@ -835,9 +900,9 @@ public class BiometricServiceTest {
@Test
public void testAcquire_whenAuthenticating_sentToSystemUI() throws Exception {
- setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG);
invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
- false /* requireConfirmation */, false /* allowDeviceCredential */);
+ false /* requireConfirmation */, null /* authenticators */);
mBiometricService.mInternalReceiver.onAcquired(
FingerprintManager.FINGERPRINT_ACQUIRED_IMAGER_DIRTY,
@@ -851,26 +916,354 @@ public class BiometricServiceTest {
BiometricService.STATE_AUTH_STARTED);
}
+ @Test
+ public void testCancel_whenAuthenticating() throws Exception {
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG);
+ invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
+ false /* requireConfirmation */, null /* authenticators */);
+
+ mBiometricService.mImpl.cancelAuthentication(mBiometricService.mCurrentAuthSession.mToken,
+ TEST_PACKAGE_NAME);
+ waitForIdle();
+
+ // Pretend that the HAL has responded to cancel with ERROR_CANCELED
+ mBiometricService.mInternalReceiver.onError(getCookieForCurrentSession(
+ mBiometricService.mCurrentAuthSession), BiometricAuthenticator.TYPE_FINGERPRINT,
+ BiometricConstants.BIOMETRIC_ERROR_CANCELED, 0 /* vendorCode */);
+ waitForIdle();
+
+ // Hides system dialog and invokes the onError callback
+ verify(mReceiver1).onError(eq(BiometricAuthenticator.TYPE_FINGERPRINT),
+ eq(BiometricConstants.BIOMETRIC_ERROR_CANCELED),
+ eq(0 /* vendorCode */));
+ verify(mBiometricService.mStatusBarService).hideAuthenticationDialog();
+ }
+
+ @Test
+ public void testCanAuthenticate_whenDeviceHasRequestedBiometricStrength() throws Exception {
+ // When only biometric is requested, and sensor is strong enough
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG);
+
+ assertEquals(BiometricManager.BIOMETRIC_SUCCESS,
+ invokeCanAuthenticate(mBiometricService, Authenticators.BIOMETRIC_STRONG));
+ }
+
+ @Test
+ public void testCanAuthenticate_whenDeviceDoesNotHaveRequestedBiometricStrength()
+ throws Exception {
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT, Authenticators.BIOMETRIC_WEAK);
+
+ // When only biometric is requested, and sensor is not strong enough
+ when(mTrustManager.isDeviceSecure(anyInt())).thenReturn(false);
+ int authenticators = Authenticators.BIOMETRIC_STRONG;
+ assertEquals(BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE,
+ invokeCanAuthenticate(mBiometricService, authenticators));
+
+ // When credential and biometric are requested, and sensor is not strong enough
+ when(mTrustManager.isDeviceSecure(anyInt())).thenReturn(true);
+ authenticators = Authenticators.BIOMETRIC_STRONG | Authenticators.DEVICE_CREDENTIAL;
+ assertEquals(BiometricManager.BIOMETRIC_SUCCESS,
+ invokeCanAuthenticate(mBiometricService, authenticators));
+ }
+
+ @Test
+ public void testCanAuthenticate_onlyCredentialRequested() throws Exception {
+ mBiometricService = new BiometricService(mContext, mInjector);
+ mBiometricService.onStart();
+
+ // Credential requested but not set up
+ when(mTrustManager.isDeviceSecure(anyInt())).thenReturn(false);
+ assertEquals(BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED,
+ invokeCanAuthenticate(mBiometricService, Authenticators.DEVICE_CREDENTIAL));
+
+ // Credential requested and set up
+ when(mTrustManager.isDeviceSecure(anyInt())).thenReturn(true);
+ assertEquals(BiometricManager.BIOMETRIC_SUCCESS,
+ invokeCanAuthenticate(mBiometricService, Authenticators.DEVICE_CREDENTIAL));
+ }
+
+ @Test
+ public void testCanAuthenticate_whenNoBiometricsEnrolled() throws Exception {
+ // With credential set up, test the following.
+ when(mTrustManager.isDeviceSecure(anyInt())).thenReturn(true);
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG,
+ false /* enrolled */);
+
+ // When only biometric is requested
+ int authenticators = Authenticators.BIOMETRIC_STRONG;
+ assertEquals(BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED,
+ invokeCanAuthenticate(mBiometricService, authenticators));
+
+ // When credential and biometric are requested
+ authenticators = Authenticators.BIOMETRIC_STRONG | Authenticators.DEVICE_CREDENTIAL;
+ assertEquals(BiometricManager.BIOMETRIC_SUCCESS,
+ invokeCanAuthenticate(mBiometricService, authenticators));
+ }
+
+ @Test
+ public void testCanAuthenticate_whenBiometricsNotEnabledForApps() throws Exception {
+ setupAuthForOnly(BiometricAuthenticator.TYPE_FACE, Authenticators.BIOMETRIC_STRONG);
+ when(mBiometricService.mSettingObserver.getFaceEnabledForApps(anyInt())).thenReturn(false);
+ when(mTrustManager.isDeviceSecure(anyInt())).thenReturn(true);
+
+ // When only biometric is requested
+ int authenticators = Authenticators.BIOMETRIC_STRONG;
+ assertEquals(BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE,
+ invokeCanAuthenticate(mBiometricService, authenticators));
+
+ // When credential and biometric are requested
+ authenticators = Authenticators.BIOMETRIC_STRONG | Authenticators.DEVICE_CREDENTIAL;
+ assertEquals(BiometricManager.BIOMETRIC_SUCCESS,
+ invokeCanAuthenticate(mBiometricService, authenticators));
+ }
+
+ @Test
+ public void testCanAuthenticate_whenNoBiometricSensor() throws Exception {
+ mBiometricService = new BiometricService(mContext, mInjector);
+ mBiometricService.onStart();
+
+ // When only biometric is requested
+ int authenticators = Authenticators.BIOMETRIC_STRONG;
+ assertEquals(BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE,
+ invokeCanAuthenticate(mBiometricService, authenticators));
+
+ // When credential and biometric are requested, and credential is not set up
+ authenticators = Authenticators.BIOMETRIC_STRONG | Authenticators.DEVICE_CREDENTIAL;
+ assertEquals(BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED,
+ invokeCanAuthenticate(mBiometricService, authenticators));
+
+ // When credential and biometric are requested, and credential is set up
+ when(mTrustManager.isDeviceSecure(anyInt())).thenReturn(true);
+ assertEquals(BiometricManager.BIOMETRIC_SUCCESS,
+ invokeCanAuthenticate(mBiometricService, authenticators));
+ }
+
+ @Test
+ public void testAuthenticatorActualStrength() {
+ // Tuple of OEM config, updatedStrength, and expectedStrength
+ final int[][] testCases = {
+ // Downgrades to the specified strength
+ {Authenticators.BIOMETRIC_STRONG, Authenticators.BIOMETRIC_WEAK,
+ Authenticators.BIOMETRIC_WEAK},
+
+ // Cannot be upgraded
+ {Authenticators.BIOMETRIC_WEAK, Authenticators.BIOMETRIC_STRONG,
+ Authenticators.BIOMETRIC_WEAK},
+
+ // Downgrades to convenience
+ {Authenticators.BIOMETRIC_WEAK, Authenticators.BIOMETRIC_CONVENIENCE,
+ Authenticators.BIOMETRIC_CONVENIENCE},
+
+ // EMPTY_SET does not modify specified strength
+ {Authenticators.BIOMETRIC_WEAK, Authenticators.EMPTY_SET,
+ Authenticators.BIOMETRIC_WEAK},
+ };
+
+ for (int i = 0; i < testCases.length; i++) {
+ final BiometricService.AuthenticatorWrapper authenticator =
+ new BiometricService.AuthenticatorWrapper(0 /* id */,
+ BiometricAuthenticator.TYPE_FINGERPRINT,
+ testCases[i][0],
+ null /* impl */);
+ authenticator.updateStrength(testCases[i][1]);
+ assertEquals(testCases[i][2], authenticator.getActualStrength());
+ }
+ }
+
+ @Test
+ public void testWithDowngradedAuthenticator() throws Exception {
+ mBiometricService = new BiometricService(mContext, mInjector);
+ mBiometricService.onStart();
+
+ final int testId = 0;
+
+ when(mFingerprintAuthenticator.hasEnrolledTemplates(anyInt(), any()))
+ .thenReturn(true);
+ when(mFingerprintAuthenticator.isHardwareDetected(any())).thenReturn(true);
+ mBiometricService.mImpl.registerAuthenticator(testId /* id */,
+ BiometricAuthenticator.TYPE_FINGERPRINT, Authenticators.BIOMETRIC_STRONG,
+ mFingerprintAuthenticator);
+
+ // Downgrade the authenticator
+ for (BiometricService.AuthenticatorWrapper wrapper : mBiometricService.mAuthenticators) {
+ if (wrapper.id == testId) {
+ wrapper.updateStrength(Authenticators.BIOMETRIC_WEAK);
+ }
+ }
+
+ // STRONG-only auth is not available
+ int authenticators = Authenticators.BIOMETRIC_STRONG;
+ assertEquals(BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE,
+ invokeCanAuthenticate(mBiometricService, authenticators));
+ invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
+ authenticators);
+ waitForIdle();
+ verify(mReceiver1).onError(
+ eq(BiometricAuthenticator.TYPE_NONE),
+ eq(BiometricPrompt.BIOMETRIC_ERROR_HW_NOT_PRESENT),
+ eq(0) /* vendorCode */);
+
+ // Request for weak auth works
+ resetReceiver();
+ authenticators = Authenticators.BIOMETRIC_WEAK;
+ assertEquals(BiometricManager.BIOMETRIC_SUCCESS,
+ invokeCanAuthenticate(mBiometricService, authenticators));
+ invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
+ false /* requireConfirmation */,
+ authenticators);
+ waitForIdle();
+ verify(mBiometricService.mStatusBarService).showAuthenticationDialog(
+ eq(mBiometricService.mCurrentAuthSession.mBundle),
+ any(IBiometricServiceReceiverInternal.class),
+ eq(BiometricAuthenticator.TYPE_FINGERPRINT /* biometricModality */),
+ anyBoolean() /* requireConfirmation */,
+ anyInt() /* userId */,
+ eq(TEST_PACKAGE_NAME));
+
+ // Requesting strong and credential, when credential is setup
+ resetReceiver();
+ authenticators = Authenticators.BIOMETRIC_STRONG | Authenticators.DEVICE_CREDENTIAL;
+ when(mTrustManager.isDeviceSecure(anyInt())).thenReturn(true);
+ assertEquals(BiometricManager.BIOMETRIC_SUCCESS,
+ invokeCanAuthenticate(mBiometricService, authenticators));
+ invokeAuthenticate(mBiometricService.mImpl, mReceiver1,
+ false /* requireConfirmation */,
+ authenticators);
+ waitForIdle();
+ assertTrue(Utils.isDeviceCredentialAllowed(mBiometricService.mCurrentAuthSession.mBundle));
+ verify(mBiometricService.mStatusBarService).showAuthenticationDialog(
+ eq(mBiometricService.mCurrentAuthSession.mBundle),
+ any(IBiometricServiceReceiverInternal.class),
+ eq(BiometricAuthenticator.TYPE_NONE /* biometricModality */),
+ anyBoolean() /* requireConfirmation */,
+ anyInt() /* userId */,
+ eq(TEST_PACKAGE_NAME));
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void testRegistrationWithDuplicateId_throwsIllegalStateException() throws Exception {
+ mBiometricService = new BiometricService(mContext, mInjector);
+ mBiometricService.onStart();
+
+ mBiometricService.mImpl.registerAuthenticator(
+ 0 /* id */, 2 /* modality */, 15 /* strength */,
+ mFingerprintAuthenticator);
+ mBiometricService.mImpl.registerAuthenticator(
+ 0 /* id */, 2 /* modality */, 15 /* strength */,
+ mFingerprintAuthenticator);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void testRegistrationWithUnknownId_throwsIllegalStateException() throws Exception {
+ mBiometricService = new BiometricService(mContext, mInjector);
+ mBiometricService.onStart();
+
+ mBiometricService.mImpl.registerAuthenticator(
+ 100 /* id */, 2 /* modality */, 15 /* strength */,
+ mFingerprintAuthenticator);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void testRegistrationWithUnsupportedStrength_throwsIllegalStateException()
+ throws Exception {
+ mBiometricService = new BiometricService(mContext, mInjector);
+ mBiometricService.onStart();
+
+ // Only STRONG and WEAK are supported. Let's enforce that CONVENIENCE cannot be
+ // registered. If there is a compelling reason, we can remove this constraint.
+ mBiometricService.mImpl.registerAuthenticator(
+ 0 /* id */, 2 /* modality */,
+ Authenticators.BIOMETRIC_CONVENIENCE /* strength */,
+ mFingerprintAuthenticator);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testRegistrationWithNullAuthenticator_throwsIllegalArgumentException()
+ throws Exception {
+ mBiometricService = new BiometricService(mContext, mInjector);
+ mBiometricService.onStart();
+
+ mBiometricService.mImpl.registerAuthenticator(
+ 0 /* id */, 2 /* modality */,
+ Authenticators.BIOMETRIC_STRONG /* strength */,
+ null /* authenticator */);
+ }
+
+ @Test
+ public void testRegistrationHappyPath_isOk() throws Exception {
+ // This is being tested in many of the other cases, but here's the base case.
+ mBiometricService = new BiometricService(mContext, mInjector);
+ mBiometricService.onStart();
+
+ for (String s : mInjector.getConfiguration(null)) {
+ SensorConfig config = new SensorConfig(s);
+ mBiometricService.mImpl.registerAuthenticator(config.mId, config.mModality,
+ config.mStrength, mFingerprintAuthenticator);
+ }
+ }
+
// Helper methods
- private void setupAuthForOnly(int modality) throws RemoteException {
+ private int invokeCanAuthenticate(BiometricService service, int authenticators)
+ throws Exception {
+ return service.mImpl.canAuthenticate(TEST_PACKAGE_NAME, 0 /* userId */, authenticators);
+ }
+
+ private void setupAuthForOnly(int modality, int strength) throws Exception {
+ setupAuthForOnly(modality, strength, true /* enrolled */);
+ }
+
+ // TODO: Reconcile the registration strength with the injector
+ private void setupAuthForOnly(int modality, int strength, boolean enrolled) throws Exception {
mBiometricService = new BiometricService(mContext, mInjector);
mBiometricService.onStart();
when(mBiometricService.mSettingObserver.getFaceEnabledForApps(anyInt())).thenReturn(true);
- if (modality == BiometricAuthenticator.TYPE_FINGERPRINT) {
- when(mFingerprintAuthenticator.hasEnrolledTemplates(anyInt(), any())).thenReturn(true);
+ if ((modality & BiometricAuthenticator.TYPE_FINGERPRINT) != 0) {
+ when(mFingerprintAuthenticator.hasEnrolledTemplates(anyInt(), any()))
+ .thenReturn(enrolled);
when(mFingerprintAuthenticator.isHardwareDetected(any())).thenReturn(true);
- mBiometricService.mImpl.registerAuthenticator(0 /* id */, STRENGTH_STRONG, modality,
+ mBiometricService.mImpl.registerAuthenticator(0 /* id */, modality, strength,
mFingerprintAuthenticator);
- } else if (modality == BiometricAuthenticator.TYPE_FACE) {
- when(mFaceAuthenticator.hasEnrolledTemplates(anyInt(), any())).thenReturn(true);
+ }
+
+ if ((modality & BiometricAuthenticator.TYPE_FACE) != 0) {
+ when(mFaceAuthenticator.hasEnrolledTemplates(anyInt(), any())).thenReturn(enrolled);
when(mFaceAuthenticator.isHardwareDetected(any())).thenReturn(true);
- mBiometricService.mImpl.registerAuthenticator(0 /* id */, STRENGTH_STRONG, modality,
+ mBiometricService.mImpl.registerAuthenticator(1 /* id */, modality, strength,
mFaceAuthenticator);
- } else {
- fail("Unknown modality: " + modality);
+ }
+ }
+
+ // TODO: Reduce duplicated code, currently we cannot start the BiometricService in setUp() for
+ // all tests.
+ private void setupAuthForMultiple(int[] modalities, int[] strengths) throws RemoteException {
+ mBiometricService = new BiometricService(mContext, mInjector);
+ mBiometricService.onStart();
+
+ when(mBiometricService.mSettingObserver.getFaceEnabledForApps(anyInt())).thenReturn(true);
+
+ assertEquals(modalities.length, strengths.length);
+
+ for (int i = 0; i < modalities.length; i++) {
+ final int modality = modalities[i];
+ final int strength = strengths[i];
+
+ if ((modality & BiometricAuthenticator.TYPE_FINGERPRINT) != 0) {
+ when(mFingerprintAuthenticator.hasEnrolledTemplates(anyInt(), any()))
+ .thenReturn(true);
+ when(mFingerprintAuthenticator.isHardwareDetected(any())).thenReturn(true);
+ mBiometricService.mImpl.registerAuthenticator(0 /* id */, modality, strength,
+ mFingerprintAuthenticator);
+ }
+
+ if ((modality & BiometricAuthenticator.TYPE_FACE) != 0) {
+ when(mFaceAuthenticator.hasEnrolledTemplates(anyInt(), any())).thenReturn(true);
+ when(mFaceAuthenticator.isHardwareDetected(any())).thenReturn(true);
+ mBiometricService.mImpl.registerAuthenticator(1 /* id */, modality, strength,
+ mFaceAuthenticator);
+ }
}
}
@@ -885,9 +1278,9 @@ public class BiometricServiceTest {
private void invokeAuthenticateAndStart(IBiometricService.Stub service,
IBiometricServiceReceiver receiver, boolean requireConfirmation,
- boolean allowDeviceCredential) throws Exception {
+ Integer authenticators) throws Exception {
// Request auth, creates a pending session
- invokeAuthenticate(service, receiver, requireConfirmation, allowDeviceCredential);
+ invokeAuthenticate(service, receiver, requireConfirmation, authenticators);
waitForIdle();
startPendingAuthSession(mBiometricService);
@@ -908,23 +1301,24 @@ public class BiometricServiceTest {
private static void invokeAuthenticate(IBiometricService.Stub service,
IBiometricServiceReceiver receiver, boolean requireConfirmation,
- boolean allowDeviceCredential) throws Exception {
+ Integer authenticators) throws Exception {
service.authenticate(
new Binder() /* token */,
0 /* sessionId */,
0 /* userId */,
receiver,
TEST_PACKAGE_NAME /* packageName */,
- createTestBiometricPromptBundle(requireConfirmation, allowDeviceCredential));
+ createTestBiometricPromptBundle(requireConfirmation, authenticators));
}
- private static Bundle createTestBiometricPromptBundle(boolean requireConfirmation,
- boolean allowDeviceCredential) {
+ private static Bundle createTestBiometricPromptBundle(
+ boolean requireConfirmation,
+ Integer authenticators) {
final Bundle bundle = new Bundle();
bundle.putBoolean(BiometricPrompt.KEY_REQUIRE_CONFIRMATION, requireConfirmation);
- if (allowDeviceCredential) {
- bundle.putBoolean(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL, true);
+ if (authenticators != null) {
+ bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
}
return bundle;
}
diff --git a/services/tests/servicestests/src/com/android/server/biometrics/OWNERS b/services/tests/servicestests/src/com/android/server/biometrics/OWNERS
new file mode 100644
index 000000000000..8765c9a64b77
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/biometrics/OWNERS
@@ -0,0 +1,7 @@
+set noparent
+
+kchyn@google.com
+jaggies@google.com
+curtislb@google.com
+ilyamaty@google.com
+joshmccloskey@google.com
diff --git a/services/tests/servicestests/src/com/android/server/biometrics/UtilsTest.java b/services/tests/servicestests/src/com/android/server/biometrics/UtilsTest.java
new file mode 100644
index 000000000000..abe39f0934db
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/biometrics/UtilsTest.java
@@ -0,0 +1,226 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.biometrics;
+
+import static android.hardware.biometrics.BiometricManager.Authenticators;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+
+import static org.junit.Assert.assertNull;
+
+import android.hardware.biometrics.BiometricConstants;
+import android.hardware.biometrics.BiometricManager;
+import android.hardware.biometrics.BiometricPrompt;
+import android.os.Bundle;
+
+import androidx.test.filters.SmallTest;
+
+import org.junit.Test;
+
+@SmallTest
+public class UtilsTest {
+
+ @Test
+ public void testCombineAuthenticatorBundles_withKeyDeviceCredential_andKeyAuthenticators() {
+ final boolean allowDeviceCredential = false;
+ final @Authenticators.Types int authenticators =
+ Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_WEAK;
+ final Bundle bundle = new Bundle();
+
+ bundle.putBoolean(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL, allowDeviceCredential);
+ bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
+ Utils.combineAuthenticatorBundles(bundle);
+
+ assertNull(bundle.get(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL));
+ assertEquals(bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED), authenticators);
+ }
+
+ @Test
+ public void testCombineAuthenticatorBundles_withNoKeyDeviceCredential_andKeyAuthenticators() {
+ final @Authenticators.Types int authenticators =
+ Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_WEAK;
+ final Bundle bundle = new Bundle();
+
+ bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
+ Utils.combineAuthenticatorBundles(bundle);
+
+ assertNull(bundle.get(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL));
+ assertEquals(bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED), authenticators);
+ }
+
+ @Test
+ public void testCombineAuthenticatorBundles_withKeyDeviceCredential_andNoKeyAuthenticators() {
+ final boolean allowDeviceCredential = true;
+ final Bundle bundle = new Bundle();
+
+ bundle.putBoolean(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL, allowDeviceCredential);
+ Utils.combineAuthenticatorBundles(bundle);
+
+ assertNull(bundle.get(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL));
+ assertEquals(bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED),
+ Authenticators.DEVICE_CREDENTIAL | Authenticators.BIOMETRIC_WEAK);
+ }
+
+ @Test
+ public void testCombineAuthenticatorBundles_withNoKeyDeviceCredential_andNoKeyAuthenticators() {
+ final Bundle bundle = new Bundle();
+
+ Utils.combineAuthenticatorBundles(bundle);
+
+ assertNull(bundle.get(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL));
+ assertEquals(bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED),
+ Authenticators.BIOMETRIC_WEAK);
+ }
+
+ @Test
+ public void testIsDeviceCredentialAllowed_withIntegerFlags() {
+ int authenticators = 0;
+ assertFalse(Utils.isDeviceCredentialAllowed(authenticators));
+
+ authenticators |= Authenticators.DEVICE_CREDENTIAL;
+ assertTrue(Utils.isDeviceCredentialAllowed(authenticators));
+
+ authenticators |= Authenticators.BIOMETRIC_WEAK;
+ assertTrue(Utils.isDeviceCredentialAllowed(authenticators));
+ }
+
+ @Test
+ public void testIsDeviceCredentialAllowed_withBundle() {
+ Bundle bundle = new Bundle();
+ assertFalse(Utils.isDeviceCredentialAllowed(bundle));
+
+ int authenticators = 0;
+ bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
+ assertFalse(Utils.isDeviceCredentialAllowed(bundle));
+
+ authenticators |= Authenticators.DEVICE_CREDENTIAL;
+ bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
+ assertTrue(Utils.isDeviceCredentialAllowed(bundle));
+
+ authenticators |= Authenticators.BIOMETRIC_WEAK;
+ bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
+ assertTrue(Utils.isDeviceCredentialAllowed(bundle));
+ }
+
+ @Test
+ public void testGetBiometricStrength_removeUnrelatedBits() {
+ // BIOMETRIC_MIN_STRENGTH uses all of the allowed bits for biometric strength, so any other
+ // bits aside from these should be clipped off.
+
+ int authenticators = Integer.MAX_VALUE;
+ assertEquals(Authenticators.BIOMETRIC_WEAK,
+ Utils.getPublicBiometricStrength(authenticators));
+
+ Bundle bundle = new Bundle();
+ bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
+ assertEquals(Authenticators.BIOMETRIC_WEAK, Utils.getPublicBiometricStrength(bundle));
+ }
+
+ @Test
+ public void testIsBiometricAllowed() {
+ // Only the lowest 8 bits (BIOMETRIC_WEAK mask) are allowed to integrate with the
+ // Biometric APIs
+ Bundle bundle = new Bundle();
+ for (int i = 0; i <= 7; i++) {
+ int authenticators = 1 << i;
+ bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
+ assertTrue(Utils.isBiometricAllowed(bundle));
+ }
+
+ // The rest of the bits are not allowed to integrate with the public APIs
+ for (int i = 8; i < 32; i++) {
+ int authenticators = 1 << i;
+ bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
+ assertFalse(Utils.isBiometricAllowed(bundle));
+ }
+ }
+
+ @Test
+ public void testIsValidAuthenticatorConfig() {
+ assertTrue(Utils.isValidAuthenticatorConfig(Authenticators.EMPTY_SET));
+
+ assertTrue(Utils.isValidAuthenticatorConfig(Authenticators.BIOMETRIC_STRONG));
+
+ assertTrue(Utils.isValidAuthenticatorConfig(Authenticators.BIOMETRIC_WEAK));
+
+ assertTrue(Utils.isValidAuthenticatorConfig(Authenticators.DEVICE_CREDENTIAL));
+
+ assertTrue(Utils.isValidAuthenticatorConfig(Authenticators.DEVICE_CREDENTIAL
+ | Authenticators.BIOMETRIC_STRONG));
+
+ assertTrue(Utils.isValidAuthenticatorConfig(Authenticators.DEVICE_CREDENTIAL
+ | Authenticators.BIOMETRIC_WEAK));
+
+ assertFalse(Utils.isValidAuthenticatorConfig(Authenticators.BIOMETRIC_CONVENIENCE));
+
+ assertFalse(Utils.isValidAuthenticatorConfig(Authenticators.BIOMETRIC_CONVENIENCE
+ | Authenticators.DEVICE_CREDENTIAL));
+
+ assertFalse(Utils.isValidAuthenticatorConfig(Authenticators.BIOMETRIC_MAX_STRENGTH));
+
+ assertFalse(Utils.isValidAuthenticatorConfig(Authenticators.BIOMETRIC_MIN_STRENGTH));
+
+ // The rest of the bits are not allowed to integrate with the public APIs
+ for (int i = 8; i < 32; i++) {
+ final int authenticator = 1 << i;
+ if (authenticator == Authenticators.DEVICE_CREDENTIAL) {
+ continue;
+ }
+ assertFalse(Utils.isValidAuthenticatorConfig(1 << i));
+ }
+ }
+
+ @Test
+ public void testIsAtLeastStrength() {
+ int sensorStrength = Authenticators.BIOMETRIC_STRONG;
+ int requestedStrength = Authenticators.BIOMETRIC_WEAK;
+ assertTrue(Utils.isAtLeastStrength(sensorStrength, requestedStrength));
+
+ requestedStrength = Authenticators.BIOMETRIC_STRONG;
+ assertTrue(Utils.isAtLeastStrength(sensorStrength, requestedStrength));
+
+ sensorStrength = Authenticators.BIOMETRIC_WEAK;
+ requestedStrength = Authenticators.BIOMETRIC_STRONG;
+ assertFalse(Utils.isAtLeastStrength(sensorStrength, requestedStrength));
+
+ requestedStrength = Authenticators.BIOMETRIC_WEAK;
+ assertTrue(Utils.isAtLeastStrength(sensorStrength, requestedStrength));
+ }
+
+ @Test
+ public void testBiometricConstantsConversion() {
+ final int[][] testCases = {
+ {BiometricConstants.BIOMETRIC_SUCCESS,
+ BiometricManager.BIOMETRIC_SUCCESS},
+ {BiometricConstants.BIOMETRIC_ERROR_NO_BIOMETRICS,
+ BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED},
+ {BiometricConstants.BIOMETRIC_ERROR_NO_DEVICE_CREDENTIAL,
+ BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED},
+ {BiometricConstants.BIOMETRIC_ERROR_HW_UNAVAILABLE,
+ BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE},
+ {BiometricConstants.BIOMETRIC_ERROR_HW_NOT_PRESENT,
+ BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE}
+ };
+
+ for (int i = 0; i < testCases.length; i++) {
+ assertEquals(testCases[i][1],
+ Utils.biometricConstantsToBiometricManager(testCases[i][0]));
+ }
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/compat/CompatConfigTest.java b/services/tests/servicestests/src/com/android/server/compat/CompatConfigTest.java
index 72679769be8e..cb99c118a407 100644
--- a/services/tests/servicestests/src/com/android/server/compat/CompatConfigTest.java
+++ b/services/tests/servicestests/src/com/android/server/compat/CompatConfigTest.java
@@ -22,15 +22,13 @@ import android.content.pm.ApplicationInfo;
import androidx.test.runner.AndroidJUnit4;
-import com.android.compat.annotation.Change;
-import com.android.compat.annotation.XmlWriter;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.io.OutputStream;
import java.util.UUID;
@RunWith(AndroidJUnit4.class)
@@ -50,18 +48,10 @@ public class CompatConfigTest {
return dir;
}
- private void writeChangesToFile(Change[] changes, File f) {
- XmlWriter writer = new XmlWriter();
- for (Change change: changes) {
- writer.addChange(change);
- }
- try {
- f.createNewFile();
- writer.write(new FileOutputStream(f));
- } catch (IOException e) {
- throw new RuntimeException(
- "Encountered an error while writing compat config file", e);
- }
+ private void writeToFile(File dir, String filename, String content) throws IOException {
+ OutputStream os = new FileOutputStream(new File(dir, filename));
+ os.write(content.getBytes());
+ os.close();
}
@Test
@@ -173,13 +163,15 @@ public class CompatConfigTest {
}
@Test
- public void testReadConfig() {
- Change[] changes = {new Change(1234L, "MY_CHANGE1", false, 2, null), new Change(1235L,
- "MY_CHANGE2", true, null, "description"), new Change(1236L, "MY_CHANGE3", false,
- null, "")};
+ public void testReadConfig() throws IOException {
+ String configXml = "<config>"
+ + "<compat-change id=\"1234\" name=\"MY_CHANGE1\" enableAfterTargetSdk=\"2\" />"
+ + "<compat-change id=\"1235\" name=\"MY_CHANGE2\" disabled=\"true\" />"
+ + "<compat-change id=\"1236\" name=\"MY_CHANGE3\" />"
+ + "</config>";
File dir = createTempDir();
- writeChangesToFile(changes, new File(dir.getPath() + "/platform_compat_config.xml"));
+ writeToFile(dir, "platform_compat_config.xml", configXml);
CompatConfig pc = new CompatConfig();
pc.initConfigFromLib(dir);
@@ -191,17 +183,18 @@ public class CompatConfigTest {
}
@Test
- public void testReadConfigMultipleFiles() {
- Change[] changes1 = {new Change(1234L, "MY_CHANGE1", false, 2, null)};
- Change[] changes2 = {new Change(1235L, "MY_CHANGE2", true, null, ""), new Change(1236L,
- "MY_CHANGE3", false, null, null)};
+ public void testReadConfigMultipleFiles() throws IOException {
+ String configXml1 = "<config>"
+ + "<compat-change id=\"1234\" name=\"MY_CHANGE1\" enableAfterTargetSdk=\"2\" />"
+ + "</config>";
+ String configXml2 = "<config>"
+ + "<compat-change id=\"1235\" name=\"MY_CHANGE2\" disabled=\"true\" />"
+ + "<compat-change id=\"1236\" name=\"MY_CHANGE3\" />"
+ + "</config>";
File dir = createTempDir();
- writeChangesToFile(changes1,
- new File(dir.getPath() + "/libcore_platform_compat_config.xml"));
- writeChangesToFile(changes2,
- new File(dir.getPath() + "/frameworks_platform_compat_config.xml"));
-
+ writeToFile(dir, "libcore_platform_compat_config.xml", configXml1);
+ writeToFile(dir, "frameworks_platform_compat_config.xml", configXml2);
CompatConfig pc = new CompatConfig();
pc.initConfigFromLib(dir);
diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
index 43d8f927a57e..4fcfa32c3c3b 100644
--- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
@@ -100,7 +100,6 @@ import com.android.internal.widget.LockscreenCredential;
import com.android.server.LocalServices;
import com.android.server.SystemService;
import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
-import com.android.server.pm.UserRestrictionsUtils;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
@@ -1162,7 +1161,8 @@ public class DevicePolicyManagerTest extends DpmTestBase {
MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
- eq(UserHandle.USER_SYSTEM), eq(null),
+ eq(UserHandle.USER_SYSTEM),
+ MockUtils.checkUserRestrictions(),
eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
@@ -1718,28 +1718,6 @@ public class DevicePolicyManagerTest extends DpmTestBase {
assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
UserHandle.USER_SYSTEM));
- // Check that the user restrictions that are enabled by default are set. Then unset them.
- final String[] defaultRestrictions = UserRestrictionsUtils
- .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
- DpmTestUtils.assertRestrictions(
- DpmTestUtils.newRestrictions(defaultRestrictions),
- dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
- );
- DpmTestUtils.assertRestrictions(
- DpmTestUtils.newRestrictions(defaultRestrictions),
- dpm.getUserRestrictions(admin1)
- );
- verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
- eq(UserHandle.USER_SYSTEM),
- MockUtils.checkUserRestrictions(defaultRestrictions),
- eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER)
- );
- reset(getServices().userManagerInternal);
-
- for (String restriction : defaultRestrictions) {
- dpm.clearUserRestriction(admin1, restriction);
- }
-
assertNoDeviceOwnerRestrictions();
reset(getServices().userManagerInternal);
@@ -1966,7 +1944,6 @@ public class DevicePolicyManagerTest extends DpmTestBase {
// TODO Make sure restrictions are written to the file.
}
- // TODO: (b/138709470) test addUserRestriction as PO of an organization-owned device
public void testSetUserRestriction_asPoOfOrgOwnedDevice() throws Exception {
final int MANAGED_PROFILE_USER_ID = DpmMockContext.CALLER_USER_HANDLE;
final int MANAGED_PROFILE_ADMIN_UID =
@@ -1979,22 +1956,32 @@ public class DevicePolicyManagerTest extends DpmTestBase {
when(getServices().userManager.getProfileParent(MANAGED_PROFILE_USER_ID))
.thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
+ parentDpm.addUserRestriction(admin1, UserManager.DISALLOW_CONFIG_DATE_TIME);
+ verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
+ eq(MANAGED_PROFILE_USER_ID),
+ MockUtils.checkUserRestrictions(UserManager.DISALLOW_CONFIG_DATE_TIME),
+ eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE));
+ reset(getServices().userManagerInternal);
+
+ parentDpm.clearUserRestriction(admin1, UserManager.DISALLOW_CONFIG_DATE_TIME);
+ reset(getServices().userManagerInternal);
+
parentDpm.setCameraDisabled(admin1, true);
verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
- eq(UserHandle.USER_SYSTEM),
+ eq(MANAGED_PROFILE_USER_ID),
MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE));
reset(getServices().userManagerInternal);
parentDpm.setCameraDisabled(admin1, false);
verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
- eq(UserHandle.USER_SYSTEM),
+ eq(MANAGED_PROFILE_USER_ID),
MockUtils.checkUserRestrictions(),
eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE));
reset(getServices().userManagerInternal);
}
- public void testDefaultEnabledUserRestrictions() throws Exception {
+ public void testNoDefaultEnabledUserRestrictions() throws Exception {
mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
mContext.callerPermissions.add(permission.MANAGE_USERS);
mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
@@ -2012,29 +1999,6 @@ public class DevicePolicyManagerTest extends DpmTestBase {
assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
UserHandle.USER_SYSTEM));
- // Check that the user restrictions that are enabled by default are set. Then unset them.
- String[] defaultRestrictions = UserRestrictionsUtils
- .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
- assertTrue(defaultRestrictions.length > 0);
- DpmTestUtils.assertRestrictions(
- DpmTestUtils.newRestrictions(defaultRestrictions),
- dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
- );
- DpmTestUtils.assertRestrictions(
- DpmTestUtils.newRestrictions(defaultRestrictions),
- dpm.getUserRestrictions(admin1)
- );
- verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
- eq(UserHandle.USER_SYSTEM),
- MockUtils.checkUserRestrictions(defaultRestrictions),
- eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER)
- );
- reset(getServices().userManagerInternal);
-
- for (String restriction : defaultRestrictions) {
- dpm.clearUserRestriction(admin1, restriction);
- }
-
assertNoDeviceOwnerRestrictions();
// Initialize DPMS again and check that the user restriction wasn't enabled again.
@@ -2044,47 +2008,6 @@ public class DevicePolicyManagerTest extends DpmTestBase {
assertNotNull(dpms.getDeviceOwnerAdminLocked());
assertNoDeviceOwnerRestrictions();
-
- // Add a new restriction to the default set, initialize DPMS, and check that the restriction
- // is set as it wasn't enabled during setDeviceOwner.
- final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
- assertFalse(UserRestrictionsUtils
- .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
- UserRestrictionsUtils
- .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
- try {
- reset(getServices().userManagerInternal);
- initializeDpms();
- assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
- assertNotNull(dpms.getDeviceOwnerAdminLocked());
-
- DpmTestUtils.assertRestrictions(
- DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
- dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
- );
- DpmTestUtils.assertRestrictions(
- DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
- dpm.getUserRestrictions(admin1)
- );
- verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
- eq(UserHandle.USER_SYSTEM),
- MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
- eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER)
- );
- reset(getServices().userManagerInternal);
-
- // Remove the restriction.
- dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
-
- // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
- initializeDpms();
- assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
- assertNotNull(dpms.getDeviceOwnerAdminLocked());
- assertNoDeviceOwnerRestrictions();
- } finally {
- UserRestrictionsUtils
- .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
- }
}
private void assertNoDeviceOwnerRestrictions() {
@@ -3673,6 +3596,45 @@ public class DevicePolicyManagerTest extends DpmTestBase {
verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
}
+ public void testSetAutoTimeZoneModifiesSetting() throws Exception {
+ mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
+ setupDeviceOwner();
+ dpm.setAutoTimeZone(admin1, true);
+ verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 1);
+
+ dpm.setAutoTimeZone(admin1, false);
+ verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0);
+ }
+
+ public void testSetAutoTimeZoneWithPOOnUser0() throws Exception {
+ mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
+ setupProfileOwnerOnUser0();
+ dpm.setAutoTimeZone(admin1, true);
+ verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 1);
+
+ dpm.setAutoTimeZone(admin1, false);
+ verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0);
+ }
+
+ public void testSetAutoTimeZoneFailWithPONotOnUser0() throws Exception {
+ setupProfileOwner();
+ assertExpectException(SecurityException.class, null,
+ () -> dpm.setAutoTimeZone(admin1, false));
+ verify(getServices().settings, never()).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE,
+ 0);
+ }
+
+ public void testSetAutoTimeZoneWithPOOfOrganizationOwnedDevice() throws Exception {
+ setupProfileOwner();
+ configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
+
+ dpm.setAutoTimeZone(admin1, true);
+ verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 1);
+
+ dpm.setAutoTimeZone(admin1, false);
+ verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0);
+ }
+
public void testSetTime() throws Exception {
mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
setupDeviceOwner();
@@ -5548,6 +5510,38 @@ public class DevicePolicyManagerTest extends DpmTestBase {
mServiceContext.binder.restoreCallingIdentity(ident);
}
+ public void testGetCrossProfilePackages_notSet_returnsEmpty() {
+ setAsProfileOwner(admin1);
+ assertTrue(dpm.getCrossProfilePackages(admin1).isEmpty());
+ }
+
+ public void testGetCrossProfilePackages_notSet_dpmsReinitialized_returnsEmpty() {
+ setAsProfileOwner(admin1);
+
+ initializeDpms();
+
+ assertTrue(dpm.getCrossProfilePackages(admin1).isEmpty());
+ }
+
+ public void testGetCrossProfilePackages_whenSet_returnsEqual() {
+ setAsProfileOwner(admin1);
+ Set<String> packages = Collections.singleton("TEST_PACKAGE");
+
+ dpm.setCrossProfilePackages(admin1, packages);
+
+ assertEquals(packages, dpm.getCrossProfilePackages(admin1));
+ }
+
+ public void testGetCrossProfilePackages_whenSet_dpmsReinitialized_returnsEqual() {
+ setAsProfileOwner(admin1);
+ Set<String> packages = Collections.singleton("TEST_PACKAGE");
+
+ dpm.setCrossProfilePackages(admin1, packages);
+ initializeDpms();
+
+ assertEquals(packages, dpm.getCrossProfilePackages(admin1));
+ }
+
// admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java b/services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java
index 7a2350eb4402..919a3f6d7d1b 100644
--- a/services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java
+++ b/services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java
@@ -35,6 +35,7 @@ import android.app.timedetector.TimeDetector;
import android.app.timezonedetector.TimeZoneDetector;
import android.app.usage.UsageStatsManagerInternal;
import android.content.BroadcastReceiver;
+import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
@@ -162,6 +163,8 @@ public class MockSystemServices {
// Package manager is huge, so we use a partial mock instead.
packageManager = spy(realContext.getPackageManager());
+ when(packageManagerInternal.getSystemUiServiceComponent()).thenReturn(
+ new ComponentName("com.android.systemui", ".Service"));
contentResolver = new MockContentResolver();
contentResolver.addProvider("telephony", new MockContentProvider(realContext) {
diff --git a/services/tests/servicestests/src/com/android/server/display/AutomaticBrightnessControllerTest.java b/services/tests/servicestests/src/com/android/server/display/AutomaticBrightnessControllerTest.java
new file mode 100644
index 000000000000..f6c4d3aa5f5f
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/display/AutomaticBrightnessControllerTest.java
@@ -0,0 +1,192 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.display;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyFloat;
+import static org.mockito.Mockito.anyInt;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.hardware.Sensor;
+import android.hardware.SensorEventListener;
+import android.hardware.SensorManager;
+import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest;
+import android.os.Handler;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class AutomaticBrightnessControllerTest {
+
+ private static final int BRIGHTNESS_MIN = 1;
+ private static final int BRIGHTNESS_MAX = 255;
+ private static final int LIGHT_SENSOR_RATE = 20;
+ private static final int INITIAL_LIGHT_SENSOR_RATE = 20;
+ private static final int BRIGHTENING_LIGHT_DEBOUNCE_CONFIG = 0;
+ private static final int DARKENING_LIGHT_DEBOUNCE_CONFIG = 0;
+ private static final int SHORT_TERM_MODEL_TIMEOUT = 0;
+ private static final float DOZE_SCALE_FACTOR = 0.0f;
+ private static final boolean RESET_AMBIENT_LUX_AFTER_WARMUP_CONFIG = false;
+
+ private Context mContext;
+ @Mock SensorManager mSensorManager;
+ @Mock BrightnessMappingStrategy mBrightnessMappingStrategy;
+ @Mock HysteresisLevels mAmbientBrightnessThresholds;
+ @Mock HysteresisLevels mScreenBrightnessThresholds;
+ @Mock PackageManager mPackageManager;
+ @Mock Handler mNoopHandler;
+
+ private static final int LIGHT_SENSOR_WARMUP_TIME = 0;
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+
+ mContext = InstrumentationRegistry.getContext();
+ }
+
+ private AutomaticBrightnessController setupController(Sensor lightSensor) {
+ AutomaticBrightnessController controller = new AutomaticBrightnessController(
+ new AutomaticBrightnessController.Injector() {
+ @Override
+ public Handler getBackgroundThreadHandler() {
+ return mNoopHandler;
+ }
+ },
+ () -> { }, mContext.getMainLooper(), mSensorManager, lightSensor,
+ mBrightnessMappingStrategy, LIGHT_SENSOR_WARMUP_TIME, BRIGHTNESS_MIN,
+ BRIGHTNESS_MAX, DOZE_SCALE_FACTOR, LIGHT_SENSOR_RATE, INITIAL_LIGHT_SENSOR_RATE,
+ BRIGHTENING_LIGHT_DEBOUNCE_CONFIG, DARKENING_LIGHT_DEBOUNCE_CONFIG,
+ RESET_AMBIENT_LUX_AFTER_WARMUP_CONFIG, mAmbientBrightnessThresholds,
+ mScreenBrightnessThresholds, SHORT_TERM_MODEL_TIMEOUT, mPackageManager);
+ controller.setLoggingEnabled(true);
+
+ // Configure the brightness controller and grab an instance of the sensor listener,
+ // through which we can deliver fake (for test) sensor values.
+ controller.configure(true /* enable */, null /* configuration */,
+ 0 /* brightness */, false /* userChangedBrightness */, 0 /* adjustment */,
+ false /* userChanged */, DisplayPowerRequest.POLICY_BRIGHT);
+
+ return controller;
+ }
+
+ @Test
+ public void testNoHysteresisAtMinBrightness() throws Exception {
+ Sensor lightSensor = TestUtils.createSensor(Sensor.TYPE_LIGHT, "Light Sensor");
+ AutomaticBrightnessController controller = setupController(lightSensor);
+
+ ArgumentCaptor<SensorEventListener> listenerCaptor =
+ ArgumentCaptor.forClass(SensorEventListener.class);
+ verify(mSensorManager).registerListener(listenerCaptor.capture(), eq(lightSensor),
+ eq(INITIAL_LIGHT_SENSOR_RATE * 1000), any(Handler.class));
+ SensorEventListener listener = listenerCaptor.getValue();
+
+ // Set up system to return 5 as a brightness value
+ float lux1 = 100.0f;
+ float normalizedBrightness1 = 0.02f;
+ when(mAmbientBrightnessThresholds.getBrighteningThreshold(lux1))
+ .thenReturn(lux1);
+ when(mAmbientBrightnessThresholds.getDarkeningThreshold(lux1))
+ .thenReturn(lux1);
+ when(mBrightnessMappingStrategy.getBrightness(eq(lux1), eq(null), anyInt()))
+ .thenReturn(normalizedBrightness1);
+
+ // This is the important bit: When the new brightness is set, make sure the new
+ // brightening threshold is beyond the maximum brightness value...so that we can test that
+ // our threshold clamping works.
+ when(mScreenBrightnessThresholds.getBrighteningThreshold(5)).thenReturn(1.0f);
+
+ // Send new sensor value and verify
+ listener.onSensorChanged(TestUtils.createSensorEvent(lightSensor, (int) lux1));
+ assertEquals(5, controller.getAutomaticScreenBrightness());
+
+
+ // Set up system to return 255 as a brightness value
+ float lux2 = 10.0f;
+ float normalizedBrightness2 = 0.0f;
+ when(mAmbientBrightnessThresholds.getBrighteningThreshold(lux2))
+ .thenReturn(lux2);
+ when(mAmbientBrightnessThresholds.getDarkeningThreshold(lux2))
+ .thenReturn(lux2);
+ when(mBrightnessMappingStrategy.getBrightness(anyFloat(), eq(null), anyInt()))
+ .thenReturn(normalizedBrightness2);
+
+ // Send new sensor value and verify
+ listener.onSensorChanged(TestUtils.createSensorEvent(lightSensor, (int) lux2));
+ assertEquals(1, controller.getAutomaticScreenBrightness());
+ }
+
+ @Test
+ public void testNoHysteresisAtMaxBrightness() throws Exception {
+ Sensor lightSensor = TestUtils.createSensor(Sensor.TYPE_LIGHT, "Light Sensor");
+ AutomaticBrightnessController controller = setupController(lightSensor);
+
+ ArgumentCaptor<SensorEventListener> listenerCaptor =
+ ArgumentCaptor.forClass(SensorEventListener.class);
+ verify(mSensorManager).registerListener(listenerCaptor.capture(), eq(lightSensor),
+ eq(INITIAL_LIGHT_SENSOR_RATE * 1000), any(Handler.class));
+ SensorEventListener listener = listenerCaptor.getValue();
+
+ // Set up system to return 250 as a brightness value
+ float lux1 = 100.0f;
+ float normalizedBrightness1 = 0.98f;
+ when(mAmbientBrightnessThresholds.getBrighteningThreshold(lux1))
+ .thenReturn(lux1);
+ when(mAmbientBrightnessThresholds.getDarkeningThreshold(lux1))
+ .thenReturn(lux1);
+ when(mBrightnessMappingStrategy.getBrightness(eq(lux1), eq(null), anyInt()))
+ .thenReturn(normalizedBrightness1);
+
+ // This is the important bit: When the new brightness is set, make sure the new
+ // brightening threshold is beyond the maximum brightness value...so that we can test that
+ // our threshold clamping works.
+ when(mScreenBrightnessThresholds.getBrighteningThreshold(250)).thenReturn(260.0f);
+
+ // Send new sensor value and verify
+ listener.onSensorChanged(TestUtils.createSensorEvent(lightSensor, (int) lux1));
+ assertEquals(250, controller.getAutomaticScreenBrightness());
+
+
+ // Set up system to return 255 as a brightness value
+ float lux2 = 110.0f;
+ float normalizedBrightness2 = 1.0f;
+ when(mAmbientBrightnessThresholds.getBrighteningThreshold(lux2))
+ .thenReturn(lux2);
+ when(mAmbientBrightnessThresholds.getDarkeningThreshold(lux2))
+ .thenReturn(lux2);
+ when(mBrightnessMappingStrategy.getBrightness(anyFloat(), eq(null), anyInt()))
+ .thenReturn(normalizedBrightness2);
+
+ // Send new sensor value and verify
+ listener.onSensorChanged(TestUtils.createSensorEvent(lightSensor, (int) lux2));
+ assertEquals(255, controller.getAutomaticScreenBrightness());
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/display/DisplayManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/display/DisplayManagerServiceTest.java
index 4742a73b17a8..8d5939ad6ef6 100644
--- a/services/tests/servicestests/src/com/android/server/display/DisplayManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/DisplayManagerServiceTest.java
@@ -11,7 +11,7 @@
* 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
+ * limitations under the License.
*/
package com.android.server.display;
diff --git a/services/tests/servicestests/src/com/android/server/display/TestUtils.java b/services/tests/servicestests/src/com/android/server/display/TestUtils.java
new file mode 100644
index 000000000000..859dfe3c3fa4
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/display/TestUtils.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.display;
+
+import android.hardware.Sensor;
+import android.hardware.SensorEvent;
+import android.os.SystemClock;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+
+public final class TestUtils {
+
+ public static SensorEvent createSensorEvent(Sensor sensor, int lux) throws Exception {
+ final Constructor<SensorEvent> constructor =
+ SensorEvent.class.getDeclaredConstructor(int.class);
+ constructor.setAccessible(true);
+ final SensorEvent event = constructor.newInstance(1);
+ event.sensor = sensor;
+ event.values[0] = lux;
+ event.timestamp = SystemClock.elapsedRealtimeNanos();
+ return event;
+ }
+
+
+ public static void setSensorType(Sensor sensor, int type, String strType) throws Exception {
+ Method setter = Sensor.class.getDeclaredMethod("setType", Integer.TYPE);
+ setter.setAccessible(true);
+ setter.invoke(sensor, type);
+ if (strType != null) {
+ Field f = sensor.getClass().getDeclaredField("mStringType");
+ f.setAccessible(true);
+ f.set(sensor, strType);
+ }
+ }
+
+ public static Sensor createSensor(int type, String strType) throws Exception {
+ Constructor<Sensor> constr = Sensor.class.getDeclaredConstructor();
+ constr.setAccessible(true);
+ Sensor sensor = constr.newInstance();
+ setSensorType(sensor, type, strType);
+ return sensor;
+ }
+
+}
diff --git a/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientLuxTest.java b/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientLuxTest.java
index acf2d0e700d4..2565ae3b4a85 100644
--- a/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientLuxTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientLuxTest.java
@@ -16,31 +16,19 @@
package com.android.server.display.whitebalance;
-import com.android.internal.R;
-import com.android.server.display.utils.AmbientFilter;
-import com.android.server.display.utils.AmbientFilterStubber;
-import com.google.common.collect.ImmutableList;
-
import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-import static org.mockito.Mockito.doAnswer;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
-import org.mockito.stubbing.Answer;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.mockito.Spy;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
import android.content.ContextWrapper;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.hardware.Sensor;
-import android.hardware.SensorEvent;
-import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.Looper;
@@ -48,15 +36,22 @@ import android.util.TypedValue;
import androidx.test.InstrumentationRegistry;
+import com.android.internal.R;
+import com.android.server.display.TestUtils;
+import com.android.server.display.utils.AmbientFilter;
+import com.android.server.display.utils.AmbientFilterStubber;
+
+import com.google.common.collect.ImmutableList;
+
import org.junit.Before;
-import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
import java.util.List;
@RunWith(JUnit4.class)
@@ -84,8 +79,8 @@ public final class AmbientLuxTest {
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- mLightSensor = createSensor(Sensor.TYPE_LIGHT, null);
- mAmbientColorSensor = createSensor(AMBIENT_COLOR_TYPE, AMBIENT_COLOR_TYPE_STR);
+ mLightSensor = TestUtils.createSensor(Sensor.TYPE_LIGHT, null);
+ mAmbientColorSensor = TestUtils.createSensor(AMBIENT_COLOR_TYPE, AMBIENT_COLOR_TYPE_STR);
mContextSpy = spy(new ContextWrapper(InstrumentationRegistry.getContext()));
mResourcesSpy = spy(mContextSpy.getResources());
when(mContextSpy.getResources()).thenReturn(mResourcesSpy);
@@ -482,25 +477,6 @@ public final class AmbientLuxTest {
}
}
- private void setSensorType(Sensor sensor, int type, String strType) throws Exception {
- Method setter = Sensor.class.getDeclaredMethod("setType", Integer.TYPE);
- setter.setAccessible(true);
- setter.invoke(sensor, type);
- if (strType != null) {
- Field f = sensor.getClass().getDeclaredField("mStringType");
- f.setAccessible(true);
- f.set(sensor, strType);
- }
- }
-
- private Sensor createSensor(int type, String strType) throws Exception {
- Constructor<Sensor> constr = Sensor.class.getDeclaredConstructor();
- constr.setAccessible(true);
- Sensor sensor = constr.newInstance();
- setSensorType(sensor, type, strType);
- return sensor;
- }
-
private TypedArray createTypedArray() throws Exception {
TypedArray mockArray = mock(TypedArray.class);
return mockArray;
diff --git a/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientSensorTest.java b/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientSensorTest.java
index 6ff4f3b22b9c..3e3e535df986 100644
--- a/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientSensorTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientSensorTest.java
@@ -28,15 +28,14 @@ import static org.mockito.Mockito.when;
import android.content.ContextWrapper;
import android.content.res.Resources;
import android.hardware.Sensor;
-import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.Looper;
-import android.os.SystemClock;
import androidx.test.InstrumentationRegistry;
+import com.android.server.display.TestUtils;
import com.android.server.display.whitebalance.AmbientSensor.AmbientBrightnessSensor;
import com.android.server.display.whitebalance.AmbientSensor.AmbientColorTemperatureSensor;
@@ -50,9 +49,6 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -73,8 +69,8 @@ public final class AmbientSensorTest {
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- mLightSensor = createSensor(Sensor.TYPE_LIGHT, null);
- mAmbientColorSensor = createSensor(AMBIENT_COLOR_TYPE, AMBIENT_COLOR_TYPE_STR);
+ mLightSensor = TestUtils.createSensor(Sensor.TYPE_LIGHT, null);
+ mAmbientColorSensor = TestUtils.createSensor(AMBIENT_COLOR_TYPE, AMBIENT_COLOR_TYPE_STR);
mContextSpy = spy(new ContextWrapper(InstrumentationRegistry.getContext()));
mResourcesSpy = spy(mContextSpy.getResources());
when(mContextSpy.getResources()).thenReturn(mResourcesSpy);
@@ -96,7 +92,7 @@ public final class AmbientSensorTest {
// There should be no issues when we callback the listener, even if there is no callback
// set.
SensorEventListener listener = captor.getValue();
- listener.onSensorChanged(createSensorEvent(mLightSensor, 100));
+ listener.onSensorChanged(TestUtils.createSensorEvent(mLightSensor, 100));
}
@Test
@@ -122,7 +118,7 @@ public final class AmbientSensorTest {
verify(mSensorManagerMock).registerListener(captor.capture(), eq(mLightSensor),
anyInt(), eq(mHandler));
SensorEventListener listener = captor.getValue();
- listener.onSensorChanged(createSensorEvent(mLightSensor, luxValue));
+ listener.onSensorChanged(TestUtils.createSensorEvent(mLightSensor, luxValue));
assertTrue(changeSignal.await(5, TimeUnit.SECONDS));
assertEquals(luxValue, luxReturned[0]);
}
@@ -155,39 +151,8 @@ public final class AmbientSensorTest {
verify(mSensorManagerMock).registerListener(captor.capture(), eq(mAmbientColorSensor),
anyInt(), eq(mHandler));
SensorEventListener listener = captor.getValue();
- listener.onSensorChanged(createSensorEvent(mAmbientColorSensor, colorTempValue));
+ listener.onSensorChanged(TestUtils.createSensorEvent(mAmbientColorSensor, colorTempValue));
assertTrue(changeSignal.await(5, TimeUnit.SECONDS));
assertEquals(colorTempValue, colorTempReturned[0]);
}
-
- private SensorEvent createSensorEvent(Sensor sensor, int lux) throws Exception {
- final Constructor<SensorEvent> constructor =
- SensorEvent.class.getDeclaredConstructor(int.class);
- constructor.setAccessible(true);
- final SensorEvent event = constructor.newInstance(1);
- event.sensor = sensor;
- event.values[0] = lux;
- event.timestamp = SystemClock.elapsedRealtimeNanos();
- return event;
- }
-
-
- private void setSensorType(Sensor sensor, int type, String strType) throws Exception {
- Method setter = Sensor.class.getDeclaredMethod("setType", Integer.TYPE);
- setter.setAccessible(true);
- setter.invoke(sensor, type);
- if (strType != null) {
- Field f = sensor.getClass().getDeclaredField("mStringType");
- f.setAccessible(true);
- f.set(sensor, strType);
- }
- }
-
- private Sensor createSensor(int type, String strType) throws Exception {
- Constructor<Sensor> constr = Sensor.class.getDeclaredConstructor();
- constr.setAccessible(true);
- Sensor sensor = constr.newInstance();
- setSensorType(sensor, type, strType);
- return sensor;
- }
}
diff --git a/services/tests/servicestests/src/com/android/server/input/ConfigurationProcessorTest.java b/services/tests/servicestests/src/com/android/server/input/ConfigurationProcessorTest.java
index 636aa375a84c..2bd4a3a397b1 100644
--- a/services/tests/servicestests/src/com/android/server/input/ConfigurationProcessorTest.java
+++ b/services/tests/servicestests/src/com/android/server/input/ConfigurationProcessorTest.java
@@ -18,11 +18,9 @@ package com.android.server.input;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import android.content.Context;
-import android.util.Pair;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
@@ -32,7 +30,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.InputStream;
-import java.util.List;
+import java.util.Map;
/**
* Build/Install/Run:
@@ -52,7 +50,7 @@ public class ConfigurationProcessorTest {
public void testGetInputPortAssociations() {
final int res = com.android.frameworks.servicestests.R.raw.input_port_associations;
InputStream xml = mContext.getResources().openRawResource(res);
- List<Pair<String, String>> associations = null;
+ Map<String, Integer> associations = null;
try {
associations = ConfigurationProcessor.processInputPortAssociations(xml);
} catch (Exception e) {
@@ -60,8 +58,8 @@ public class ConfigurationProcessorTest {
}
assertNotNull(associations);
assertEquals(2, associations.size());
- assertTrue(associations.contains(Pair.create("USB1", "0")));
- assertTrue(associations.contains(Pair.create("USB2", "1")));
+ assertEquals(0, associations.get("USB1").intValue());
+ assertEquals(1, associations.get("USB2").intValue());
}
@Test
@@ -69,7 +67,7 @@ public class ConfigurationProcessorTest {
final int res =
com.android.frameworks.servicestests.R.raw.input_port_associations_bad_displayport;
InputStream xml = mContext.getResources().openRawResource(res);
- List<Pair<String, String>> associations = null;
+ Map<String, Integer> associations = null;
try {
associations = ConfigurationProcessor.processInputPortAssociations(xml);
} catch (Exception e) {
diff --git a/services/tests/servicestests/src/com/android/server/integrity/AppIntegrityManagerServiceImplTest.java b/services/tests/servicestests/src/com/android/server/integrity/AppIntegrityManagerServiceImplTest.java
new file mode 100644
index 000000000000..37ff06a18492
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/integrity/AppIntegrityManagerServiceImplTest.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.integrity;
+
+import static android.content.pm.PackageManager.EXTRA_VERIFICATION_ID;
+
+import static org.mockito.Mockito.verify;
+
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManagerInternal;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.server.LocalServices;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnit;
+import org.mockito.junit.MockitoRule;
+
+/** Unit test for {@link com.android.server.integrity.AppIntegrityManagerServiceImpl} */
+@RunWith(AndroidJUnit4.class)
+public class AppIntegrityManagerServiceImplTest {
+
+ @Rule public MockitoRule mMockitoRule = MockitoJUnit.rule();
+
+ @Mock PackageManagerInternal mPackageManagerInternal;
+
+ // under test
+ private AppIntegrityManagerServiceImpl mService;
+
+ @Before
+ public void setup() {
+ LocalServices.addService(PackageManagerInternal.class, mPackageManagerInternal);
+
+ mService = new AppIntegrityManagerServiceImpl(InstrumentationRegistry.getContext());
+ }
+
+ @Test
+ public void integrityVerification_allow() {
+ int verificationId = 2;
+ Intent integrityVerificationIntent = new Intent();
+ integrityVerificationIntent.setAction(Intent.ACTION_PACKAGE_NEEDS_INTEGRITY_VERIFICATION);
+ integrityVerificationIntent.putExtra(EXTRA_VERIFICATION_ID, verificationId);
+
+ // We cannot send the broadcast using the context since it is a protected broadcast and
+ // we will get a security exception.
+ mService.handleIntegrityVerification(integrityVerificationIntent);
+
+ verify(mPackageManagerInternal)
+ .setIntegrityVerificationResult(verificationId, PackageManager.VERIFICATION_ALLOW);
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/integrity/serializer/RuleIndexingDetailsIdentifierTest.java b/services/tests/servicestests/src/com/android/server/integrity/serializer/RuleIndexingDetailsIdentifierTest.java
new file mode 100644
index 000000000000..90ec19e06c8c
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/integrity/serializer/RuleIndexingDetailsIdentifierTest.java
@@ -0,0 +1,323 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.integrity.serializer;
+
+import static com.android.server.integrity.serializer.RuleIndexingDetails.APP_CERTIFICATE_INDEXED;
+import static com.android.server.integrity.serializer.RuleIndexingDetails.NOT_INDEXED;
+import static com.android.server.integrity.serializer.RuleIndexingDetails.PACKAGE_NAME_INDEXED;
+import static com.android.server.integrity.serializer.RuleIndexingDetailsIdentifier.splitRulesIntoIndexBuckets;
+import static com.android.server.testutils.TestUtils.assertExpectException;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.integrity.AppInstallMetadata;
+import android.content.integrity.AtomicFormula;
+import android.content.integrity.CompoundFormula;
+import android.content.integrity.Formula;
+import android.content.integrity.Rule;
+
+import androidx.annotation.NonNull;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+/** Unit tests for {@link RuleIndexingDetailsIdentifier}. */
+@RunWith(JUnit4.class)
+public class RuleIndexingDetailsIdentifierTest {
+
+ private static final String SAMPLE_APP_CERTIFICATE = "testcert";
+ private static final String SAMPLE_INSTALLER_NAME = "com.test.installer";
+ private static final String SAMPLE_INSTALLER_CERTIFICATE = "installercert";
+ private static final String SAMPLE_PACKAGE_NAME = "com.test.package";
+
+ private static final AtomicFormula ATOMIC_FORMULA_WITH_PACKAGE_NAME =
+ new AtomicFormula.StringAtomicFormula(
+ AtomicFormula.PACKAGE_NAME,
+ SAMPLE_PACKAGE_NAME,
+ /* isHashedValue= */ false);
+ private static final AtomicFormula ATOMIC_FORMULA_WITH_APP_CERTIFICATE =
+ new AtomicFormula.StringAtomicFormula(
+ AtomicFormula.APP_CERTIFICATE,
+ SAMPLE_APP_CERTIFICATE,
+ /* isHashedValue= */ false);
+ private static final AtomicFormula ATOMIC_FORMULA_WITH_INSTALLER_NAME =
+ new AtomicFormula.StringAtomicFormula(
+ AtomicFormula.INSTALLER_NAME,
+ SAMPLE_INSTALLER_NAME,
+ /* isHashedValue= */ false);
+ private static final AtomicFormula ATOMIC_FORMULA_WITH_INSTALLER_CERTIFICATE =
+ new AtomicFormula.StringAtomicFormula(
+ AtomicFormula.INSTALLER_CERTIFICATE,
+ SAMPLE_INSTALLER_CERTIFICATE,
+ /* isHashedValue= */ false);
+ private static final AtomicFormula ATOMIC_FORMULA_WITH_VERSION_CODE =
+ new AtomicFormula.IntAtomicFormula(AtomicFormula.VERSION_CODE, AtomicFormula.EQ, 12);
+ private static final AtomicFormula ATOMIC_FORMULA_WITH_ISPREINSTALLED =
+ new AtomicFormula.BooleanAtomicFormula(AtomicFormula.PRE_INSTALLED, /* booleanValue= */
+ true);
+
+
+ private static final Rule RULE_WITH_PACKAGE_NAME =
+ new Rule(
+ new CompoundFormula(
+ CompoundFormula.AND,
+ Arrays.asList(
+ ATOMIC_FORMULA_WITH_PACKAGE_NAME,
+ ATOMIC_FORMULA_WITH_INSTALLER_NAME)),
+ Rule.DENY);
+ private static final Rule RULE_WITH_APP_CERTIFICATE =
+ new Rule(
+ new CompoundFormula(
+ CompoundFormula.AND,
+ Arrays.asList(
+ ATOMIC_FORMULA_WITH_APP_CERTIFICATE,
+ ATOMIC_FORMULA_WITH_INSTALLER_NAME)),
+ Rule.DENY);
+ private static final Rule RULE_WITH_INSTALLER_RESTRICTIONS =
+ new Rule(
+ new CompoundFormula(
+ CompoundFormula.AND,
+ Arrays.asList(
+ ATOMIC_FORMULA_WITH_INSTALLER_NAME,
+ ATOMIC_FORMULA_WITH_INSTALLER_CERTIFICATE)),
+ Rule.DENY);
+
+ private static final Rule RULE_WITH_NONSTRING_RESTRICTIONS =
+ new Rule(
+ new CompoundFormula(
+ CompoundFormula.AND,
+ Arrays.asList(
+ ATOMIC_FORMULA_WITH_VERSION_CODE,
+ ATOMIC_FORMULA_WITH_ISPREINSTALLED)),
+ Rule.DENY);
+
+ @Test
+ public void getIndexType_nullRule() {
+ List<Rule> ruleList = null;
+
+ assertExpectException(
+ IllegalArgumentException.class,
+ /* expectedExceptionMessageRegex= */
+ "Index buckets cannot be created for null rule list.",
+ () -> splitRulesIntoIndexBuckets(ruleList));
+ }
+
+ @Test
+ public void getIndexType_invalidFormula() {
+ List<Rule> ruleList = new ArrayList();
+ ruleList.add(new Rule(getInvalidFormula(), Rule.DENY));
+
+ assertExpectException(
+ IllegalArgumentException.class,
+ /* expectedExceptionMessageRegex= */ "Invalid formula tag type.",
+ () -> splitRulesIntoIndexBuckets(ruleList));
+ }
+
+ @Test
+ public void getIndexType_ruleContainingPackageNameFormula() {
+ List<Rule> ruleList = new ArrayList();
+ ruleList.add(RULE_WITH_PACKAGE_NAME);
+
+ Map<Integer, List<Rule>> result = splitRulesIntoIndexBuckets(ruleList);
+
+ // Verify the resulting map content.
+ assertThat(result.keySet())
+ .containsExactly(NOT_INDEXED, PACKAGE_NAME_INDEXED, APP_CERTIFICATE_INDEXED);
+ assertThat(result.get(NOT_INDEXED)).isEmpty();
+ assertThat(result.get(APP_CERTIFICATE_INDEXED)).isEmpty();
+ assertThat(result.get(PACKAGE_NAME_INDEXED)).containsExactly(RULE_WITH_PACKAGE_NAME);
+ }
+
+ @Test
+ public void getIndexType_ruleContainingAppCertificateFormula() {
+ List<Rule> ruleList = new ArrayList();
+ ruleList.add(RULE_WITH_APP_CERTIFICATE);
+
+ Map<Integer, List<Rule>> result = splitRulesIntoIndexBuckets(ruleList);
+
+ assertThat(result.keySet())
+ .containsExactly(NOT_INDEXED, PACKAGE_NAME_INDEXED, APP_CERTIFICATE_INDEXED);
+ assertThat(result.get(NOT_INDEXED)).isEmpty();
+ assertThat(result.get(PACKAGE_NAME_INDEXED)).isEmpty();
+ assertThat(result.get(APP_CERTIFICATE_INDEXED)).containsExactly(RULE_WITH_APP_CERTIFICATE);
+ }
+
+ @Test
+ public void getIndexType_ruleWithUnindexedCompoundFormula() {
+ List<Rule> ruleList = new ArrayList();
+ ruleList.add(RULE_WITH_INSTALLER_RESTRICTIONS);
+
+ Map<Integer, List<Rule>> result = splitRulesIntoIndexBuckets(ruleList);
+
+ assertThat(result.keySet())
+ .containsExactly(NOT_INDEXED, PACKAGE_NAME_INDEXED, APP_CERTIFICATE_INDEXED);
+ assertThat(result.get(PACKAGE_NAME_INDEXED)).isEmpty();
+ assertThat(result.get(APP_CERTIFICATE_INDEXED)).isEmpty();
+ assertThat(result.get(NOT_INDEXED)).containsExactly(RULE_WITH_INSTALLER_RESTRICTIONS);
+ }
+
+ @Test
+ public void getIndexType_ruleContainingCompoundFormulaWithIntAndBoolean() {
+ List<Rule> ruleList = new ArrayList();
+ ruleList.add(RULE_WITH_NONSTRING_RESTRICTIONS);
+
+ Map<Integer, List<Rule>> result = splitRulesIntoIndexBuckets(ruleList);
+
+ assertThat(result.keySet())
+ .containsExactly(NOT_INDEXED, PACKAGE_NAME_INDEXED, APP_CERTIFICATE_INDEXED);
+ assertThat(result.get(PACKAGE_NAME_INDEXED)).isEmpty();
+ assertThat(result.get(APP_CERTIFICATE_INDEXED)).isEmpty();
+ assertThat(result.get(NOT_INDEXED)).containsExactly(RULE_WITH_NONSTRING_RESTRICTIONS);
+ }
+
+ @Test
+ public void getIndexType_negatedRuleContainingPackageNameFormula() {
+ Rule negatedRule =
+ new Rule(
+ new CompoundFormula(
+ CompoundFormula.NOT,
+ Arrays.asList(
+ new CompoundFormula(
+ CompoundFormula.AND,
+ Arrays.asList(
+ ATOMIC_FORMULA_WITH_PACKAGE_NAME,
+ ATOMIC_FORMULA_WITH_APP_CERTIFICATE)))),
+ Rule.DENY);
+ List<Rule> ruleList = new ArrayList();
+ ruleList.add(negatedRule);
+
+ Map<Integer, List<Rule>> result = splitRulesIntoIndexBuckets(ruleList);
+
+ assertThat(result.keySet())
+ .containsExactly(NOT_INDEXED, PACKAGE_NAME_INDEXED, APP_CERTIFICATE_INDEXED);
+ assertThat(result.get(PACKAGE_NAME_INDEXED)).isEmpty();
+ assertThat(result.get(APP_CERTIFICATE_INDEXED)).isEmpty();
+ assertThat(result.get(NOT_INDEXED)).containsExactly(negatedRule);
+ }
+
+ @Test
+ public void getIndexType_allRulesTogetherInValidOrder() {
+ Rule packageNameRuleA = getRuleWithPackageName("aaa");
+ Rule packageNameRuleB = getRuleWithPackageName("bbb");
+ Rule packageNameRuleC = getRuleWithPackageName("ccc");
+ Rule certificateRule1 = getRuleWithAppCertificate("cert1");
+ Rule certificateRule2 = getRuleWithAppCertificate("cert2");
+ Rule certificateRule3 = getRuleWithAppCertificate("cert3");
+
+ List<Rule> ruleList = new ArrayList();
+ ruleList.add(packageNameRuleB);
+ ruleList.add(packageNameRuleC);
+ ruleList.add(packageNameRuleA);
+ ruleList.add(certificateRule3);
+ ruleList.add(certificateRule2);
+ ruleList.add(certificateRule1);
+ ruleList.add(RULE_WITH_INSTALLER_RESTRICTIONS);
+ ruleList.add(RULE_WITH_NONSTRING_RESTRICTIONS);
+
+ Map<Integer, List<Rule>> result = splitRulesIntoIndexBuckets(ruleList);
+
+ assertThat(result.keySet())
+ .containsExactly(NOT_INDEXED, PACKAGE_NAME_INDEXED, APP_CERTIFICATE_INDEXED);
+
+ // We check asserts this way to ensure ordering based on package name.
+ assertThat(result.get(PACKAGE_NAME_INDEXED).get(0)).isEqualTo(packageNameRuleA);
+ assertThat(result.get(PACKAGE_NAME_INDEXED).get(1)).isEqualTo(packageNameRuleB);
+ assertThat(result.get(PACKAGE_NAME_INDEXED).get(2)).isEqualTo(packageNameRuleC);
+
+ // We check asserts this way to ensure ordering based on app certificate.
+ assertThat(result.get(APP_CERTIFICATE_INDEXED).get(0)).isEqualTo(certificateRule1);
+ assertThat(result.get(APP_CERTIFICATE_INDEXED).get(1)).isEqualTo(certificateRule2);
+ assertThat(result.get(APP_CERTIFICATE_INDEXED).get(2)).isEqualTo(certificateRule3);
+
+ assertThat(result.get(NOT_INDEXED))
+ .containsExactly(
+ RULE_WITH_INSTALLER_RESTRICTIONS,
+ RULE_WITH_NONSTRING_RESTRICTIONS);
+ }
+
+ private Rule getRuleWithPackageName(String packageName) {
+ return new Rule(
+ new CompoundFormula(
+ CompoundFormula.AND,
+ Arrays.asList(
+ new AtomicFormula.StringAtomicFormula(
+ AtomicFormula.PACKAGE_NAME,
+ packageName,
+ /* isHashedValue= */ false),
+ ATOMIC_FORMULA_WITH_INSTALLER_NAME)),
+ Rule.DENY);
+ }
+
+ private Rule getRuleWithAppCertificate(String certificate) {
+ return new Rule(
+ new CompoundFormula(
+ CompoundFormula.AND,
+ Arrays.asList(
+ new AtomicFormula.StringAtomicFormula(
+ AtomicFormula.APP_CERTIFICATE,
+ certificate,
+ /* isHashedValue= */ false),
+ ATOMIC_FORMULA_WITH_INSTALLER_NAME)),
+ Rule.DENY);
+ }
+
+ private Formula getInvalidFormula() {
+ return new Formula() {
+ @Override
+ public boolean isSatisfied(AppInstallMetadata appInstallMetadata) {
+ return false;
+ }
+
+ @Override
+ public int getTag() {
+ return 4;
+ }
+
+ @Override
+ public int hashCode() {
+ return super.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ return super.equals(obj);
+ }
+
+ @NonNull
+ @Override
+ protected Object clone() throws CloneNotSupportedException {
+ return super.clone();
+ }
+
+ @Override
+ public String toString() {
+ return super.toString();
+ }
+
+ @Override
+ protected void finalize() throws Throwable {
+ super.finalize();
+ }
+ };
+ }
+}
diff --git a/tests/utils/testutils/java/test/util/MockitoUtils.kt b/services/tests/servicestests/src/com/android/server/om/MockitoUtils.kt
index 5151abe54108..0f915dbdcf6f 100644
--- a/tests/utils/testutils/java/test/util/MockitoUtils.kt
+++ b/services/tests/servicestests/src/com/android/server/om/MockitoUtils.kt
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package test.util
+package com.android.server.om
import org.mockito.Answers
import org.mockito.Mockito
@@ -22,6 +22,8 @@ import org.mockito.invocation.InvocationOnMock
import org.mockito.stubbing.Answer
import org.mockito.stubbing.Stubber
+// TODO(chiuwinson): Move this entire file to a shared utility module
+// TODO(b/135203078): De-dupe utils added for overlays vs package refactor
object MockitoUtils {
val ANSWER_THROWS = Answer<Any?> {
when (val name = it.method.name) {
diff --git a/services/tests/servicestests/src/com/android/server/om/OverlayReferenceMapperTests.kt b/services/tests/servicestests/src/com/android/server/om/OverlayReferenceMapperTests.kt
index f45316fc74cd..ef1294819f34 100644
--- a/services/tests/servicestests/src/com/android/server/om/OverlayReferenceMapperTests.kt
+++ b/services/tests/servicestests/src/com/android/server/om/OverlayReferenceMapperTests.kt
@@ -24,8 +24,6 @@ import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.testng.Assert.assertThrows
-import test.util.mockThrowOnUnmocked
-import test.util.whenever
@RunWith(Parameterized::class)
class OverlayReferenceMapperTests {
diff --git a/services/tests/servicestests/src/com/android/server/pm/ApexManagerTest.java b/services/tests/servicestests/src/com/android/server/pm/ApexManagerTest.java
index fb9c68a5b70d..40ada2aedd59 100644
--- a/services/tests/servicestests/src/com/android/server/pm/ApexManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/ApexManagerTest.java
@@ -30,6 +30,7 @@ import static org.testng.Assert.assertThrows;
import android.apex.ApexInfo;
import android.apex.ApexSessionInfo;
+import android.apex.ApexSessionParams;
import android.apex.IApexService;
import android.content.Context;
import android.content.pm.PackageInfo;
@@ -183,19 +184,18 @@ public class ApexManagerTest {
public void testSubmitStagedSession_throwPackageManagerException() throws RemoteException {
doAnswer(invocation -> {
throw new Exception();
- }).when(mApexService).submitStagedSession(anyInt(), any(), any());
+ }).when(mApexService).submitStagedSession(any(), any());
assertThrows(PackageManagerException.class,
- () -> mApexManager.submitStagedSession(TEST_SESSION_ID, TEST_CHILD_SESSION_ID));
+ () -> mApexManager.submitStagedSession(testParamsWithChildren()));
}
@Test
public void testSubmitStagedSession_throwRunTimeException() throws RemoteException {
- doThrow(RemoteException.class).when(mApexService).submitStagedSession(anyInt(), any(),
- any());
+ doThrow(RemoteException.class).when(mApexService).submitStagedSession(any(), any());
assertThrows(RuntimeException.class,
- () -> mApexManager.submitStagedSession(TEST_SESSION_ID, TEST_CHILD_SESSION_ID));
+ () -> mApexManager.submitStagedSession(testParamsWithChildren()));
}
@Test
@@ -272,6 +272,13 @@ public class ApexManagerTest {
return stagedSessionInfo;
}
+ private static ApexSessionParams testParamsWithChildren() {
+ ApexSessionParams params = new ApexSessionParams();
+ params.sessionId = TEST_SESSION_ID;
+ params.childSessionIds = TEST_CHILD_SESSION_ID;
+ return params;
+ }
+
/**
* Copies a specified {@code resourceId} to a temp file. Returns a non-null file if the copy
* succeeded
diff --git a/services/tests/servicestests/src/com/android/server/pm/PackageInstallerSessionTest.java b/services/tests/servicestests/src/com/android/server/pm/PackageInstallerSessionTest.java
index b751308a4bb4..c478ec472e61 100644
--- a/services/tests/servicestests/src/com/android/server/pm/PackageInstallerSessionTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/PackageInstallerSessionTest.java
@@ -173,6 +173,7 @@ public class PackageInstallerSessionTest {
/* createdMillis */ 0L,
/* stageDir */ mTmpDir,
/* stageCid */ null,
+ /* files */ null,
/* prepared */ true,
/* committed */ true,
/* sealed */ false, // Setting to true would trigger some PM logic.
diff --git a/services/tests/servicestests/src/com/android/server/pm/UserManagerServiceUserTypeTest.java b/services/tests/servicestests/src/com/android/server/pm/UserManagerServiceUserTypeTest.java
index 7aadd87efb08..8e74c903534f 100644
--- a/services/tests/servicestests/src/com/android/server/pm/UserManagerServiceUserTypeTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/UserManagerServiceUserTypeTest.java
@@ -25,24 +25,32 @@ import static android.content.pm.UserInfo.FLAG_PROFILE;
import static android.content.pm.UserInfo.FLAG_RESTRICTED;
import static android.content.pm.UserInfo.FLAG_SYSTEM;
+import static com.android.server.pm.UserTypeDetails.UNLIMITED_NUMBER_OF_USERS;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import static org.testng.Assert.assertThrows;
import android.content.pm.UserInfo;
import android.content.res.Resources;
+import android.content.res.XmlResourceParser;
+import android.os.Bundle;
import android.os.UserManager;
+import android.util.ArrayMap;
+import androidx.test.InstrumentationRegistry;
import androidx.test.filters.MediumTest;
import androidx.test.runner.AndroidJUnit4;
+import com.android.frameworks.servicestests.R;
+
+import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
-import java.util.ArrayList;
-import java.util.Arrays;
-
/**
* Tests for {@link UserTypeDetails} and {@link UserTypeFactory}.
*
@@ -52,9 +60,17 @@ import java.util.Arrays;
@MediumTest
public class UserManagerServiceUserTypeTest {
+ private Resources mResources;
+
+ @Before
+ public void setup() {
+ mResources = InstrumentationRegistry.getTargetContext().getResources();
+ }
+
@Test
public void testUserTypeBuilder_createUserType() {
- UserTypeDetails type = new UserTypeDetails.Builder()
+ final Bundle restrictions = makeRestrictionsBundle("r1", "r2");
+ final UserTypeDetails type = new UserTypeDetails.Builder()
.setName("a.name")
.setEnabled(true)
.setMaxAllowed(21)
@@ -67,7 +83,7 @@ public class UserManagerServiceUserTypeTest {
.setBadgeNoBackground(30)
.setLabel(31)
.setMaxAllowedPerParent(32)
- .setDefaultRestrictions(new ArrayList<>(Arrays.asList("r1", "r2")))
+ .setDefaultRestrictions(restrictions)
.createUserTypeDetails();
assertEquals("a.name", type.getName());
@@ -79,7 +95,8 @@ public class UserManagerServiceUserTypeTest {
assertEquals(30, type.getBadgeNoBackground());
assertEquals(31, type.getLabel());
assertEquals(32, type.getMaxAllowedPerParent());
- assertEquals(new ArrayList<>(Arrays.asList("r1", "r2")), type.getDefaultRestrictions());
+ assertTrue(UserRestrictionsUtils.areEqual(restrictions, type.getDefaultRestrictions()));
+ assertNotSame(restrictions, type.getDefaultRestrictions());
assertEquals(23, type.getBadgeLabel(0));
@@ -106,8 +123,8 @@ public class UserManagerServiceUserTypeTest {
.createUserTypeDetails();
assertTrue(type.isEnabled());
- assertEquals(UserTypeDetails.UNLIMITED_NUMBER_OF_USERS, type.getMaxAllowed());
- assertEquals(UserTypeDetails.UNLIMITED_NUMBER_OF_USERS, type.getMaxAllowedPerParent());
+ assertEquals(UNLIMITED_NUMBER_OF_USERS, type.getMaxAllowed());
+ assertEquals(UNLIMITED_NUMBER_OF_USERS, type.getMaxAllowedPerParent());
assertEquals(FLAG_FULL, type.getDefaultUserInfoFlags());
assertEquals(Resources.ID_NULL, type.getIconBadge());
assertEquals(Resources.ID_NULL, type.getBadgePlain());
@@ -185,8 +202,173 @@ public class UserManagerServiceUserTypeTest {
UserInfo.getDefaultUserType(FLAG_EPHEMERAL));
}
+ /** Tests {@link UserTypeFactory#customizeBuilders} for a reasonable xml file. */
+ @Test
+ public void testUserTypeFactoryCustomize_profile() throws Exception {
+ final String userTypeAosp1 = "android.test.1"; // Profile user that is not customized
+ final String userTypeAosp2 = "android.test.2"; // Profile user that is customized
+ final String userTypeOem1 = "custom.test.1"; // Custom-defined profile
+
+ // Mock some "AOSP defaults".
+ final Bundle restrictions = makeRestrictionsBundle("no_config_vpn", "no_config_tethering");
+ final ArrayMap<String, UserTypeDetails.Builder> builders = new ArrayMap<>();
+ builders.put(userTypeAosp1, new UserTypeDetails.Builder()
+ .setName(userTypeAosp1)
+ .setBaseType(FLAG_PROFILE)
+ .setMaxAllowedPerParent(31)
+ .setDefaultRestrictions(restrictions));
+ builders.put(userTypeAosp2, new UserTypeDetails.Builder()
+ .setName(userTypeAosp1)
+ .setBaseType(FLAG_PROFILE)
+ .setMaxAllowedPerParent(32)
+ .setIconBadge(401)
+ .setBadgeColors(402, 403, 404)
+ .setDefaultRestrictions(restrictions));
+
+ final XmlResourceParser parser = mResources.getXml(R.xml.usertypes_test_profile);
+ UserTypeFactory.customizeBuilders(builders, parser);
+
+ // userTypeAosp1 should not be modified.
+ UserTypeDetails aospType = builders.get(userTypeAosp1).createUserTypeDetails();
+ assertEquals(31, aospType.getMaxAllowedPerParent());
+ assertEquals(Resources.ID_NULL, aospType.getIconBadge());
+ assertTrue(UserRestrictionsUtils.areEqual(restrictions, aospType.getDefaultRestrictions()));
+
+ // userTypeAosp2 should be modified.
+ aospType = builders.get(userTypeAosp2).createUserTypeDetails();
+ assertEquals(12, aospType.getMaxAllowedPerParent());
+ assertEquals(com.android.internal.R.drawable.ic_corp_icon_badge_case,
+ aospType.getIconBadge());
+ assertEquals(Resources.ID_NULL, aospType.getBadgePlain()); // No resId for 'garbage'
+ assertEquals(com.android.internal.R.drawable.ic_corp_badge_no_background,
+ aospType.getBadgeNoBackground());
+ assertEquals(com.android.internal.R.string.managed_profile_label_badge,
+ aospType.getBadgeLabel(0));
+ assertEquals(com.android.internal.R.string.managed_profile_label_badge_2,
+ aospType.getBadgeLabel(1));
+ assertEquals(com.android.internal.R.string.managed_profile_label_badge_2,
+ aospType.getBadgeLabel(2));
+ assertEquals(com.android.internal.R.string.managed_profile_label_badge_2,
+ aospType.getBadgeLabel(3));
+ assertEquals(com.android.internal.R.color.profile_badge_1,
+ aospType.getBadgeColor(0));
+ assertEquals(com.android.internal.R.color.profile_badge_2,
+ aospType.getBadgeColor(1));
+ assertEquals(com.android.internal.R.color.profile_badge_2,
+ aospType.getBadgeColor(2));
+ assertEquals(com.android.internal.R.color.profile_badge_2,
+ aospType.getBadgeColor(3));
+ assertTrue(UserRestrictionsUtils.areEqual(
+ makeRestrictionsBundle("no_remove_user", "no_bluetooth"),
+ aospType.getDefaultRestrictions()));
+
+ // userTypeOem1 should be created.
+ UserTypeDetails.Builder customType = builders.get(userTypeOem1);
+ assertNotNull(customType);
+ assertEquals(14, customType.createUserTypeDetails().getMaxAllowedPerParent());
+ }
+
+ /** Tests {@link UserTypeFactory#customizeBuilders} for customizing a FULL user. */
+ @Test
+ public void testUserTypeFactoryCustomize_full() throws Exception {
+ final String userTypeFull = "android.test.1";
+
+ // Mock "AOSP default".
+ final Bundle restrictions = makeRestrictionsBundle("no_config_vpn", "no_config_tethering");
+ final ArrayMap<String, UserTypeDetails.Builder> builders = new ArrayMap<>();
+ builders.put(userTypeFull, new UserTypeDetails.Builder()
+ .setName(userTypeFull)
+ .setBaseType(FLAG_FULL)
+ .setDefaultRestrictions(restrictions));
+
+ final XmlResourceParser parser = mResources.getXml(R.xml.usertypes_test_full);
+ UserTypeFactory.customizeBuilders(builders, parser);
+
+ UserTypeDetails details = builders.get(userTypeFull).createUserTypeDetails();
+ assertEquals(UNLIMITED_NUMBER_OF_USERS, details.getMaxAllowedPerParent());
+ assertTrue(UserRestrictionsUtils.areEqual(
+ makeRestrictionsBundle("no_remove_user", "no_bluetooth"),
+ details.getDefaultRestrictions()));
+ assertEquals(Resources.ID_NULL, details.getBadgeColor(0));
+ }
+
+ /**
+ * Tests {@link UserTypeFactory#customizeBuilders} when custom user type deletes the
+ * badge-colors and restrictions.
+ */
+ @Test
+ public void testUserTypeFactoryCustomize_eraseArray() throws Exception {
+ final String typeName = "android.test";
+
+ final ArrayMap<String, UserTypeDetails.Builder> builders = new ArrayMap<>();
+ builders.put(typeName, new UserTypeDetails.Builder()
+ .setName(typeName)
+ .setBaseType(FLAG_PROFILE)
+ .setMaxAllowedPerParent(1)
+ .setBadgeColors(501, 502)
+ .setDefaultRestrictions(makeRestrictionsBundle("r1")));
+
+ final XmlResourceParser parser = mResources.getXml(R.xml.usertypes_test_eraseArray);
+ UserTypeFactory.customizeBuilders(builders, parser);
+
+ UserTypeDetails typeDetails = builders.get(typeName).createUserTypeDetails();
+ assertEquals(2, typeDetails.getMaxAllowedPerParent());
+ assertEquals(Resources.ID_NULL, typeDetails.getBadgeColor(0));
+ assertEquals(Resources.ID_NULL, typeDetails.getBadgeColor(1));
+ assertTrue(typeDetails.getDefaultRestrictions().isEmpty());
+ }
+
+ /** Tests {@link UserTypeFactory#customizeBuilders} when custom user type has illegal name. */
+ @Test
+ public void testUserTypeFactoryCustomize_illegalOemName() throws Exception {
+ final String userTypeAosp = "android.aosp.legal";
+ final String userTypeOem = "android.oem.illegal.name"; // Custom-defined profile
+
+ final ArrayMap<String, UserTypeDetails.Builder> builders = new ArrayMap<>();
+ builders.put(userTypeAosp, new UserTypeDetails.Builder()
+ .setName(userTypeAosp)
+ .setBaseType(FLAG_PROFILE)
+ .setMaxAllowedPerParent(21));
+
+ final XmlResourceParser parser = mResources.getXml(R.xml.usertypes_test_illegalOemName);
+
+ // parser is illegal because non-AOSP user types cannot be prefixed with "android.".
+ assertThrows(IllegalArgumentException.class,
+ () -> UserTypeFactory.customizeBuilders(builders, parser));
+ }
+
+ /**
+ * Tests {@link UserTypeFactory#customizeBuilders} when illegally customizing a non-profile as
+ * a profile.
+ */
+ @Test
+ public void testUserTypeFactoryCustomize_illegalUserBaseType() throws Exception {
+ final String userTypeFull = "android.test";
+
+ final ArrayMap<String, UserTypeDetails.Builder> builders = new ArrayMap<>();
+ builders.put(userTypeFull, new UserTypeDetails.Builder()
+ .setName(userTypeFull)
+ .setBaseType(FLAG_FULL)
+ .setMaxAllowedPerParent(21));
+
+ XmlResourceParser parser = mResources.getXml(R.xml.usertypes_test_illegalUserBaseType);
+
+ // parser is illegal because userTypeFull is FULL but the tag is for profile-type.
+ assertThrows(IllegalArgumentException.class,
+ () -> UserTypeFactory.customizeBuilders(builders, parser));
+ }
+
/** Returns a minimal {@link UserTypeDetails.Builder} that can legitimately be created. */
private UserTypeDetails.Builder getMinimalBuilder() {
return new UserTypeDetails.Builder().setName("name").setBaseType(FLAG_FULL);
}
+
+ /** Creates a Bundle of the given String restrictions, each set to true. */
+ private Bundle makeRestrictionsBundle(String ... restrictions) {
+ final Bundle bundle = new Bundle();
+ for (String restriction : restrictions) {
+ bundle.putBoolean(restriction, true);
+ }
+ return bundle;
+ }
}
diff --git a/services/tests/servicestests/src/com/android/server/pm/UserManagerTest.java b/services/tests/servicestests/src/com/android/server/pm/UserManagerTest.java
index dee79bb7b501..06b3dc1d9deb 100644
--- a/services/tests/servicestests/src/com/android/server/pm/UserManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/UserManagerTest.java
@@ -16,6 +16,12 @@
package com.android.server.pm;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
import android.annotation.UserIdInt;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
@@ -29,15 +35,21 @@ import android.os.Bundle;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.Settings;
-import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.LargeTest;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
-import com.android.internal.util.ArrayUtils;
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.google.common.collect.Range;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -45,7 +57,8 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/** Test {@link UserManager} functionality. */
-public class UserManagerTest extends AndroidTestCase {
+@RunWith(AndroidJUnit4.class)
+public final class UserManagerTest {
// Taken from UserManagerService
private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // 30 years
@@ -58,6 +71,8 @@ public class UserManagerTest extends AndroidTestCase {
"com.android.egg"
};
+ private final Context mContext = InstrumentationRegistry.getInstrumentation().getContext();
+
private final Object mUserRemoveLock = new Object();
private final Object mUserSwitchLock = new Object();
@@ -65,15 +80,14 @@ public class UserManagerTest extends AndroidTestCase {
private PackageManager mPackageManager;
private List<Integer> usersToRemove;
- @Override
+ @Before
public void setUp() throws Exception {
- super.setUp();
- mUserManager = UserManager.get(getContext());
- mPackageManager = getContext().getPackageManager();
+ mUserManager = UserManager.get(mContext);
+ mPackageManager = mContext.getPackageManager();
IntentFilter filter = new IntentFilter(Intent.ACTION_USER_REMOVED);
filter.addAction(Intent.ACTION_USER_SWITCHED);
- getContext().registerReceiver(new BroadcastReceiver() {
+ mContext.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
@@ -95,36 +109,35 @@ public class UserManagerTest extends AndroidTestCase {
usersToRemove = new ArrayList<>();
}
- @Override
- protected void tearDown() throws Exception {
+ @After
+ public void tearDown() throws Exception {
for (Integer userId : usersToRemove) {
removeUser(userId);
}
- super.tearDown();
}
private void removeExistingUsers() {
+ int currentUser = ActivityManager.getCurrentUser();
List<UserInfo> list = mUserManager.getUsers();
for (UserInfo user : list) {
- // Keep system and primary user.
- // We do not have to keep primary user, but in split system user mode, we need it
- // until http://b/22976637 is fixed. Right now in split system user mode, you need to
- // switch to primary user and run tests under primary user.
- if (user.id != UserHandle.USER_SYSTEM && !user.isPrimary()) {
+ // Keep system and current user
+ if (user.id != UserHandle.USER_SYSTEM && user.id != currentUser) {
removeUser(user.id);
}
}
}
@SmallTest
+ @Test
public void testHasSystemUser() throws Exception {
- assertTrue(findUser(UserHandle.USER_SYSTEM));
+ assertThat(findUser(UserHandle.USER_SYSTEM)).isTrue();
}
@MediumTest
- public void testAddUser() throws Exception {
+ @Test
+ public void testAddGuest() throws Exception {
UserInfo userInfo = createUser("Guest 1", UserInfo.FLAG_GUEST);
- assertTrue(userInfo != null);
+ assertThat(userInfo).isNotNull();
List<UserInfo> list = mUserManager.getUsers();
boolean found = false;
@@ -135,35 +148,39 @@ public class UserManagerTest extends AndroidTestCase {
&& !user.isPrimary()) {
found = true;
Bundle restrictions = mUserManager.getUserRestrictions(user.getUserHandle());
- assertTrue("Guest user should have DISALLOW_CONFIG_WIFI=true by default",
- restrictions.getBoolean(UserManager.DISALLOW_CONFIG_WIFI));
+ assertWithMessage("Guest user should have DISALLOW_CONFIG_WIFI=true by default")
+ .that(restrictions.getBoolean(UserManager.DISALLOW_CONFIG_WIFI))
+ .isTrue();
}
}
- assertTrue(found);
+ assertThat(found).isTrue();
}
@MediumTest
+ @Test
public void testAdd2Users() throws Exception {
UserInfo user1 = createUser("Guest 1", UserInfo.FLAG_GUEST);
UserInfo user2 = createUser("User 2", UserInfo.FLAG_ADMIN);
- assertTrue(user1 != null);
- assertTrue(user2 != null);
+ assertThat(user1).isNotNull();
+ assertThat(user2).isNotNull();
- assertTrue(findUser(0));
- assertTrue(findUser(user1.id));
- assertTrue(findUser(user2.id));
+ assertThat(findUser(UserHandle.USER_SYSTEM)).isTrue();
+ assertThat(findUser(user1.id)).isTrue();
+ assertThat(findUser(user2.id)).isTrue();
}
@MediumTest
+ @Test
public void testRemoveUser() throws Exception {
UserInfo userInfo = createUser("Guest 1", UserInfo.FLAG_GUEST);
removeUser(userInfo.id);
- assertFalse(findUser(userInfo.id));
+ assertThat(findUser(userInfo.id)).isFalse();
}
@MediumTest
+ @Test
public void testRemoveUserByHandle() {
UserInfo userInfo = createUser("Guest 1", UserInfo.FLAG_GUEST);
final UserHandle user = userInfo.getUserHandle();
@@ -183,10 +200,11 @@ public class UserManagerTest extends AndroidTestCase {
}
}
- assertFalse(findUser(userInfo.id));
+ assertThat(findUser(userInfo.id)).isFalse();
}
@MediumTest
+ @Test
public void testRemoveUserByHandle_ThrowsException() {
synchronized (mUserRemoveLock) {
try {
@@ -200,6 +218,7 @@ public class UserManagerTest extends AndroidTestCase {
/** Tests creating a FULL user via specifying userType. */
@MediumTest
+ @Test
public void testCreateUserViaTypes() throws Exception {
createUserWithTypeAndCheckFlags(UserManager.USER_TYPE_FULL_GUEST,
UserInfo.FLAG_GUEST | UserInfo.FLAG_FULL);
@@ -213,6 +232,7 @@ public class UserManagerTest extends AndroidTestCase {
/** Tests creating a FULL user via specifying user flags. */
@MediumTest
+ @Test
public void testCreateUserViaFlags() throws Exception {
createUserWithFlagsAndCheckType(UserInfo.FLAG_GUEST, UserManager.USER_TYPE_FULL_GUEST,
UserInfo.FLAG_FULL);
@@ -231,10 +251,9 @@ public class UserManagerTest extends AndroidTestCase {
private void createUserWithTypeAndCheckFlags(String userType,
@UserIdInt int requiredFlags) {
final UserInfo userInfo = createUser("Name", userType, 0);
- assertEquals("Wrong user type", userType, userInfo.userType);
- assertEquals(
- "Flags " + userInfo.flags + " did not contain expected " + requiredFlags,
- requiredFlags, userInfo.flags & requiredFlags);
+ assertWithMessage("Wrong user type").that(userInfo.userType).isEqualTo(userType);
+ assertWithMessage("Flags %s did not contain expected %s", userInfo.flags, requiredFlags)
+ .that(userInfo.flags & requiredFlags).isEqualTo(requiredFlags);
removeUser(userInfo.id);
}
@@ -245,145 +264,140 @@ public class UserManagerTest extends AndroidTestCase {
private void createUserWithFlagsAndCheckType(@UserIdInt int flags, String expectedUserType,
@UserIdInt int additionalRequiredFlags) {
final UserInfo userInfo = createUser("Name", flags);
- assertEquals("Wrong user type", expectedUserType, userInfo.userType);
+ assertWithMessage("Wrong user type").that(userInfo.userType).isEqualTo(expectedUserType);
additionalRequiredFlags |= flags;
- assertEquals(
- "Flags " + userInfo.flags + " did not contain expected " + additionalRequiredFlags,
- additionalRequiredFlags, userInfo.flags & additionalRequiredFlags);
+ assertWithMessage("Flags %s did not contain expected %s", userInfo.flags,
+ additionalRequiredFlags).that(userInfo.flags & additionalRequiredFlags)
+ .isEqualTo(additionalRequiredFlags);
removeUser(userInfo.id);
}
@MediumTest
- public void testAddGuest() throws Exception {
+ @Test
+ public void testThereCanBeOnlyOneGuest() throws Exception {
UserInfo userInfo1 = createUser("Guest 1", UserInfo.FLAG_GUEST);
+ assertThat(userInfo1).isNotNull();
UserInfo userInfo2 = createUser("Guest 2", UserInfo.FLAG_GUEST);
- assertNotNull(userInfo1);
- assertNull(userInfo2);
+ assertThat(userInfo2).isNull();
}
@MediumTest
+ @Test
public void testFindExistingGuest_guestExists() throws Exception {
UserInfo userInfo1 = createUser("Guest", UserInfo.FLAG_GUEST);
+ assertThat(userInfo1).isNotNull();
UserInfo foundGuest = mUserManager.findCurrentGuestUser();
- assertNotNull(foundGuest);
+ assertThat(foundGuest).isNotNull();
}
@SmallTest
+ @Test
public void testFindExistingGuest_guestDoesNotExist() throws Exception {
UserInfo foundGuest = mUserManager.findCurrentGuestUser();
- assertNull(foundGuest);
+ assertThat(foundGuest).isNull();
}
@MediumTest
+ @Test
public void testSetUserAdmin() throws Exception {
UserInfo userInfo = createUser("SecondaryUser", /*flags=*/ 0);
+ assertThat(userInfo.isAdmin()).isFalse();
- // Assert user is not admin and has SMS and calls restrictions.
- assertFalse(userInfo.isAdmin());
- assertTrue(mUserManager.hasUserRestriction(UserManager.DISALLOW_SMS,
- userInfo.getUserHandle()));
- assertTrue(mUserManager.hasUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS,
- userInfo.getUserHandle()));
-
- // Assign admin privileges.
mUserManager.setUserAdmin(userInfo.id);
- // Refresh.
userInfo = mUserManager.getUserInfo(userInfo.id);
-
- // Verify user became admin and SMS and call restrictions are lifted.
- assertTrue(userInfo.isAdmin());
- assertFalse(mUserManager.hasUserRestriction(UserManager.DISALLOW_SMS,
- userInfo.getUserHandle()));
- assertFalse(mUserManager.hasUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS,
- userInfo.getUserHandle()));
+ assertThat(userInfo.isAdmin()).isTrue();
}
@MediumTest
+ @Test
public void testGetProfileParent() throws Exception {
+ assumeManagedUsersSupported();
final int primaryUserId = mUserManager.getPrimaryUser().id;
UserInfo userInfo = createProfileForUser("Profile",
UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
- assertNotNull(userInfo);
- assertNull(mUserManager.getProfileParent(primaryUserId));
+ assertThat(userInfo).isNotNull();
+ assertThat(mUserManager.getProfileParent(primaryUserId)).isNull();
UserInfo parentProfileInfo = mUserManager.getProfileParent(userInfo.id);
- assertNotNull(parentProfileInfo);
- assertEquals(parentProfileInfo.id, primaryUserId);
+ assertThat(parentProfileInfo).isNotNull();
+ assertThat(primaryUserId).isEqualTo(parentProfileInfo.id);
removeUser(userInfo.id);
- assertNull(mUserManager.getProfileParent(primaryUserId));
+ assertThat(mUserManager.getProfileParent(primaryUserId)).isNull();
}
/** Test that UserManager returns the correct badge information for a managed profile. */
@MediumTest
+ @Test
public void testProfileTypeInformation() throws Exception {
+ assumeManagedUsersSupported();
final UserTypeDetails userTypeDetails =
UserTypeFactory.getUserTypes().get(UserManager.USER_TYPE_PROFILE_MANAGED);
- assertNotNull("No " + UserManager.USER_TYPE_PROFILE_MANAGED + " type on device",
- userTypeDetails);
- assertEquals(UserManager.USER_TYPE_PROFILE_MANAGED, userTypeDetails.getName());
+ assertWithMessage("No %s type on device", UserManager.USER_TYPE_PROFILE_MANAGED)
+ .that(userTypeDetails).isNotNull();
+ assertThat(userTypeDetails.getName()).isEqualTo(UserManager.USER_TYPE_PROFILE_MANAGED);
final int primaryUserId = mUserManager.getPrimaryUser().id;
UserInfo userInfo = createProfileForUser("Managed",
UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
- assertNotNull(userInfo);
+ assertThat(userInfo).isNotNull();
final int userId = userInfo.id;
final UserHandle userHandle = new UserHandle(userId);
- assertEquals(userTypeDetails.hasBadge(),
- mUserManager.hasBadge(userId));
- assertEquals(userTypeDetails.getIconBadge(),
- mUserManager.getUserIconBadgeResId(userId));
- assertEquals(userTypeDetails.getBadgePlain(),
- mUserManager.getUserBadgeResId(userId));
- assertEquals(userTypeDetails.getBadgeNoBackground(),
- mUserManager.getUserBadgeNoBackgroundResId(userId));
- assertEquals(userTypeDetails.isProfile(),
- mUserManager.isProfile(userId));
- assertEquals(userTypeDetails.getName(),
- mUserManager.getUserTypeForUser(userHandle));
+ assertThat(mUserManager.hasBadge(userId)).isEqualTo(userTypeDetails.hasBadge());
+ assertThat(mUserManager.getUserIconBadgeResId(userId))
+ .isEqualTo(userTypeDetails.getIconBadge());
+ assertThat(mUserManager.getUserBadgeResId(userId))
+ .isEqualTo(userTypeDetails.getBadgePlain());
+ assertThat(mUserManager.getUserBadgeNoBackgroundResId(userId))
+ .isEqualTo(userTypeDetails.getBadgeNoBackground());
+ assertThat(mUserManager.isProfile(userId)).isEqualTo(userTypeDetails.isProfile());
+ assertThat(mUserManager.getUserTypeForUser(userHandle))
+ .isEqualTo(userTypeDetails.getName());
final int badgeIndex = userInfo.profileBadge;
- assertEquals(
- Resources.getSystem().getColor(userTypeDetails.getBadgeColor(badgeIndex), null),
- mUserManager.getUserBadgeColor(userId));
- assertEquals(
- Resources.getSystem().getString(userTypeDetails.getBadgeLabel(badgeIndex), "Test"),
- mUserManager.getBadgedLabelForUser("Test", userHandle));
+ assertThat(mUserManager.getUserBadgeColor(userId)).isEqualTo(
+ Resources.getSystem().getColor(userTypeDetails.getBadgeColor(badgeIndex), null));
+ assertThat(mUserManager.getBadgedLabelForUser("Test", userHandle)).isEqualTo(
+ Resources.getSystem().getString(userTypeDetails.getBadgeLabel(badgeIndex), "Test"));
}
// Make sure only one managed profile can be created
@MediumTest
+ @Test
public void testAddManagedProfile() throws Exception {
+ assumeManagedUsersSupported();
final int primaryUserId = mUserManager.getPrimaryUser().id;
UserInfo userInfo1 = createProfileForUser("Managed 1",
UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
UserInfo userInfo2 = createProfileForUser("Managed 2",
UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
- assertNotNull(userInfo1);
- assertNull(userInfo2);
+ assertThat(userInfo1).isNotNull();
+ assertThat(userInfo2).isNull();
- assertEquals(userInfo1.userType, UserManager.USER_TYPE_PROFILE_MANAGED);
+ assertThat(userInfo1.userType).isEqualTo(UserManager.USER_TYPE_PROFILE_MANAGED);
int requiredFlags = UserInfo.FLAG_MANAGED_PROFILE | UserInfo.FLAG_PROFILE;
- assertEquals("Wrong flags " + userInfo1.flags, requiredFlags,
- userInfo1.flags & requiredFlags);
+ assertWithMessage("Wrong flags %s", userInfo1.flags).that(userInfo1.flags & requiredFlags)
+ .isEqualTo(requiredFlags);
// Verify that current user is not a managed profile
- assertFalse(mUserManager.isManagedProfile());
+ assertThat(mUserManager.isManagedProfile()).isFalse();
}
// Verify that disallowed packages are not installed in the managed profile.
@MediumTest
+ @Test
public void testAddManagedProfile_withDisallowedPackages() throws Exception {
+ assumeManagedUsersSupported();
final int primaryUserId = mUserManager.getPrimaryUser().id;
UserInfo userInfo1 = createProfileForUser("Managed1",
UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
// Verify that the packagesToVerify are installed by default.
for (String pkg : PACKAGES) {
- assertTrue("Package should be installed in managed profile: " + pkg,
- isPackageInstalledForUser(pkg, userInfo1.id));
+ assertWithMessage("Package should be installed in managed profile: %s", pkg)
+ .that(isPackageInstalledForUser(pkg, userInfo1.id)).isTrue();
}
removeUser(userInfo1.id);
@@ -391,50 +405,57 @@ public class UserManagerTest extends AndroidTestCase {
UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId, PACKAGES);
// Verify that the packagesToVerify are not installed by default.
for (String pkg : PACKAGES) {
- assertFalse("Package should not be installed in managed profile when disallowed: "
- + pkg, isPackageInstalledForUser(pkg, userInfo2.id));
+ assertWithMessage(
+ "Package should not be installed in managed profile when disallowed: %s", pkg)
+ .that(isPackageInstalledForUser(pkg, userInfo2.id)).isFalse();
}
}
// Verify that if any packages are disallowed to install during creation of managed profile can
// still be installed later.
@MediumTest
+ @Test
public void testAddManagedProfile_disallowedPackagesInstalledLater() throws Exception {
+ assumeManagedUsersSupported();
final int primaryUserId = mUserManager.getPrimaryUser().id;
UserInfo userInfo = createProfileForUser("Managed",
UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId, PACKAGES);
// Verify that the packagesToVerify are not installed by default.
for (String pkg : PACKAGES) {
- assertFalse("Package should not be installed in managed profile when disallowed: "
- + pkg, isPackageInstalledForUser(pkg, userInfo.id));
+ assertWithMessage("Pkg should not be installed in managed profile when disallowed: %s",
+ pkg).that(isPackageInstalledForUser(pkg, userInfo.id)).isFalse();
}
// Verify that the disallowed packages during profile creation can be installed now.
for (String pkg : PACKAGES) {
- assertEquals("Package could not be installed: " + pkg,
- PackageManager.INSTALL_SUCCEEDED,
- mPackageManager.installExistingPackageAsUser(pkg, userInfo.id));
+ assertWithMessage("Package could not be installed: %s", pkg)
+ .that(mPackageManager.installExistingPackageAsUser(pkg, userInfo.id))
+ .isEqualTo(PackageManager.INSTALL_SUCCEEDED);
}
}
// Make sure createUser would fail if we have DISALLOW_ADD_USER.
@MediumTest
+ @Test
public void testCreateUser_disallowAddUser() throws Exception {
- final int primaryUserId = mUserManager.getPrimaryUser().id;
- final UserHandle primaryUserHandle = new UserHandle(primaryUserId);
- mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, true, primaryUserHandle);
+ final int creatorId = isAutomotive() ? ActivityManager.getCurrentUser()
+ : mUserManager.getPrimaryUser().id;
+ final UserHandle creatorHandle = new UserHandle(creatorId);
+ mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, true, creatorHandle);
try {
- UserInfo userInfo = createUser("SecondaryUser", /*flags=*/ 0);
- assertNull(userInfo);
+ UserInfo createadInfo = createUser("SecondaryUser", /*flags=*/ 0);
+ assertThat(createadInfo).isNull();
} finally {
mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false,
- primaryUserHandle);
+ creatorHandle);
}
}
// Make sure createProfile would fail if we have DISALLOW_ADD_MANAGED_PROFILE.
@MediumTest
+ @Test
public void testCreateProfileForUser_disallowAddManagedProfile() throws Exception {
+ assumeManagedUsersSupported();
final int primaryUserId = mUserManager.getPrimaryUser().id;
final UserHandle primaryUserHandle = new UserHandle(primaryUserId);
mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, true,
@@ -442,7 +463,7 @@ public class UserManagerTest extends AndroidTestCase {
try {
UserInfo userInfo = createProfileForUser("Managed",
UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
- assertNull(userInfo);
+ assertThat(userInfo).isNull();
} finally {
mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, false,
primaryUserHandle);
@@ -451,7 +472,9 @@ public class UserManagerTest extends AndroidTestCase {
// Make sure createProfileEvenWhenDisallowedForUser bypass DISALLOW_ADD_MANAGED_PROFILE.
@MediumTest
+ @Test
public void testCreateProfileForUserEvenWhenDisallowed() throws Exception {
+ assumeManagedUsersSupported();
final int primaryUserId = mUserManager.getPrimaryUser().id;
final UserHandle primaryUserHandle = new UserHandle(primaryUserId);
mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, true,
@@ -459,7 +482,7 @@ public class UserManagerTest extends AndroidTestCase {
try {
UserInfo userInfo = createProfileEvenWhenDisallowedForUser("Managed",
UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
- assertNotNull(userInfo);
+ assertThat(userInfo).isNotNull();
} finally {
mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, false,
primaryUserHandle);
@@ -468,14 +491,16 @@ public class UserManagerTest extends AndroidTestCase {
// createProfile succeeds even if DISALLOW_ADD_USER is set
@MediumTest
+ @Test
public void testCreateProfileForUser_disallowAddUser() throws Exception {
+ assumeManagedUsersSupported();
final int primaryUserId = mUserManager.getPrimaryUser().id;
final UserHandle primaryUserHandle = new UserHandle(primaryUserId);
mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, true, primaryUserHandle);
try {
UserInfo userInfo = createProfileForUser("Managed",
UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
- assertNotNull(userInfo);
+ assertThat(userInfo).isNotNull();
} finally {
mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false,
primaryUserHandle);
@@ -483,73 +508,85 @@ public class UserManagerTest extends AndroidTestCase {
}
@MediumTest
+ @Test
public void testAddRestrictedProfile() throws Exception {
- assertFalse("There should be no associated restricted profiles before the test",
- mUserManager.hasRestrictedProfiles());
+ if (isAutomotive()) return;
+ assertWithMessage("There should be no associated restricted profiles before the test")
+ .that(mUserManager.hasRestrictedProfiles()).isFalse();
UserInfo userInfo = createRestrictedProfile("Profile");
- assertNotNull(userInfo);
+ assertThat(userInfo).isNotNull();
Bundle restrictions = mUserManager.getUserRestrictions(UserHandle.of(userInfo.id));
- assertTrue("Restricted profile should have DISALLOW_MODIFY_ACCOUNTS restriction by default",
- restrictions.getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS));
- assertTrue("Restricted profile should have DISALLOW_SHARE_LOCATION restriction by default",
- restrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION));
-
- int locationMode = Settings.Secure.getIntForUser(getContext().getContentResolver(),
+ assertWithMessage(
+ "Restricted profile should have DISALLOW_MODIFY_ACCOUNTS restriction by default")
+ .that(restrictions.getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS))
+ .isTrue();
+ assertWithMessage(
+ "Restricted profile should have DISALLOW_SHARE_LOCATION restriction by default")
+ .that(restrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION))
+ .isTrue();
+
+ int locationMode = Settings.Secure.getIntForUser(mContext.getContentResolver(),
Settings.Secure.LOCATION_MODE,
Settings.Secure.LOCATION_MODE_HIGH_ACCURACY,
userInfo.id);
- assertEquals("Restricted profile should have setting LOCATION_MODE set to "
- + "LOCATION_MODE_OFF by default", locationMode, Settings.Secure.LOCATION_MODE_OFF);
+ assertWithMessage("Restricted profile should have setting LOCATION_MODE set to "
+ + "LOCATION_MODE_OFF by default").that(locationMode)
+ .isEqualTo(Settings.Secure.LOCATION_MODE_OFF);
- assertTrue("Newly created profile should be associated with the current user",
- mUserManager.hasRestrictedProfiles());
+ assertWithMessage("Newly created profile should be associated with the current user")
+ .that(mUserManager.hasRestrictedProfiles()).isTrue();
}
@MediumTest
+ @Test
public void testGetUserCreationTime() throws Exception {
+ // TODO: should add a regular user instead of a profile, so it can be tested everywhere
+ assumeManagedUsersSupported();
final int primaryUserId = mUserManager.getPrimaryUser().id;
final long startTime = System.currentTimeMillis();
UserInfo profile = createProfileForUser("Managed 1",
UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
final long endTime = System.currentTimeMillis();
- assertNotNull(profile);
+ assertThat(profile).isNotNull();
if (System.currentTimeMillis() > EPOCH_PLUS_30_YEARS) {
- assertTrue("creationTime must be set when the profile is created",
- profile.creationTime >= startTime && profile.creationTime <= endTime);
+ assertWithMessage("creationTime must be set when the profile is created")
+ .that(profile.creationTime).isIn(Range.closed(startTime, endTime));
} else {
- assertTrue("creationTime must be 0 if the time is not > EPOCH_PLUS_30_years",
- profile.creationTime == 0);
+ assertWithMessage("creationTime must be 0 if the time is not > EPOCH_PLUS_30_years")
+ .that(profile.creationTime).isEqualTo(0);
}
- assertEquals(profile.creationTime, mUserManager.getUserCreationTime(
- new UserHandle(profile.id)));
+ assertThat(mUserManager.getUserCreationTime(
+ new UserHandle(profile.id))).isEqualTo(profile.creationTime);
long ownerCreationTime = mUserManager.getUserInfo(primaryUserId).creationTime;
- assertEquals(ownerCreationTime, mUserManager.getUserCreationTime(
- new UserHandle(primaryUserId)));
+ assertThat(mUserManager.getUserCreationTime(
+ new UserHandle(primaryUserId))).isEqualTo(ownerCreationTime);
}
@SmallTest
+ @Test
public void testGetUserCreationTime_nonExistentUser() throws Exception {
try {
int noSuchUserId = 100500;
mUserManager.getUserCreationTime(new UserHandle(noSuchUserId));
fail("SecurityException should be thrown for nonexistent user");
} catch (Exception e) {
- assertTrue("SecurityException should be thrown for nonexistent user, but was: " + e,
- e instanceof SecurityException);
+ assertWithMessage("SecurityException should be thrown for nonexistent user").that(e)
+ .isInstanceOf(SecurityException.class);
}
}
@SmallTest
+ @Test
public void testGetUserCreationTime_otherUser() throws Exception {
UserInfo user = createUser("User 1", 0);
try {
mUserManager.getUserCreationTime(new UserHandle(user.id));
fail("SecurityException should be thrown for other user");
} catch (Exception e) {
- assertTrue("SecurityException should be thrown for other user, but was: " + e,
- e instanceof SecurityException);
+ assertWithMessage("SecurityException should be thrown for other user").that(e)
+ .isInstanceOf(SecurityException.class);
}
}
@@ -565,56 +602,58 @@ public class UserManagerTest extends AndroidTestCase {
}
@MediumTest
+ @Test
public void testSerialNumber() {
UserInfo user1 = createUser("User 1", 0);
int serialNumber1 = user1.serialNumber;
- assertEquals(serialNumber1, mUserManager.getUserSerialNumber(user1.id));
- assertEquals(user1.id, mUserManager.getUserHandle(serialNumber1));
+ assertThat(mUserManager.getUserSerialNumber(user1.id)).isEqualTo(serialNumber1);
+ assertThat(mUserManager.getUserHandle(serialNumber1)).isEqualTo(user1.id);
UserInfo user2 = createUser("User 2", 0);
int serialNumber2 = user2.serialNumber;
- assertFalse(serialNumber1 == serialNumber2);
- assertEquals(serialNumber2, mUserManager.getUserSerialNumber(user2.id));
- assertEquals(user2.id, mUserManager.getUserHandle(serialNumber2));
+ assertThat(serialNumber1 == serialNumber2).isFalse();
+ assertThat(mUserManager.getUserSerialNumber(user2.id)).isEqualTo(serialNumber2);
+ assertThat(mUserManager.getUserHandle(serialNumber2)).isEqualTo(user2.id);
}
@MediumTest
+ @Test
public void testGetSerialNumbersOfUsers() {
UserInfo user1 = createUser("User 1", 0);
UserInfo user2 = createUser("User 2", 0);
long[] serialNumbersOfUsers = mUserManager.getSerialNumbersOfUsers(false);
- String errMsg = "Array " + Arrays.toString(serialNumbersOfUsers) + " should contain ";
- assertTrue(errMsg + user1.serialNumber,
- ArrayUtils.contains(serialNumbersOfUsers, user1.serialNumber));
- assertTrue(errMsg + user2.serialNumber,
- ArrayUtils.contains(serialNumbersOfUsers, user2.serialNumber));
+ assertThat(serialNumbersOfUsers).asList().containsAllOf(
+ (long) user1.serialNumber, (long) user2.serialNumber);
}
@MediumTest
+ @Test
public void testMaxUsers() {
int N = UserManager.getMaxSupportedUsers();
int count = mUserManager.getUsers().size();
// Create as many users as permitted and make sure creation passes
while (count < N) {
UserInfo ui = createUser("User " + count, 0);
- assertNotNull(ui);
+ assertThat(ui).isNotNull();
count++;
}
// Try to create one more user and make sure it fails
UserInfo extra = createUser("One more", 0);
- assertNull(extra);
+ assertThat(extra).isNull();
}
@MediumTest
+ @Test
public void testGetUserCount() {
int count = mUserManager.getUsers().size();
UserInfo user1 = createUser("User 1", 0);
- assertNotNull(user1);
+ assertThat(user1).isNotNull();
UserInfo user2 = createUser("User 2", 0);
- assertNotNull(user2);
- assertEquals(count + 2, mUserManager.getUserCount());
+ assertThat(user2).isNotNull();
+ assertThat(mUserManager.getUserCount()).isEqualTo(count + 2);
}
@MediumTest
+ @Test
public void testRestrictions() {
UserInfo testUser = createUser("User 1", 0);
@@ -625,12 +664,29 @@ public class UserManagerTest extends AndroidTestCase {
Bundle stored = mUserManager.getUserRestrictions(new UserHandle(testUser.id));
// Note this will fail if DO already sets those restrictions.
- assertEquals(stored.getBoolean(UserManager.DISALLOW_CONFIG_WIFI), false);
- assertEquals(stored.getBoolean(UserManager.DISALLOW_UNINSTALL_APPS), false);
- assertEquals(stored.getBoolean(UserManager.DISALLOW_INSTALL_APPS), true);
+ assertThat(stored.getBoolean(UserManager.DISALLOW_CONFIG_WIFI)).isFalse();
+ assertThat(stored.getBoolean(UserManager.DISALLOW_UNINSTALL_APPS)).isFalse();
+ assertThat(stored.getBoolean(UserManager.DISALLOW_INSTALL_APPS)).isTrue();
}
@MediumTest
+ @Test
+ public void testDefaultRestrictionsApplied() throws Exception {
+ final UserInfo userInfo = createUser("Useroid", UserManager.USER_TYPE_FULL_SECONDARY, 0);
+ final UserTypeDetails userTypeDetails =
+ UserTypeFactory.getUserTypes().get(UserManager.USER_TYPE_FULL_SECONDARY);
+ final Bundle expectedRestrictions = userTypeDetails.getDefaultRestrictions();
+ // Note this can fail if DO unset those restrictions.
+ for (String restriction : expectedRestrictions.keySet()) {
+ if (expectedRestrictions.getBoolean(restriction)) {
+ assertThat(mUserManager.hasUserRestriction(restriction, UserHandle.of(userInfo.id)))
+ .isTrue();
+ }
+ }
+ }
+
+ @MediumTest
+ @Test
public void testSetDefaultGuestRestrictions() {
final Bundle origGuestRestrictions = mUserManager.getDefaultGuestRestrictions();
Bundle restrictions = new Bundle();
@@ -639,26 +695,28 @@ public class UserManagerTest extends AndroidTestCase {
try {
UserInfo guest = createUser("Guest", UserInfo.FLAG_GUEST);
- assertNotNull(guest);
- assertTrue(mUserManager.hasUserRestriction(UserManager.DISALLOW_FUN,
- guest.getUserHandle()));
+ assertThat(guest).isNotNull();
+ assertThat(mUserManager.hasUserRestriction(UserManager.DISALLOW_FUN,
+ guest.getUserHandle())).isTrue();
} finally {
mUserManager.setDefaultGuestRestrictions(origGuestRestrictions);
}
}
+ @Test
public void testGetUserSwitchability() {
int userSwitchable = mUserManager.getUserSwitchability();
- assertEquals("Expected users to be switchable", UserManager.SWITCHABILITY_STATUS_OK,
- userSwitchable);
+ assertWithMessage("Expected users to be switchable").that(userSwitchable)
+ .isEqualTo(UserManager.SWITCHABILITY_STATUS_OK);
}
@LargeTest
+ @Test
public void testSwitchUser() {
- ActivityManager am = getContext().getSystemService(ActivityManager.class);
+ ActivityManager am = mContext.getSystemService(ActivityManager.class);
final int startUser = am.getCurrentUser();
UserInfo user = createUser("User", 0);
- assertNotNull(user);
+ assertThat(user).isNotNull();
// Switch to the user just created.
switchUser(user.id, null, true);
// Switch back to the starting user.
@@ -666,21 +724,23 @@ public class UserManagerTest extends AndroidTestCase {
}
@LargeTest
+ @Test
public void testSwitchUserByHandle() {
- ActivityManager am = getContext().getSystemService(ActivityManager.class);
+ ActivityManager am = mContext.getSystemService(ActivityManager.class);
final int startUser = am.getCurrentUser();
UserInfo user = createUser("User", 0);
- assertNotNull(user);
+ assertThat(user).isNotNull();
// Switch to the user just created.
switchUser(-1, user.getUserHandle(), false);
// Switch back to the starting user.
switchUser(-1, UserHandle.of(startUser), false);
}
+ @Test
public void testSwitchUserByHandle_ThrowsException() {
synchronized (mUserSwitchLock) {
try {
- ActivityManager am = getContext().getSystemService(ActivityManager.class);
+ ActivityManager am = mContext.getSystemService(ActivityManager.class);
am.switchUser(null);
fail("Expected IllegalArgumentException on passing in a null UserHandle.");
} catch (IllegalArgumentException expected) {
@@ -690,6 +750,7 @@ public class UserManagerTest extends AndroidTestCase {
}
@MediumTest
+ @Test
public void testConcurrentUserCreate() throws Exception {
int userCount = mUserManager.getUserCount();
int maxSupportedUsers = UserManager.getMaxSupportedUsers();
@@ -712,11 +773,12 @@ public class UserManagerTest extends AndroidTestCase {
}
es.shutdown();
es.awaitTermination(20, TimeUnit.SECONDS);
- assertEquals(maxSupportedUsers, mUserManager.getUserCount());
- assertEquals(canBeCreatedCount, created.get());
+ assertThat(mUserManager.getUserCount()).isEqualTo(maxSupportedUsers);
+ assertThat(created.get()).isEqualTo(canBeCreatedCount);
}
@MediumTest
+ @Test
public void testGetUserHandles_createNewUser_shouldFindNewUser() {
UserInfo user = createUser("Guest 1", UserManager.USER_TYPE_FULL_GUEST, /*flags*/ 0);
@@ -728,7 +790,7 @@ public class UserManagerTest extends AndroidTestCase {
}
}
- assertTrue(found);
+ assertThat(found).isTrue();
}
private boolean isPackageInstalledForUser(String packageName, int userId) {
@@ -747,7 +809,7 @@ public class UserManagerTest extends AndroidTestCase {
*/
private void switchUser(int userId, UserHandle user, boolean ignoreHandle) {
synchronized (mUserSwitchLock) {
- ActivityManager am = getContext().getSystemService(ActivityManager.class);
+ ActivityManager am = mContext.getSystemService(ActivityManager.class);
if (ignoreHandle) {
am.switchUser(userId);
} else {
@@ -833,4 +895,12 @@ public class UserManagerTest extends AndroidTestCase {
return profile;
}
+ private void assumeManagedUsersSupported() {
+ assumeTrue("device doesn't support managed users",
+ mPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS));
+ }
+
+ private boolean isAutomotive() {
+ return mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
+ }
}
diff --git a/services/tests/servicestests/src/com/android/server/pm/UserSystemPackageInstallerTest.java b/services/tests/servicestests/src/com/android/server/pm/UserSystemPackageInstallerTest.java
index 683278b699c0..3db832b24236 100644
--- a/services/tests/servicestests/src/com/android/server/pm/UserSystemPackageInstallerTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/UserSystemPackageInstallerTest.java
@@ -26,6 +26,7 @@ import static com.android.server.pm.UserSystemPackageInstaller.USER_TYPE_PACKAGE
import static com.android.server.pm.UserSystemPackageInstaller.USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE;
import static com.android.server.pm.UserSystemPackageInstaller.USER_TYPE_PACKAGE_WHITELIST_MODE_IGNORE_OTA;
import static com.android.server.pm.UserSystemPackageInstaller.USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST;
+import static com.android.server.pm.UserSystemPackageInstaller.USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST_SYSTEM;
import static com.android.server.pm.UserSystemPackageInstaller.USER_TYPE_PACKAGE_WHITELIST_MODE_LOG;
import static org.junit.Assert.assertEquals;
@@ -262,39 +263,25 @@ public class UserSystemPackageInstallerTest {
// No implicit whitelist, so only install pkg1.
boolean implicit = false;
- boolean isSysUser = false;
assertTrue(UserSystemPackageInstaller.shouldInstallPackage(
- pkg1, pkgBitSetMap, userWhitelist, implicit, isSysUser));
+ pkg1, pkgBitSetMap, userWhitelist, implicit));
assertFalse(UserSystemPackageInstaller.shouldInstallPackage(
- pkg2, pkgBitSetMap, userWhitelist, implicit, isSysUser));
+ pkg2, pkgBitSetMap, userWhitelist, implicit));
assertFalse(UserSystemPackageInstaller.shouldInstallPackage(
- pkg3, pkgBitSetMap, userWhitelist, implicit, isSysUser));
+ pkg3, pkgBitSetMap, userWhitelist, implicit));
assertFalse(UserSystemPackageInstaller.shouldInstallPackage(
- pkg4, pkgBitSetMap, userWhitelist, implicit, isSysUser));
+ pkg4, pkgBitSetMap, userWhitelist, implicit));
// Use implicit whitelist, so install pkg1 and pkg4
implicit = true;
- isSysUser = false;
assertTrue(UserSystemPackageInstaller.shouldInstallPackage(
- pkg1, pkgBitSetMap, userWhitelist, implicit, isSysUser));
+ pkg1, pkgBitSetMap, userWhitelist, implicit));
assertFalse(UserSystemPackageInstaller.shouldInstallPackage(
- pkg2, pkgBitSetMap, userWhitelist, implicit, isSysUser));
+ pkg2, pkgBitSetMap, userWhitelist, implicit));
assertFalse(UserSystemPackageInstaller.shouldInstallPackage(
- pkg3, pkgBitSetMap, userWhitelist, implicit, isSysUser));
+ pkg3, pkgBitSetMap, userWhitelist, implicit));
assertTrue(UserSystemPackageInstaller.shouldInstallPackage(
- pkg4, pkgBitSetMap, userWhitelist, implicit, isSysUser));
-
- // For user 0 specifically, we always implicitly whitelist.
- implicit = false;
- isSysUser = true;
- assertTrue(UserSystemPackageInstaller.shouldInstallPackage(
- pkg1, pkgBitSetMap, userWhitelist, implicit, isSysUser));
- assertFalse(UserSystemPackageInstaller.shouldInstallPackage(
- pkg2, pkgBitSetMap, userWhitelist, implicit, isSysUser));
- assertFalse(UserSystemPackageInstaller.shouldInstallPackage(
- pkg3, pkgBitSetMap, userWhitelist, implicit, isSysUser));
- assertTrue(UserSystemPackageInstaller.shouldInstallPackage(
- pkg4, pkgBitSetMap, userWhitelist, implicit, isSysUser));
+ pkg4, pkgBitSetMap, userWhitelist, implicit));
}
/**
@@ -400,30 +387,42 @@ public class UserSystemPackageInstallerTest {
assertFalse(mUserSystemPackageInstaller.isLogMode());
assertFalse(mUserSystemPackageInstaller.isEnforceMode());
assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistMode());
+ assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistSystemMode());
assertFalse(mUserSystemPackageInstaller.isIgnoreOtaMode());
setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_LOG);
assertTrue(mUserSystemPackageInstaller.isLogMode());
assertFalse(mUserSystemPackageInstaller.isEnforceMode());
assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistMode());
+ assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistSystemMode());
assertFalse(mUserSystemPackageInstaller.isIgnoreOtaMode());
setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE);
assertFalse(mUserSystemPackageInstaller.isLogMode());
assertTrue(mUserSystemPackageInstaller.isEnforceMode());
assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistMode());
+ assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistSystemMode());
assertFalse(mUserSystemPackageInstaller.isIgnoreOtaMode());
setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST);
assertFalse(mUserSystemPackageInstaller.isLogMode());
assertFalse(mUserSystemPackageInstaller.isEnforceMode());
assertTrue(mUserSystemPackageInstaller.isImplicitWhitelistMode());
+ assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistSystemMode());
+ assertFalse(mUserSystemPackageInstaller.isIgnoreOtaMode());
+
+ setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST_SYSTEM);
+ assertFalse(mUserSystemPackageInstaller.isLogMode());
+ assertFalse(mUserSystemPackageInstaller.isEnforceMode());
+ assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistMode());
+ assertTrue(mUserSystemPackageInstaller.isImplicitWhitelistSystemMode());
assertFalse(mUserSystemPackageInstaller.isIgnoreOtaMode());
setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_IGNORE_OTA);
assertFalse(mUserSystemPackageInstaller.isLogMode());
assertFalse(mUserSystemPackageInstaller.isEnforceMode());
assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistMode());
+ assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistSystemMode());
assertTrue(mUserSystemPackageInstaller.isIgnoreOtaMode());
setUserTypePackageWhitelistMode(
@@ -431,6 +430,7 @@ public class UserSystemPackageInstallerTest {
assertTrue(mUserSystemPackageInstaller.isLogMode());
assertTrue(mUserSystemPackageInstaller.isEnforceMode());
assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistMode());
+ assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistSystemMode());
assertFalse(mUserSystemPackageInstaller.isIgnoreOtaMode());
setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST
@@ -438,6 +438,7 @@ public class UserSystemPackageInstallerTest {
assertFalse(mUserSystemPackageInstaller.isLogMode());
assertTrue(mUserSystemPackageInstaller.isEnforceMode());
assertTrue(mUserSystemPackageInstaller.isImplicitWhitelistMode());
+ assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistSystemMode());
assertFalse(mUserSystemPackageInstaller.isIgnoreOtaMode());
}
diff --git a/services/tests/servicestests/src/com/android/server/soundtrigger_middleware/ConversionUtilTest.java b/services/tests/servicestests/src/com/android/server/soundtrigger_middleware/ConversionUtilTest.java
new file mode 100644
index 000000000000..5a2ce4540b82
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/soundtrigger_middleware/ConversionUtilTest.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.soundtrigger_middleware;
+
+import static org.junit.Assert.assertEquals;
+
+import android.hardware.audio.common.V2_0.Uuid;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class ConversionUtilTest {
+ private static final String TAG = "ConversionUtilTest";
+
+ @Test
+ public void testUuidRoundTrip() {
+ Uuid hidl = new Uuid();
+ hidl.timeLow = 0xFEDCBA98;
+ hidl.timeMid = (short) 0xEDCB;
+ hidl.versionAndTimeHigh = (short) 0xDCBA;
+ hidl.variantAndClockSeqHigh = (short) 0xCBA9;
+ hidl.node = new byte[] { 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
+
+ String aidl = ConversionUtil.hidl2aidlUuid(hidl);
+ assertEquals("fedcba98-edcb-dcba-cba9-111213141516", aidl);
+
+ Uuid reconstructed = ConversionUtil.aidl2hidlUuid(aidl);
+ assertEquals(hidl, reconstructed);
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/soundtrigger_middleware/SoundTriggerMiddlewareImplTest.java b/services/tests/servicestests/src/com/android/server/soundtrigger_middleware/SoundTriggerMiddlewareImplTest.java
new file mode 100644
index 000000000000..82f32f88d3a2
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/soundtrigger_middleware/SoundTriggerMiddlewareImplTest.java
@@ -0,0 +1,1306 @@
+/*
+ * Copyright (C) 2019 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 com.android.server.soundtrigger_middleware;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.clearInvocations;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.hardware.audio.common.V2_0.AudioConfig;
+import android.hardware.audio.common.V2_0.Uuid;
+import android.hardware.soundtrigger.V2_3.OptionalModelParameterRange;
+import android.media.audio.common.AudioChannelMask;
+import android.media.audio.common.AudioFormat;
+import android.media.soundtrigger_middleware.ConfidenceLevel;
+import android.media.soundtrigger_middleware.ISoundTriggerCallback;
+import android.media.soundtrigger_middleware.ISoundTriggerModule;
+import android.media.soundtrigger_middleware.ModelParameter;
+import android.media.soundtrigger_middleware.ModelParameterRange;
+import android.media.soundtrigger_middleware.Phrase;
+import android.media.soundtrigger_middleware.PhraseRecognitionEvent;
+import android.media.soundtrigger_middleware.PhraseRecognitionExtra;
+import android.media.soundtrigger_middleware.PhraseSoundModel;
+import android.media.soundtrigger_middleware.RecognitionConfig;
+import android.media.soundtrigger_middleware.RecognitionEvent;
+import android.media.soundtrigger_middleware.RecognitionMode;
+import android.media.soundtrigger_middleware.RecognitionStatus;
+import android.media.soundtrigger_middleware.SoundModel;
+import android.media.soundtrigger_middleware.SoundModelType;
+import android.media.soundtrigger_middleware.SoundTriggerModuleDescriptor;
+import android.media.soundtrigger_middleware.SoundTriggerModuleProperties;
+import android.os.HidlMemoryUtil;
+import android.os.HwParcel;
+import android.os.IHwBinder;
+import android.os.IHwInterface;
+import android.os.RemoteException;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.stubbing.Answer;
+
+@RunWith(Parameterized.class)
+public class SoundTriggerMiddlewareImplTest {
+ private static final String TAG = "SoundTriggerMiddlewareImplTest";
+
+ // We run the test once for every version of the underlying driver.
+ @Parameterized.Parameters
+ public static Object[] data() {
+ return new Object[]{
+ mock(android.hardware.soundtrigger.V2_0.ISoundTriggerHw.class),
+ mock(android.hardware.soundtrigger.V2_1.ISoundTriggerHw.class),
+ mock(android.hardware.soundtrigger.V2_2.ISoundTriggerHw.class),
+ mock(android.hardware.soundtrigger.V2_3.ISoundTriggerHw.class),
+ };
+ }
+
+ @Mock
+ @Parameterized.Parameter
+ public android.hardware.soundtrigger.V2_0.ISoundTriggerHw mHalDriver;
+
+ @Mock
+ private SoundTriggerMiddlewareImpl.AudioSessionProvider mAudioSessionProvider = mock(
+ SoundTriggerMiddlewareImpl.AudioSessionProvider.class);
+
+ private SoundTriggerMiddlewareImpl mService;
+
+ private static ISoundTriggerCallback createCallbackMock() {
+ return mock(ISoundTriggerCallback.Stub.class, Mockito.CALLS_REAL_METHODS);
+ }
+
+ private static SoundModel createGenericSoundModel() {
+ return createSoundModel(SoundModelType.GENERIC);
+ }
+
+ private static SoundModel createSoundModel(int type) {
+ SoundModel model = new SoundModel();
+ model.type = type;
+ model.uuid = "12345678-2345-3456-4567-abcdef987654";
+ model.vendorUuid = "87654321-5432-6543-7654-456789fedcba";
+ model.data = new byte[]{91, 92, 93, 94, 95};
+ return model;
+ }
+
+ private static PhraseSoundModel createPhraseSoundModel() {
+ PhraseSoundModel model = new PhraseSoundModel();
+ model.common = createSoundModel(SoundModelType.KEYPHRASE);
+ model.phrases = new Phrase[1];
+ model.phrases[0] = new Phrase();
+ model.phrases[0].id = 123;
+ model.phrases[0].users = new int[]{5, 6, 7};
+ model.phrases[0].locale = "locale";
+ model.phrases[0].text = "text";
+ model.phrases[0].recognitionModes =
+ RecognitionMode.USER_AUTHENTICATION | RecognitionMode.USER_IDENTIFICATION;
+ return model;
+ }
+
+ private static android.hardware.soundtrigger.V2_0.ISoundTriggerHw.Properties createDefaultProperties(
+ boolean supportConcurrentCapture) {
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw.Properties properties =
+ new android.hardware.soundtrigger.V2_0.ISoundTriggerHw.Properties();
+ properties.implementor = "implementor";
+ properties.description = "description";
+ properties.version = 123;
+ properties.uuid = new Uuid();
+ properties.uuid.timeLow = 1;
+ properties.uuid.timeMid = 2;
+ properties.uuid.versionAndTimeHigh = 3;
+ properties.uuid.variantAndClockSeqHigh = 4;
+ properties.uuid.node = new byte[]{5, 6, 7, 8, 9, 10};
+
+ properties.maxSoundModels = 456;
+ properties.maxKeyPhrases = 567;
+ properties.maxUsers = 678;
+ properties.recognitionModes = 789;
+ properties.captureTransition = true;
+ properties.maxBufferMs = 321;
+ properties.concurrentCapture = supportConcurrentCapture;
+ properties.triggerInEvent = true;
+ properties.powerConsumptionMw = 432;
+ return properties;
+ }
+
+ private static void validateDefaultProperties(SoundTriggerModuleProperties properties,
+ boolean supportConcurrentCapture) {
+ assertEquals("implementor", properties.implementor);
+ assertEquals("description", properties.description);
+ assertEquals(123, properties.version);
+ assertEquals("00000001-0002-0003-0004-05060708090a", properties.uuid);
+ assertEquals(456, properties.maxSoundModels);
+ assertEquals(567, properties.maxKeyPhrases);
+ assertEquals(678, properties.maxUsers);
+ assertEquals(789, properties.recognitionModes);
+ assertTrue(properties.captureTransition);
+ assertEquals(321, properties.maxBufferMs);
+ assertEquals(supportConcurrentCapture, properties.concurrentCapture);
+ assertTrue(properties.triggerInEvent);
+ assertEquals(432, properties.powerConsumptionMw);
+ }
+
+
+ private static android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.RecognitionEvent createRecognitionEvent_2_0(
+ int hwHandle,
+ int status) {
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.RecognitionEvent halEvent =
+ new android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.RecognitionEvent();
+ halEvent.status = status;
+ halEvent.type = SoundModelType.GENERIC;
+ halEvent.model = hwHandle;
+ halEvent.captureAvailable = true;
+ // This field is ignored.
+ halEvent.captureSession = 123;
+ halEvent.captureDelayMs = 234;
+ halEvent.capturePreambleMs = 345;
+ halEvent.triggerInData = true;
+ halEvent.audioConfig = new AudioConfig();
+ halEvent.audioConfig.sampleRateHz = 456;
+ halEvent.audioConfig.channelMask = AudioChannelMask.IN_LEFT;
+ halEvent.audioConfig.format = AudioFormat.MP3;
+ // hwEvent.audioConfig.offloadInfo is irrelevant.
+ halEvent.data.add((byte) 31);
+ halEvent.data.add((byte) 32);
+ halEvent.data.add((byte) 33);
+ return halEvent;
+ }
+
+ private static android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.RecognitionEvent createRecognitionEvent_2_1(
+ int hwHandle,
+ int status) {
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.RecognitionEvent halEvent =
+ new android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.RecognitionEvent();
+ halEvent.header = createRecognitionEvent_2_0(hwHandle, status);
+ halEvent.header.data.clear();
+ halEvent.data = HidlMemoryUtil.byteArrayToHidlMemory(new byte[]{31, 32, 33});
+ return halEvent;
+ }
+
+ private static void validateRecognitionEvent(RecognitionEvent event, int status) {
+ assertEquals(status, event.status);
+ assertEquals(SoundModelType.GENERIC, event.type);
+ assertTrue(event.captureAvailable);
+ assertEquals(101, event.captureSession);
+ assertEquals(234, event.captureDelayMs);
+ assertEquals(345, event.capturePreambleMs);
+ assertTrue(event.triggerInData);
+ assertEquals(456, event.audioConfig.sampleRateHz);
+ assertEquals(AudioChannelMask.IN_LEFT, event.audioConfig.channelMask);
+ assertEquals(AudioFormat.MP3, event.audioConfig.format);
+ }
+
+ private static android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.PhraseRecognitionEvent createPhraseRecognitionEvent_2_0(
+ int hwHandle, int status) {
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.PhraseRecognitionEvent halEvent =
+ new android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.PhraseRecognitionEvent();
+ halEvent.common = createRecognitionEvent_2_0(hwHandle, status);
+
+ android.hardware.soundtrigger.V2_0.PhraseRecognitionExtra halExtra =
+ new android.hardware.soundtrigger.V2_0.PhraseRecognitionExtra();
+ halExtra.id = 123;
+ halExtra.confidenceLevel = 52;
+ halExtra.recognitionModes = android.hardware.soundtrigger.V2_0.RecognitionMode.VOICE_TRIGGER
+ | android.hardware.soundtrigger.V2_0.RecognitionMode.GENERIC_TRIGGER;
+ android.hardware.soundtrigger.V2_0.ConfidenceLevel halLevel =
+ new android.hardware.soundtrigger.V2_0.ConfidenceLevel();
+ halLevel.userId = 31;
+ halLevel.levelPercent = 43;
+ halExtra.levels.add(halLevel);
+ halEvent.phraseExtras.add(halExtra);
+ return halEvent;
+ }
+
+ private static android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.PhraseRecognitionEvent createPhraseRecognitionEvent_2_1(
+ int hwHandle, int status) {
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.PhraseRecognitionEvent halEvent =
+ new android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.PhraseRecognitionEvent();
+ halEvent.common = createRecognitionEvent_2_1(hwHandle, status);
+
+ android.hardware.soundtrigger.V2_0.PhraseRecognitionExtra halExtra =
+ new android.hardware.soundtrigger.V2_0.PhraseRecognitionExtra();
+ halExtra.id = 123;
+ halExtra.confidenceLevel = 52;
+ halExtra.recognitionModes = android.hardware.soundtrigger.V2_0.RecognitionMode.VOICE_TRIGGER
+ | android.hardware.soundtrigger.V2_0.RecognitionMode.GENERIC_TRIGGER;
+ android.hardware.soundtrigger.V2_0.ConfidenceLevel halLevel =
+ new android.hardware.soundtrigger.V2_0.ConfidenceLevel();
+ halLevel.userId = 31;
+ halLevel.levelPercent = 43;
+ halExtra.levels.add(halLevel);
+ halEvent.phraseExtras.add(halExtra);
+ return halEvent;
+ }
+
+ private static void validatePhraseRecognitionEvent(PhraseRecognitionEvent event, int status) {
+ validateRecognitionEvent(event.common, status);
+
+ assertEquals(1, event.phraseExtras.length);
+ assertEquals(123, event.phraseExtras[0].id);
+ assertEquals(52, event.phraseExtras[0].confidenceLevel);
+ assertEquals(RecognitionMode.VOICE_TRIGGER | RecognitionMode.GENERIC_TRIGGER,
+ event.phraseExtras[0].recognitionModes);
+ assertEquals(1, event.phraseExtras[0].levels.length);
+ assertEquals(31, event.phraseExtras[0].levels[0].userId);
+ assertEquals(43, event.phraseExtras[0].levels[0].levelPercent);
+ }
+
+ private void initService(boolean supportConcurrentCapture) throws RemoteException {
+ doAnswer(invocation -> {
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw.Properties properties =
+ createDefaultProperties(
+ supportConcurrentCapture);
+ ((android.hardware.soundtrigger.V2_0.ISoundTriggerHw.getPropertiesCallback) invocation.getArgument(
+ 0)).onValues(0,
+ properties);
+ return null;
+ }).when(mHalDriver).getProperties(any());
+ mService = new SoundTriggerMiddlewareImpl(mHalDriver, mAudioSessionProvider);
+ }
+
+ private int loadGenericModel_2_0(ISoundTriggerModule module, int hwHandle)
+ throws RemoteException {
+ SoundModel model = createGenericSoundModel();
+ ArgumentCaptor<android.hardware.soundtrigger.V2_0.ISoundTriggerHw.SoundModel> modelCaptor =
+ ArgumentCaptor.forClass(
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw.SoundModel.class);
+ doAnswer(invocation -> {
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback callback =
+ invocation.getArgument(1);
+ int callbackCookie = invocation.getArgument(2);
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw.loadSoundModelCallback
+ resultCallback = invocation.getArgument(3);
+
+ // This is the return of this method.
+ resultCallback.onValues(0, hwHandle);
+
+ // This is the async mCallback that comes after.
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.ModelEvent modelEvent =
+ new android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.ModelEvent();
+ modelEvent.status =
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.SoundModelStatus.UPDATED;
+ modelEvent.model = hwHandle;
+ callback.soundModelCallback(modelEvent, callbackCookie);
+ return null;
+ }).when(mHalDriver).loadSoundModel(modelCaptor.capture(), any(), anyInt(), any());
+
+ when(mAudioSessionProvider.acquireSession()).thenReturn(
+ new SoundTriggerMiddlewareImpl.AudioSessionProvider.AudioSession(101, 102, 103));
+
+ int handle = module.loadModel(model);
+ verify(mHalDriver).loadSoundModel(any(), any(), anyInt(), any());
+ verify(mAudioSessionProvider).acquireSession();
+
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw.SoundModel hidlModel =
+ modelCaptor.getValue();
+ assertEquals(android.hardware.soundtrigger.V2_0.SoundModelType.GENERIC,
+ hidlModel.type);
+ assertEquals(model.uuid, ConversionUtil.hidl2aidlUuid(hidlModel.uuid));
+ assertEquals(model.vendorUuid, ConversionUtil.hidl2aidlUuid(hidlModel.vendorUuid));
+ assertArrayEquals(new Byte[]{91, 92, 93, 94, 95}, hidlModel.data.toArray());
+
+ return handle;
+ }
+
+ private int loadGenericModel_2_1(ISoundTriggerModule module, int hwHandle)
+ throws RemoteException {
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw driver =
+ (android.hardware.soundtrigger.V2_1.ISoundTriggerHw) mHalDriver;
+ SoundModel model = createGenericSoundModel();
+ ArgumentCaptor<android.hardware.soundtrigger.V2_1.ISoundTriggerHw.SoundModel> modelCaptor =
+ ArgumentCaptor.forClass(
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.SoundModel.class);
+ doAnswer(invocation -> {
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback callback =
+ invocation.getArgument(1);
+ int callbackCookie = invocation.getArgument(2);
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.loadSoundModel_2_1Callback
+ resultCallback = invocation.getArgument(3);
+
+ // This is the return of this method.
+ resultCallback.onValues(0, hwHandle);
+
+ // This is the async mCallback that comes after.
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.ModelEvent modelEvent =
+ new android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.ModelEvent();
+ modelEvent.header.status =
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.SoundModelStatus.UPDATED;
+ modelEvent.header.model = hwHandle;
+ callback.soundModelCallback_2_1(modelEvent, callbackCookie);
+ return null;
+ }).when(driver).loadSoundModel_2_1(modelCaptor.capture(), any(), anyInt(), any());
+
+ when(mAudioSessionProvider.acquireSession()).thenReturn(
+ new SoundTriggerMiddlewareImpl.AudioSessionProvider.AudioSession(101, 102, 103));
+
+ int handle = module.loadModel(model);
+ verify(driver).loadSoundModel_2_1(any(), any(), anyInt(), any());
+ verify(mAudioSessionProvider).acquireSession();
+
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.SoundModel hidlModel =
+ modelCaptor.getValue();
+ assertEquals(android.hardware.soundtrigger.V2_0.SoundModelType.GENERIC,
+ hidlModel.header.type);
+ assertEquals(model.uuid, ConversionUtil.hidl2aidlUuid(hidlModel.header.uuid));
+ assertEquals(model.vendorUuid, ConversionUtil.hidl2aidlUuid(hidlModel.header.vendorUuid));
+ assertArrayEquals(new byte[]{91, 92, 93, 94, 95},
+ HidlMemoryUtil.hidlMemoryToByteArray(hidlModel.data));
+
+ return handle;
+ }
+
+ private int loadGenericModel(ISoundTriggerModule module, int hwHandle) throws RemoteException {
+ if (mHalDriver instanceof android.hardware.soundtrigger.V2_1.ISoundTriggerHw) {
+ return loadGenericModel_2_1(module, hwHandle);
+ } else {
+ return loadGenericModel_2_0(module, hwHandle);
+ }
+ }
+
+ private int loadPhraseModel_2_0(ISoundTriggerModule module, int hwHandle)
+ throws RemoteException {
+ PhraseSoundModel model = createPhraseSoundModel();
+ ArgumentCaptor<android.hardware.soundtrigger.V2_0.ISoundTriggerHw.PhraseSoundModel>
+ modelCaptor = ArgumentCaptor.forClass(
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw.PhraseSoundModel.class);
+ doAnswer(invocation -> {
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback callback =
+ invocation.getArgument(
+ 1);
+ int callbackCookie = invocation.getArgument(2);
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw.loadPhraseSoundModelCallback
+ resultCallback =
+ invocation.getArgument(
+ 3);
+
+ // This is the return of this method.
+ resultCallback.onValues(0, hwHandle);
+
+ // This is the async mCallback that comes after.
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.ModelEvent modelEvent =
+ new android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.ModelEvent();
+ modelEvent.status =
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.SoundModelStatus.UPDATED;
+ modelEvent.model = hwHandle;
+ callback.soundModelCallback(modelEvent, callbackCookie);
+ return null;
+ }).when(mHalDriver).loadPhraseSoundModel(modelCaptor.capture(), any(), anyInt(), any());
+
+ when(mAudioSessionProvider.acquireSession()).thenReturn(
+ new SoundTriggerMiddlewareImpl.AudioSessionProvider.AudioSession(101, 102, 103));
+
+ int handle = module.loadPhraseModel(model);
+ verify(mHalDriver).loadPhraseSoundModel(any(), any(), anyInt(), any());
+ verify(mAudioSessionProvider).acquireSession();
+
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw.PhraseSoundModel hidlModel =
+ modelCaptor.getValue();
+
+ // Validate common part.
+ assertEquals(android.hardware.soundtrigger.V2_0.SoundModelType.KEYPHRASE,
+ hidlModel.common.type);
+ assertEquals(model.common.uuid, ConversionUtil.hidl2aidlUuid(hidlModel.common.uuid));
+ assertEquals(model.common.vendorUuid,
+ ConversionUtil.hidl2aidlUuid(hidlModel.common.vendorUuid));
+ assertArrayEquals(new Byte[]{91, 92, 93, 94, 95}, hidlModel.common.data.toArray());
+
+ // Validate phrase part.
+ assertEquals(1, hidlModel.phrases.size());
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw.Phrase hidlPhrase =
+ hidlModel.phrases.get(0);
+ assertEquals(123, hidlPhrase.id);
+ assertArrayEquals(new Integer[]{5, 6, 7}, hidlPhrase.users.toArray());
+ assertEquals("locale", hidlPhrase.locale);
+ assertEquals("text", hidlPhrase.text);
+ assertEquals(android.hardware.soundtrigger.V2_0.RecognitionMode.USER_AUTHENTICATION
+ | android.hardware.soundtrigger.V2_0.RecognitionMode.USER_IDENTIFICATION,
+ hidlPhrase.recognitionModes);
+
+ return handle;
+ }
+
+ private int loadPhraseModel_2_1(ISoundTriggerModule module, int hwHandle)
+ throws RemoteException {
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw driver =
+ (android.hardware.soundtrigger.V2_1.ISoundTriggerHw) mHalDriver;
+
+ PhraseSoundModel model = createPhraseSoundModel();
+ ArgumentCaptor<android.hardware.soundtrigger.V2_1.ISoundTriggerHw.PhraseSoundModel>
+ modelCaptor = ArgumentCaptor.forClass(
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.PhraseSoundModel.class);
+ doAnswer(invocation -> {
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback callback =
+ invocation.getArgument(
+ 1);
+ int callbackCookie = invocation.getArgument(2);
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.loadPhraseSoundModel_2_1Callback
+ resultCallback =
+ invocation.getArgument(
+ 3);
+
+ // This is the return of this method.
+ resultCallback.onValues(0, hwHandle);
+
+ // This is the async mCallback that comes after.
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.ModelEvent modelEvent =
+ new android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.ModelEvent();
+ modelEvent.header.status =
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.SoundModelStatus.UPDATED;
+ modelEvent.header.model = hwHandle;
+ callback.soundModelCallback_2_1(modelEvent, callbackCookie);
+ return null;
+ }).when(driver).loadPhraseSoundModel_2_1(modelCaptor.capture(), any(), anyInt(), any());
+
+ when(mAudioSessionProvider.acquireSession()).thenReturn(
+ new SoundTriggerMiddlewareImpl.AudioSessionProvider.AudioSession(101, 102, 103));
+
+ int handle = module.loadPhraseModel(model);
+ verify(driver).loadPhraseSoundModel_2_1(any(), any(), anyInt(), any());
+ verify(mAudioSessionProvider).acquireSession();
+
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.PhraseSoundModel hidlModel =
+ modelCaptor.getValue();
+
+ // Validate common part.
+ assertEquals(android.hardware.soundtrigger.V2_0.SoundModelType.KEYPHRASE,
+ hidlModel.common.header.type);
+ assertEquals(model.common.uuid, ConversionUtil.hidl2aidlUuid(hidlModel.common.header.uuid));
+ assertEquals(model.common.vendorUuid,
+ ConversionUtil.hidl2aidlUuid(hidlModel.common.header.vendorUuid));
+ assertArrayEquals(new byte[]{91, 92, 93, 94, 95},
+ HidlMemoryUtil.hidlMemoryToByteArray(hidlModel.common.data));
+
+ // Validate phrase part.
+ assertEquals(1, hidlModel.phrases.size());
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.Phrase hidlPhrase =
+ hidlModel.phrases.get(0);
+ assertEquals(123, hidlPhrase.id);
+ assertArrayEquals(new Integer[]{5, 6, 7}, hidlPhrase.users.toArray());
+ assertEquals("locale", hidlPhrase.locale);
+ assertEquals("text", hidlPhrase.text);
+ assertEquals(android.hardware.soundtrigger.V2_0.RecognitionMode.USER_AUTHENTICATION
+ | android.hardware.soundtrigger.V2_0.RecognitionMode.USER_IDENTIFICATION,
+ hidlPhrase.recognitionModes);
+
+ return handle;
+ }
+
+ private int loadPhraseModel(ISoundTriggerModule module, int hwHandle) throws RemoteException {
+ if (mHalDriver instanceof android.hardware.soundtrigger.V2_1.ISoundTriggerHw) {
+ return loadPhraseModel_2_1(module, hwHandle);
+ } else {
+ return loadPhraseModel_2_0(module, hwHandle);
+ }
+ }
+
+ private void unloadModel(ISoundTriggerModule module, int handle, int hwHandle)
+ throws RemoteException {
+ module.unloadModel(handle);
+ verify(mHalDriver).unloadSoundModel(hwHandle);
+ verify(mAudioSessionProvider).releaseSession(101);
+ }
+
+ private SoundTriggerHwCallback startRecognition_2_0(ISoundTriggerModule module, int handle,
+ int hwHandle) throws RemoteException {
+ ArgumentCaptor<android.hardware.soundtrigger.V2_0.ISoundTriggerHw.RecognitionConfig>
+ configCaptor = ArgumentCaptor.forClass(
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw.RecognitionConfig.class);
+ ArgumentCaptor<android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback> callbackCaptor =
+ ArgumentCaptor.forClass(
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.class);
+ ArgumentCaptor<Integer> cookieCaptor = ArgumentCaptor.forClass(Integer.class);
+
+ when(mHalDriver.startRecognition(eq(hwHandle), configCaptor.capture(),
+ callbackCaptor.capture(), cookieCaptor.capture())).thenReturn(0);
+
+ RecognitionConfig config = createRecognitionConfig();
+
+ module.startRecognition(handle, config);
+ verify(mHalDriver).startRecognition(eq(hwHandle), any(), any(), anyInt());
+
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHw.RecognitionConfig halConfig =
+ configCaptor.getValue();
+ assertTrue(halConfig.captureRequested);
+ assertEquals(102, halConfig.captureHandle);
+ assertEquals(103, halConfig.captureDevice);
+ assertEquals(1, halConfig.phrases.size());
+ android.hardware.soundtrigger.V2_0.PhraseRecognitionExtra halPhraseExtra =
+ halConfig.phrases.get(0);
+ assertEquals(123, halPhraseExtra.id);
+ assertEquals(4, halPhraseExtra.confidenceLevel);
+ assertEquals(5, halPhraseExtra.recognitionModes);
+ assertEquals(1, halPhraseExtra.levels.size());
+ android.hardware.soundtrigger.V2_0.ConfidenceLevel halLevel = halPhraseExtra.levels.get(0);
+ assertEquals(234, halLevel.userId);
+ assertEquals(34, halLevel.levelPercent);
+ assertArrayEquals(new Byte[]{5, 4, 3, 2, 1}, halConfig.data.toArray());
+
+ return new SoundTriggerHwCallback(callbackCaptor.getValue(), cookieCaptor.getValue());
+ }
+
+ private SoundTriggerHwCallback startRecognition_2_1(ISoundTriggerModule module, int handle,
+ int hwHandle) throws RemoteException {
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw driver =
+ (android.hardware.soundtrigger.V2_1.ISoundTriggerHw) mHalDriver;
+
+ ArgumentCaptor<android.hardware.soundtrigger.V2_1.ISoundTriggerHw.RecognitionConfig>
+ configCaptor = ArgumentCaptor.forClass(
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.RecognitionConfig.class);
+ ArgumentCaptor<android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback> callbackCaptor =
+ ArgumentCaptor.forClass(
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback.class);
+ ArgumentCaptor<Integer> cookieCaptor = ArgumentCaptor.forClass(Integer.class);
+
+ when(driver.startRecognition_2_1(eq(hwHandle), configCaptor.capture(),
+ callbackCaptor.capture(), cookieCaptor.capture())).thenReturn(0);
+
+ RecognitionConfig config = createRecognitionConfig();
+
+ module.startRecognition(handle, config);
+ verify(driver).startRecognition_2_1(eq(hwHandle), any(), any(), anyInt());
+
+ android.hardware.soundtrigger.V2_1.ISoundTriggerHw.RecognitionConfig halConfig =
+ configCaptor.getValue();
+ assertTrue(halConfig.header.captureRequested);
+ assertEquals(102, halConfig.header.captureHandle);
+ assertEquals(103, halConfig.header.captureDevice);
+ assertEquals(1, halConfig.header.phrases.size());
+ android.hardware.soundtrigger.V2_0.PhraseRecognitionExtra halPhraseExtra =
+ halConfig.header.phrases.get(0);
+ assertEquals(123, halPhraseExtra.id);
+ assertEquals(4, halPhraseExtra.confidenceLevel);
+ assertEquals(5, halPhraseExtra.recognitionModes);
+ assertEquals(1, halPhraseExtra.levels.size());
+ android.hardware.soundtrigger.V2_0.ConfidenceLevel halLevel = halPhraseExtra.levels.get(0);
+ assertEquals(234, halLevel.userId);
+ assertEquals(34, halLevel.levelPercent);
+ assertArrayEquals(new byte[]{5, 4, 3, 2, 1},
+ HidlMemoryUtil.hidlMemoryToByteArray(halConfig.data));
+
+ return new SoundTriggerHwCallback(callbackCaptor.getValue(), cookieCaptor.getValue());
+ }
+
+ private SoundTriggerHwCallback startRecognition(ISoundTriggerModule module, int handle,
+ int hwHandle) throws RemoteException {
+ if (mHalDriver instanceof android.hardware.soundtrigger.V2_1.ISoundTriggerHw) {
+ return startRecognition_2_1(module, handle, hwHandle);
+ } else {
+ return startRecognition_2_0(module, handle, hwHandle);
+ }
+ }
+
+ private RecognitionConfig createRecognitionConfig() {
+ RecognitionConfig config = new RecognitionConfig();
+ config.captureRequested = true;
+ config.phraseRecognitionExtras = new PhraseRecognitionExtra[]{new PhraseRecognitionExtra()};
+ config.phraseRecognitionExtras[0].id = 123;
+ config.phraseRecognitionExtras[0].confidenceLevel = 4;
+ config.phraseRecognitionExtras[0].recognitionModes = 5;
+ config.phraseRecognitionExtras[0].levels = new ConfidenceLevel[]{new ConfidenceLevel()};
+ config.phraseRecognitionExtras[0].levels[0].userId = 234;
+ config.phraseRecognitionExtras[0].levels[0].levelPercent = 34;
+ config.data = new byte[]{5, 4, 3, 2, 1};
+ return config;
+ }
+
+ private void stopRecognition(ISoundTriggerModule module, int handle, int hwHandle)
+ throws RemoteException {
+ when(mHalDriver.stopRecognition(hwHandle)).thenReturn(0);
+ module.stopRecognition(handle);
+ verify(mHalDriver).stopRecognition(hwHandle);
+ }
+
+ private void verifyNotStartRecognition() throws RemoteException {
+ verify(mHalDriver, never()).startRecognition(anyInt(), any(), any(), anyInt());
+ if (mHalDriver instanceof android.hardware.soundtrigger.V2_1.ISoundTriggerHw) {
+ verify((android.hardware.soundtrigger.V2_1.ISoundTriggerHw) mHalDriver,
+ never()).startRecognition_2_1(anyInt(), any(), any(), anyInt());
+ }
+ }
+
+
+ @Before
+ public void setUp() throws Exception {
+ clearInvocations(mHalDriver);
+ clearInvocations(mAudioSessionProvider);
+
+ // This binder is associated with the mock, so it can be cast to either version of the
+ // HAL interface.
+ final IHwBinder binder = new IHwBinder() {
+ @Override
+ public void transact(int code, HwParcel request, HwParcel reply, int flags)
+ throws RemoteException {
+ // This is a little hacky, but a very easy way to gracefully reject a request for
+ // an unsupported interface (after queryLocalInterface() returns null, the client
+ // will attempt a remote transaction to obtain the interface. RemoteException will
+ // cause it to give up).
+ throw new RemoteException();
+ }
+
+ @Override
+ public IHwInterface queryLocalInterface(String descriptor) {
+ if (descriptor.equals("android.hardware.soundtrigger@2.0::ISoundTriggerHw")
+ || descriptor.equals("android.hardware.soundtrigger@2.1::ISoundTriggerHw")
+ && mHalDriver instanceof android.hardware.soundtrigger.V2_1.ISoundTriggerHw
+ || descriptor.equals("android.hardware.soundtrigger@2.2::ISoundTriggerHw")
+ && mHalDriver instanceof android.hardware.soundtrigger.V2_2.ISoundTriggerHw
+ || descriptor.equals("android.hardware.soundtrigger@2.3::ISoundTriggerHw")
+ && mHalDriver instanceof android.hardware.soundtrigger.V2_3.ISoundTriggerHw) {
+ return mHalDriver;
+ }
+ return null;
+ }
+
+ @Override
+ public boolean linkToDeath(DeathRecipient recipient, long cookie) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean unlinkToDeath(DeathRecipient recipient) {
+ throw new UnsupportedOperationException();
+ }
+ };
+
+ when(mHalDriver.asBinder()).thenReturn(binder);
+ }
+
+ @Test
+ public void testSetUpAndTearDown() {
+ }
+
+ @Test
+ public void testListModules() throws Exception {
+ initService(true);
+ // Note: input and output properties are NOT the same type, even though they are in any way
+ // equivalent. One is a type that's exposed by the HAL and one is a type that's exposed by
+ // the service. The service actually performs a (trivial) conversion between the two.
+ SoundTriggerModuleDescriptor[] allDescriptors = mService.listModules();
+ assertEquals(1, allDescriptors.length);
+
+ SoundTriggerModuleProperties properties = allDescriptors[0].properties;
+
+ validateDefaultProperties(properties, true);
+ }
+
+ @Test
+ public void testAttachDetach() throws Exception {
+ // Normal attachment / detachment.
+ initService(true);
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+ verify(callback).onRecognitionAvailabilityChange(true);
+ assertNotNull(module);
+ module.detach();
+ }
+
+ @Test
+ public void testAttachDetachNotAvailable() throws Exception {
+ // Attachment / detachment during external capture, with a module not supporting concurrent
+ // capture.
+ initService(false);
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+ verify(callback).onRecognitionAvailabilityChange(false);
+ assertNotNull(module);
+ module.detach();
+ }
+
+ @Test
+ public void testAttachDetachAvailable() throws Exception {
+ // Attachment / detachment during external capture, with a module supporting concurrent
+ // capture.
+ initService(true);
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+ verify(callback).onRecognitionAvailabilityChange(true);
+ assertNotNull(module);
+ module.detach();
+ }
+
+ @Test
+ public void testLoadUnloadModel() throws Exception {
+ initService(true);
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+
+ final int hwHandle = 7;
+ int handle = loadGenericModel(module, hwHandle);
+ unloadModel(module, handle, hwHandle);
+ module.detach();
+ }
+
+ @Test
+ public void testLoadUnloadPhraseModel() throws Exception {
+ initService(true);
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+
+ final int hwHandle = 73;
+ int handle = loadPhraseModel(module, hwHandle);
+ unloadModel(module, handle, hwHandle);
+ module.detach();
+ }
+
+ @Test
+ public void testStartStopRecognition() throws Exception {
+ initService(true);
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+
+ // Load the model.
+ final int hwHandle = 7;
+ int handle = loadGenericModel(module, hwHandle);
+
+ // Initiate a recognition.
+ startRecognition(module, handle, hwHandle);
+
+ // Stop the recognition.
+ stopRecognition(module, handle, hwHandle);
+
+ // Unload the model.
+ unloadModel(module, handle, hwHandle);
+ module.detach();
+ }
+
+ @Test
+ public void testStartStopPhraseRecognition() throws Exception {
+ initService(true);
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+
+ // Load the model.
+ final int hwHandle = 67;
+ int handle = loadPhraseModel(module, hwHandle);
+
+ // Initiate a recognition.
+ startRecognition(module, handle, hwHandle);
+
+ // Stop the recognition.
+ stopRecognition(module, handle, hwHandle);
+
+ // Unload the model.
+ unloadModel(module, handle, hwHandle);
+ module.detach();
+ }
+
+ @Test
+ public void testRecognition() throws Exception {
+ initService(true);
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+
+ // Load the model.
+ final int hwHandle = 7;
+ int handle = loadGenericModel(module, hwHandle);
+
+ // Initiate a recognition.
+ SoundTriggerHwCallback hwCallback = startRecognition(module, handle, hwHandle);
+
+ // Signal a capture from the driver.
+ hwCallback.sendRecognitionEvent(hwHandle,
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.RecognitionStatus.SUCCESS);
+
+ ArgumentCaptor<RecognitionEvent> eventCaptor = ArgumentCaptor.forClass(
+ RecognitionEvent.class);
+ verify(callback).onRecognition(eq(handle), eventCaptor.capture());
+
+ // Validate the event.
+ validateRecognitionEvent(eventCaptor.getValue(), RecognitionStatus.SUCCESS);
+
+ // Unload the model.
+ unloadModel(module, handle, hwHandle);
+ module.detach();
+ }
+
+ @Test
+ public void testPhraseRecognition() throws Exception {
+ initService(true);
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+
+ // Load the model.
+ final int hwHandle = 7;
+ int handle = loadPhraseModel(module, hwHandle);
+
+ // Initiate a recognition.
+ SoundTriggerHwCallback hwCallback = startRecognition(module, handle, hwHandle);
+
+ // Signal a capture from the driver.
+ hwCallback.sendPhraseRecognitionEvent(hwHandle,
+ android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback.RecognitionStatus.SUCCESS);
+
+ ArgumentCaptor<PhraseRecognitionEvent> eventCaptor = ArgumentCaptor.forClass(
+ PhraseRecognitionEvent.class);
+ verify(callback).onPhraseRecognition(eq(handle), eventCaptor.capture());
+
+ // Validate the event.
+ validatePhraseRecognitionEvent(eventCaptor.getValue(), RecognitionStatus.SUCCESS);
+
+ // Unload the model.
+ unloadModel(module, handle, hwHandle);
+ module.detach();
+ }
+
+ @Test
+ public void testForceRecognition() throws Exception {
+ if (!(mHalDriver instanceof android.hardware.soundtrigger.V2_2.ISoundTriggerHw)) {
+ return;
+ }
+
+ android.hardware.soundtrigger.V2_2.ISoundTriggerHw driver =
+ (android.hardware.soundtrigger.V2_2.ISoundTriggerHw) mHalDriver;
+
+ initService(true);
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+
+ // Load the model.
+ final int hwHandle = 17;
+ int handle = loadGenericModel(module, hwHandle);
+
+ // Initiate a recognition.
+ SoundTriggerHwCallback hwCallback = startRecognition(module, handle, hwHandle);
+
+ // Force a trigger.
+ module.forceRecognitionEvent(handle);
+ verify(driver).getModelState(hwHandle);
+
+ // Signal a capture from the driver.
+ // '3' means 'forced', there's no constant for that in the HAL.
+ hwCallback.sendRecognitionEvent(hwHandle, 3);
+
+ ArgumentCaptor<RecognitionEvent> eventCaptor = ArgumentCaptor.forClass(
+ RecognitionEvent.class);
+ verify(callback).onRecognition(eq(handle), eventCaptor.capture());
+
+ // Validate the event.
+ validateRecognitionEvent(eventCaptor.getValue(), RecognitionStatus.FORCED);
+
+ // Stop the recognition.
+ stopRecognition(module, handle, hwHandle);
+
+ // Unload the model.
+ unloadModel(module, handle, hwHandle);
+ module.detach();
+ }
+
+ @Test
+ public void testForcePhraseRecognition() throws Exception {
+ if (!(mHalDriver instanceof android.hardware.soundtrigger.V2_2.ISoundTriggerHw)) {
+ return;
+ }
+
+ android.hardware.soundtrigger.V2_2.ISoundTriggerHw driver =
+ (android.hardware.soundtrigger.V2_2.ISoundTriggerHw) mHalDriver;
+
+ initService(true);
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+
+ // Load the model.
+ final int hwHandle = 17;
+ int handle = loadPhraseModel(module, hwHandle);
+
+ // Initiate a recognition.
+ SoundTriggerHwCallback hwCallback = startRecognition(module, handle, hwHandle);
+
+ // Force a trigger.
+ module.forceRecognitionEvent(handle);
+ verify(driver).getModelState(hwHandle);
+
+ // Signal a capture from the driver.
+ // '3' means 'forced', there's no constant for that in the HAL.
+ hwCallback.sendPhraseRecognitionEvent(hwHandle, 3);
+
+ ArgumentCaptor<PhraseRecognitionEvent> eventCaptor = ArgumentCaptor.forClass(
+ PhraseRecognitionEvent.class);
+ verify(callback).onPhraseRecognition(eq(handle), eventCaptor.capture());
+
+ // Validate the event.
+ validatePhraseRecognitionEvent(eventCaptor.getValue(), RecognitionStatus.FORCED);
+
+ // Stop the recognition.
+ stopRecognition(module, handle, hwHandle);
+
+ // Unload the model.
+ unloadModel(module, handle, hwHandle);
+ module.detach();
+ }
+
+ @Test
+ public void testAbortRecognition() throws Exception {
+ // Make sure the HAL doesn't support concurrent capture.
+ initService(false);
+ mService.setExternalCaptureState(false);
+
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+ verify(callback).onRecognitionAvailabilityChange(true);
+
+ // Load the model.
+ final int hwHandle = 11;
+ int handle = loadGenericModel(module, hwHandle);
+
+ // Initiate a recognition.
+ startRecognition(module, handle, hwHandle);
+
+ // Abort.
+ mService.setExternalCaptureState(true);
+
+ ArgumentCaptor<RecognitionEvent> eventCaptor = ArgumentCaptor.forClass(
+ RecognitionEvent.class);
+ verify(callback).onRecognition(eq(handle), eventCaptor.capture());
+
+ // Validate the event.
+ assertEquals(RecognitionStatus.ABORTED, eventCaptor.getValue().status);
+
+ // Make sure we are notified of the lost availability.
+ verify(callback).onRecognitionAvailabilityChange(false);
+
+ // Attempt to start a new recognition - should get an abort event immediately, without
+ // involving the HAL.
+ clearInvocations(callback);
+ clearInvocations(mHalDriver);
+ module.startRecognition(handle, createRecognitionConfig());
+ verify(callback).onRecognition(eq(handle), eventCaptor.capture());
+ assertEquals(RecognitionStatus.ABORTED, eventCaptor.getValue().status);
+ verifyNotStartRecognition();
+
+ // Now enable it and make sure we are notified.
+ mService.setExternalCaptureState(false);
+ verify(callback).onRecognitionAvailabilityChange(true);
+
+ // Unload the model.
+ unloadModel(module, handle, hwHandle);
+ module.detach();
+ }
+
+ @Test
+ public void testAbortPhraseRecognition() throws Exception {
+ // Make sure the HAL doesn't support concurrent capture.
+ initService(false);
+ mService.setExternalCaptureState(false);
+
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+ verify(callback).onRecognitionAvailabilityChange(true);
+
+ // Load the model.
+ final int hwHandle = 11;
+ int handle = loadPhraseModel(module, hwHandle);
+
+ // Initiate a recognition.
+ startRecognition(module, handle, hwHandle);
+
+ // Abort.
+ mService.setExternalCaptureState(true);
+
+ ArgumentCaptor<PhraseRecognitionEvent> eventCaptor = ArgumentCaptor.forClass(
+ PhraseRecognitionEvent.class);
+ verify(callback).onPhraseRecognition(eq(handle), eventCaptor.capture());
+
+ // Validate the event.
+ assertEquals(RecognitionStatus.ABORTED, eventCaptor.getValue().common.status);
+
+ // Make sure we are notified of the lost availability.
+ verify(callback).onRecognitionAvailabilityChange(false);
+
+ // Attempt to start a new recognition - should get an abort event immediately, without
+ // involving the HAL.
+ clearInvocations(callback);
+ clearInvocations(mHalDriver);
+ module.startRecognition(handle, createRecognitionConfig());
+ verify(callback).onPhraseRecognition(eq(handle), eventCaptor.capture());
+ assertEquals(RecognitionStatus.ABORTED, eventCaptor.getValue().common.status);
+ verifyNotStartRecognition();
+
+ // Now enable it and make sure we are notified.
+ mService.setExternalCaptureState(false);
+ verify(callback).onRecognitionAvailabilityChange(true);
+
+ // Unload the model.
+ unloadModel(module, handle, hwHandle);
+ module.detach();
+ }
+
+ @Test
+ public void testNotAbortRecognitionConcurrent() throws Exception {
+ // Make sure the HAL supports concurrent capture.
+ initService(true);
+
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+ verify(callback).onRecognitionAvailabilityChange(true);
+ clearInvocations(callback);
+
+ // Load the model.
+ final int hwHandle = 13;
+ int handle = loadGenericModel(module, hwHandle);
+
+ // Initiate a recognition.
+ startRecognition(module, handle, hwHandle);
+
+ // Signal concurrent capture. Shouldn't abort.
+ mService.setExternalCaptureState(true);
+ verify(callback, never()).onRecognition(anyInt(), any());
+ verify(callback, never()).onRecognitionAvailabilityChange(anyBoolean());
+
+ // Stop the recognition.
+ stopRecognition(module, handle, hwHandle);
+
+ // Initiating a new one should work fine.
+ clearInvocations(mHalDriver);
+ startRecognition(module, handle, hwHandle);
+ verify(callback, never()).onRecognition(anyInt(), any());
+ stopRecognition(module, handle, hwHandle);
+
+ // Unload the model.
+ module.unloadModel(handle);
+ module.detach();
+ }
+
+ @Test
+ public void testNotAbortPhraseRecognitionConcurrent() throws Exception {
+ // Make sure the HAL supports concurrent capture.
+ initService(true);
+
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+ verify(callback).onRecognitionAvailabilityChange(true);
+ clearInvocations(callback);
+
+ // Load the model.
+ final int hwHandle = 13;
+ int handle = loadPhraseModel(module, hwHandle);
+
+ // Initiate a recognition.
+ startRecognition(module, handle, hwHandle);
+
+ // Signal concurrent capture. Shouldn't abort.
+ mService.setExternalCaptureState(true);
+ verify(callback, never()).onPhraseRecognition(anyInt(), any());
+ verify(callback, never()).onRecognitionAvailabilityChange(anyBoolean());
+
+ // Stop the recognition.
+ stopRecognition(module, handle, hwHandle);
+
+ // Initiating a new one should work fine.
+ clearInvocations(mHalDriver);
+ startRecognition(module, handle, hwHandle);
+ verify(callback, never()).onRecognition(anyInt(), any());
+ stopRecognition(module, handle, hwHandle);
+
+ // Unload the model.
+ module.unloadModel(handle);
+ module.detach();
+ }
+
+ @Test
+ public void testParameterSupported() throws Exception {
+ if (!(mHalDriver instanceof android.hardware.soundtrigger.V2_3.ISoundTriggerHw)) {
+ return;
+ }
+
+ android.hardware.soundtrigger.V2_3.ISoundTriggerHw driver =
+ (android.hardware.soundtrigger.V2_3.ISoundTriggerHw) mHalDriver;
+
+ initService(false);
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+ final int hwHandle = 12;
+ int modelHandle = loadGenericModel(module, hwHandle);
+
+ doAnswer((Answer<Void>) invocation -> {
+ android.hardware.soundtrigger.V2_3.ISoundTriggerHw.queryParameterCallback
+ resultCallback = invocation.getArgument(2);
+ android.hardware.soundtrigger.V2_3.ModelParameterRange range =
+ new android.hardware.soundtrigger.V2_3.ModelParameterRange();
+ range.start = 23;
+ range.end = 45;
+ OptionalModelParameterRange optionalRange = new OptionalModelParameterRange();
+ optionalRange.range(range);
+ resultCallback.onValues(0, optionalRange);
+ return null;
+ }).when(driver).queryParameter(eq(hwHandle),
+ eq(android.hardware.soundtrigger.V2_3.ModelParameter.THRESHOLD_FACTOR), any());
+
+ ModelParameterRange range = module.queryModelParameterSupport(modelHandle,
+ ModelParameter.THRESHOLD_FACTOR);
+
+ verify(driver).queryParameter(eq(hwHandle),
+ eq(android.hardware.soundtrigger.V2_3.ModelParameter.THRESHOLD_FACTOR), any());
+
+ assertEquals(23, range.minInclusive);
+ assertEquals(45, range.maxInclusive);
+ }
+
+ @Test
+ public void testParameterNotSupportedOld() throws Exception {
+ if (mHalDriver instanceof android.hardware.soundtrigger.V2_3.ISoundTriggerHw) {
+ return;
+ }
+
+ initService(false);
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+ final int hwHandle = 13;
+ int modelHandle = loadGenericModel(module, hwHandle);
+
+ ModelParameterRange range = module.queryModelParameterSupport(modelHandle,
+ ModelParameter.THRESHOLD_FACTOR);
+
+ assertNull(range);
+ }
+
+ @Test
+ public void testParameterNotSupported() throws Exception {
+ if (!(mHalDriver instanceof android.hardware.soundtrigger.V2_3.ISoundTriggerHw)) {
+ return;
+ }
+
+ android.hardware.soundtrigger.V2_3.ISoundTriggerHw driver =
+ (android.hardware.soundtrigger.V2_3.ISoundTriggerHw) mHalDriver;
+
+ initService(false);
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+ final int hwHandle = 13;
+ int modelHandle = loadGenericModel(module, hwHandle);
+
+ doAnswer(invocation -> {
+ android.hardware.soundtrigger.V2_3.ISoundTriggerHw.queryParameterCallback
+ resultCallback = invocation.getArgument(2);
+ // This is the return of this method.
+ resultCallback.onValues(0, new OptionalModelParameterRange());
+ return null;
+ }).when(driver).queryParameter(eq(hwHandle),
+ eq(android.hardware.soundtrigger.V2_3.ModelParameter.THRESHOLD_FACTOR), any());
+
+ ModelParameterRange range = module.queryModelParameterSupport(modelHandle,
+ ModelParameter.THRESHOLD_FACTOR);
+
+ verify(driver).queryParameter(eq(hwHandle),
+ eq(android.hardware.soundtrigger.V2_3.ModelParameter.THRESHOLD_FACTOR), any());
+
+ assertNull(range);
+ }
+
+ @Test
+ public void testGetParameter() throws Exception {
+ if (!(mHalDriver instanceof android.hardware.soundtrigger.V2_3.ISoundTriggerHw)) {
+ return;
+ }
+
+ android.hardware.soundtrigger.V2_3.ISoundTriggerHw driver =
+ (android.hardware.soundtrigger.V2_3.ISoundTriggerHw) mHalDriver;
+
+ initService(false);
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+ final int hwHandle = 14;
+ int modelHandle = loadGenericModel(module, hwHandle);
+
+ doAnswer(invocation -> {
+ android.hardware.soundtrigger.V2_3.ISoundTriggerHw.getParameterCallback
+ resultCallback = invocation.getArgument(2);
+ // This is the return of this method.
+ resultCallback.onValues(0, 234);
+ return null;
+ }).when(driver).getParameter(eq(hwHandle),
+ eq(android.hardware.soundtrigger.V2_3.ModelParameter.THRESHOLD_FACTOR), any());
+
+ int value = module.getModelParameter(modelHandle, ModelParameter.THRESHOLD_FACTOR);
+
+ verify(driver).getParameter(eq(hwHandle),
+ eq(android.hardware.soundtrigger.V2_3.ModelParameter.THRESHOLD_FACTOR), any());
+
+ assertEquals(234, value);
+ }
+
+ @Test
+ public void testSetParameter() throws Exception {
+ if (!(mHalDriver instanceof android.hardware.soundtrigger.V2_3.ISoundTriggerHw)) {
+ return;
+ }
+
+ android.hardware.soundtrigger.V2_3.ISoundTriggerHw driver =
+ (android.hardware.soundtrigger.V2_3.ISoundTriggerHw) mHalDriver;
+
+ initService(false);
+ ISoundTriggerCallback callback = createCallbackMock();
+ ISoundTriggerModule module = mService.attach(0, callback);
+ final int hwHandle = 17;
+ int modelHandle = loadGenericModel(module, hwHandle);
+
+ when(driver.setParameter(hwHandle,
+ android.hardware.soundtrigger.V2_3.ModelParameter.THRESHOLD_FACTOR,
+ 456)).thenReturn(0);
+
+ module.setModelParameter(modelHandle, ModelParameter.THRESHOLD_FACTOR, 456);
+
+ verify(driver).setParameter(hwHandle,
+ android.hardware.soundtrigger.V2_3.ModelParameter.THRESHOLD_FACTOR, 456);
+ }
+
+ private static class SoundTriggerHwCallback {
+ private final android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback mCallback;
+ private final int mCookie;
+
+ SoundTriggerHwCallback(android.hardware.soundtrigger.V2_0.ISoundTriggerHwCallback callback,
+ int cookie) {
+ mCallback = callback;
+ mCookie = cookie;
+ }
+
+ private void sendRecognitionEvent(int hwHandle, int status) throws RemoteException {
+ if (mCallback instanceof android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback) {
+ ((android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback) mCallback).recognitionCallback_2_1(
+ createRecognitionEvent_2_1(hwHandle, status), mCookie);
+ } else {
+ mCallback.recognitionCallback(createRecognitionEvent_2_0(hwHandle, status),
+ mCookie);
+ }
+ }
+
+ private void sendPhraseRecognitionEvent(int hwHandle, int status) throws RemoteException {
+ if (mCallback instanceof android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback) {
+ ((android.hardware.soundtrigger.V2_1.ISoundTriggerHwCallback) mCallback).phraseRecognitionCallback_2_1(
+ createPhraseRecognitionEvent_2_1(hwHandle, status), mCookie);
+ } else {
+ mCallback.phraseRecognitionCallback(
+ createPhraseRecognitionEvent_2_0(hwHandle, status), mCookie);
+ }
+ }
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/timedetector/SimpleTimeDetectorStrategyTest.java b/services/tests/servicestests/src/com/android/server/timedetector/SimpleTimeDetectorStrategyTest.java
deleted file mode 100644
index 7a0a28dfbd16..000000000000
--- a/services/tests/servicestests/src/com/android/server/timedetector/SimpleTimeDetectorStrategyTest.java
+++ /dev/null
@@ -1,661 +0,0 @@
-/*
- * Copyright (C) 2018 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 com.android.server.timedetector;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import android.app.timedetector.ManualTimeSuggestion;
-import android.app.timedetector.PhoneTimeSuggestion;
-import android.content.Intent;
-import android.icu.util.Calendar;
-import android.icu.util.GregorianCalendar;
-import android.icu.util.TimeZone;
-import android.util.TimestampedValue;
-
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.time.Duration;
-
-@RunWith(AndroidJUnit4.class)
-public class SimpleTimeDetectorStrategyTest {
-
- private static final Scenario SCENARIO_1 = new Scenario.Builder()
- .setInitialDeviceSystemClockUtc(1977, 1, 1, 12, 0, 0)
- .setInitialDeviceRealtimeMillis(123456789L)
- .setActualTimeUtc(2018, 1, 1, 12, 0, 0)
- .build();
-
- private static final int ARBITRARY_PHONE_ID = 123456;
-
- private static final long ONE_DAY_MILLIS = Duration.ofDays(1).toMillis();
-
- private Script mScript;
-
- @Before
- public void setUp() {
- mScript = new Script();
- }
-
- @Test
- public void testSuggestPhoneTime_autoTimeEnabled() {
- Scenario scenario = SCENARIO_1;
- mScript.pokeFakeClocks(scenario)
- .pokeTimeDetectionEnabled(true);
-
- PhoneTimeSuggestion timeSuggestion =
- scenario.createPhoneTimeSuggestionForActual(ARBITRARY_PHONE_ID);
- final int clockIncrement = 1000;
- long expectSystemClockMillis = scenario.getActualTimeMillis() + clockIncrement;
-
- mScript.simulateTimePassing(clockIncrement)
- .simulatePhoneTimeSuggestion(timeSuggestion)
- .verifySystemClockWasSetAndResetCallTracking(
- expectSystemClockMillis, true /* expectNetworkBroadcast */);
- }
-
- @Test
- public void testSuggestPhoneTime_emptySuggestionIgnored() {
- Scenario scenario = SCENARIO_1;
- mScript.pokeFakeClocks(scenario)
- .pokeTimeDetectionEnabled(true);
-
- PhoneTimeSuggestion timeSuggestion = createPhoneTimeSuggestion(ARBITRARY_PHONE_ID, null);
-
- mScript.simulatePhoneTimeSuggestion(timeSuggestion)
- .verifySystemClockWasNotSetAndResetCallTracking();
- }
-
- @Test
- public void testSuggestPhoneTime_systemClockThreshold() {
- Scenario scenario = SCENARIO_1;
- final int systemClockUpdateThresholdMillis = 1000;
- mScript.pokeFakeClocks(scenario)
- .pokeThresholds(systemClockUpdateThresholdMillis)
- .pokeTimeDetectionEnabled(true);
-
- PhoneTimeSuggestion timeSuggestion1 =
- scenario.createPhoneTimeSuggestionForActual(ARBITRARY_PHONE_ID);
- TimestampedValue<Long> utcTime1 = timeSuggestion1.getUtcTime();
-
- final int clockIncrement = 100;
- // Increment the the device clocks to simulate the passage of time.
- mScript.simulateTimePassing(clockIncrement);
-
- long expectSystemClockMillis1 =
- TimeDetectorStrategy.getTimeAt(utcTime1, mScript.peekElapsedRealtimeMillis());
-
- // Send the first time signal. It should be used.
- mScript.simulatePhoneTimeSuggestion(timeSuggestion1)
- .verifySystemClockWasSetAndResetCallTracking(
- expectSystemClockMillis1, true /* expectNetworkBroadcast */);
-
- // Now send another time signal, but one that is too similar to the last one and should be
- // ignored.
- int underThresholdMillis = systemClockUpdateThresholdMillis - 1;
- TimestampedValue<Long> utcTime2 = new TimestampedValue<>(
- mScript.peekElapsedRealtimeMillis(),
- mScript.peekSystemClockMillis() + underThresholdMillis);
- PhoneTimeSuggestion timeSuggestion2 =
- createPhoneTimeSuggestion(ARBITRARY_PHONE_ID, utcTime2);
- mScript.simulateTimePassing(clockIncrement)
- .simulatePhoneTimeSuggestion(timeSuggestion2)
- .verifySystemClockWasNotSetAndResetCallTracking();
-
- // Now send another time signal, but one that is on the threshold and so should be used.
- TimestampedValue<Long> utcTime3 = new TimestampedValue<>(
- mScript.peekElapsedRealtimeMillis(),
- mScript.peekSystemClockMillis() + systemClockUpdateThresholdMillis);
-
- PhoneTimeSuggestion timeSuggestion3 =
- createPhoneTimeSuggestion(ARBITRARY_PHONE_ID, utcTime3);
- mScript.simulateTimePassing(clockIncrement);
-
- long expectSystemClockMillis3 =
- TimeDetectorStrategy.getTimeAt(utcTime3, mScript.peekElapsedRealtimeMillis());
-
- mScript.simulatePhoneTimeSuggestion(timeSuggestion3)
- .verifySystemClockWasSetAndResetCallTracking(
- expectSystemClockMillis3, true /* expectNetworkBroadcast */);
- }
-
- @Test
- public void testSuggestPhoneTime_autoTimeDisabled() {
- Scenario scenario = SCENARIO_1;
- mScript.pokeFakeClocks(scenario)
- .pokeTimeDetectionEnabled(false);
-
- PhoneTimeSuggestion timeSuggestion =
- scenario.createPhoneTimeSuggestionForActual(ARBITRARY_PHONE_ID);
- mScript.simulatePhoneTimeSuggestion(timeSuggestion)
- .verifySystemClockWasNotSetAndResetCallTracking();
- }
-
- @Test
- public void testSuggestPhoneTime_invalidNitzReferenceTimesIgnored() {
- Scenario scenario = SCENARIO_1;
- final int systemClockUpdateThreshold = 2000;
- mScript.pokeFakeClocks(scenario)
- .pokeThresholds(systemClockUpdateThreshold)
- .pokeTimeDetectionEnabled(true);
- PhoneTimeSuggestion timeSuggestion1 =
- scenario.createPhoneTimeSuggestionForActual(ARBITRARY_PHONE_ID);
- TimestampedValue<Long> utcTime1 = timeSuggestion1.getUtcTime();
-
- // Initialize the strategy / device with a time set from NITZ.
- mScript.simulateTimePassing(100);
- long expectedSystemClockMillis1 =
- TimeDetectorStrategy.getTimeAt(utcTime1, mScript.peekElapsedRealtimeMillis());
- mScript.simulatePhoneTimeSuggestion(timeSuggestion1)
- .verifySystemClockWasSetAndResetCallTracking(
- expectedSystemClockMillis1, true /* expectNetworkBroadcast */);
-
- // The UTC time increment should be larger than the system clock update threshold so we
- // know it shouldn't be ignored for other reasons.
- long validUtcTimeMillis = utcTime1.getValue() + (2 * systemClockUpdateThreshold);
-
- // Now supply a new signal that has an obviously bogus reference time : older than the last
- // one.
- long referenceTimeBeforeLastSignalMillis = utcTime1.getReferenceTimeMillis() - 1;
- TimestampedValue<Long> utcTime2 = new TimestampedValue<>(
- referenceTimeBeforeLastSignalMillis, validUtcTimeMillis);
- PhoneTimeSuggestion timeSuggestion2 =
- createPhoneTimeSuggestion(ARBITRARY_PHONE_ID, utcTime2);
- mScript.simulatePhoneTimeSuggestion(timeSuggestion2)
- .verifySystemClockWasNotSetAndResetCallTracking();
-
- // Now supply a new signal that has an obviously bogus reference time : substantially in the
- // future.
- long referenceTimeInFutureMillis =
- utcTime1.getReferenceTimeMillis() + Integer.MAX_VALUE + 1;
- TimestampedValue<Long> utcTime3 = new TimestampedValue<>(
- referenceTimeInFutureMillis, validUtcTimeMillis);
- PhoneTimeSuggestion timeSuggestion3 =
- createPhoneTimeSuggestion(ARBITRARY_PHONE_ID, utcTime3);
- mScript.simulatePhoneTimeSuggestion(timeSuggestion3)
- .verifySystemClockWasNotSetAndResetCallTracking();
-
- // Just to prove validUtcTimeMillis is valid.
- long validReferenceTimeMillis = utcTime1.getReferenceTimeMillis() + 100;
- TimestampedValue<Long> utcTime4 = new TimestampedValue<>(
- validReferenceTimeMillis, validUtcTimeMillis);
- long expectedSystemClockMillis4 =
- TimeDetectorStrategy.getTimeAt(utcTime4, mScript.peekElapsedRealtimeMillis());
- PhoneTimeSuggestion timeSuggestion4 =
- createPhoneTimeSuggestion(ARBITRARY_PHONE_ID, utcTime4);
- mScript.simulatePhoneTimeSuggestion(timeSuggestion4)
- .verifySystemClockWasSetAndResetCallTracking(
- expectedSystemClockMillis4, true /* expectNetworkBroadcast */);
- }
-
- @Test
- public void testSuggestPhoneTime_timeDetectionToggled() {
- Scenario scenario = SCENARIO_1;
- final int clockIncrementMillis = 100;
- final int systemClockUpdateThreshold = 2000;
- mScript.pokeFakeClocks(scenario)
- .pokeThresholds(systemClockUpdateThreshold)
- .pokeTimeDetectionEnabled(false);
-
- PhoneTimeSuggestion timeSuggestion1 =
- scenario.createPhoneTimeSuggestionForActual(ARBITRARY_PHONE_ID);
- TimestampedValue<Long> utcTime1 = timeSuggestion1.getUtcTime();
-
- // Simulate time passing.
- mScript.simulateTimePassing(clockIncrementMillis);
-
- // Simulate the time signal being received. It should not be used because auto time
- // detection is off but it should be recorded.
- mScript.simulatePhoneTimeSuggestion(timeSuggestion1)
- .verifySystemClockWasNotSetAndResetCallTracking();
-
- // Simulate more time passing.
- mScript.simulateTimePassing(clockIncrementMillis);
-
- long expectedSystemClockMillis1 =
- TimeDetectorStrategy.getTimeAt(utcTime1, mScript.peekElapsedRealtimeMillis());
-
- // Turn on auto time detection.
- mScript.simulateAutoTimeDetectionToggle()
- .verifySystemClockWasSetAndResetCallTracking(
- expectedSystemClockMillis1, true /* expectNetworkBroadcast */);
-
- // Turn off auto time detection.
- mScript.simulateAutoTimeDetectionToggle()
- .verifySystemClockWasNotSetAndResetCallTracking();
-
- // Receive another valid time signal.
- // It should be on the threshold and accounting for the clock increments.
- TimestampedValue<Long> utcTime2 = new TimestampedValue<>(
- mScript.peekElapsedRealtimeMillis(),
- mScript.peekSystemClockMillis() + systemClockUpdateThreshold);
- PhoneTimeSuggestion timeSuggestion2 =
- createPhoneTimeSuggestion(ARBITRARY_PHONE_ID, utcTime2);
-
- // Simulate more time passing.
- mScript.simulateTimePassing(clockIncrementMillis);
-
- long expectedSystemClockMillis2 =
- TimeDetectorStrategy.getTimeAt(utcTime2, mScript.peekElapsedRealtimeMillis());
-
- // The new time, though valid, should not be set in the system clock because auto time is
- // disabled.
- mScript.simulatePhoneTimeSuggestion(timeSuggestion2)
- .verifySystemClockWasNotSetAndResetCallTracking();
-
- // Turn on auto time detection.
- mScript.simulateAutoTimeDetectionToggle()
- .verifySystemClockWasSetAndResetCallTracking(
- expectedSystemClockMillis2, true /* expectNetworkBroadcast */);
- }
-
- @Test
- public void testSuggestManualTime_autoTimeDisabled() {
- Scenario scenario = SCENARIO_1;
- mScript.pokeFakeClocks(scenario)
- .pokeTimeDetectionEnabled(false);
-
- ManualTimeSuggestion timeSuggestion = scenario.createManualTimeSuggestionForActual();
- final int clockIncrement = 1000;
- long expectSystemClockMillis = scenario.getActualTimeMillis() + clockIncrement;
-
- mScript.simulateTimePassing(clockIncrement)
- .simulateManualTimeSuggestion(timeSuggestion)
- .verifySystemClockWasSetAndResetCallTracking(
- expectSystemClockMillis, false /* expectNetworkBroadcast */);
- }
-
- @Test
- public void testSuggestManualTime_retainsAutoSignal() {
- Scenario scenario = SCENARIO_1;
-
- // Configure the start state.
- mScript.pokeFakeClocks(scenario)
- .pokeTimeDetectionEnabled(true);
-
- // Simulate a phone suggestion.
- PhoneTimeSuggestion phoneTimeSuggestion =
- scenario.createPhoneTimeSuggestionForActual(ARBITRARY_PHONE_ID);
- long expectedAutoClockMillis = phoneTimeSuggestion.getUtcTime().getValue();
- final int clockIncrement = 1000;
-
- // Simulate the passage of time.
- mScript.simulateTimePassing(clockIncrement);
- expectedAutoClockMillis += clockIncrement;
-
- mScript.simulatePhoneTimeSuggestion(phoneTimeSuggestion)
- .verifySystemClockWasSetAndResetCallTracking(
- expectedAutoClockMillis, true /* expectNetworkBroadcast */);
-
- // Simulate the passage of time.
- mScript.simulateTimePassing(clockIncrement);
- expectedAutoClockMillis += clockIncrement;
-
- // Switch to manual.
- mScript.simulateAutoTimeDetectionToggle()
- .verifySystemClockWasNotSetAndResetCallTracking();
-
- // Simulate the passage of time.
- mScript.simulateTimePassing(clockIncrement);
- expectedAutoClockMillis += clockIncrement;
-
-
- // Simulate a manual suggestion 1 day different from the auto suggestion.
- long manualTimeMillis = SCENARIO_1.getActualTimeMillis() + ONE_DAY_MILLIS;
- long expectedManualClockMillis = manualTimeMillis;
- ManualTimeSuggestion manualTimeSuggestion = createManualTimeSuggestion(manualTimeMillis);
- mScript.simulateManualTimeSuggestion(manualTimeSuggestion)
- .verifySystemClockWasSetAndResetCallTracking(
- expectedManualClockMillis, false /* expectNetworkBroadcast */);
-
- // Simulate the passage of time.
- mScript.simulateTimePassing(clockIncrement);
- expectedAutoClockMillis += clockIncrement;
-
- // Switch back to auto.
- mScript.simulateAutoTimeDetectionToggle();
-
- mScript.verifySystemClockWasSetAndResetCallTracking(
- expectedAutoClockMillis, true /* expectNetworkBroadcast */);
-
- // Switch back to manual - nothing should happen to the clock.
- mScript.simulateAutoTimeDetectionToggle()
- .verifySystemClockWasNotSetAndResetCallTracking();
- }
-
- /**
- * Manual suggestions should be ignored if auto time is enabled.
- */
- @Test
- public void testSuggestManualTime_autoTimeEnabled() {
- Scenario scenario = SCENARIO_1;
- mScript.pokeFakeClocks(scenario)
- .pokeTimeDetectionEnabled(true);
-
- ManualTimeSuggestion timeSuggestion = scenario.createManualTimeSuggestionForActual();
- final int clockIncrement = 1000;
-
- mScript.simulateTimePassing(clockIncrement)
- .simulateManualTimeSuggestion(timeSuggestion)
- .verifySystemClockWasNotSetAndResetCallTracking();
- }
-
- /**
- * A fake implementation of TimeDetectorStrategy.Callback. Besides tracking changes and behaving
- * like the real thing should, it also asserts preconditions.
- */
- private static class FakeCallback implements TimeDetectorStrategy.Callback {
- private boolean mTimeDetectionEnabled;
- private boolean mWakeLockAcquired;
- private long mElapsedRealtimeMillis;
- private long mSystemClockMillis;
- private int mSystemClockUpdateThresholdMillis = 2000;
-
- // Tracking operations.
- private boolean mSystemClockWasSet;
- private Intent mBroadcastSent;
-
- @Override
- public int systemClockUpdateThresholdMillis() {
- return mSystemClockUpdateThresholdMillis;
- }
-
- @Override
- public boolean isAutoTimeDetectionEnabled() {
- return mTimeDetectionEnabled;
- }
-
- @Override
- public void acquireWakeLock() {
- if (mWakeLockAcquired) {
- fail("Wake lock already acquired");
- }
- mWakeLockAcquired = true;
- }
-
- @Override
- public long elapsedRealtimeMillis() {
- assertWakeLockAcquired();
- return mElapsedRealtimeMillis;
- }
-
- @Override
- public long systemClockMillis() {
- assertWakeLockAcquired();
- return mSystemClockMillis;
- }
-
- @Override
- public void setSystemClock(long newTimeMillis) {
- assertWakeLockAcquired();
- mSystemClockWasSet = true;
- mSystemClockMillis = newTimeMillis;
- }
-
- @Override
- public void releaseWakeLock() {
- assertWakeLockAcquired();
- mWakeLockAcquired = false;
- }
-
- @Override
- public void sendStickyBroadcast(Intent intent) {
- assertNotNull(intent);
- mBroadcastSent = intent;
- }
-
- // Methods below are for managing the fake's behavior.
-
- public void pokeSystemClockUpdateThreshold(int thresholdMillis) {
- mSystemClockUpdateThresholdMillis = thresholdMillis;
- }
-
- public void pokeElapsedRealtimeMillis(long elapsedRealtimeMillis) {
- mElapsedRealtimeMillis = elapsedRealtimeMillis;
- }
-
- public void pokeSystemClockMillis(long systemClockMillis) {
- mSystemClockMillis = systemClockMillis;
- }
-
- public void pokeAutoTimeDetectionEnabled(boolean enabled) {
- mTimeDetectionEnabled = enabled;
- }
-
- public long peekElapsedRealtimeMillis() {
- return mElapsedRealtimeMillis;
- }
-
- public long peekSystemClockMillis() {
- return mSystemClockMillis;
- }
-
- public void simulateTimePassing(int incrementMillis) {
- mElapsedRealtimeMillis += incrementMillis;
- mSystemClockMillis += incrementMillis;
- }
-
- public void simulateAutoTimeZoneDetectionToggle() {
- mTimeDetectionEnabled = !mTimeDetectionEnabled;
- }
-
- public void verifySystemClockNotSet() {
- assertFalse(mSystemClockWasSet);
- }
-
- public void verifySystemClockWasSet(long expectSystemClockMillis) {
- assertTrue(mSystemClockWasSet);
- assertEquals(expectSystemClockMillis, mSystemClockMillis);
- }
-
- public void verifyIntentWasBroadcast() {
- assertTrue(mBroadcastSent != null);
- }
-
- public void verifyIntentWasNotBroadcast() {
- assertNull(mBroadcastSent);
- }
-
- public void resetCallTracking() {
- mSystemClockWasSet = false;
- mBroadcastSent = null;
- }
-
- private void assertWakeLockAcquired() {
- assertTrue("The operation must be performed only after acquiring the wakelock",
- mWakeLockAcquired);
- }
- }
-
- /**
- * A fluent helper class for tests.
- */
- private class Script {
-
- private final FakeCallback mFakeCallback;
- private final SimpleTimeDetectorStrategy mSimpleTimeDetectorStrategy;
-
- Script() {
- mFakeCallback = new FakeCallback();
- mSimpleTimeDetectorStrategy = new SimpleTimeDetectorStrategy();
- mSimpleTimeDetectorStrategy.initialize(mFakeCallback);
-
- }
-
- Script pokeTimeDetectionEnabled(boolean enabled) {
- mFakeCallback.pokeAutoTimeDetectionEnabled(enabled);
- return this;
- }
-
- Script pokeFakeClocks(Scenario scenario) {
- mFakeCallback.pokeElapsedRealtimeMillis(scenario.getInitialRealTimeMillis());
- mFakeCallback.pokeSystemClockMillis(scenario.getInitialSystemClockMillis());
- return this;
- }
-
- Script pokeThresholds(int systemClockUpdateThreshold) {
- mFakeCallback.pokeSystemClockUpdateThreshold(systemClockUpdateThreshold);
- return this;
- }
-
- long peekElapsedRealtimeMillis() {
- return mFakeCallback.peekElapsedRealtimeMillis();
- }
-
- long peekSystemClockMillis() {
- return mFakeCallback.peekSystemClockMillis();
- }
-
- Script simulatePhoneTimeSuggestion(PhoneTimeSuggestion timeSuggestion) {
- mSimpleTimeDetectorStrategy.suggestPhoneTime(timeSuggestion);
- return this;
- }
-
- Script simulateManualTimeSuggestion(ManualTimeSuggestion timeSuggestion) {
- mSimpleTimeDetectorStrategy.suggestManualTime(timeSuggestion);
- return this;
- }
-
- Script simulateAutoTimeDetectionToggle() {
- mFakeCallback.simulateAutoTimeZoneDetectionToggle();
- mSimpleTimeDetectorStrategy.handleAutoTimeDetectionChanged();
- return this;
- }
-
- Script simulateTimePassing(int clockIncrement) {
- mFakeCallback.simulateTimePassing(clockIncrement);
- return this;
- }
-
- Script verifySystemClockWasNotSetAndResetCallTracking() {
- mFakeCallback.verifySystemClockNotSet();
- mFakeCallback.verifyIntentWasNotBroadcast();
- mFakeCallback.resetCallTracking();
- return this;
- }
-
- Script verifySystemClockWasSetAndResetCallTracking(
- long expectSystemClockMillis, boolean expectNetworkBroadcast) {
- mFakeCallback.verifySystemClockWasSet(expectSystemClockMillis);
- if (expectNetworkBroadcast) {
- mFakeCallback.verifyIntentWasBroadcast();
- }
- mFakeCallback.resetCallTracking();
- return this;
- }
- }
-
- /**
- * A starting scenario used during tests. Describes a fictional "physical" reality.
- */
- private static class Scenario {
-
- private final long mInitialDeviceSystemClockMillis;
- private final long mInitialDeviceRealtimeMillis;
- private final long mActualTimeMillis;
-
- Scenario(long initialDeviceSystemClock, long elapsedRealtime, long timeMillis) {
- mInitialDeviceSystemClockMillis = initialDeviceSystemClock;
- mActualTimeMillis = timeMillis;
- mInitialDeviceRealtimeMillis = elapsedRealtime;
- }
-
- long getInitialRealTimeMillis() {
- return mInitialDeviceRealtimeMillis;
- }
-
- long getInitialSystemClockMillis() {
- return mInitialDeviceSystemClockMillis;
- }
-
- long getActualTimeMillis() {
- return mActualTimeMillis;
- }
-
- PhoneTimeSuggestion createPhoneTimeSuggestionForActual(int phoneId) {
- TimestampedValue<Long> time = new TimestampedValue<>(
- mInitialDeviceRealtimeMillis, mActualTimeMillis);
- return createPhoneTimeSuggestion(phoneId, time);
- }
-
- ManualTimeSuggestion createManualTimeSuggestionForActual() {
- TimestampedValue<Long> time = new TimestampedValue<>(
- mInitialDeviceRealtimeMillis, mActualTimeMillis);
- return new ManualTimeSuggestion(time);
- }
-
- static class Builder {
-
- private long mInitialDeviceSystemClockMillis;
- private long mInitialDeviceRealtimeMillis;
- private long mActualTimeMillis;
-
- Builder setInitialDeviceSystemClockUtc(int year, int monthInYear, int day,
- int hourOfDay, int minute, int second) {
- mInitialDeviceSystemClockMillis = createUtcTime(year, monthInYear, day, hourOfDay,
- minute, second);
- return this;
- }
-
- Builder setInitialDeviceRealtimeMillis(long realtimeMillis) {
- mInitialDeviceRealtimeMillis = realtimeMillis;
- return this;
- }
-
- Builder setActualTimeUtc(int year, int monthInYear, int day, int hourOfDay,
- int minute, int second) {
- mActualTimeMillis =
- createUtcTime(year, monthInYear, day, hourOfDay, minute, second);
- return this;
- }
-
- Scenario build() {
- return new Scenario(mInitialDeviceSystemClockMillis, mInitialDeviceRealtimeMillis,
- mActualTimeMillis);
- }
- }
- }
-
- private static PhoneTimeSuggestion createPhoneTimeSuggestion(int phoneId,
- TimestampedValue<Long> utcTime) {
- return new PhoneTimeSuggestion.Builder(phoneId)
- .setUtcTime(utcTime)
- .build();
- }
-
- private ManualTimeSuggestion createManualTimeSuggestion(long timeMillis) {
- TimestampedValue<Long> utcTime =
- new TimestampedValue<>(mScript.peekElapsedRealtimeMillis(), timeMillis);
- return new ManualTimeSuggestion(utcTime);
- }
-
- private static long createUtcTime(int year, int monthInYear, int day, int hourOfDay, int minute,
- int second) {
- Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("Etc/UTC"));
- cal.clear();
- cal.set(year, monthInYear - 1, day, hourOfDay, minute, second);
- return cal.getTimeInMillis();
- }
-}
diff --git a/services/tests/servicestests/src/com/android/server/timedetector/TimeDetectorServiceTest.java b/services/tests/servicestests/src/com/android/server/timedetector/TimeDetectorServiceTest.java
index 84b495f14c1f..72a7f508772b 100644
--- a/services/tests/servicestests/src/com/android/server/timedetector/TimeDetectorServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/timedetector/TimeDetectorServiceTest.java
@@ -38,8 +38,6 @@ import android.util.TimestampedValue;
import androidx.test.runner.AndroidJUnit4;
-import com.android.server.timedetector.TimeDetectorStrategy.Callback;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -52,7 +50,6 @@ public class TimeDetectorServiceTest {
private Context mMockContext;
private StubbedTimeDetectorStrategy mStubbedTimeDetectorStrategy;
- private Callback mMockCallback;
private TimeDetectorService mTimeDetectorService;
private HandlerThread mHandlerThread;
@@ -68,12 +65,10 @@ public class TimeDetectorServiceTest {
mHandlerThread.start();
mTestHandler = new TestHandler(mHandlerThread.getLooper());
- mMockCallback = mock(Callback.class);
mStubbedTimeDetectorStrategy = new StubbedTimeDetectorStrategy();
mTimeDetectorService = new TimeDetectorService(
- mMockContext, mTestHandler, mMockCallback,
- mStubbedTimeDetectorStrategy);
+ mMockContext, mTestHandler, mStubbedTimeDetectorStrategy);
}
@After
@@ -100,13 +95,13 @@ public class TimeDetectorServiceTest {
@Test
public void testSuggestManualTime() throws Exception {
- doNothing().when(mMockContext).enforceCallingPermission(anyString(), any());
+ doNothing().when(mMockContext).enforceCallingOrSelfPermission(anyString(), any());
ManualTimeSuggestion manualTimeSuggestion = createManualTimeSuggestion();
mTimeDetectorService.suggestManualTime(manualTimeSuggestion);
mTestHandler.assertTotalMessagesEnqueued(1);
- verify(mMockContext).enforceCallingPermission(
+ verify(mMockContext).enforceCallingOrSelfPermission(
eq(android.Manifest.permission.SET_TIME),
anyString());
diff --git a/services/tests/servicestests/src/com/android/server/timedetector/TimeDetectorStrategyImplTest.java b/services/tests/servicestests/src/com/android/server/timedetector/TimeDetectorStrategyImplTest.java
new file mode 100644
index 000000000000..1aa3d8fe654b
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/timedetector/TimeDetectorStrategyImplTest.java
@@ -0,0 +1,758 @@
+/*
+ * Copyright (C) 2018 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 com.android.server.timedetector;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import android.app.timedetector.ManualTimeSuggestion;
+import android.app.timedetector.PhoneTimeSuggestion;
+import android.content.Intent;
+import android.icu.util.Calendar;
+import android.icu.util.GregorianCalendar;
+import android.icu.util.TimeZone;
+import android.util.TimestampedValue;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.time.Duration;
+
+@RunWith(AndroidJUnit4.class)
+public class TimeDetectorStrategyImplTest {
+
+ private static final TimestampedValue<Long> ARBITRARY_CLOCK_INITIALIZATION_INFO =
+ new TimestampedValue<>(
+ 123456789L /* realtimeClockMillis */,
+ createUtcTime(1977, 1, 1, 12, 0, 0));
+
+ private static final long ARBITRARY_TEST_TIME_MILLIS = createUtcTime(2018, 1, 1, 12, 0, 0);
+
+ private static final int ARBITRARY_PHONE_ID = 123456;
+
+ private static final long ONE_DAY_MILLIS = Duration.ofDays(1).toMillis();
+
+ private Script mScript;
+
+ @Before
+ public void setUp() {
+ mScript = new Script();
+ }
+
+ @Test
+ public void testSuggestPhoneTime_autoTimeEnabled() {
+ mScript.pokeFakeClocks(ARBITRARY_CLOCK_INITIALIZATION_INFO)
+ .pokeAutoTimeDetectionEnabled(true);
+
+ int phoneId = ARBITRARY_PHONE_ID;
+ long testTimeMillis = ARBITRARY_TEST_TIME_MILLIS;
+ PhoneTimeSuggestion timeSuggestion =
+ mScript.generatePhoneTimeSuggestion(phoneId, testTimeMillis);
+ int clockIncrement = 1000;
+ long expectedSystemClockMillis = testTimeMillis + clockIncrement;
+
+ mScript.simulateTimePassing(clockIncrement)
+ .simulatePhoneTimeSuggestion(timeSuggestion)
+ .verifySystemClockWasSetAndResetCallTracking(
+ expectedSystemClockMillis, true /* expectNetworkBroadcast */)
+ .assertLatestPhoneSuggestion(phoneId, timeSuggestion);
+ }
+
+ @Test
+ public void testSuggestPhoneTime_emptySuggestionIgnored() {
+ mScript.pokeFakeClocks(ARBITRARY_CLOCK_INITIALIZATION_INFO)
+ .pokeAutoTimeDetectionEnabled(true);
+
+ int phoneId = ARBITRARY_PHONE_ID;
+ PhoneTimeSuggestion timeSuggestion =
+ mScript.generatePhoneTimeSuggestion(phoneId, null);
+ mScript.simulatePhoneTimeSuggestion(timeSuggestion)
+ .verifySystemClockWasNotSetAndResetCallTracking()
+ .assertLatestPhoneSuggestion(phoneId, null);
+ }
+
+ @Test
+ public void testSuggestPhoneTime_systemClockThreshold() {
+ int systemClockUpdateThresholdMillis = 1000;
+ mScript.pokeFakeClocks(ARBITRARY_CLOCK_INITIALIZATION_INFO)
+ .pokeThresholds(systemClockUpdateThresholdMillis)
+ .pokeAutoTimeDetectionEnabled(true);
+
+ final int clockIncrement = 100;
+ int phoneId = ARBITRARY_PHONE_ID;
+
+ // Send the first time signal. It should be used.
+ {
+ long testTimeMillis = ARBITRARY_TEST_TIME_MILLIS;
+ PhoneTimeSuggestion timeSuggestion1 =
+ mScript.generatePhoneTimeSuggestion(phoneId, testTimeMillis);
+ TimestampedValue<Long> utcTime1 = timeSuggestion1.getUtcTime();
+
+ // Increment the the device clocks to simulate the passage of time.
+ mScript.simulateTimePassing(clockIncrement);
+
+ long expectedSystemClockMillis1 =
+ TimeDetectorStrategy.getTimeAt(utcTime1, mScript.peekElapsedRealtimeMillis());
+
+ mScript.simulatePhoneTimeSuggestion(timeSuggestion1)
+ .verifySystemClockWasSetAndResetCallTracking(
+ expectedSystemClockMillis1, true /* expectNetworkBroadcast */)
+ .assertLatestPhoneSuggestion(phoneId, timeSuggestion1);
+ }
+
+ // Now send another time signal, but one that is too similar to the last one and should be
+ // stored, but not used to set the system clock.
+ {
+ int underThresholdMillis = systemClockUpdateThresholdMillis - 1;
+ PhoneTimeSuggestion timeSuggestion2 = mScript.generatePhoneTimeSuggestion(
+ phoneId, mScript.peekSystemClockMillis() + underThresholdMillis);
+ mScript.simulateTimePassing(clockIncrement)
+ .simulatePhoneTimeSuggestion(timeSuggestion2)
+ .verifySystemClockWasNotSetAndResetCallTracking()
+ .assertLatestPhoneSuggestion(phoneId, timeSuggestion2);
+ }
+
+ // Now send another time signal, but one that is on the threshold and so should be used.
+ {
+ PhoneTimeSuggestion timeSuggestion3 = mScript.generatePhoneTimeSuggestion(
+ phoneId,
+ mScript.peekSystemClockMillis() + systemClockUpdateThresholdMillis);
+ mScript.simulateTimePassing(clockIncrement);
+
+ long expectedSystemClockMillis3 =
+ TimeDetectorStrategy.getTimeAt(timeSuggestion3.getUtcTime(),
+ mScript.peekElapsedRealtimeMillis());
+
+ mScript.simulatePhoneTimeSuggestion(timeSuggestion3)
+ .verifySystemClockWasSetAndResetCallTracking(
+ expectedSystemClockMillis3, true /* expectNetworkBroadcast */)
+ .assertLatestPhoneSuggestion(phoneId, timeSuggestion3);
+ }
+ }
+
+ @Test
+ public void testSuggestPhoneTime_multiplePhoneIdsAndBucketing() {
+ mScript.pokeFakeClocks(ARBITRARY_CLOCK_INITIALIZATION_INFO)
+ .pokeAutoTimeDetectionEnabled(true);
+
+ // There are 2 phones in this test. Phone 2 has a different idea of the current time.
+ // phone1Id < phone2Id (which is important because the strategy uses the lowest ID when
+ // multiple phone suggestions are available.
+ int phone1Id = ARBITRARY_PHONE_ID;
+ int phone2Id = ARBITRARY_PHONE_ID + 1;
+ long phone1TimeMillis = ARBITRARY_TEST_TIME_MILLIS;
+ long phone2TimeMillis = phone1TimeMillis + 60000;
+
+ final int clockIncrement = 999;
+
+ // Make a suggestion with phone2Id.
+ {
+ PhoneTimeSuggestion phone2TimeSuggestion =
+ mScript.generatePhoneTimeSuggestion(phone2Id, phone2TimeMillis);
+ mScript.simulateTimePassing(clockIncrement);
+
+ long expectedSystemClockMillis = phone2TimeMillis + clockIncrement;
+
+ mScript.simulatePhoneTimeSuggestion(phone2TimeSuggestion)
+ .verifySystemClockWasSetAndResetCallTracking(
+ expectedSystemClockMillis, true /* expectNetworkBroadcast */)
+ .assertLatestPhoneSuggestion(phone1Id, null)
+ .assertLatestPhoneSuggestion(phone2Id, phone2TimeSuggestion);
+ }
+
+ mScript.simulateTimePassing(clockIncrement);
+
+ // Now make a different suggestion with phone1Id.
+ {
+ PhoneTimeSuggestion phone1TimeSuggestion =
+ mScript.generatePhoneTimeSuggestion(phone1Id, phone1TimeMillis);
+ mScript.simulateTimePassing(clockIncrement);
+
+ long expectedSystemClockMillis = phone1TimeMillis + clockIncrement;
+
+ mScript.simulatePhoneTimeSuggestion(phone1TimeSuggestion)
+ .verifySystemClockWasSetAndResetCallTracking(
+ expectedSystemClockMillis, true /* expectNetworkBroadcast */)
+ .assertLatestPhoneSuggestion(phone1Id, phone1TimeSuggestion);
+
+ }
+
+ mScript.simulateTimePassing(clockIncrement);
+
+ // Make another suggestion with phone2Id. It should be stored but not used because the
+ // phone1Id suggestion will still "win".
+ {
+ PhoneTimeSuggestion phone2TimeSuggestion =
+ mScript.generatePhoneTimeSuggestion(phone2Id, phone2TimeMillis);
+ mScript.simulateTimePassing(clockIncrement);
+
+ mScript.simulatePhoneTimeSuggestion(phone2TimeSuggestion)
+ .verifySystemClockWasNotSetAndResetCallTracking()
+ .assertLatestPhoneSuggestion(phone2Id, phone2TimeSuggestion);
+ }
+
+ // Let enough time pass that phone1Id's suggestion should now be too old.
+ mScript.simulateTimePassing(TimeDetectorStrategyImpl.PHONE_BUCKET_SIZE_MILLIS);
+
+ // Make another suggestion with phone2Id. It should be used because the phoneId1
+ // is in an older "bucket".
+ {
+ PhoneTimeSuggestion phone2TimeSuggestion =
+ mScript.generatePhoneTimeSuggestion(phone2Id, phone2TimeMillis);
+ mScript.simulateTimePassing(clockIncrement);
+
+ long expectedSystemClockMillis = phone2TimeMillis + clockIncrement;
+
+ mScript.simulatePhoneTimeSuggestion(phone2TimeSuggestion)
+ .verifySystemClockWasSetAndResetCallTracking(
+ expectedSystemClockMillis, true /* expectNetworkBroadcast */)
+ .assertLatestPhoneSuggestion(phone2Id, phone2TimeSuggestion);
+ }
+ }
+
+ @Test
+ public void testSuggestPhoneTime_autoTimeDisabled() {
+ mScript.pokeFakeClocks(ARBITRARY_CLOCK_INITIALIZATION_INFO)
+ .pokeAutoTimeDetectionEnabled(false);
+
+ int phoneId = ARBITRARY_PHONE_ID;
+ PhoneTimeSuggestion timeSuggestion =
+ mScript.generatePhoneTimeSuggestion(phoneId, ARBITRARY_TEST_TIME_MILLIS);
+ mScript.simulateTimePassing(1000)
+ .simulatePhoneTimeSuggestion(timeSuggestion)
+ .verifySystemClockWasNotSetAndResetCallTracking()
+ .assertLatestPhoneSuggestion(phoneId, timeSuggestion);
+ }
+
+ @Test
+ public void testSuggestPhoneTime_invalidNitzReferenceTimesIgnored() {
+ final int systemClockUpdateThreshold = 2000;
+ mScript.pokeFakeClocks(ARBITRARY_CLOCK_INITIALIZATION_INFO)
+ .pokeThresholds(systemClockUpdateThreshold)
+ .pokeAutoTimeDetectionEnabled(true);
+
+ long testTimeMillis = ARBITRARY_TEST_TIME_MILLIS;
+ int phoneId = ARBITRARY_PHONE_ID;
+
+ PhoneTimeSuggestion timeSuggestion1 =
+ mScript.generatePhoneTimeSuggestion(phoneId, testTimeMillis);
+ TimestampedValue<Long> utcTime1 = timeSuggestion1.getUtcTime();
+
+ // Initialize the strategy / device with a time set from a phone suggestion.
+ mScript.simulateTimePassing(100);
+ long expectedSystemClockMillis1 =
+ TimeDetectorStrategy.getTimeAt(utcTime1, mScript.peekElapsedRealtimeMillis());
+ mScript.simulatePhoneTimeSuggestion(timeSuggestion1)
+ .verifySystemClockWasSetAndResetCallTracking(
+ expectedSystemClockMillis1, true /* expectNetworkBroadcast */)
+ .assertLatestPhoneSuggestion(phoneId, timeSuggestion1);
+
+ // The UTC time increment should be larger than the system clock update threshold so we
+ // know it shouldn't be ignored for other reasons.
+ long validUtcTimeMillis = utcTime1.getValue() + (2 * systemClockUpdateThreshold);
+
+ // Now supply a new signal that has an obviously bogus reference time : older than the last
+ // one.
+ long referenceTimeBeforeLastSignalMillis = utcTime1.getReferenceTimeMillis() - 1;
+ TimestampedValue<Long> utcTime2 = new TimestampedValue<>(
+ referenceTimeBeforeLastSignalMillis, validUtcTimeMillis);
+ PhoneTimeSuggestion timeSuggestion2 =
+ createPhoneTimeSuggestion(phoneId, utcTime2);
+ mScript.simulatePhoneTimeSuggestion(timeSuggestion2)
+ .verifySystemClockWasNotSetAndResetCallTracking()
+ .assertLatestPhoneSuggestion(phoneId, timeSuggestion1);
+
+ // Now supply a new signal that has an obviously bogus reference time : substantially in the
+ // future.
+ long referenceTimeInFutureMillis =
+ utcTime1.getReferenceTimeMillis() + Integer.MAX_VALUE + 1;
+ TimestampedValue<Long> utcTime3 = new TimestampedValue<>(
+ referenceTimeInFutureMillis, validUtcTimeMillis);
+ PhoneTimeSuggestion timeSuggestion3 =
+ createPhoneTimeSuggestion(phoneId, utcTime3);
+ mScript.simulatePhoneTimeSuggestion(timeSuggestion3)
+ .verifySystemClockWasNotSetAndResetCallTracking()
+ .assertLatestPhoneSuggestion(phoneId, timeSuggestion1);
+
+ // Just to prove validUtcTimeMillis is valid.
+ long validReferenceTimeMillis = utcTime1.getReferenceTimeMillis() + 100;
+ TimestampedValue<Long> utcTime4 = new TimestampedValue<>(
+ validReferenceTimeMillis, validUtcTimeMillis);
+ long expectedSystemClockMillis4 =
+ TimeDetectorStrategy.getTimeAt(utcTime4, mScript.peekElapsedRealtimeMillis());
+ PhoneTimeSuggestion timeSuggestion4 =
+ createPhoneTimeSuggestion(phoneId, utcTime4);
+ mScript.simulatePhoneTimeSuggestion(timeSuggestion4)
+ .verifySystemClockWasSetAndResetCallTracking(
+ expectedSystemClockMillis4, true /* expectNetworkBroadcast */)
+ .assertLatestPhoneSuggestion(phoneId, timeSuggestion4);
+ }
+
+ @Test
+ public void testSuggestPhoneTime_timeDetectionToggled() {
+ final int clockIncrementMillis = 100;
+ final int systemClockUpdateThreshold = 2000;
+ mScript.pokeFakeClocks(ARBITRARY_CLOCK_INITIALIZATION_INFO)
+ .pokeThresholds(systemClockUpdateThreshold)
+ .pokeAutoTimeDetectionEnabled(false);
+
+ int phoneId = ARBITRARY_PHONE_ID;
+ long testTimeMillis = ARBITRARY_TEST_TIME_MILLIS;
+ PhoneTimeSuggestion timeSuggestion1 =
+ mScript.generatePhoneTimeSuggestion(phoneId, testTimeMillis);
+ TimestampedValue<Long> utcTime1 = timeSuggestion1.getUtcTime();
+
+ // Simulate time passing.
+ mScript.simulateTimePassing(clockIncrementMillis);
+
+ // Simulate the time signal being received. It should not be used because auto time
+ // detection is off but it should be recorded.
+ mScript.simulatePhoneTimeSuggestion(timeSuggestion1)
+ .verifySystemClockWasNotSetAndResetCallTracking()
+ .assertLatestPhoneSuggestion(phoneId, timeSuggestion1);
+
+ // Simulate more time passing.
+ mScript.simulateTimePassing(clockIncrementMillis);
+
+ long expectedSystemClockMillis1 =
+ TimeDetectorStrategy.getTimeAt(utcTime1, mScript.peekElapsedRealtimeMillis());
+
+ // Turn on auto time detection.
+ mScript.simulateAutoTimeDetectionToggle()
+ .verifySystemClockWasSetAndResetCallTracking(
+ expectedSystemClockMillis1, true /* expectNetworkBroadcast */)
+ .assertLatestPhoneSuggestion(phoneId, timeSuggestion1);
+
+ // Turn off auto time detection.
+ mScript.simulateAutoTimeDetectionToggle()
+ .verifySystemClockWasNotSetAndResetCallTracking()
+ .assertLatestPhoneSuggestion(phoneId, timeSuggestion1);
+
+ // Receive another valid time signal.
+ // It should be on the threshold and accounting for the clock increments.
+ PhoneTimeSuggestion timeSuggestion2 = mScript.generatePhoneTimeSuggestion(
+ phoneId, mScript.peekSystemClockMillis() + systemClockUpdateThreshold);
+
+ // Simulate more time passing.
+ mScript.simulateTimePassing(clockIncrementMillis);
+
+ long expectedSystemClockMillis2 = TimeDetectorStrategy.getTimeAt(
+ timeSuggestion2.getUtcTime(), mScript.peekElapsedRealtimeMillis());
+
+ // The new time, though valid, should not be set in the system clock because auto time is
+ // disabled.
+ mScript.simulatePhoneTimeSuggestion(timeSuggestion2)
+ .verifySystemClockWasNotSetAndResetCallTracking()
+ .assertLatestPhoneSuggestion(phoneId, timeSuggestion2);
+
+ // Turn on auto time detection.
+ mScript.simulateAutoTimeDetectionToggle()
+ .verifySystemClockWasSetAndResetCallTracking(
+ expectedSystemClockMillis2, true /* expectNetworkBroadcast */)
+ .assertLatestPhoneSuggestion(phoneId, timeSuggestion2);
+ }
+
+ @Test
+ public void testSuggestPhoneTime_maxSuggestionAge() {
+ mScript.pokeFakeClocks(ARBITRARY_CLOCK_INITIALIZATION_INFO)
+ .pokeAutoTimeDetectionEnabled(true);
+
+ int phoneId = ARBITRARY_PHONE_ID;
+ long testTimeMillis = ARBITRARY_TEST_TIME_MILLIS;
+ PhoneTimeSuggestion phoneSuggestion =
+ mScript.generatePhoneTimeSuggestion(phoneId, testTimeMillis);
+ int clockIncrementMillis = 1000;
+
+ mScript.simulateTimePassing(clockIncrementMillis)
+ .simulatePhoneTimeSuggestion(phoneSuggestion)
+ .verifySystemClockWasSetAndResetCallTracking(
+ testTimeMillis + clockIncrementMillis, true /* expectedNetworkBroadcast */)
+ .assertLatestPhoneSuggestion(phoneId, phoneSuggestion);
+
+ // Look inside and check what the strategy considers the current best phone suggestion.
+ assertEquals(phoneSuggestion, mScript.peekBestPhoneSuggestion());
+
+ // Simulate time passing, long enough that phoneSuggestion is now too old.
+ mScript.simulateTimePassing(TimeDetectorStrategyImpl.PHONE_MAX_AGE_MILLIS);
+
+ // Look inside and check what the strategy considers the current best phone suggestion. It
+ // should still be the, it's just no longer used.
+ assertNull(mScript.peekBestPhoneSuggestion());
+ mScript.assertLatestPhoneSuggestion(phoneId, phoneSuggestion);
+ }
+
+ @Test
+ public void testSuggestManualTime_autoTimeDisabled() {
+ mScript.pokeFakeClocks(ARBITRARY_CLOCK_INITIALIZATION_INFO)
+ .pokeAutoTimeDetectionEnabled(false);
+
+ long testTimeMillis = ARBITRARY_TEST_TIME_MILLIS;
+ ManualTimeSuggestion timeSuggestion = mScript.generateManualTimeSuggestion(testTimeMillis);
+ final int clockIncrement = 1000;
+ long expectedSystemClockMillis = testTimeMillis + clockIncrement;
+
+ mScript.simulateTimePassing(clockIncrement)
+ .simulateManualTimeSuggestion(timeSuggestion)
+ .verifySystemClockWasSetAndResetCallTracking(
+ expectedSystemClockMillis, false /* expectNetworkBroadcast */);
+ }
+
+ @Test
+ public void testSuggestManualTime_retainsAutoSignal() {
+ // Configure the start state.
+ mScript.pokeFakeClocks(ARBITRARY_CLOCK_INITIALIZATION_INFO)
+ .pokeAutoTimeDetectionEnabled(true);
+
+ int phoneId = ARBITRARY_PHONE_ID;
+
+ // Simulate a phone suggestion.
+ long testTimeMillis = ARBITRARY_TEST_TIME_MILLIS;
+ PhoneTimeSuggestion phoneTimeSuggestion =
+ mScript.generatePhoneTimeSuggestion(phoneId, testTimeMillis);
+ long expectedAutoClockMillis = phoneTimeSuggestion.getUtcTime().getValue();
+ final int clockIncrement = 1000;
+
+ // Simulate the passage of time.
+ mScript.simulateTimePassing(clockIncrement);
+ expectedAutoClockMillis += clockIncrement;
+
+ mScript.simulatePhoneTimeSuggestion(phoneTimeSuggestion)
+ .verifySystemClockWasSetAndResetCallTracking(
+ expectedAutoClockMillis, true /* expectNetworkBroadcast */)
+ .assertLatestPhoneSuggestion(phoneId, phoneTimeSuggestion);
+
+ // Simulate the passage of time.
+ mScript.simulateTimePassing(clockIncrement);
+ expectedAutoClockMillis += clockIncrement;
+
+ // Switch to manual.
+ mScript.simulateAutoTimeDetectionToggle()
+ .verifySystemClockWasNotSetAndResetCallTracking()
+ .assertLatestPhoneSuggestion(phoneId, phoneTimeSuggestion);
+
+ // Simulate the passage of time.
+ mScript.simulateTimePassing(clockIncrement);
+ expectedAutoClockMillis += clockIncrement;
+
+ // Simulate a manual suggestion 1 day different from the auto suggestion.
+ long manualTimeMillis = testTimeMillis + ONE_DAY_MILLIS;
+ long expectedManualClockMillis = manualTimeMillis;
+ ManualTimeSuggestion manualTimeSuggestion =
+ mScript.generateManualTimeSuggestion(manualTimeMillis);
+ mScript.simulateManualTimeSuggestion(manualTimeSuggestion)
+ .verifySystemClockWasSetAndResetCallTracking(
+ expectedManualClockMillis, false /* expectNetworkBroadcast */)
+ .assertLatestPhoneSuggestion(phoneId, phoneTimeSuggestion);
+
+ // Simulate the passage of time.
+ mScript.simulateTimePassing(clockIncrement);
+ expectedAutoClockMillis += clockIncrement;
+
+ // Switch back to auto.
+ mScript.simulateAutoTimeDetectionToggle();
+
+ mScript.verifySystemClockWasSetAndResetCallTracking(
+ expectedAutoClockMillis, true /* expectNetworkBroadcast */)
+ .assertLatestPhoneSuggestion(phoneId, phoneTimeSuggestion);
+
+ // Switch back to manual - nothing should happen to the clock.
+ mScript.simulateAutoTimeDetectionToggle()
+ .verifySystemClockWasNotSetAndResetCallTracking()
+ .assertLatestPhoneSuggestion(phoneId, phoneTimeSuggestion);
+ }
+
+ /**
+ * Manual suggestions should be ignored if auto time is enabled.
+ */
+ @Test
+ public void testSuggestManualTime_autoTimeEnabled() {
+ mScript.pokeFakeClocks(ARBITRARY_CLOCK_INITIALIZATION_INFO)
+ .pokeAutoTimeDetectionEnabled(true);
+
+ ManualTimeSuggestion timeSuggestion =
+ mScript.generateManualTimeSuggestion(ARBITRARY_TEST_TIME_MILLIS);
+ final int clockIncrement = 1000;
+
+ mScript.simulateTimePassing(clockIncrement)
+ .simulateManualTimeSuggestion(timeSuggestion)
+ .verifySystemClockWasNotSetAndResetCallTracking();
+ }
+
+ /**
+ * A fake implementation of TimeDetectorStrategy.Callback. Besides tracking changes and behaving
+ * like the real thing should, it also asserts preconditions.
+ */
+ private static class FakeCallback implements TimeDetectorStrategy.Callback {
+ private boolean mAutoTimeDetectionEnabled;
+ private boolean mWakeLockAcquired;
+ private long mElapsedRealtimeMillis;
+ private long mSystemClockMillis;
+ private int mSystemClockUpdateThresholdMillis = 2000;
+
+ // Tracking operations.
+ private boolean mSystemClockWasSet;
+ private Intent mBroadcastSent;
+
+ @Override
+ public int systemClockUpdateThresholdMillis() {
+ return mSystemClockUpdateThresholdMillis;
+ }
+
+ @Override
+ public boolean isAutoTimeDetectionEnabled() {
+ return mAutoTimeDetectionEnabled;
+ }
+
+ @Override
+ public void acquireWakeLock() {
+ if (mWakeLockAcquired) {
+ fail("Wake lock already acquired");
+ }
+ mWakeLockAcquired = true;
+ }
+
+ @Override
+ public long elapsedRealtimeMillis() {
+ return mElapsedRealtimeMillis;
+ }
+
+ @Override
+ public long systemClockMillis() {
+ assertWakeLockAcquired();
+ return mSystemClockMillis;
+ }
+
+ @Override
+ public void setSystemClock(long newTimeMillis) {
+ assertWakeLockAcquired();
+ mSystemClockWasSet = true;
+ mSystemClockMillis = newTimeMillis;
+ }
+
+ @Override
+ public void releaseWakeLock() {
+ assertWakeLockAcquired();
+ mWakeLockAcquired = false;
+ }
+
+ @Override
+ public void sendStickyBroadcast(Intent intent) {
+ assertNotNull(intent);
+ mBroadcastSent = intent;
+ }
+
+ // Methods below are for managing the fake's behavior.
+
+ void pokeSystemClockUpdateThreshold(int thresholdMillis) {
+ mSystemClockUpdateThresholdMillis = thresholdMillis;
+ }
+
+ void pokeElapsedRealtimeMillis(long elapsedRealtimeMillis) {
+ mElapsedRealtimeMillis = elapsedRealtimeMillis;
+ }
+
+ void pokeSystemClockMillis(long systemClockMillis) {
+ mSystemClockMillis = systemClockMillis;
+ }
+
+ void pokeAutoTimeDetectionEnabled(boolean enabled) {
+ mAutoTimeDetectionEnabled = enabled;
+ }
+
+ long peekElapsedRealtimeMillis() {
+ return mElapsedRealtimeMillis;
+ }
+
+ long peekSystemClockMillis() {
+ return mSystemClockMillis;
+ }
+
+ void simulateTimePassing(long incrementMillis) {
+ mElapsedRealtimeMillis += incrementMillis;
+ mSystemClockMillis += incrementMillis;
+ }
+
+ void simulateAutoTimeZoneDetectionToggle() {
+ mAutoTimeDetectionEnabled = !mAutoTimeDetectionEnabled;
+ }
+
+ void verifySystemClockNotSet() {
+ assertFalse(mSystemClockWasSet);
+ }
+
+ void verifySystemClockWasSet(long expectedSystemClockMillis) {
+ assertTrue(mSystemClockWasSet);
+ assertEquals(expectedSystemClockMillis, mSystemClockMillis);
+ }
+
+ void verifyIntentWasBroadcast() {
+ assertTrue(mBroadcastSent != null);
+ }
+
+ void verifyIntentWasNotBroadcast() {
+ assertNull(mBroadcastSent);
+ }
+
+ void resetCallTracking() {
+ mSystemClockWasSet = false;
+ mBroadcastSent = null;
+ }
+
+ private void assertWakeLockAcquired() {
+ assertTrue("The operation must be performed only after acquiring the wakelock",
+ mWakeLockAcquired);
+ }
+ }
+
+ /**
+ * A fluent helper class for tests.
+ */
+ private class Script {
+
+ private final FakeCallback mFakeCallback;
+ private final TimeDetectorStrategyImpl mTimeDetectorStrategy;
+
+ Script() {
+ mFakeCallback = new FakeCallback();
+ mTimeDetectorStrategy = new TimeDetectorStrategyImpl();
+ mTimeDetectorStrategy.initialize(mFakeCallback);
+
+ }
+
+ Script pokeAutoTimeDetectionEnabled(boolean enabled) {
+ mFakeCallback.pokeAutoTimeDetectionEnabled(enabled);
+ return this;
+ }
+
+ Script pokeFakeClocks(TimestampedValue<Long> timeInfo) {
+ mFakeCallback.pokeElapsedRealtimeMillis(timeInfo.getReferenceTimeMillis());
+ mFakeCallback.pokeSystemClockMillis(timeInfo.getValue());
+ return this;
+ }
+
+ Script pokeThresholds(int systemClockUpdateThreshold) {
+ mFakeCallback.pokeSystemClockUpdateThreshold(systemClockUpdateThreshold);
+ return this;
+ }
+
+ long peekElapsedRealtimeMillis() {
+ return mFakeCallback.peekElapsedRealtimeMillis();
+ }
+
+ long peekSystemClockMillis() {
+ return mFakeCallback.peekSystemClockMillis();
+ }
+
+ Script simulatePhoneTimeSuggestion(PhoneTimeSuggestion timeSuggestion) {
+ mTimeDetectorStrategy.suggestPhoneTime(timeSuggestion);
+ return this;
+ }
+
+ Script simulateManualTimeSuggestion(ManualTimeSuggestion timeSuggestion) {
+ mTimeDetectorStrategy.suggestManualTime(timeSuggestion);
+ return this;
+ }
+
+ Script simulateAutoTimeDetectionToggle() {
+ mFakeCallback.simulateAutoTimeZoneDetectionToggle();
+ mTimeDetectorStrategy.handleAutoTimeDetectionChanged();
+ return this;
+ }
+
+ Script simulateTimePassing(long clockIncrementMillis) {
+ mFakeCallback.simulateTimePassing(clockIncrementMillis);
+ return this;
+ }
+
+ Script verifySystemClockWasNotSetAndResetCallTracking() {
+ mFakeCallback.verifySystemClockNotSet();
+ mFakeCallback.verifyIntentWasNotBroadcast();
+ mFakeCallback.resetCallTracking();
+ return this;
+ }
+
+ Script verifySystemClockWasSetAndResetCallTracking(
+ long expectedSystemClockMillis, boolean expectNetworkBroadcast) {
+ mFakeCallback.verifySystemClockWasSet(expectedSystemClockMillis);
+ if (expectNetworkBroadcast) {
+ mFakeCallback.verifyIntentWasBroadcast();
+ }
+ mFakeCallback.resetCallTracking();
+ return this;
+ }
+
+ /**
+ * White box test info: Asserts the latest suggestion for the phone ID is as expected.
+ */
+ Script assertLatestPhoneSuggestion(int phoneId, PhoneTimeSuggestion expected) {
+ assertEquals(expected, mTimeDetectorStrategy.getLatestPhoneSuggestion(phoneId));
+ return this;
+ }
+
+ /**
+ * White box test info: Returns the phone suggestion that would be used, if any, given the
+ * current elapsed real time clock.
+ */
+ PhoneTimeSuggestion peekBestPhoneSuggestion() {
+ return mTimeDetectorStrategy.findBestPhoneSuggestionForTests();
+ }
+
+ /**
+ * Generates a ManualTimeSuggestion using the current elapsed realtime clock for the
+ * reference time.
+ */
+ ManualTimeSuggestion generateManualTimeSuggestion(long timeMillis) {
+ TimestampedValue<Long> utcTime =
+ new TimestampedValue<>(mFakeCallback.peekElapsedRealtimeMillis(), timeMillis);
+ return new ManualTimeSuggestion(utcTime);
+ }
+
+ /**
+ * Generates a PhoneTimeSuggestion using the current elapsed realtime clock for the
+ * reference time.
+ */
+ PhoneTimeSuggestion generatePhoneTimeSuggestion(int phoneId, Long timeMillis) {
+ TimestampedValue<Long> time = null;
+ if (timeMillis != null) {
+ time = new TimestampedValue<>(peekElapsedRealtimeMillis(), timeMillis);
+ }
+ return createPhoneTimeSuggestion(phoneId, time);
+ }
+ }
+
+ private static PhoneTimeSuggestion createPhoneTimeSuggestion(int phoneId,
+ TimestampedValue<Long> utcTime) {
+ return new PhoneTimeSuggestion.Builder(phoneId)
+ .setUtcTime(utcTime)
+ .build();
+ }
+
+ private static long createUtcTime(int year, int monthInYear, int day, int hourOfDay, int minute,
+ int second) {
+ Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("Etc/UTC"));
+ cal.clear();
+ cal.set(year, monthInYear - 1, day, hourOfDay, minute, second);
+ return cal.getTimeInMillis();
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/timezonedetector/TimeZoneDetectorStrategyTest.java b/services/tests/servicestests/src/com/android/server/timezonedetector/TimeZoneDetectorStrategyTest.java
index 270436d65614..2429cfc1bcd0 100644
--- a/services/tests/servicestests/src/com/android/server/timezonedetector/TimeZoneDetectorStrategyTest.java
+++ b/services/tests/servicestests/src/com/android/server/timezonedetector/TimeZoneDetectorStrategyTest.java
@@ -50,7 +50,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
-import java.util.Objects;
/**
* White-box unit tests for {@link TimeZoneDetectorStrategy}.
@@ -445,8 +444,7 @@ public class TimeZoneDetectorStrategyTest {
static class FakeTimeZoneDetectorStrategyCallback implements TimeZoneDetectorStrategy.Callback {
private boolean mAutoTimeZoneDetectionEnabled;
- private TestState<TimeZoneChange> mTimeZoneChanges = new TestState<>();
- private String mTimeZoneId;
+ private TestState<String> mTimeZoneId = new TestState<>();
@Override
public boolean isAutoTimeZoneDetectionEnabled() {
@@ -455,18 +453,17 @@ public class TimeZoneDetectorStrategyTest {
@Override
public boolean isDeviceTimeZoneInitialized() {
- return mTimeZoneId != null;
+ return mTimeZoneId.getLatest() != null;
}
@Override
public String getDeviceTimeZone() {
- return mTimeZoneId;
+ return mTimeZoneId.getLatest();
}
@Override
- public void setDeviceTimeZone(String zoneId, boolean withNetworkBroadcast) {
- mTimeZoneId = zoneId;
- mTimeZoneChanges.set(new TimeZoneChange(zoneId, withNetworkBroadcast));
+ public void setDeviceTimeZone(String zoneId) {
+ mTimeZoneId.set(zoneId);
}
void initializeAutoTimeZoneDetection(boolean enabled) {
@@ -474,7 +471,7 @@ public class TimeZoneDetectorStrategyTest {
}
void initializeTimeZone(String zoneId) {
- mTimeZoneId = zoneId;
+ mTimeZoneId.init(zoneId);
}
void setAutoTimeZoneDetectionEnabled(boolean enabled) {
@@ -482,46 +479,17 @@ public class TimeZoneDetectorStrategyTest {
}
void assertTimeZoneNotSet() {
- mTimeZoneChanges.assertHasNotBeenSet();
+ mTimeZoneId.assertHasNotBeenSet();
}
- void assertTimeZoneSet(String timeZoneId, boolean withNetworkBroadcast) {
- mTimeZoneChanges.assertHasBeenSet();
- mTimeZoneChanges.assertChangeCount(1);
- TimeZoneChange expectedChange = new TimeZoneChange(timeZoneId, withNetworkBroadcast);
- mTimeZoneChanges.assertLatestEquals(expectedChange);
+ void assertTimeZoneSet(String timeZoneId) {
+ mTimeZoneId.assertHasBeenSet();
+ mTimeZoneId.assertChangeCount(1);
+ mTimeZoneId.assertLatestEquals(timeZoneId);
}
void commitAllChanges() {
- mTimeZoneChanges.commitLatest();
- }
- }
-
- private static class TimeZoneChange {
- private final String mTimeZoneId;
- private final boolean mWithNetworkBroadcast;
-
- private TimeZoneChange(String timeZoneId, boolean withNetworkBroadcast) {
- mTimeZoneId = timeZoneId;
- mWithNetworkBroadcast = withNetworkBroadcast;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
- TimeZoneChange that = (TimeZoneChange) o;
- return mWithNetworkBroadcast == that.mWithNetworkBroadcast
- && mTimeZoneId.equals(that.mTimeZoneId);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mTimeZoneId, mWithNetworkBroadcast);
+ mTimeZoneId.commitLatest();
}
}
@@ -614,21 +582,13 @@ public class TimeZoneDetectorStrategyTest {
}
Script verifyTimeZoneSetAndReset(PhoneTimeZoneSuggestion suggestion) {
- // Phone suggestions should cause a TelephonyIntents.ACTION_NETWORK_SET_TIMEZONE
- // broadcast.
- boolean withNetworkBroadcast = true;
- mFakeTimeZoneDetectorStrategyCallback.assertTimeZoneSet(
- suggestion.getZoneId(), withNetworkBroadcast);
+ mFakeTimeZoneDetectorStrategyCallback.assertTimeZoneSet(suggestion.getZoneId());
mFakeTimeZoneDetectorStrategyCallback.commitAllChanges();
return this;
}
Script verifyTimeZoneSetAndReset(ManualTimeZoneSuggestion suggestion) {
- // Manual suggestions should not cause a TelephonyIntents.ACTION_NETWORK_SET_TIMEZONE
- // broadcast.
- boolean withNetworkBroadcast = false;
- mFakeTimeZoneDetectorStrategyCallback.assertTimeZoneSet(
- suggestion.getZoneId(), withNetworkBroadcast);
+ mFakeTimeZoneDetectorStrategyCallback.assertTimeZoneSet(suggestion.getZoneId());
mFakeTimeZoneDetectorStrategyCallback.commitAllChanges();
return this;
}
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationComparatorTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationComparatorTest.java
index 0b4760d89686..a328568da7ed 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationComparatorTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationComparatorTest.java
@@ -23,6 +23,7 @@ import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.spy;
import android.app.Notification;
import android.app.NotificationChannel;
@@ -271,6 +272,18 @@ public class NotificationComparatorTest extends UiServiceTestCase {
}
@Test
+ public void testRankingScoreOverrides() {
+ NotificationComparator comp = new NotificationComparator(mContext);
+ NotificationRecord recordMinCallNonInterruptive = spy(mRecordMinCallNonInterruptive);
+ assertTrue(comp.compare(mRecordMinCall, recordMinCallNonInterruptive) < 0);
+
+ when(recordMinCallNonInterruptive.getRankingScore()).thenReturn(1f);
+ assertTrue(comp.compare(mRecordMinCall, recordMinCallNonInterruptive) > 0);
+ assertTrue(comp.compare(mRecordCheater, recordMinCallNonInterruptive) > 0);
+ assertTrue(comp.compare(mRecordColorizedCall, recordMinCallNonInterruptive) < 0);
+ }
+
+ @Test
public void testMessaging() {
NotificationComparator comp = new NotificationComparator(mContext);
assertTrue(comp.isImportantMessaging(mRecordInlineReply));
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationRecordTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationRecordTest.java
index 7c2235050caf..fab6b7fd0d77 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationRecordTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationRecordTest.java
@@ -52,11 +52,13 @@ import android.graphics.drawable.Icon;
import android.media.AudioAttributes;
import android.metrics.LogMaker;
import android.net.Uri;
+import android.os.Build;
import android.os.Bundle;
import android.os.UserHandle;
import android.provider.Settings;
import android.service.notification.Adjustment;
import android.service.notification.StatusBarNotification;
+import android.widget.RemoteViews;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
@@ -114,7 +116,9 @@ public class NotificationRecordTest extends UiServiceTestCase {
when(mMockContext.getResources()).thenReturn(getContext().getResources());
when(mMockContext.getPackageManager()).thenReturn(mPm);
- when(mMockContext.getApplicationInfo()).thenReturn(new ApplicationInfo());
+ ApplicationInfo appInfo = new ApplicationInfo();
+ appInfo.targetSdkVersion = Build.VERSION_CODES.O;
+ when(mMockContext.getApplicationInfo()).thenReturn(appInfo);
}
private StatusBarNotification getNotification(String pkg, boolean noisy, boolean defaultSound,
@@ -168,6 +172,28 @@ public class NotificationRecordTest extends UiServiceTestCase {
return new StatusBarNotification(pkg, pkg, id1, tag1, uid, uid, n, mUser, null, uid);
}
+ private StatusBarNotification getStyledNotification(boolean customContent, boolean customBig,
+ boolean customHeadsUp, Notification.Style style) {
+ final Builder builder = new Builder(mMockContext)
+ .setContentTitle("foo")
+ .setSmallIcon(android.R.drawable.sym_def_app_icon);
+ if (style != null) {
+ builder.setStyle(style);
+ }
+ if (customContent) {
+ builder.setCustomContentView(mock(RemoteViews.class));
+ }
+ if (customBig) {
+ builder.setCustomBigContentView(mock(RemoteViews.class));
+ }
+ if (customHeadsUp) {
+ builder.setCustomHeadsUpContentView(mock(RemoteViews.class));
+ }
+
+ Notification n = builder.build();
+ return new StatusBarNotification(pkg, pkg, id1, tag1, uid, uid, n, mUser, null, uid);
+ }
+
//
// Tests
//
@@ -999,4 +1025,74 @@ public class NotificationRecordTest extends UiServiceTestCase {
assertEquals(IMPORTANCE_LOW, record.getImportance());
}
+
+ @Test
+ public void testHasUndecoratedRemoteViews_NoRemoteViews() {
+ StatusBarNotification sbn = getStyledNotification(false, false, false, null);
+ NotificationRecord record = new NotificationRecord(mMockContext, sbn, channel);
+
+ assertFalse("false positive detection", record.hasUndecoratedRemoteView());
+ }
+
+ @Test
+ public void testHasUndecoratedRemoteViews_NoRemoteViewsWithStyle() {
+ StatusBarNotification sbn = getStyledNotification(false, false, false,
+ new Notification.BigPictureStyle());
+ NotificationRecord record = new NotificationRecord(mMockContext, sbn, channel);
+
+ assertFalse("false positive detection", record.hasUndecoratedRemoteView());
+ }
+
+ @Test
+ public void testHasUndecoratedRemoteViews_UndecoratedContent() {
+ StatusBarNotification sbn = getStyledNotification(true, false, false, null);
+ NotificationRecord record = new NotificationRecord(mMockContext, sbn, channel);
+
+ assertTrue("false negative detection", record.hasUndecoratedRemoteView());
+ }
+
+
+ @Test
+ public void testHasUndecoratedRemoteViews_UndecoratedBig() {
+ StatusBarNotification sbn = getStyledNotification(false, true, false, null);
+ NotificationRecord record = new NotificationRecord(mMockContext, sbn, channel);
+
+ assertTrue("false negative detection", record.hasUndecoratedRemoteView());
+ }
+
+
+ @Test
+ public void testHasUndecoratedRemoteViews_UndecoratedHeadsup() {
+ StatusBarNotification sbn = getStyledNotification(false, false, true, null);
+ NotificationRecord record = new NotificationRecord(mMockContext, sbn, channel);
+
+ assertTrue("false negative detection", record.hasUndecoratedRemoteView());
+ }
+
+ @Test
+ public void testHasUndecoratedRemoteViews_DecoratedRemoteViews() {
+ StatusBarNotification sbn = getStyledNotification(true, true, true,
+ new Notification.DecoratedCustomViewStyle());
+ NotificationRecord record = new NotificationRecord(mMockContext, sbn, channel);
+
+ assertFalse("false positive detection", record.hasUndecoratedRemoteView());
+ }
+
+ @Test
+ public void testHasUndecoratedRemoteViews_DecoratedMediaRemoteViews() {
+ StatusBarNotification sbn = getStyledNotification(true, true, true,
+ new Notification.DecoratedMediaCustomViewStyle());
+ NotificationRecord record = new NotificationRecord(mMockContext, sbn, channel);
+
+ assertFalse("false positive detection", record.hasUndecoratedRemoteView());
+ }
+
+ @Test
+ public void testHasUndecoratedRemoteViews_UndecoratedWrongStyle() {
+ StatusBarNotification sbn = getStyledNotification(true, true, true,
+ new Notification.BigPictureStyle());
+ NotificationRecord record = new NotificationRecord(mMockContext, sbn, channel);
+
+ assertTrue("false negative detection", record.hasUndecoratedRemoteView());
+ }
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityDisplayTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityDisplayTests.java
index de2bba275171..9c17de9954c4 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityDisplayTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityDisplayTests.java
@@ -47,7 +47,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
/**
- * Tests for the {@link ActivityDisplay} class.
+ * Tests for the {@link DisplayContent} class.
*
* Build/Install/Run:
* atest WmTests:ActivityDisplayTests
@@ -55,12 +55,13 @@ import org.junit.runner.RunWith;
@SmallTest
@Presubmit
@RunWith(WindowTestRunner.class)
+// TODO(b/144248496): Merge to DisplayContentTests
public class ActivityDisplayTests extends ActivityTestsBase {
@Test
public void testLastFocusedStackIsUpdatedWhenMovingStack() {
// Create a stack at bottom.
- final ActivityDisplay display = mRootActivityContainer.getDefaultDisplay();
+ final DisplayContent display = mRootActivityContainer.getDefaultDisplay();
final ActivityStack stack =
new StackBuilder(mRootActivityContainer).setOnTop(!ON_TOP).build();
final ActivityStack prevFocusedStack = display.getFocusedStack();
@@ -103,13 +104,13 @@ public class ActivityDisplayTests extends ActivityTestsBase {
}
/**
- * Test {@link ActivityDisplay#mPreferredTopFocusableStack} will be cleared when the stack is
+ * Test {@link DisplayContent#mPreferredTopFocusableStack} will be cleared when the stack is
* removed or moved to back, and the focused stack will be according to z-order.
*/
@Test
public void testStackShouldNotBeFocusedAfterMovingToBackOrRemoving() {
// Create a display which only contains 2 stacks.
- final ActivityDisplay display = addNewActivityDisplayAt(ActivityDisplay.POSITION_TOP);
+ final DisplayContent display = addNewDisplayContentAt(DisplayContent.POSITION_TOP);
final ActivityStack stack1 = createFullscreenStackWithSimpleActivityAt(display);
final ActivityStack stack2 = createFullscreenStackWithSimpleActivityAt(display);
@@ -128,13 +129,13 @@ public class ActivityDisplayTests extends ActivityTestsBase {
}
/**
- * Verifies {@link ActivityDisplay#remove} should not resume home stack on the removing display.
+ * Verifies {@link DisplayContent#remove} should not resume home stack on the removing display.
*/
@Test
public void testNotResumeHomeStackOnRemovingDisplay() {
// Create a display which supports system decoration and allows reparenting stacks to
// another display when the display is removed.
- final ActivityDisplay display = new TestActivityDisplay.Builder(
+ final DisplayContent display = new TestDisplayContent.Builder(
mService, 1000, 1500).setSystemDecorations(true).build();
doReturn(false).when(display).shouldDestroyContentOnRemove();
@@ -144,7 +145,7 @@ public class ActivityDisplayTests extends ActivityTestsBase {
// Put a finishing standard activity which will be reparented.
final ActivityStack stack = createFullscreenStackWithSimpleActivityAt(display);
- stack.topRunningActivityLocked().makeFinishingLocked();
+ stack.topRunningActivity().makeFinishingLocked();
clearInvocations(homeStack);
display.remove();
@@ -154,7 +155,7 @@ public class ActivityDisplayTests extends ActivityTestsBase {
verify(homeStack, never()).resumeTopActivityUncheckedLocked(any(), any());
}
- private ActivityStack createFullscreenStackWithSimpleActivityAt(ActivityDisplay display) {
+ private ActivityStack createFullscreenStackWithSimpleActivityAt(DisplayContent display) {
final ActivityStack fullscreenStack = display.createStack(
WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, ON_TOP);
final Task fullscreenTask = new TaskBuilder(mService.mStackSupervisor)
@@ -168,7 +169,7 @@ public class ActivityDisplayTests extends ActivityTestsBase {
*/
@Test
public void testTopRunningActivity() {
- final ActivityDisplay display = mRootActivityContainer.getDefaultDisplay();
+ final DisplayContent display = mRootActivityContainer.getDefaultDisplay();
final KeyguardController keyguard = mSupervisor.getKeyguardController();
final ActivityStack stack = new StackBuilder(mRootActivityContainer).build();
final ActivityRecord activity = stack.getTopNonFinishingActivity();
@@ -208,7 +209,7 @@ public class ActivityDisplayTests extends ActivityTestsBase {
assertTopRunningActivity(showWhenLockedActivity, display);
}
- private static void assertTopRunningActivity(ActivityRecord top, ActivityDisplay display) {
+ private static void assertTopRunningActivity(ActivityRecord top, DisplayContent display) {
assertEquals(top, display.topRunningActivity());
assertEquals(top, display.topRunningActivity(true /* considerKeyguardState */));
}
@@ -218,7 +219,7 @@ public class ActivityDisplayTests extends ActivityTestsBase {
*/
@Test
public void testAlwaysOnTopStackLocation() {
- final ActivityDisplay display = mRootActivityContainer.getDefaultDisplay();
+ final DisplayContent display = mRootActivityContainer.getDefaultDisplay();
final ActivityStack alwaysOnTopStack = display.createStack(WINDOWING_MODE_FREEFORM,
ACTIVITY_TYPE_STANDARD, true /* onTop */);
final ActivityRecord activity = new ActivityBuilder(mService).setCreateTask(true)
@@ -283,7 +284,7 @@ public class ActivityDisplayTests extends ActivityTestsBase {
}
private void removeStackTests(Runnable runnable) {
- final ActivityDisplay display = mRootActivityContainer.getDefaultDisplay();
+ final DisplayContent display = mRootActivityContainer.getDefaultDisplay();
final ActivityStack stack1 = display.createStack(WINDOWING_MODE_FULLSCREEN,
ACTIVITY_TYPE_STANDARD, ON_TOP);
final ActivityStack stack2 = display.createStack(WINDOWING_MODE_FULLSCREEN,
@@ -301,24 +302,18 @@ public class ActivityDisplayTests extends ActivityTestsBase {
doAnswer(invocation -> {
display.positionStackAtTop(stack3, false);
return true;
- }).when(mSupervisor).removeTaskByIdLocked(eq(task4.mTaskId), anyBoolean(), anyBoolean(),
- any());
+ }).when(mSupervisor).removeTask(eq(task4), anyBoolean(), anyBoolean(), any());
// Removing stacks from the display while removing stacks.
doAnswer(invocation -> {
display.removeStack(stack2);
return true;
- }).when(mSupervisor).removeTaskByIdLocked(eq(task2.mTaskId), anyBoolean(), anyBoolean(),
- any());
+ }).when(mSupervisor).removeTask(eq(task2), anyBoolean(), anyBoolean(), any());
runnable.run();
- verify(mSupervisor).removeTaskByIdLocked(eq(task4.mTaskId), anyBoolean(), anyBoolean(),
- any());
- verify(mSupervisor).removeTaskByIdLocked(eq(task3.mTaskId), anyBoolean(), anyBoolean(),
- any());
- verify(mSupervisor).removeTaskByIdLocked(eq(task2.mTaskId), anyBoolean(), anyBoolean(),
- any());
- verify(mSupervisor).removeTaskByIdLocked(eq(task1.mTaskId), anyBoolean(), anyBoolean(),
- any());
+ verify(mSupervisor).removeTask(eq(task4), anyBoolean(), anyBoolean(), any());
+ verify(mSupervisor).removeTask(eq(task3), anyBoolean(), anyBoolean(), any());
+ verify(mSupervisor).removeTask(eq(task2), anyBoolean(), anyBoolean(), any());
+ verify(mSupervisor).removeTask(eq(task1), anyBoolean(), anyBoolean(), any());
}
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
index dbcfa94c69bf..89723d14090b 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
@@ -107,7 +107,7 @@ public class ActivityRecordTests extends ActivityTestsBase {
@Before
public void setUp() throws Exception {
mStack = new StackBuilder(mRootActivityContainer).build();
- mTask = mStack.getChildAt(0);
+ mTask = mStack.getBottomMostTask();
mActivity = mTask.getTopNonFinishingActivity();
doReturn(false).when(mService).isBooting();
@@ -635,12 +635,12 @@ public class ActivityRecordTests extends ActivityTestsBase {
final ActivityStack stack1 = new StackBuilder(mRootActivityContainer).build();
mStack.moveToFront("test");
// The stack2 is needed here for moving back to simulate the
- // {@link ActivityDisplay#mPreferredTopFocusableStack} is cleared, so
- // {@link ActivityDisplay#getFocusedStack} will rely on the order of focusable-and-visible
+ // {@link DisplayContent#mPreferredTopFocusableStack} is cleared, so
+ // {@link DisplayContent#getFocusedStack} will rely on the order of focusable-and-visible
// stacks. Then when mActivity is finishing, its stack will be invisible (no running
// activities in the stack) that is the key condition to verify.
final ActivityStack stack2 = new StackBuilder(mRootActivityContainer).build();
- stack2.moveToBack("test", stack2.getChildAt(0));
+ stack2.moveToBack("test", stack2.getBottomMostTask());
assertTrue(mStack.isTopStackOnDisplay());
@@ -948,9 +948,7 @@ public class ActivityRecordTests extends ActivityTestsBase {
public void testDestroyIfPossible_lastActivityAboveEmptyHomeStack() {
// Empty the home stack.
final ActivityStack homeStack = mActivity.getDisplay().getHomeStack();
- for (Task t : homeStack.getAllTasks()) {
- homeStack.removeChild(t, "test");
- }
+ homeStack.forAllTasks((t) -> { homeStack.removeChild(t, "test"); });
mActivity.finishing = true;
doReturn(false).when(mRootActivityContainer).resumeFocusedStacksTopActivities();
spyOn(mStack);
@@ -974,9 +972,7 @@ public class ActivityRecordTests extends ActivityTestsBase {
public void testCompleteFinishing_lastActivityAboveEmptyHomeStack() {
// Empty the home stack.
final ActivityStack homeStack = mActivity.getDisplay().getHomeStack();
- for (Task t : homeStack.getAllTasks()) {
- homeStack.removeChild(t, "test");
- }
+ homeStack.forAllTasks((t) -> { homeStack.removeChild(t, "test"); });
mActivity.finishing = true;
spyOn(mStack);
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStackSupervisorTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStackSupervisorTests.java
index 0219539b3588..530adb590f75 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityStackSupervisorTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStackSupervisorTests.java
@@ -112,7 +112,7 @@ public class ActivityStackSupervisorTests extends ActivityTestsBase {
@Test
public void testHandleNonResizableTaskOnSecondaryDisplay() {
// Create an unresizable task on secondary display.
- final ActivityDisplay newDisplay = addNewActivityDisplayAt(ActivityDisplay.POSITION_TOP);
+ final DisplayContent newDisplay = addNewDisplayContentAt(DisplayContent.POSITION_TOP);
final ActivityStack stack = new StackBuilder(mRootActivityContainer)
.setDisplay(newDisplay).build();
final ActivityRecord unresizableActivity = stack.getTopNonFinishingActivity();
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java
index 7806d40c3c0d..8a1a10d6139a 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java
@@ -54,7 +54,6 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
-import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import android.content.ComponentName;
@@ -78,7 +77,7 @@ import org.junit.runner.RunWith;
@Presubmit
@RunWith(WindowTestRunner.class)
public class ActivityStackTests extends ActivityTestsBase {
- private ActivityDisplay mDefaultDisplay;
+ private DisplayContent mDefaultDisplay;
private ActivityStack mStack;
private Task mTask;
@@ -279,19 +278,19 @@ public class ActivityStackTests extends ActivityTestsBase {
@Test
public void testMoveStackToBackIncludingParent() {
- final ActivityDisplay display = addNewActivityDisplayAt(ActivityDisplay.POSITION_TOP);
+ final DisplayContent display = addNewDisplayContentAt(DisplayContent.POSITION_TOP);
final ActivityStack stack1 = createStackForShouldBeVisibleTest(display,
WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
final ActivityStack stack2 = createStackForShouldBeVisibleTest(display,
WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
// Do not move display to back because there is still another stack.
- stack2.moveToBack("testMoveStackToBackIncludingParent", stack2.topTask());
+ stack2.moveToBack("testMoveStackToBackIncludingParent", stack2.getTopMostTask());
verify(stack2).positionChildAtBottom(any(), eq(false) /* includingParents */);
// Also move display to back because there is only one stack left.
display.removeStack(stack1);
- stack2.moveToBack("testMoveStackToBackIncludingParent", stack2.topTask());
+ stack2.moveToBack("testMoveStackToBackIncludingParent", stack2.getTopMostTask());
verify(stack2).positionChildAtBottom(any(), eq(true) /* includingParents */);
}
@@ -545,7 +544,7 @@ public class ActivityStackTests extends ActivityTestsBase {
public void testShouldBeVisible_Finishing() {
final ActivityStack homeStack = createStackForShouldBeVisibleTest(mDefaultDisplay,
WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, true /* onTop */);
- ActivityRecord topRunningHomeActivity = homeStack.topRunningActivityLocked();
+ ActivityRecord topRunningHomeActivity = homeStack.topRunningActivity();
if (topRunningHomeActivity == null) {
topRunningHomeActivity = new ActivityBuilder(mService)
.setStack(homeStack)
@@ -563,7 +562,7 @@ public class ActivityStackTests extends ActivityTestsBase {
topRunningHomeActivity.finishing = true;
final ActivityRecord topRunningTranslucentActivity =
- translucentStack.topRunningActivityLocked();
+ translucentStack.topRunningActivity();
topRunningTranslucentActivity.finishing = true;
// Home stack should be visible even there are no running activities.
@@ -815,7 +814,7 @@ public class ActivityStackTests extends ActivityTestsBase {
@SuppressWarnings("TypeParameterUnusedInFormals")
private ActivityStack createStackForShouldBeVisibleTest(
- ActivityDisplay display, int windowingMode, int activityType, boolean onTop) {
+ DisplayContent display, int windowingMode, int activityType, boolean onTop) {
final ActivityStack stack;
if (activityType == ACTIVITY_TYPE_HOME) {
// Home stack and activity are created in ActivityTestsBase#setupActivityManagerService
@@ -883,7 +882,7 @@ public class ActivityStackTests extends ActivityTestsBase {
// removed from the task. Since the overlay activity should be removed as well, the task
// should be empty.
assertFalse(mTask.hasChild());
- assertThat(mStack.getAllTasks()).isEmpty();
+ assertFalse(mStack.hasChild());
}
@Test
@@ -905,7 +904,7 @@ public class ActivityStackTests extends ActivityTestsBase {
mStack.handleAppDiedLocked(secondActivity.app);
assertFalse(mTask.hasChild());
- assertThat(mStack.getAllTasks()).isEmpty();
+ assertFalse(mStack.hasChild());
}
@Test
@@ -919,7 +918,7 @@ public class ActivityStackTests extends ActivityTestsBase {
mStack.handleAppDiedLocked(activity.app);
assertEquals(1, mTask.getChildCount());
- assertEquals(1, mStack.getAllTasks().size());
+ assertEquals(1, mStack.getChildCount());
}
@Test
@@ -933,7 +932,7 @@ public class ActivityStackTests extends ActivityTestsBase {
mStack.handleAppDiedLocked(activity.app);
assertFalse(mTask.hasChild());
- assertThat(mStack.getAllTasks()).isEmpty();
+ assertFalse(mStack.hasChild());
}
@Test
@@ -947,7 +946,7 @@ public class ActivityStackTests extends ActivityTestsBase {
mStack.handleAppDiedLocked(activity.app);
assertEquals(1, mTask.getChildCount());
- assertEquals(1, mStack.getAllTasks().size());
+ assertEquals(1, mStack.getChildCount());
}
@Test
@@ -961,7 +960,7 @@ public class ActivityStackTests extends ActivityTestsBase {
mStack.handleAppDiedLocked(activity.app);
assertFalse(mTask.hasChild());
- assertThat(mStack.getAllTasks()).isEmpty();
+ assertFalse(mStack.hasChild());
}
@Test
@@ -982,7 +981,7 @@ public class ActivityStackTests extends ActivityTestsBase {
final ActivityStack homeStack = createStackForShouldBeVisibleTest(mDefaultDisplay,
WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, true /* onTop */);
- ActivityRecord activity = homeStack.topRunningActivityLocked();
+ ActivityRecord activity = homeStack.topRunningActivity();
if (activity == null) {
activity = new ActivityBuilder(mService)
.setStack(homeStack)
@@ -998,7 +997,7 @@ public class ActivityStackTests extends ActivityTestsBase {
@Test
public void testFinishCurrentActivity() {
// Create 2 activities on a new display.
- final ActivityDisplay display = addNewActivityDisplayAt(ActivityDisplay.POSITION_TOP);
+ final DisplayContent display = addNewDisplayContentAt(DisplayContent.POSITION_TOP);
final ActivityStack stack1 = createStackForShouldBeVisibleTest(display,
WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
final ActivityStack stack2 = createStackForShouldBeVisibleTest(display,
@@ -1020,7 +1019,7 @@ public class ActivityStackTests extends ActivityTestsBase {
}
private ActivityRecord finishTopActivity(ActivityStack stack) {
- final ActivityRecord activity = stack.topRunningActivityLocked();
+ final ActivityRecord activity = stack.topRunningActivity();
assertNotNull(activity);
activity.setState(STOPPED, "finishTopActivity");
activity.makeFinishingLocked();
@@ -1065,6 +1064,7 @@ public class ActivityStackTests extends ActivityTestsBase {
StackOrderChangedListener listener = new StackOrderChangedListener();
mDefaultDisplay.registerStackOrderChangedListener(listener);
try {
+ mStack.mReparenting = true;
mDefaultDisplay.addStack(mStack, 0);
} finally {
mDefaultDisplay.unregisterStackOrderChangedListener(listener);
@@ -1156,10 +1156,10 @@ public class ActivityStackTests extends ActivityTestsBase {
private void verifyShouldSleepActivities(boolean focusedStack,
boolean keyguardGoingAway, boolean displaySleeping, boolean expected) {
- final ActivityDisplay display = mock(ActivityDisplay.class);
+ final DisplayContent display = mock(DisplayContent.class);
final KeyguardController keyguardController = mSupervisor.getKeyguardController();
- doReturn(display).when(mRootActivityContainer).getActivityDisplay(anyInt());
+ doReturn(display).when(mStack).getDisplay();
doReturn(keyguardGoingAway).when(keyguardController).isKeyguardGoingAway();
doReturn(displaySleeping).when(display).isSleeping();
doReturn(focusedStack).when(mStack).isFocusedStackOnDisplay();
@@ -1168,7 +1168,7 @@ public class ActivityStackTests extends ActivityTestsBase {
}
private static class StackOrderChangedListener
- implements ActivityDisplay.OnStackOrderChangedListener {
+ implements DisplayContent.OnStackOrderChangedListener {
public boolean mChanged = false;
@Override
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
index d5fdf9871f97..7e22dfcabc8e 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
@@ -47,13 +47,14 @@ import static com.android.dx.mockito.inline.extended.ExtendedMockito.spy;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.times;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;
-import static com.android.server.wm.ActivityDisplay.POSITION_BOTTOM;
-import static com.android.server.wm.ActivityDisplay.POSITION_TOP;
import static com.android.server.wm.ActivityTaskManagerService.ANIMATE;
+import static com.android.server.wm.WindowContainer.POSITION_BOTTOM;
+import static com.android.server.wm.WindowContainer.POSITION_TOP;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -501,7 +502,7 @@ public class ActivityStarterTests extends ActivityTestsBase {
*/
@Test
public void testTaskModeViolation() {
- final ActivityDisplay display = mService.mRootActivityContainer.getDefaultDisplay();
+ final DisplayContent display = mService.mRootActivityContainer.getDefaultDisplay();
display.removeAllTasks();
assertNoTasks(display);
@@ -516,10 +517,10 @@ public class ActivityStarterTests extends ActivityTestsBase {
assertNoTasks(display);
}
- private void assertNoTasks(ActivityDisplay display) {
+ private void assertNoTasks(DisplayContent display) {
for (int i = display.getStackCount() - 1; i >= 0; --i) {
final ActivityStack stack = display.getStackAt(i);
- assertThat(stack.getAllTasks()).isEmpty();
+ assertFalse(stack.hasChild());
}
}
@@ -760,8 +761,8 @@ public class ActivityStarterTests extends ActivityTestsBase {
false /* mockGetLaunchStack */);
// Create a secondary display at bottom.
- final TestActivityDisplay secondaryDisplay =
- new TestActivityDisplay.Builder(mService, 1000, 1500)
+ final TestDisplayContent secondaryDisplay =
+ new TestDisplayContent.Builder(mService, 1000, 1500)
.setPosition(POSITION_BOTTOM).build();
final ActivityStack stack = secondaryDisplay.createStack(WINDOWING_MODE_FULLSCREEN,
ACTIVITY_TYPE_STANDARD, true /* onTop */);
@@ -799,8 +800,8 @@ public class ActivityStarterTests extends ActivityTestsBase {
false /* mockGetLaunchStack */);
// Create a secondary display with an activity.
- final TestActivityDisplay secondaryDisplay =
- new TestActivityDisplay.Builder(mService, 1000, 1500).build();
+ final TestDisplayContent secondaryDisplay =
+ new TestDisplayContent.Builder(mService, 1000, 1500).build();
mRootActivityContainer.addChild(secondaryDisplay, POSITION_TOP);
final ActivityRecord singleTaskActivity = createSingleTaskActivityOn(
secondaryDisplay.createStack(WINDOWING_MODE_FULLSCREEN,
@@ -852,7 +853,7 @@ public class ActivityStarterTests extends ActivityTestsBase {
false /* mockGetLaunchStack */);
// Create a secondary display at bottom.
- final TestActivityDisplay secondaryDisplay = addNewActivityDisplayAt(POSITION_BOTTOM);
+ final TestDisplayContent secondaryDisplay = addNewDisplayContentAt(POSITION_BOTTOM);
secondaryDisplay.createStack(WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD,
true /* onTop */);
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityTaskManagerServiceTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityTaskManagerServiceTests.java
index dae1052286f7..f1de6e914032 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityTaskManagerServiceTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityTaskManagerServiceTests.java
@@ -19,15 +19,21 @@ package com.android.server.wm;
import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.any;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
import android.app.Activity;
import android.app.ActivityManager;
+import android.app.PictureInPictureParams;
import android.content.res.Configuration;
import android.graphics.Rect;
+import android.os.IBinder;
import android.view.IDisplayWindowListener;
import android.view.WindowContainerTransaction;
@@ -36,6 +42,7 @@ import androidx.test.filters.MediumTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.MockitoSession;
import java.util.ArrayList;
@@ -59,7 +66,7 @@ public class ActivityTaskManagerServiceTests extends ActivityTestsBase {
@Test
public void testActivityFinish() {
final ActivityStack stack = new StackBuilder(mRootActivityContainer).build();
- final ActivityRecord activity = stack.getChildAt(0).getTopNonFinishingActivity();
+ final ActivityRecord activity = stack.getBottomMostTask().getTopNonFinishingActivity();
assertTrue("Activity must be finished", mService.finishActivity(activity.appToken,
0 /* resultCode */, null /* resultData */,
Activity.DONT_FINISH_TASK_WITH_ACTIVITY));
@@ -75,7 +82,7 @@ public class ActivityTaskManagerServiceTests extends ActivityTestsBase {
removeGlobalMinSizeRestriction();
final ActivityStack stack = new StackBuilder(mRootActivityContainer)
.setWindowingMode(WINDOWING_MODE_FREEFORM).build();
- final Task task = stack.topTask();
+ final Task task = stack.getTopMostTask();
WindowContainerTransaction t = new WindowContainerTransaction();
Rect newBounds = new Rect(10, 10, 100, 100);
t.setBounds(task.mRemoteToken, new Rect(10, 10, 100, 100));
@@ -126,7 +133,7 @@ public class ActivityTaskManagerServiceTests extends ActivityTestsBase {
assertEquals(0, removed.size());
added.clear();
// Check adding a display
- ActivityDisplay newDisp1 = new TestActivityDisplay.Builder(mService, 600, 800).build();
+ DisplayContent newDisp1 = new TestDisplayContent.Builder(mService, 600, 800).build();
assertEquals(1, added.size());
assertEquals(0, changed.size());
assertEquals(0, removed.size());
@@ -148,5 +155,43 @@ public class ActivityTaskManagerServiceTests extends ActivityTestsBase {
assertEquals(0, changed.size());
assertEquals(1, removed.size());
}
+
+ /*
+ a test to verify b/144045134 - ignore PIP mode request for destroyed activity.
+ mocks r.getParent() to return null to cause NPE inside enterPipRunnable#run() in
+ ActivityTaskMangerservice#enterPictureInPictureMode(), which rebooted the device.
+ It doesn't fully simulate the issue's reproduce steps, but this should suffice.
+ */
+ @Test
+ public void testEnterPipModeWhenRecordParentChangesToNull() {
+ MockitoSession mockSession = mockitoSession()
+ .initMocks(this)
+ .mockStatic(ActivityRecord.class)
+ .startMocking();
+
+ ActivityRecord record = mock(ActivityRecord.class);
+ IBinder token = mock(IBinder.class);
+ PictureInPictureParams params = mock(PictureInPictureParams.class);
+ record.pictureInPictureArgs = params;
+
+ //mock operations in private method ensureValidPictureInPictureActivityParamsLocked()
+ when(ActivityRecord.forTokenLocked(token)).thenReturn(record);
+ doReturn(true).when(record).supportsPictureInPicture();
+ doReturn(false).when(params).hasSetAspectRatio();
+
+ //mock other operations
+ doReturn(true).when(record)
+ .checkEnterPictureInPictureState("enterPictureInPictureMode", false);
+ doReturn(false).when(mService).isInPictureInPictureMode(any());
+ doReturn(false).when(mService).isKeyguardLocked();
+
+ //to simulate NPE
+ doReturn(null).when(record).getParent();
+
+ mService.enterPictureInPictureMode(token, params);
+ //if record's null parent is not handled gracefully, test will fail with NPE
+
+ mockSession.finishMocking();
+ }
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java b/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java
index 0021cc5368e2..b72cc942594f 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java
@@ -77,9 +77,9 @@ class ActivityTestsBase extends SystemServiceTestsBase {
mRootActivityContainer = mService.mRootActivityContainer;
}
- /** Creates and adds a {@link TestActivityDisplay} to supervisor at the given position. */
- TestActivityDisplay addNewActivityDisplayAt(int position) {
- return new TestActivityDisplay.Builder(mService, 1000, 1500).setPosition(position).build();
+ /** Creates and adds a {@link TestDisplayContent} to supervisor at the given position. */
+ TestDisplayContent addNewDisplayContentAt(int position) {
+ return new TestDisplayContent.Builder(mService, 1000, 1500).setPosition(position).build();
}
/** Sets the default minimum task size to 1 so that tests can use small task sizes */
@@ -381,7 +381,7 @@ class ActivityTestsBase extends SystemServiceTestsBase {
static class StackBuilder {
private final RootActivityContainer mRootActivityContainer;
- private ActivityDisplay mDisplay;
+ private DisplayContent mDisplay;
private int mStackId = -1;
private int mWindowingMode = WINDOWING_MODE_UNDEFINED;
private int mActivityType = ACTIVITY_TYPE_STANDARD;
@@ -408,15 +408,8 @@ class ActivityTestsBase extends SystemServiceTestsBase {
return this;
}
- // TODO(display-merge): Remove
- StackBuilder setDisplay(ActivityDisplay display) {
- mDisplay = display;
- return this;
- }
-
StackBuilder setDisplay(DisplayContent display) {
- // TODO(display-merge): Remove cast
- mDisplay = (ActivityDisplay) display;
+ mDisplay = display;
return this;
}
@@ -449,7 +442,7 @@ class ActivityTestsBase extends SystemServiceTestsBase {
if (mOnTop) {
// We move the task to front again in order to regain focus after activity
// added to the stack.
- // Or {@link ActivityDisplay#mPreferredTopFocusableStack} could be other
+ // Or {@link DisplayContent#mPreferredTopFocusableStack} could be other
// stacks (e.g. home stack).
stack.moveToFront("createActivityStack");
} else {
diff --git a/services/tests/wmtests/src/com/android/server/wm/AnimatingActivityRegistryTest.java b/services/tests/wmtests/src/com/android/server/wm/AnimatingActivityRegistryTest.java
index c6203c5736fc..a39be565121f 100644
--- a/services/tests/wmtests/src/com/android/server/wm/AnimatingActivityRegistryTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/AnimatingActivityRegistryTest.java
@@ -60,6 +60,7 @@ public class AnimatingActivityRegistryTest extends WindowTestsBase {
}
@Test
+ @FlakyTest(bugId = 144611135)
public void testDeferring() {
final ActivityRecord activity1 = createActivityRecord(mDisplayContent,
WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
diff --git a/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java b/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java
index 0382bf829acf..70e5ee71b448 100644
--- a/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java
@@ -31,7 +31,6 @@ import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
import static android.view.WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
-import static android.view.WindowManager.TRANSIT_UNSET;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
@@ -136,17 +135,19 @@ public class AppWindowTokenTests extends WindowTestsBase {
@Test
@Presubmit
- public void testGetTopFullscreenWindow() {
- assertNull(mActivity.getTopFullscreenWindow());
+ public void testGetTopFullscreenOpaqueWindow() {
+ assertNull(mActivity.getTopFullscreenOpaqueWindow());
final WindowState window1 = createWindow(null, TYPE_BASE_APPLICATION, mActivity, "window1");
final WindowState window11 = createWindow(null, TYPE_APPLICATION, mActivity, "window11");
final WindowState window12 = createWindow(null, TYPE_APPLICATION, mActivity, "window12");
- assertEquals(window12, mActivity.getTopFullscreenWindow());
+ assertEquals(window12, mActivity.getTopFullscreenOpaqueWindow());
window12.mAttrs.width = 500;
- assertEquals(window11, mActivity.getTopFullscreenWindow());
+ assertEquals(window11, mActivity.getTopFullscreenOpaqueWindow());
window11.mAttrs.width = 500;
- assertEquals(window1, mActivity.getTopFullscreenWindow());
+ assertEquals(window1, mActivity.getTopFullscreenOpaqueWindow());
+ window1.mAttrs.alpha = 0f;
+ assertNull(mActivity.getTopFullscreenOpaqueWindow());
mActivity.removeImmediately();
}
@@ -182,7 +183,7 @@ public class AppWindowTokenTests extends WindowTestsBase {
@Test
public void testLandscapeSeascapeRotationByPolicy() {
- // This instance has been spied in {@link TestActivityDisplay}.
+ // This instance has been spied in {@link TestDisplayContent}.
final DisplayRotation displayRotation = mDisplayContent.getDisplayRotation();
final WindowManager.LayoutParams attrs = new WindowManager.LayoutParams(
@@ -303,8 +304,8 @@ public class AppWindowTokenTests extends WindowTestsBase {
"closingWindow");
closingWindow.mAnimatingExit = true;
closingWindow.mRemoveOnExit = true;
- closingWindow.mActivityRecord.commitVisibility(null, false /* visible */, TRANSIT_UNSET,
- true /* performLayout */, false /* isVoiceInteraction */);
+ closingWindow.mActivityRecord.commitVisibility(
+ false /* visible */, true /* performLayout */);
// We pretended that we were running an exit animation, but that should have been cleared up
// by changing visibility of ActivityRecord
diff --git a/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java b/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java
index 716e777ab779..ccbafd4768c3 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java
@@ -244,7 +244,6 @@ public class DisplayContentTests extends WindowTestsBase {
// Add stack with activity.
final ActivityStack stack = createTaskStackOnDisplay(dc);
assertEquals(dc.getDisplayId(), stack.getDisplayContent().getDisplayId());
- assertEquals(dc, stack.getParent().getParent());
assertEquals(dc, stack.getDisplayContent());
final Task task = createTaskInStack(stack, 0 /* userId */);
@@ -256,7 +255,6 @@ public class DisplayContentTests extends WindowTestsBase {
// Move stack to first display.
mDisplayContent.moveStackToDisplay(stack, true /* onTop */);
assertEquals(mDisplayContent.getDisplayId(), stack.getDisplayContent().getDisplayId());
- assertEquals(mDisplayContent, stack.getParent().getParent());
assertEquals(mDisplayContent, stack.getDisplayContent());
assertEquals(mDisplayContent, task.getDisplayContent());
assertEquals(mDisplayContent, activity.getDisplayContent());
@@ -744,7 +742,7 @@ public class DisplayContentTests extends WindowTestsBase {
final ActivityStack stack =
new ActivityTestsBase.StackBuilder(mWm.mAtmService.mRootActivityContainer)
.setDisplay(dc).build();
- final ActivityRecord activity = stack.topTask().getTopNonFinishingActivity();
+ final ActivityRecord activity = stack.getTopMostTask().getTopNonFinishingActivity();
activity.setRequestedOrientation(newOrientation);
@@ -766,13 +764,12 @@ public class DisplayContentTests extends WindowTestsBase {
final ActivityStack stack =
new ActivityTestsBase.StackBuilder(mWm.mAtmService.mRootActivityContainer)
.setDisplay(dc).build();
- final ActivityRecord activity = stack.topTask().getTopNonFinishingActivity();
+ final ActivityRecord activity = stack.getTopMostTask().getTopNonFinishingActivity();
activity.setRequestedOrientation(newOrientation);
- // TODO(display-merge): Remove cast
- verify((ActivityDisplay) dc, never()).updateDisplayOverrideConfigurationLocked(any(),
- eq(activity), anyBoolean(), same(null));
+ verify(dc, never()).updateDisplayOverrideConfigurationLocked(any(), eq(activity),
+ anyBoolean(), same(null));
assertEquals(dc.getDisplayRotation().getUserRotation(), dc.getRotation());
}
@@ -966,7 +963,7 @@ public class DisplayContentTests extends WindowTestsBase {
invocation -> {
continued[0] = true;
return true;
- }).when((ActivityDisplay) dc).updateDisplayOverrideConfigurationLocked();
+ }).when(dc).updateDisplayOverrideConfigurationLocked();
final boolean[] called = new boolean[1];
mWm.mDisplayRotationController =
new IDisplayWindowRotationController.Stub() {
diff --git a/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyLayoutTests.java b/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyLayoutTests.java
index 62ab11c5a18f..de73645833de 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyLayoutTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyLayoutTests.java
@@ -36,6 +36,7 @@ import static android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_M
import static android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER;
import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_DRAW_BAR_BACKGROUNDS;
import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_IS_SCREEN_DECOR;
+import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_ONLY_DRAW_BOTTOM_BAR_BACKGROUND;
import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION;
@@ -45,6 +46,7 @@ import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
+import static org.junit.Assume.assumeTrue;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.spy;
@@ -55,6 +57,10 @@ import android.platform.test.annotations.Presubmit;
import android.util.Pair;
import android.view.DisplayCutout;
import android.view.DisplayInfo;
+import android.view.InsetsState;
+import android.view.ViewRootImpl;
+import android.view.WindowInsets.Side;
+import android.view.WindowInsets.Type;
import android.view.WindowManager;
import androidx.test.filters.FlakyTest;
@@ -97,8 +103,6 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
final WindowManager.LayoutParams attrs = mWindow.mAttrs;
attrs.width = MATCH_PARENT;
attrs.height = MATCH_PARENT;
- attrs.flags =
- FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR | FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
attrs.format = PixelFormat.TRANSLUCENT;
}
@@ -134,8 +138,186 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
}
@Test
+ public void layoutWindowLw_fitStatusBars() {
+ assumeTrue(ViewRootImpl.sNewInsetsMode == ViewRootImpl.NEW_INSETS_MODE_FULL);
+
+ mWindow.mAttrs.setFitWindowInsetsTypes(Type.statusBars());
+ addWindow(mWindow);
+
+ mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+ mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+
+ assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getDisplayFrameLw(), STATUS_BAR_HEIGHT, 0);
+ assertInsetByTopBottom(mWindow.getParentFrame(), STATUS_BAR_HEIGHT, 0);
+ assertInsetByTopBottom(mWindow.getVisibleFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
+ }
+
+ @Test
+ public void layoutWindowLw_fitNavigationBars() {
+ assumeTrue(ViewRootImpl.sNewInsetsMode == ViewRootImpl.NEW_INSETS_MODE_FULL);
+
+ mWindow.mAttrs.setFitWindowInsetsTypes(Type.navigationBars());
+ addWindow(mWindow);
+
+ mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+ mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+
+ assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getDisplayFrameLw(), 0, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getParentFrame(), 0, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getVisibleFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
+ }
+
+ @Test
public void layoutWindowLw_appDrawsBars() {
- mWindow.mAttrs.flags |= FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
+ assumeTrue(ViewRootImpl.sNewInsetsMode == ViewRootImpl.NEW_INSETS_MODE_FULL);
+
+ mWindow.mAttrs.flags = FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
+ mWindow.mAttrs.setFitWindowInsetsTypes(Type.systemBars());
+ addWindow(mWindow);
+
+ mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+ mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+
+ assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getDisplayFrameLw(), 0, 0);
+ assertInsetByTopBottom(mWindow.getParentFrame(), 0, 0);
+ assertInsetByTopBottom(mWindow.getVisibleFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
+ }
+
+ @Test
+ public void layoutWindowLw_forceAppDrawBars() {
+ assumeTrue(ViewRootImpl.sNewInsetsMode == ViewRootImpl.NEW_INSETS_MODE_FULL);
+
+ mWindow.mAttrs.privateFlags = PRIVATE_FLAG_FORCE_DRAW_BAR_BACKGROUNDS;
+ mWindow.mAttrs.setFitWindowInsetsTypes(Type.systemBars());
+ addWindow(mWindow);
+
+ mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+ mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+
+ assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getDisplayFrameLw(), 0, 0);
+ assertInsetByTopBottom(mWindow.getParentFrame(), 0, 0);
+ assertInsetByTopBottom(mWindow.getVisibleFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
+ }
+
+ @Test
+ public void layoutWindowLw_onlyDrawBottomBar() {
+ assumeTrue(ViewRootImpl.sNewInsetsMode == ViewRootImpl.NEW_INSETS_MODE_FULL);
+
+ mWindow.mAttrs.flags = FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
+ mWindow.mAttrs.privateFlags = PRIVATE_FLAG_ONLY_DRAW_BOTTOM_BAR_BACKGROUND;
+ mWindow.mAttrs.setFitWindowInsetsTypes(Type.systemBars());
+ addWindow(mWindow);
+
+ mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+ mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+
+ assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getDisplayFrameLw(), STATUS_BAR_HEIGHT, 0);
+ assertInsetByTopBottom(mWindow.getParentFrame(), STATUS_BAR_HEIGHT, 0);
+ assertInsetByTopBottom(mWindow.getVisibleFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
+ }
+
+ @Test
+ public void layoutWindowLw_fitAllSides() {
+ assumeTrue(ViewRootImpl.sNewInsetsMode == ViewRootImpl.NEW_INSETS_MODE_FULL);
+
+ mWindow.mAttrs.setFitWindowInsetsSides(Side.all());
+ addWindow(mWindow);
+
+ mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+ mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+
+ assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getDisplayFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getParentFrame(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getVisibleFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
+ }
+
+ @Test
+ public void layoutWindowLw_fitTopOnly() {
+ assumeTrue(ViewRootImpl.sNewInsetsMode == ViewRootImpl.NEW_INSETS_MODE_FULL);
+
+ mWindow.mAttrs.setFitWindowInsetsSides(Side.TOP);
+ addWindow(mWindow);
+
+ mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+ mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+
+ assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getDisplayFrameLw(), STATUS_BAR_HEIGHT, 0);
+ assertInsetByTopBottom(mWindow.getParentFrame(), STATUS_BAR_HEIGHT, 0);
+ assertInsetByTopBottom(mWindow.getVisibleFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
+ }
+
+ @Test
+ public void layoutWindowLw_fitMax() {
+ assumeTrue(ViewRootImpl.sNewInsetsMode == ViewRootImpl.NEW_INSETS_MODE_FULL);
+
+ final InsetsState state =
+ mDisplayContent.getInsetsStateController().getInsetsForDispatch(mWindow);
+ state.getSource(InsetsState.ITYPE_STATUS_BAR).setVisible(false);
+ state.getSource(InsetsState.ITYPE_NAVIGATION_BAR).setVisible(false);
+ mWindow.mAttrs.setFitIgnoreVisibility(true);
+ addWindow(mWindow);
+
+ mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+ mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+
+ assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getDisplayFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getParentFrame(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getVisibleFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
+ }
+
+ @Test
+ public void layoutWindowLw_fitNonMax() {
+ assumeTrue(ViewRootImpl.sNewInsetsMode == ViewRootImpl.NEW_INSETS_MODE_FULL);
+
+ final InsetsState state =
+ mDisplayContent.getInsetsStateController().getInsetsForDispatch(mWindow);
+ state.getSource(InsetsState.ITYPE_STATUS_BAR).setVisible(false);
+ state.getSource(InsetsState.ITYPE_NAVIGATION_BAR).setVisible(false);
+ mWindow.mAttrs.setFitIgnoreVisibility(false);
+ addWindow(mWindow);
+
+ mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+ mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+
+ assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getDisplayFrameLw(), 0, 0);
+ assertInsetByTopBottom(mWindow.getParentFrame(), 0, 0);
+ assertInsetByTopBottom(mWindow.getVisibleFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+ assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
+ }
+
+ // TODO(b/118118435): remove after migration
+ @Test
+ public void layoutWindowLw_appDrawsBarsLegacy() {
+ assumeTrue(ViewRootImpl.sNewInsetsMode != ViewRootImpl.NEW_INSETS_MODE_FULL);
+
+ mWindow.mAttrs.flags =
+ FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR | FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
addWindow(mWindow);
mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
@@ -148,9 +330,12 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
assertInsetBy(mWindow.getDisplayFrameLw(), 0, 0, 0, 0);
}
+ // TODO(b/118118435): remove after migration
@Test
public void layoutWindowLw_appWontDrawBars() {
- mWindow.mAttrs.flags &= ~FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
+ assumeTrue(ViewRootImpl.sNewInsetsMode != ViewRootImpl.NEW_INSETS_MODE_FULL);
+
+ mWindow.mAttrs.flags = FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR;
addWindow(mWindow);
mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
@@ -163,10 +348,13 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
assertInsetByTopBottom(mWindow.getDisplayFrameLw(), 0, NAV_BAR_HEIGHT);
}
+ // TODO(b/118118435): remove after migration
@Test
public void layoutWindowLw_appWontDrawBars_forceStatusAndNav() throws Exception {
- mWindow.mAttrs.flags &= ~FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
- mWindow.mAttrs.privateFlags |= PRIVATE_FLAG_FORCE_DRAW_BAR_BACKGROUNDS;
+ assumeTrue(ViewRootImpl.sNewInsetsMode != ViewRootImpl.NEW_INSETS_MODE_FULL);
+
+ mWindow.mAttrs.flags = FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR;
+ mWindow.mAttrs.privateFlags = PRIVATE_FLAG_FORCE_DRAW_BAR_BACKGROUNDS;
addWindow(mWindow);
mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
@@ -179,11 +367,14 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
assertInsetByTopBottom(mWindow.getDisplayFrameLw(), 0, 0);
}
+ // TODO(b/118118435): remove after migration (keyguard dialog is not special with the new logic)
@Test
public void layoutWindowLw_keyguardDialog_hideNav() {
mWindow.mAttrs.type = TYPE_KEYGUARD_DIALOG;
- mWindow.mAttrs.flags |= FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
+ mWindow.mAttrs.flags =
+ FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR | FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
mWindow.mAttrs.systemUiVisibility = SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
+ mWindow.mAttrs.setFitWindowInsetsTypes(0 /* types */);
addWindow(mWindow);
mDisplayPolicy.beginLayoutLw(mFrames, 0 /* uiMode */);
@@ -200,6 +391,8 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
public void layoutWindowLw_withDisplayCutout() {
addDisplayCutout();
+ mWindow.mAttrs.flags =
+ FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR | FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
addWindow(mWindow);
mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
@@ -216,6 +409,8 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
public void layoutWindowLw_withDisplayCutout_never() {
addDisplayCutout();
+ mWindow.mAttrs.flags =
+ FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR | FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
mWindow.mAttrs.layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER;
addWindow(mWindow);
@@ -233,7 +428,11 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
public void layoutWindowLw_withDisplayCutout_layoutFullscreen() {
addDisplayCutout();
+ mWindow.mAttrs.flags =
+ FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR | FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
mWindow.mAttrs.subtreeSystemUiVisibility |= SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
+ mWindow.mAttrs.setFitWindowInsetsTypes(
+ mWindow.mAttrs.getFitWindowInsetsTypes() & ~Type.statusBars());
addWindow(mWindow);
mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
@@ -243,14 +442,18 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
- assertInsetBy(mWindow.getDisplayFrameLw(), 0, 0, 0, 0);
+ assertInsetByTopBottom(mWindow.getDisplayFrameLw(), 0, 0);
}
@Test
public void layoutWindowLw_withDisplayCutout_fullscreen() {
addDisplayCutout();
+ mWindow.mAttrs.flags =
+ FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR | FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
mWindow.mAttrs.subtreeSystemUiVisibility |= SYSTEM_UI_FLAG_FULLSCREEN;
+ mDisplayContent.getInsetsStateController().getInsetsForDispatch(mWindow)
+ .getSource(InsetsState.ITYPE_STATUS_BAR).setVisible(false);
addWindow(mWindow);
mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
@@ -267,7 +470,11 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
public void layoutWindowLw_withDisplayCutout_fullscreenInCutout() {
addDisplayCutout();
+ mWindow.mAttrs.flags =
+ FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR | FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
mWindow.mAttrs.subtreeSystemUiVisibility |= SYSTEM_UI_FLAG_FULLSCREEN;
+ mDisplayContent.getInsetsStateController().getInsetsForDispatch(mWindow)
+ .getSource(InsetsState.ITYPE_STATUS_BAR).setVisible(false);
mWindow.mAttrs.layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
addWindow(mWindow);
@@ -286,6 +493,9 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
public void layoutWindowLw_withDisplayCutout_landscape() {
addDisplayCutout();
setRotation(ROTATION_90);
+
+ mWindow.mAttrs.flags =
+ FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR | FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
addWindow(mWindow);
mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
@@ -303,6 +513,9 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
public void layoutWindowLw_withDisplayCutout_seascape() {
addDisplayCutout();
setRotation(ROTATION_270);
+
+ mWindow.mAttrs.flags =
+ FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR | FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
addWindow(mWindow);
mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
@@ -321,7 +534,11 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
addDisplayCutout();
setRotation(ROTATION_90);
+ mWindow.mAttrs.flags =
+ FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR | FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
mWindow.mAttrs.subtreeSystemUiVisibility |= SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
+ mWindow.mAttrs.setFitWindowInsetsTypes(
+ mWindow.mAttrs.getFitWindowInsetsTypes() & ~Type.statusBars());
addWindow(mWindow);
mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
@@ -339,6 +556,7 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
addDisplayCutout();
mWindow.mAttrs.flags = FLAG_LAYOUT_IN_SCREEN;
+ mWindow.mAttrs.setFitWindowInsetsTypes(Type.systemBars() & ~Type.statusBars());
mWindow.mAttrs.type = TYPE_APPLICATION_OVERLAY;
mWindow.mAttrs.width = DISPLAY_WIDTH;
mWindow.mAttrs.height = DISPLAY_HEIGHT;
@@ -356,7 +574,11 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
addDisplayCutout();
setRotation(ROTATION_90);
+ mWindow.mAttrs.flags =
+ FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR | FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
mWindow.mAttrs.subtreeSystemUiVisibility |= SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
+ mWindow.mAttrs.setFitWindowInsetsTypes(
+ mWindow.mAttrs.getFitWindowInsetsTypes() & ~Type.statusBars());
mWindow.mAttrs.layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
addWindow(mWindow);
@@ -372,6 +594,8 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
@Test
public void layoutWindowLw_withForwardInset_SoftInputAdjustResize() {
+ mWindow.mAttrs.flags =
+ FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR | FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
mWindow.mAttrs.softInputMode = SOFT_INPUT_ADJUST_RESIZE;
addWindow(mWindow);
@@ -392,6 +616,8 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
@Test
public void layoutWindowLw_withForwardInset_SoftInputAdjustNothing() {
+ mWindow.mAttrs.flags =
+ FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR | FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
mWindow.mAttrs.softInputMode = SOFT_INPUT_ADJUST_NOTHING;
addWindow(mWindow);
@@ -408,9 +634,12 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
assertInsetBy(mWindow.getDisplayFrameLw(), 0, 0, 0, 0);
}
+ // TODO(b/118118435): remove after removing PolicyControl
@FlakyTest(bugId = 129711077)
@Test
public void layoutWindowLw_withImmersive_SoftInputAdjustResize() {
+ assumeTrue(ViewRootImpl.sNewInsetsMode != ViewRootImpl.NEW_INSETS_MODE_FULL);
+
synchronized (mWm.mGlobalLock) {
mWindow.mAttrs.softInputMode = SOFT_INPUT_ADJUST_RESIZE;
mWindow.mAttrs.flags = 0;
@@ -433,9 +662,12 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
}
}
+ // TODO(b/118118435): remove after removing PolicyControl
@FlakyTest(bugId = 129711077)
@Test
public void layoutWindowLw_withImmersive_SoftInputAdjustNothing() {
+ assumeTrue(ViewRootImpl.sNewInsetsMode != ViewRootImpl.NEW_INSETS_MODE_FULL);
+
synchronized (mWm.mGlobalLock) {
mWindow.mAttrs.softInputMode = SOFT_INPUT_ADJUST_NOTHING;
mWindow.mAttrs.flags = 0;
@@ -457,9 +689,12 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
}
}
+ // TODO(b/118118435): remove after removing PolicyControl
@FlakyTest(bugId = 129711077)
@Test
public void layoutWindowLw_withForceImmersive_fullscreen() {
+ assumeTrue(ViewRootImpl.sNewInsetsMode != ViewRootImpl.NEW_INSETS_MODE_FULL);
+
synchronized (mWm.mGlobalLock) {
mWindow.mAttrs.softInputMode = SOFT_INPUT_ADJUST_RESIZE;
mWindow.mAttrs.flags = 0;
@@ -481,9 +716,12 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
}
}
+ // TODO(b/118118435): remove after removing PolicyControl
@FlakyTest(bugId = 129711077)
@Test
public void layoutWindowLw_withForceImmersive_nonFullscreen() {
+ assumeTrue(ViewRootImpl.sNewInsetsMode != ViewRootImpl.NEW_INSETS_MODE_FULL);
+
synchronized (mWm.mGlobalLock) {
mWindow.mAttrs.softInputMode = SOFT_INPUT_ADJUST_RESIZE;
mWindow.mAttrs.flags = 0;
@@ -509,6 +747,9 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
@Test
public void layoutHint_appWindow() {
+ mWindow.mAttrs.flags =
+ FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR | FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
+
// Initialize DisplayFrames
mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
@@ -530,6 +771,9 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
@Test
public void layoutHint_appWindowInTask() {
+ mWindow.mAttrs.flags =
+ FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR | FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
+
// Initialize DisplayFrames
mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
@@ -553,6 +797,9 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
@Test
public void layoutHint_appWindowInTask_outsideContentFrame() {
+ mWindow.mAttrs.flags =
+ FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR | FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
+
// Initialize DisplayFrames
mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
@@ -581,7 +828,8 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
public void forceShowSystemBars_clearsSystemUIFlags() {
mDisplayPolicy.mLastSystemUiFlags |= SYSTEM_UI_FLAG_FULLSCREEN;
mWindow.mAttrs.subtreeSystemUiVisibility |= SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
- mWindow.mAttrs.flags |= FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
+ mWindow.mAttrs.flags =
+ FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR | FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
mWindow.mSystemUiVisibility = SYSTEM_UI_FLAG_FULLSCREEN;
mDisplayPolicy.setForceShowSystemBars(true);
addWindow(mWindow);
@@ -600,7 +848,8 @@ public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
@Test
public void testScreenDecorWindows() {
final WindowState decorWindow = createWindow(null, TYPE_APPLICATION_OVERLAY, "decorWindow");
- decorWindow.mAttrs.flags |= FLAG_NOT_FOCUSABLE;
+ mWindow.mAttrs.flags = FLAG_NOT_FOCUSABLE | FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR
+ | FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
decorWindow.mAttrs.privateFlags |= PRIVATE_FLAG_IS_SCREEN_DECOR;
addWindow(decorWindow);
addWindow(mWindow);
diff --git a/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyTestsBase.java b/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyTestsBase.java
index d4558dc29fda..d0b335082ef5 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyTestsBase.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyTestsBase.java
@@ -78,6 +78,8 @@ public class DisplayPolicyTestsBase extends WindowTestsBase {
resources.addOverride(R.dimen.navigation_bar_height, NAV_BAR_HEIGHT);
resources.addOverride(R.dimen.navigation_bar_height_landscape, NAV_BAR_HEIGHT);
resources.addOverride(R.dimen.navigation_bar_width, NAV_BAR_HEIGHT);
+ resources.addOverride(R.dimen.navigation_bar_frame_height_landscape, NAV_BAR_HEIGHT);
+ resources.addOverride(R.dimen.navigation_bar_frame_height, NAV_BAR_HEIGHT);
doReturn(resources.getResources()).when(mDisplayPolicy).getCurrentUserResources();
doReturn(true).when(mDisplayPolicy).hasNavigationBar();
doReturn(true).when(mDisplayPolicy).hasStatusBar();
diff --git a/services/tests/wmtests/src/com/android/server/wm/LaunchParamsPersisterTests.java b/services/tests/wmtests/src/com/android/server/wm/LaunchParamsPersisterTests.java
index 9e5d9da65b87..84914bb8899b 100644
--- a/services/tests/wmtests/src/com/android/server/wm/LaunchParamsPersisterTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/LaunchParamsPersisterTests.java
@@ -80,7 +80,7 @@ public class LaunchParamsPersisterTests extends ActivityTestsBase {
private TestPersisterQueue mPersisterQueue;
private File mFolder;
- private ActivityDisplay mTestDisplay;
+ private DisplayContent mTestDisplay;
private String mDisplayUniqueId;
private Task mTestTask;
private Task mTaskWithDifferentUser;
@@ -104,9 +104,9 @@ public class LaunchParamsPersisterTests extends ActivityTestsBase {
deleteRecursively(mFolder);
mDisplayUniqueId = "test:" + Integer.toString(sNextUniqueId++);
- mTestDisplay = new TestActivityDisplay.Builder(mService, 1000, 1500)
+ mTestDisplay = new TestDisplayContent.Builder(mService, 1000, 1500)
.setUniqueId(mDisplayUniqueId).build();
- when(mRootActivityContainer.getActivityDisplay(eq(mDisplayUniqueId)))
+ when(mRootActivityContainer.getDisplayContent(eq(mDisplayUniqueId)))
.thenReturn(mTestDisplay);
ActivityStack stack = mTestDisplay.createStack(TEST_WINDOWING_MODE,
@@ -180,7 +180,7 @@ public class LaunchParamsPersisterTests extends ActivityTestsBase {
public void testReturnsEmptyDisplayIfDisplayIsNotFound() {
mTarget.saveTask(mTestTask);
- when(mRootActivityContainer.getActivityDisplay(eq(mDisplayUniqueId))).thenReturn(null);
+ when(mRootActivityContainer.getDisplayContent(eq(mDisplayUniqueId))).thenReturn(null);
mTarget.getLaunchParams(mTestTask, null, mResult);
diff --git a/services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java
index 6ced8160b426..0cc2626d9f89 100644
--- a/services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java
@@ -106,6 +106,7 @@ public class LockTaskControllerTest {
@Mock private ActivityStackSupervisor mSupervisor;
@Mock private RootActivityContainer mRootActivityContainer;
+ @Mock private RootWindowContainer mRootWindowContainer;
@Mock private IDevicePolicyManager mDevicePolicyManager;
@Mock private IStatusBarService mStatusBarService;
@Mock private WindowManagerService mWindowManager;
@@ -134,6 +135,7 @@ public class LockTaskControllerTest {
mSupervisor.mRecentTasks = mRecentTasks;
mSupervisor.mRootActivityContainer = mRootActivityContainer;
+ mRootActivityContainer.mRootWindowContainer = mRootWindowContainer;
mLockTaskController = new LockTaskController(mContext, mSupervisor,
new ImmediatelyExecuteHandler());
diff --git a/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java b/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java
index 9f97c488cf4d..eaf4aa34a0a4 100644
--- a/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java
@@ -41,8 +41,12 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -98,7 +102,7 @@ public class RecentTasksTest extends ActivityTestsBase {
UserManager.USER_TYPE_PROFILE_MANAGED);
private static final int INVALID_STACK_ID = 999;
- private ActivityDisplay mDisplay;
+ private DisplayContent mDisplay;
private ActivityStack mStack;
private TestTaskPersister mTaskPersister;
private TestRecentTasks mRecentTasks;
@@ -112,7 +116,8 @@ public class RecentTasksTest extends ActivityTestsBase {
@Before
public void setUp() throws Exception {
mTaskPersister = new TestTaskPersister(mContext.getFilesDir());
- mDisplay = mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
+ spyOn(mTaskPersister);
+ mDisplay = mRootActivityContainer.getDisplayContent(DEFAULT_DISPLAY);
// Set the recent tasks we should use for testing in this class.
mRecentTasks = new TestRecentTasks(mService, mTaskPersister);
@@ -171,6 +176,46 @@ public class RecentTasksTest extends ActivityTestsBase {
}
@Test
+ public void testPersister() {
+ // Add some tasks, ensure the persister is woken
+ mRecentTasks.add(mTasks.get(0));
+ mRecentTasks.add(mTasks.get(1));
+ verify(mTaskPersister, times(1)).wakeup(eq(mTasks.get(0)), anyBoolean());
+ verify(mTaskPersister, times(1)).wakeup(eq(mTasks.get(1)), anyBoolean());
+ reset(mTaskPersister);
+
+ // Update a task, ensure the persister is woken
+ mRecentTasks.add(mTasks.get(0));
+ verify(mTaskPersister, times(1)).wakeup(eq(mTasks.get(0)), anyBoolean());
+ reset(mTaskPersister);
+
+ // Remove some tasks, ensure the persister is woken
+ mRecentTasks.remove(mTasks.get(0));
+ mRecentTasks.remove(mTasks.get(1));
+ verify(mTaskPersister, times(1)).wakeup(eq(mTasks.get(0)), anyBoolean());
+ verify(mTaskPersister, times(1)).wakeup(eq(mTasks.get(1)), anyBoolean());
+ reset(mTaskPersister);
+ }
+
+ @Test
+ public void testPersisterTrimmed() {
+ mRecentTasks.setOnlyTestVisibleRange();
+
+ // Limit the global maximum number of recent tasks to a fixed size
+ mRecentTasks.setGlobalMaxNumTasks(1 /* globalMaxNumTasks */);
+
+ mRecentTasks.add(mTasks.get(0));
+ verify(mTaskPersister, times(1)).wakeup(eq(mTasks.get(0)), anyBoolean());
+ reset(mTaskPersister);
+
+ // Add N+1 tasks to ensure the previous task is trimmed
+ mRecentTasks.add(mTasks.get(1));
+ verify(mTaskPersister, times(1)).wakeup(eq(mTasks.get(0)), anyBoolean());
+ verify(mTaskPersister, times(1)).wakeup(eq(mTasks.get(1)), anyBoolean());
+ assertTrimmed(mTasks.get(0));
+ }
+
+ @Test
public void testAddTasksNoMultiple_expectNoTrim() {
// Add same non-multiple-task document tasks will remove the task (to re-add it) but not
// trim it
@@ -608,8 +653,8 @@ public class RecentTasksTest extends ActivityTestsBase {
mRecentTasks.setOnlyTestVisibleRange();
mRecentTasks.setParameters(-1 /* min */, 3 /* max */, -1 /* ms */);
- final ActivityDisplay singleTaskDisplay =
- addNewActivityDisplayAt(ActivityDisplay.POSITION_TOP);
+ final DisplayContent singleTaskDisplay =
+ addNewDisplayContentAt(DisplayContent.POSITION_TOP);
singleTaskDisplay.setDisplayToSingleTaskInstance();
ActivityStack singleTaskStack = singleTaskDisplay.createStack(
WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
@@ -788,7 +833,7 @@ public class RecentTasksTest extends ActivityTestsBase {
mRecentTasks.setParameters(-1 /* min */, 1 /* max */, -1 /* ms */);
final ActivityStack homeStack = mDisplay.getHomeStack();
- final ActivityDisplay otherDisplay = addNewActivityDisplayAt(ActivityDisplay.POSITION_TOP);
+ final DisplayContent otherDisplay = addNewDisplayContentAt(DisplayContent.POSITION_TOP);
final ActivityStack otherDisplayStack = otherDisplay.createStack(
WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
@@ -1282,10 +1327,10 @@ public class RecentTasksTest extends ActivityTestsBase {
@Override
void getTasks(int maxNum, List<RunningTaskInfo> list, int ignoreActivityType,
- int ignoreWindowingMode, ArrayList<ActivityDisplay> activityDisplays,
+ int ignoreWindowingMode, RootActivityContainer root,
int callingUid, boolean allowed, boolean crossUser, ArraySet<Integer> profileIds) {
mLastAllowed = allowed;
- super.getTasks(maxNum, list, ignoreActivityType, ignoreWindowingMode, activityDisplays,
+ super.getTasks(maxNum, list, ignoreActivityType, ignoreWindowingMode, root,
callingUid, allowed, crossUser, profileIds);
}
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java
index 2374847283e0..945928d1b967 100644
--- a/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java
@@ -138,8 +138,7 @@ public class RecentsAnimationControllerTest extends WindowTestsBase {
@Test
public void testIncludedApps_expectTargetAndVisible() {
mWm.setRecentsAnimationController(mController);
- // TODO(display-merge): Remove cast
- final ActivityStack homeStack = ((ActivityDisplay) mDisplayContent).getOrCreateStack(
+ final ActivityStack homeStack = mDisplayContent.getOrCreateStack(
WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, ON_TOP);
final ActivityRecord homeActivity =
new ActivityTestsBase.ActivityBuilder(mWm.mAtmService)
@@ -164,8 +163,7 @@ public class RecentsAnimationControllerTest extends WindowTestsBase {
@Test
public void testWallpaperIncluded_expectTarget() throws Exception {
mWm.setRecentsAnimationController(mController);
- // TODO(display-merge): Remove cast
- final ActivityStack homeStack = ((ActivityDisplay) mDisplayContent).getOrCreateStack(
+ final ActivityStack homeStack = mDisplayContent.getOrCreateStack(
WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, ON_TOP);
final ActivityRecord homeAppWindow =
new ActivityTestsBase.ActivityBuilder(mWm.mAtmService)
@@ -194,8 +192,7 @@ public class RecentsAnimationControllerTest extends WindowTestsBase {
@Test
public void testWallpaperAnimatorCanceled_expectAnimationKeepsRunning() throws Exception {
mWm.setRecentsAnimationController(mController);
- // TODO(display-merge): Remove cast
- final ActivityStack homeStack = ((ActivityDisplay) mDisplayContent).getOrCreateStack(
+ final ActivityStack homeStack = mDisplayContent.getOrCreateStack(
WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, ON_TOP);
final ActivityRecord homeActivity =
new ActivityTestsBase.ActivityBuilder(mWm.mAtmService)
@@ -226,8 +223,7 @@ public class RecentsAnimationControllerTest extends WindowTestsBase {
@Test
public void testFinish_expectTargetAndWallpaperAdaptersRemoved() {
mWm.setRecentsAnimationController(mController);
- // TODO(display-merge): Remove cast
- final ActivityStack homeStack = ((ActivityDisplay) mDisplayContent).getOrCreateStack(
+ final ActivityStack homeStack = mDisplayContent.getOrCreateStack(
WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, ON_TOP);
final ActivityRecord homeActivity =
new ActivityTestsBase.ActivityBuilder(mWm.mAtmService)
diff --git a/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java
index 4abab63cba81..07be3e47859b 100644
--- a/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java
@@ -88,7 +88,7 @@ public class RecentsAnimationTest extends ActivityTestsBase {
@Test
public void testRecentsActivityVisiblility() {
- ActivityDisplay display = mRootActivityContainer.getDefaultDisplay();
+ DisplayContent display = mRootActivityContainer.getDefaultDisplay();
ActivityStack recentsStack = display.createStack(WINDOWING_MODE_FULLSCREEN,
ACTIVITY_TYPE_RECENTS, true /* onTop */);
ActivityRecord recentActivity = new ActivityBuilder(mService)
@@ -116,11 +116,11 @@ public class RecentsAnimationTest extends ActivityTestsBase {
@Test
public void testPreloadRecentsActivity() {
- final ActivityDisplay defaultDisplay = mRootActivityContainer.getDefaultDisplay();
+ final DisplayContent defaultDisplay = mRootActivityContainer.getDefaultDisplay();
final ActivityStack homeStack =
defaultDisplay.getStack(WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME);
defaultDisplay.positionStackAtTop(homeStack, false /* includingParents */);
- ActivityRecord topRunningHomeActivity = homeStack.topRunningActivityLocked();
+ ActivityRecord topRunningHomeActivity = homeStack.topRunningActivity();
if (topRunningHomeActivity == null) {
topRunningHomeActivity = new ActivityBuilder(mService)
.setStack(homeStack)
@@ -149,7 +149,7 @@ public class RecentsAnimationTest extends ActivityTestsBase {
mService.startRecentsActivity(recentsIntent, null /* assistDataReceiver */,
null /* recentsAnimationRunner */);
- ActivityDisplay display = mRootActivityContainer.getDefaultDisplay();
+ DisplayContent display = mRootActivityContainer.getDefaultDisplay();
ActivityStack recentsStack = display.getStack(WINDOWING_MODE_FULLSCREEN,
ACTIVITY_TYPE_RECENTS);
assertThat(recentsStack).isNotNull();
@@ -178,7 +178,7 @@ public class RecentsAnimationTest extends ActivityTestsBase {
@Test
public void testRestartRecentsActivity() throws Exception {
// Have a recents activity that is not attached to its process (ActivityRecord.app = null).
- ActivityDisplay display = mRootActivityContainer.getDefaultDisplay();
+ DisplayContent display = mRootActivityContainer.getDefaultDisplay();
ActivityStack recentsStack = display.createStack(WINDOWING_MODE_FULLSCREEN,
ACTIVITY_TYPE_RECENTS, true /* onTop */);
ActivityRecord recentActivity = new ActivityBuilder(mService).setComponent(
@@ -207,7 +207,7 @@ public class RecentsAnimationTest extends ActivityTestsBase {
@Test
public void testSetLaunchTaskBehindOfTargetActivity() {
- ActivityDisplay display = mRootActivityContainer.getDefaultDisplay();
+ DisplayContent display = mRootActivityContainer.getDefaultDisplay();
display.mDisplayContent.mBoundsAnimationController = mock(BoundsAnimationController.class);
ActivityStack homeStack = display.getHomeStack();
// Assume the home activity support recents.
@@ -253,7 +253,7 @@ public class RecentsAnimationTest extends ActivityTestsBase {
@Test
public void testCancelAnimationOnVisibleStackOrderChange() {
- ActivityDisplay display = mService.mRootActivityContainer.getDefaultDisplay();
+ DisplayContent display = mService.mRootActivityContainer.getDefaultDisplay();
display.mDisplayContent.mBoundsAnimationController = mock(BoundsAnimationController.class);
ActivityStack fullscreenStack = display.createStack(WINDOWING_MODE_FULLSCREEN,
ACTIVITY_TYPE_STANDARD, true /* onTop */);
@@ -299,7 +299,7 @@ public class RecentsAnimationTest extends ActivityTestsBase {
@Test
public void testKeepAnimationOnHiddenStackOrderChange() {
- ActivityDisplay display = mService.mRootActivityContainer.getDefaultDisplay();
+ DisplayContent display = mService.mRootActivityContainer.getDefaultDisplay();
ActivityStack fullscreenStack = display.createStack(WINDOWING_MODE_FULLSCREEN,
ACTIVITY_TYPE_STANDARD, true /* onTop */);
new ActivityBuilder(mService)
@@ -335,7 +335,7 @@ public class RecentsAnimationTest extends ActivityTestsBase {
@Test
public void testMultipleUserHomeActivity_findUserHomeTask() {
- ActivityDisplay display = mService.mRootActivityContainer.getDefaultDisplay();
+ DisplayContent display = mService.mRootActivityContainer.getDefaultDisplay();
ActivityStack homeStack = display.getStack(WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_HOME);
ActivityRecord otherUserHomeActivity = new ActivityBuilder(mService)
.setStack(homeStack)
diff --git a/services/tests/wmtests/src/com/android/server/wm/RootActivityContainerTests.java b/services/tests/wmtests/src/com/android/server/wm/RootActivityContainerTests.java
index 59c7c021d71e..2d45a59d3fc5 100644
--- a/services/tests/wmtests/src/com/android/server/wm/RootActivityContainerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RootActivityContainerTests.java
@@ -128,7 +128,7 @@ public class RootActivityContainerTests extends ActivityTestsBase {
mRootActivityContainer.moveActivityToPinnedStack(firstActivity, sourceBounds,
0f /*aspectRatio*/, "initialMove");
- final ActivityDisplay display = mFullscreenStack.getDisplay();
+ final DisplayContent display = mFullscreenStack.getDisplay();
ActivityStack pinnedStack = display.getPinnedStack();
// Ensure a task has moved over.
ensureStackPlacement(pinnedStack, firstActivity);
@@ -147,7 +147,7 @@ public class RootActivityContainerTests extends ActivityTestsBase {
}
private static void ensureStackPlacement(ActivityStack stack, ActivityRecord... activities) {
- final Task task = stack.getAllTasks().get(0);
+ final Task task = stack.getBottomMostTask();
final ArrayList<ActivityRecord> stackActivities = new ArrayList<>();
task.forAllActivities((Consumer<ActivityRecord>) stackActivities::add, false);
@@ -166,7 +166,7 @@ public class RootActivityContainerTests extends ActivityTestsBase {
@Test
public void testApplySleepTokens() {
- final ActivityDisplay display = mRootActivityContainer.getDefaultDisplay();
+ final DisplayContent display = mRootActivityContainer.getDefaultDisplay();
final KeyguardController keyguard = mSupervisor.getKeyguardController();
final ActivityStack stack = new StackBuilder(mRootActivityContainer)
.setCreateActivity(false)
@@ -202,7 +202,7 @@ public class RootActivityContainerTests extends ActivityTestsBase {
false /* expectResumeTopActivity */);
}
- private void verifySleepTokenBehavior(ActivityDisplay display, KeyguardController keyguard,
+ private void verifySleepTokenBehavior(DisplayContent display, KeyguardController keyguard,
ActivityStack stack, boolean displaySleeping, boolean displayShouldSleep,
boolean isFocusedStack, boolean keyguardShowing, boolean expectWakeFromSleep,
boolean expectResumeTopActivity) {
@@ -225,7 +225,7 @@ public class RootActivityContainerTests extends ActivityTestsBase {
*/
@Test
public void testRemovingStackOnAppCrash() {
- final ActivityDisplay defaultDisplay = mRootActivityContainer.getDefaultDisplay();
+ final DisplayContent defaultDisplay = mRootActivityContainer.getDefaultDisplay();
final int originalStackCount = defaultDisplay.getStackCount();
final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().createStack(
WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, false /* onTop */);
@@ -320,7 +320,7 @@ public class RootActivityContainerTests extends ActivityTestsBase {
.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY)
.setOnTop(true)
.build();
- final Task task = primaryStack.topTask();
+ final Task task = primaryStack.getTopMostTask();
// Resize dock stack.
mService.resizeDockedStack(stackSize, taskSize, null, null, null);
@@ -336,11 +336,11 @@ public class RootActivityContainerTests extends ActivityTestsBase {
@Test
public void testFindTaskToMoveToFrontWhenRecentsOnTop() {
// Create stack/task on default display.
- final ActivityDisplay display = mRootActivityContainer.getDefaultDisplay();
+ final DisplayContent display = mRootActivityContainer.getDefaultDisplay();
final ActivityStack targetStack = new StackBuilder(mRootActivityContainer)
.setOnTop(false)
.build();
- final Task targetTask = targetStack.getChildAt(0);
+ final Task targetTask = targetStack.getBottomMostTask();
// Create Recents on top of the display.
final ActivityStack stack = new StackBuilder(mRootActivityContainer).setActivityType(
@@ -360,14 +360,14 @@ public class RootActivityContainerTests extends ActivityTestsBase {
@Test
public void testFindTaskToMoveToFrontWhenRecentsOnOtherDisplay() {
// Create stack/task on default display.
- final ActivityDisplay display = mRootActivityContainer.getDefaultDisplay();
+ final DisplayContent display = mRootActivityContainer.getDefaultDisplay();
final ActivityStack targetStack = display.createStack(WINDOWING_MODE_FULLSCREEN,
ACTIVITY_TYPE_STANDARD, false /* onTop */);
final Task targetTask = new TaskBuilder(mSupervisor).setStack(targetStack).build();
// Create Recents on secondary display.
- final TestActivityDisplay secondDisplay = addNewActivityDisplayAt(
- ActivityDisplay.POSITION_TOP);
+ final TestDisplayContent secondDisplay = addNewDisplayContentAt(
+ DisplayContent.POSITION_TOP);
final ActivityStack stack = secondDisplay.createStack(WINDOWING_MODE_FULLSCREEN,
ACTIVITY_TYPE_RECENTS, true /* onTop */);
final Task task = new TaskBuilder(mSupervisor).setStack(stack).build();
@@ -387,7 +387,7 @@ public class RootActivityContainerTests extends ActivityTestsBase {
@Test
public void testResumeActivityWhenNonTopmostStackIsTopFocused() {
// Create a stack at bottom.
- final ActivityDisplay display = mRootActivityContainer.getDefaultDisplay();
+ final DisplayContent display = mRootActivityContainer.getDefaultDisplay();
final ActivityStack targetStack = spy(display.createStack(WINDOWING_MODE_FULLSCREEN,
ACTIVITY_TYPE_STANDARD, false /* onTop */));
final Task task = new TaskBuilder(mSupervisor).setStack(targetStack).build();
@@ -415,8 +415,9 @@ public class RootActivityContainerTests extends ActivityTestsBase {
@Test
public void testResumeFocusedStacksStartsHomeActivity_NoActivities() {
mFullscreenStack.removeIfPossible();
- mService.mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY).getHomeStack().removeIfPossible();
- mService.mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY)
+ mService.mRootActivityContainer.getDisplayContent(DEFAULT_DISPLAY).getHomeStack()
+ .removeIfPossible();
+ mService.mRootActivityContainer.getDisplayContent(DEFAULT_DISPLAY)
.createStack(WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, ON_TOP);
doReturn(true).when(mRootActivityContainer).resumeHomeActivity(any(), any(), anyInt());
@@ -437,13 +438,14 @@ public class RootActivityContainerTests extends ActivityTestsBase {
@Test
public void testResumeFocusedStacksStartsHomeActivity_ActivityOnSecondaryScreen() {
mFullscreenStack.removeIfPossible();
- mService.mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY).getHomeStack().removeIfPossible();
- mService.mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY)
+ mService.mRootActivityContainer.getDisplayContent(DEFAULT_DISPLAY).getHomeStack()
+ .removeIfPossible();
+ mService.mRootActivityContainer.getDisplayContent(DEFAULT_DISPLAY)
.createStack(WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, ON_TOP);
// Create an activity on secondary display.
- final TestActivityDisplay secondDisplay = addNewActivityDisplayAt(
- ActivityDisplay.POSITION_TOP);
+ final TestDisplayContent secondDisplay = addNewDisplayContentAt(
+ DisplayContent.POSITION_TOP);
final ActivityStack stack = secondDisplay.createStack(WINDOWING_MODE_FULLSCREEN,
ACTIVITY_TYPE_STANDARD, true /* onTop */);
final Task task = new TaskBuilder(mSupervisor).setStack(stack).build();
@@ -467,7 +469,7 @@ public class RootActivityContainerTests extends ActivityTestsBase {
@Test
public void testResumeActivityLingeringTransition() {
// Create a stack at top.
- final ActivityDisplay display = mRootActivityContainer.getDefaultDisplay();
+ final DisplayContent display = mRootActivityContainer.getDefaultDisplay();
final ActivityStack targetStack = spy(display.createStack(WINDOWING_MODE_FULLSCREEN,
ACTIVITY_TYPE_STANDARD, false /* onTop */));
final Task task = new TaskBuilder(mSupervisor).setStack(targetStack).build();
@@ -487,7 +489,7 @@ public class RootActivityContainerTests extends ActivityTestsBase {
@Test
public void testResumeActivityLingeringTransition_notExecuted() {
// Create a stack at bottom.
- final ActivityDisplay display = mRootActivityContainer.getDefaultDisplay();
+ final DisplayContent display = mRootActivityContainer.getDefaultDisplay();
final ActivityStack targetStack = spy(display.createStack(WINDOWING_MODE_FULLSCREEN,
ACTIVITY_TYPE_STANDARD, false /* onTop */));
final Task task = new TaskBuilder(mSupervisor).setStack(targetStack).build();
@@ -515,8 +517,8 @@ public class RootActivityContainerTests extends ActivityTestsBase {
mockResolveSecondaryHomeActivity();
// Create secondary displays.
- final TestActivityDisplay secondDisplay =
- new TestActivityDisplay.Builder(mService, 1000, 1500)
+ final TestDisplayContent secondDisplay =
+ new TestDisplayContent.Builder(mService, 1000, 1500)
.setSystemDecorations(true).build();
doReturn(true).when(mRootActivityContainer)
@@ -582,8 +584,8 @@ public class RootActivityContainerTests extends ActivityTestsBase {
@Test
public void testStartSecondaryHomeOnDisplayWithUserKeyLocked() {
// Create secondary displays.
- final TestActivityDisplay secondDisplay =
- new TestActivityDisplay.Builder(mService, 1000, 1500)
+ final TestDisplayContent secondDisplay =
+ new TestDisplayContent.Builder(mService, 1000, 1500)
.setSystemDecorations(true).build();
// Use invalid user id to let StorageManager.isUserKeyUnlocked() return false.
@@ -608,8 +610,8 @@ public class RootActivityContainerTests extends ActivityTestsBase {
@Test
public void testStartSecondaryHomeOnDisplayWithoutSysDecorations() {
// Create secondary displays.
- final TestActivityDisplay secondDisplay =
- new TestActivityDisplay.Builder(mService, 1000, 1500)
+ final TestDisplayContent secondDisplay =
+ new TestDisplayContent.Builder(mService, 1000, 1500)
.setSystemDecorations(false).build();
mRootActivityContainer.startHomeOnDisplay(0 /* userId */, "testStartSecondaryHome",
@@ -831,8 +833,8 @@ public class RootActivityContainerTests extends ActivityTestsBase {
@Test
public void testGetLaunchStackWithRealCallerId() {
// Create a non-system owned virtual display.
- final TestActivityDisplay secondaryDisplay =
- new TestActivityDisplay.Builder(mService, 1000, 1500)
+ final TestDisplayContent secondaryDisplay =
+ new TestDisplayContent.Builder(mService, 1000, 1500)
.setType(TYPE_VIRTUAL).setOwnerUid(100).build();
// Create an activity with specify the original launch pid / uid.
diff --git a/services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java b/services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java
index 5c9ccae8b7d1..b32cb8b5e637 100644
--- a/services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java
@@ -57,9 +57,9 @@ public class RunningTasksTest extends ActivityTestsBase {
@Test
public void testCollectTasksByLastActiveTime() {
// Create a number of stacks with tasks (of incrementing active time)
- final ArrayList<ActivityDisplay> displays = new ArrayList<>();
- final ActivityDisplay display =
- new TestActivityDisplay.Builder(mService, 1000, 2500).build();
+ final ArrayList<DisplayContent> displays = new ArrayList<>();
+ final DisplayContent display =
+ new TestDisplayContent.Builder(mService, 1000, 2500).build();
displays.add(display);
final int numStacks = 2;
@@ -82,8 +82,8 @@ public class RunningTasksTest extends ActivityTestsBase {
final int numFetchTasks = 5;
ArrayList<RunningTaskInfo> tasks = new ArrayList<>();
mRunningTasks.getTasks(5, tasks, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED,
- displays, -1 /* callingUid */, true /* allowed */, true /*crossUser */,
- PROFILE_IDS);
+ mRootActivityContainer, -1 /* callingUid */, true /* allowed */,
+ true /*crossUser */, PROFILE_IDS);
assertThat(tasks).hasSize(numFetchTasks);
for (int i = 0; i < numFetchTasks; i++) {
assertEquals(numTasks - i - 1, tasks.get(i).id);
@@ -93,8 +93,8 @@ public class RunningTasksTest extends ActivityTestsBase {
// and does not crash
tasks.clear();
mRunningTasks.getTasks(100, tasks, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED,
- displays, -1 /* callingUid */, true /* allowed */, true /* crossUser */,
- PROFILE_IDS);
+ mRootActivityContainer, -1 /* callingUid */, true /* allowed */,
+ true /* crossUser */, PROFILE_IDS);
assertThat(tasks).hasSize(numTasks);
for (int i = 0; i < numTasks; i++) {
assertEquals(numTasks - i - 1, tasks.get(i).id);
diff --git a/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java b/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
index 212931b76b88..be0fd2b26f7c 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
@@ -16,7 +16,6 @@
package com.android.server.wm;
-import static android.content.pm.ActivityInfo.CONFIG_ORIENTATION;
import static android.content.pm.ActivityInfo.RESIZE_MODE_UNRESIZEABLE;
import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
@@ -27,7 +26,7 @@ import static android.view.Surface.ROTATION_90;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.doNothing;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.eq;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock;
-import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.never;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;
import static com.android.server.wm.ActivityStack.ActivityState.STOPPED;
@@ -36,7 +35,6 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.when;
import android.app.ActivityManager;
import android.app.ActivityManagerInternal;
@@ -54,7 +52,6 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.ArrayList;
-import java.util.concurrent.TimeUnit;
/**
* Tests for Size Compatibility mode.
@@ -70,9 +67,9 @@ public class SizeCompatTests extends ActivityTestsBase {
private Task mTask;
private ActivityRecord mActivity;
- private void setUpApp(ActivityDisplay display) {
+ private void setUpApp(DisplayContent display) {
mStack = new StackBuilder(mRootActivityContainer).setDisplay(display).build();
- mTask = mStack.getChildAt(0);
+ mTask = mStack.getBottomMostTask();
mActivity = mTask.getTopNonFinishingActivity();
}
@@ -82,7 +79,7 @@ public class SizeCompatTests extends ActivityTestsBase {
@Test
public void testRestartProcessIfVisible() {
- setUpApp(new TestActivityDisplay.Builder(mService, 1000, 2500).build());
+ setUpApp(new TestDisplayContent.Builder(mService, 1000, 2500).build());
doNothing().when(mSupervisor).scheduleRestartTimeout(mActivity);
mActivity.mVisibleRequested = true;
mActivity.setSavedState(null /* savedState */);
@@ -102,7 +99,7 @@ public class SizeCompatTests extends ActivityTestsBase {
public void testKeepBoundsWhenChangingFromFreeformToFullscreen() {
removeGlobalMinSizeRestriction();
// create freeform display and a freeform app
- ActivityDisplay display = new TestActivityDisplay.Builder(mService, 2000, 1000)
+ DisplayContent display = new TestDisplayContent.Builder(mService, 2000, 1000)
.setCanRotate(false)
.setWindowingMode(WindowConfiguration.WINDOWING_MODE_FREEFORM).build();
setUpApp(display);
@@ -129,7 +126,7 @@ public class SizeCompatTests extends ActivityTestsBase {
@Test
public void testFixedAspectRatioBoundsWithDecor() {
final int decorHeight = 200; // e.g. The device has cutout.
- setUpApp(new TestActivityDisplay.Builder(mService, 600, 800)
+ setUpApp(new TestDisplayContent.Builder(mService, 600, 800)
.setNotch(decorHeight).build());
mActivity.info.minAspectRatio = mActivity.info.maxAspectRatio = 1;
@@ -155,11 +152,11 @@ public class SizeCompatTests extends ActivityTestsBase {
@Test
public void testFixedScreenConfigurationWhenMovingToDisplay() {
- setUpApp(new TestActivityDisplay.Builder(mService, 1000, 2500).build());
+ setUpApp(new TestDisplayContent.Builder(mService, 1000, 2500).build());
// Make a new less-tall display with lower density
- final ActivityDisplay newDisplay =
- new TestActivityDisplay.Builder(mService, 1000, 2000)
+ final DisplayContent newDisplay =
+ new TestDisplayContent.Builder(mService, 1000, 2000)
.setDensityDpi(200).build();
mActivity = new ActivityBuilder(mService)
@@ -183,7 +180,7 @@ public class SizeCompatTests extends ActivityTestsBase {
@Test
public void testFixedScreenBoundsWhenDisplaySizeChanged() {
- setUpApp(new TestActivityDisplay.Builder(mService, 1000, 2500).build());
+ setUpApp(new TestDisplayContent.Builder(mService, 1000, 2500).build());
prepareUnresizable(-1f /* maxAspect */, SCREEN_ORIENTATION_PORTRAIT);
assertFalse(mActivity.inSizeCompatMode());
@@ -206,7 +203,7 @@ public class SizeCompatTests extends ActivityTestsBase {
@Test
public void testLetterboxFullscreenBounds() {
- setUpApp(new TestActivityDisplay.Builder(mService, 1000, 2500).build());
+ setUpApp(new TestDisplayContent.Builder(mService, 1000, 2500).build());
// Fill out required fields on default display since WM-side is mocked out
prepareUnresizable(-1.f /* maxAspect */, SCREEN_ORIENTATION_LANDSCAPE);
@@ -216,10 +213,10 @@ public class SizeCompatTests extends ActivityTestsBase {
@Test
public void testMoveToDifferentOrientDisplay() {
- setUpApp(new TestActivityDisplay.Builder(mService, 1000, 2500).build());
+ setUpApp(new TestDisplayContent.Builder(mService, 1000, 2500).build());
- final ActivityDisplay newDisplay =
- new TestActivityDisplay.Builder(mService, 2000, 1000)
+ final DisplayContent newDisplay =
+ new TestDisplayContent.Builder(mService, 2000, 1000)
.setCanRotate(false).build();
prepareUnresizable(-1.f /* maxAspect */, SCREEN_ORIENTATION_PORTRAIT);
@@ -238,7 +235,7 @@ public class SizeCompatTests extends ActivityTestsBase {
@Test
public void testFixedOrientRotateCutoutDisplay() {
// Create a display with a notch/cutout
- setUpApp(new TestActivityDisplay.Builder(mService, 1000, 2500).setNotch(60).build());
+ setUpApp(new TestDisplayContent.Builder(mService, 1000, 2500).setNotch(60).build());
prepareUnresizable(1.4f /* maxAspect */, SCREEN_ORIENTATION_PORTRAIT);
final Rect origBounds = new Rect(mActivity.getBounds());
@@ -262,10 +259,11 @@ public class SizeCompatTests extends ActivityTestsBase {
@Test
public void testFixedAspOrientChangeOrient() {
- setUpApp(new TestActivityDisplay.Builder(mService, 1000, 2500).build());
+ setUpApp(new TestDisplayContent.Builder(mService, 1000, 2500).build());
prepareUnresizable(1.4f /* maxAspect */, SCREEN_ORIENTATION_LANDSCAPE);
- assertTrue(mActivity.inSizeCompatMode());
+ // The display aspect ratio 2.5 > 1.4 (max of activity), so the size is fitted.
+ assertFalse(mActivity.inSizeCompatMode());
final Rect originalBounds = new Rect(mActivity.getBounds());
final Rect originalAppBounds = new Rect(mActivity.getWindowConfiguration().getAppBounds());
@@ -288,7 +286,7 @@ public class SizeCompatTests extends ActivityTestsBase {
@Test
public void testFixedScreenLayoutSizeBits() {
- setUpApp(new TestActivityDisplay.Builder(mService, 1000, 2500).build());
+ setUpApp(new TestDisplayContent.Builder(mService, 1000, 2500).build());
final int fixedScreenLayout = Configuration.SCREENLAYOUT_LONG_NO
| Configuration.SCREENLAYOUT_SIZE_NORMAL
| Configuration.SCREENLAYOUT_COMPAT_NEEDED;
@@ -316,38 +314,36 @@ public class SizeCompatTests extends ActivityTestsBase {
@Test
public void testResetNonVisibleActivity() {
- setUpApp(new TestActivityDisplay.Builder(mService, 1000, 2500).build());
- final ActivityDisplay display = mStack.getDisplay();
- spyOn(display);
-
+ setUpApp(new TestDisplayContent.Builder(mService, 1000, 2500).build());
prepareUnresizable(1.5f, SCREEN_ORIENTATION_UNSPECIFIED);
+ final DisplayContent display = mStack.getDisplay();
+ // Resize the display so the activity is in size compatibility mode.
+ resizeDisplay(display, 900, 1800);
+
mActivity.setState(STOPPED, "testSizeCompatMode");
mActivity.mVisibleRequested = false;
mActivity.app.setReportedProcState(ActivityManager.PROCESS_STATE_CACHED_ACTIVITY);
- // Make the parent bounds to be different so the activity is in size compatibility mode.
- mTask.getWindowConfiguration().setAppBounds(new Rect(0, 0, 600, 1200));
// Simulate the display changes orientation.
- when(display.getLastOverrideConfigurationChanges()).thenReturn(
- ActivityInfo.CONFIG_SCREEN_SIZE | CONFIG_ORIENTATION
- | ActivityInfo.CONFIG_WINDOW_CONFIGURATION);
- mActivity.onConfigurationChanged(mTask.getConfiguration());
- when(display.getLastOverrideConfigurationChanges()).thenCallRealMethod();
- // The override configuration should not change so it is still in size compatibility mode.
+ final Configuration c = new Configuration();
+ display.getDisplayRotation().setRotation(ROTATION_90);
+ display.computeScreenConfiguration(c);
+ display.onRequestedOverrideConfigurationChanged(c);
+ // Size compatibility mode is able to handle orientation change so the process shouldn't be
+ // restarted and the override configuration won't be cleared.
+ verify(mActivity, never()).restartProcessIfVisible();
assertTrue(mActivity.inSizeCompatMode());
// Change display density
- final DisplayContent displayContent = mStack.getDisplay().mDisplayContent;
- displayContent.mBaseDisplayDensity = (int) (0.7f * displayContent.mBaseDisplayDensity);
- final Configuration c = new Configuration();
- displayContent.computeScreenConfiguration(c);
+ display.mBaseDisplayDensity = (int) (0.7f * display.mBaseDisplayDensity);
+ display.computeScreenConfiguration(c);
mService.mAmInternal = mock(ActivityManagerInternal.class);
- mStack.getDisplay().onRequestedOverrideConfigurationChanged(c);
+ display.onRequestedOverrideConfigurationChanged(c);
// The override configuration should be reset and the activity's process will be killed.
assertFalse(mActivity.inSizeCompatMode());
verify(mActivity).restartProcessIfVisible();
- mLockRule.runWithScissors(mService.mH, () -> { }, TimeUnit.SECONDS.toMillis(3));
+ waitHandlerIdle(mService.mH);
verify(mService.mAmInternal).killProcess(
eq(mActivity.app.mName), eq(mActivity.app.mUid), anyString());
}
@@ -358,11 +354,10 @@ public class SizeCompatTests extends ActivityTestsBase {
*/
@Test
public void testHandleActivitySizeCompatMode() {
- setUpApp(new TestActivityDisplay.Builder(mService, 1000, 2000).build());
+ setUpApp(new TestDisplayContent.Builder(mService, 1000, 2000).build());
ActivityRecord activity = mActivity;
activity.setState(ActivityStack.ActivityState.RESUMED, "testHandleActivitySizeCompatMode");
prepareUnresizable(-1.f /* maxAspect */, SCREEN_ORIENTATION_PORTRAIT);
- ensureActivityConfiguration();
assertFalse(mActivity.inSizeCompatMode());
final ArrayList<IBinder> compatTokens = new ArrayList<>();
@@ -417,7 +412,7 @@ public class SizeCompatTests extends ActivityTestsBase {
ensureActivityConfiguration();
}
- private void resizeDisplay(ActivityDisplay display, int width, int height) {
+ private void resizeDisplay(DisplayContent display, int width, int height) {
final DisplayContent displayContent = display.mDisplayContent;
displayContent.mBaseDisplayWidth = width;
displayContent.mBaseDisplayHeight = height;
diff --git a/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimationRunnerTest.java b/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimationRunnerTest.java
index 3008a75740e8..e0112809b22b 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimationRunnerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimationRunnerTest.java
@@ -88,6 +88,7 @@ public class SurfaceAnimationRunnerTest extends WindowTestsBase {
mFinishCallbackLatch.countDown();
}
+ @FlakyTest(bugId = 144611135)
@Test
public void testAnimation() throws Exception {
mSurfaceAnimationRunner
diff --git a/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java b/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java
index d3b68e02cbf8..811f46f9112a 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java
@@ -286,9 +286,12 @@ public class SystemServicesTestRule implements TestRule {
// Mock root, some default display, and home stack.
spyOn(mWmService.mRoot);
- final ActivityDisplay display = mAtmService.mRootActivityContainer.getDefaultDisplay();
+ final DisplayContent display = mAtmService.mRootActivityContainer.getDefaultDisplay();
+ // Set default display to be in fullscreen mode. Devices with PC feature may start their
+ // default display in freeform mode but some of tests in WmTests have implicit assumption on
+ // that the default display is in fullscreen mode.
+ display.setDisplayWindowingMode(WINDOWING_MODE_FULLSCREEN);
spyOn(display);
- spyOn(display.mDisplayContent);
final ActivityStack homeStack = display.getStack(
WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME);
spyOn(homeStack);
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java
index 9a91efe0be62..5aa41eb2b856 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java
@@ -107,7 +107,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
// =============================
@Test
public void testDefaultToPrimaryDisplay() {
- createNewActivityDisplay(WINDOWING_MODE_FREEFORM);
+ createNewDisplayContent(WINDOWING_MODE_FREEFORM);
assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, /* layout */ null,
mActivity, /* source */ null, /* options */ null, mCurrent, mResult));
@@ -127,8 +127,8 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testUsesPreviousDisplayIdIfSet() {
- createNewActivityDisplay(WINDOWING_MODE_FREEFORM);
- final TestActivityDisplay display = createNewActivityDisplay(WINDOWING_MODE_FULLSCREEN);
+ createNewDisplayContent(WINDOWING_MODE_FREEFORM);
+ final TestDisplayContent display = createNewDisplayContent(WINDOWING_MODE_FULLSCREEN);
mCurrent.mPreferredDisplayId = display.mDisplayId;
@@ -140,9 +140,9 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testUsesSourcesDisplayIdIfSet() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
- final TestActivityDisplay fullscreenDisplay = createNewActivityDisplay(
+ final TestDisplayContent fullscreenDisplay = createNewDisplayContent(
WINDOWING_MODE_FULLSCREEN);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -157,9 +157,9 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testUsesOptionsDisplayIdIfSet() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
- final TestActivityDisplay fullscreenDisplay = createNewActivityDisplay(
+ final TestDisplayContent fullscreenDisplay = createNewDisplayContent(
WINDOWING_MODE_FULLSCREEN);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -176,9 +176,9 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testUsesTasksDisplayIdPriorToSourceIfSet() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
- final TestActivityDisplay fullscreenDisplay = createNewActivityDisplay(
+ final TestDisplayContent fullscreenDisplay = createNewDisplayContent(
WINDOWING_MODE_FULLSCREEN);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -193,7 +193,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testUsesTaskDisplayIdIfSet() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
ActivityRecord source = createSourceActivity(freeformDisplay);
@@ -205,9 +205,9 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testUsesNoDisplaySourceHandoverDisplayIdIfSet() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
- final TestActivityDisplay fullscreenDisplay = createNewActivityDisplay(
+ final TestDisplayContent fullscreenDisplay = createNewDisplayContent(
WINDOWING_MODE_FULLSCREEN);
mCurrent.mPreferredDisplayId = fullscreenDisplay.mDisplayId;
@@ -227,7 +227,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
// =====================================
@Test
public void testBoundsInOptionsInfersFreeformOnFreeformDisplay() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
final ActivityOptions options = ActivityOptions.makeBasic();
@@ -258,7 +258,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testInheritsFreeformModeFromSourceOnFullscreenDisplay() {
- final TestActivityDisplay fullscreenDisplay = createNewActivityDisplay(
+ final TestDisplayContent fullscreenDisplay = createNewDisplayContent(
WINDOWING_MODE_FULLSCREEN);
final ActivityRecord source = createSourceActivity(fullscreenDisplay);
source.setWindowingMode(WINDOWING_MODE_FREEFORM);
@@ -272,7 +272,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testKeepsPictureInPictureLaunchModeInOptions() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
final ActivityOptions options = ActivityOptions.makeBasic();
@@ -289,7 +289,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testKeepsPictureInPictureLaunchModeWithBoundsInOptions() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
final ActivityOptions options = ActivityOptions.makeBasic();
@@ -321,7 +321,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testNonEmptyLayoutInfersFreeformOnFreeformDisplay() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -338,7 +338,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testNonEmptyLayoutInfersFreeformWithEmptySize() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -382,7 +382,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testRespectsFullyResolvedCurrentParam_Fullscreen() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -397,7 +397,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testRespectsModeFromFullyResolvedCurrentParam_NonEmptyBounds() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -414,7 +414,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testForceMaximizesUnresizeableApp() {
mService.mSizeCompatFreeform = false;
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
final ActivityOptions options = ActivityOptions.makeBasic();
@@ -437,7 +437,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testLaunchesAppInWindowOnFreeformDisplay() {
mService.mSizeCompatFreeform = true;
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
Rect expectedLaunchBounds = new Rect(0, 0, 200, 100);
@@ -494,7 +494,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testUsesFullscreenWhenRequestedOnFreeformDisplay() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
final ActivityOptions options = ActivityOptions.makeBasic();
@@ -510,7 +510,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testUsesFreeformByDefaultForPostNApp() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
final ActivityOptions options = ActivityOptions.makeBasic();
@@ -525,7 +525,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testUsesFreeformByDefaultForPreNResizeableAppWithoutOrientationRequest() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
final ActivityOptions options = ActivityOptions.makeBasic();
@@ -559,7 +559,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
// ===============================
@Test
public void testKeepsBoundsWithPictureInPictureLaunchModeInOptions() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
final ActivityOptions options = ActivityOptions.makeBasic();
@@ -578,7 +578,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testRespectsLaunchBoundsWithFreeformSourceOnFullscreenDisplay() {
- final TestActivityDisplay fullscreenDisplay = createNewActivityDisplay(
+ final TestDisplayContent fullscreenDisplay = createNewDisplayContent(
WINDOWING_MODE_FULLSCREEN);
final ActivityRecord source = createSourceActivity(fullscreenDisplay);
source.setWindowingMode(WINDOWING_MODE_FREEFORM);
@@ -595,7 +595,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testNonEmptyLayoutBoundsRespectsGravityWithEmptySize_LeftGravity() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -611,7 +611,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testNonEmptyLayoutBoundsRespectsGravityWithEmptySize_TopGravity() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -627,7 +627,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testNonEmptyLayoutBoundsRespectsGravityWithEmptySize_TopLeftGravity() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -644,7 +644,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testNonEmptyLayoutBoundsRespectsGravityWithEmptySize_RightGravity() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -660,7 +660,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testNonEmptyLayoutBoundsRespectsGravityWithEmptySize_BottomGravity() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -676,7 +676,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testNonEmptyLayoutBoundsRespectsGravityWithEmptySize_BottomRightGravity() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -693,7 +693,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testNonEmptyLayoutBoundsOnFreeformDisplay_CenterToDisplay() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -709,7 +709,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testNonEmptyLayoutBoundsOnFreeformDisplay_LeftGravity() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -725,7 +725,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testNonEmptyLayoutBoundsOnFreeformDisplay_TopGravity() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -741,7 +741,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testNonEmptyLayoutBoundsOnFreeformDisplay_TopLeftGravity() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -757,7 +757,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testNonEmptyLayoutBoundsOnFreeformDisplay_RightGravity() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -773,7 +773,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testNonEmptyLayoutBoundsOnFreeformDisplay_BottomGravity() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -789,7 +789,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testNonEmptyLayoutBoundsOnFreeformDisplay_RightBottomGravity() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -805,7 +805,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testNonEmptyLayoutFractionBoundsOnFreeformDisplay() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -821,7 +821,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testRespectBoundsFromFullyResolvedCurrentParam_NonEmptyBounds() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -836,7 +836,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testReturnBoundsForFullscreenWindowingMode() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
@@ -851,7 +851,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testUsesDisplayOrientationForNoSensorOrientation() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
final ActivityOptions options = ActivityOptions.makeBasic();
@@ -875,7 +875,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testRespectsAppRequestedOrientation_Landscape() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
final ActivityOptions options = ActivityOptions.makeBasic();
@@ -892,7 +892,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testRespectsAppRequestedOrientation_Portrait() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
final ActivityOptions options = ActivityOptions.makeBasic();
@@ -909,7 +909,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testDefaultSizeSmallerThanBigScreen() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
final ActivityOptions options = ActivityOptions.makeBasic();
@@ -933,7 +933,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testDefaultFreeformSizeCenteredToDisplay() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
final ActivityOptions options = ActivityOptions.makeBasic();
@@ -954,7 +954,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testCascadesToSourceSizeForFreeform() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
final ActivityOptions options = ActivityOptions.makeBasic();
@@ -981,7 +981,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testAdjustBoundsToFitDisplay_TopLeftOutOfDisplay() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
final ActivityOptions options = ActivityOptions.makeBasic();
@@ -1003,7 +1003,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testAdjustBoundsToFitDisplay_BottomRightOutOfDisplay() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
final ActivityOptions options = ActivityOptions.makeBasic();
@@ -1025,7 +1025,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testAdjustBoundsToFitNewDisplay_LargerThanDisplay() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
final ActivityOptions options = ActivityOptions.makeBasic();
@@ -1052,7 +1052,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
overrideConfig.setLayoutDirection(new Locale("ar", "EG"));
mRootActivityContainer.onRequestedOverrideConfigurationChanged(overrideConfig);
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
final ActivityOptions options = ActivityOptions.makeBasic();
@@ -1073,7 +1073,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testRespectsLayoutMinDimensions() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
// This test case requires a relatively big app bounds to ensure the default size calculated
@@ -1098,7 +1098,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testRotatesInPlaceInitialBoundsMismatchOrientation() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
final ActivityOptions options = ActivityOptions.makeBasic();
@@ -1115,7 +1115,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testShiftsToRightForCloseToLeftBoundsWhenConflict() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
addFreeformTaskTo(freeformDisplay, new Rect(50, 50, 100, 150));
@@ -1132,7 +1132,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testShiftsToLeftForCloseToRightBoundsWhenConflict() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
addFreeformTaskTo(freeformDisplay, new Rect(1720, 50, 1830, 150));
@@ -1149,7 +1149,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testShiftsToRightFirstForHorizontallyCenteredAndCloseToTopWhenConflict() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
addFreeformTaskTo(freeformDisplay, new Rect(0, 0, 100, 300));
@@ -1166,7 +1166,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testShiftsToLeftNoSpaceOnRightForHorizontallyCenteredAndCloseToTopWhenConflict() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
addFreeformTaskTo(freeformDisplay, new Rect(120, 0, 240, 300));
@@ -1183,7 +1183,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testShiftsToBottomRightFirstForCenteredBoundsWhenConflict() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
addFreeformTaskTo(freeformDisplay, new Rect(120, 0, 240, 100));
@@ -1200,7 +1200,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testShiftsToTopLeftIfNoSpaceOnBottomRightForCenteredBoundsWhenConflict() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
addFreeformTaskTo(freeformDisplay, new Rect(120, 67, 240, 100));
@@ -1230,7 +1230,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testAdjustsBoundsToFitInDisplayFullyResolvedBounds() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
mCurrent.mPreferredDisplayId = Display.INVALID_DISPLAY;
@@ -1248,7 +1248,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testAdjustsBoundsToAvoidConflictFullyResolvedBounds() {
- final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
+ final TestDisplayContent freeformDisplay = createNewDisplayContent(
WINDOWING_MODE_FREEFORM);
addFreeformTaskTo(freeformDisplay, new Rect(0, 0, 200, 100));
@@ -1283,7 +1283,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
@Test
public void testNoMultiDisplaySupports() {
final boolean orgValue = mService.mSupportsMultiDisplay;
- final TestActivityDisplay display = createNewActivityDisplay(WINDOWING_MODE_FULLSCREEN);
+ final TestDisplayContent display = createNewDisplayContent(WINDOWING_MODE_FULLSCREEN);
mCurrent.mPreferredDisplayId = display.mDisplayId;
try {
@@ -1296,8 +1296,8 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
}
}
- private TestActivityDisplay createNewActivityDisplay(int windowingMode) {
- final TestActivityDisplay display = addNewActivityDisplayAt(ActivityDisplay.POSITION_TOP);
+ private TestDisplayContent createNewDisplayContent(int windowingMode) {
+ final TestDisplayContent display = addNewDisplayContentAt(DisplayContent.POSITION_TOP);
display.setWindowingMode(windowingMode);
display.setBounds(DISPLAY_BOUNDS);
display.getConfiguration().densityDpi = DENSITY_DEFAULT;
@@ -1311,13 +1311,13 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
return display;
}
- private ActivityRecord createSourceActivity(TestActivityDisplay display) {
+ private ActivityRecord createSourceActivity(TestDisplayContent display) {
final ActivityStack stack = display.createStack(display.getWindowingMode(),
ACTIVITY_TYPE_STANDARD, true);
return new ActivityBuilder(mService).setStack(stack).setCreateTask(true).build();
}
- private void addFreeformTaskTo(TestActivityDisplay display, Rect bounds) {
+ private void addFreeformTaskTo(TestDisplayContent display, Rect bounds) {
final ActivityStack stack = display.createStack(display.getWindowingMode(),
ACTIVITY_TYPE_STANDARD, true);
stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java
index 599edb1465d0..1a18df5b6fcf 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java
@@ -193,7 +193,7 @@ public class TaskRecordTests extends ActivityTestsBase {
@FlakyTest(bugId = 137879065)
public void testFitWithinBounds() {
final Rect parentBounds = new Rect(10, 10, 200, 200);
- ActivityDisplay display = mService.mRootActivityContainer.getDefaultDisplay();
+ DisplayContent display = mService.mRootActivityContainer.getDefaultDisplay();
ActivityStack stack = display.createStack(WINDOWING_MODE_FREEFORM, ACTIVITY_TYPE_STANDARD,
true /* onTop */);
Task task = new TaskBuilder(mSupervisor).setStack(stack).build();
@@ -232,10 +232,10 @@ public class TaskRecordTests extends ActivityTestsBase {
@Test
@FlakyTest(bugId = 137879065)
public void testBoundsOnModeChangeFreeformToFullscreen() {
- ActivityDisplay display = mService.mRootActivityContainer.getDefaultDisplay();
+ DisplayContent display = mService.mRootActivityContainer.getDefaultDisplay();
ActivityStack stack = new StackBuilder(mRootActivityContainer).setDisplay(display)
.setWindowingMode(WINDOWING_MODE_FREEFORM).build();
- Task task = stack.getChildAt(0);
+ Task task = stack.getBottomMostTask();
task.getRootActivity().setOrientation(SCREEN_ORIENTATION_UNSPECIFIED);
DisplayInfo info = new DisplayInfo();
display.mDisplay.getDisplayInfo(info);
@@ -265,9 +265,9 @@ public class TaskRecordTests extends ActivityTestsBase {
public void testFullscreenBoundsForcedOrientation() {
final Rect fullScreenBounds = new Rect(0, 0, 1920, 1080);
final Rect fullScreenBoundsPort = new Rect(0, 0, 1080, 1920);
- ActivityDisplay display = new TestActivityDisplay.Builder(
+ DisplayContent display = new TestDisplayContent.Builder(
mService, fullScreenBounds.width(), fullScreenBounds.height()).build();
- assertTrue(mRootActivityContainer.getActivityDisplay(display.mDisplayId) != null);
+ assertTrue(mRootActivityContainer.getDisplayContent(display.mDisplayId) != null);
// Fix the display orientation to landscape which is the natural rotation (0) for the test
// display.
final DisplayRotation dr = display.mDisplayContent.getDisplayRotation();
@@ -276,7 +276,7 @@ public class TaskRecordTests extends ActivityTestsBase {
ActivityStack stack = new StackBuilder(mRootActivityContainer)
.setWindowingMode(WINDOWING_MODE_FULLSCREEN).setDisplay(display).build();
- Task task = stack.getChildAt(0);
+ Task task = stack.getBottomMostTask();
ActivityRecord root = task.getTopNonFinishingActivity();
assertEquals(fullScreenBounds, task.getBounds());
@@ -328,7 +328,7 @@ public class TaskRecordTests extends ActivityTestsBase {
@Test
public void testIgnoresForcedOrientationWhenParentHandles() {
final Rect fullScreenBounds = new Rect(0, 0, 1920, 1080);
- ActivityDisplay display = new TestActivityDisplay.Builder(
+ DisplayContent display = new TestDisplayContent.Builder(
mService, fullScreenBounds.width(), fullScreenBounds.height()).build();
display.getRequestedOverrideConfiguration().orientation =
@@ -337,7 +337,7 @@ public class TaskRecordTests extends ActivityTestsBase {
display.getRequestedOverrideConfiguration());
ActivityStack stack = new StackBuilder(mRootActivityContainer)
.setWindowingMode(WINDOWING_MODE_FULLSCREEN).setDisplay(display).build();
- Task task = stack.getChildAt(0);
+ Task task = stack.getBottomMostTask();
ActivityRecord root = task.getTopNonFinishingActivity();
final WindowContainer parentWindowContainer =
@@ -803,13 +803,13 @@ public class TaskRecordTests extends ActivityTestsBase {
private Task getTestTask() {
final ActivityStack stack = new StackBuilder(mRootActivityContainer).build();
- return stack.getChildAt(0);
+ return stack.getBottomMostTask();
}
private void testStackBoundsConfiguration(int windowingMode, Rect parentBounds, Rect bounds,
Rect expectedConfigBounds) {
- ActivityDisplay display = mService.mRootActivityContainer.getDefaultDisplay();
+ DisplayContent display = mService.mRootActivityContainer.getDefaultDisplay();
ActivityStack stack = display.createStack(windowingMode, ACTIVITY_TYPE_STANDARD,
true /* onTop */);
Task task = new TaskBuilder(mSupervisor).setStack(stack).build();
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskSnapshotControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/TaskSnapshotControllerTest.java
index 6ebaf29d2977..e17e0d87994c 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskSnapshotControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskSnapshotControllerTest.java
@@ -18,15 +18,25 @@ package com.android.server.wm;
import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW;
import static android.view.WindowManager.LayoutParams.FLAG_SECURE;
-import static android.view.WindowManager.TRANSIT_UNSET;
import static com.android.server.wm.TaskSnapshotController.SNAPSHOT_MODE_APP_THEME;
import static com.android.server.wm.TaskSnapshotController.SNAPSHOT_MODE_REAL;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import android.app.ActivityManager;
+import android.app.WindowConfiguration;
+import android.content.ComponentName;
+import android.content.res.Configuration;
+import android.graphics.ColorSpace;
+import android.graphics.GraphicBuffer;
+import android.graphics.PixelFormat;
+import android.graphics.Rect;
import android.platform.test.annotations.Presubmit;
import android.util.ArraySet;
+import android.view.View;
import androidx.test.filters.SmallTest;
@@ -34,6 +44,7 @@ import com.google.android.collect.Sets;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.Mockito;
/**
* Test class for {@link TaskSnapshotController}.
@@ -50,8 +61,8 @@ public class TaskSnapshotControllerTest extends WindowTestsBase {
public void testGetClosingApps_closing() {
final WindowState closingWindow = createWindow(null, FIRST_APPLICATION_WINDOW,
"closingWindow");
- closingWindow.mActivityRecord.commitVisibility(null, false /* visible */, TRANSIT_UNSET,
- true /* performLayout */, false /* isVoiceInteraction */);
+ closingWindow.mActivityRecord.commitVisibility(
+ false /* visible */, true /* performLayout */);
final ArraySet<ActivityRecord> closingApps = new ArraySet<>();
closingApps.add(closingWindow.mActivityRecord);
final ArraySet<Task> closingTasks = new ArraySet<>();
@@ -66,10 +77,10 @@ public class TaskSnapshotControllerTest extends WindowTestsBase {
"closingWindow");
final WindowState openingWindow = createAppWindow(closingWindow.getTask(),
FIRST_APPLICATION_WINDOW, "openingWindow");
- closingWindow.mActivityRecord.commitVisibility(null, false /* visible */, TRANSIT_UNSET,
- true /* performLayout */, false /* isVoiceInteraction */);
- openingWindow.mActivityRecord.commitVisibility(null, true /* visible */, TRANSIT_UNSET,
- true /* performLayout */, false /* isVoiceInteraction */);
+ closingWindow.mActivityRecord.commitVisibility(
+ false /* visible */, true /* performLayout */);
+ openingWindow.mActivityRecord.commitVisibility(
+ true /* visible */, true /* performLayout */);
final ArraySet<ActivityRecord> closingApps = new ArraySet<>();
closingApps.add(closingWindow.mActivityRecord);
final ArraySet<Task> closingTasks = new ArraySet<>();
@@ -81,8 +92,8 @@ public class TaskSnapshotControllerTest extends WindowTestsBase {
public void testGetClosingApps_skipClosingAppsSnapshotTasks() {
final WindowState closingWindow = createWindow(null, FIRST_APPLICATION_WINDOW,
"closingWindow");
- closingWindow.mActivityRecord.commitVisibility(null, false /* visible */, TRANSIT_UNSET,
- true /* performLayout */, false /* isVoiceInteraction */);
+ closingWindow.mActivityRecord.commitVisibility(
+ false /* visible */, true /* performLayout */);
final ArraySet<ActivityRecord> closingApps = new ArraySet<>();
closingApps.add(closingWindow.mActivityRecord);
final ArraySet<Task> closingTasks = new ArraySet<>();
@@ -111,4 +122,57 @@ public class TaskSnapshotControllerTest extends WindowTestsBase {
assertEquals(SNAPSHOT_MODE_APP_THEME,
mWm.mTaskSnapshotController.getSnapshotMode(secureWindow.getTask()));
}
+
+ @Test
+ public void testSnapshotBuilder() {
+ final GraphicBuffer buffer = Mockito.mock(GraphicBuffer.class);
+ final ColorSpace sRGB = ColorSpace.get(ColorSpace.Named.SRGB);
+ final long id = 1234L;
+ final ComponentName activityComponent = new ComponentName("package", ".Class");
+ final int windowingMode = WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
+ final int systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN;
+ final int pixelFormat = PixelFormat.RGBA_8888;
+ final int orientation = Configuration.ORIENTATION_PORTRAIT;
+ final float scaleFraction = 0.25f;
+ final Rect contentInsets = new Rect(1, 2, 3, 4);
+
+ try {
+ ActivityManager.TaskSnapshot.Builder builder =
+ new ActivityManager.TaskSnapshot.Builder();
+ builder.setId(id);
+ builder.setTopActivityComponent(activityComponent);
+ builder.setSystemUiVisibility(systemUiVisibility);
+ builder.setWindowingMode(windowingMode);
+ builder.setColorSpace(sRGB);
+ builder.setReducedResolution(true);
+ builder.setOrientation(orientation);
+ builder.setContentInsets(contentInsets);
+ builder.setIsTranslucent(true);
+ builder.setScaleFraction(0.25f);
+ builder.setSnapshot(buffer);
+ builder.setIsRealSnapshot(true);
+ builder.setPixelFormat(pixelFormat);
+
+ // Not part of TaskSnapshot itself, used in screenshot process
+ assertEquals(pixelFormat, builder.getPixelFormat());
+
+ ActivityManager.TaskSnapshot snapshot = builder.build();
+ assertEquals(id, snapshot.getId());
+ assertEquals(activityComponent, snapshot.getTopActivityComponent());
+ assertEquals(systemUiVisibility, snapshot.getSystemUiVisibility());
+ assertEquals(windowingMode, snapshot.getWindowingMode());
+ assertEquals(sRGB, snapshot.getColorSpace());
+ assertTrue(snapshot.isReducedResolution());
+ assertEquals(orientation, snapshot.getOrientation());
+ assertEquals(contentInsets, snapshot.getContentInsets());
+ assertTrue(snapshot.isTranslucent());
+ assertEquals(scaleFraction, builder.getScaleFraction(), 0.001f);
+ assertSame(buffer, snapshot.getSnapshot());
+ assertTrue(snapshot.isRealSnapshot());
+ } finally {
+ if (buffer != null) {
+ buffer.destroy();
+ }
+ }
+ }
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskSnapshotSurfaceTest.java b/services/tests/wmtests/src/com/android/server/wm/TaskSnapshotSurfaceTest.java
index 817344f9e36f..2d418ffffcf6 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskSnapshotSurfaceTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskSnapshotSurfaceTest.java
@@ -74,7 +74,7 @@ public class TaskSnapshotSurfaceTest extends WindowTestsBase {
0 /* systemUiVisibility */, false /* isTranslucent */);
mSurface = new TaskSnapshotSurface(mWm, new Window(), new SurfaceControl(), snapshot, "Test",
createTaskDescription(Color.WHITE, Color.RED, Color.BLUE), sysuiVis, windowFlags, 0,
- taskBounds, ORIENTATION_PORTRAIT);
+ taskBounds, ORIENTATION_PORTRAIT, null /* insetsState */);
}
private static TaskDescription createTaskDescription(int background, int statusBar,
diff --git a/services/tests/wmtests/src/com/android/server/wm/TestActivityDisplay.java b/services/tests/wmtests/src/com/android/server/wm/TestDisplayContent.java
index 247cd87f98b8..325cea72da24 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TestActivityDisplay.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TestDisplayContent.java
@@ -35,11 +35,11 @@ import android.view.Display;
import android.view.DisplayCutout;
import android.view.DisplayInfo;
-class TestActivityDisplay extends ActivityDisplay {
+class TestDisplayContent extends DisplayContent {
private final ActivityStackSupervisor mSupervisor;
- private TestActivityDisplay(ActivityStackSupervisor supervisor, Display display) {
- super(supervisor.mService.mRootActivityContainer, display);
+ private TestDisplayContent(ActivityStackSupervisor supervisor, Display display) {
+ super(display, supervisor.mService.mRootActivityContainer);
// Normally this comes from display-properties as exposed by WM. Without that, just
// hard-code to FULLSCREEN for tests.
setWindowingMode(WINDOWING_MODE_FULLSCREEN);
@@ -140,13 +140,13 @@ class TestActivityDisplay extends ActivityDisplay {
mInfo.logicalDensityDpi = dpi;
return this;
}
- TestActivityDisplay build() {
+ TestDisplayContent build() {
final int displayId = SystemServicesTestRule.sNextDisplayId++;
final Display display = new Display(DisplayManagerGlobal.getInstance(), displayId,
mInfo, DEFAULT_DISPLAY_ADJUSTMENTS);
- final TestActivityDisplay newDisplay;
+ final TestDisplayContent newDisplay;
synchronized (mService.mGlobalLock) {
- newDisplay = new TestActivityDisplay(mService.mStackSupervisor, display);
+ newDisplay = new TestDisplayContent(mService.mStackSupervisor, display);
mService.mRootActivityContainer.addChild(newDisplay, mPosition);
}
// disable the normal system decorations
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java
index 4d25a83155fd..6108db366cad 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java
@@ -61,33 +61,33 @@ public class WindowProcessControllerTests extends ActivityTestsBase {
assertEquals(INVALID_DISPLAY, mWpc.getDisplayId());
// Register to display 1 as a listener.
- TestActivityDisplay testActivityDisplay1 = createTestActivityDisplayInContainer();
- mWpc.registerDisplayConfigurationListenerLocked(testActivityDisplay1);
- assertTrue(testActivityDisplay1.containsListener(mWpc));
- assertEquals(testActivityDisplay1.mDisplayId, mWpc.getDisplayId());
+ TestDisplayContent testDisplayContent1 = createTestDisplayContentInContainer();
+ mWpc.registerDisplayConfigurationListenerLocked(testDisplayContent1);
+ assertTrue(testDisplayContent1.containsListener(mWpc));
+ assertEquals(testDisplayContent1.mDisplayId, mWpc.getDisplayId());
// Move to display 2.
- TestActivityDisplay testActivityDisplay2 = createTestActivityDisplayInContainer();
- mWpc.registerDisplayConfigurationListenerLocked(testActivityDisplay2);
- assertFalse(testActivityDisplay1.containsListener(mWpc));
- assertTrue(testActivityDisplay2.containsListener(mWpc));
- assertEquals(testActivityDisplay2.mDisplayId, mWpc.getDisplayId());
+ TestDisplayContent testDisplayContent2 = createTestDisplayContentInContainer();
+ mWpc.registerDisplayConfigurationListenerLocked(testDisplayContent2);
+ assertFalse(testDisplayContent1.containsListener(mWpc));
+ assertTrue(testDisplayContent2.containsListener(mWpc));
+ assertEquals(testDisplayContent2.mDisplayId, mWpc.getDisplayId());
- // Null ActivityDisplay will not change anything.
+ // Null DisplayContent will not change anything.
mWpc.registerDisplayConfigurationListenerLocked(null);
- assertTrue(testActivityDisplay2.containsListener(mWpc));
- assertEquals(testActivityDisplay2.mDisplayId, mWpc.getDisplayId());
+ assertTrue(testDisplayContent2.containsListener(mWpc));
+ assertEquals(testDisplayContent2.mDisplayId, mWpc.getDisplayId());
// Unregister listener will remove the wpc from registered displays.
mWpc.unregisterDisplayConfigurationListenerLocked();
- assertFalse(testActivityDisplay1.containsListener(mWpc));
- assertFalse(testActivityDisplay2.containsListener(mWpc));
+ assertFalse(testDisplayContent1.containsListener(mWpc));
+ assertFalse(testDisplayContent2.containsListener(mWpc));
assertEquals(INVALID_DISPLAY, mWpc.getDisplayId());
// Unregistration still work even if the display was removed.
- mWpc.registerDisplayConfigurationListenerLocked(testActivityDisplay1);
- assertEquals(testActivityDisplay1.mDisplayId, mWpc.getDisplayId());
- mRootActivityContainer.removeChild(testActivityDisplay1);
+ mWpc.registerDisplayConfigurationListenerLocked(testDisplayContent1);
+ assertEquals(testDisplayContent1.mDisplayId, mWpc.getDisplayId());
+ mRootActivityContainer.removeChild(testDisplayContent1);
mWpc.unregisterDisplayConfigurationListenerLocked();
assertEquals(INVALID_DISPLAY, mWpc.getDisplayId());
}
@@ -129,7 +129,7 @@ public class WindowProcessControllerTests extends ActivityTestsBase {
orderVerifier.verifyNoMoreInteractions();
}
- private TestActivityDisplay createTestActivityDisplayInContainer() {
- return new TestActivityDisplay.Builder(mService, 1000, 1500).build();
+ private TestDisplayContent createTestDisplayContentInContainer() {
+ return new TestDisplayContent.Builder(mService, 1000, 1500).build();
}
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java
index 72baedb5ed66..0018c633e675 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java
@@ -32,7 +32,9 @@ import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA_OVERLAY;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
+import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL;
+import static android.view.WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR;
@@ -61,6 +63,7 @@ import static org.mockito.Mockito.when;
import android.graphics.Insets;
import android.graphics.Matrix;
+import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.platform.test.annotations.Presubmit;
import android.util.Size;
@@ -81,7 +84,9 @@ import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
+import java.util.Arrays;
import java.util.LinkedList;
+import java.util.List;
/**
* Tests for the {@link WindowState} class.
@@ -222,8 +227,7 @@ public class WindowStateTests extends WindowTestsBase {
final WindowState appWindow = createWindow(null, TYPE_APPLICATION, "appWindow");
final WindowState imeWindow = createWindow(null, TYPE_INPUT_METHOD, "imeWindow");
- // Setting FLAG_NOT_FOCUSABLE without FLAG_ALT_FOCUSABLE_IM prevents the window from being
- // an IME target.
+ // Setting FLAG_NOT_FOCUSABLE prevents the window from being an IME target.
appWindow.mAttrs.flags |= FLAG_NOT_FOCUSABLE;
imeWindow.mAttrs.flags |= FLAG_NOT_FOCUSABLE;
@@ -231,7 +235,7 @@ public class WindowStateTests extends WindowTestsBase {
appWindow.setHasSurface(true);
imeWindow.setHasSurface(true);
- // Windows without flags (FLAG_NOT_FOCUSABLE|FLAG_ALT_FOCUSABLE_IM) can't be IME targets
+ // Windows with FLAG_NOT_FOCUSABLE can't be IME targets
assertFalse(appWindow.canBeImeTarget());
assertFalse(imeWindow.canBeImeTarget());
@@ -239,11 +243,22 @@ public class WindowStateTests extends WindowTestsBase {
appWindow.mAttrs.flags |= (FLAG_NOT_FOCUSABLE | FLAG_ALT_FOCUSABLE_IM);
imeWindow.mAttrs.flags |= (FLAG_NOT_FOCUSABLE | FLAG_ALT_FOCUSABLE_IM);
- // Visible app window with flags can be IME target while an IME window can never be an IME
- // target regardless of its visibility or flags.
- assertTrue(appWindow.canBeImeTarget());
+ // Visible app window with flags FLAG_NOT_FOCUSABLE or FLAG_ALT_FOCUSABLE_IM can't be IME
+ // target while an IME window can never be an IME target regardless of its visibility
+ // or flags.
+ assertFalse(appWindow.canBeImeTarget());
assertFalse(imeWindow.canBeImeTarget());
+ // b/145812508: special legacy use-case for transparent/translucent windows.
+ appWindow.mAttrs.format = PixelFormat.TRANSPARENT;
+ assertTrue(appWindow.canBeImeTarget());
+
+ appWindow.mAttrs.format = PixelFormat.OPAQUE;
+ appWindow.mAttrs.flags &= ~FLAG_ALT_FOCUSABLE_IM;
+ assertFalse(appWindow.canBeImeTarget());
+ appWindow.mAttrs.flags &= ~FLAG_NOT_FOCUSABLE;
+ assertTrue(appWindow.canBeImeTarget());
+
// Make windows invisible
appWindow.hideLw(false /* doAnimation */);
imeWindow.hideLw(false /* doAnimation */);
@@ -521,6 +536,31 @@ public class WindowStateTests extends WindowTestsBase {
}
@Test
+ public void testRequestDrawIfNeeded() {
+ final WindowState startingApp = createWindow(null /* parent */,
+ TYPE_BASE_APPLICATION, "startingApp");
+ final WindowState startingWindow = createWindow(null /* parent */,
+ TYPE_APPLICATION_STARTING, startingApp.mToken, "starting");
+ startingApp.mActivityRecord.startingWindow = startingWindow;
+ final WindowState keyguardHostWindow = mStatusBarWindow;
+ final WindowState allDrawnApp = mAppWindow;
+ allDrawnApp.mActivityRecord.allDrawn = true;
+
+ // The waiting list is used to ensure the content is ready when turning on screen.
+ final List<WindowState> outWaitingForDrawn = mDisplayContent.mWaitingForDrawn;
+ final List<WindowState> visibleWindows = Arrays.asList(mChildAppWindowAbove,
+ keyguardHostWindow, allDrawnApp, startingApp, startingWindow);
+ visibleWindows.forEach(w -> {
+ w.mHasSurface = true;
+ w.requestDrawIfNeeded(outWaitingForDrawn);
+ });
+
+ // Keyguard host window should be always contained. The drawn app or app with starting
+ // window are unnecessary to draw.
+ assertEquals(Arrays.asList(keyguardHostWindow, startingWindow), outWaitingForDrawn);
+ }
+
+ @Test
public void testGetTransformationMatrix() {
final int PARENT_WINDOW_OFFSET = 1;
final int DISPLAY_IN_PARENT_WINDOW_OFFSET = 2;
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
index 22ba90b84562..6f53428cc6a6 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
@@ -340,8 +340,8 @@ class WindowTestsBase extends SystemServiceTestsBase {
/** Creates a {@link DisplayContent} and adds it to the system. */
DisplayContent createNewDisplay(DisplayInfo info) {
- final ActivityDisplay display =
- new TestActivityDisplay.Builder(mWm.mAtmService, info).build();
+ final DisplayContent display =
+ new TestDisplayContent.Builder(mWm.mAtmService, info).build();
return display.mDisplayContent;
}
diff --git a/services/usage/java/com/android/server/usage/StorageStatsService.java b/services/usage/java/com/android/server/usage/StorageStatsService.java
index 0f3050f9e3d3..531a93117752 100644
--- a/services/usage/java/com/android/server/usage/StorageStatsService.java
+++ b/services/usage/java/com/android/server/usage/StorageStatsService.java
@@ -19,6 +19,9 @@ package com.android.server.usage;
import static com.android.internal.util.ArrayUtils.defeatNullable;
import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.UserIdInt;
import android.app.AppOpsManager;
import android.app.usage.ExternalStorageStats;
import android.app.usage.IStorageStatsManager;
@@ -30,6 +33,7 @@ import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PackageStats;
+import android.content.pm.ParceledListSlice;
import android.content.pm.UserInfo;
import android.net.Uri;
import android.os.Binder;
@@ -44,10 +48,13 @@ import android.os.StatFs;
import android.os.SystemProperties;
import android.os.UserHandle;
import android.os.UserManager;
+import android.os.storage.CrateInfo;
+import android.os.storage.CrateMetadata;
import android.os.storage.StorageEventListener;
import android.os.storage.StorageManager;
import android.os.storage.VolumeInfo;
import android.provider.Settings;
+import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.ArrayMap;
import android.util.DataUnit;
@@ -67,6 +74,9 @@ import com.android.server.storage.CacheQuotaStrategy;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
public class StorageStatsService extends IStorageStatsManager.Stub {
private static final String TAG = "StorageStatsService";
@@ -139,7 +149,7 @@ public class StorageStatsService extends IStorageStatsManager.Stub {
}
}
- private void enforcePermission(int callingUid, String callingPackage) {
+ private void enforceStatsPermission(int callingUid, String callingPackage) {
final int mode = mAppOps.noteOp(AppOpsManager.OP_GET_USAGE_STATS,
callingUid, callingPackage);
switch (mode) {
@@ -222,7 +232,7 @@ public class StorageStatsService extends IStorageStatsManager.Stub {
@Override
public long getCacheBytes(String volumeUuid, String callingPackage) {
- enforcePermission(Binder.getCallingUid(), callingPackage);
+ enforceStatsPermission(Binder.getCallingUid(), callingPackage);
long cacheBytes = 0;
for (UserInfo user : mUser.getUsers()) {
@@ -234,7 +244,7 @@ public class StorageStatsService extends IStorageStatsManager.Stub {
@Override
public long getCacheQuotaBytes(String volumeUuid, int uid, String callingPackage) {
- enforcePermission(Binder.getCallingUid(), callingPackage);
+ enforceStatsPermission(Binder.getCallingUid(), callingPackage);
if (mCacheQuotas.containsKey(volumeUuid)) {
final SparseLongArray uidMap = mCacheQuotas.get(volumeUuid);
@@ -263,7 +273,7 @@ public class StorageStatsService extends IStorageStatsManager.Stub {
if (Binder.getCallingUid() == appInfo.uid) {
// No permissions required when asking about themselves
} else {
- enforcePermission(Binder.getCallingUid(), callingPackage);
+ enforceStatsPermission(Binder.getCallingUid(), callingPackage);
}
if (defeatNullable(mPackage.getPackagesForUid(appInfo.uid)).length == 1) {
@@ -307,7 +317,7 @@ public class StorageStatsService extends IStorageStatsManager.Stub {
if (Binder.getCallingUid() == uid) {
// No permissions required when asking about themselves
} else {
- enforcePermission(Binder.getCallingUid(), callingPackage);
+ enforceStatsPermission(Binder.getCallingUid(), callingPackage);
}
final String[] packageNames = defeatNullable(mPackage.getPackagesForUid(uid));
@@ -354,7 +364,7 @@ public class StorageStatsService extends IStorageStatsManager.Stub {
}
// Always require permission to see user-level stats
- enforcePermission(Binder.getCallingUid(), callingPackage);
+ enforceStatsPermission(Binder.getCallingUid(), callingPackage);
final int[] appIds = getAppIds(userId);
final PackageStats stats = new PackageStats(TAG);
@@ -381,7 +391,7 @@ public class StorageStatsService extends IStorageStatsManager.Stub {
}
// Always require permission to see user-level stats
- enforcePermission(Binder.getCallingUid(), callingPackage);
+ enforceStatsPermission(Binder.getCallingUid(), callingPackage);
final int[] appIds = getAppIds(userId);
final long[] stats;
@@ -556,4 +566,143 @@ public class StorageStatsService extends IStorageStatsManager.Stub {
mContext.getContentResolver().notifyChange(
Uri.parse("content://com.android.externalstorage.documents/"), null, false);
}
+
+ /**
+ * To enforce the calling or self to have the {@link android.Manifest.permission#MANAGE_CRATES}
+ * permission.
+ * @param callingUid the calling uid
+ * @param callingPackage the calling package name
+ */
+ private void enforceCratesPermission(int callingUid, String callingPackage) {
+ mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_CRATES,
+ callingPackage);
+ }
+
+ /**
+ * To copy from CrateMetadata instances into CrateInfo instances.
+ */
+ @NonNull
+ private static List<CrateInfo> convertCrateInfoFrom(@Nullable CrateMetadata[] crateMetadatas) {
+ if (ArrayUtils.isEmpty(crateMetadatas)) {
+ return Collections.EMPTY_LIST;
+ }
+
+ ArrayList<CrateInfo> crateInfos = new ArrayList<>();
+ for (CrateMetadata crateMetadata : crateMetadatas) {
+ if (crateMetadata == null || TextUtils.isEmpty(crateMetadata.id)
+ || TextUtils.isEmpty(crateMetadata.packageName)) {
+ continue;
+ }
+
+ CrateInfo crateInfo = CrateInfo.copyFrom(crateMetadata.uid,
+ crateMetadata.packageName, crateMetadata.id);
+ if (crateInfo == null) {
+ continue;
+ }
+
+ crateInfos.add(crateInfo);
+ }
+
+ return crateInfos;
+ }
+
+ @NonNull
+ private ParceledListSlice<CrateInfo> getAppCrates(String volumeUuid, String[] packageNames,
+ @UserIdInt int userId) {
+ try {
+ CrateMetadata[] crateMetadatas = mInstaller.getAppCrates(volumeUuid,
+ packageNames, userId);
+ return new ParceledListSlice<>(convertCrateInfoFrom(crateMetadatas));
+ } catch (InstallerException e) {
+ throw new ParcelableException(new IOException(e.getMessage()));
+ }
+ }
+
+ @NonNull
+ @Override
+ public ParceledListSlice<CrateInfo> queryCratesForPackage(String volumeUuid,
+ @NonNull String packageName, @UserIdInt int userId, @NonNull String callingPackage) {
+ if (userId != UserHandle.getCallingUserId()) {
+ mContext.enforceCallingOrSelfPermission(
+ android.Manifest.permission.INTERACT_ACROSS_USERS, TAG);
+ }
+
+ final ApplicationInfo appInfo;
+ try {
+ appInfo = mPackage.getApplicationInfoAsUser(packageName,
+ PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
+ } catch (NameNotFoundException e) {
+ throw new ParcelableException(e);
+ }
+
+ if (Binder.getCallingUid() == appInfo.uid) {
+ // No permissions required when asking about themselves
+ } else {
+ enforceCratesPermission(Binder.getCallingUid(), callingPackage);
+ }
+
+ final String[] packageNames = new String[] { packageName };
+ return getAppCrates(volumeUuid, packageNames, userId);
+ }
+
+ @NonNull
+ @Override
+ public ParceledListSlice<CrateInfo> queryCratesForUid(String volumeUuid, int uid,
+ @NonNull String callingPackage) {
+ final int userId = UserHandle.getUserId(uid);
+ if (userId != UserHandle.getCallingUserId()) {
+ mContext.enforceCallingOrSelfPermission(
+ android.Manifest.permission.INTERACT_ACROSS_USERS, TAG);
+ }
+
+ if (Binder.getCallingUid() == uid) {
+ // No permissions required when asking about themselves
+ } else {
+ enforceCratesPermission(Binder.getCallingUid(), callingPackage);
+ }
+
+ final String[] packageNames = defeatNullable(mPackage.getPackagesForUid(uid));
+ String[] validatedPackageNames = new String[0];
+
+ for (String packageName : packageNames) {
+ if (TextUtils.isEmpty(packageName)) {
+ continue;
+ }
+
+ try {
+ final ApplicationInfo appInfo = mPackage.getApplicationInfoAsUser(packageName,
+ PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
+ if (appInfo == null) {
+ continue;
+ }
+
+ validatedPackageNames = ArrayUtils.appendElement(String.class,
+ validatedPackageNames, packageName);
+ } catch (NameNotFoundException e) {
+ throw new ParcelableException(e);
+ }
+ }
+
+ return getAppCrates(volumeUuid, validatedPackageNames, userId);
+ }
+
+ @NonNull
+ @Override
+ public ParceledListSlice<CrateInfo> queryCratesForUser(String volumeUuid, int userId,
+ @NonNull String callingPackage) {
+ if (userId != UserHandle.getCallingUserId()) {
+ mContext.enforceCallingOrSelfPermission(
+ android.Manifest.permission.INTERACT_ACROSS_USERS, TAG);
+ }
+
+ // Always require permission to see user-level stats
+ enforceCratesPermission(Binder.getCallingUid(), callingPackage);
+
+ try {
+ CrateMetadata[] crateMetadatas = mInstaller.getUserCrates(volumeUuid, userId);
+ return new ParceledListSlice<>(convertCrateInfoFrom(crateMetadatas));
+ } catch (InstallerException e) {
+ throw new ParcelableException(new IOException(e.getMessage()));
+ }
+ }
}
diff --git a/services/usage/java/com/android/server/usage/UsageStatsDatabase.java b/services/usage/java/com/android/server/usage/UsageStatsDatabase.java
index 1996dd4f6545..ef9a73b794f7 100644
--- a/services/usage/java/com/android/server/usage/UsageStatsDatabase.java
+++ b/services/usage/java/com/android/server/usage/UsageStatsDatabase.java
@@ -229,8 +229,8 @@ public class UsageStatsDatabase {
}
try {
- IntervalStats stats = new IntervalStats();
for (int i = start; i < fileCount - 1; i++) {
+ final IntervalStats stats = new IntervalStats();
readLocked(files.valueAt(i), stats);
if (!checkinAction.checkin(stats)) {
return false;
@@ -848,10 +848,10 @@ public class UsageStatsDatabase {
}
}
- final IntervalStats stats = new IntervalStats();
final ArrayList<T> results = new ArrayList<>();
for (int i = startIndex; i <= endIndex; i++) {
final AtomicFile f = intervalStats.valueAt(i);
+ final IntervalStats stats = new IntervalStats();
if (DEBUG) {
Slog.d(TAG, "Reading stat file " + f.getBaseFile().getAbsolutePath());
@@ -1061,6 +1061,11 @@ public class UsageStatsDatabase {
}
}
+ /**
+ * Note: the data read from the given file will add to the IntervalStats object passed into this
+ * method. It is up to the caller to ensure that this is the desired behavior - if not, the
+ * caller should ensure that the data in the reused object is being cleared.
+ */
private void readLocked(AtomicFile file, IntervalStats statsOut)
throws IOException, RuntimeException {
if (mCurrentVersion <= 3) {
@@ -1072,6 +1077,10 @@ public class UsageStatsDatabase {
/**
* Returns {@code true} if any stats were omitted while reading, {@code false} otherwise.
+ * <p/>
+ * Note: the data read from the given file will add to the IntervalStats object passed into this
+ * method. It is up to the caller to ensure that this is the desired behavior - if not, the
+ * caller should ensure that the data in the reused object is being cleared.
*/
private static boolean readLocked(AtomicFile file, IntervalStats statsOut, int version,
PackagesTokenData packagesTokenData) throws IOException, RuntimeException {
@@ -1098,6 +1107,10 @@ public class UsageStatsDatabase {
/**
* Returns {@code true} if any stats were omitted while reading, {@code false} otherwise.
+ * <p/>
+ * Note: the data read from the given file will add to the IntervalStats object passed into this
+ * method. It is up to the caller to ensure that this is the desired behavior - if not, the
+ * caller should ensure that the data in the reused object is being cleared.
*/
private static boolean readLocked(InputStream in, IntervalStats statsOut, int version,
PackagesTokenData packagesTokenData) throws RuntimeException {
diff --git a/services/usb/java/com/android/server/usb/UsbHandlerManager.java b/services/usb/java/com/android/server/usb/UsbHandlerManager.java
index 1730d8f22950..f3112743bcf2 100644
--- a/services/usb/java/com/android/server/usb/UsbHandlerManager.java
+++ b/services/usb/java/com/android/server/usb/UsbHandlerManager.java
@@ -19,6 +19,7 @@ package com.android.server.usb;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.ActivityNotFoundException;
+import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
@@ -59,8 +60,9 @@ class UsbHandlerManager {
if (uri != null && uri.length() > 0) {
// display URI to user
Intent dialogIntent = createDialogIntent();
- dialogIntent.setClassName("com.android.systemui",
- "com.android.systemui.usb.UsbAccessoryUriActivity");
+ dialogIntent.setComponent(ComponentName.unflattenFromString(
+ mContext.getResources().getString(
+ com.android.internal.R.string.config_usbAccessoryUriActivity)));
dialogIntent.putExtra(UsbManager.EXTRA_ACCESSORY, accessory);
dialogIntent.putExtra("uri", uri);
try {
@@ -84,8 +86,9 @@ class UsbHandlerManager {
@Nullable UsbAccessory accessory) {
Intent resolverIntent = createDialogIntent();
// start UsbConfirmActivity if there is only one choice
- resolverIntent.setClassName("com.android.systemui",
- "com.android.systemui.usb.UsbConfirmActivity");
+ resolverIntent.setComponent(ComponentName.unflattenFromString(
+ mContext.getResources().getString(
+ com.android.internal.R.string.config_usbConfirmActivity)));
resolverIntent.putExtra("rinfo", rInfo);
UserHandle user =
UserHandle.getUserHandleForUid(rInfo.activityInfo.applicationInfo.uid);
@@ -115,8 +118,9 @@ class UsbHandlerManager {
void selectUsbHandler(@NonNull ArrayList<ResolveInfo> matches,
@NonNull UserHandle user, @NonNull Intent intent) {
Intent resolverIntent = createDialogIntent();
- resolverIntent.setClassName("com.android.systemui",
- "com.android.systemui.usb.UsbResolverActivity");
+ resolverIntent.setComponent(ComponentName.unflattenFromString(
+ mContext.getResources().getString(
+ com.android.internal.R.string.config_usbResolverActivity)));
resolverIntent.putParcelableArrayListExtra("rlist", matches);
resolverIntent.putExtra(Intent.EXTRA_INTENT, intent);
diff --git a/services/usb/java/com/android/server/usb/UsbPortManager.java b/services/usb/java/com/android/server/usb/UsbPortManager.java
index 749258e76f79..c3e2013eff10 100644
--- a/services/usb/java/com/android/server/usb/UsbPortManager.java
+++ b/services/usb/java/com/android/server/usb/UsbPortManager.java
@@ -34,6 +34,7 @@ import android.annotation.NonNull;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
+import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
@@ -225,8 +226,8 @@ public class UsbPortManager {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- intent.setClassName("com.android.systemui",
- "com.android.systemui.usb.UsbContaminantActivity");
+ intent.setComponent(ComponentName.unflattenFromString(r.getString(
+ com.android.internal.R.string.config_usbContaminantActivity)));
intent.putExtra(UsbManager.EXTRA_PORT, ParcelableUsbPort.of(currentPortInfo.mUsbPort));
PendingIntent pi = PendingIntent.getActivityAsUser(mContext, 0,
diff --git a/services/usb/java/com/android/server/usb/UsbSerialReader.java b/services/usb/java/com/android/server/usb/UsbSerialReader.java
index 86016bb6036f..095e8e9b7b5b 100644
--- a/services/usb/java/com/android/server/usb/UsbSerialReader.java
+++ b/services/usb/java/com/android/server/usb/UsbSerialReader.java
@@ -75,12 +75,14 @@ class UsbSerialReader extends IUsbSerialReader.Stub {
if (uid != Process.SYSTEM_UID) {
enforcePackageBelongsToUid(uid, packageName);
+ UserHandle user = Binder.getCallingUserHandle();
int packageTargetSdkVersion;
long token = Binder.clearCallingIdentity();
try {
PackageInfo pkg;
try {
- pkg = mContext.getPackageManager().getPackageInfo(packageName, 0);
+ pkg = mContext.getPackageManager()
+ .getPackageInfoAsUser(packageName, 0, user.getIdentifier());
} catch (PackageManager.NameNotFoundException e) {
throw new RemoteException("package " + packageName + " cannot be found");
}
diff --git a/services/usb/java/com/android/server/usb/UsbUserPermissionManager.java b/services/usb/java/com/android/server/usb/UsbUserPermissionManager.java
index 58f5484657c5..2a94393b8009 100644
--- a/services/usb/java/com/android/server/usb/UsbUserPermissionManager.java
+++ b/services/usb/java/com/android/server/usb/UsbUserPermissionManager.java
@@ -20,6 +20,7 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
+import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
@@ -515,8 +516,8 @@ class UsbUserPermissionManager {
intent.putExtra(Intent.EXTRA_UID, uid);
intent.putExtra(UsbManager.EXTRA_CAN_BE_DEFAULT, canBeDefault);
intent.putExtra(UsbManager.EXTRA_PACKAGE, packageName);
- intent.setClassName("com.android.systemui",
- "com.android.systemui.usb.UsbPermissionActivity");
+ intent.setComponent(ComponentName.unflattenFromString(userContext.getResources().getString(
+ com.android.internal.R.string.config_usbPermissionActivity)));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
diff --git a/services/voiceinteraction/java/com/android/server/soundtrigger/SoundTriggerHelper.java b/services/voiceinteraction/java/com/android/server/soundtrigger/SoundTriggerHelper.java
index 735b9a1dcf2e..198b4c31249a 100644
--- a/services/voiceinteraction/java/com/android/server/soundtrigger/SoundTriggerHelper.java
+++ b/services/voiceinteraction/java/com/android/server/soundtrigger/SoundTriggerHelper.java
@@ -16,11 +16,14 @@
package com.android.server.soundtrigger;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.soundtrigger.IRecognitionStatusCallback;
+import android.hardware.soundtrigger.ModelParams;
import android.hardware.soundtrigger.SoundTrigger;
import android.hardware.soundtrigger.SoundTrigger.GenericRecognitionEvent;
import android.hardware.soundtrigger.SoundTrigger.GenericSoundModel;
@@ -28,6 +31,7 @@ import android.hardware.soundtrigger.SoundTrigger.Keyphrase;
import android.hardware.soundtrigger.SoundTrigger.KeyphraseRecognitionEvent;
import android.hardware.soundtrigger.SoundTrigger.KeyphraseRecognitionExtra;
import android.hardware.soundtrigger.SoundTrigger.KeyphraseSoundModel;
+import android.hardware.soundtrigger.SoundTrigger.ModelParamRange;
import android.hardware.soundtrigger.SoundTrigger.ModuleProperties;
import android.hardware.soundtrigger.SoundTrigger.RecognitionConfig;
import android.hardware.soundtrigger.SoundTrigger.RecognitionEvent;
@@ -605,6 +609,67 @@ public class SoundTriggerHelper implements SoundTrigger.StatusListener {
return STATUS_ERROR;
}
+ int setParameter(UUID modelId, @ModelParams int modelParam, int value) {
+ synchronized (mLock) {
+ MetricsLogger.count(mContext, "sth_set_parameter", 1);
+ if (modelId == null || mModule == null) {
+ return SoundTrigger.STATUS_ERROR;
+ }
+ ModelData modelData = mModelDataMap.get(modelId);
+ if (modelData == null) {
+ Slog.w(TAG, "SetParameter: Invalid model id:" + modelId);
+ return SoundTrigger.STATUS_BAD_VALUE;
+ }
+ if (!modelData.isModelLoaded()) {
+ Slog.i(TAG, "SetParameter: Given model is not loaded:" + modelId);
+ return SoundTrigger.STATUS_BAD_VALUE;
+ }
+
+ return mModule.setParameter(modelData.getHandle(), modelParam, value);
+ }
+ }
+
+ int getParameter(@NonNull UUID modelId, @ModelParams int modelParam)
+ throws UnsupportedOperationException, IllegalArgumentException {
+ synchronized (mLock) {
+ MetricsLogger.count(mContext, "sth_get_parameter", 1);
+ if (mModule == null) {
+ throw new UnsupportedOperationException("SoundTriggerModule not initialized");
+ }
+
+ ModelData modelData = mModelDataMap.get(modelId);
+ if (modelData == null) {
+ throw new IllegalArgumentException("Invalid model id:" + modelId);
+ }
+ if (!modelData.isModelLoaded()) {
+ throw new UnsupportedOperationException("Given model is not loaded:" + modelId);
+ }
+
+ return mModule.getParameter(modelData.getHandle(), modelParam);
+ }
+ }
+
+ @Nullable
+ ModelParamRange queryParameter(@NonNull UUID modelId, @ModelParams int modelParam) {
+ synchronized (mLock) {
+ MetricsLogger.count(mContext, "sth_query_parameter", 1);
+ if (mModule == null) {
+ return null;
+ }
+ ModelData modelData = mModelDataMap.get(modelId);
+ if (modelData == null) {
+ Slog.w(TAG, "queryParameter: Invalid model id:" + modelId);
+ return null;
+ }
+ if (!modelData.isModelLoaded()) {
+ Slog.i(TAG, "queryParameter: Given model is not loaded:" + modelId);
+ return null;
+ }
+
+ return mModule.queryParameter(modelData.getHandle(), modelParam);
+ }
+ }
+
//---- SoundTrigger.StatusListener methods
@Override
public void onRecognition(RecognitionEvent event) {
@@ -653,15 +718,15 @@ public class SoundTriggerHelper implements SoundTrigger.StatusListener {
}
ModelData model = getModelDataForLocked(event.soundModelHandle);
if (model == null || !model.isGenericModel()) {
- Slog.w(TAG, "Generic recognition event: Model does not exist for handle: " +
- event.soundModelHandle);
+ Slog.w(TAG, "Generic recognition event: Model does not exist for handle: "
+ + event.soundModelHandle);
return;
}
IRecognitionStatusCallback callback = model.getCallback();
if (callback == null) {
- Slog.w(TAG, "Generic recognition event: Null callback for model handle: " +
- event.soundModelHandle);
+ Slog.w(TAG, "Generic recognition event: Null callback for model handle: "
+ + event.soundModelHandle);
return;
}
@@ -678,8 +743,8 @@ public class SoundTriggerHelper implements SoundTrigger.StatusListener {
RecognitionConfig config = model.getRecognitionConfig();
if (config == null) {
- Slog.w(TAG, "Generic recognition event: Null RecognitionConfig for model handle: " +
- event.soundModelHandle);
+ Slog.w(TAG, "Generic recognition event: Null RecognitionConfig for model handle: "
+ + event.soundModelHandle);
return;
}
diff --git a/services/voiceinteraction/java/com/android/server/soundtrigger/SoundTriggerService.java b/services/voiceinteraction/java/com/android/server/soundtrigger/SoundTriggerService.java
index 1dd3972b56b4..96d2df125a3c 100644
--- a/services/voiceinteraction/java/com/android/server/soundtrigger/SoundTriggerService.java
+++ b/services/voiceinteraction/java/com/android/server/soundtrigger/SoundTriggerService.java
@@ -22,7 +22,9 @@ import static android.content.Context.BIND_FOREGROUND_SERVICE;
import static android.content.pm.PackageManager.GET_META_DATA;
import static android.content.pm.PackageManager.GET_SERVICES;
import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
+import static android.hardware.soundtrigger.SoundTrigger.STATUS_BAD_VALUE;
import static android.hardware.soundtrigger.SoundTrigger.STATUS_ERROR;
+import static android.hardware.soundtrigger.SoundTrigger.STATUS_NO_INIT;
import static android.hardware.soundtrigger.SoundTrigger.STATUS_OK;
import static android.provider.Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY;
import static android.provider.Settings.Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT;
@@ -39,9 +41,11 @@ import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.hardware.soundtrigger.IRecognitionStatusCallback;
+import android.hardware.soundtrigger.ModelParams;
import android.hardware.soundtrigger.SoundTrigger;
import android.hardware.soundtrigger.SoundTrigger.GenericSoundModel;
import android.hardware.soundtrigger.SoundTrigger.KeyphraseSoundModel;
+import android.hardware.soundtrigger.SoundTrigger.ModelParamRange;
import android.hardware.soundtrigger.SoundTrigger.ModuleProperties;
import android.hardware.soundtrigger.SoundTrigger.RecognitionConfig;
import android.hardware.soundtrigger.SoundTrigger.SoundModel;
@@ -683,6 +687,101 @@ public class SoundTriggerService extends SystemService {
return properties;
}
}
+
+ @Override
+ public int setParameter(ParcelUuid soundModelId,
+ @ModelParams int modelParam, int value) {
+ enforceCallingPermission(Manifest.permission.MANAGE_SOUND_TRIGGER);
+ if (!isInitialized()) return STATUS_NO_INIT;
+ if (DEBUG) {
+ Slog.d(TAG, "setParameter(): id=" + soundModelId
+ + ", param=" + modelParam
+ + ", value=" + value);
+ }
+
+ sEventLogger.log(new SoundTriggerLogger.StringEvent(
+ "setParameter(): id=" + soundModelId
+ + ", param=" + modelParam
+ + ", value=" + value));
+
+ synchronized (mLock) {
+ SoundModel soundModel = mLoadedModels.get(soundModelId.getUuid());
+ if (soundModel == null) {
+ Slog.e(TAG, soundModelId + " is not loaded. Loaded models: "
+ + mLoadedModels.toString());
+
+ sEventLogger.log(new SoundTriggerLogger.StringEvent("setParameter(): "
+ + soundModelId + " is not loaded"));
+
+ return STATUS_BAD_VALUE;
+ }
+
+ return mSoundTriggerHelper.setParameter(soundModel.uuid, modelParam, value);
+ }
+ }
+
+ @Override
+ public int getParameter(@NonNull ParcelUuid soundModelId,
+ @ModelParams int modelParam)
+ throws UnsupportedOperationException, IllegalArgumentException {
+ enforceCallingPermission(Manifest.permission.MANAGE_SOUND_TRIGGER);
+ if (!isInitialized()) {
+ throw new UnsupportedOperationException("SoundTriggerHelper not initialized");
+ }
+ if (DEBUG) {
+ Slog.d(TAG, "getParameter(): id=" + soundModelId
+ + ", param=" + modelParam);
+ }
+
+ sEventLogger.log(new SoundTriggerLogger.StringEvent(
+ "getParameter(): id=" + soundModelId
+ + ", param=" + modelParam));
+
+ synchronized (mLock) {
+ SoundModel soundModel = mLoadedModels.get(soundModelId.getUuid());
+ if (soundModel == null) {
+ Slog.e(TAG, soundModelId + " is not loaded");
+
+ sEventLogger.log(new SoundTriggerLogger.StringEvent("getParameter(): "
+ + soundModelId + " is not loaded"));
+
+ throw new IllegalArgumentException("sound model is not loaded");
+ }
+
+ return mSoundTriggerHelper.getParameter(soundModel.uuid, modelParam);
+ }
+ }
+
+ @Override
+ @Nullable
+ public ModelParamRange queryParameter(@NonNull ParcelUuid soundModelId,
+ @ModelParams int modelParam) {
+ enforceCallingPermission(Manifest.permission.MANAGE_SOUND_TRIGGER);
+ if (!isInitialized()) return null;
+ if (DEBUG) {
+ Slog.d(TAG, "queryParameter(): id=" + soundModelId
+ + ", param=" + modelParam);
+ }
+
+ sEventLogger.log(new SoundTriggerLogger.StringEvent(
+ "queryParameter(): id=" + soundModelId
+ + ", param=" + modelParam));
+
+ synchronized (mLock) {
+ SoundModel soundModel = mLoadedModels.get(soundModelId.getUuid());
+ if (soundModel == null) {
+ Slog.e(TAG, soundModelId + " is not loaded");
+
+ sEventLogger.log(new SoundTriggerLogger.StringEvent(
+ "queryParameter(): "
+ + soundModelId + " is not loaded"));
+
+ return null;
+ }
+
+ return mSoundTriggerHelper.queryParameter(soundModel.uuid, modelParam);
+ }
+ }
}
/**
diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
index 6132cc2250b9..404346fa9286 100644
--- a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
+++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
@@ -1291,6 +1291,7 @@ public class VoiceInteractionManagerService extends SystemService {
pw.println(" mCurUser: " + mCurUser);
pw.println(" mCurUserUnlocked: " + mCurUserUnlocked);
pw.println(" mCurUserSupported: " + mCurUserSupported);
+ dumpSupportedUsers(pw, " ");
if (mImpl == null) {
pw.println(" (No active implementation)");
return;
diff --git a/telecomm/java/android/telecom/Connection.java b/telecomm/java/android/telecom/Connection.java
index c06327995bc0..0becaf237a73 100644
--- a/telecomm/java/android/telecom/Connection.java
+++ b/telecomm/java/android/telecom/Connection.java
@@ -695,6 +695,15 @@ public abstract class Connection extends Conferenceable {
public static final String EVENT_CALL_HOLD_FAILED = "android.telecom.event.CALL_HOLD_FAILED";
/**
+ * Connection event used to inform Telecom when a switch operation on a call has failed.
+ * <p>
+ * Sent via {@link #sendConnectionEvent(String, Bundle)}. The {@link Bundle} parameter is
+ * expected to be null when this connection event is used.
+ */
+ public static final String EVENT_CALL_SWITCH_FAILED =
+ "android.telecom.event.CALL_SWITCH_FAILED";
+
+ /**
* Connection event used to inform {@link InCallService}s when the process of merging a
* Connection into a conference has begun.
* <p>
diff --git a/telecomm/java/android/telecom/TelecomManager.java b/telecomm/java/android/telecom/TelecomManager.java
index 39d741c3d3bf..af3c55abf00c 100644
--- a/telecomm/java/android/telecom/TelecomManager.java
+++ b/telecomm/java/android/telecom/TelecomManager.java
@@ -485,6 +485,103 @@ public class TelecomManager {
"android.telecom.extra.START_CALL_WITH_RTT";
/**
+ * Start an activity indicating that the completion of an outgoing call or an incoming call
+ * which was not blocked by the {@link CallScreeningService}, and which was NOT terminated
+ * while the call was in {@link Call#STATE_AUDIO_PROCESSING}.
+ *
+ * The {@link Uri} extra {@link #EXTRA_HANDLE} will contain the uri handle(phone number) for the
+ * call which completed.
+ *
+ * The integer extra {@link #EXTRA_DISCONNECT_CAUSE} will indicate the reason for the call
+ * disconnection. See {@link #EXTRA_DISCONNECT_CAUSE} for more information.
+ *
+ * The integer extra {@link #EXTRA_CALL_DURATION} will indicate the duration of the call. See
+ * {@link #EXTRA_CALL_DURATION} for more information.
+ */
+ public static final String ACTION_POST_CALL = "android.telecom.action.POST_CALL";
+
+ /**
+ * A {@link Uri} extra, which when set on the {@link #ACTION_POST_CALL} intent, indicates the
+ * uri handle(phone number) of the completed call.
+ */
+ public static final String EXTRA_HANDLE = "android.telecom.extra.HANDLE";
+
+ /**
+ * A integer value provided for completed calls to indicate the reason for the call
+ * disconnection.
+ * <p>
+ * Allowed values:
+ * <ul>
+ * <li>{@link DisconnectCause#UNKNOWN}</li>
+ * <li>{@link DisconnectCause#LOCAL}</li>
+ * <li>{@link DisconnectCause#REMOTE}</li>
+ * <li>{@link DisconnectCause#REJECTED}</li>
+ * <li>{@link DisconnectCause#MISSED}</li>
+ * </ul>
+ * </p>
+ */
+ public static final String EXTRA_DISCONNECT_CAUSE = "android.telecom.extra.DISCONNECT_CAUSE";
+
+ /**
+ * A integer value provided for completed calls to indicate the duration of the call.
+ * <p>
+ * Allowed values:
+ * <ul>
+ * <li>{@link #DURATION_VERY_SHORT}</li>
+ * <li>{@link #DURATION_SHORT}</li>
+ * <li>{@link #DURATION_MEDIUM}</li>
+ * <li>{@link #DURATION_LONG}</li>
+ * </ul>
+ * </p>
+ */
+ public static final String EXTRA_CALL_DURATION = "android.telecom.extra.CALL_DURATION";
+
+ /**
+ * A integer value for {@link #EXTRA_CALL_DURATION}, indicates the duration of the completed
+ * call was < 3 seconds.
+ */
+ public static final int DURATION_VERY_SHORT = 0;
+
+ /**
+ * A integer value for {@link #EXTRA_CALL_DURATION}, indicates the duration of the completed
+ * call was >= 3 seconds and < 60 seconds.
+ */
+ public static final int DURATION_SHORT = 1;
+
+ /**
+ * A integer value for {@link #EXTRA_CALL_DURATION}, indicates the duration of the completed
+ * call was >= 60 seconds and < 120 seconds.
+ */
+ public static final int DURATION_MEDIUM = 2;
+
+ /**
+ * A integer value for {@link #EXTRA_CALL_DURATION}, indicates the duration of the completed
+ * call was >= 120 seconds.
+ */
+ public static final int DURATION_LONG = 3;
+
+ /**
+ * The threshold between {@link #DURATION_VERY_SHORT} calls and {@link #DURATION_SHORT} calls in
+ * milliseconds.
+ * @hide
+ */
+ public static final long VERY_SHORT_CALL_TIME_MS = 3000;
+
+ /**
+ * The threshold between {@link #DURATION_SHORT} calls and {@link #DURATION_MEDIUM} calls in
+ * milliseconds.
+ * @hide
+ */
+ public static final long SHORT_CALL_TIME_MS = 60000;
+
+ /**
+ * The threshold between {@link #DURATION_MEDIUM} calls and {@link #DURATION_LONG} calls in
+ * milliseconds.
+ * @hide
+ */
+ public static final long MEDIUM_CALL_TIME_MS = 120000;
+
+ /**
* A boolean meta-data value indicating whether an {@link InCallService} implements an
* in-call user interface. Dialer implementations (see {@link #getDefaultDialerPackage()}) which
* would also like to replace the in-call interface should set this meta-data to {@code true} in
diff --git a/telephony/common/com/android/internal/telephony/TelephonyPermissions.java b/telephony/common/com/android/internal/telephony/TelephonyPermissions.java
index 86630b0eb991..fbb1380efcc1 100644
--- a/telephony/common/com/android/internal/telephony/TelephonyPermissions.java
+++ b/telephony/common/com/android/internal/telephony/TelephonyPermissions.java
@@ -27,8 +27,6 @@ import android.content.pm.PackageManager;
import android.os.Binder;
import android.os.Build;
import android.os.Process;
-import android.os.RemoteException;
-import android.os.ServiceManager;
import android.os.UserHandle;
import android.telephony.Rlog;
import android.telephony.SubscriptionManager;
@@ -42,7 +40,6 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
-import java.util.function.Supplier;
/** Utility class for Telephony permission enforcement. */
public final class TelephonyPermissions {
@@ -50,9 +47,6 @@ public final class TelephonyPermissions {
private static final boolean DBG = false;
- private static final Supplier<ITelephony> TELEPHONY_SUPPLIER = () ->
- ITelephony.Stub.asInterface(ServiceManager.getService(Context.TELEPHONY_SERVICE));
-
/**
* Whether to disable the new device identifier access restrictions.
*/
@@ -138,49 +132,6 @@ public final class TelephonyPermissions {
public static boolean checkReadPhoneState(
Context context, int subId, int pid, int uid, String callingPackage,
@Nullable String callingFeatureId, String message) {
- return checkReadPhoneState(
- context, TELEPHONY_SUPPLIER, subId, pid, uid, callingPackage, callingFeatureId,
- message);
- }
-
- /**
- * Check whether the calling packages has carrier privileges for the passing subscription.
- * @return {@code true} if the caller has carrier privileges, {@false} otherwise.
- */
- public static boolean checkCarrierPrivilegeForSubId(int subId) {
- if (SubscriptionManager.isValidSubscriptionId(subId)
- && getCarrierPrivilegeStatus(TELEPHONY_SUPPLIER, subId, Binder.getCallingUid())
- == TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS) {
- return true;
- }
- return false;
- }
-
- /**
- * Check whether the app with the given pid/uid can read phone state.
- *
- * <p>This method behaves in one of the following ways:
- * <ul>
- * <li>return true: if the caller has the READ_PRIVILEGED_PHONE_STATE permission, the
- * READ_PHONE_STATE runtime permission, or carrier privileges on the given subId.
- * <li>throw SecurityException: if the caller didn't declare any of these permissions, or, for
- * apps which support runtime permissions, if the caller does not currently have any of
- * these permissions.
- * <li>return false: if the caller lacks all of these permissions and doesn't support runtime
- * permissions. This implies that the user revoked the ability to read phone state
- * manually (via AppOps). In this case we can't throw as it would break app compatibility,
- * so we return false to indicate that the calling function should return dummy data.
- * </ul>
- *
- * <p>Note: for simplicity, this method always returns false for callers using legacy
- * permissions and who have had READ_PHONE_STATE revoked, even if they are carrier-privileged.
- * Such apps should migrate to runtime permissions or stop requiring READ_PHONE_STATE on P+
- * devices.
- */
- @VisibleForTesting
- public static boolean checkReadPhoneState(
- Context context, Supplier<ITelephony> telephonySupplier, int subId, int pid, int uid,
- String callingPackage, @Nullable String callingFeatureId, String message) {
try {
context.enforcePermission(
android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, pid, uid, message);
@@ -195,7 +146,7 @@ public final class TelephonyPermissions {
// If we don't have the runtime permission, but do have carrier privileges, that
// suffices for reading phone state.
if (SubscriptionManager.isValidSubscriptionId(subId)) {
- enforceCarrierPrivilege(telephonySupplier, subId, uid, message);
+ enforceCarrierPrivilege(context, subId, uid, message);
return true;
}
throw phoneStateException;
@@ -210,23 +161,16 @@ public final class TelephonyPermissions {
}
/**
- * Check whether the app with the given pid/uid can read phone state, or has carrier
- * privileges on any active subscription.
- *
- * <p>If the app does not have carrier privilege, this method will return {@code false} instead
- * of throwing a SecurityException. Therefore, the callers cannot tell the difference
- * between M+ apps which declare the runtime permission but do not have it, and pre-M apps
- * which declare the static permission but had access revoked via AppOps. Apps in the former
- * category expect SecurityExceptions; apps in the latter don't. So this method is suitable for
- * use only if the behavior in both scenarios is meant to be identical.
- *
- * @return {@code true} if the app can read phone state or has carrier privilege;
- * {@code false} otherwise.
+ * Check whether the calling packages has carrier privileges for the passing subscription.
+ * @return {@code true} if the caller has carrier privileges, {@false} otherwise.
*/
- public static boolean checkReadPhoneStateOnAnyActiveSub(Context context, int pid, int uid,
- String callingPackage, @Nullable String callingFeatureId, String message) {
- return checkReadPhoneStateOnAnyActiveSub(context, TELEPHONY_SUPPLIER, pid, uid,
- callingPackage, callingFeatureId, message);
+ public static boolean checkCarrierPrivilegeForSubId(Context context, int subId) {
+ if (SubscriptionManager.isValidSubscriptionId(subId)
+ && getCarrierPrivilegeStatus(context, subId, Binder.getCallingUid())
+ == TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS) {
+ return true;
+ }
+ return false;
}
/**
@@ -243,9 +187,7 @@ public final class TelephonyPermissions {
* @return {@code true} if the app can read phone state or has carrier privilege;
* {@code false} otherwise.
*/
- @VisibleForTesting
- public static boolean checkReadPhoneStateOnAnyActiveSub(
- Context context, Supplier<ITelephony> telephonySupplier, int pid, int uid,
+ public static boolean checkReadPhoneStateOnAnyActiveSub(Context context, int pid, int uid,
String callingPackage, @Nullable String callingFeatureId, String message) {
try {
context.enforcePermission(
@@ -260,7 +202,7 @@ public final class TelephonyPermissions {
} catch (SecurityException phoneStateException) {
// If we don't have the runtime permission, but do have carrier privileges, that
// suffices for reading phone state.
- return checkCarrierPrivilegeForAnySubId(context, telephonySupplier, uid);
+ return checkCarrierPrivilegeForAnySubId(context, uid);
}
}
@@ -375,12 +317,11 @@ public final class TelephonyPermissions {
}
// If the calling package has carrier privileges for specified sub, then allow access.
- if (checkCarrierPrivilegeForSubId(subId)) return true;
+ if (checkCarrierPrivilegeForSubId(context, subId)) return true;
// If the calling package has carrier privileges for any subscription
// and allowCarrierPrivilegeOnAnySub is set true, then allow access.
- if (allowCarrierPrivilegeOnAnySub && checkCarrierPrivilegeForAnySubId(
- context, TELEPHONY_SUPPLIER, uid)) {
+ if (allowCarrierPrivilegeOnAnySub && checkCarrierPrivilegeForAnySubId(context, uid)) {
return true;
}
@@ -468,7 +409,7 @@ public final class TelephonyPermissions {
uid) == PackageManager.PERMISSION_GRANTED) {
return false;
}
- if (checkCarrierPrivilegeForSubId(subId)) {
+ if (checkCarrierPrivilegeForSubId(context, subId)) {
return false;
}
}
@@ -484,26 +425,12 @@ public final class TelephonyPermissions {
public static boolean checkReadCallLog(
Context context, int subId, int pid, int uid, String callingPackage,
@Nullable String callingPackageName) {
- return checkReadCallLog(
- context, TELEPHONY_SUPPLIER, subId, pid, uid, callingPackage, callingPackageName);
- }
-
- /**
- * Check whether the app with the given pid/uid can read the call log.
- * @return {@code true} if the specified app has the read call log permission and AppOpp granted
- * to it, {@code false} otherwise.
- */
- @VisibleForTesting
- public static boolean checkReadCallLog(
- Context context, Supplier<ITelephony> telephonySupplier, int subId, int pid, int uid,
- String callingPackage, @Nullable String callingFeatureId) {
-
if (context.checkPermission(Manifest.permission.READ_CALL_LOG, pid, uid)
!= PERMISSION_GRANTED) {
// If we don't have the runtime permission, but do have carrier privileges, that
// suffices for being able to see the call phone numbers.
if (SubscriptionManager.isValidSubscriptionId(subId)) {
- enforceCarrierPrivilege(telephonySupplier, subId, uid, "readCallLog");
+ enforceCarrierPrivilege(context, subId, uid, "readCallLog");
return true;
}
return false;
@@ -513,7 +440,7 @@ public final class TelephonyPermissions {
// revoked.
AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
return appOps.noteOp(AppOpsManager.OPSTR_READ_CALL_LOG, uid, callingPackage,
- callingFeatureId, null) == AppOpsManager.MODE_ALLOWED;
+ callingPackageName, null) == AppOpsManager.MODE_ALLOWED;
}
/**
@@ -526,7 +453,7 @@ public final class TelephonyPermissions {
Context context, int subId, String callingPackage, @Nullable String callingFeatureId,
String message) {
return checkReadPhoneNumber(
- context, TELEPHONY_SUPPLIER, subId, Binder.getCallingPid(), Binder.getCallingUid(),
+ context, subId, Binder.getCallingPid(), Binder.getCallingUid(),
callingPackage, callingFeatureId, message);
}
@@ -538,7 +465,7 @@ public final class TelephonyPermissions {
*/
@VisibleForTesting
public static boolean checkReadPhoneNumber(
- Context context, Supplier<ITelephony> telephonySupplier, int subId, int pid, int uid,
+ Context context, int subId, int pid, int uid,
String callingPackage, @Nullable String callingFeatureId, String message) {
// Default SMS app can always read it.
AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
@@ -553,7 +480,7 @@ public final class TelephonyPermissions {
// First, check if we can read the phone state.
try {
return checkReadPhoneState(
- context, telephonySupplier, subId, pid, uid, callingPackage, callingFeatureId,
+ context, subId, pid, uid, callingPackage, callingFeatureId,
message);
} catch (SecurityException readPhoneStateSecurityException) {
}
@@ -595,7 +522,7 @@ public final class TelephonyPermissions {
}
if (DBG) Rlog.d(LOG_TAG, "No modify permission, check carrier privilege next.");
- enforceCallingOrSelfCarrierPrivilege(subId, message);
+ enforceCallingOrSelfCarrierPrivilege(context, subId, message);
}
/**
@@ -615,7 +542,7 @@ public final class TelephonyPermissions {
Rlog.d(LOG_TAG, "No READ_PHONE_STATE permission, check carrier privilege next.");
}
- enforceCallingOrSelfCarrierPrivilege(subId, message);
+ enforceCallingOrSelfCarrierPrivilege(context, subId, message);
}
/**
@@ -636,7 +563,7 @@ public final class TelephonyPermissions {
+ "check carrier privilege next.");
}
- enforceCallingOrSelfCarrierPrivilege(subId, message);
+ enforceCallingOrSelfCarrierPrivilege(context, subId, message);
}
/**
@@ -644,21 +571,18 @@ public final class TelephonyPermissions {
*
* @throws SecurityException if the caller does not have the required privileges
*/
- public static void enforceCallingOrSelfCarrierPrivilege(int subId, String message) {
+ public static void enforceCallingOrSelfCarrierPrivilege(
+ Context context, int subId, String message) {
// NOTE: It's critical that we explicitly pass the calling UID here rather than call
// TelephonyManager#hasCarrierPrivileges directly, as the latter only works when called from
// the phone process. When called from another process, it will check whether that process
// has carrier privileges instead.
- enforceCarrierPrivilege(subId, Binder.getCallingUid(), message);
- }
-
- private static void enforceCarrierPrivilege(int subId, int uid, String message) {
- enforceCarrierPrivilege(TELEPHONY_SUPPLIER, subId, uid, message);
+ enforceCarrierPrivilege(context, subId, Binder.getCallingUid(), message);
}
private static void enforceCarrierPrivilege(
- Supplier<ITelephony> telephonySupplier, int subId, int uid, String message) {
- if (getCarrierPrivilegeStatus(telephonySupplier, subId, uid)
+ Context context, int subId, int uid, String message) {
+ if (getCarrierPrivilegeStatus(context, subId, uid)
!= TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS) {
if (DBG) Rlog.e(LOG_TAG, "No Carrier Privilege.");
throw new SecurityException(message);
@@ -666,13 +590,12 @@ public final class TelephonyPermissions {
}
/** Returns whether the provided uid has carrier privileges for any active subscription ID. */
- private static boolean checkCarrierPrivilegeForAnySubId(
- Context context, Supplier<ITelephony> telephonySupplier, int uid) {
+ private static boolean checkCarrierPrivilegeForAnySubId(Context context, int uid) {
SubscriptionManager sm = (SubscriptionManager) context.getSystemService(
Context.TELEPHONY_SUBSCRIPTION_SERVICE);
int[] activeSubIds = sm.getActiveSubscriptionIdList(/* visibleOnly */ false);
for (int activeSubId : activeSubIds) {
- if (getCarrierPrivilegeStatus(telephonySupplier, activeSubId, uid)
+ if (getCarrierPrivilegeStatus(context, activeSubId, uid)
== TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS) {
return true;
}
@@ -680,18 +603,15 @@ public final class TelephonyPermissions {
return false;
}
- private static int getCarrierPrivilegeStatus(
- Supplier<ITelephony> telephonySupplier, int subId, int uid) {
- ITelephony telephony = telephonySupplier.get();
+ private static int getCarrierPrivilegeStatus(Context context, int subId, int uid) {
+ final long identity = Binder.clearCallingIdentity();
try {
- if (telephony != null) {
- return telephony.getCarrierPrivilegeStatusForUid(subId, uid);
- }
- } catch (RemoteException e) {
- // Fallback below.
+ TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(
+ Context.TELEPHONY_SERVICE);
+ return telephonyManager.createForSubscriptionId(subId).getCarrierPrivilegeStatus(uid);
+ } finally {
+ Binder.restoreCallingIdentity(identity);
}
- Rlog.e(LOG_TAG, "Phone process is down, cannot check carrier privileges");
- return TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
}
/**
diff --git a/telephony/java/android/telephony/Annotation.java b/telephony/java/android/telephony/Annotation.java
index f89bbc7d179a..3940a3b0a1cf 100644
--- a/telephony/java/android/telephony/Annotation.java
+++ b/telephony/java/android/telephony/Annotation.java
@@ -116,7 +116,8 @@ public class Annotation {
ApnSetting.TYPE_CBS,
ApnSetting.TYPE_IA,
ApnSetting.TYPE_EMERGENCY,
- ApnSetting.TYPE_MCX
+ ApnSetting.TYPE_MCX,
+ ApnSetting.TYPE_XCAP,
})
@Retention(RetentionPolicy.SOURCE)
public @interface ApnType {
@@ -463,9 +464,7 @@ public class Annotation {
DataFailCause.UNKNOWN,
DataFailCause.RADIO_NOT_AVAILABLE,
DataFailCause.UNACCEPTABLE_NETWORK_PARAMETER,
- DataFailCause.CONNECTION_TO_DATACONNECTIONAC_BROKEN,
DataFailCause.LOST_CONNECTION,
- DataFailCause.RESET_BY_FRAMEWORK
})
@Retention(RetentionPolicy.SOURCE)
public @interface DataFailureCause {
diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java
index 91646add6964..7381acb36812 100755
--- a/telephony/java/android/telephony/CarrierConfigManager.java
+++ b/telephony/java/android/telephony/CarrierConfigManager.java
@@ -419,12 +419,33 @@ public class CarrierConfigManager {
KEY_GSM_NONROAMING_NETWORKS_STRING_ARRAY = "gsm_nonroaming_networks_string_array";
/**
- * Override the device's configuration for the ImsService to use for this SIM card.
+ * The package name containing the ImsService that will be bound to the telephony framework to
+ * support both IMS MMTEL and RCS feature functionality instead of the device default
+ * ImsService for this subscription.
+ * @deprecated Use {@link #KEY_CONFIG_IMS_MMTEL_PACKAGE_OVERRIDE_STRING} and
+ * {@link #KEY_CONFIG_IMS_RCS_PACKAGE_OVERRIDE_STRING} instead to configure these values
+ * separately. If any of those values are not empty, they will override this value.
*/
public static final String KEY_CONFIG_IMS_PACKAGE_OVERRIDE_STRING =
"config_ims_package_override_string";
/**
+ * The package name containing the ImsService that will be bound to the telephony framework to
+ * support IMS MMTEL feature functionality instead of the device default ImsService for this
+ * subscription.
+ */
+ public static final String KEY_CONFIG_IMS_MMTEL_PACKAGE_OVERRIDE_STRING =
+ "config_ims_mmtel_package_override_string";
+
+ /**
+ * The package name containing the ImsService that will be bound to the telephony framework to
+ * support IMS RCS feature functionality instead of the device default ImsService for this
+ * subscription.
+ */
+ public static final String KEY_CONFIG_IMS_RCS_PACKAGE_OVERRIDE_STRING =
+ "config_ims_rcs_package_override_string";
+
+ /**
* Override the package that will manage {@link SubscriptionPlan}
* information instead of the {@link CarrierService} that defines this
* value.
@@ -1052,9 +1073,6 @@ public class CarrierConfigManager {
*
* When {@code false}, the old behavior is used, where the toggle in accessibility settings is
* used to set the IMS stack's RTT enabled state.
- *
- * @deprecated -- this flag no longer does anything. Remove once the new behavior is verified.
- *
* @hide
*/
public static final String KEY_IGNORE_RTT_MODE_SETTING_BOOL =
@@ -1949,6 +1967,12 @@ public class CarrierConfigManager {
"allow_add_call_during_video_call";
/**
+ * When false, indicates that holding a video call is disabled
+ */
+ public static final String KEY_ALLOW_HOLDING_VIDEO_CALL_BOOL =
+ "allow_holding_video_call";
+
+ /**
* When true, indicates that the HD audio icon in the in-call screen should not be shown for
* VoWifi calls.
* @hide
@@ -2092,12 +2116,6 @@ public class CarrierConfigManager {
"allow_metered_network_for_cert_download_bool";
/**
- * Carrier specified WiFi networks.
- * @hide
- */
- public static final String KEY_CARRIER_WIFI_STRING_ARRAY = "carrier_wifi_string_array";
-
- /**
* Time delay (in ms) after which we show the notification to switch the preferred
* network.
* @hide
@@ -2185,7 +2203,7 @@ public class CarrierConfigManager {
* the start of the next month.
* <p>
* This setting may be still overridden by explicit user choice. By default,
- * the platform value will be used.
+ * {@link #DATA_CYCLE_USE_PLATFORM_DEFAULT} will be used.
*/
public static final String KEY_MONTHLY_DATA_CYCLE_DAY_INT =
"monthly_data_cycle_day_int";
@@ -2194,10 +2212,7 @@ public class CarrierConfigManager {
* When {@link #KEY_MONTHLY_DATA_CYCLE_DAY_INT}, {@link #KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG},
* or {@link #KEY_DATA_WARNING_THRESHOLD_BYTES_LONG} are set to this value, the platform default
* value will be used for that key.
- *
- * @hide
*/
- @Deprecated
public static final int DATA_CYCLE_USE_PLATFORM_DEFAULT = -1;
/**
@@ -2221,8 +2236,8 @@ public class CarrierConfigManager {
* If the value is set to {@link #DATA_CYCLE_THRESHOLD_DISABLED}, the data usage warning will
* be disabled.
* <p>
- * This setting may be overridden by explicit user choice. By default, the platform value
- * will be used.
+ * This setting may be overridden by explicit user choice. By default,
+ * {@link #DATA_CYCLE_USE_PLATFORM_DEFAULT} will be used.
*/
public static final String KEY_DATA_WARNING_THRESHOLD_BYTES_LONG =
"data_warning_threshold_bytes_long";
@@ -2230,8 +2245,7 @@ public class CarrierConfigManager {
/**
* Controls if the device should automatically notify the user as they reach
* their cellular data warning. When set to {@code false} the carrier is
- * expected to have implemented their own notification mechanism.
- * @hide
+ * expected to have implemented their own notification mechanism. {@code true} by default.
*/
public static final String KEY_DATA_WARNING_NOTIFICATION_BOOL =
"data_warning_notification_bool";
@@ -2253,8 +2267,8 @@ public class CarrierConfigManager {
* phone. If the value is set to {@link #DATA_CYCLE_THRESHOLD_DISABLED}, the data limit will be
* disabled.
* <p>
- * This setting may be overridden by explicit user choice. By default, the platform value
- * will be used.
+ * This setting may be overridden by explicit user choice. By default,
+ * {@link #DATA_CYCLE_USE_PLATFORM_DEFAULT} will be used.
*/
public static final String KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG =
"data_limit_threshold_bytes_long";
@@ -2262,8 +2276,7 @@ public class CarrierConfigManager {
/**
* Controls if the device should automatically notify the user as they reach
* their cellular data limit. When set to {@code false} the carrier is
- * expected to have implemented their own notification mechanism.
- * @hide
+ * expected to have implemented their own notification mechanism. {@code true} by default.
*/
public static final String KEY_DATA_LIMIT_NOTIFICATION_BOOL =
"data_limit_notification_bool";
@@ -2271,8 +2284,7 @@ public class CarrierConfigManager {
/**
* Controls if the device should automatically notify the user when rapid
* cellular data usage is observed. When set to {@code false} the carrier is
- * expected to have implemented their own notification mechanism.
- * @hide
+ * expected to have implemented their own notification mechanism. {@code true} by default.
*/
public static final String KEY_DATA_RAPID_NOTIFICATION_BOOL =
"data_rapid_notification_bool";
@@ -3046,7 +3058,6 @@ public class CarrierConfigManager {
/**
* Location information during (and after) an emergency call is only provided over control
* plane signaling from the network.
- * @hide
*/
public static final int SUPL_EMERGENCY_MODE_TYPE_CP_ONLY = 0;
@@ -3054,7 +3065,6 @@ public class CarrierConfigManager {
* Location information during (and after) an emergency call is provided over the data
* plane and serviced by the framework GNSS service, but if it fails, the carrier also
* supports control plane backup signaling.
- * @hide
*/
public static final int SUPL_EMERGENCY_MODE_TYPE_CP_FALLBACK = 1;
@@ -3062,7 +3072,6 @@ public class CarrierConfigManager {
* Location information during (and after) an emergency call is provided over the data plane
* and serviced by the framework GNSS service only. There is no backup signalling over the
* control plane if it fails.
- * @hide
*/
public static final int SUPL_EMERGENCY_MODE_TYPE_DP_ONLY = 2;
@@ -3169,11 +3178,21 @@ public class CarrierConfigManager {
* {@link #SUPL_EMERGENCY_MODE_TYPE_CP_ONLY}.
* <p>
* The default value for this configuration is {@link #SUPL_EMERGENCY_MODE_TYPE_CP_ONLY}.
- * @hide
*/
public static final String KEY_ES_SUPL_CONTROL_PLANE_SUPPORT_INT = KEY_PREFIX
+ "es_supl_control_plane_support_int";
+ /**
+ * A list of roaming PLMNs where SUPL ES mode does not support a control-plane mechanism to
+ * get a user's location in the event that data plane SUPL fails or is otherwise
+ * unavailable.
+ * <p>
+ * A string array of PLMNs that do not support a control-plane mechanism for getting a
+ * user's location for SUPL ES.
+ */
+ public static final String KEY_ES_SUPL_DATA_PLANE_ONLY_ROAMING_PLMN_STRING_ARRAY =
+ KEY_PREFIX + "es_supl_data_plane_only_roaming_plmn_string_array";
+
private static PersistableBundle getDefaults() {
PersistableBundle defaults = new PersistableBundle();
defaults.putBoolean(KEY_PERSIST_LPP_MODE_BOOL, true);
@@ -3190,63 +3209,11 @@ public class CarrierConfigManager {
defaults.putString(KEY_NFW_PROXY_APPS_STRING, "");
defaults.putInt(KEY_ES_SUPL_CONTROL_PLANE_SUPPORT_INT,
SUPL_EMERGENCY_MODE_TYPE_CP_ONLY);
+ defaults.putStringArray(KEY_ES_SUPL_DATA_PLANE_ONLY_ROAMING_PLMN_STRING_ARRAY, null);
return defaults;
}
}
- /**
- * Wi-Fi configs used in Carrier Wi-Fi application.
- *
- * @hide
- */
- @SystemApi
- public static final class Wifi {
- /** Prefix of all Wifi.KEY_* constants. */
- public static final String KEY_PREFIX = "wifi.";
-
- /**
- * Whenever any information under wifi namespace is changed, the version should be
- * incremented by 1 so that the device is able to figure out the latest profiles based on
- * the version.
- */
- public static final String KEY_CARRIER_PROFILES_VERSION_INT =
- KEY_PREFIX + "carrier_profiles_version_int";
-
- /**
- * It contains the package name of connection manager that the carrier owns.
- *
- * <P>Once it is installed, the profiles installed by Carrier Wi-Fi Application
- * will be deleted.
- * Once it is uninstalled, Carrier Wi-Fi Application will re-install the latest profiles.
- */
- public static final String KEY_CARRIER_CONNECTION_MANAGER_PACKAGE_STRING =
- KEY_PREFIX + "carrier_connection_manager_package_string";
- /**
- * It is to have the list of wifi networks profiles which contain the information about
- * the wifi-networks to which carrier wants the device to connect.
- */
- public static final String KEY_NETWORK_PROFILES_STRING_ARRAY =
- KEY_PREFIX + "network_profiles_string_array";
-
- /**
- * It is to have the list of Passpoint profiles which contain the information about
- * the Passpoint networks to which carrier wants the device to connect.
- */
- public static final String KEY_PASSPOINT_PROFILES_STRING_ARRAY =
- KEY_PREFIX + "passpoint_profiles_string_array";
-
- private static PersistableBundle getDefaults() {
- PersistableBundle defaults = new PersistableBundle();
- defaults.putInt(KEY_CARRIER_PROFILES_VERSION_INT, -1);
- defaults.putString(KEY_CARRIER_CONNECTION_MANAGER_PACKAGE_STRING, null);
- defaults.putStringArray(KEY_NETWORK_PROFILES_STRING_ARRAY, null);
- defaults.putStringArray(KEY_PASSPOINT_PROFILES_STRING_ARRAY, null);
- return defaults;
- }
-
- private Wifi() {}
- }
-
/**
* An int array containing CDMA enhanced roaming indicator values for Home (non-roaming) network.
* The default values come from 3GPP2 C.R1001 table 8.1-1.
@@ -3540,6 +3507,8 @@ public class CarrierConfigManager {
sDefaults.putStringArray(KEY_GSM_ROAMING_NETWORKS_STRING_ARRAY, null);
sDefaults.putStringArray(KEY_GSM_NONROAMING_NETWORKS_STRING_ARRAY, null);
sDefaults.putString(KEY_CONFIG_IMS_PACKAGE_OVERRIDE_STRING, null);
+ sDefaults.putString(KEY_CONFIG_IMS_MMTEL_PACKAGE_OVERRIDE_STRING, null);
+ sDefaults.putString(KEY_CONFIG_IMS_RCS_PACKAGE_OVERRIDE_STRING, null);
sDefaults.putStringArray(KEY_CDMA_ROAMING_NETWORKS_STRING_ARRAY, null);
sDefaults.putStringArray(KEY_CDMA_NONROAMING_NETWORKS_STRING_ARRAY, null);
sDefaults.putStringArray(KEY_DIAL_STRING_REPLACE_STRING_ARRAY, null);
@@ -3548,7 +3517,7 @@ public class CarrierConfigManager {
sDefaults.putInt(KEY_IMS_DTMF_TONE_DELAY_INT, 0);
sDefaults.putInt(KEY_CDMA_DTMF_TONE_DELAY_INT, 100);
sDefaults.putBoolean(KEY_CALL_FORWARDING_MAP_NON_NUMBER_TO_VOICEMAIL_BOOL, false);
- sDefaults.putBoolean(KEY_IGNORE_RTT_MODE_SETTING_BOOL, true);
+ sDefaults.putBoolean(KEY_IGNORE_RTT_MODE_SETTING_BOOL, false);
sDefaults.putInt(KEY_CDMA_3WAYCALL_FLASH_DELAY_INT , 0);
sDefaults.putBoolean(KEY_SUPPORT_CONFERENCE_CALL_BOOL, true);
sDefaults.putBoolean(KEY_SUPPORT_IMS_CONFERENCE_CALL_BOOL, true);
@@ -3683,6 +3652,7 @@ public class CarrierConfigManager {
sDefaults.putBoolean(KEY_DROP_VIDEO_CALL_WHEN_ANSWERING_AUDIO_CALL_BOOL, false);
sDefaults.putBoolean(KEY_ALLOW_MERGE_WIFI_CALLS_WHEN_VOWIFI_OFF_BOOL, true);
sDefaults.putBoolean(KEY_ALLOW_ADD_CALL_DURING_VIDEO_CALL_BOOL, true);
+ sDefaults.putBoolean(KEY_ALLOW_HOLDING_VIDEO_CALL_BOOL, true);
sDefaults.putBoolean(KEY_WIFI_CALLS_CAN_BE_HD_AUDIO, true);
sDefaults.putBoolean(KEY_VIDEO_CALLS_CAN_BE_HD_AUDIO, true);
sDefaults.putBoolean(KEY_GSM_CDMA_CALLS_CAN_BE_HD_AUDIO, false);
@@ -3699,7 +3669,6 @@ public class CarrierConfigManager {
sDefaults.putBoolean(KEY_STK_DISABLE_LAUNCH_BROWSER_BOOL, false);
sDefaults.putBoolean(KEY_ALLOW_METERED_NETWORK_FOR_CERT_DOWNLOAD_BOOL, false);
sDefaults.putBoolean(KEY_HIDE_DIGITS_HELPER_TEXT_ON_STK_INPUT_SCREEN_BOOL, true);
- sDefaults.putStringArray(KEY_CARRIER_WIFI_STRING_ARRAY, null);
sDefaults.putInt(KEY_PREF_NETWORK_NOTIFICATION_DELAY_INT, -1);
sDefaults.putInt(KEY_EMERGENCY_NOTIFICATION_DELAY_INT, -1);
sDefaults.putBoolean(KEY_ALLOW_USSD_REQUESTS_VIA_TELEPHONY_MANAGER_BOOL, true);
@@ -3828,7 +3797,6 @@ public class CarrierConfigManager {
/* Default value is 60 seconds. */
sDefaults.putLong(KEY_OPPORTUNISTIC_NETWORK_MAX_BACKOFF_TIME_LONG, 60000);
sDefaults.putAll(Gps.getDefaults());
- sDefaults.putAll(Wifi.getDefaults());
sDefaults.putIntArray(KEY_CDMA_ENHANCED_ROAMING_INDICATOR_FOR_HOME_NETWORK_INT_ARRAY,
new int[] {
1 /* Roaming Indicator Off */
diff --git a/telephony/java/android/telephony/CbGeoUtils.java b/telephony/java/android/telephony/CbGeoUtils.java
index ce5e3f38e78b..7314edda8f16 100644
--- a/telephony/java/android/telephony/CbGeoUtils.java
+++ b/telephony/java/android/telephony/CbGeoUtils.java
@@ -18,19 +18,25 @@ package android.telephony;
import android.annotation.NonNull;
import android.annotation.SystemApi;
-import android.os.Build;
import android.text.TextUtils;
+import com.android.internal.telephony.util.TelephonyUtils;
+
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
- * This utils class is specifically used for geo-targeting of CellBroadcast messages.
+ * This utils class is used for geo-fencing of CellBroadcast messages and is used by the cell
+ * broadcast module.
+ *
* The coordinates used by this utils class are latitude and longitude, but some algorithms in this
* class only use them as coordinates on plane, so the calculation will be inaccurate. So don't use
* this class for anything other then geo-targeting of cellbroadcast messages.
+ *
+ * More information regarding cell broadcast geo-fencing logic is laid out in 3GPP TS 23.041 and
+ * ATIS-0700041.
* @hide
*/
@SystemApi
@@ -81,7 +87,7 @@ public class CbGeoUtils {
/** @hide */
private static final String POLYGON_SYMBOL = "polygon";
- /** Point represent by (latitude, longitude). */
+ /** A point represented by (latitude, longitude). */
public static class LatLng {
public final double lat;
public final double lng;
@@ -97,8 +103,8 @@ public class CbGeoUtils {
}
/**
- * @param p the point use to calculate the subtraction result.
- * @return the result of this point subtract the given point {@code p}.
+ * @param p the point to subtract
+ * @return the result of the subtraction
*/
@NonNull
public LatLng subtract(@NonNull LatLng p) {
@@ -106,9 +112,9 @@ public class CbGeoUtils {
}
/**
- * Calculate the distance in meter between this point and the given point {@code p}.
- * @param p the point use to calculate the distance.
- * @return the distance in meter.
+ * Calculate the distance in meters between this point and the given point {@code p}.
+ * @param p the point used to calculate the distance.
+ * @return the distance in meters.
*/
public double distance(@NonNull LatLng p) {
double dlat = Math.sin(0.5 * Math.toRadians(lat - p.lat));
@@ -125,8 +131,9 @@ public class CbGeoUtils {
}
/**
- * The class represents a simple polygon with at least 3 points.
- * @hide
+ * A class representing a simple polygon with at least 3 points. This is used for geo-fencing
+ * logic with cell broadcasts. More information regarding cell broadcast geo-fencing logic is
+ * laid out in 3GPP TS 23.041 and ATIS-0700041.
*/
public static class Polygon implements Geometry {
/**
@@ -145,7 +152,7 @@ public class CbGeoUtils {
* connected to form an edge of the polygon. The polygon has at least 3 vertices, and the
* last vertices and the first vertices must be adjacent.
*
- * The longitude difference in the vertices should be less than 180 degree.
+ * The longitude difference in the vertices should be less than 180 degrees.
*/
public Polygon(@NonNull List<LatLng> vertices) {
mVertices = vertices;
@@ -164,19 +171,24 @@ public class CbGeoUtils {
.collect(Collectors.toList());
}
- public List<LatLng> getVertices() {
+ /**
+ * Return the list of vertices which compose the polygon.
+ */
+ public @NonNull List<LatLng> getVertices() {
return mVertices;
}
/**
- * Check if the given point {@code p} is inside the polygon. This method counts the number
- * of times the polygon winds around the point P, A.K.A "winding number". The point is
- * outside only when this "winding number" is 0.
+ * Check if the given LatLng is inside the polygon.
*
- * If a point is on the edge of the polygon, it is also considered to be inside the polygon.
+ * If a LatLng is on the edge of the polygon, it is also considered to be inside the
+ * polygon.
*/
@Override
- public boolean contains(LatLng latLng) {
+ public boolean contains(@NonNull LatLng latLng) {
+ // This method counts the number of times the polygon winds around the point P, A.K.A
+ // "winding number". The point is outside only when this "winding number" is 0.
+
Point p = convertAndScaleLatLng(latLng);
int n = mScaledVertices.size();
@@ -245,6 +257,7 @@ public class CbGeoUtils {
return a.x * b.y - a.y * b.x;
}
+ /** @hide */
static final class Point {
public final double x;
public final double y;
@@ -262,7 +275,7 @@ public class CbGeoUtils {
@Override
public String toString() {
String str = "Polygon: ";
- if (Build.IS_DEBUGGABLE) {
+ if (TelephonyUtils.IS_DEBUGGABLE) {
str += mVertices;
}
return str;
@@ -270,35 +283,53 @@ public class CbGeoUtils {
}
/**
- * The class represents a circle.
- * @hide
+ * A class represents a {@link Geometry} in the shape of a Circle. This is used for handling
+ * geo-fenced cell broadcasts. More information regarding cell broadcast geo-fencing logic is
+ * laid out in 3GPP TS 23.041 and ATIS-0700041.
*/
public static class Circle implements Geometry {
private final LatLng mCenter;
private final double mRadiusMeter;
- public Circle(LatLng center, double radiusMeter) {
+ /**
+ * Construct a Circle given a center point and a radius in meters.
+ *
+ * @param center the latitude and longitude of the center of the circle
+ * @param radiusInMeters the radius of the circle in meters
+ */
+ public Circle(@NonNull LatLng center, double radiusInMeters) {
this.mCenter = center;
- this.mRadiusMeter = radiusMeter;
+ this.mRadiusMeter = radiusInMeters;
}
- public LatLng getCenter() {
+ /**
+ * Return the latitude and longitude of the center of the circle;
+ */
+ public @NonNull LatLng getCenter() {
return mCenter;
}
+ /**
+ * Return the radius of the circle in meters.
+ */
public double getRadius() {
return mRadiusMeter;
}
+ /**
+ * Check if the given LatLng is inside the circle.
+ *
+ * If a LatLng is on the edge of the circle, it is also considered to be inside the circle.
+ */
@Override
- public boolean contains(LatLng p) {
- return mCenter.distance(p) <= mRadiusMeter;
+ public boolean contains(@NonNull LatLng latLng) {
+ return mCenter.distance(latLng) <= mRadiusMeter;
}
@Override
public String toString() {
String str = "Circle: ";
- if (Build.IS_DEBUGGABLE) {
+ if (TelephonyUtils.IS_DEBUGGABLE) {
str += mCenter + ", radius = " + mRadiusMeter;
}
diff --git a/telephony/java/android/telephony/DataFailCause.java b/telephony/java/android/telephony/DataFailCause.java
index 7bdf1f57f8b2..e1c4bef0dd65 100644
--- a/telephony/java/android/telephony/DataFailCause.java
+++ b/telephony/java/android/telephony/DataFailCause.java
@@ -950,14 +950,10 @@ public final class DataFailCause {
public static final int UNKNOWN = 0x10000;
/** Data fail due to radio not unavailable. */
public static final int RADIO_NOT_AVAILABLE = 0x10001; /* no retry */
- /** @hide */
+ /** Data fail due to unacceptable network parameter. */
public static final int UNACCEPTABLE_NETWORK_PARAMETER = 0x10002; /* no retry */
- /** @hide */
- public static final int CONNECTION_TO_DATACONNECTIONAC_BROKEN = 0x10003;
/** Data connection was lost. */
public static final int LOST_CONNECTION = 0x10004;
- /** @hide */
- public static final int RESET_BY_FRAMEWORK = 0x10005;
/**
* Data handover failed.
@@ -1361,10 +1357,7 @@ public final class DataFailCause {
sFailCauseMap.put(RADIO_NOT_AVAILABLE, "RADIO_NOT_AVAILABLE");
sFailCauseMap.put(UNACCEPTABLE_NETWORK_PARAMETER,
"UNACCEPTABLE_NETWORK_PARAMETER");
- sFailCauseMap.put(CONNECTION_TO_DATACONNECTIONAC_BROKEN,
- "CONNECTION_TO_DATACONNECTIONAC_BROKEN");
sFailCauseMap.put(LOST_CONNECTION, "LOST_CONNECTION");
- sFailCauseMap.put(RESET_BY_FRAMEWORK, "RESET_BY_FRAMEWORK");
}
private DataFailCause() {
diff --git a/telephony/java/android/telephony/ImsManager.java b/telephony/java/android/telephony/ImsManager.java
index 02d8be3ccfd5..39af34c0e0f0 100644
--- a/telephony/java/android/telephony/ImsManager.java
+++ b/telephony/java/android/telephony/ImsManager.java
@@ -16,7 +16,10 @@
package android.telephony.ims;
+import android.annotation.NonNull;
+import android.annotation.SystemApi;
import android.annotation.SystemService;
+import android.annotation.TestApi;
import android.content.Context;
import android.telephony.SubscriptionManager;
@@ -25,12 +28,15 @@ import android.telephony.SubscriptionManager;
*
* @hide
*/
+@SystemApi
+@TestApi
@SystemService(Context.TELEPHONY_IMS_SERVICE)
public class ImsManager {
private Context mContext;
- public ImsManager(Context context) {
+ /** @hide */
+ public ImsManager(@NonNull Context context) {
mContext = context;
}
@@ -41,6 +47,7 @@ public class ImsManager {
* @throws IllegalArgumentException if the subscription is invalid.
* @return a ImsRcsManager instance with the specific subscription ID.
*/
+ @NonNull
public ImsRcsManager getImsRcsManager(int subscriptionId) {
if (!SubscriptionManager.isValidSubscriptionId(subscriptionId)) {
throw new IllegalArgumentException("Invalid subscription ID: " + subscriptionId);
@@ -56,6 +63,7 @@ public class ImsManager {
* @throws IllegalArgumentException if the subscription is invalid.
* @return a ImsMmTelManager instance with the specific subscription ID.
*/
+ @NonNull
public ImsMmTelManager getImsMmTelManager(int subscriptionId) {
if (!SubscriptionManager.isValidSubscriptionId(subscriptionId)) {
throw new IllegalArgumentException("Invalid subscription ID: " + subscriptionId);
diff --git a/telephony/java/android/telephony/LocationAccessPolicy.java b/telephony/java/android/telephony/LocationAccessPolicy.java
index fe273b267e98..95aa101b8b2c 100644
--- a/telephony/java/android/telephony/LocationAccessPolicy.java
+++ b/telephony/java/android/telephony/LocationAccessPolicy.java
@@ -34,6 +34,8 @@ import android.os.UserManager;
import android.util.Log;
import android.widget.Toast;
+import com.android.internal.telephony.util.TelephonyUtils;
+
import java.util.List;
/**
@@ -174,7 +176,7 @@ public final class LocationAccessPolicy {
}
Log.e(TAG, errorMsg);
try {
- if (Build.IS_DEBUGGABLE) {
+ if (TelephonyUtils.IS_DEBUGGABLE) {
Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
}
} catch (Throwable t) {
diff --git a/telephony/java/android/telephony/ModemActivityInfo.java b/telephony/java/android/telephony/ModemActivityInfo.java
index 16fbae25199b..aebe78031ba2 100644
--- a/telephony/java/android/telephony/ModemActivityInfo.java
+++ b/telephony/java/android/telephony/ModemActivityInfo.java
@@ -205,10 +205,10 @@ public final class ModemActivityInfo implements Parcelable {
}
/**
+ * Indicate if the ModemActivityInfo is invalid due to modem's invalid reporting.
+ *
* @return {@code true} if this {@link ModemActivityInfo} record is valid,
* {@code false} otherwise.
- *
- * @hide
*/
public boolean isValid() {
for (TransmitPower powerInfo : getTransmitPowerInfo()) {
diff --git a/telephony/java/android/telephony/NetworkScanRequest.java b/telephony/java/android/telephony/NetworkScanRequest.java
index 465b6aa79d40..c8b8ffb9846b 100644
--- a/telephony/java/android/telephony/NetworkScanRequest.java
+++ b/telephony/java/android/telephony/NetworkScanRequest.java
@@ -20,10 +20,10 @@ import android.annotation.IntDef;
import android.os.Parcel;
import android.os.Parcelable;
-import java.util.ArrayList;
-import java.util.Arrays;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
+import java.util.ArrayList;
+import java.util.Arrays;
/**
* Defines a request to peform a network scan.
@@ -221,9 +221,15 @@ public final class NetworkScanRequest implements Parcelable {
private NetworkScanRequest(Parcel in) {
mScanType = in.readInt();
- mSpecifiers = (RadioAccessSpecifier[]) in.readParcelableArray(
- Object.class.getClassLoader(),
- RadioAccessSpecifier.class);
+ Parcelable[] tempSpecifiers = in.readParcelableArray(Object.class.getClassLoader());
+ if (tempSpecifiers != null) {
+ mSpecifiers = new RadioAccessSpecifier[tempSpecifiers.length];
+ for (int i = 0; i < tempSpecifiers.length; i++) {
+ mSpecifiers[i] = (RadioAccessSpecifier) tempSpecifiers[i];
+ }
+ } else {
+ mSpecifiers = null;
+ }
mSearchPeriodicity = in.readInt();
mMaxSearchTime = in.readInt();
mIncrementalResults = in.readBoolean();
diff --git a/telephony/java/android/telephony/PhoneNumberRange.java b/telephony/java/android/telephony/PhoneNumberRange.java
index e6f107e28c98..2b199d2df141 100644
--- a/telephony/java/android/telephony/PhoneNumberRange.java
+++ b/telephony/java/android/telephony/PhoneNumberRange.java
@@ -85,18 +85,18 @@ public final class PhoneNumberRange implements Parcelable {
}
private PhoneNumberRange(Parcel in) {
- mCountryCode = in.readStringNoHelper();
- mPrefix = in.readStringNoHelper();
- mLowerBound = in.readStringNoHelper();
- mUpperBound = in.readStringNoHelper();
+ mCountryCode = in.readString();
+ mPrefix = in.readString();
+ mLowerBound = in.readString();
+ mUpperBound = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
- dest.writeStringNoHelper(mCountryCode);
- dest.writeStringNoHelper(mPrefix);
- dest.writeStringNoHelper(mLowerBound);
- dest.writeStringNoHelper(mUpperBound);
+ dest.writeString(mCountryCode);
+ dest.writeString(mPrefix);
+ dest.writeString(mLowerBound);
+ dest.writeString(mUpperBound);
}
@Override
diff --git a/telephony/java/android/telephony/PreciseDataConnectionState.java b/telephony/java/android/telephony/PreciseDataConnectionState.java
index 257d634f1577..78ad5c58423c 100644
--- a/telephony/java/android/telephony/PreciseDataConnectionState.java
+++ b/telephony/java/android/telephony/PreciseDataConnectionState.java
@@ -19,8 +19,10 @@ package android.telephony;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
+import android.annotation.TestApi;
import android.annotation.UnsupportedAppUsage;
import android.net.LinkProperties;
+import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.telephony.Annotation.ApnType;
@@ -29,6 +31,8 @@ import android.telephony.Annotation.DataState;
import android.telephony.Annotation.NetworkType;
import android.telephony.data.ApnSetting;
+import dalvik.system.VMRuntime;
+
import java.util.Objects;
@@ -46,35 +50,62 @@ import java.util.Objects;
* <li>Data connection fail cause.
* </ul>
*
- * @hide
*/
-@SystemApi
public final class PreciseDataConnectionState implements Parcelable {
private @DataState int mState = TelephonyManager.DATA_UNKNOWN;
private @NetworkType int mNetworkType = TelephonyManager.NETWORK_TYPE_UNKNOWN;
private @DataFailureCause int mFailCause = DataFailCause.NONE;
- private @ApnType int mAPNTypes = ApnSetting.TYPE_NONE;
- private String mAPN = "";
+ private @ApnType int mApnTypes = ApnSetting.TYPE_NONE;
+ private String mApn = "";
private LinkProperties mLinkProperties = null;
+ private ApnSetting mApnSetting = null;
/**
* Constructor
*
+ * @deprecated this constructor has been superseded and should not be used.
* @hide
*/
- @UnsupportedAppUsage
+ @TestApi
+ @Deprecated
+ @UnsupportedAppUsage // (maxTargetSdk = Build.VERSION_CODES.Q)
+ // FIXME: figure out how to remove the UnsupportedAppUsage and delete this constructor
public PreciseDataConnectionState(@DataState int state,
@NetworkType int networkType,
- @ApnType int apnTypes, String apn,
- LinkProperties linkProperties,
+ @ApnType int apnTypes, @NonNull String apn,
+ @Nullable LinkProperties linkProperties,
@DataFailureCause int failCause) {
+ this(state, networkType, apnTypes, apn, linkProperties, failCause, null);
+ }
+
+
+ /**
+ * Constructor
+ *
+ * @param state the state of the data connection
+ * @param networkType the access network that is/would carry this data connection
+ * @param apnTypes the APN types that this data connection carries
+ * @param apnSetting if there is a valid APN for this Data Connection, then the APN Settings;
+ * if there is no valid APN setting for the specific type, then this will be null
+ * @param linkProperties if the data connection is connected, the properties of the connection
+ * @param failCause in case a procedure related to this data connection fails, a non-zero error
+ * code indicating the cause of the failure.
+ * @hide
+ */
+ public PreciseDataConnectionState(@DataState int state,
+ @NetworkType int networkType,
+ @ApnType int apnTypes, @NonNull String apn,
+ @Nullable LinkProperties linkProperties,
+ @DataFailureCause int failCause,
+ @Nullable ApnSetting apnSetting) {
mState = state;
mNetworkType = networkType;
- mAPNTypes = apnTypes;
- mAPN = apn;
+ mApnTypes = apnTypes;
+ mApn = apn;
mLinkProperties = linkProperties;
mFailCause = failCause;
+ mApnSetting = apnSetting;
}
/**
@@ -93,76 +124,160 @@ public final class PreciseDataConnectionState implements Parcelable {
private PreciseDataConnectionState(Parcel in) {
mState = in.readInt();
mNetworkType = in.readInt();
- mAPNTypes = in.readInt();
- mAPN = in.readString();
- mLinkProperties = (LinkProperties)in.readParcelable(null);
+ mApnTypes = in.readInt();
+ mApn = in.readString();
+ mLinkProperties = (LinkProperties) in.readParcelable(null);
mFailCause = in.readInt();
+ mApnSetting = (ApnSetting) in.readParcelable(null);
}
/**
* Returns the state of data connection that supported the apn types returned by
* {@link #getDataConnectionApnTypeBitMask()}
+ *
+ * @deprecated use {@link #getState()}
+ * @hide
*/
+ @Deprecated
+ @SystemApi
public @DataState int getDataConnectionState() {
+ if (mState == TelephonyManager.DATA_DISCONNECTING
+ && VMRuntime.getRuntime().getTargetSdkVersion() < Build.VERSION_CODES.R) {
+ return TelephonyManager.DATA_CONNECTED;
+ }
+
+ return mState;
+ }
+
+ /**
+ * Returns the high-level state of this data connection.
+ */
+ public @DataState int getState() {
return mState;
}
/**
* Returns the network type associated with this data connection.
+ *
+ * @deprecated use {@link getNetworkType()}
* @hide
*/
+ @Deprecated
+ @SystemApi
public @NetworkType int getDataConnectionNetworkType() {
return mNetworkType;
}
/**
- * Returns the data connection APN types supported by this connection and triggers
- * {@link PreciseDataConnectionState} change.
+ * Returns the network type associated with this data connection.
+ *
+ * Return the current/latest (radio) bearer technology that carries this data connection.
+ * For a variety of reasons, the network type can change during the life of the data
+ * connection, and this information is not reliable unless the physical link is currently
+ * active; (there is currently no mechanism to know whether the physical link is active at
+ * any given moment). Thus, this value is generally correct but may not be relied-upon to
+ * represent the status of the radio bearer at any given moment.
+ */
+ public @NetworkType int getNetworkType() {
+ return mNetworkType;
+ }
+
+ /**
+ * Returns the APN types mapped to this data connection.
+ *
+ * @deprecated use {@link #getApnSetting()}
+ * @hide
*/
+ @Deprecated
+ @SystemApi
public @ApnType int getDataConnectionApnTypeBitMask() {
- return mAPNTypes;
+ return mApnTypes;
}
/**
- * Returns APN {@link ApnSetting} of this data connection.
+ * Returns APN of this data connection.
+ *
+ * @deprecated use {@link #getApnSetting()}
+ * @hide
*/
- @Nullable
+ @NonNull
+ @SystemApi
+ @Deprecated
public String getDataConnectionApn() {
- return mAPN;
+ return mApn;
}
/**
* Get the properties of the network link {@link LinkProperties}.
+ *
+ * @deprecated use {@link #getLinkProperties()}
* @hide
*/
- @UnsupportedAppUsage
+ @Deprecated
+ @SystemApi
+ @Nullable
public LinkProperties getDataConnectionLinkProperties() {
return mLinkProperties;
}
/**
- * Returns data connection fail cause, in case there was a failure.
+ * Get the properties of the network link {@link LinkProperties}.
+ */
+ @Nullable
+ public LinkProperties getLinkProperties() {
+ return mLinkProperties;
+ }
+
+ /**
+ * Returns the cause code generated by the most recent state change.
+ *
+ * @deprecated use {@link #getLastCauseCode()}
+ * @hide
+ */
+ @Deprecated
+ @SystemApi
+ public int getDataConnectionFailCause() {
+ return mFailCause;
+ }
+
+ /**
+ * Returns the cause code generated by the most recent state change.
+ *
+ * Return the cause code for the most recent change in {@link #getState}. In the event of an
+ * error, this cause code will be non-zero.
*/
- public @Annotation.DataFailureCause int getDataConnectionFailCause() {
+ // FIXME(b144774287): some of these cause codes should have a prescribed meaning.
+ public int getLastCauseCode() {
return mFailCause;
}
+ /**
+ * Return the APN Settings for this data connection.
+ *
+ * Returns the ApnSetting that was used to configure this data connection.
+ */
+ // FIXME: This shouldn't be nullable; update once the ApnSetting is supplied correctly
+ @Nullable ApnSetting getApnSetting() {
+ return mApnSetting;
+ }
+
@Override
public int describeContents() {
return 0;
}
@Override
- public void writeToParcel(Parcel out, int flags) {
+ public void writeToParcel(@NonNull Parcel out, int flags) {
out.writeInt(mState);
out.writeInt(mNetworkType);
- out.writeInt(mAPNTypes);
- out.writeString(mAPN);
+ out.writeInt(mApnTypes);
+ out.writeString(mApn);
out.writeParcelable(mLinkProperties, flags);
out.writeInt(mFailCause);
+ out.writeParcelable(mApnSetting, flags);
}
- public static final @android.annotation.NonNull Parcelable.Creator<PreciseDataConnectionState> CREATOR
+ public static final @NonNull Parcelable.Creator<PreciseDataConnectionState> CREATOR
= new Parcelable.Creator<PreciseDataConnectionState>() {
public PreciseDataConnectionState createFromParcel(Parcel in) {
@@ -176,8 +291,8 @@ public final class PreciseDataConnectionState implements Parcelable {
@Override
public int hashCode() {
- return Objects.hash(mState, mNetworkType, mAPNTypes, mAPN, mLinkProperties,
- mFailCause);
+ return Objects.hash(mState, mNetworkType, mApnTypes, mApn, mLinkProperties,
+ mFailCause, mApnSetting);
}
@Override
@@ -188,11 +303,12 @@ public final class PreciseDataConnectionState implements Parcelable {
}
PreciseDataConnectionState other = (PreciseDataConnectionState) obj;
- return Objects.equals(mAPN, other.mAPN) && mAPNTypes == other.mAPNTypes
+ return Objects.equals(mApn, other.mApn) && mApnTypes == other.mApnTypes
&& mFailCause == other.mFailCause
&& Objects.equals(mLinkProperties, other.mLinkProperties)
&& mNetworkType == other.mNetworkType
- && mState == other.mState;
+ && mState == other.mState
+ && Objects.equals(mApnSetting, other.mApnSetting);
}
@NonNull
@@ -202,10 +318,11 @@ public final class PreciseDataConnectionState implements Parcelable {
sb.append("Data Connection state: " + mState);
sb.append(", Network type: " + mNetworkType);
- sb.append(", APN types: " + ApnSetting.getApnTypesStringFromBitmask(mAPNTypes));
- sb.append(", APN: " + mAPN);
+ sb.append(", APN types: " + ApnSetting.getApnTypesStringFromBitmask(mApnTypes));
+ sb.append(", APN: " + mApn);
sb.append(", Link properties: " + mLinkProperties);
sb.append(", Fail cause: " + DataFailCause.toString(mFailCause));
+ sb.append(", Apn Setting: " + mApnSetting);
return sb.toString();
}
diff --git a/telephony/java/android/telephony/ServiceState.java b/telephony/java/android/telephony/ServiceState.java
index d2c851789b96..d7d85c280e19 100644
--- a/telephony/java/android/telephony/ServiceState.java
+++ b/telephony/java/android/telephony/ServiceState.java
@@ -941,7 +941,7 @@ public class ServiceState implements Parcelable {
rtString = "LTE_CA";
break;
case RIL_RADIO_TECHNOLOGY_NR:
- rtString = "LTE_NR";
+ rtString = "NR_SA";
break;
default:
rtString = "Unexpected";
@@ -1479,8 +1479,9 @@ public class ServiceState implements Parcelable {
return AccessNetworkType.CDMA2000;
case RIL_RADIO_TECHNOLOGY_LTE:
case RIL_RADIO_TECHNOLOGY_LTE_CA:
- case RIL_RADIO_TECHNOLOGY_NR:
return AccessNetworkType.EUTRAN;
+ case RIL_RADIO_TECHNOLOGY_NR:
+ return AccessNetworkType.NGRAN;
case RIL_RADIO_TECHNOLOGY_IWLAN:
return AccessNetworkType.IWLAN;
case RIL_RADIO_TECHNOLOGY_UNKNOWN:
diff --git a/telephony/java/android/telephony/SmsManager.java b/telephony/java/android/telephony/SmsManager.java
index 37f33885de20..cab5286f53b7 100644
--- a/telephony/java/android/telephony/SmsManager.java
+++ b/telephony/java/android/telephony/SmsManager.java
@@ -1998,6 +1998,27 @@ public final class SmsManager {
}
}
+ /**
+ * Gets the total capacity of SMS storage on RUIM and SIM cards
+ *
+ * @return the total capacity count of SMS on RUIM and SIM cards
+ * @hide
+ */
+ @SystemApi
+ @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
+ public int getSmsCapacityOnIcc() {
+ int ret = 0;
+ try {
+ ISms iccISms = getISmsService();
+ if (iccISms != null) {
+ ret = iccISms.getSmsCapacityOnIccForSubscriber(getSubscriptionId());
+ }
+ } catch (RemoteException ex) {
+ //ignore it
+ }
+ return ret;
+ }
+
// see SmsMessage.getStatusOnIcc
/** Free space (TS 51.011 10.5.3 / 3GPP2 C.S0023 3.4.27). */
diff --git a/telephony/java/android/telephony/SubscriptionInfo.java b/telephony/java/android/telephony/SubscriptionInfo.java
index ebb517596b6c..94085e918bf5 100644
--- a/telephony/java/android/telephony/SubscriptionInfo.java
+++ b/telephony/java/android/telephony/SubscriptionInfo.java
@@ -30,7 +30,6 @@ import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.Typeface;
-import android.os.Build;
import android.os.Parcel;
import android.os.ParcelUuid;
import android.os.Parcelable;
@@ -38,6 +37,8 @@ import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
+import com.android.internal.telephony.util.TelephonyUtils;
+
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -209,6 +210,12 @@ public class SubscriptionInfo implements Parcelable {
private int mSubscriptionType;
/**
+ * Whether uicc applications are configured to enable or disable.
+ * By default it's true.
+ */
+ private boolean mAreUiccApplicationsEnabled = true;
+
+ /**
* @hide
*/
public SubscriptionInfo(int id, String iccId, int simSlotIndex, CharSequence displayName,
@@ -219,7 +226,7 @@ public class SubscriptionInfo implements Parcelable {
roaming, icon, mcc, mnc, countryIso, isEmbedded, nativeAccessRules, cardString, -1,
false, null, false, TelephonyManager.UNKNOWN_CARRIER_ID,
SubscriptionManager.PROFILE_CLASS_DEFAULT,
- SubscriptionManager.SUBSCRIPTION_TYPE_LOCAL_SIM, null, null);
+ SubscriptionManager.SUBSCRIPTION_TYPE_LOCAL_SIM, null, null, true);
}
/**
@@ -233,7 +240,7 @@ public class SubscriptionInfo implements Parcelable {
this(id, iccId, simSlotIndex, displayName, carrierName, nameSource, iconTint, number,
roaming, icon, mcc, mnc, countryIso, isEmbedded, nativeAccessRules, cardString, -1,
isOpportunistic, groupUUID, false, carrierId, profileClass,
- SubscriptionManager.SUBSCRIPTION_TYPE_LOCAL_SIM, null, null);
+ SubscriptionManager.SUBSCRIPTION_TYPE_LOCAL_SIM, null, null, true);
}
/**
@@ -245,7 +252,8 @@ public class SubscriptionInfo implements Parcelable {
@Nullable UiccAccessRule[] nativeAccessRules, String cardString, int cardId,
boolean isOpportunistic, @Nullable String groupUUID, boolean isGroupDisabled,
int carrierId, int profileClass, int subType, @Nullable String groupOwner,
- @Nullable UiccAccessRule[] carrierConfigAccessRules) {
+ @Nullable UiccAccessRule[] carrierConfigAccessRules,
+ boolean areUiccApplicationsEnabled) {
this.mId = id;
this.mIccId = iccId;
this.mSimSlotIndex = simSlotIndex;
@@ -271,6 +279,7 @@ public class SubscriptionInfo implements Parcelable {
this.mSubscriptionType = subType;
this.mGroupOwner = groupOwner;
this.mCarrierConfigAccessRules = carrierConfigAccessRules;
+ this.mAreUiccApplicationsEnabled = areUiccApplicationsEnabled;
}
/**
@@ -659,14 +668,23 @@ public class SubscriptionInfo implements Parcelable {
return mIsGroupDisabled;
}
+ /**
+ * Return whether uicc applications are set to be enabled or disabled.
+ * @hide
+ */
+ @SystemApi
+ public boolean areUiccApplicationsEnabled() {
+ return mAreUiccApplicationsEnabled;
+ }
+
public static final @android.annotation.NonNull Parcelable.Creator<SubscriptionInfo> CREATOR = new Parcelable.Creator<SubscriptionInfo>() {
@Override
public SubscriptionInfo createFromParcel(Parcel source) {
int id = source.readInt();
String iccId = source.readString();
int simSlotIndex = source.readInt();
- CharSequence displayName = source.readCharSequence();
- CharSequence carrierName = source.readCharSequence();
+ CharSequence displayName = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
+ CharSequence carrierName = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
int nameSource = source.readInt();
int iconTint = source.readInt();
String number = source.readString();
@@ -685,17 +703,18 @@ public class SubscriptionInfo implements Parcelable {
int carrierid = source.readInt();
int profileClass = source.readInt();
int subType = source.readInt();
- String[] ehplmns = source.readStringArray();
- String[] hplmns = source.readStringArray();
+ String[] ehplmns = source.createStringArray();
+ String[] hplmns = source.createStringArray();
String groupOwner = source.readString();
UiccAccessRule[] carrierConfigAccessRules = source.createTypedArray(
UiccAccessRule.CREATOR);
+ boolean areUiccApplicationsEnabled = source.readBoolean();
SubscriptionInfo info = new SubscriptionInfo(id, iccId, simSlotIndex, displayName,
carrierName, nameSource, iconTint, number, dataRoaming, iconBitmap, mcc, mnc,
countryIso, isEmbedded, nativeAccessRules, cardString, cardId, isOpportunistic,
groupUUID, isGroupDisabled, carrierid, profileClass, subType, groupOwner,
- carrierConfigAccessRules);
+ carrierConfigAccessRules, areUiccApplicationsEnabled);
info.setAssociatedPlmns(ehplmns, hplmns);
return info;
}
@@ -711,8 +730,8 @@ public class SubscriptionInfo implements Parcelable {
dest.writeInt(mId);
dest.writeString(mIccId);
dest.writeInt(mSimSlotIndex);
- dest.writeCharSequence(mDisplayName);
- dest.writeCharSequence(mCarrierName);
+ TextUtils.writeToParcel(mDisplayName, dest, 0);
+ TextUtils.writeToParcel(mCarrierName, dest, 0);
dest.writeInt(mNameSource);
dest.writeInt(mIconTint);
dest.writeString(mNumber);
@@ -735,6 +754,7 @@ public class SubscriptionInfo implements Parcelable {
dest.writeStringArray(mHplmns);
dest.writeString(mGroupOwner);
dest.writeTypedArray(mCarrierConfigAccessRules, flags);
+ dest.writeBoolean(mAreUiccApplicationsEnabled);
}
@Override
@@ -748,7 +768,7 @@ public class SubscriptionInfo implements Parcelable {
public static String givePrintableIccid(String iccId) {
String iccIdToPrint = null;
if (iccId != null) {
- if (iccId.length() > 9 && !Build.IS_DEBUGGABLE) {
+ if (iccId.length() > 9 && !TelephonyUtils.IS_DEBUGGABLE) {
iccIdToPrint = iccId.substring(0, 9) + Rlog.pii(false, iccId.substring(9));
} else {
iccIdToPrint = iccId;
@@ -764,7 +784,8 @@ public class SubscriptionInfo implements Parcelable {
return "{id=" + mId + " iccId=" + iccIdToPrint + " simSlotIndex=" + mSimSlotIndex
+ " carrierId=" + mCarrierId + " displayName=" + mDisplayName
+ " carrierName=" + mCarrierName + " nameSource=" + mNameSource
- + " iconTint=" + mIconTint + " mNumber=" + Rlog.pii(Build.IS_DEBUGGABLE, mNumber)
+ + " iconTint=" + mIconTint
+ + " mNumber=" + Rlog.pii(TelephonyUtils.IS_DEBUGGABLE, mNumber)
+ " dataRoaming=" + mDataRoaming + " iconBitmap=" + mIconBitmap + " mcc " + mMcc
+ " mnc " + mMnc + "mCountryIso=" + mCountryIso + " isEmbedded " + mIsEmbedded
+ " nativeAccessRules " + Arrays.toString(mNativeAccessRules)
@@ -776,15 +797,16 @@ public class SubscriptionInfo implements Parcelable {
+ " hplmns=" + Arrays.toString(mHplmns)
+ " subscriptionType=" + mSubscriptionType
+ " mGroupOwner=" + mGroupOwner
- + " carrierConfigAccessRules=" + mCarrierConfigAccessRules + "}";
+ + " carrierConfigAccessRules=" + mCarrierConfigAccessRules
+ + " mAreUiccApplicationsEnabled=" + mAreUiccApplicationsEnabled + "}";
}
@Override
public int hashCode() {
return Objects.hash(mId, mSimSlotIndex, mNameSource, mIconTint, mDataRoaming, mIsEmbedded,
- mIsOpportunistic, mGroupUUID, mIccId, mNumber, mMcc, mMnc,
- mCountryIso, mCardString, mCardId, mDisplayName, mCarrierName, mNativeAccessRules,
- mIsGroupDisabled, mCarrierId, mProfileClass, mGroupOwner);
+ mIsOpportunistic, mGroupUUID, mIccId, mNumber, mMcc, mMnc, mCountryIso, mCardString,
+ mCardId, mDisplayName, mCarrierName, mNativeAccessRules, mIsGroupDisabled,
+ mCarrierId, mProfileClass, mGroupOwner, mAreUiccApplicationsEnabled);
}
@Override
@@ -807,6 +829,7 @@ public class SubscriptionInfo implements Parcelable {
&& mIsEmbedded == toCompare.mIsEmbedded
&& mIsOpportunistic == toCompare.mIsOpportunistic
&& mIsGroupDisabled == toCompare.mIsGroupDisabled
+ && mAreUiccApplicationsEnabled == toCompare.mAreUiccApplicationsEnabled
&& mCarrierId == toCompare.mCarrierId
&& Objects.equals(mGroupUUID, toCompare.mGroupUUID)
&& Objects.equals(mIccId, toCompare.mIccId)
diff --git a/telephony/java/android/telephony/SubscriptionManager.java b/telephony/java/android/telephony/SubscriptionManager.java
index cf705f466e48..740622dae1d9 100644
--- a/telephony/java/android/telephony/SubscriptionManager.java
+++ b/telephony/java/android/telephony/SubscriptionManager.java
@@ -48,7 +48,6 @@ import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
-import android.os.HandlerExecutor;
import android.os.Looper;
import android.os.ParcelUuid;
import android.os.Process;
@@ -64,6 +63,7 @@ import android.util.Pair;
import com.android.internal.telephony.ISetOpportunisticDataCallback;
import com.android.internal.telephony.ISub;
import com.android.internal.telephony.PhoneConstants;
+import com.android.internal.telephony.util.HandlerExecutor;
import com.android.internal.util.Preconditions;
import java.lang.annotation.Retention;
@@ -835,6 +835,12 @@ public class SubscriptionManager {
public static final String IMSI = "imsi";
/**
+ * Whether uicc applications is set to be enabled or disabled. By default it's enabled.
+ * @hide
+ */
+ public static final String UICC_APPLICATIONS_ENABLED = "uicc_applications_enabled";
+
+ /**
* Broadcast Action: The user has changed one of the default subs related to
* data, phone calls, or sms</p>
*
diff --git a/telephony/java/android/telephony/TelephonyFrameworkInitializer.java b/telephony/java/android/telephony/TelephonyFrameworkInitializer.java
index b75d53379423..407ad19b4364 100644
--- a/telephony/java/android/telephony/TelephonyFrameworkInitializer.java
+++ b/telephony/java/android/telephony/TelephonyFrameworkInitializer.java
@@ -16,12 +16,16 @@
package android.telephony;
+import android.annotation.NonNull;
import android.annotation.SystemApi;
import android.app.SystemServiceRegistry;
import android.content.Context;
+import android.os.TelephonyServiceManager;
import android.telephony.euicc.EuiccCardManager;
import android.telephony.euicc.EuiccManager;
+import com.android.internal.util.Preconditions;
+
/**
* Class for performing registration for all telephony services.
@@ -34,6 +38,23 @@ public class TelephonyFrameworkInitializer {
private TelephonyFrameworkInitializer() {
}
+ private static volatile TelephonyServiceManager sTelephonyServiceManager;
+
+ /**
+ * Sets an instance of {@link TelephonyServiceManager} that allows
+ * the telephony mainline module to register/obtain telephony binder services. This is called
+ * by the platform during the system initialization.
+ *
+ * @param telephonyServiceManager instance of {@link TelephonyServiceManager} that allows
+ * the telephony mainline module to register/obtain telephony binder services.
+ */
+ public static void setTelephonyServiceManager(
+ @NonNull TelephonyServiceManager telephonyServiceManager) {
+ Preconditions.checkState(sTelephonyServiceManager == null,
+ "setTelephonyServiceManager called twice!");
+ sTelephonyServiceManager = Preconditions.checkNotNull(telephonyServiceManager);
+ }
+
/**
* Called by {@link SystemServiceRegistry}'s static initializer and registers all telephony
* services to {@link Context}, so that {@link Context#getSystemService} can return them.
@@ -68,4 +89,9 @@ public class TelephonyFrameworkInitializer {
context -> new EuiccCardManager(context)
);
}
+
+ /** @hide */
+ public static TelephonyServiceManager getTelephonyServiceManager() {
+ return sTelephonyServiceManager;
+ }
}
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index e3981f6abf34..555fd84b5797 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -38,6 +38,9 @@ import android.annotation.UnsupportedAppUsage;
import android.annotation.WorkerThread;
import android.app.ActivityThread;
import android.app.PendingIntent;
+import android.compat.Compatibility;
+import android.compat.annotation.ChangeId;
+import android.compat.annotation.EnabledAfter;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
@@ -142,6 +145,14 @@ public class TelephonyManager {
private static final String TAG = "TelephonyManager";
/**
+ * To expand the error codes for {@link TelephonyManager#updateAvailableNetworks} and
+ * {@link TelephonyManager#setPreferredOpportunisticDataSubscription}.
+ */
+ @ChangeId
+ @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
+ private static final long CALLBACK_ON_MORE_ERROR_CODE_CHANGE = 130595455L;
+
+ /**
* The key to use when placing the result of {@link #requestModemActivityInfo(ResultReceiver)}
* into the ResultReceiver Bundle.
* @hide
@@ -430,14 +441,14 @@ public class TelephonyManager {
int modemCount = 1;
switch (getMultiSimConfiguration()) {
case UNKNOWN:
- ConnectivityManager cm = mContext == null ? null : (ConnectivityManager) mContext
- .getSystemService(Context.CONNECTIVITY_SERVICE);
+ modemCount = MODEM_COUNT_SINGLE_MODEM;
// check for voice and data support, 0 if not supported
- if (!isVoiceCapable() && !isSmsCapable() && cm != null
- && !cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE)) {
- modemCount = MODEM_COUNT_NO_MODEM;
- } else {
- modemCount = MODEM_COUNT_SINGLE_MODEM;
+ if (!isVoiceCapable() && !isSmsCapable() && mContext != null) {
+ ConnectivityManager cm = (ConnectivityManager) mContext
+ .getSystemService(Context.CONNECTIVITY_SERVICE);
+ if (cm != null && !cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE)) {
+ modemCount = MODEM_COUNT_NO_MODEM;
+ }
}
break;
case DSDS:
@@ -605,6 +616,7 @@ public class TelephonyManager {
*
* @hide
*/
+ @SystemApi
@SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
public static final String ACTION_EMERGENCY_ASSISTANCE =
"android.telephony.action.EMERGENCY_ASSISTANCE";
@@ -716,31 +728,6 @@ public class TelephonyManager {
public static final String EXTRA_INCOMING_NUMBER = "incoming_number";
/**
- * Broadcast intent action indicating that a precise call state
- * (cellular) on the device has changed.
- *
- * <p>
- * The {@link #EXTRA_RINGING_CALL_STATE} extra indicates the ringing call state.
- * The {@link #EXTRA_FOREGROUND_CALL_STATE} extra indicates the foreground call state.
- * The {@link #EXTRA_BACKGROUND_CALL_STATE} extra indicates the background call state.
- *
- * <p class="note">
- * Requires the READ_PRECISE_PHONE_STATE permission.
- *
- * @see #EXTRA_RINGING_CALL_STATE
- * @see #EXTRA_FOREGROUND_CALL_STATE
- * @see #EXTRA_BACKGROUND_CALL_STATE
- *
- * <p class="note">
- * Requires the READ_PRECISE_PHONE_STATE permission.
- * @deprecated use {@link PhoneStateListener#LISTEN_PRECISE_CALL_STATE} instead
- * @hide
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String ACTION_PRECISE_CALL_STATE_CHANGED =
- "android.intent.action.PRECISE_CALL_STATE";
-
- /**
* Broadcast intent action indicating that call disconnect cause has changed.
*
* <p>
@@ -762,78 +749,6 @@ public class TelephonyManager {
/**
* The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast and
* {@link PhoneStateListener#onPreciseCallStateChanged(PreciseCallState)} for an integer
- * containing the state of the current ringing call.
- *
- * @see PreciseCallState#PRECISE_CALL_STATE_NOT_VALID
- * @see PreciseCallState#PRECISE_CALL_STATE_IDLE
- * @see PreciseCallState#PRECISE_CALL_STATE_ACTIVE
- * @see PreciseCallState#PRECISE_CALL_STATE_HOLDING
- * @see PreciseCallState#PRECISE_CALL_STATE_DIALING
- * @see PreciseCallState#PRECISE_CALL_STATE_ALERTING
- * @see PreciseCallState#PRECISE_CALL_STATE_INCOMING
- * @see PreciseCallState#PRECISE_CALL_STATE_WAITING
- * @see PreciseCallState#PRECISE_CALL_STATE_DISCONNECTED
- * @see PreciseCallState#PRECISE_CALL_STATE_DISCONNECTING
- *
- * <p class="note">
- * Retrieve with
- * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
- *
- * @hide
- */
- public static final String EXTRA_RINGING_CALL_STATE = "ringing_state";
-
- /**
- * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast and
- * {@link PhoneStateListener#onPreciseCallStateChanged(PreciseCallState)} for an integer
- * containing the state of the current foreground call.
- *
- * @see PreciseCallState#PRECISE_CALL_STATE_NOT_VALID
- * @see PreciseCallState#PRECISE_CALL_STATE_IDLE
- * @see PreciseCallState#PRECISE_CALL_STATE_ACTIVE
- * @see PreciseCallState#PRECISE_CALL_STATE_HOLDING
- * @see PreciseCallState#PRECISE_CALL_STATE_DIALING
- * @see PreciseCallState#PRECISE_CALL_STATE_ALERTING
- * @see PreciseCallState#PRECISE_CALL_STATE_INCOMING
- * @see PreciseCallState#PRECISE_CALL_STATE_WAITING
- * @see PreciseCallState#PRECISE_CALL_STATE_DISCONNECTED
- * @see PreciseCallState#PRECISE_CALL_STATE_DISCONNECTING
- *
- * <p class="note">
- * Retrieve with
- * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
- *
- * @hide
- */
- public static final String EXTRA_FOREGROUND_CALL_STATE = "foreground_state";
-
- /**
- * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast and
- * {@link PhoneStateListener#onPreciseCallStateChanged(PreciseCallState)} for an integer
- * containing the state of the current background call.
- *
- * @see PreciseCallState#PRECISE_CALL_STATE_NOT_VALID
- * @see PreciseCallState#PRECISE_CALL_STATE_IDLE
- * @see PreciseCallState#PRECISE_CALL_STATE_ACTIVE
- * @see PreciseCallState#PRECISE_CALL_STATE_HOLDING
- * @see PreciseCallState#PRECISE_CALL_STATE_DIALING
- * @see PreciseCallState#PRECISE_CALL_STATE_ALERTING
- * @see PreciseCallState#PRECISE_CALL_STATE_INCOMING
- * @see PreciseCallState#PRECISE_CALL_STATE_WAITING
- * @see PreciseCallState#PRECISE_CALL_STATE_DISCONNECTED
- * @see PreciseCallState#PRECISE_CALL_STATE_DISCONNECTING
- *
- * <p class="note">
- * Retrieve with
- * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
- *
- * @hide
- */
- public static final String EXTRA_BACKGROUND_CALL_STATE = "background_state";
-
- /**
- * The lookup key used with the {@link #ACTION_PRECISE_CALL_STATE_CHANGED} broadcast and
- * {@link PhoneStateListener#onPreciseCallStateChanged(PreciseCallState)} for an integer
* containing the disconnect cause.
*
* @see DisconnectCause
@@ -842,8 +757,10 @@ public class TelephonyManager {
* Retrieve with
* {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
*
+ * @deprecated Should use the {@link TelecomManager#EXTRA_DISCONNECT_CAUSE} instead.
* @hide
*/
+ @Deprecated
public static final String EXTRA_DISCONNECT_CAUSE = "disconnect_cause";
/**
@@ -862,88 +779,6 @@ public class TelephonyManager {
public static final String EXTRA_PRECISE_DISCONNECT_CAUSE = "precise_disconnect_cause";
/**
- * Broadcast intent action indicating a data connection has changed,
- * providing precise information about the connection.
- *
- * <p>
- * The {@link #EXTRA_DATA_STATE} extra indicates the connection state.
- * The {@link #EXTRA_DATA_NETWORK_TYPE} extra indicates the connection network type.
- * The {@link #EXTRA_DATA_APN_TYPE} extra indicates the APN type.
- * The {@link #EXTRA_DATA_APN} extra indicates the APN.
- * The {@link #EXTRA_DATA_IFACE_PROPERTIES} extra indicates the connection interface.
- * The {@link #EXTRA_DATA_FAILURE_CAUSE} extra indicates the connection fail cause.
- *
- * <p class="note">
- * Requires the READ_PRECISE_PHONE_STATE permission.
- *
- * @see #EXTRA_DATA_STATE
- * @see #EXTRA_DATA_NETWORK_TYPE
- * @see #EXTRA_DATA_APN_TYPE
- * @see #EXTRA_DATA_APN
- * @see #EXTRA_DATA_IFACE
- * @see #EXTRA_DATA_FAILURE_CAUSE
- * @hide
- *
- * @deprecated If the app is running in the background, it won't be able to receive this
- * broadcast. Apps should use ConnectivityManager {@link #registerNetworkCallback(
- * android.net.NetworkRequest, ConnectivityManager.NetworkCallback)} to listen for network
- * changes.
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- @Deprecated
- @UnsupportedAppUsage
- public static final String ACTION_PRECISE_DATA_CONNECTION_STATE_CHANGED =
- "android.intent.action.PRECISE_DATA_CONNECTION_STATE_CHANGED";
-
- /**
- * The lookup key used with the {@link #ACTION_PRECISE_DATA_CONNECTION_STATE_CHANGED} broadcast
- * for an integer containing the state of the current data connection.
- *
- * @see TelephonyManager#DATA_UNKNOWN
- * @see TelephonyManager#DATA_DISCONNECTED
- * @see TelephonyManager#DATA_CONNECTING
- * @see TelephonyManager#DATA_CONNECTED
- * @see TelephonyManager#DATA_SUSPENDED
- *
- * <p class="note">
- * Retrieve with
- * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
- *
- * @hide
- */
- public static final String EXTRA_DATA_STATE = PhoneConstants.STATE_KEY;
-
- /**
- * The lookup key used with the {@link #ACTION_PRECISE_DATA_CONNECTION_STATE_CHANGED} broadcast
- * for an integer containing the network type.
- *
- * @see TelephonyManager#NETWORK_TYPE_UNKNOWN
- * @see TelephonyManager#NETWORK_TYPE_GPRS
- * @see TelephonyManager#NETWORK_TYPE_EDGE
- * @see TelephonyManager#NETWORK_TYPE_UMTS
- * @see TelephonyManager#NETWORK_TYPE_CDMA
- * @see TelephonyManager#NETWORK_TYPE_EVDO_0
- * @see TelephonyManager#NETWORK_TYPE_EVDO_A
- * @see TelephonyManager#NETWORK_TYPE_1xRTT
- * @see TelephonyManager#NETWORK_TYPE_HSDPA
- * @see TelephonyManager#NETWORK_TYPE_HSUPA
- * @see TelephonyManager#NETWORK_TYPE_HSPA
- * @see TelephonyManager#NETWORK_TYPE_IDEN
- * @see TelephonyManager#NETWORK_TYPE_EVDO_B
- * @see TelephonyManager#NETWORK_TYPE_LTE
- * @see TelephonyManager#NETWORK_TYPE_EHRPD
- * @see TelephonyManager#NETWORK_TYPE_HSPAP
- * @see TelephonyManager#NETWORK_TYPE_NR
- *
- * <p class="note">
- * Retrieve with
- * {@link android.content.Intent#getIntExtra(String name, int defaultValue)}.
- *
- * @hide
- */
- public static final String EXTRA_DATA_NETWORK_TYPE = PhoneConstants.DATA_NETWORK_TYPE_KEY;
-
- /**
* The lookup key used with the {@link #ACTION_PRECISE_DATA_CONNECTION_STATE_CHANGED} broadcast
* for an String containing the data APN type.
*
@@ -968,30 +803,6 @@ public class TelephonyManager {
public static final String EXTRA_DATA_APN = PhoneConstants.DATA_APN_KEY;
/**
- * The lookup key used with the {@link #ACTION_PRECISE_DATA_CONNECTION_STATE_CHANGED} broadcast
- * for an String representation of the data interface.
- *
- * <p class="note">
- * Retrieve with
- * {@link android.content.Intent#getParcelableExtra(String name)}.
- *
- * @hide
- */
- public static final String EXTRA_DATA_LINK_PROPERTIES_KEY = PhoneConstants.DATA_LINK_PROPERTIES_KEY;
-
- /**
- * The lookup key used with the {@link #ACTION_PRECISE_DATA_CONNECTION_STATE_CHANGED} broadcast
- * for the data connection fail cause.
- *
- * <p class="note">
- * Retrieve with
- * {@link android.content.Intent#getStringExtra(String name)}.
- *
- * @hide
- */
- public static final String EXTRA_DATA_FAILURE_CAUSE = PhoneConstants.DATA_FAILURE_CAUSE_KEY;
-
- /**
* Broadcast intent action for letting the default dialer to know to show voicemail
* notification.
*
@@ -1652,6 +1463,26 @@ public class TelephonyManager {
*/
public static final String EXTRA_SIM_COMBINATION_NAMES =
"android.telephony.extra.SIM_COMBINATION_NAMES";
+
+ /**
+ * Broadcast Action: The time was set by the carrier (typically by the NITZ string).
+ * This is a sticky broadcast.
+ * The intent will have the following extra values:</p>
+ * <ul>
+ * <li><em>time</em> - The time as a long in UTC milliseconds.</li>
+ * </ul>
+ *
+ * <p class="note">
+ * Requires the READ_PHONE_STATE permission.
+ *
+ * <p class="note">This is a protected intent that can only be sent
+ * by the system.
+ *
+ * @hide
+ */
+ @SystemApi
+ public static final String ACTION_NETWORK_SET_TIME = "android.telephony.action.NETWORK_SET_TIME";
+
//
//
// Device Info
@@ -2632,7 +2463,7 @@ public class TelephonyManager {
/*
* When adding a network type to the list below, make sure to add the correct icon to
- * MobileSignalController.mapIconSets().
+ * MobileSignalController.mapIconSets() as well as NETWORK_TYPES
* Do not add negative types.
*/
/** Network type is unknown */
@@ -2680,8 +2511,36 @@ public class TelephonyManager {
/** Current network is NR(New Radio) 5G. */
public static final int NETWORK_TYPE_NR = TelephonyProtoEnums.NETWORK_TYPE_NR; // 20.
- /** Max network type number. Update as new types are added. Don't add negative types. {@hide} */
- public static final int MAX_NETWORK_TYPE = NETWORK_TYPE_NR;
+ private static final @NetworkType int[] NETWORK_TYPES = {
+ NETWORK_TYPE_GPRS,
+ NETWORK_TYPE_EDGE,
+ NETWORK_TYPE_UMTS,
+ NETWORK_TYPE_CDMA,
+ NETWORK_TYPE_EVDO_0,
+ NETWORK_TYPE_EVDO_A,
+ NETWORK_TYPE_1xRTT,
+ NETWORK_TYPE_HSDPA,
+ NETWORK_TYPE_HSUPA,
+ NETWORK_TYPE_HSPA,
+ NETWORK_TYPE_IDEN,
+ NETWORK_TYPE_EVDO_B,
+ NETWORK_TYPE_LTE,
+ NETWORK_TYPE_EHRPD,
+ NETWORK_TYPE_HSPAP,
+ NETWORK_TYPE_GSM,
+ NETWORK_TYPE_TD_SCDMA,
+ NETWORK_TYPE_IWLAN,
+ NETWORK_TYPE_LTE_CA,
+ NETWORK_TYPE_NR
+ };
+
+ /**
+ * Return a collection of all network types
+ * @return network types
+ */
+ public static @NonNull @NetworkType int[] getAllNetworkTypes() {
+ return NETWORK_TYPES;
+ }
/**
* Return the current data network type.
@@ -3026,6 +2885,24 @@ public class TelephonyManager {
//
//
+ /** @hide */
+ @IntDef(prefix = {"SIM_STATE_"},
+ value = {
+ SIM_STATE_UNKNOWN,
+ SIM_STATE_ABSENT,
+ SIM_STATE_PIN_REQUIRED,
+ SIM_STATE_PUK_REQUIRED,
+ SIM_STATE_NETWORK_LOCKED,
+ SIM_STATE_READY,
+ SIM_STATE_NOT_READY,
+ SIM_STATE_PERM_DISABLED,
+ SIM_STATE_CARD_IO_ERROR,
+ SIM_STATE_CARD_RESTRICTED,
+ SIM_STATE_LOADED,
+ SIM_STATE_PRESENT,
+ })
+ public @interface SimState {}
+
/**
* SIM card state: Unknown. Signifies that the SIM is in transition
* between states. For example, when the user inputs the SIM pin
@@ -3231,7 +3108,7 @@ public class TelephonyManager {
* @see #SIM_STATE_CARD_IO_ERROR
* @see #SIM_STATE_CARD_RESTRICTED
*/
- public int getSimState() {
+ public @SimState int getSimState() {
int simState = getSimStateIncludingLoaded();
if (simState == SIM_STATE_LOADED) {
simState = SIM_STATE_READY;
@@ -3239,7 +3116,7 @@ public class TelephonyManager {
return simState;
}
- private int getSimStateIncludingLoaded() {
+ private @SimState int getSimStateIncludingLoaded() {
int slotIndex = getSlotIndex();
// slotIndex may be invalid due to sim being absent. In that case query all slots to get
// sim state
@@ -3273,7 +3150,7 @@ public class TelephonyManager {
* @hide
*/
@SystemApi
- public int getSimCardState() {
+ public @SimState int getSimCardState() {
int simState = getSimState();
return getSimCardStateFromSimState(simState);
}
@@ -3293,7 +3170,7 @@ public class TelephonyManager {
*/
@SystemApi
@RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
- public int getSimCardState(int physicalSlotIndex) {
+ public @SimState int getSimCardState(int physicalSlotIndex) {
int simState = getSimState(getLogicalSlotIndex(physicalSlotIndex));
return getSimCardStateFromSimState(simState);
}
@@ -3303,7 +3180,7 @@ public class TelephonyManager {
* @param simState
* @return SIM card state
*/
- private int getSimCardStateFromSimState(int simState) {
+ private @SimState int getSimCardStateFromSimState(int simState) {
switch (simState) {
case SIM_STATE_UNKNOWN:
case SIM_STATE_ABSENT:
@@ -3343,7 +3220,7 @@ public class TelephonyManager {
* @hide
*/
@SystemApi
- public int getSimApplicationState() {
+ public @SimState int getSimApplicationState() {
int simState = getSimStateIncludingLoaded();
return getSimApplicationStateFromSimState(simState);
}
@@ -3366,7 +3243,7 @@ public class TelephonyManager {
*/
@SystemApi
@RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
- public int getSimApplicationState(int physicalSlotIndex) {
+ public @SimState int getSimApplicationState(int physicalSlotIndex) {
int simState =
SubscriptionManager.getSimStateForSlotIndex(getLogicalSlotIndex(physicalSlotIndex));
return getSimApplicationStateFromSimState(simState);
@@ -3377,7 +3254,7 @@ public class TelephonyManager {
* @param simState
* @return SIM application state
*/
- private int getSimApplicationStateFromSimState(int simState) {
+ private @SimState int getSimApplicationStateFromSimState(int simState) {
switch (simState) {
case SIM_STATE_UNKNOWN:
case SIM_STATE_ABSENT:
@@ -3434,7 +3311,7 @@ public class TelephonyManager {
* @see #SIM_STATE_CARD_IO_ERROR
* @see #SIM_STATE_CARD_RESTRICTED
*/
- public int getSimState(int slotIndex) {
+ public @SimState int getSimState(int slotIndex) {
int simState = SubscriptionManager.getSimStateForSlotIndex(slotIndex);
if (simState == SIM_STATE_LOADED) {
simState = SIM_STATE_READY;
@@ -5262,6 +5139,7 @@ public class TelephonyManager {
DATA_CONNECTING,
DATA_CONNECTED,
DATA_SUSPENDED,
+ DATA_DISCONNECTING,
})
@Retention(RetentionPolicy.SOURCE)
public @interface DataState{}
@@ -5278,6 +5156,12 @@ public class TelephonyManager {
* traffic is temporarily unavailable. For example, in a 2G network,
* data activity may be suspended when a voice call arrives. */
public static final int DATA_SUSPENDED = 3;
+ /**
+ * Data connection state: Disconnecting.
+ *
+ * IP traffic may be available but will cease working imminently.
+ */
+ public static final int DATA_DISCONNECTING = 4;
/**
* Returns a constant indicating the current data connection state
@@ -5287,14 +5171,21 @@ public class TelephonyManager {
* @see #DATA_CONNECTING
* @see #DATA_CONNECTED
* @see #DATA_SUSPENDED
+ * @see #DATA_DISCONNECTING
*/
public int getDataState() {
try {
ITelephony telephony = getITelephony();
if (telephony == null)
return DATA_DISCONNECTED;
- return telephony.getDataStateForSubId(
+ int state = telephony.getDataStateForSubId(
getSubId(SubscriptionManager.getActiveDataSubscriptionId()));
+ if (state == TelephonyManager.DATA_DISCONNECTING
+ && VMRuntime.getRuntime().getTargetSdkVersion() < Build.VERSION_CODES.R) {
+ return TelephonyManager.DATA_CONNECTED;
+ }
+
+ return state;
} catch (RemoteException ex) {
// the phone process is restarting.
return DATA_DISCONNECTED;
@@ -5315,6 +5206,7 @@ public class TelephonyManager {
case DATA_CONNECTING: return "CONNECTING";
case DATA_CONNECTED: return "CONNECTED";
case DATA_SUSPENDED: return "SUSPENDED";
+ case DATA_DISCONNECTING: return "DISCONNECTING";
}
return "UNKNOWN(" + state + ")";
}
@@ -5324,7 +5216,8 @@ public class TelephonyManager {
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
private ITelephony getITelephony() {
- return ITelephony.Stub.asInterface(ServiceManager.getService(Context.TELEPHONY_SERVICE));
+ return ITelephony.Stub.asInterface(TelephonyFrameworkInitializer
+ .getTelephonyServiceManager().getTelephonyServiceRegisterer().get());
}
private ITelephonyRegistry getTelephonyRegistry() {
@@ -6629,75 +6522,6 @@ public class TelephonyManager {
}
/**
- * Sets a per-phone telephony property with the value specified.
- *
- * @hide
- */
- @UnsupportedAppUsage
- public static void setTelephonyProperty(int phoneId, String property, String value) {
- String propVal = "";
- String p[] = null;
- String prop = SystemProperties.get(property);
-
- if (value == null) {
- value = "";
- }
- value.replace(',', ' ');
- if (prop != null) {
- p = prop.split(",");
- }
-
- if (!SubscriptionManager.isValidPhoneId(phoneId)) {
- Rlog.d(TAG, "setTelephonyProperty: invalid phoneId=" + phoneId +
- " property=" + property + " value: " + value + " prop=" + prop);
- return;
- }
-
- for (int i = 0; i < phoneId; i++) {
- String str = "";
- if ((p != null) && (i < p.length)) {
- str = p[i];
- }
- propVal = propVal + str + ",";
- }
-
- propVal = propVal + value;
- if (p != null) {
- for (int i = phoneId + 1; i < p.length; i++) {
- propVal = propVal + "," + p[i];
- }
- }
-
- int propValLen = propVal.length();
- try {
- propValLen = propVal.getBytes("utf-8").length;
- } catch (java.io.UnsupportedEncodingException e) {
- Rlog.d(TAG, "setTelephonyProperty: utf-8 not supported");
- }
- if (propValLen > SystemProperties.PROP_VALUE_MAX) {
- Rlog.d(TAG, "setTelephonyProperty: property too long phoneId=" + phoneId +
- " property=" + property + " value: " + value + " propVal=" + propVal);
- return;
- }
-
- SystemProperties.set(property, propVal);
- }
-
- /**
- * Sets a global telephony property with the value specified.
- *
- * @hide
- */
- public static void setTelephonyProperty(String property, String value) {
- if (value == null) {
- value = "";
- }
- Rlog.d(TAG, "setTelephonyProperty: success" + " property=" +
- property + " value: " + value);
- SystemProperties.set(property, value);
- }
-
- /**
* Inserts or updates a list property. Expands the list if its length is not enough.
*/
private static <T> List<T> updateTelephonyProperty(List<T> prop, int phoneId, T value) {
@@ -7034,7 +6858,8 @@ public class TelephonyManager {
* If the list is longer than the size of EFfplmn, then the file will be written from the
* beginning of the list up to the file size.
*
- * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
+ * <p>Requires Permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE
+ * MODIFY_PHONE_STATE}
* or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
*
* @param fplmns a list of PLMNs to be forbidden.
@@ -7048,7 +6873,7 @@ public class TelephonyManager {
public int setForbiddenPlmns(@NonNull List<String> fplmns) {
try {
ITelephony telephony = getITelephony();
- if (telephony == null) return 0;
+ if (telephony == null) return -1;
return telephony.setForbiddenPlmns(
getSubId(), APPTYPE_USIM, fplmns, getOpPackageName(), getFeatureId());
} catch (RemoteException ex) {
@@ -7057,7 +6882,7 @@ public class TelephonyManager {
// This could happen before phone starts
Rlog.e(TAG, "setForbiddenPlmns NullPointerException: " + ex.getMessage());
}
- return 0;
+ return -1;
}
/**
@@ -8549,6 +8374,44 @@ public class TelephonyManager {
}
/**
+ * Shut down all the live radios over all the slot index.
+ *
+ * @hide
+ */
+ @SystemApi
+ @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
+ public void shutdownAllRadios() {
+ try {
+ ITelephony telephony = getITelephony();
+ if (telephony != null) {
+ telephony.shutdownMobileRadios();
+ }
+ } catch (RemoteException e) {
+ Log.e(TAG, "Error calling ITelephony#shutdownMobileRadios", e);
+ }
+ }
+
+ /**
+ * Check if any radio is on over all the slot indexes.
+ *
+ * @return {@code true} if any radio is on over any slot index.
+ * @hide
+ */
+ @SystemApi
+ @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
+ public boolean isAnyRadioPoweredOn() {
+ try {
+ ITelephony telephony = getITelephony();
+ if (telephony != null) {
+ return telephony.needMobileRadioShutdown();
+ }
+ } catch (RemoteException e) {
+ Log.e(TAG, "Error calling ITelephony#needMobileRadioShutdown", e);
+ }
+ return false;
+ }
+
+ /**
* Radio explicitly powered off (e.g, airplane mode).
* @hide
*/
@@ -9802,7 +9665,8 @@ public class TelephonyManager {
* {@link android.telephony.ModemActivityInfo} object.
* @hide
*/
- public void requestModemActivityInfo(ResultReceiver result) {
+ @SystemApi
+ public void requestModemActivityInfo(@NonNull ResultReceiver result) {
try {
ITelephony service = getITelephony();
if (service != null) {
@@ -10457,19 +10321,25 @@ public class TelephonyManager {
}
/**
- * Action set from carrier signalling broadcast receivers to enable/disable radio
- * Permissions {@link android.Manifest.permission.MODIFY_PHONE_STATE} is required.
- * @param subId the subscription ID that this action applies to.
+ * Carrier action to enable or disable the radio.
+ *
+ * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
+ * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
+ *
+ * <p>Requires Permission:
+ * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
+ *
* @param enabled control enable or disable radio.
* @hide
*/
@SystemApi
@RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
- public void carrierActionSetRadioEnabled(int subId, boolean enabled) {
+ public void setRadioEnabled(boolean enabled) {
try {
ITelephony service = getITelephony();
if (service != null) {
- service.carrierActionSetRadioEnabled(subId, enabled);
+ service.carrierActionSetRadioEnabled(
+ getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), enabled);
}
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelephony#carrierActionSetRadioEnabled", e);
@@ -10477,20 +10347,25 @@ public class TelephonyManager {
}
/**
- * Action set from carrier signalling broadcast receivers to start/stop reporting default
- * network available events
- * Permissions {@link android.Manifest.permission.MODIFY_PHONE_STATE} is required.
- * @param subId the subscription ID that this action applies to.
+ * Carrier action to start or stop reporting default network available events.
+ *
+ * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
+ * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
+ *
+ * <p>Requires Permission:
+ * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
+ *
* @param report control start/stop reporting network status.
* @hide
*/
@SystemApi
@RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
- public void carrierActionReportDefaultNetworkStatus(int subId, boolean report) {
+ public void reportDefaultNetworkStatus(boolean report) {
try {
ITelephony service = getITelephony();
if (service != null) {
- service.carrierActionReportDefaultNetworkStatus(subId, report);
+ service.carrierActionReportDefaultNetworkStatus(
+ getSubId(SubscriptionManager.getDefaultDataSubscriptionId()), report);
}
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelephony#carrierActionReportDefaultNetworkStatus", e);
@@ -10498,18 +10373,24 @@ public class TelephonyManager {
}
/**
- * Action set from carrier signalling broadcast receivers to reset all carrier actions
- * Permissions {@link android.Manifest.permission.MODIFY_PHONE_STATE} is required.
- * @param subId the subscription ID that this action applies to.
+ * Reset all carrier actions previously set by {@link #setRadioEnabled},
+ * {@link #reportDefaultNetworkStatus} and {@link #setCarrierDataEnabled}.
+ *
+ * <p>If this object has been created with {@link #createForSubscriptionId}, applies to the
+ * given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultDataSubscriptionId()}
+ *
+ * <p>Requires Permission:
+ * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
* @hide
*/
@SystemApi
@RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
- public void carrierActionResetAll(int subId) {
+ public void resetAllCarrierActions() {
try {
ITelephony service = getITelephony();
if (service != null) {
- service.carrierActionResetAll(subId);
+ service.carrierActionResetAll(
+ getSubId(SubscriptionManager.getDefaultDataSubscriptionId()));
}
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelephony#carrierActionResetAll", e);
@@ -11522,7 +11403,11 @@ public class TelephonyManager {
final long identity = Binder.clearCallingIdentity();
try {
executor.execute(() -> {
- callback.accept(SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION);
+ if (Compatibility.isChangeEnabled(CALLBACK_ON_MORE_ERROR_CODE_CHANGE)) {
+ callback.accept(SET_OPPORTUNISTIC_SUB_REMOTE_SERVICE_EXCEPTION);
+ } else {
+ callback.accept(SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION);
+ }
});
} finally {
Binder.restoreCallingIdentity(identity);
@@ -11619,7 +11504,11 @@ public class TelephonyManager {
final long identity = Binder.clearCallingIdentity();
try {
executor.execute(() -> {
- callback.accept(UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION);
+ if (Compatibility.isChangeEnabled(CALLBACK_ON_MORE_ERROR_CODE_CHANGE)) {
+ callback.accept(UPDATE_AVAILABLE_NETWORKS_REMOTE_SERVICE_EXCEPTION);
+ } else {
+ callback.accept(UPDATE_AVAILABLE_NETWORKS_UNKNOWN_FAILURE);
+ }
});
} finally {
Binder.restoreCallingIdentity(identity);
@@ -11893,6 +11782,32 @@ public class TelephonyManager {
}
/**
+ * Get the calling application status about carrier privileges for the subscription created
+ * in TelephonyManager. Used by Telephony Module for permission checking.
+ *
+ * @param uid Uid to check.
+ * @return any value of {@link #CARRIER_PRIVILEGE_STATUS_HAS_ACCESS},
+ * {@link #CARRIER_PRIVILEGE_STATUS_NO_ACCESS},
+ * {@link #CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED}, or
+ * {@link #CARRIER_PRIVILEGE_STATUS_ERROR_LOADING_RULES}
+ *
+ * @hide
+ */
+ @SystemApi
+ @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
+ public int getCarrierPrivilegeStatus(int uid) {
+ try {
+ ITelephony telephony = getITelephony();
+ if (telephony != null) {
+ return telephony.getCarrierPrivilegeStatusForUid(getSubId(), uid);
+ }
+ } catch (RemoteException ex) {
+ Log.e(TAG, "getCarrierPrivilegeStatus RemoteException", ex);
+ }
+ return TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
+ }
+
+ /**
* Return whether data is enabled for certain APN type. This will tell if framework will accept
* corresponding network requests on a subId.
*
@@ -11935,6 +11850,8 @@ public class TelephonyManager {
*
* @hide
*/
+ @SystemApi
+ @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
public boolean isApnMetered(@ApnType int apnType) {
try {
ITelephony service = getITelephony();
diff --git a/telephony/java/android/telephony/data/ApnSetting.java b/telephony/java/android/telephony/data/ApnSetting.java
index 60774e7f1e7f..034fc220cbbe 100644
--- a/telephony/java/android/telephony/data/ApnSetting.java
+++ b/telephony/java/android/telephony/data/ApnSetting.java
@@ -20,7 +20,7 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.ContentValues;
import android.database.Cursor;
-import android.hardware.radio.V1_4.ApnTypes;
+import android.hardware.radio.V1_5.ApnTypes;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
@@ -110,6 +110,8 @@ public class ApnSetting implements Parcelable {
public static final int TYPE_EMERGENCY = ApnTypes.EMERGENCY;
/** APN type for MCX (Mission Critical Service) where X can be PTT/Video/Data */
public static final int TYPE_MCX = ApnTypes.MCX;
+ /** APN type for XCAP. */
+ public static final int TYPE_XCAP = ApnTypes.XCAP;
// Possible values for authentication types.
/** No authentication type. */
@@ -198,6 +200,7 @@ public class ApnSetting implements Parcelable {
APN_TYPE_STRING_MAP.put("ia", TYPE_IA);
APN_TYPE_STRING_MAP.put("emergency", TYPE_EMERGENCY);
APN_TYPE_STRING_MAP.put("mcx", TYPE_MCX);
+ APN_TYPE_STRING_MAP.put("xcap", TYPE_XCAP);
APN_TYPE_INT_MAP = new ArrayMap<Integer, String>();
APN_TYPE_INT_MAP.put(TYPE_DEFAULT, "default");
APN_TYPE_INT_MAP.put(TYPE_MMS, "mms");
@@ -210,6 +213,7 @@ public class ApnSetting implements Parcelable {
APN_TYPE_INT_MAP.put(TYPE_IA, "ia");
APN_TYPE_INT_MAP.put(TYPE_EMERGENCY, "emergency");
APN_TYPE_INT_MAP.put(TYPE_MCX, "mcx");
+ APN_TYPE_INT_MAP.put(TYPE_XCAP, "xcap");
PROTOCOL_STRING_MAP = new ArrayMap<String, Integer>();
PROTOCOL_STRING_MAP.put("IP", PROTOCOL_IP);
@@ -1944,8 +1948,9 @@ public class ApnSetting implements Parcelable {
* {@link ApnSetting} built from this builder otherwise.
*/
public ApnSetting build() {
- if ((mApnTypeBitmask & (TYPE_DEFAULT | TYPE_MMS | TYPE_SUPL | TYPE_DUN | TYPE_HIPRI |
- TYPE_FOTA | TYPE_IMS | TYPE_CBS | TYPE_IA | TYPE_EMERGENCY | TYPE_MCX)) == 0
+ if ((mApnTypeBitmask & (TYPE_DEFAULT | TYPE_MMS | TYPE_SUPL | TYPE_DUN | TYPE_HIPRI
+ | TYPE_FOTA | TYPE_IMS | TYPE_CBS | TYPE_IA | TYPE_EMERGENCY | TYPE_MCX
+ | TYPE_XCAP)) == 0
|| TextUtils.isEmpty(mApnName) || TextUtils.isEmpty(mEntryName)) {
return null;
}
diff --git a/telephony/java/android/telephony/data/DataProfile.java b/telephony/java/android/telephony/data/DataProfile.java
index 30c209b28a4d..96a5a8151065 100644
--- a/telephony/java/android/telephony/data/DataProfile.java
+++ b/telephony/java/android/telephony/data/DataProfile.java
@@ -22,7 +22,6 @@ import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
-import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.telephony.Annotation.ApnType;
@@ -31,6 +30,7 @@ import android.telephony.data.ApnSetting.AuthType;
import android.text.TextUtils;
import com.android.internal.telephony.RILConstants;
+import com.android.internal.telephony.util.TelephonyUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -261,7 +261,7 @@ public final class DataProfile implements Parcelable {
@Override
public String toString() {
return "DataProfile=" + mProfileId + "/" + mProtocolType + "/" + mAuthType
- + "/" + (Build.IS_USER ? "***/***/***" :
+ + "/" + (TelephonyUtils.IS_USER ? "***/***/***" :
(mApn + "/" + mUserName + "/" + mPassword)) + "/" + mType + "/"
+ mMaxConnectionsTime + "/" + mMaxConnections + "/"
+ mWaitTime + "/" + mEnabled + "/" + mSupportedApnTypesBitmask + "/"
diff --git a/telephony/java/android/telephony/ims/ImsCallSession.java b/telephony/java/android/telephony/ims/ImsCallSession.java
index 47c468121484..5adc99e11478 100644
--- a/telephony/java/android/telephony/ims/ImsCallSession.java
+++ b/telephony/java/android/telephony/ims/ImsCallSession.java
@@ -1173,18 +1173,8 @@ public class ImsCallSession {
public void callSessionMergeComplete(IImsCallSession newSession) {
if (mListener != null) {
if (newSession != null) {
- // Check if the active session is the same session that was
- // active before the merge request was sent.
- ImsCallSession validActiveSession = ImsCallSession.this;
- try {
- if (!Objects.equals(miSession.getCallId(), newSession.getCallId())) {
- // New session created after conference
- validActiveSession = new ImsCallSession(newSession);
- }
- } catch (RemoteException rex) {
- Log.e(TAG, "callSessionMergeComplete: exception for getCallId!");
- }
- mListener.callSessionMergeComplete(validActiveSession);
+ // New session created after conference
+ mListener.callSessionMergeComplete(new ImsCallSession(newSession));
} else {
// Session already exists. Hence no need to pass
mListener.callSessionMergeComplete(null);
diff --git a/telephony/java/android/telephony/ims/ImsRcsManager.java b/telephony/java/android/telephony/ims/ImsRcsManager.java
index b37d7c759be3..d3fb37f005cd 100644
--- a/telephony/java/android/telephony/ims/ImsRcsManager.java
+++ b/telephony/java/android/telephony/ims/ImsRcsManager.java
@@ -20,6 +20,8 @@ import android.Manifest;
import android.annotation.CallbackExecutor;
import android.annotation.NonNull;
import android.annotation.RequiresPermission;
+import android.annotation.SystemApi;
+import android.annotation.TestApi;
import android.content.Context;
import android.os.Binder;
import android.os.IBinder;
@@ -30,6 +32,7 @@ import android.telephony.ims.aidl.IImsCapabilityCallback;
import android.telephony.ims.aidl.IImsRcsController;
import android.telephony.ims.feature.ImsFeature;
import android.telephony.ims.feature.RcsFeature;
+import android.telephony.ims.stub.ImsRegistrationImplBase;
import android.util.Log;
import java.util.concurrent.Executor;
@@ -42,6 +45,8 @@ import java.util.function.Consumer;
* Use {@link ImsManager#getImsRcsManager(int)} to create an instance of this manager.
* @hide
*/
+@SystemApi
+@TestApi
public class ImsRcsManager implements RegistrationManager {
private static final String TAG = "ImsRcsManager";
@@ -105,7 +110,7 @@ public class ImsRcsManager implements RegistrationManager {
*
* @param capabilities The new availability of the capabilities.
*/
- public void onAvailabilityChanged(RcsFeature.RcsImsCapabilities capabilities) {
+ public void onAvailabilityChanged(@NonNull RcsFeature.RcsImsCapabilities capabilities) {
}
/**@hide*/
@@ -142,6 +147,7 @@ public class ImsRcsManager implements RegistrationManager {
/**{@inheritDoc}*/
@Override
+ @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
public void registerImsRegistrationCallback(
@NonNull @CallbackExecutor Executor executor,
@NonNull RegistrationCallback c)
@@ -159,6 +165,7 @@ public class ImsRcsManager implements RegistrationManager {
/**{@inheritDoc}*/
@Override
+ @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
public void unregisterImsRegistrationCallback(
@NonNull RegistrationManager.RegistrationCallback c) {
if (c == null) {
@@ -170,6 +177,7 @@ public class ImsRcsManager implements RegistrationManager {
/**{@inheritDoc}*/
@Override
+ @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
public void getRegistrationState(@NonNull @CallbackExecutor Executor executor,
@NonNull @ImsRegistrationState Consumer<Integer> stateCallback) {
if (stateCallback == null) {
@@ -184,6 +192,7 @@ public class ImsRcsManager implements RegistrationManager {
/**{@inheritDoc}*/
@Override
+ @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
public void getRegistrationTransportType(@NonNull @CallbackExecutor Executor executor,
@NonNull @AccessNetworkConstants.TransportType
Consumer<Integer> transportTypeCallback) {
@@ -219,7 +228,7 @@ public class ImsRcsManager implements RegistrationManager {
* becomes inactive. See {@link ImsException#getCode()} for more information on the error codes.
*/
@RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
- public void registerRcsAvailabilityCallback(@CallbackExecutor Executor executor,
+ public void registerRcsAvailabilityCallback(@NonNull @CallbackExecutor Executor executor,
@NonNull AvailabilityCallback c) throws ImsException {
if (c == null) {
throw new IllegalArgumentException("Must include a non-null AvailabilityCallback.");
@@ -231,13 +240,13 @@ public class ImsRcsManager implements RegistrationManager {
IImsRcsController imsRcsController = getIImsRcsController();
if (imsRcsController == null) {
Log.e(TAG, "Register availability callback: IImsRcsController is null");
- throw new ImsException("Can not find remote IMS service",
+ throw new ImsException("Cannot find remote IMS service",
ImsException.CODE_ERROR_SERVICE_UNAVAILABLE);
}
c.setExecutor(executor);
try {
- imsRcsController.registerRcsAvailabilityCallback(c.getBinder());
+ imsRcsController.registerRcsAvailabilityCallback(mSubId, c.getBinder());
} catch (RemoteException e) {
Log.e(TAG, "Error calling IImsRcsController#registerRcsAvailabilityCallback", e);
throw new ImsException("Remote IMS Service is not available",
@@ -267,12 +276,12 @@ public class ImsRcsManager implements RegistrationManager {
IImsRcsController imsRcsController = getIImsRcsController();
if (imsRcsController == null) {
Log.e(TAG, "Unregister availability callback: IImsRcsController is null");
- throw new ImsException("Can not find remote IMS service",
+ throw new ImsException("Cannot find remote IMS service",
ImsException.CODE_ERROR_SERVICE_UNAVAILABLE);
}
try {
- imsRcsController.unregisterRcsAvailabilityCallback(c.getBinder());
+ imsRcsController.unregisterRcsAvailabilityCallback(mSubId, c.getBinder());
} catch (RemoteException e) {
Log.e(TAG, "Error calling IImsRcsController#unregisterRcsAvailabilityCallback", e);
throw new ImsException("Remote IMS Service is not available",
@@ -287,6 +296,9 @@ public class ImsRcsManager implements RegistrationManager {
* RCS capabilities provided over-the-top by applications.
*
* @param capability The RCS capability to query.
+ * @param radioTech The radio tech that this capability failed for, defined as
+ * {@link ImsRegistrationImplBase#REGISTRATION_TECH_LTE} or
+ * {@link ImsRegistrationImplBase#REGISTRATION_TECH_IWLAN}.
* @return true if the RCS capability is capable for this subscription, false otherwise. This
* does not necessarily mean that we are registered for IMS and the capability is available, but
* rather the subscription is capable of this service over IMS.
@@ -297,17 +309,17 @@ public class ImsRcsManager implements RegistrationManager {
* See {@link ImsException#getCode()} for more information on the error codes.
*/
@RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
- public boolean isCapable(@RcsFeature.RcsImsCapabilities.RcsImsCapabilityFlag int capability)
- throws ImsException {
+ public boolean isCapable(@RcsFeature.RcsImsCapabilities.RcsImsCapabilityFlag int capability,
+ @ImsRegistrationImplBase.ImsRegistrationTech int radioTech) throws ImsException {
IImsRcsController imsRcsController = getIImsRcsController();
if (imsRcsController == null) {
Log.e(TAG, "isCapable: IImsRcsController is null");
- throw new ImsException("Can not find remote IMS service",
+ throw new ImsException("Cannot find remote IMS service",
ImsException.CODE_ERROR_SERVICE_UNAVAILABLE);
}
try {
- return imsRcsController.isCapable(mSubId, capability);
+ return imsRcsController.isCapable(mSubId, capability, radioTech);
} catch (RemoteException e) {
Log.e(TAG, "Error calling IImsRcsController#isCapable", e);
throw new ImsException("Remote IMS Service is not available",
@@ -336,7 +348,7 @@ public class ImsRcsManager implements RegistrationManager {
IImsRcsController imsRcsController = getIImsRcsController();
if (imsRcsController == null) {
Log.e(TAG, "isAvailable: IImsRcsController is null");
- throw new ImsException("Can not find remote IMS service",
+ throw new ImsException("Cannot find remote IMS service",
ImsException.CODE_ERROR_SERVICE_UNAVAILABLE);
}
diff --git a/telephony/java/android/telephony/ims/aidl/IImsRcsController.aidl b/telephony/java/android/telephony/ims/aidl/IImsRcsController.aidl
index b379bd0cd748..e81bac0f6764 100644
--- a/telephony/java/android/telephony/ims/aidl/IImsRcsController.aidl
+++ b/telephony/java/android/telephony/ims/aidl/IImsRcsController.aidl
@@ -26,9 +26,9 @@ import android.telephony.ims.aidl.IRcsUceControllerCallback;
* {@hide}
*/
interface IImsRcsController {
- void registerRcsAvailabilityCallback(IImsCapabilityCallback c);
- void unregisterRcsAvailabilityCallback(IImsCapabilityCallback c);
- boolean isCapable(int subId, int capability);
+ void registerRcsAvailabilityCallback(int subId, IImsCapabilityCallback c);
+ void unregisterRcsAvailabilityCallback(int subId, IImsCapabilityCallback c);
+ boolean isCapable(int subId, int capability, int radioTech);
boolean isAvailable(int subId, int capability);
// ImsUceAdapter specific
diff --git a/telephony/java/android/telephony/ims/feature/ImsFeature.java b/telephony/java/android/telephony/ims/feature/ImsFeature.java
index 72390d070337..4cb8575b8e93 100644
--- a/telephony/java/android/telephony/ims/feature/ImsFeature.java
+++ b/telephony/java/android/telephony/ims/feature/ImsFeature.java
@@ -22,7 +22,6 @@ import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.content.Context;
import android.os.IInterface;
-import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.telephony.SubscriptionManager;
import android.telephony.ims.aidl.IImsCapabilityCallback;
@@ -31,6 +30,7 @@ import android.util.Log;
import com.android.ims.internal.IImsFeatureStatusCallback;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.telephony.util.RemoteCallbackListExt;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -310,12 +310,12 @@ public abstract class ImsFeature {
/** @hide */
protected final Object mLock = new Object();
- private final RemoteCallbackList<IImsFeatureStatusCallback> mStatusCallbacks =
- new RemoteCallbackList<>();
+ private final RemoteCallbackListExt<IImsFeatureStatusCallback> mStatusCallbacks =
+ new RemoteCallbackListExt<>();
private @ImsState int mState = STATE_UNAVAILABLE;
private int mSlotId = SubscriptionManager.INVALID_SIM_SLOT_INDEX;
- private final RemoteCallbackList<IImsCapabilityCallback> mCapabilityCallbacks =
- new RemoteCallbackList<>();
+ private final RemoteCallbackListExt<IImsCapabilityCallback> mCapabilityCallbacks =
+ new RemoteCallbackListExt<>();
private Capabilities mCapabilityStatus = new Capabilities();
/**
@@ -391,7 +391,7 @@ public abstract class ImsFeature {
* Internal method called by ImsFeature when setFeatureState has changed.
*/
private void notifyFeatureState(@ImsState int state) {
- mStatusCallbacks.broadcast((c) -> {
+ mStatusCallbacks.broadcastAction((c) -> {
try {
c.notifyImsFeatureStatus(state);
} catch (RemoteException e) {
@@ -470,7 +470,7 @@ public abstract class ImsFeature {
synchronized (mLock) {
mCapabilityStatus = caps.copy();
}
- mCapabilityCallbacks.broadcast((callback) -> {
+ mCapabilityCallbacks.broadcastAction((callback) -> {
try {
callback.onCapabilitiesStatusChanged(caps.mCapabilities);
} catch (RemoteException e) {
diff --git a/telephony/java/android/telephony/ims/feature/RcsFeature.java b/telephony/java/android/telephony/ims/feature/RcsFeature.java
index 0eaf8dc2fd51..884a0bc7c06e 100644
--- a/telephony/java/android/telephony/ims/feature/RcsFeature.java
+++ b/telephony/java/android/telephony/ims/feature/RcsFeature.java
@@ -193,7 +193,6 @@ public class RcsFeature extends ImsFeature {
* of the capability and notify the capability status as true using
* {@link #notifyCapabilitiesStatusChanged(RcsImsCapabilities)}. This will signal to the
* framework that the capability is available for usage.
- * @hide
*/
public static class RcsImsCapabilities extends Capabilities {
/** @hide*/
@@ -207,7 +206,6 @@ public class RcsFeature extends ImsFeature {
/**
* Undefined capability type for initialization
- * @hide
*/
public static final int CAPABILITY_TYPE_NONE = 0;
@@ -215,7 +213,6 @@ public class RcsFeature extends ImsFeature {
* This carrier supports User Capability Exchange using SIP OPTIONS as defined by the
* framework. If set, the RcsFeature should support capability exchange using SIP OPTIONS.
* If not set, this RcsFeature should not service capability requests.
- * @hide
*/
public static final int CAPABILITY_TYPE_OPTIONS_UCE = 1 << 0;
@@ -224,33 +221,27 @@ public class RcsFeature extends ImsFeature {
* framework. If set, the RcsFeature should support capability exchange using a presence
* server. If not set, this RcsFeature should not publish capabilities or service capability
* requests using presence.
- * @hide
*/
public static final int CAPABILITY_TYPE_PRESENCE_UCE = 1 << 1;
- /**@hide*/
public RcsImsCapabilities(@RcsImsCapabilityFlag int capabilities) {
super(capabilities);
}
- /**@hide*/
private RcsImsCapabilities(Capabilities c) {
super(c.getMask());
}
- /**@hide*/
@Override
public void addCapabilities(@RcsImsCapabilityFlag int capabilities) {
super.addCapabilities(capabilities);
}
- /**@hide*/
@Override
public void removeCapabilities(@RcsImsCapabilityFlag int capabilities) {
super.removeCapabilities(capabilities);
}
- /**@hide*/
@Override
public boolean isCapable(@RcsImsCapabilityFlag int capabilities) {
return super.isCapable(capabilities);
@@ -295,10 +286,9 @@ public class RcsFeature extends ImsFeature {
* set, the {@link RcsFeature} has brought up the capability and is ready for framework
* requests. To change the status of the capabilities
* {@link #notifyCapabilitiesStatusChanged(RcsImsCapabilities)} should be called.
- * @hide
*/
@Override
- public final RcsImsCapabilities queryCapabilityStatus() {
+ public @NonNull final RcsImsCapabilities queryCapabilityStatus() {
return new RcsImsCapabilities(super.queryCapabilityStatus());
}
@@ -306,7 +296,6 @@ public class RcsFeature extends ImsFeature {
* Notify the framework that the capabilities status has changed. If a capability is enabled,
* this signals to the framework that the capability has been initialized and is ready.
* Call {@link #queryCapabilityStatus()} to return the current capability status.
- * @hide
*/
public final void notifyCapabilitiesStatusChanged(@NonNull RcsImsCapabilities c) {
if (c == null) {
@@ -321,7 +310,6 @@ public class RcsFeature extends ImsFeature {
* {@link #changeEnabledCapabilities(CapabilityChangeRequest, CapabilityCallbackProxy)} to
* enable or disable capability A, this method should return the correct configuration for
* capability A afterwards (until it has changed).
- * @hide
*/
public boolean queryCapabilityConfiguration(
@RcsImsCapabilities.RcsImsCapabilityFlag int capability,
@@ -343,11 +331,10 @@ public class RcsFeature extends ImsFeature {
* If for some reason one or more of these capabilities can not be enabled/disabled,
* {@link CapabilityCallbackProxy#onChangeCapabilityConfigurationError(int, int, int)} should
* be called for each capability change that resulted in an error.
- * @hide
*/
@Override
- public void changeEnabledCapabilities(CapabilityChangeRequest request,
- CapabilityCallbackProxy c) {
+ public void changeEnabledCapabilities(@NonNull CapabilityChangeRequest request,
+ @NonNull CapabilityCallbackProxy c) {
// Base Implementation - Override to provide functionality
}
diff --git a/telephony/java/android/telephony/ims/stub/ImsConfigImplBase.java b/telephony/java/android/telephony/ims/stub/ImsConfigImplBase.java
index 4c0de7f9c1b7..d18e93c7e8bf 100644
--- a/telephony/java/android/telephony/ims/stub/ImsConfigImplBase.java
+++ b/telephony/java/android/telephony/ims/stub/ImsConfigImplBase.java
@@ -21,7 +21,6 @@ import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.content.Context;
import android.os.PersistableBundle;
-import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.telephony.ims.aidl.IImsConfig;
import android.telephony.ims.aidl.IImsConfigCallback;
@@ -29,6 +28,7 @@ import android.util.Log;
import com.android.ims.ImsConfig;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.telephony.util.RemoteCallbackListExt;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -248,7 +248,8 @@ public class ImsConfigImplBase {
})
public @interface SetConfigResult {}
- private final RemoteCallbackList<IImsConfigCallback> mCallbacks = new RemoteCallbackList<>();
+ private final RemoteCallbackListExt<IImsConfigCallback> mCallbacks =
+ new RemoteCallbackListExt<>();
ImsConfigStub mImsConfigStub;
/**
@@ -289,7 +290,7 @@ public class ImsConfigImplBase {
if (mCallbacks == null) {
return;
}
- mCallbacks.broadcast(c -> {
+ mCallbacks.broadcastAction(c -> {
try {
c.onIntConfigChanged(item, value);
} catch (RemoteException e) {
@@ -303,7 +304,7 @@ public class ImsConfigImplBase {
if (mCallbacks == null) {
return;
}
- mCallbacks.broadcast(c -> {
+ mCallbacks.broadcastAction(c -> {
try {
c.onStringConfigChanged(item, value);
} catch (RemoteException e) {
diff --git a/telephony/java/android/telephony/ims/stub/ImsRegistrationImplBase.java b/telephony/java/android/telephony/ims/stub/ImsRegistrationImplBase.java
index c0f16e5f9fbc..14a64d2585ed 100644
--- a/telephony/java/android/telephony/ims/stub/ImsRegistrationImplBase.java
+++ b/telephony/java/android/telephony/ims/stub/ImsRegistrationImplBase.java
@@ -20,7 +20,6 @@ import android.annotation.IntDef;
import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.net.Uri;
-import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.telephony.ims.ImsReasonInfo;
import android.telephony.ims.RegistrationManager;
@@ -29,6 +28,7 @@ import android.telephony.ims.aidl.IImsRegistrationCallback;
import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.telephony.util.RemoteCallbackListExt;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -94,8 +94,8 @@ public class ImsRegistrationImplBase {
}
};
- private final RemoteCallbackList<IImsRegistrationCallback> mCallbacks
- = new RemoteCallbackList<>();
+ private final RemoteCallbackListExt<IImsRegistrationCallback> mCallbacks =
+ new RemoteCallbackListExt<>();
private final Object mLock = new Object();
// Locked on mLock
private @ImsRegistrationTech
@@ -129,7 +129,7 @@ public class ImsRegistrationImplBase {
*/
public final void onRegistered(@ImsRegistrationTech int imsRadioTech) {
updateToState(imsRadioTech, RegistrationManager.REGISTRATION_STATE_REGISTERED);
- mCallbacks.broadcast((c) -> {
+ mCallbacks.broadcastAction((c) -> {
try {
c.onRegistered(imsRadioTech);
} catch (RemoteException e) {
@@ -147,7 +147,7 @@ public class ImsRegistrationImplBase {
*/
public final void onRegistering(@ImsRegistrationTech int imsRadioTech) {
updateToState(imsRadioTech, RegistrationManager.REGISTRATION_STATE_REGISTERING);
- mCallbacks.broadcast((c) -> {
+ mCallbacks.broadcastAction((c) -> {
try {
c.onRegistering(imsRadioTech);
} catch (RemoteException e) {
@@ -175,7 +175,7 @@ public class ImsRegistrationImplBase {
*/
public final void onDeregistered(ImsReasonInfo info) {
updateToDisconnectedState(info);
- mCallbacks.broadcast((c) -> {
+ mCallbacks.broadcastAction((c) -> {
try {
c.onDeregistered(info);
} catch (RemoteException e) {
@@ -194,7 +194,7 @@ public class ImsRegistrationImplBase {
*/
public final void onTechnologyChangeFailed(@ImsRegistrationTech int imsRadioTech,
ImsReasonInfo info) {
- mCallbacks.broadcast((c) -> {
+ mCallbacks.broadcastAction((c) -> {
try {
c.onTechnologyChangeFailed(imsRadioTech, info);
} catch (RemoteException e) {
@@ -210,7 +210,7 @@ public class ImsRegistrationImplBase {
* @param uris
*/
public final void onSubscriberAssociatedUriChanged(Uri[] uris) {
- mCallbacks.broadcast((c) -> {
+ mCallbacks.broadcastAction((c) -> {
try {
c.onSubscriberAssociatedUriChanged(uris);
} catch (RemoteException e) {
diff --git a/telephony/java/com/android/ims/ImsConfig.java b/telephony/java/com/android/ims/ImsConfig.java
index 4fc6a19d1f38..cfc803ca3639 100644
--- a/telephony/java/com/android/ims/ImsConfig.java
+++ b/telephony/java/com/android/ims/ImsConfig.java
@@ -17,7 +17,6 @@
package com.android.ims;
import android.os.Handler;
-import android.os.HandlerExecutor;
import android.os.Looper;
import android.os.RemoteException;
import android.telephony.Rlog;
@@ -26,6 +25,8 @@ import android.telephony.ims.ProvisioningManager;
import android.telephony.ims.aidl.IImsConfig;
import android.telephony.ims.aidl.IImsConfigCallback;
+import com.android.internal.telephony.util.HandlerExecutor;
+
import java.util.concurrent.Executor;
/**
diff --git a/telephony/java/com/android/internal/telephony/ISms.aidl b/telephony/java/com/android/internal/telephony/ISms.aidl
index ac4c8ecea842..9f4d066ff8b4 100644
--- a/telephony/java/com/android/internal/telephony/ISms.aidl
+++ b/telephony/java/com/android/internal/telephony/ISms.aidl
@@ -594,4 +594,12 @@ interface ISms {
* @return true for success, false otherwise.
*/
boolean setSmscAddressOnIccEfForSubscriber(String smsc, int subId, String callingPackage);
+
+ /**
+ * Get the capacity count of sms on Icc card.
+ *
+ * @param subId for subId which getSmsCapacityOnIcc is queried.
+ * @return capacity of ICC
+ */
+ int getSmsCapacityOnIccForSubscriber(int subId);
}
diff --git a/telephony/java/com/android/internal/telephony/ISmsImplBase.java b/telephony/java/com/android/internal/telephony/ISmsImplBase.java
index 9865f76d2580..2430d8237d9c 100644
--- a/telephony/java/com/android/internal/telephony/ISmsImplBase.java
+++ b/telephony/java/com/android/internal/telephony/ISmsImplBase.java
@@ -211,4 +211,9 @@ public class ISmsImplBase extends ISms.Stub {
String smsc, int subId, String callingPackage) {
throw new UnsupportedOperationException();
}
+
+ @Override
+ public int getSmsCapacityOnIccForSubscriber(int subId) {
+ throw new UnsupportedOperationException();
+ }
}
diff --git a/telephony/java/com/android/internal/telephony/ITelephony.aidl b/telephony/java/com/android/internal/telephony/ITelephony.aidl
index 0ec54ecf56df..97b24aef4af5 100644
--- a/telephony/java/com/android/internal/telephony/ITelephony.aidl
+++ b/telephony/java/com/android/internal/telephony/ITelephony.aidl
@@ -888,12 +888,13 @@ interface ITelephony {
/**
* @return true if the ImsService to bind to for the slot id specified was set, false otherwise.
*/
- boolean setImsService(int slotId, boolean isCarrierImsService, String packageName);
+ boolean setBoundImsServiceOverride(int slotIndex, boolean isCarrierService,
+ in int[] featureTypes, in String packageName);
/**
* @return the package name of the carrier/device ImsService associated with this slot.
*/
- String getImsService(int slotId, boolean isCarrierImsService);
+ String getBoundImsServicePackage(int slotIndex, boolean isCarrierImsService, int featureType);
/**
* Get the MmTelFeature state attached to this subscription id.
diff --git a/telephony/java/com/android/internal/telephony/IccCardConstants.java b/telephony/java/com/android/internal/telephony/IccCardConstants.java
index 6ff27b1152c8..25f03c200610 100644
--- a/telephony/java/com/android/internal/telephony/IccCardConstants.java
+++ b/telephony/java/com/android/internal/telephony/IccCardConstants.java
@@ -15,6 +15,7 @@
*/
package com.android.internal.telephony;
+import android.content.Intent;
import android.telephony.TelephonyManager;
import dalvik.annotation.compat.UnsupportedAppUsage;
@@ -25,37 +26,38 @@ import dalvik.annotation.compat.UnsupportedAppUsage;
public class IccCardConstants {
/* The extra data for broadcasting intent INTENT_ICC_STATE_CHANGE */
- public static final String INTENT_KEY_ICC_STATE = "ss";
+ public static final String INTENT_KEY_ICC_STATE = Intent.EXTRA_SIM_STATE;
/* UNKNOWN means the ICC state is unknown */
- public static final String INTENT_VALUE_ICC_UNKNOWN = "UNKNOWN";
+ public static final String INTENT_VALUE_ICC_UNKNOWN = Intent.SIM_STATE_UNKNOWN;
/* NOT_READY means the ICC interface is not ready (eg, radio is off or powering on) */
- public static final String INTENT_VALUE_ICC_NOT_READY = "NOT_READY";
+ public static final String INTENT_VALUE_ICC_NOT_READY = Intent.SIM_STATE_NOT_READY;
/* ABSENT means ICC is missing */
- public static final String INTENT_VALUE_ICC_ABSENT = "ABSENT";
+ public static final String INTENT_VALUE_ICC_ABSENT = Intent.SIM_STATE_ABSENT;
/* PRESENT means ICC is present */
- public static final String INTENT_VALUE_ICC_PRESENT = "PRESENT";
+ public static final String INTENT_VALUE_ICC_PRESENT = Intent.SIM_STATE_PRESENT;
/* CARD_IO_ERROR means for three consecutive times there was SIM IO error */
- static public final String INTENT_VALUE_ICC_CARD_IO_ERROR = "CARD_IO_ERROR";
+ static public final String INTENT_VALUE_ICC_CARD_IO_ERROR = Intent.SIM_STATE_CARD_IO_ERROR;
/* CARD_RESTRICTED means card is present but not usable due to carrier restrictions */
- static public final String INTENT_VALUE_ICC_CARD_RESTRICTED = "CARD_RESTRICTED";
+ static public final String INTENT_VALUE_ICC_CARD_RESTRICTED = Intent.SIM_STATE_CARD_RESTRICTED;
/* LOCKED means ICC is locked by pin or by network */
- public static final String INTENT_VALUE_ICC_LOCKED = "LOCKED";
+ public static final String INTENT_VALUE_ICC_LOCKED = Intent.SIM_STATE_LOCKED;
/* READY means ICC is ready to access */
- public static final String INTENT_VALUE_ICC_READY = "READY";
+ public static final String INTENT_VALUE_ICC_READY = Intent.SIM_STATE_READY;
/* IMSI means ICC IMSI is ready in property */
- public static final String INTENT_VALUE_ICC_IMSI = "IMSI";
+ public static final String INTENT_VALUE_ICC_IMSI = Intent.SIM_STATE_IMSI;
/* LOADED means all ICC records, including IMSI, are loaded */
- public static final String INTENT_VALUE_ICC_LOADED = "LOADED";
+ public static final String INTENT_VALUE_ICC_LOADED = Intent.SIM_STATE_LOADED;
/* The extra data for broadcasting intent INTENT_ICC_STATE_CHANGE */
- public static final String INTENT_KEY_LOCKED_REASON = "reason";
+ public static final String INTENT_KEY_LOCKED_REASON = Intent.EXTRA_SIM_LOCKED_REASON;
/* PIN means ICC is locked on PIN1 */
- public static final String INTENT_VALUE_LOCKED_ON_PIN = "PIN";
+ public static final String INTENT_VALUE_LOCKED_ON_PIN = Intent.SIM_LOCKED_ON_PIN;
/* PUK means ICC is locked on PUK1 */
- public static final String INTENT_VALUE_LOCKED_ON_PUK = "PUK";
+ public static final String INTENT_VALUE_LOCKED_ON_PUK = Intent.SIM_LOCKED_ON_PUK;
/* NETWORK means ICC is locked on NETWORK PERSONALIZATION */
- public static final String INTENT_VALUE_LOCKED_NETWORK = "NETWORK";
+ public static final String INTENT_VALUE_LOCKED_NETWORK = Intent.SIM_LOCKED_NETWORK;
/* PERM_DISABLED means ICC is permanently disabled due to puk fails */
- public static final String INTENT_VALUE_ABSENT_ON_PERM_DISABLED = "PERM_DISABLED";
+ public static final String INTENT_VALUE_ABSENT_ON_PERM_DISABLED =
+ Intent.SIM_ABSENT_ON_PERM_DISABLED;
/**
* This is combination of IccCardStatus.CardState and IccCardApplicationStatus.AppState
diff --git a/telephony/java/com/android/internal/telephony/PhoneConstantConversions.java b/telephony/java/com/android/internal/telephony/PhoneConstantConversions.java
index f7f0f29fcb29..8640acca7c8c 100644
--- a/telephony/java/com/android/internal/telephony/PhoneConstantConversions.java
+++ b/telephony/java/com/android/internal/telephony/PhoneConstantConversions.java
@@ -16,14 +16,10 @@
package com.android.internal.telephony;
-import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
-import android.telephony.PreciseCallState;
import com.android.internal.telephony.PhoneConstants;
-import java.util.List;
-
public class PhoneConstantConversions {
/**
* Convert the {@link PhoneConstants.State} enum into the TelephonyManager.CALL_STATE_*
@@ -67,6 +63,8 @@ public class PhoneConstantConversions {
return TelephonyManager.DATA_CONNECTED;
case SUSPENDED:
return TelephonyManager.DATA_SUSPENDED;
+ case DISCONNECTING:
+ return TelephonyManager.DATA_DISCONNECTING;
default:
return TelephonyManager.DATA_DISCONNECTED;
}
@@ -84,6 +82,8 @@ public class PhoneConstantConversions {
return PhoneConstants.DataState.CONNECTED;
case TelephonyManager.DATA_SUSPENDED:
return PhoneConstants.DataState.SUSPENDED;
+ case TelephonyManager.DATA_DISCONNECTING:
+ return PhoneConstants.DataState.DISCONNECTING;
default:
return PhoneConstants.DataState.DISCONNECTED;
}
diff --git a/telephony/java/com/android/internal/telephony/PhoneConstants.java b/telephony/java/com/android/internal/telephony/PhoneConstants.java
index c19ae7b3916a..fadb5739e31f 100644
--- a/telephony/java/com/android/internal/telephony/PhoneConstants.java
+++ b/telephony/java/com/android/internal/telephony/PhoneConstants.java
@@ -46,6 +46,7 @@ public class PhoneConstants {
* <ul>
* <li>CONNECTED = IP traffic should be available</li>
* <li>CONNECTING = Currently setting up data connection</li>
+ * <li>DISCONNECTING = IP temporarily available</li>
* <li>DISCONNECTED = IP not available</li>
* <li>SUSPENDED = connection is created but IP traffic is
* temperately not available. i.e. voice call is in place
@@ -55,10 +56,15 @@ public class PhoneConstants {
@UnsupportedAppUsage(implicitMember =
"values()[Lcom/android/internal/telephony/PhoneConstants$DataState;")
public enum DataState {
- @UnsupportedAppUsage CONNECTED,
- @UnsupportedAppUsage CONNECTING,
- @UnsupportedAppUsage DISCONNECTED,
- @UnsupportedAppUsage SUSPENDED;
+ @UnsupportedAppUsage
+ CONNECTED,
+ @UnsupportedAppUsage
+ CONNECTING,
+ @UnsupportedAppUsage
+ DISCONNECTED,
+ @UnsupportedAppUsage
+ SUSPENDED,
+ DISCONNECTING;
};
public static final String STATE_KEY = "state";
@@ -91,20 +97,12 @@ public class PhoneConstants {
public static final String PHONE_NAME_KEY = "phoneName";
public static final String DATA_NETWORK_TYPE_KEY = "networkType";
- public static final String DATA_FAILURE_CAUSE_KEY = "failCause";
public static final String DATA_APN_TYPE_KEY = "apnType";
public static final String DATA_APN_KEY = "apn";
- public static final String DATA_LINK_PROPERTIES_KEY = "linkProperties";
- public static final String DATA_NETWORK_CAPABILITIES_KEY = "networkCapabilities";
- public static final String DATA_IFACE_NAME_KEY = "iface";
- public static final String NETWORK_UNAVAILABLE_KEY = "networkUnvailable";
- public static final String DATA_NETWORK_ROAMING_KEY = "networkRoaming";
public static final String PHONE_IN_ECM_STATE = "phoneinECMState";
public static final String PHONE_IN_EMERGENCY_CALL = "phoneInEmergencyCall";
- public static final String REASON_LINK_PROPERTIES_CHANGED = "linkPropertiesChanged";
-
/**
* Return codes for supplyPinReturnResult and
* supplyPukReturnResult APIs
@@ -154,6 +152,8 @@ public class PhoneConstants {
public static final String APN_TYPE_EMERGENCY = "emergency";
/** APN type for Mission Critical Services */
public static final String APN_TYPE_MCX = "mcx";
+ /** APN type for XCAP */
+ public static final String APN_TYPE_XCAP = "xcap";
/** Array of all APN types */
public static final String[] APN_TYPES = {APN_TYPE_DEFAULT,
APN_TYPE_MMS,
@@ -165,7 +165,8 @@ public class PhoneConstants {
APN_TYPE_CBS,
APN_TYPE_IA,
APN_TYPE_EMERGENCY,
- APN_TYPE_MCX
+ APN_TYPE_MCX,
+ APN_TYPE_XCAP,
};
public static final int RIL_CARD_MAX_APPS = 8;
@@ -182,10 +183,6 @@ public class PhoneConstants {
public static final String SLOT_KEY = "slot";
- /** Fired when a subscriptions phone state changes. */
- public static final String ACTION_SUBSCRIPTION_PHONE_STATE_CHANGED =
- "android.intent.action.SUBSCRIPTION_PHONE_STATE";
-
// FIXME: This is used to pass a subId via intents, we need to look at its usage, which is
// FIXME: extensive, and see if this should be an array of all active subId's or ...?
/**
diff --git a/telephony/java/com/android/internal/telephony/RILConstants.java b/telephony/java/com/android/internal/telephony/RILConstants.java
index 22168c54510b..9cbcd7fc6b04 100644
--- a/telephony/java/com/android/internal/telephony/RILConstants.java
+++ b/telephony/java/com/android/internal/telephony/RILConstants.java
@@ -489,6 +489,8 @@ public interface RILConstants {
int RIL_REQUEST_EMERGENCY_DIAL = 205;
int RIL_REQUEST_GET_PHONE_CAPABILITY = 206;
int RIL_REQUEST_SWITCH_DUAL_SIM_CONFIG = 207;
+ int RIL_REQUEST_ENABLE_UICC_APPLICATIONS = 208;
+ int RIL_REQUEST_GET_UICC_APPLICATIONS_ENABLEMENT = 209;
/* Responses begin */
int RIL_RESPONSE_ACKNOWLEDGEMENT = 800;
@@ -552,4 +554,5 @@ public interface RILConstants {
int RIL_UNSOL_ICC_SLOT_STATUS = 1100;
int RIL_UNSOL_PHYSICAL_CHANNEL_CONFIG = 1101;
int RIL_UNSOL_EMERGENCY_NUMBER_LIST = 1102;
+ int RIL_UNSOL_UICC_APPLICATIONS_ENABLEMENT_CHANGED = 1103;
}
diff --git a/telephony/java/com/android/internal/telephony/TelephonyIntents.java b/telephony/java/com/android/internal/telephony/TelephonyIntents.java
index 8b62872b77af..8e1a78c56e0a 100644
--- a/telephony/java/com/android/internal/telephony/TelephonyIntents.java
+++ b/telephony/java/com/android/internal/telephony/TelephonyIntents.java
@@ -225,41 +225,6 @@ public class TelephonyIntents {
public static final String EXTRA_REBROADCAST_ON_UNLOCK= "rebroadcastOnUnlock";
/**
- * Broadcast Action: The time was set by the carrier (typically by the NITZ string).
- * This is a sticky broadcast.
- * The intent will have the following extra values:</p>
- * <ul>
- * <li><em>time</em> - The time as a long in UTC milliseconds.</li>
- * </ul>
- *
- * <p class="note">
- * Requires the READ_PHONE_STATE permission.
- *
- * <p class="note">This is a protected intent that can only be sent
- * by the system.
- */
- public static final String ACTION_NETWORK_SET_TIME = "android.intent.action.NETWORK_SET_TIME";
-
-
- /**
- * Broadcast Action: The timezone was set by the carrier (typically by the NITZ string).
- * This is a sticky broadcast.
- * The intent will have the following extra values:</p>
- * <ul>
- * <li><em>time-zone</em> - The java.util.TimeZone.getID() value identifying the new time
- * zone.</li>
- * </ul>
- *
- * <p class="note">
- * Requires the READ_PHONE_STATE permission.
- *
- * <p class="note">This is a protected intent that can only be sent
- * by the system.
- */
- public static final String ACTION_NETWORK_SET_TIMEZONE
- = "android.intent.action.NETWORK_SET_TIMEZONE";
-
- /**
* <p>Broadcast Action: It indicates the Emergency callback mode blocks datacall/sms
* <p class="note">.
* This is to pop up a notice to show user that the phone is in emergency callback mode
diff --git a/telephony/java/com/android/internal/telephony/gsm/GsmSmsCbMessage.java b/telephony/java/com/android/internal/telephony/gsm/GsmSmsCbMessage.java
deleted file mode 100644
index c16eafb41dde..000000000000
--- a/telephony/java/com/android/internal/telephony/gsm/GsmSmsCbMessage.java
+++ /dev/null
@@ -1,521 +0,0 @@
-/*
- * 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 com.android.internal.telephony.gsm;
-
-import static android.telephony.SmsCbEtwsInfo.ETWS_WARNING_TYPE_EARTHQUAKE;
-import static android.telephony.SmsCbEtwsInfo.ETWS_WARNING_TYPE_EARTHQUAKE_AND_TSUNAMI;
-import static android.telephony.SmsCbEtwsInfo.ETWS_WARNING_TYPE_OTHER_EMERGENCY;
-import static android.telephony.SmsCbEtwsInfo.ETWS_WARNING_TYPE_TEST_MESSAGE;
-import static android.telephony.SmsCbEtwsInfo.ETWS_WARNING_TYPE_TSUNAMI;
-
-import android.annotation.NonNull;
-import android.content.Context;
-import android.content.res.Resources;
-import android.telephony.CbGeoUtils;
-import android.telephony.CbGeoUtils.Circle;
-import android.telephony.CbGeoUtils.Geometry;
-import android.telephony.CbGeoUtils.LatLng;
-import android.telephony.CbGeoUtils.Polygon;
-import android.telephony.Rlog;
-import android.telephony.SmsCbLocation;
-import android.telephony.SmsCbMessage;
-import android.telephony.SubscriptionManager;
-import android.util.Pair;
-
-import com.android.internal.R;
-import com.android.internal.telephony.GsmAlphabet;
-import com.android.internal.telephony.SmsConstants;
-import com.android.internal.telephony.gsm.GsmSmsCbMessage.GeoFencingTriggerMessage.CellBroadcastIdentity;
-import com.android.internal.telephony.gsm.SmsCbHeader.DataCodingScheme;
-
-import java.io.UnsupportedEncodingException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.stream.Collectors;
-
-/**
- * Parses a GSM or UMTS format SMS-CB message into an {@link SmsCbMessage} object. The class is
- * public because {@link #createSmsCbMessage(SmsCbLocation, byte[][])} is used by some test cases.
- */
-public class GsmSmsCbMessage {
- private static final String TAG = GsmSmsCbMessage.class.getSimpleName();
-
- private static final char CARRIAGE_RETURN = 0x0d;
-
- private static final int PDU_BODY_PAGE_LENGTH = 82;
-
- /** Utility class with only static methods. */
- private GsmSmsCbMessage() { }
-
- /**
- * Get built-in ETWS primary messages by category. ETWS primary message does not contain text,
- * so we have to show the pre-built messages to the user.
- *
- * @param context Device context
- * @param category ETWS message category defined in SmsCbConstants
- * @return ETWS text message in string. Return an empty string if no match.
- */
- private static String getEtwsPrimaryMessage(Context context, int category) {
- final Resources r = context.getResources();
- switch (category) {
- case ETWS_WARNING_TYPE_EARTHQUAKE:
- return r.getString(R.string.etws_primary_default_message_earthquake);
- case ETWS_WARNING_TYPE_TSUNAMI:
- return r.getString(R.string.etws_primary_default_message_tsunami);
- case ETWS_WARNING_TYPE_EARTHQUAKE_AND_TSUNAMI:
- return r.getString(R.string.etws_primary_default_message_earthquake_and_tsunami);
- case ETWS_WARNING_TYPE_TEST_MESSAGE:
- return r.getString(R.string.etws_primary_default_message_test);
- case ETWS_WARNING_TYPE_OTHER_EMERGENCY:
- return r.getString(R.string.etws_primary_default_message_others);
- default:
- return "";
- }
- }
-
- /**
- * Create a new SmsCbMessage object from a header object plus one or more received PDUs.
- *
- * @param pdus PDU bytes
- * @slotIndex slotIndex for which received sms cb message
- */
- public static SmsCbMessage createSmsCbMessage(Context context, SmsCbHeader header,
- SmsCbLocation location, byte[][] pdus, int slotIndex)
- throws IllegalArgumentException {
- SubscriptionManager sm = (SubscriptionManager) context.getSystemService(
- Context.TELEPHONY_SUBSCRIPTION_SERVICE);
- int subId = SubscriptionManager.DEFAULT_SUBSCRIPTION_ID;
- int[] subIds = sm.getSubscriptionIds(slotIndex);
- if (subIds != null && subIds.length > 0) {
- subId = subIds[0];
- }
-
- long receivedTimeMillis = System.currentTimeMillis();
- if (header.isEtwsPrimaryNotification()) {
- // ETSI TS 23.041 ETWS Primary Notification message
- // ETWS primary message only contains 4 fields including serial number,
- // message identifier, warning type, and warning security information.
- // There is no field for the content/text so we get the text from the resources.
- return new SmsCbMessage(SmsCbMessage.MESSAGE_FORMAT_3GPP, header.getGeographicalScope(),
- header.getSerialNumber(), location, header.getServiceCategory(), null,
- getEtwsPrimaryMessage(context, header.getEtwsInfo().getWarningType()),
- SmsCbMessage.MESSAGE_PRIORITY_EMERGENCY, header.getEtwsInfo(),
- header.getCmasInfo(), 0, null /* geometries */, receivedTimeMillis, slotIndex,
- subId);
- } else if (header.isUmtsFormat()) {
- // UMTS format has only 1 PDU
- byte[] pdu = pdus[0];
- Pair<String, String> cbData = parseUmtsBody(header, pdu);
- String language = cbData.first;
- String body = cbData.second;
- int priority = header.isEmergencyMessage() ? SmsCbMessage.MESSAGE_PRIORITY_EMERGENCY
- : SmsCbMessage.MESSAGE_PRIORITY_NORMAL;
- int nrPages = pdu[SmsCbHeader.PDU_HEADER_LENGTH];
- int wacDataOffset = SmsCbHeader.PDU_HEADER_LENGTH
- + 1 // number of pages
- + (PDU_BODY_PAGE_LENGTH + 1) * nrPages; // cb data
-
- // Has Warning Area Coordinates information
- List<Geometry> geometries = null;
- int maximumWaitingTimeSec = 255;
- if (pdu.length > wacDataOffset) {
- try {
- Pair<Integer, List<Geometry>> wac = parseWarningAreaCoordinates(pdu,
- wacDataOffset);
- maximumWaitingTimeSec = wac.first;
- geometries = wac.second;
- } catch (Exception ex) {
- // Catch the exception here, the message will be considered as having no WAC
- // information which means the message will be broadcasted directly.
- Rlog.e(TAG, "Can't parse warning area coordinates, ex = " + ex.toString());
- }
- }
-
- return new SmsCbMessage(SmsCbMessage.MESSAGE_FORMAT_3GPP,
- header.getGeographicalScope(), header.getSerialNumber(), location,
- header.getServiceCategory(), language, body, priority,
- header.getEtwsInfo(), header.getCmasInfo(), maximumWaitingTimeSec, geometries,
- receivedTimeMillis, slotIndex, subId);
- } else {
- String language = null;
- StringBuilder sb = new StringBuilder();
- for (byte[] pdu : pdus) {
- Pair<String, String> p = parseGsmBody(header, pdu);
- language = p.first;
- sb.append(p.second);
- }
- int priority = header.isEmergencyMessage() ? SmsCbMessage.MESSAGE_PRIORITY_EMERGENCY
- : SmsCbMessage.MESSAGE_PRIORITY_NORMAL;
-
- return new SmsCbMessage(SmsCbMessage.MESSAGE_FORMAT_3GPP,
- header.getGeographicalScope(), header.getSerialNumber(), location,
- header.getServiceCategory(), language, sb.toString(), priority,
- header.getEtwsInfo(), header.getCmasInfo(), 0, null /* geometries */,
- receivedTimeMillis, slotIndex, subId);
- }
- }
-
- /**
- * Parse WEA Handset Action Message(WHAM) a.k.a geo-fencing trigger message.
- *
- * WEA Handset Action Message(WHAM) is a cell broadcast service message broadcast by the network
- * to direct devices to perform a geo-fencing check on selected alerts.
- *
- * WEA Handset Action Message(WHAM) requirements from ATIS-0700041 section 4
- * 1. The Warning Message contents of a WHAM shall be in Cell Broadcast(CB) data format as
- * defined in TS 23.041.
- * 2. The Warning Message Contents of WHAM shall be limited to one CB page(max 20 referenced
- * WEA messages).
- * 3. The broadcast area for a WHAM shall be the union of the broadcast areas of the referenced
- * WEA message.
- * @param pdu cell broadcast pdu, including the header
- * @return {@link GeoFencingTriggerMessage} instance
- */
- public static GeoFencingTriggerMessage createGeoFencingTriggerMessage(byte[] pdu) {
- try {
- // Header length + 1(number of page). ATIS-0700041 define the number of page of
- // geo-fencing trigger message is 1.
- int whamOffset = SmsCbHeader.PDU_HEADER_LENGTH + 1;
-
- BitStreamReader bitReader = new BitStreamReader(pdu, whamOffset);
- int type = bitReader.read(4);
- int length = bitReader.read(7);
- // Skip the remained 5 bits
- bitReader.skip();
-
- int messageIdentifierCount = (length - 2) * 8 / 32;
- List<CellBroadcastIdentity> cbIdentifiers = new ArrayList<>();
- for (int i = 0; i < messageIdentifierCount; i++) {
- // Both messageIdentifier and serialNumber are 16 bits integers.
- // ATIS-0700041 Section 5.1.6
- int messageIdentifier = bitReader.read(16);
- int serialNumber = bitReader.read(16);
- cbIdentifiers.add(new CellBroadcastIdentity(messageIdentifier, serialNumber));
- }
- return new GeoFencingTriggerMessage(type, cbIdentifiers);
- } catch (Exception ex) {
- Rlog.e(TAG, "create geo-fencing trigger failed, ex = " + ex.toString());
- return null;
- }
- }
-
- /**
- * Parse the broadcast area and maximum wait time from the Warning Area Coordinates TLV.
- *
- * @param pdu Warning Area Coordinates TLV.
- * @param wacOffset the offset of Warning Area Coordinates TLV.
- * @return a pair with the first element is maximum wait time and the second is the broadcast
- * area. The default value of the maximum wait time is 255 which means use the device default
- * value.
- */
- private static Pair<Integer, List<Geometry>> parseWarningAreaCoordinates(
- byte[] pdu, int wacOffset) {
- // little-endian
- int wacDataLength = ((pdu[wacOffset + 1] & 0xff) << 8) | (pdu[wacOffset] & 0xff);
- int offset = wacOffset + 2;
-
- if (offset + wacDataLength > pdu.length) {
- throw new IllegalArgumentException("Invalid wac data, expected the length of pdu at"
- + "least " + offset + wacDataLength + ", actual is " + pdu.length);
- }
-
- BitStreamReader bitReader = new BitStreamReader(pdu, offset);
-
- int maximumWaitTimeSec = SmsCbMessage.MAXIMUM_WAIT_TIME_NOT_SET;
-
- List<Geometry> geo = new ArrayList<>();
- int remainedBytes = wacDataLength;
- while (remainedBytes > 0) {
- int type = bitReader.read(4);
- int length = bitReader.read(10);
- remainedBytes -= length;
- // Skip the 2 remained bits
- bitReader.skip();
-
- switch (type) {
- case CbGeoUtils.GEO_FENCING_MAXIMUM_WAIT_TIME:
- maximumWaitTimeSec = bitReader.read(8);
- break;
- case CbGeoUtils.GEOMETRY_TYPE_POLYGON:
- List<LatLng> latLngs = new ArrayList<>();
- // Each coordinate is represented by 44 bits integer.
- // ATIS-0700041 5.2.4 Coordinate coding
- int n = (length - 2) * 8 / 44;
- for (int i = 0; i < n; i++) {
- latLngs.add(getLatLng(bitReader));
- }
- // Skip the padding bits
- bitReader.skip();
- geo.add(new Polygon(latLngs));
- break;
- case CbGeoUtils.GEOMETRY_TYPE_CIRCLE:
- LatLng center = getLatLng(bitReader);
- // radius = (wacRadius / 2^6). The unit of wacRadius is km, we use meter as the
- // distance unit during geo-fencing.
- // ATIS-0700041 5.2.5 radius coding
- double radius = (bitReader.read(20) * 1.0 / (1 << 6)) * 1000.0;
- geo.add(new Circle(center, radius));
- break;
- default:
- throw new IllegalArgumentException("Unsupported geoType = " + type);
- }
- }
- return new Pair(maximumWaitTimeSec, geo);
- }
-
- /**
- * The coordinate is (latitude, longitude), represented by a 44 bits integer.
- * The coding is defined in ATIS-0700041 5.2.4
- * @param bitReader
- * @return coordinate (latitude, longitude)
- */
- private static LatLng getLatLng(BitStreamReader bitReader) {
- // wacLatitude = floor(((latitude + 90) / 180) * 2^22)
- // wacLongitude = floor(((longitude + 180) / 360) * 2^22)
- int wacLat = bitReader.read(22);
- int wacLng = bitReader.read(22);
-
- // latitude = wacLatitude * 180 / 2^22 - 90
- // longitude = wacLongitude * 360 / 2^22 -180
- return new LatLng((wacLat * 180.0 / (1 << 22)) - 90, (wacLng * 360.0 / (1 << 22) - 180));
- }
-
- /**
- * Parse and unpack the UMTS body text according to the encoding in the data coding scheme.
- *
- * @param header the message header to use
- * @param pdu the PDU to decode
- * @return a pair of string containing the language and body of the message in order
- */
- private static Pair<String, String> parseUmtsBody(SmsCbHeader header, byte[] pdu) {
- // Payload may contain multiple pages
- int nrPages = pdu[SmsCbHeader.PDU_HEADER_LENGTH];
- String language = header.getDataCodingSchemeStructedData().language;
-
- if (pdu.length < SmsCbHeader.PDU_HEADER_LENGTH + 1 + (PDU_BODY_PAGE_LENGTH + 1)
- * nrPages) {
- throw new IllegalArgumentException("Pdu length " + pdu.length + " does not match "
- + nrPages + " pages");
- }
-
- StringBuilder sb = new StringBuilder();
-
- for (int i = 0; i < nrPages; i++) {
- // Each page is 82 bytes followed by a length octet indicating
- // the number of useful octets within those 82
- int offset = SmsCbHeader.PDU_HEADER_LENGTH + 1 + (PDU_BODY_PAGE_LENGTH + 1) * i;
- int length = pdu[offset + PDU_BODY_PAGE_LENGTH];
-
- if (length > PDU_BODY_PAGE_LENGTH) {
- throw new IllegalArgumentException("Page length " + length
- + " exceeds maximum value " + PDU_BODY_PAGE_LENGTH);
- }
-
- Pair<String, String> p = unpackBody(pdu, offset, length,
- header.getDataCodingSchemeStructedData());
- language = p.first;
- sb.append(p.second);
- }
- return new Pair(language, sb.toString());
-
- }
-
- /**
- * Parse and unpack the GSM body text according to the encoding in the data coding scheme.
- * @param header the message header to use
- * @param pdu the PDU to decode
- * @return a pair of string containing the language and body of the message in order
- */
- private static Pair<String, String> parseGsmBody(SmsCbHeader header, byte[] pdu) {
- // Payload is one single page
- int offset = SmsCbHeader.PDU_HEADER_LENGTH;
- int length = pdu.length - offset;
- return unpackBody(pdu, offset, length, header.getDataCodingSchemeStructedData());
- }
-
- /**
- * Unpack body text from the pdu using the given encoding, position and length within the pdu.
- *
- * @param pdu The pdu
- * @param offset Position of the first byte to unpack
- * @param length Number of bytes to unpack
- * @param dcs data coding scheme
- * @return a Pair of Strings containing the language and body of the message
- */
- private static Pair<String, String> unpackBody(byte[] pdu, int offset, int length,
- DataCodingScheme dcs) {
- String body = null;
-
- String language = dcs.language;
- switch (dcs.encoding) {
- case SmsConstants.ENCODING_7BIT:
- body = GsmAlphabet.gsm7BitPackedToString(pdu, offset, length * 8 / 7);
-
- if (dcs.hasLanguageIndicator && body != null && body.length() > 2) {
- // Language is two GSM characters followed by a CR.
- // The actual body text is offset by 3 characters.
- language = body.substring(0, 2);
- body = body.substring(3);
- }
- break;
-
- case SmsConstants.ENCODING_16BIT:
- if (dcs.hasLanguageIndicator && pdu.length >= offset + 2) {
- // Language is two GSM characters.
- // The actual body text is offset by 2 bytes.
- language = GsmAlphabet.gsm7BitPackedToString(pdu, offset, 2);
- offset += 2;
- length -= 2;
- }
-
- try {
- body = new String(pdu, offset, (length & 0xfffe), "utf-16");
- } catch (UnsupportedEncodingException e) {
- // Apparently it wasn't valid UTF-16.
- throw new IllegalArgumentException("Error decoding UTF-16 message", e);
- }
- break;
-
- default:
- break;
- }
-
- if (body != null) {
- // Remove trailing carriage return
- for (int i = body.length() - 1; i >= 0; i--) {
- if (body.charAt(i) != CARRIAGE_RETURN) {
- body = body.substring(0, i + 1);
- break;
- }
- }
- } else {
- body = "";
- }
-
- return new Pair<String, String>(language, body);
- }
-
- /** A class use to facilitate the processing of bits stream data. */
- private static final class BitStreamReader {
- /** The bits stream represent by a bytes array. */
- private final byte[] mData;
-
- /** The offset of the current byte. */
- private int mCurrentOffset;
-
- /**
- * The remained bits of the current byte which have not been read. The most significant
- * will be read first, so the remained bits are always the least significant bits.
- */
- private int mRemainedBit;
-
- /**
- * Constructor
- * @param data bit stream data represent by byte array.
- * @param offset the offset of the first byte.
- */
- BitStreamReader(byte[] data, int offset) {
- mData = data;
- mCurrentOffset = offset;
- mRemainedBit = 8;
- }
-
- /**
- * Read the first {@code count} bits.
- * @param count the number of bits need to read
- * @return {@code bits} represent by an 32-bits integer, therefore {@code count} must be no
- * greater than 32.
- */
- public int read(int count) throws IndexOutOfBoundsException {
- int val = 0;
- while (count > 0) {
- if (count >= mRemainedBit) {
- val <<= mRemainedBit;
- val |= mData[mCurrentOffset] & ((1 << mRemainedBit) - 1);
- count -= mRemainedBit;
- mRemainedBit = 8;
- ++mCurrentOffset;
- } else {
- val <<= count;
- val |= (mData[mCurrentOffset] & ((1 << mRemainedBit) - 1))
- >> (mRemainedBit - count);
- mRemainedBit -= count;
- count = 0;
- }
- }
- return val;
- }
-
- /**
- * Skip the current bytes if the remained bits is less than 8. This is useful when
- * processing the padding or reserved bits.
- */
- public void skip() {
- if (mRemainedBit < 8) {
- mRemainedBit = 8;
- ++mCurrentOffset;
- }
- }
- }
-
- /**
- * Part of a GSM SMS cell broadcast message which may trigger geo-fencing logic.
- * @hide
- */
- public static final class GeoFencingTriggerMessage {
- /**
- * Indicate the list of active alerts share their warning area coordinates which means the
- * broadcast area is the union of the broadcast areas of the active alerts in this list.
- */
- public static final int TYPE_ACTIVE_ALERT_SHARE_WAC = 2;
-
- public final int type;
- public final List<CellBroadcastIdentity> cbIdentifiers;
-
- GeoFencingTriggerMessage(int type, @NonNull List<CellBroadcastIdentity> cbIdentifiers) {
- this.type = type;
- this.cbIdentifiers = cbIdentifiers;
- }
-
- /**
- * Whether the trigger message indicates that the broadcast areas are shared between all
- * active alerts.
- * @return true if broadcast areas are to be shared
- */
- boolean shouldShareBroadcastArea() {
- return type == TYPE_ACTIVE_ALERT_SHARE_WAC;
- }
-
- static final class CellBroadcastIdentity {
- public final int messageIdentifier;
- public final int serialNumber;
- CellBroadcastIdentity(int messageIdentifier, int serialNumber) {
- this.messageIdentifier = messageIdentifier;
- this.serialNumber = serialNumber;
- }
- }
-
- @Override
- public String toString() {
- String identifiers = cbIdentifiers.stream()
- .map(cbIdentifier ->String.format("(msgId = %d, serial = %d)",
- cbIdentifier.messageIdentifier, cbIdentifier.serialNumber))
- .collect(Collectors.joining(","));
- return "triggerType=" + type + " identifiers=" + identifiers;
- }
- }
-}
diff --git a/telephony/java/com/android/internal/telephony/util/HandlerExecutor.java b/telephony/java/com/android/internal/telephony/util/HandlerExecutor.java
new file mode 100644
index 000000000000..8a2545772b5b
--- /dev/null
+++ b/telephony/java/com/android/internal/telephony/util/HandlerExecutor.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2019 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 com.android.internal.telephony.util;
+
+import android.annotation.NonNull;
+import android.os.Handler;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.RejectedExecutionException;
+
+/**
+ * An adapter {@link Executor} that posts all executed tasks onto the given
+ * {@link Handler}.
+ *
+ * @hide
+ */
+public class HandlerExecutor implements Executor {
+ private final Handler mHandler;
+
+ public HandlerExecutor(@NonNull Handler handler) {
+ if (handler == null) {
+ throw new NullPointerException();
+ }
+ mHandler = handler;
+ }
+
+ @Override
+ public void execute(Runnable command) {
+ if (!mHandler.post(command)) {
+ throw new RejectedExecutionException(mHandler + " is shutting down");
+ }
+ }
+}
diff --git a/telephony/java/com/android/internal/telephony/util/RemoteCallbackListExt.java b/telephony/java/com/android/internal/telephony/util/RemoteCallbackListExt.java
new file mode 100644
index 000000000000..d66bda911729
--- /dev/null
+++ b/telephony/java/com/android/internal/telephony/util/RemoteCallbackListExt.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2019 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 com.android.internal.telephony.util;
+
+import android.os.IInterface;
+import android.os.RemoteCallbackList;
+
+import java.util.function.Consumer;
+
+/**
+ * Extension of RemoteCallbackList
+ * @param <E> defines the type of registered callbacks
+ */
+public class RemoteCallbackListExt<E extends IInterface> extends RemoteCallbackList<E> {
+ /**
+ * Performs {@code action} on each callback, calling
+ * {@link RemoteCallbackListExt#beginBroadcast()}
+ * /{@link RemoteCallbackListExt#finishBroadcast()} before/after looping
+ * @param action to be performed on each callback
+ *
+ */
+ public void broadcastAction(Consumer<E> action) {
+ int itemCount = beginBroadcast();
+ try {
+ for (int i = 0; i < itemCount; i++) {
+ action.accept(getBroadcastItem(i));
+ }
+ } finally {
+ finishBroadcast();
+ }
+ }
+}
diff --git a/test-mock/Android.bp b/test-mock/Android.bp
index aa4174ad40f4..248c117d2e03 100644
--- a/test-mock/Android.bp
+++ b/test-mock/Android.bp
@@ -28,8 +28,9 @@ java_sdk_library {
":framework_native_aidl",
],
libs: [
- "framework-all",
+ "framework",
"app-compat-annotations",
+ "unsupportedappusage",
],
api_packages: [
diff --git a/test-mock/src/android/test/mock/MockContext.java b/test-mock/src/android/test/mock/MockContext.java
index 0208c3a0a0de..9d913b9861e5 100644
--- a/test-mock/src/android/test/mock/MockContext.java
+++ b/test-mock/src/android/test/mock/MockContext.java
@@ -16,6 +16,7 @@
package android.test.mock;
+import android.annotation.NonNull;
import android.annotation.SystemApi;
import android.app.IApplicationThread;
import android.app.IServiceConnection;
@@ -211,6 +212,15 @@ public class MockContext extends Context {
throw new UnsupportedOperationException();
}
+ /**
+ * {@inheritDoc Context#getCrateDir()}
+ * @hide
+ */
+ @Override
+ public File getCrateDir(@NonNull String crateId) {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public File getNoBackupFilesDir() {
throw new UnsupportedOperationException();
diff --git a/tests/ActivityManagerPerfTests/stub-app/Android.bp b/tests/ActivityManagerPerfTests/stub-app/Android.bp
new file mode 100644
index 000000000000..a3c1f5b2f17d
--- /dev/null
+++ b/tests/ActivityManagerPerfTests/stub-app/Android.bp
@@ -0,0 +1,68 @@
+// Copyright (C) 2019 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.
+
+android_test_helper_app {
+ name: "ActivityManagerPerfTestsStubApp1",
+ static_libs: ["ActivityManagerPerfTestsUtils"],
+ srcs: [
+ "src/**/*.java",
+ ],
+ resource_dirs: [
+ "app1/res",
+ "res",
+ ],
+ platform_apis: true,
+ certificate: "platform",
+ aaptflags: [
+ "--rename-manifest-package com.android.stubs.am1",
+ "--auto-add-overlay",
+ ],
+}
+
+android_test_helper_app {
+ name: "ActivityManagerPerfTestsStubApp2",
+ static_libs: ["ActivityManagerPerfTestsUtils"],
+ srcs: [
+ "src/**/*.java",
+ ],
+ resource_dirs: [
+ "app2/res",
+ "res",
+ ],
+ platform_apis: true,
+ certificate: "platform",
+ aaptflags: [
+ "--rename-manifest-package com.android.stubs.am2",
+ "--auto-add-overlay",
+ ],
+}
+
+android_test_helper_app {
+ name: "ActivityManagerPerfTestsStubApp3",
+ static_libs: ["ActivityManagerPerfTestsUtils"],
+ srcs: [
+ "src/**/*.java",
+ ],
+ resource_dirs: [
+ "app3/res",
+ "res",
+ ],
+ platform_apis: true,
+ certificate: "platform",
+ aaptflags: [
+ "--rename-manifest-package com.android.stubs.am3",
+ "--auto-add-overlay",
+ ],
+}
+
diff --git a/tests/ActivityManagerPerfTests/stub-app/AndroidManifest.xml b/tests/ActivityManagerPerfTests/stub-app/AndroidManifest.xml
new file mode 100644
index 000000000000..a57f64c320c8
--- /dev/null
+++ b/tests/ActivityManagerPerfTests/stub-app/AndroidManifest.xml
@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2019 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.android.stubs.am">
+
+ <uses-permission android:name="android.permission.START_ACTIVITIES_FROM_BACKGROUND"/>
+ <application android:label="Android TestCase" >
+ <provider
+ android:authorities="@string/authority"
+ android:name=".TestContentProvider"
+ android:exported="true" />
+ <receiver
+ android:name=".TestBroadcastReceiver"
+ android:exported="true">
+ <intent-filter>
+ <action android:name="com.android.stubs.am.ACTION_BROADCAST_TEST" />
+ <category android:name="android.intent.category.DEFAULT" />
+ </intent-filter>
+ </receiver>
+ <service
+ android:name=".InitService"
+ android:exported="true" />
+ <service
+ android:name=".TestService"
+ android:exported="true" />
+ <activity
+ android:name=".TestActivity"
+ android:excludeFromRecents="true"
+ android:turnScreenOn="true"
+ android:launchMode="singleTask">
+ <intent-filter>
+ <action android:name="com.android.stubs.am.ACTION_START_TEST_ACTIVITY" />
+ <category android:name="android.intent.category.DEFAULT" />
+ </intent-filter>
+ </activity>
+ </application>
+
+</manifest>
+
diff --git a/tests/ActivityManagerPerfTests/stub-app/app1/res/values/config.xml b/tests/ActivityManagerPerfTests/stub-app/app1/res/values/config.xml
new file mode 100644
index 000000000000..667472db5f83
--- /dev/null
+++ b/tests/ActivityManagerPerfTests/stub-app/app1/res/values/config.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2019 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.
+-->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+ <string name="authority" translatable="false">com.android.stubs.am1.testapp</string>
+</resources>
diff --git a/tests/ActivityManagerPerfTests/stub-app/app2/res/values/config.xml b/tests/ActivityManagerPerfTests/stub-app/app2/res/values/config.xml
new file mode 100644
index 000000000000..085273574d95
--- /dev/null
+++ b/tests/ActivityManagerPerfTests/stub-app/app2/res/values/config.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2019 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.
+-->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+ <string name="authority" translatable="false">com.android.stubs.am2.testapp</string>
+</resources>
diff --git a/tests/ActivityManagerPerfTests/stub-app/app3/res/values/config.xml b/tests/ActivityManagerPerfTests/stub-app/app3/res/values/config.xml
new file mode 100644
index 000000000000..6895d7258dad
--- /dev/null
+++ b/tests/ActivityManagerPerfTests/stub-app/app3/res/values/config.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2019 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.
+-->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+ <string name="authority" translatable="false">com.android.stubs.am3.testapp</string>
+</resources>
diff --git a/tests/ActivityManagerPerfTests/stub-app/res/layout/activity_content.xml b/tests/ActivityManagerPerfTests/stub-app/res/layout/activity_content.xml
new file mode 100644
index 000000000000..f79f006087d7
--- /dev/null
+++ b/tests/ActivityManagerPerfTests/stub-app/res/layout/activity_content.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/content"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"/>
diff --git a/tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/InitService.java b/tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/InitService.java
new file mode 100644
index 000000000000..18fdc442bfbf
--- /dev/null
+++ b/tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/InitService.java
@@ -0,0 +1,301 @@
+/*
+ * Copyright (C) 2019 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 com.android.stubs.am;
+
+import static com.android.frameworks.perftests.am.util.Constants.COMMAND_ACQUIRE_CONTENT_PROVIDER;
+import static com.android.frameworks.perftests.am.util.Constants.COMMAND_BIND_SERVICE;
+import static com.android.frameworks.perftests.am.util.Constants.COMMAND_RELEASE_CONTENT_PROVIDER;
+import static com.android.frameworks.perftests.am.util.Constants.COMMAND_SEND_BROADCAST;
+import static com.android.frameworks.perftests.am.util.Constants.COMMAND_START_ACTIVITY;
+import static com.android.frameworks.perftests.am.util.Constants.COMMAND_STOP_ACTIVITY;
+import static com.android.frameworks.perftests.am.util.Constants.COMMAND_UNBIND_SERVICE;
+
+import android.app.Service;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.IContentProvider;
+import android.content.Intent;
+import android.content.ServiceConnection;
+import android.net.Uri;
+import android.os.Binder;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.IBinder;
+import android.os.Looper;
+import android.os.Message;
+import android.os.Messenger;
+import android.os.RemoteException;
+import android.util.ArrayMap;
+import android.util.Log;
+
+import com.android.frameworks.perftests.am.util.Constants;
+import com.android.frameworks.perftests.am.util.ICommandReceiver;
+
+public class InitService extends Service {
+ private static final String TAG = "InitService";
+ public static final boolean VERBOSE = false;
+
+ private static class Stub extends ICommandReceiver.Stub {
+ private final Context mContext;
+ private final Messenger mCallback;
+ private final Handler mHandler;
+ private final Messenger mMessenger;
+ final ArrayMap<String, MyServiceConnection> mServices =
+ new ArrayMap<String, MyServiceConnection>();
+ final ArrayMap<Uri, IContentProvider> mProviders =
+ new ArrayMap<Uri, IContentProvider>();
+
+ Stub(Context context, Messenger callback) {
+ mContext = context;
+ mCallback = callback;
+ HandlerThread thread = new HandlerThread("result handler");
+ thread.start();
+ mHandler = new H(thread.getLooper());
+ mMessenger = new Messenger(mHandler);
+ }
+
+ private class H extends Handler {
+ H(Looper looper) {
+ super(looper);
+ }
+
+ @Override
+ public void handleMessage(Message msg) {
+ if (msg.what == Constants.MSG_DEFAULT) {
+ if (VERBOSE) {
+ Log.i(TAG, "H: received seq=" + msg.arg1 + ", result=" + msg.arg2);
+ }
+ sendResult(mCallback, Constants.REPLY_COMMAND_RESULT, msg.arg1, msg.arg2, null);
+ } else if (msg.what == Constants.MSG_UNBIND_DONE) {
+ if (VERBOSE) {
+ Log.i(TAG, "H: received unbind=" + msg.obj);
+ }
+ synchronized (InitService.sStub) {
+ Bundle b = (Bundle) msg.obj;
+ String pkg = b.getString(Constants.EXTRA_SOURCE_PACKAGE, "");
+ MyServiceConnection c = mServices.remove(pkg);
+ if (c != null) {
+ sendResult(mCallback, Constants.REPLY_COMMAND_RESULT, c.mSeq,
+ Constants.RESULT_NO_ERROR, null);
+ }
+ }
+ }
+ }
+ }
+
+ @Override
+ public void sendCommand(int command, int seq, String sourcePackage, String targetPackage,
+ int flags, Bundle bundle) {
+ if (VERBOSE) {
+ Log.i(TAG, "Received command=" + command + ", seq=" + seq + ", from="
+ + sourcePackage + ", to=" + targetPackage + ", flags=" + flags);
+ }
+ switch (command) {
+ case COMMAND_BIND_SERVICE:
+ handleBindService(seq, targetPackage, flags, bundle);
+ break;
+ case COMMAND_UNBIND_SERVICE:
+ handleUnbindService(seq, targetPackage);
+ break;
+ case COMMAND_ACQUIRE_CONTENT_PROVIDER:
+ acquireProvider(seq, bundle.getParcelable(Constants.EXTRA_URI));
+ break;
+ case COMMAND_RELEASE_CONTENT_PROVIDER:
+ releaseProvider(seq, bundle.getParcelable(Constants.EXTRA_URI));
+ break;
+ case COMMAND_SEND_BROADCAST:
+ sendBroadcast(seq, targetPackage);
+ break;
+ case COMMAND_START_ACTIVITY:
+ startActivity(seq, targetPackage);
+ break;
+ case COMMAND_STOP_ACTIVITY:
+ stopActivity(seq, targetPackage);
+ break;
+ }
+ }
+
+ private void handleBindService(int seq, String targetPackage, int flags, Bundle bundle) {
+ Intent intent = new Intent();
+ intent.setClassName(targetPackage, "com.android.stubs.am.TestService");
+ intent.putExtra(Constants.EXTRA_RECEIVER_CALLBACK, mMessenger);
+ if (bundle != null) {
+ intent.putExtras(bundle);
+ }
+ synchronized (this) {
+ if (!mServices.containsKey(targetPackage)) {
+ MyServiceConnection c = new MyServiceConnection(mCallback);
+ c.mSeq = seq;
+ if (!mContext.bindService(intent, c, flags)) {
+ Log.e(TAG, "Unable to bind to service in " + targetPackage);
+ sendResult(mCallback, Constants.REPLY_COMMAND_RESULT, seq,
+ Constants.RESULT_ERROR, null);
+ } else {
+ if (VERBOSE) {
+ Log.i(TAG, "Bind to service " + intent);
+ }
+ mServices.put(targetPackage, c);
+ }
+ } else {
+ sendResult(mCallback, Constants.REPLY_COMMAND_RESULT, seq,
+ Constants.RESULT_NO_ERROR, null);
+ }
+ }
+ }
+
+ private void handleUnbindService(int seq, String target) {
+ MyServiceConnection c = null;
+ synchronized (this) {
+ c = mServices.get(target);
+ }
+ if (c != null) {
+ c.mSeq = seq;
+ mContext.unbindService(c);
+ }
+ }
+
+ private void acquireProvider(int seq, Uri uri) {
+ ContentResolver resolver = mContext.getContentResolver();
+ IContentProvider provider = resolver.acquireProvider(uri);
+ if (provider != null) {
+ synchronized (mProviders) {
+ mProviders.put(uri, provider);
+ }
+ sendResult(mCallback, Constants.REPLY_COMMAND_RESULT, seq,
+ Constants.RESULT_NO_ERROR, null);
+ } else {
+ sendResult(mCallback, Constants.REPLY_COMMAND_RESULT, seq,
+ Constants.RESULT_ERROR, null);
+ }
+ }
+
+ private void releaseProvider(int seq, Uri uri) {
+ ContentResolver resolver = mContext.getContentResolver();
+ IContentProvider provider;
+ synchronized (mProviders) {
+ provider = mProviders.get(uri);
+ }
+ if (provider != null) {
+ resolver.releaseProvider(provider);
+ synchronized (mProviders) {
+ mProviders.remove(uri);
+ }
+ }
+ sendResult(mCallback, Constants.REPLY_COMMAND_RESULT, seq,
+ Constants.RESULT_NO_ERROR, null);
+ }
+
+ private void sendBroadcast(final int seq, String targetPackage) {
+ Intent intent = new Intent(Constants.STUB_ACTION_BROADCAST);
+ intent.setPackage(targetPackage);
+ mContext.sendOrderedBroadcast(intent, null, new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ sendResult(mCallback, Constants.REPLY_COMMAND_RESULT, seq,
+ Constants.RESULT_NO_ERROR, null);
+ }
+ }, null, 0, null, null);
+ }
+
+ private void startActivity(int seq, String targetPackage) {
+ Intent intent = new Intent(Constants.STUB_ACTION_ACTIVITY);
+ intent.setClassName(targetPackage, "com.android.stubs.am.TestActivity");
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
+ intent.putExtra(Constants.EXTRA_ARG1, seq);
+ intent.putExtra(Constants.EXTRA_RECEIVER_CALLBACK, mMessenger);
+ mContext.startActivity(intent);
+ }
+
+ private void stopActivity(int seq, String targetPackage) {
+ Intent intent = new Intent(Constants.STUB_ACTION_ACTIVITY);
+ intent.setClassName(targetPackage, "com.android.stubs.am.TestActivity");
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
+ intent.putExtra(Constants.EXTRA_REQ_FINISH_ACTIVITY, true);
+ intent.putExtra(Constants.EXTRA_ARG1, seq);
+ intent.putExtra(Constants.EXTRA_RECEIVER_CALLBACK, mMessenger);
+ mContext.startActivity(intent);
+ }
+ };
+
+ private static void sendResult(Messenger callback, int what, int seq, int result, Object obj) {
+ Message msg = Message.obtain();
+ msg.what = what;
+ msg.arg1 = seq;
+ msg.arg2 = result;
+ msg.obj = obj;
+ try {
+ if (VERBOSE) {
+ Log.i(TAG, "Sending result seq=" + seq + ", result=" + result);
+ }
+ callback.send(msg);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Error in sending result back", e);
+ }
+ msg.recycle();
+ }
+
+ private static class MyServiceConnection implements ServiceConnection {
+ private Messenger mCallback;
+ int mSeq;
+
+ MyServiceConnection(Messenger callback) {
+ mCallback = callback;
+ }
+
+ @Override
+ public void onServiceConnected(ComponentName name, IBinder service) {
+ sendResult(mCallback, Constants.REPLY_COMMAND_RESULT, mSeq,
+ Constants.RESULT_NO_ERROR, null);
+ }
+
+ @Override
+ public void onServiceDisconnected(ComponentName name) {
+ synchronized (sStub) {
+ MyServiceConnection c = sStub.mServices.remove(name.getPackageName());
+ if (c != null) {
+ sendResult(mCallback, Constants.REPLY_COMMAND_RESULT, c.mSeq,
+ Constants.RESULT_NO_ERROR, null);
+ }
+ }
+ }
+ }
+
+ private static Stub sStub = null;
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ return new Binder();
+ }
+
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ Messenger callback = intent.getParcelableExtra(Constants.EXTRA_RECEIVER_CALLBACK);
+ if (sStub == null) {
+ sStub = new Stub(getApplicationContext(), callback);
+ }
+
+ Bundle extras = new Bundle();
+ extras.putString(Constants.EXTRA_SOURCE_PACKAGE, getPackageName());
+ extras.putBinder(Constants.EXTRA_RECEIVER_CALLBACK, sStub);
+ sendResult(callback, Constants.REPLY_PACKAGE_START_RESULT,
+ intent.getIntExtra(Constants.EXTRA_SEQ, -1), 0, extras);
+ return START_NOT_STICKY;
+ }
+}
diff --git a/tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/TestActivity.java b/tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/TestActivity.java
new file mode 100644
index 000000000000..f7ea35672f0a
--- /dev/null
+++ b/tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/TestActivity.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2019 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 com.android.stubs.am;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.Message;
+import android.os.Messenger;
+import android.os.RemoteException;
+import android.util.Log;
+
+import com.android.frameworks.perftests.am.util.Constants;
+
+public class TestActivity extends Activity {
+ private static final String TAG = "TestActivity";
+ private static final boolean VERBOSE = InitService.VERBOSE;
+
+ private Messenger mResultTo;
+
+ @Override
+ public void onCreate(Bundle icicle) {
+ super.onCreate(icicle);
+ if (VERBOSE) {
+ Log.i(TAG, getPackageName() + " onCreate()");
+ }
+ setContentView(R.layout.activity_content);
+ mResultTo = getIntent().getParcelableExtra(Constants.EXTRA_RECEIVER_CALLBACK);
+ }
+
+ @Override
+ public void onNewIntent(Intent intent) {
+ super.onNewIntent(intent);
+ setIntent(intent);
+ mResultTo = intent.getParcelableExtra(Constants.EXTRA_RECEIVER_CALLBACK);
+ if (intent.getBooleanExtra(Constants.EXTRA_REQ_FINISH_ACTIVITY, false)) {
+ if (VERBOSE) {
+ Log.i(TAG, getPackageName() + " finishing activity");
+ }
+ finish();
+ }
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ if (VERBOSE) {
+ Log.i(TAG, getPackageName() + " onResume()");
+ }
+ sendResult(Constants.RESULT_NO_ERROR);
+ }
+
+ @Override
+ protected void onDestroy() {
+ super.onDestroy();
+ if (VERBOSE) {
+ Log.i(TAG, getPackageName() + " onDestroy()");
+ }
+ sendResult(Constants.RESULT_NO_ERROR);
+ }
+
+ private void sendResult(int result) {
+ Message msg = Message.obtain();
+ msg.arg1 = getIntent().getIntExtra(Constants.EXTRA_ARG1, -1);
+ msg.arg2 = result;
+ try {
+ mResultTo.send(msg);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Error in sending result back", e);
+ }
+ }
+}
diff --git a/tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/TestBroadcastReceiver.java b/tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/TestBroadcastReceiver.java
new file mode 100644
index 000000000000..36c7a0a3a405
--- /dev/null
+++ b/tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/TestBroadcastReceiver.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2019 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 com.android.stubs.am;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+public class TestBroadcastReceiver extends BroadcastReceiver {
+ private static final String TAG = "TestBroadcastReceiver";
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ Log.i(TAG, context.getPackageName() + " received broadcast: " + intent);
+ }
+}
diff --git a/tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/TestContentProvider.java b/tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/TestContentProvider.java
new file mode 100644
index 000000000000..4fdbf1f29036
--- /dev/null
+++ b/tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/TestContentProvider.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2019 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 com.android.stubs.am;
+
+import android.content.ContentProvider;
+import android.content.ContentValues;
+import android.database.Cursor;
+import android.net.Uri;
+import android.util.Log;
+
+public class TestContentProvider extends ContentProvider {
+ private static final String TAG = "TestContentProvider";
+ private static final boolean VERBOSE = InitService.VERBOSE;
+
+ @Override
+ public Uri insert(Uri uri, ContentValues values) {
+ return null;
+ }
+
+ @Override
+ public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
+ String sortOrder) {
+ return null;
+ }
+
+ @Override
+ public String getType(Uri uri) {
+ return null;
+ }
+
+ @Override
+ public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
+ return 0;
+ }
+
+ @Override
+ public boolean onCreate() {
+ if (VERBOSE) {
+ Log.i(TAG, getContext().getPackageName() + " onCreate()");
+ }
+ return false;
+ }
+
+ @Override
+ public int delete(Uri uri, String selection, String[] selectionArgs) {
+ return 0;
+ }
+}
diff --git a/tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/TestService.java b/tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/TestService.java
new file mode 100644
index 000000000000..ba220e003203
--- /dev/null
+++ b/tests/ActivityManagerPerfTests/stub-app/src/com/android/stubs/am/TestService.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2019 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 com.android.stubs.am;
+
+import android.app.Service;
+import android.content.Intent;
+import android.os.Binder;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.Message;
+import android.os.Messenger;
+import android.os.RemoteException;
+import android.util.Log;
+
+import com.android.frameworks.perftests.am.util.Constants;
+
+public class TestService extends Service {
+ private static final String TAG = "TestService";
+ private static final boolean VERBOSE = InitService.VERBOSE;
+
+ private Binder mStub = new Binder();
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ if (VERBOSE) {
+ Log.i(TAG, getPackageName() + " onBind()");
+ }
+ return mStub;
+ }
+
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ if (VERBOSE) {
+ Log.i(TAG, getPackageName() + " onStartCommand()");
+ }
+ return START_NOT_STICKY;
+ }
+
+ @Override
+ public boolean onUnbind(Intent intent) {
+ if (VERBOSE) {
+ Log.i(TAG, getPackageName() + " onUnbind()");
+ }
+ Messenger messenger = intent.getParcelableExtra(Constants.EXTRA_RECEIVER_CALLBACK);
+ Message msg = Message.obtain();
+ msg.what = Constants.MSG_UNBIND_DONE;
+ Bundle b = new Bundle();
+ b.putString(Constants.EXTRA_SOURCE_PACKAGE, getPackageName());
+ msg.obj = b;
+ try {
+ messenger.send(msg);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Error in sending result back", e);
+ }
+ return false;
+ }
+}
diff --git a/tests/ActivityManagerPerfTests/tests/AndroidTest.xml b/tests/ActivityManagerPerfTests/tests/AndroidTest.xml
index 76c40b2e3dc6..475bb82a9856 100644
--- a/tests/ActivityManagerPerfTests/tests/AndroidTest.xml
+++ b/tests/ActivityManagerPerfTests/tests/AndroidTest.xml
@@ -17,6 +17,9 @@
<target_preparer class="com.android.tradefed.targetprep.TestAppInstallSetup">
<option name="test-file-name" value="ActivityManagerPerfTests.apk"/>
<option name="test-file-name" value="ActivityManagerPerfTestsTestApp.apk"/>
+ <option name="test-file-name" value="ActivityManagerPerfTestsStubApp1.apk"/>
+ <option name="test-file-name" value="ActivityManagerPerfTestsStubApp2.apk"/>
+ <option name="test-file-name" value="ActivityManagerPerfTestsStubApp3.apk"/>
<option name="cleanup-apks" value="true"/>
</target_preparer>
@@ -26,4 +29,4 @@
<option name="package" value="com.android.frameworks.perftests.amtests"/>
<option name="runner" value="androidx.test.runner.AndroidJUnitRunner"/>
</test>
-</configuration> \ No newline at end of file
+</configuration>
diff --git a/tests/ActivityManagerPerfTests/tests/src/com/android/frameworks/perftests/am/tests/OomAdjPerfTest.java b/tests/ActivityManagerPerfTests/tests/src/com/android/frameworks/perftests/am/tests/OomAdjPerfTest.java
new file mode 100644
index 000000000000..1d3ff06e6bf1
--- /dev/null
+++ b/tests/ActivityManagerPerfTests/tests/src/com/android/frameworks/perftests/am/tests/OomAdjPerfTest.java
@@ -0,0 +1,241 @@
+/*
+ * Copyright (C) 2019 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 com.android.frameworks.perftests.am.tests;
+
+
+import android.content.ContentResolver;
+import android.content.Context;
+import android.net.Uri;
+import android.os.HandlerThread;
+import android.perftests.utils.ManualBenchmarkState;
+import android.perftests.utils.PerfManualStatusReporter;
+import android.perftests.utils.TraceMarkParser;
+import android.perftests.utils.TraceMarkParser.TraceMarkLine;
+import android.perftests.utils.TraceMarkParser.TraceMarkSlice;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.LargeTest;
+
+import com.android.frameworks.perftests.am.util.AtraceUtils;
+import com.android.frameworks.perftests.am.util.TargetPackageUtils;
+import com.android.frameworks.perftests.am.util.Utils;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * This benchmark test basically manipulates 3 test packages, let them bind to
+ * each other, send broadcast to each other, etc. All of these actions essentially
+ * triggers OomAdjuster to update the oom_adj scores and proc state of them.
+ * In the meanwhile it'll also monitor the atrace output, extract duration between
+ * the start and exit entries of the updateOomAdjLocked, include each of them
+ * into the stats; when there are enough samples in the stats, the test will
+ * stop and output the mean/stddev time spent on the updateOomAdjLocked.
+ */
+@RunWith(JUnit4.class)
+@LargeTest
+public final class OomAdjPerfTest {
+ private static final String TAG = "OomAdjPerfTest";
+ private static final boolean VERBOSE = true;
+
+ private static final String STUB_PACKAGE1_NAME = "com.android.stubs.am1";
+ private static final String STUB_PACKAGE2_NAME = "com.android.stubs.am2";
+ private static final String STUB_PACKAGE3_NAME = "com.android.stubs.am3";
+
+ private static final Uri STUB_PACKAGE1_URI = new Uri.Builder().scheme(
+ ContentResolver.SCHEME_CONTENT).authority("com.android.stubs.am1.testapp").build();
+ private static final Uri STUB_PACKAGE2_URI = new Uri.Builder().scheme(
+ ContentResolver.SCHEME_CONTENT).authority("com.android.stubs.am2.testapp").build();
+ private static final Uri STUB_PACKAGE3_URI = new Uri.Builder().scheme(
+ ContentResolver.SCHEME_CONTENT).authority("com.android.stubs.am3.testapp").build();
+ private static final long NANOS_PER_MICROSECOND = 1000L;
+
+ private static final String ATRACE_CATEGORY = "am";
+ private static final String ATRACE_OOMADJ_PREFIX = "updateOomAdj_";
+
+ @Rule
+ public PerfManualStatusReporter mPerfManualStatusReporter = new PerfManualStatusReporter();
+ private TraceMarkParser mTraceMarkParser = new TraceMarkParser(this::shouldFilterTraceLine);
+ private final ArrayList<Long> mDurations = new ArrayList<Long>();
+ private Context mContext;
+ private HandlerThread mHandlerThread;
+
+ @Before
+ public void setUp() {
+ mContext = InstrumentationRegistry.getTargetContext();
+ mHandlerThread = new HandlerThread("command receiver");
+ mHandlerThread.start();
+ TargetPackageUtils.initCommandResultReceiver(mHandlerThread.getLooper());
+
+ Utils.runShellCommand("cmd deviceidle whitelist +" + STUB_PACKAGE1_NAME);
+ Utils.runShellCommand("cmd deviceidle whitelist +" + STUB_PACKAGE2_NAME);
+ Utils.runShellCommand("cmd deviceidle whitelist +" + STUB_PACKAGE3_NAME);
+ TargetPackageUtils.startStubPackage(mContext, STUB_PACKAGE1_NAME);
+ TargetPackageUtils.startStubPackage(mContext, STUB_PACKAGE2_NAME);
+ TargetPackageUtils.startStubPackage(mContext, STUB_PACKAGE3_NAME);
+ }
+
+ @After
+ public void tearDown() {
+ TargetPackageUtils.stopStubPackage(mContext, STUB_PACKAGE1_NAME);
+ TargetPackageUtils.stopStubPackage(mContext, STUB_PACKAGE2_NAME);
+ TargetPackageUtils.stopStubPackage(mContext, STUB_PACKAGE3_NAME);
+ Utils.runShellCommand("cmd deviceidle whitelist -" + STUB_PACKAGE1_NAME);
+ Utils.runShellCommand("cmd deviceidle whitelist -" + STUB_PACKAGE2_NAME);
+ Utils.runShellCommand("cmd deviceidle whitelist -" + STUB_PACKAGE3_NAME);
+ mHandlerThread.quitSafely();
+ }
+
+ @Test
+ public void testOomAdj() {
+ final AtraceUtils atraceUtils = AtraceUtils.getInstance(
+ InstrumentationRegistry.getInstrumentation());
+ final ManualBenchmarkState state = mPerfManualStatusReporter.getBenchmarkState();
+ atraceUtils.startTrace(ATRACE_CATEGORY);
+ while (state.keepRunning(mDurations)) {
+ runCUJWithOomComputationOnce();
+
+ // Now kick off the trace dump
+ mDurations.clear();
+ atraceUtils.performDump(mTraceMarkParser, this::handleTraceMarkSlices);
+ }
+ atraceUtils.stopTrace();
+ }
+
+ private boolean shouldFilterTraceLine(final TraceMarkLine line) {
+ return line.name.startsWith(ATRACE_OOMADJ_PREFIX);
+ }
+
+ private void handleTraceMarkSlices(String key, List<TraceMarkSlice> slices) {
+ for (TraceMarkSlice slice: slices) {
+ mDurations.add(slice.getDurationInMicroseconds() * NANOS_PER_MICROSECOND);
+ }
+ }
+
+ /**
+ * This tries to mimic a user journey, involes multiple activity/service starts/stop,
+ * the time spent on oom adj computation would be different between all these samples,
+ * but with enough samples, we'll be able to know the overall distribution of the time
+ * spent on it.
+ */
+ private void runCUJWithOomComputationOnce() {
+ // Start activity from package1
+ TargetPackageUtils.startActivity(STUB_PACKAGE1_NAME, STUB_PACKAGE1_NAME);
+ // Start activity from package2
+ TargetPackageUtils.startActivity(STUB_PACKAGE2_NAME, STUB_PACKAGE2_NAME);
+ // Start activity from package3
+ TargetPackageUtils.startActivity(STUB_PACKAGE3_NAME, STUB_PACKAGE3_NAME);
+
+ // Stop activity in package1
+ TargetPackageUtils.stopActivity(STUB_PACKAGE1_NAME, STUB_PACKAGE1_NAME);
+ // Stop activity in package2
+ TargetPackageUtils.stopActivity(STUB_PACKAGE2_NAME, STUB_PACKAGE2_NAME);
+ // Stop activity in package3
+ TargetPackageUtils.stopActivity(STUB_PACKAGE3_NAME, STUB_PACKAGE3_NAME);
+
+ // Bind from package1 to package2
+ TargetPackageUtils.bindService(STUB_PACKAGE1_NAME, STUB_PACKAGE2_NAME,
+ Context.BIND_AUTO_CREATE);
+ // Acquire content provider from package 1 to package3
+ TargetPackageUtils.acquireProvider(STUB_PACKAGE1_NAME, STUB_PACKAGE3_NAME,
+ STUB_PACKAGE3_URI);
+ // Start activity from package1
+ TargetPackageUtils.startActivity(STUB_PACKAGE1_NAME, STUB_PACKAGE1_NAME);
+ // Bind from package2 to package3
+ TargetPackageUtils.bindService(STUB_PACKAGE2_NAME, STUB_PACKAGE3_NAME,
+ Context.BIND_AUTO_CREATE);
+ // Unbind from package 1 to package 2
+ TargetPackageUtils.unbindService(STUB_PACKAGE1_NAME, STUB_PACKAGE2_NAME, 0);
+ // Stop activity in package1
+ TargetPackageUtils.stopActivity(STUB_PACKAGE1_NAME, STUB_PACKAGE1_NAME);
+
+ // Send broadcast to all of them
+ TargetPackageUtils.sendBroadcast(STUB_PACKAGE1_NAME, STUB_PACKAGE1_NAME);
+ TargetPackageUtils.sendBroadcast(STUB_PACKAGE2_NAME, STUB_PACKAGE2_NAME);
+ TargetPackageUtils.sendBroadcast(STUB_PACKAGE3_NAME, STUB_PACKAGE3_NAME);
+
+ // Bind from package1 to package2 again
+ TargetPackageUtils.bindService(STUB_PACKAGE1_NAME, STUB_PACKAGE2_NAME,
+ Context.BIND_AUTO_CREATE);
+ // Create a cycle: package3 to package1
+ TargetPackageUtils.bindService(STUB_PACKAGE3_NAME, STUB_PACKAGE1_NAME,
+ Context.BIND_AUTO_CREATE);
+
+ // Send broadcast to all of them again
+ TargetPackageUtils.sendBroadcast(STUB_PACKAGE1_NAME, STUB_PACKAGE1_NAME);
+ TargetPackageUtils.sendBroadcast(STUB_PACKAGE2_NAME, STUB_PACKAGE2_NAME);
+ TargetPackageUtils.sendBroadcast(STUB_PACKAGE3_NAME, STUB_PACKAGE3_NAME);
+ // Start activity in package3
+ TargetPackageUtils.startActivity(STUB_PACKAGE3_NAME, STUB_PACKAGE3_NAME);
+
+ // Break the cycle: unbind from package3 to package1
+ TargetPackageUtils.unbindService(STUB_PACKAGE3_NAME, STUB_PACKAGE1_NAME, 0);
+
+ // Bind from package3 to package1 with waive priority
+ TargetPackageUtils.bindService(STUB_PACKAGE3_NAME, STUB_PACKAGE1_NAME,
+ Context.BIND_AUTO_CREATE | Context.BIND_WAIVE_PRIORITY);
+ // Release provider connection
+ TargetPackageUtils.releaseProvider(STUB_PACKAGE1_NAME, STUB_PACKAGE3_NAME,
+ STUB_PACKAGE3_URI);
+ // Unbind from package1 to package2
+ TargetPackageUtils.unbindService(STUB_PACKAGE1_NAME, STUB_PACKAGE2_NAME, 0);
+ // Unbind from package2 to packagae3
+ TargetPackageUtils.unbindService(STUB_PACKAGE2_NAME, STUB_PACKAGE3_NAME, 0);
+
+ // Bind from package3 to package2 with BIND_ABOVE_CLIENT
+ TargetPackageUtils.bindService(STUB_PACKAGE3_NAME, STUB_PACKAGE2_NAME,
+ Context.BIND_AUTO_CREATE | Context.BIND_ABOVE_CLIENT);
+ // Unbind from package3 to packagae2
+ TargetPackageUtils.unbindService(STUB_PACKAGE3_NAME, STUB_PACKAGE2_NAME, 0);
+
+ // Bind from package3 to package2 with BIND_ALLOW_OOM_MANAGEMENT
+ TargetPackageUtils.bindService(STUB_PACKAGE3_NAME, STUB_PACKAGE2_NAME,
+ Context.BIND_AUTO_CREATE | Context.BIND_ALLOW_OOM_MANAGEMENT);
+ // Unbind from package3 to packagae2
+ TargetPackageUtils.unbindService(STUB_PACKAGE3_NAME, STUB_PACKAGE2_NAME, 0);
+
+ // Bind from package3 to package2 with BIND_IMPORTANT
+ TargetPackageUtils.bindService(STUB_PACKAGE3_NAME, STUB_PACKAGE2_NAME,
+ Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT);
+ // Unbind from package3 to packagae2
+ TargetPackageUtils.unbindService(STUB_PACKAGE3_NAME, STUB_PACKAGE2_NAME, 0);
+
+ // Bind from package3 to package2 with BIND_NOT_FOREGROUND
+ TargetPackageUtils.bindService(STUB_PACKAGE3_NAME, STUB_PACKAGE2_NAME,
+ Context.BIND_AUTO_CREATE | Context.BIND_NOT_FOREGROUND);
+ // Unbind from package3 to packagae2
+ TargetPackageUtils.unbindService(STUB_PACKAGE3_NAME, STUB_PACKAGE2_NAME, 0);
+
+ // Bind from package3 to package2 with BIND_NOT_PERCEPTIBLE
+ TargetPackageUtils.bindService(STUB_PACKAGE3_NAME, STUB_PACKAGE2_NAME,
+ Context.BIND_AUTO_CREATE | Context.BIND_NOT_PERCEPTIBLE);
+ // Unbind from package3 to packagae2
+ TargetPackageUtils.unbindService(STUB_PACKAGE3_NAME, STUB_PACKAGE2_NAME, 0);
+
+ // Stop activity in package3
+ TargetPackageUtils.stopActivity(STUB_PACKAGE3_NAME, STUB_PACKAGE3_NAME);
+ // Unbind from package3 to package1
+ TargetPackageUtils.unbindService(STUB_PACKAGE3_NAME, STUB_PACKAGE1_NAME, 0);
+ }
+}
diff --git a/tests/ActivityManagerPerfTests/tests/src/com/android/frameworks/perftests/am/util/AtraceUtils.java b/tests/ActivityManagerPerfTests/tests/src/com/android/frameworks/perftests/am/util/AtraceUtils.java
new file mode 100644
index 000000000000..fcccfce8bd0e
--- /dev/null
+++ b/tests/ActivityManagerPerfTests/tests/src/com/android/frameworks/perftests/am/util/AtraceUtils.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2019 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 com.android.frameworks.perftests.am.util;
+
+import android.app.Instrumentation;
+import android.app.UiAutomation;
+import android.os.ParcelFileDescriptor;
+import android.perftests.utils.TraceMarkParser;
+import android.perftests.utils.TraceMarkParser.TraceMarkSlice;
+import android.util.Log;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.List;
+import java.util.function.BiConsumer;
+
+// Simplified version of AtraceLogger.
+public class AtraceUtils {
+ private static final String TAG = "AtraceUtils";
+ private static final boolean VERBOSE = true;
+
+ private static final String ATRACE_START = "atrace --async_start -b %d -c %s";
+ private static final String ATRACE_DUMP = "atrace --async_dump";
+ private static final String ATRACE_STOP = "atrace --async_stop";
+ private static final int DEFAULT_ATRACE_BUF_SIZE = 1024;
+
+ private UiAutomation mAutomation;
+ private static AtraceUtils sUtils = null;
+ private boolean mStarted = false;
+
+ private AtraceUtils(Instrumentation instrumentation) {
+ mAutomation = instrumentation.getUiAutomation();
+ }
+
+ public static AtraceUtils getInstance(Instrumentation instrumentation) {
+ if (sUtils == null) {
+ sUtils = new AtraceUtils(instrumentation);
+ }
+ return sUtils;
+ }
+
+ /**
+ * @param categories The list of the categories to trace, separated with space.
+ */
+ public void startTrace(String categories) {
+ synchronized (this) {
+ if (mStarted) {
+ throw new IllegalStateException("atrace already started");
+ }
+ Utils.runShellCommand(String.format(
+ ATRACE_START, DEFAULT_ATRACE_BUF_SIZE, categories));
+ mStarted = true;
+ }
+ }
+
+ public void stopTrace() {
+ synchronized (this) {
+ mStarted = false;
+ Utils.runShellCommand(ATRACE_STOP);
+ }
+ }
+
+ /**
+ * @param parser The function that can accept the buffer of atrace dump and parse it.
+ * @param handler The parse result handler
+ */
+ public void performDump(TraceMarkParser parser,
+ BiConsumer<String, List<TraceMarkSlice>> handler) {
+ parser.reset();
+ try {
+ if (VERBOSE) {
+ Log.i(TAG, "Collecting atrace dump...");
+ }
+ writeDataToBuf(mAutomation.executeShellCommand(ATRACE_DUMP), parser);
+ } catch (IOException e) {
+ Log.e(TAG, "Error in reading dump", e);
+ }
+ parser.forAllSlices(handler);
+ }
+
+ // The given file descriptor here will be closed by this function
+ private void writeDataToBuf(ParcelFileDescriptor pfDescriptor,
+ TraceMarkParser parser) throws IOException {
+ InputStream inputStream = new ParcelFileDescriptor.AutoCloseInputStream(pfDescriptor);
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
+ String line;
+ while ((line = reader.readLine()) != null) {
+ parser.visit(line);
+ }
+ }
+ }
+}
diff --git a/tests/ActivityManagerPerfTests/tests/src/com/android/frameworks/perftests/am/util/TargetPackageUtils.java b/tests/ActivityManagerPerfTests/tests/src/com/android/frameworks/perftests/am/util/TargetPackageUtils.java
index 046dd6bb7dce..d7f4d9de6735 100644
--- a/tests/ActivityManagerPerfTests/tests/src/com/android/frameworks/perftests/am/util/TargetPackageUtils.java
+++ b/tests/ActivityManagerPerfTests/tests/src/com/android/frameworks/perftests/am/util/TargetPackageUtils.java
@@ -22,12 +22,18 @@ import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
+import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
-import android.os.ResultReceiver;
+import android.os.Message;
+import android.os.Messenger;
+import android.os.RemoteException;
import android.os.SystemClock;
+import android.util.ArrayMap;
+import android.util.Log;
+import android.util.Pair;
import org.junit.Assert;
@@ -36,6 +42,7 @@ import java.util.concurrent.TimeUnit;
public class TargetPackageUtils {
private static final String TAG = TargetPackageUtils.class.getSimpleName();
+ public static final boolean VERBOSE = true;
public static final String PACKAGE_NAME = "com.android.frameworks.perftests.amteststestapp";
public static final String ACTIVITY_NAME = PACKAGE_NAME + ".TestActivity";
@@ -48,6 +55,12 @@ public class TargetPackageUtils {
// Cache for test app's uid, so we only have to query it once.
private static int sTestAppUid = -1;
+ private static final ArrayMap<String, ICommandReceiver> sStubPackages =
+ new ArrayMap<String, ICommandReceiver>();
+ private static final ArrayMap<Integer, CountDownLatch> sCommandLatches =
+ new ArrayMap<Integer, CountDownLatch>();
+ private static int sSeqNum = 0;
+
/**
* Kills the test package synchronously.
*/
@@ -145,5 +158,160 @@ public class TargetPackageUtils {
}
}
+ private static boolean isUidRunning(int uid) {
+ return !Utils.runShellCommand(String.format("cmd activity get-uid-state %d", uid))
+ .contains("(NONEXISTENT)");
+ }
+
+ public static void startStubPackage(Context context, String pkgName) {
+ stopStubPackage(context, pkgName);
+ try {
+ Pair<Integer, CountDownLatch> pair = obtainLatch();
+ Intent intent = new Intent();
+ intent.setComponent(new ComponentName(pkgName, Constants.STUB_INIT_SERVICE_NAME));
+ intent.putExtra(Constants.EXTRA_SOURCE_PACKAGE, context.getPackageName());
+ intent.putExtra(Constants.EXTRA_RECEIVER_CALLBACK, sMessenger);
+ intent.putExtra(Constants.EXTRA_SEQ, pair.first);
+ context.startService(intent);
+ Assert.assertTrue("Timeout when waiting for starting package " + pkgName,
+ pair.second.await(AWAIT_SERVICE_CONNECT_MS, TimeUnit.MILLISECONDS));
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static void stopStubPackage(Context context, String pkgName) {
+ final PackageManager pm = context.getPackageManager();
+ try {
+ final int uid = pm.getPackageUid(pkgName, 0);
+ if (isUidRunning(uid)) {
+ ActivityManager am = context.getSystemService(ActivityManager.class);
+ am.forceStopPackage(pkgName);
+ while (isUidRunning(uid)) {
+ SystemClock.sleep(WAIT_TIME_MS);
+ }
+ }
+ } catch (PackageManager.NameNotFoundException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static void initCommandResultReceiver(Looper looper) {
+ if (sMessenger == null) {
+ sMessenger = new Messenger(new H(looper));
+ }
+ }
+
+ private static void onPackageStartResult(int seq, Bundle bundle) {
+ ICommandReceiver receiver = ICommandReceiver.Stub.asInterface(
+ bundle.getBinder(Constants.EXTRA_RECEIVER_CALLBACK));
+ String sourcePkg = bundle.getString(Constants.EXTRA_SOURCE_PACKAGE);
+ sStubPackages.put(sourcePkg, receiver);
+ releaseLatch(seq);
+ }
+
+ private static void onCommandResult(int seq, int result) {
+ Assert.assertTrue("Error in command seq " + seq, result == Constants.RESULT_NO_ERROR);
+ releaseLatch(seq);
+ }
+
+ private static Messenger sMessenger = null;
+ private static class H extends Handler {
+ H(Looper looper) {
+ super(looper);
+ }
+
+ @Override
+ public void handleMessage(Message msg) {
+ switch (msg.what) {
+ case Constants.REPLY_PACKAGE_START_RESULT:
+ onPackageStartResult(msg.arg1 /* seq */, (Bundle) msg.obj);
+ break;
+ case Constants.REPLY_COMMAND_RESULT:
+ onCommandResult(msg.arg1, msg.arg2);
+ break;
+ }
+ }
+ }
+
+ private static Pair<Integer, CountDownLatch> obtainLatch() {
+ CountDownLatch latch = new CountDownLatch(1);
+ int seq;
+ synchronized (sCommandLatches) {
+ seq = sSeqNum++;
+ sCommandLatches.put(seq, latch);
+ }
+ return new Pair<>(seq, latch);
+ }
+
+ private static void releaseLatch(int seq) {
+ synchronized (sCommandLatches) {
+ CountDownLatch latch = sCommandLatches.get(seq);
+ if (latch != null) {
+ latch.countDown();
+ sCommandLatches.remove(seq);
+ }
+ }
+ }
+
+ public static void sendCommand(int command, String sourcePackage, String targetPackage,
+ int flags, Bundle bundle, boolean waitForResult) {
+ ICommandReceiver receiver = sStubPackages.get(sourcePackage);
+ Assert.assertTrue("Package hasn't been started: " + sourcePackage, receiver != null);
+ try {
+ Pair<Integer, CountDownLatch> pair = null;
+ if (waitForResult) {
+ pair = obtainLatch();
+ }
+ if (VERBOSE) {
+ Log.i(TAG, "Sending command=" + command + ", seq=" + pair.first + ", from="
+ + sourcePackage + ", to=" + targetPackage + ", flags=" + flags);
+ }
+ receiver.sendCommand(command, pair.first, sourcePackage, targetPackage, flags, bundle);
+ if (waitForResult) {
+ Assert.assertTrue("Timeout when waiting for command " + command + " from "
+ + sourcePackage + " to " + targetPackage,
+ pair.second.await(AWAIT_SERVICE_CONNECT_MS, TimeUnit.MILLISECONDS));
+ }
+ } catch (RemoteException | InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static void bindService(String sourcePackage, String targetPackage, int flags) {
+ sendCommand(Constants.COMMAND_BIND_SERVICE, sourcePackage, targetPackage, flags, null,
+ true);
+ }
+
+ public static void unbindService(String sourcePackage, String targetPackage, int flags) {
+ sendCommand(Constants.COMMAND_UNBIND_SERVICE, sourcePackage, targetPackage, flags, null,
+ true);
+ }
+
+ public static void acquireProvider(String sourcePackage, String targetPackage, Uri uri) {
+ Bundle bundle = new Bundle();
+ bundle.putParcelable(Constants.EXTRA_URI, uri);
+ sendCommand(Constants.COMMAND_ACQUIRE_CONTENT_PROVIDER, sourcePackage, targetPackage, 0,
+ bundle, true);
+ }
+
+ public static void releaseProvider(String sourcePackage, String targetPackage, Uri uri) {
+ Bundle bundle = new Bundle();
+ bundle.putParcelable(Constants.EXTRA_URI, uri);
+ sendCommand(Constants.COMMAND_RELEASE_CONTENT_PROVIDER, sourcePackage, targetPackage, 0,
+ bundle, true);
+ }
+
+ public static void sendBroadcast(String sourcePackage, String targetPackage) {
+ sendCommand(Constants.COMMAND_SEND_BROADCAST, sourcePackage, targetPackage, 0, null, true);
+ }
+
+ public static void startActivity(String sourcePackage, String targetPackage) {
+ sendCommand(Constants.COMMAND_START_ACTIVITY, sourcePackage, targetPackage, 0, null, true);
+ }
+
+ public static void stopActivity(String sourcePackage, String targetPackage) {
+ sendCommand(Constants.COMMAND_STOP_ACTIVITY, sourcePackage, targetPackage, 0, null, true);
+ }
}
diff --git a/tests/ActivityManagerPerfTests/utils/Android.bp b/tests/ActivityManagerPerfTests/utils/Android.bp
index 300b7ea998fa..766c3acf3c09 100644
--- a/tests/ActivityManagerPerfTests/utils/Android.bp
+++ b/tests/ActivityManagerPerfTests/utils/Android.bp
@@ -18,6 +18,7 @@ java_test {
srcs: [
"src/**/*.java",
"src/com/android/frameworks/perftests/am/util/ITimeReceiverCallback.aidl",
+ "src/com/android/frameworks/perftests/am/util/ICommandReceiver.aidl",
],
static_libs: [
"androidx.test.rules",
diff --git a/tests/ActivityManagerPerfTests/utils/src/com/android/frameworks/perftests/am/util/Constants.java b/tests/ActivityManagerPerfTests/utils/src/com/android/frameworks/perftests/am/util/Constants.java
index 9b076c507ff8..8e58665f5352 100644
--- a/tests/ActivityManagerPerfTests/utils/src/com/android/frameworks/perftests/am/util/Constants.java
+++ b/tests/ActivityManagerPerfTests/utils/src/com/android/frameworks/perftests/am/util/Constants.java
@@ -30,4 +30,33 @@ public class Constants {
public static final String EXTRA_RECEIVER_CALLBACK = "receiver_callback_binder";
public static final String EXTRA_LOOPER_IDLE_CALLBACK = "looper_idle_callback_binder";
+ public static final String EXTRA_SOURCE_PACKAGE = "source_package";
+ public static final String EXTRA_URI = "uri";
+ public static final String EXTRA_REQ_FINISH_ACTIVITY = "req_finish_activity";
+ public static final String EXTRA_SEQ = "seq";
+ public static final String EXTRA_ARG1 = "arg1";
+ public static final String EXTRA_ARG2 = "arg2";
+
+ public static final int RESULT_NO_ERROR = 0;
+ public static final int RESULT_ERROR = 1;
+ public static final String STUB_INIT_SERVICE_NAME = "com.android.stubs.am.InitService";
+
+ public static final int COMMAND_BIND_SERVICE = 1;
+ public static final int COMMAND_UNBIND_SERVICE = 2;
+ public static final int COMMAND_ACQUIRE_CONTENT_PROVIDER = 3;
+ public static final int COMMAND_RELEASE_CONTENT_PROVIDER = 4;
+ public static final int COMMAND_SEND_BROADCAST = 5;
+ public static final int COMMAND_START_ACTIVITY = 6;
+ public static final int COMMAND_STOP_ACTIVITY = 7;
+
+ public static final int MSG_DEFAULT = 0;
+ public static final int MSG_UNBIND_DONE = 1;
+
+ public static final int REPLY_PACKAGE_START_RESULT = 0;
+ public static final int REPLY_COMMAND_RESULT = 1;
+
+ public static final String STUB_ACTION_ACTIVITY =
+ "com.android.stubs.am.ACTION_START_TEST_ACTIVITY";
+ public static final String STUB_ACTION_BROADCAST =
+ "com.android.stubs.am.ACTION_BROADCAST_TEST";
}
diff --git a/core/java/android/service/sms/IFinancialSmsService.aidl b/tests/ActivityManagerPerfTests/utils/src/com/android/frameworks/perftests/am/util/ICommandReceiver.aidl
index caabe5851948..59ea7616a59e 100644
--- a/core/java/android/service/sms/IFinancialSmsService.aidl
+++ b/tests/ActivityManagerPerfTests/utils/src/com/android/frameworks/perftests/am/util/ICommandReceiver.aidl
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2018 The Android Open Source Project
+ * Copyright (C) 2019 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.
@@ -14,17 +14,11 @@
* limitations under the License.
*/
-package android.service.sms;
+package com.android.frameworks.perftests.am.util;
import android.os.Bundle;
-import android.os.RemoteCallback;
-/**
- * Service used by financial apps to read sms messages.
- *
- * @hide
- */
-oneway interface IFinancialSmsService
-{
- void getSmsMessages(in RemoteCallback callback, in Bundle params);
-} \ No newline at end of file
+interface ICommandReceiver {
+ oneway void sendCommand(int command, int seq, String sourcePackage, String targetPackage,
+ int flags, in Bundle bundle);
+}
diff --git a/tests/ApkVerityTest/Android.bp b/tests/ApkVerityTest/Android.bp
index adcbb4287dd0..c8d1ce1e7837 100644
--- a/tests/ApkVerityTest/Android.bp
+++ b/tests/ApkVerityTest/Android.bp
@@ -13,20 +13,20 @@
// limitations under the License.
java_test_host {
- name: "ApkVerityTests",
+ name: "ApkVerityTest",
srcs: ["src/**/*.java"],
libs: ["tradefed", "compatibility-tradefed", "compatibility-host-util"],
test_suites: ["general-tests"],
target_required: [
"block_device_writer_module",
- "ApkVerityTestApp",
- "ApkVerityTestAppSplit",
],
data: [
":ApkVerityTestCertDer",
+ ":ApkVerityTestApp",
":ApkVerityTestAppFsvSig",
":ApkVerityTestAppDm",
":ApkVerityTestAppDmFsvSig",
+ ":ApkVerityTestAppSplit",
":ApkVerityTestAppSplitFsvSig",
":ApkVerityTestAppSplitDm",
":ApkVerityTestAppSplitDmFsvSig",
diff --git a/tests/ApkVerityTest/AndroidTest.xml b/tests/ApkVerityTest/AndroidTest.xml
index 73779cbd1a87..51bcdea21f49 100644
--- a/tests/ApkVerityTest/AndroidTest.xml
+++ b/tests/ApkVerityTest/AndroidTest.xml
@@ -36,6 +36,6 @@
</target_preparer>
<test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
- <option name="jar" value="ApkVerityTests.jar" />
+ <option name="jar" value="ApkVerityTest.jar" />
</test>
</configuration>
diff --git a/tests/ManagedProfileLifecycleStressTest/app/DummyDPC/Android.bp b/tests/ManagedProfileLifecycleStressTest/app/DummyDPC/Android.bp
index d95af340337e..1f47b03d0074 100644
--- a/tests/ManagedProfileLifecycleStressTest/app/DummyDPC/Android.bp
+++ b/tests/ManagedProfileLifecycleStressTest/app/DummyDPC/Android.bp
@@ -17,4 +17,5 @@ android_test {
defaults: ["cts_defaults"],
srcs: ["src/**/*.java"],
sdk_version: "current",
+ test_suites: ["device-tests"],
}
diff --git a/tests/ManagedProfileLifecycleStressTest/src/com/android/test/stress/ManagedProfileLifecycleStressTest.java b/tests/ManagedProfileLifecycleStressTest/src/com/android/test/stress/ManagedProfileLifecycleStressTest.java
index e323592d40ca..026677e09bed 100644
--- a/tests/ManagedProfileLifecycleStressTest/src/com/android/test/stress/ManagedProfileLifecycleStressTest.java
+++ b/tests/ManagedProfileLifecycleStressTest/src/com/android/test/stress/ManagedProfileLifecycleStressTest.java
@@ -53,6 +53,8 @@ public class ManagedProfileLifecycleStressTest extends BaseHostJUnit4Test {
*/
@Test
public void testCreateStartDelete() throws Exception {
+ // Disable package verifier for ADB installs.
+ getDevice().executeShellCommand("settings put global verifier_verify_adb_installs 0");
int iteration = 0;
final long deadline = System.nanoTime() + TimeUnit.MINUTES.toNanos(TIME_LIMIT_MINUTES);
while (System.nanoTime() < deadline) {
diff --git a/tests/PackageWatchdog/src/com/android/server/PackageWatchdogTest.java b/tests/PackageWatchdog/src/com/android/server/PackageWatchdogTest.java
index ef8facec9752..b4cafe41662e 100644
--- a/tests/PackageWatchdog/src/com/android/server/PackageWatchdogTest.java
+++ b/tests/PackageWatchdog/src/com/android/server/PackageWatchdogTest.java
@@ -328,7 +328,8 @@ public class PackageWatchdogTest {
long differentVersionCode = 2L;
TestObserver observer = new TestObserver(OBSERVER_NAME_1) {
@Override
- public int onHealthCheckFailed(VersionedPackage versionedPackage) {
+ public int onHealthCheckFailed(VersionedPackage versionedPackage,
+ int failureReason) {
if (versionedPackage.getVersionCode() == VERSION_CODE) {
// Only rollback for specific versionCode
return PackageHealthObserverImpact.USER_IMPACT_MEDIUM;
@@ -1012,7 +1013,7 @@ public class PackageWatchdogTest {
mImpact = impact;
}
- public int onHealthCheckFailed(VersionedPackage versionedPackage) {
+ public int onHealthCheckFailed(VersionedPackage versionedPackage, int failureReason) {
mHealthCheckFailedPackages.add(versionedPackage.getPackageName());
return mImpact;
}
diff --git a/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/RollbackTest.java b/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/RollbackTest.java
index abe6c6152da5..daa85bd06669 100644
--- a/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/RollbackTest.java
+++ b/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/RollbackTest.java
@@ -1098,4 +1098,28 @@ public class RollbackTest {
InstallUtils.dropShellPermissionIdentity();
}
}
+
+ /**
+ * Test we can't enable rollback for non-whitelisted app without
+ * TEST_MANAGE_ROLLBACKS permission
+ */
+ @Test
+ public void testNonRollbackWhitelistedApp() throws Exception {
+ try {
+ InstallUtils.adoptShellPermissionIdentity(
+ Manifest.permission.INSTALL_PACKAGES,
+ Manifest.permission.DELETE_PACKAGES,
+ Manifest.permission.MANAGE_ROLLBACKS);
+
+ Uninstall.packages(TestApp.A);
+ Install.single(TestApp.A1).commit();
+ assertThat(RollbackUtils.getAvailableRollback(TestApp.A)).isNull();
+
+ Install.single(TestApp.A2).setEnableRollback().commit();
+ Thread.sleep(TimeUnit.SECONDS.toMillis(2));
+ assertThat(RollbackUtils.getAvailableRollback(TestApp.A)).isNull();
+ } finally {
+ InstallUtils.dropShellPermissionIdentity();
+ }
+ }
}
diff --git a/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/StagedRollbackTest.java b/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/StagedRollbackTest.java
index 3be7a4a0261d..879ac64c6a55 100644
--- a/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/StagedRollbackTest.java
+++ b/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/StagedRollbackTest.java
@@ -22,18 +22,14 @@ import static com.android.cts.rollback.lib.RollbackUtils.getUniqueRollbackInfoFo
import static com.google.common.truth.Truth.assertThat;
import android.Manifest;
-import android.annotation.Nullable;
import android.content.ComponentName;
-import android.content.Context;
import android.content.Intent;
-import android.content.pm.PackageInfo;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import android.content.rollback.RollbackInfo;
import android.content.rollback.RollbackManager;
import android.os.ParcelFileDescriptor;
import android.provider.DeviceConfig;
-import android.text.TextUtils;
import androidx.test.platform.app.InstrumentationRegistry;
@@ -75,7 +71,6 @@ public class StagedRollbackTest {
private static final String PROPERTY_WATCHDOG_REQUEST_TIMEOUT_MILLIS =
"watchdog_request_timeout_millis";
- private static final String MODULE_META_DATA_PACKAGE = getModuleMetadataPackageName();
private static final TestApp NETWORK_STACK = new TestApp("NetworkStack",
getNetworkStackPackageName(), -1, false, findNetworkStackApk());
@@ -186,21 +181,15 @@ public class StagedRollbackTest {
}
/**
- * Stage install ModuleMetadata package to simulate a Mainline module update.
+ * Stage install an apk with rollback that will be later triggered by unattributable crash.
*/
@Test
public void testNativeWatchdogTriggersRollback_Phase1() throws Exception {
- resetModuleMetadataPackage();
- Context context = InstrumentationRegistry.getInstrumentation().getContext();
- PackageInfo metadataPackageInfo = context.getPackageManager().getPackageInfo(
- MODULE_META_DATA_PACKAGE, 0);
- String metadataApkPath = metadataPackageInfo.applicationInfo.sourceDir;
- assertThat(metadataApkPath).isNotNull();
- assertThat(metadataApkPath).isNotEqualTo("");
-
- runShellCommand("pm install "
- + "-r --enable-rollback --staged --wait "
- + metadataApkPath);
+ Uninstall.packages(TestApp.A);
+ Install.single(TestApp.A1).commit();
+ assertThat(InstallUtils.getInstalledVersion(TestApp.A)).isEqualTo(1);
+
+ Install.single(TestApp.A2).setEnableRollback().setStaged().commit();
}
/**
@@ -208,9 +197,10 @@ public class StagedRollbackTest {
*/
@Test
public void testNativeWatchdogTriggersRollback_Phase2() throws Exception {
+ assertThat(InstallUtils.getInstalledVersion(TestApp.A)).isEqualTo(2);
RollbackManager rm = RollbackUtils.getRollbackManager();
assertThat(getUniqueRollbackInfoForPackage(rm.getAvailableRollbacks(),
- MODULE_META_DATA_PACKAGE)).isNotNull();
+ TestApp.A)).isNotNull();
}
/**
@@ -218,9 +208,10 @@ public class StagedRollbackTest {
*/
@Test
public void testNativeWatchdogTriggersRollback_Phase3() throws Exception {
+ assertThat(InstallUtils.getInstalledVersion(TestApp.A)).isEqualTo(1);
RollbackManager rm = RollbackUtils.getRollbackManager();
assertThat(getUniqueRollbackInfoForPackage(rm.getRecentlyCommittedRollbacks(),
- MODULE_META_DATA_PACKAGE)).isNotNull();
+ TestApp.A)).isNotNull();
}
@Test
@@ -351,24 +342,35 @@ public class StagedRollbackTest {
getNetworkStackPackageName())).isNull();
}
- @Nullable
private static String getModuleMetadataPackageName() {
- String packageName = InstrumentationRegistry.getInstrumentation().getContext()
+ return InstrumentationRegistry.getInstrumentation().getContext()
.getResources().getString(R.string.config_defaultModuleMetadataProvider);
- if (TextUtils.isEmpty(packageName)) {
- return null;
- }
- return packageName;
}
- private void resetModuleMetadataPackage() {
- RollbackManager rm = RollbackUtils.getRollbackManager();
+ @Test
+ public void testRollbackWhitelistedApp_Phase1() throws Exception {
+ // Remove available rollbacks
+ String pkgName = getModuleMetadataPackageName();
+ RollbackUtils.getRollbackManager().expireRollbackForPackage(pkgName);
+ assertThat(RollbackUtils.getAvailableRollback(pkgName)).isNull();
+
+ // Overwrite existing permissions. We don't want TEST_MANAGE_ROLLBACKS which allows us
+ // to enable rollback for any app
+ InstallUtils.adoptShellPermissionIdentity(
+ Manifest.permission.INSTALL_PACKAGES,
+ Manifest.permission.MANAGE_ROLLBACKS);
- assertThat(MODULE_META_DATA_PACKAGE).isNotNull();
- rm.expireRollbackForPackage(MODULE_META_DATA_PACKAGE);
+ // Re-install a whitelisted app with rollbacks enabled
+ String filePath = InstrumentationRegistry.getInstrumentation().getContext()
+ .getPackageManager().getPackageInfo(pkgName, 0).applicationInfo.sourceDir;
+ TestApp app = new TestApp("ModuleMetadata", pkgName, -1, false, new File(filePath));
+ Install.single(app).setStaged().setEnableRollback()
+ .addInstallFlags(PackageManager.INSTALL_REPLACE_EXISTING).commit();
+ }
- assertThat(getUniqueRollbackInfoForPackage(rm.getAvailableRollbacks(),
- MODULE_META_DATA_PACKAGE)).isNull();
+ @Test
+ public void testRollbackWhitelistedApp_Phase2() throws Exception {
+ assertThat(RollbackUtils.getAvailableRollback(getModuleMetadataPackageName())).isNotNull();
}
private static void runShellCommand(String cmd) {
diff --git a/tests/RollbackTest/StagedRollbackTest/src/com/android/tests/rollback/host/StagedRollbackTest.java b/tests/RollbackTest/StagedRollbackTest/src/com/android/tests/rollback/host/StagedRollbackTest.java
index e4a8febb8bce..07d829d2d0bb 100644
--- a/tests/RollbackTest/StagedRollbackTest/src/com/android/tests/rollback/host/StagedRollbackTest.java
+++ b/tests/RollbackTest/StagedRollbackTest/src/com/android/tests/rollback/host/StagedRollbackTest.java
@@ -175,6 +175,16 @@ public class StagedRollbackTest extends BaseHostJUnit4Test {
runPhase("testPreviouslyAbandonedRollbacks_Phase3");
}
+ /**
+ * Tests we can enable rollback for a whitelisted app.
+ */
+ @Test
+ public void testRollbackWhitelistedApp() throws Exception {
+ runPhase("testRollbackWhitelistedApp_Phase1");
+ getDevice().reboot();
+ runPhase("testRollbackWhitelistedApp_Phase2");
+ }
+
private void crashProcess(String processName, int numberOfCrashes) throws Exception {
String pid = "";
String lastPid = "invalid";
diff --git a/tests/net/common/java/android/net/LinkPropertiesTest.java b/tests/net/common/java/android/net/LinkPropertiesTest.java
index ae8285b8a908..a7eef055a71c 100644
--- a/tests/net/common/java/android/net/LinkPropertiesTest.java
+++ b/tests/net/common/java/android/net/LinkPropertiesTest.java
@@ -16,7 +16,9 @@
package android.net;
+import static com.android.testutils.ParcelUtilsKt.assertParcelSane;
import static com.android.testutils.ParcelUtilsKt.assertParcelingIsLossless;
+import static com.android.testutils.ParcelUtilsKt.parcelingRoundTrip;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -47,25 +49,22 @@ import java.util.Set;
@RunWith(AndroidJUnit4.class)
@SmallTest
public class LinkPropertiesTest {
- private static final InetAddress ADDRV4 = InetAddresses.parseNumericAddress("75.208.6.1");
- private static final InetAddress ADDRV6 = InetAddresses.parseNumericAddress(
- "2001:0db8:85a3:0000:0000:8a2e:0370:7334");
- private static final InetAddress DNS1 = InetAddresses.parseNumericAddress("75.208.7.1");
- private static final InetAddress DNS2 = InetAddresses.parseNumericAddress("69.78.7.1");
- private static final InetAddress DNS6 = InetAddresses.parseNumericAddress(
- "2001:4860:4860::8888");
- private static final InetAddress PRIVDNS1 = InetAddresses.parseNumericAddress("1.1.1.1");
- private static final InetAddress PRIVDNS2 = InetAddresses.parseNumericAddress("1.0.0.1");
- private static final InetAddress PRIVDNS6 = InetAddresses.parseNumericAddress(
- "2606:4700:4700::1111");
- private static final InetAddress PCSCFV4 = InetAddresses.parseNumericAddress("10.77.25.37");
- private static final InetAddress PCSCFV6 = InetAddresses.parseNumericAddress(
- "2001:0db8:85a3:0000:0000:8a2e:0370:1");
- private static final InetAddress GATEWAY1 = InetAddresses.parseNumericAddress("75.208.8.1");
- private static final InetAddress GATEWAY2 = InetAddresses.parseNumericAddress("69.78.8.1");
- private static final InetAddress GATEWAY61 = InetAddresses.parseNumericAddress(
- "fe80::6:0000:613");
- private static final InetAddress GATEWAY62 = InetAddresses.parseNumericAddress("fe80::6:2222");
+ private static final InetAddress ADDRV4 = address("75.208.6.1");
+ private static final InetAddress ADDRV6 = address("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
+ private static final InetAddress DNS1 = address("75.208.7.1");
+ private static final InetAddress DNS2 = address("69.78.7.1");
+ private static final InetAddress DNS6 = address("2001:4860:4860::8888");
+ private static final InetAddress PRIVDNS1 = address("1.1.1.1");
+ private static final InetAddress PRIVDNS2 = address("1.0.0.1");
+ private static final InetAddress PRIVDNS6 = address("2606:4700:4700::1111");
+ private static final InetAddress PCSCFV4 = address("10.77.25.37");
+ private static final InetAddress PCSCFV6 = address("2001:0db8:85a3:0000:0000:8a2e:0370:1");
+ private static final InetAddress GATEWAY1 = address("75.208.8.1");
+ private static final InetAddress GATEWAY2 = address("69.78.8.1");
+ private static final InetAddress GATEWAY61 = address("fe80::6:0000:613");
+ private static final InetAddress GATEWAY62 = address("fe80::6:22%lo");
+ private static final InetAddress TESTIPV4ADDR = address("192.168.47.42");
+ private static final InetAddress TESTIPV6ADDR = address("fe80::7:33%43");
private static final String NAME = "qmi0";
private static final String DOMAINS = "google.com";
private static final String PRIV_DNS_SERVER_NAME = "private.dns.com";
@@ -75,8 +74,7 @@ public class LinkPropertiesTest {
private static final LinkAddress LINKADDRV6 = new LinkAddress(ADDRV6, 128);
private static final LinkAddress LINKADDRV6LINKLOCAL = new LinkAddress("fe80::1/64");
- // TODO: replace all calls to NetworkUtils.numericToInetAddress with calls to this method.
- private InetAddress Address(String addrString) {
+ private static InetAddress address(String addrString) {
return InetAddresses.parseNumericAddress(addrString);
}
@@ -228,7 +226,7 @@ public class LinkPropertiesTest {
target.clear();
target.setInterfaceName(NAME);
// change link addresses
- target.addLinkAddress(new LinkAddress(Address("75.208.6.2"), 32));
+ target.addLinkAddress(new LinkAddress(address("75.208.6.2"), 32));
target.addLinkAddress(LINKADDRV6);
target.addDnsServer(DNS1);
target.addDnsServer(DNS2);
@@ -243,7 +241,7 @@ public class LinkPropertiesTest {
target.addLinkAddress(LINKADDRV4);
target.addLinkAddress(LINKADDRV6);
// change dnses
- target.addDnsServer(Address("75.208.7.2"));
+ target.addDnsServer(address("75.208.7.2"));
target.addDnsServer(DNS2);
target.addPcscfServer(PCSCFV6);
target.addRoute(new RouteInfo(GATEWAY1));
@@ -255,10 +253,10 @@ public class LinkPropertiesTest {
target.setInterfaceName(NAME);
target.addLinkAddress(LINKADDRV4);
target.addLinkAddress(LINKADDRV6);
- target.addDnsServer(Address("75.208.7.2"));
+ target.addDnsServer(address("75.208.7.2"));
target.addDnsServer(DNS2);
// change pcscf
- target.addPcscfServer(Address("2001::1"));
+ target.addPcscfServer(address("2001::1"));
target.addRoute(new RouteInfo(GATEWAY1));
target.addRoute(new RouteInfo(GATEWAY2));
target.setMtu(MTU);
@@ -271,9 +269,9 @@ public class LinkPropertiesTest {
target.addDnsServer(DNS1);
target.addDnsServer(DNS2);
// change gateway
- target.addRoute(new RouteInfo(Address("75.208.8.2")));
- target.addRoute(new RouteInfo(GATEWAY2));
+ target.addRoute(new RouteInfo(address("75.208.8.2")));
target.setMtu(MTU);
+ target.addRoute(new RouteInfo(GATEWAY2));
assertFalse(source.equals(target));
target.clear();
@@ -349,7 +347,7 @@ public class LinkPropertiesTest {
@Test
public void testRouteInterfaces() {
- LinkAddress prefix = new LinkAddress(Address("2001:db8::"), 32);
+ LinkAddress prefix = new LinkAddress(address("2001:db8::"), 32);
InetAddress address = ADDRV6;
// Add a route with no interface to a LinkProperties with no interface. No errors.
@@ -739,8 +737,7 @@ public class LinkPropertiesTest {
// Add an on-link route, making the on-link DNS server reachable,
// but there is still no IPv4 address.
- assertTrue(v4lp.addRoute(new RouteInfo(
- new IpPrefix(NetworkUtils.numericToInetAddress("75.208.0.0"), 16))));
+ assertTrue(v4lp.addRoute(new RouteInfo(new IpPrefix(address("75.208.0.0"), 16))));
assertFalse(v4lp.isReachable(DNS1));
assertFalse(v4lp.isReachable(DNS2));
@@ -756,9 +753,9 @@ public class LinkPropertiesTest {
assertTrue(v4lp.isReachable(DNS2));
final LinkProperties v6lp = new LinkProperties();
- final InetAddress kLinkLocalDns = Address("fe80::6:1");
- final InetAddress kLinkLocalDnsWithScope = Address("fe80::6:2%43");
- final InetAddress kOnLinkDns = Address("2001:db8:85a3::53");
+ final InetAddress kLinkLocalDns = address("fe80::6:1");
+ final InetAddress kLinkLocalDnsWithScope = address("fe80::6:2%43");
+ final InetAddress kOnLinkDns = address("2001:db8:85a3::53");
assertFalse(v6lp.isReachable(kLinkLocalDns));
assertFalse(v6lp.isReachable(kLinkLocalDnsWithScope));
assertFalse(v6lp.isReachable(kOnLinkDns));
@@ -767,7 +764,7 @@ public class LinkPropertiesTest {
// Add a link-local route, making the link-local DNS servers reachable. Because
// we assume the presence of an IPv6 link-local address, link-local DNS servers
// are considered reachable, but only those with a non-zero scope identifier.
- assertTrue(v6lp.addRoute(new RouteInfo(new IpPrefix(Address("fe80::"), 64))));
+ assertTrue(v6lp.addRoute(new RouteInfo(new IpPrefix(address("fe80::"), 64))));
assertFalse(v6lp.isReachable(kLinkLocalDns));
assertTrue(v6lp.isReachable(kLinkLocalDnsWithScope));
assertFalse(v6lp.isReachable(kOnLinkDns));
@@ -783,7 +780,7 @@ public class LinkPropertiesTest {
// Add a global route on link, but no global address yet. DNS servers reachable
// via a route that doesn't require a gateway: give them the benefit of the
// doubt and hope the link-local source address suffices for communication.
- assertTrue(v6lp.addRoute(new RouteInfo(new IpPrefix(Address("2001:db8:85a3::"), 64))));
+ assertTrue(v6lp.addRoute(new RouteInfo(new IpPrefix(address("2001:db8:85a3::"), 64))));
assertFalse(v6lp.isReachable(kLinkLocalDns));
assertTrue(v6lp.isReachable(kLinkLocalDnsWithScope));
assertTrue(v6lp.isReachable(kOnLinkDns));
@@ -812,7 +809,7 @@ public class LinkPropertiesTest {
stacked.setInterfaceName("v4-test0");
v6lp.addStackedLink(stacked);
- InetAddress stackedAddress = Address("192.0.0.4");
+ InetAddress stackedAddress = address("192.0.0.4");
LinkAddress stackedLinkAddress = new LinkAddress(stackedAddress, 32);
assertFalse(v6lp.isReachable(stackedAddress));
stacked.addLinkAddress(stackedLinkAddress);
@@ -845,7 +842,7 @@ public class LinkPropertiesTest {
LinkProperties rmnet1 = new LinkProperties();
rmnet1.setInterfaceName("rmnet1");
rmnet1.addLinkAddress(new LinkAddress("10.0.0.3/8"));
- RouteInfo defaultRoute1 = new RouteInfo((IpPrefix) null, Address("10.0.0.1"),
+ RouteInfo defaultRoute1 = new RouteInfo((IpPrefix) null, address("10.0.0.1"),
rmnet1.getInterfaceName());
RouteInfo directRoute1 = new RouteInfo(new IpPrefix("10.0.0.0/8"), null,
rmnet1.getInterfaceName());
@@ -864,7 +861,7 @@ public class LinkPropertiesTest {
rmnet2.setInterfaceName("rmnet2");
rmnet2.addLinkAddress(new LinkAddress("fe80::cafe/64"));
rmnet2.addLinkAddress(new LinkAddress("2001:db8::2/64"));
- RouteInfo defaultRoute2 = new RouteInfo((IpPrefix) null, Address("2001:db8::1"),
+ RouteInfo defaultRoute2 = new RouteInfo((IpPrefix) null, address("2001:db8::1"),
rmnet2.getInterfaceName());
RouteInfo directRoute2 = new RouteInfo(new IpPrefix("2001:db8::/64"), null,
rmnet2.getInterfaceName());
@@ -930,24 +927,54 @@ public class LinkPropertiesTest {
public void testLinkPropertiesParcelable() throws Exception {
LinkProperties source = new LinkProperties();
source.setInterfaceName(NAME);
- // set 2 link addresses
+
source.addLinkAddress(LINKADDRV4);
source.addLinkAddress(LINKADDRV6);
- // set 2 dnses
+
source.addDnsServer(DNS1);
source.addDnsServer(DNS2);
- // set 2 gateways
+ source.addDnsServer(GATEWAY62);
+
+ source.addPcscfServer(TESTIPV4ADDR);
+ source.addPcscfServer(TESTIPV6ADDR);
+
+ source.setUsePrivateDns(true);
+ source.setPrivateDnsServerName(PRIV_DNS_SERVER_NAME);
+
+ source.setDomains(DOMAINS);
+
source.addRoute(new RouteInfo(GATEWAY1));
source.addRoute(new RouteInfo(GATEWAY2));
- // set 2 validated private dnses
+
source.addValidatedPrivateDnsServer(DNS6);
source.addValidatedPrivateDnsServer(GATEWAY61);
+ source.addValidatedPrivateDnsServer(TESTIPV6ADDR);
+
+ source.setHttpProxy(ProxyInfo.buildDirectProxy("test", 8888));
source.setMtu(MTU);
+ source.setTcpBufferSizes(TCP_BUFFER_SIZES);
+
source.setNat64Prefix(new IpPrefix("2001:db8:1:2:64:64::/96"));
- assertParcelingIsLossless(source);
+ source.setWakeOnLanSupported(true);
+
+ final LinkProperties stacked = new LinkProperties();
+ stacked.setInterfaceName("test-stacked");
+ source.addStackedLink(stacked);
+
+ assertParcelSane(source, 15 /* fieldCount */);
+ }
+
+ @Test
+ public void testLinkLocalDnsServerParceling() throws Exception {
+ final String strAddress = "fe80::1%lo";
+ final LinkProperties lp = new LinkProperties();
+ lp.addDnsServer(address(strAddress));
+ final LinkProperties unparceled = parcelingRoundTrip(lp);
+ // Inet6Address#equals does not test for the scope id
+ assertEquals(strAddress, unparceled.getDnsServers().get(0).getHostAddress());
}
@Test
diff --git a/tests/net/java/android/net/TcpKeepalivePacketDataTest.java b/tests/net/java/android/net/TcpKeepalivePacketDataTest.java
index 5cb0d7e7a1a9..e632aafde70e 100644
--- a/tests/net/java/android/net/TcpKeepalivePacketDataTest.java
+++ b/tests/net/java/android/net/TcpKeepalivePacketDataTest.java
@@ -22,8 +22,6 @@ import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
-import android.net.SocketKeepalive.InvalidPacketException;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
diff --git a/tests/utils/testutils/Android.bp b/tests/utils/testutils/Android.bp
index 027b1d6799fd..f71be7b0b7d3 100644
--- a/tests/utils/testutils/Android.bp
+++ b/tests/utils/testutils/Android.bp
@@ -17,16 +17,11 @@
java_library {
name: "frameworks-base-testutils",
- srcs: [
- "java/**/*.java",
- "java/**/*.kt",
- ],
+ srcs: ["java/**/*.java"],
static_libs: [
"junit",
"hamcrest-library",
- "truth-prebuilt",
- "mockito-target-minus-junit4",
],
libs: [
diff --git a/tools/aapt2/ResourceUtils.cpp b/tools/aapt2/ResourceUtils.cpp
index bd2ab5377311..03009aaeead2 100644
--- a/tools/aapt2/ResourceUtils.cpp
+++ b/tools/aapt2/ResourceUtils.cpp
@@ -738,7 +738,13 @@ std::unique_ptr<Item> ParseBinaryResValue(const ResourceType& type, const Config
const android::Res_value& res_value,
StringPool* dst_pool) {
if (type == ResourceType::kId) {
- return util::make_unique<Id>();
+ if (res_value.dataType != android::Res_value::TYPE_REFERENCE &&
+ res_value.dataType != android::Res_value::TYPE_DYNAMIC_REFERENCE) {
+ // plain "id" resources are actually encoded as dummy values (aapt1 uses an empty string,
+ // while aapt2 uses a false boolean).
+ return util::make_unique<Id>();
+ }
+ // fall through to regular reference deserialization logic
}
const uint32_t data = util::DeviceToHost32(res_value.data);
diff --git a/tools/aapt2/java/ProguardRules.cpp b/tools/aapt2/java/ProguardRules.cpp
index b06607e41c07..0db1807c75d9 100644
--- a/tools/aapt2/java/ProguardRules.cpp
+++ b/tools/aapt2/java/ProguardRules.cpp
@@ -160,13 +160,19 @@ class MenuVisitor : public BaseVisitor {
void Visit(xml::Element* node) override {
if (node->namespace_uri.empty() && node->name == "item") {
for (const auto& attr : node->attributes) {
- if (attr.namespace_uri == xml::kSchemaAndroid) {
- if ((attr.name == "actionViewClass" || attr.name == "actionProviderClass") &&
- util::IsJavaClassName(attr.value)) {
- AddClass(node->line_number, attr.value, "android.content.Context");
- } else if (attr.name == "onClick") {
- AddMethod(node->line_number, attr.value, "android.view.MenuItem");
- }
+ // AppCompat-v7 defines its own versions of Android attributes if
+ // they're defined after SDK 7 (the below are from 11 and 14,
+ // respectively), so don't bother checking the XML namespace.
+ //
+ // Given the names of the containing XML files and the attribute
+ // names, it's unlikely that keeping these classes would be wrong.
+ if ((attr.name == "actionViewClass" || attr.name == "actionProviderClass") &&
+ util::IsJavaClassName(attr.value)) {
+ AddClass(node->line_number, attr.value, "android.content.Context");
+ }
+
+ if (attr.namespace_uri == xml::kSchemaAndroid && attr.name == "onClick") {
+ AddMethod(node->line_number, attr.value, "android.view.MenuItem");
}
}
}
diff --git a/tools/aapt2/java/ProguardRules_test.cpp b/tools/aapt2/java/ProguardRules_test.cpp
index 87205973566b..b6e76021ccc1 100644
--- a/tools/aapt2/java/ProguardRules_test.cpp
+++ b/tools/aapt2/java/ProguardRules_test.cpp
@@ -326,6 +326,25 @@ TEST(ProguardRulesTest, MenuRulesAreEmitted) {
EXPECT_THAT(actual, Not(HasSubstr("com.foo.Bat")));
}
+TEST(ProguardRulesTest, MenuRulesAreEmittedForActionClasses) {
+ std::unique_ptr<IAaptContext> context = test::ContextBuilder().Build();
+ std::unique_ptr<xml::XmlResource> menu = test::BuildXmlDom(R"(
+ <menu xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:app="http://schemas.android.com/apk/res-auto">
+ <item android:id="@+id/my_item"
+ app:actionViewClass="com.foo.Bar"
+ app:actionProviderClass="com.foo.Baz" />
+ </menu>)");
+ menu->file.name = test::ParseNameOrDie("menu/foo");
+
+ proguard::KeepSet set;
+ ASSERT_TRUE(proguard::CollectProguardRules(context.get(), menu.get(), &set));
+
+ std::string actual = GetKeepSetString(set, /** minimal_rules */ false);
+ EXPECT_THAT(actual, HasSubstr("-keep class com.foo.Bar"));
+ EXPECT_THAT(actual, HasSubstr("-keep class com.foo.Baz"));
+}
+
TEST(ProguardRulesTest, TransitionPathMotionRulesAreEmitted) {
std::unique_ptr<IAaptContext> context = test::ContextBuilder().Build();
std::unique_ptr<xml::XmlResource> transition = test::BuildXmlDom(R"(
diff --git a/tools/localedata/extract_icu_data.py b/tools/localedata/extract_icu_data.py
index 6b4c34677d96..ca1847af7d06 100755
--- a/tools/localedata/extract_icu_data.py
+++ b/tools/localedata/extract_icu_data.py
@@ -176,6 +176,9 @@ def read_and_dump_likely_data(icu_data_dir):
dump_representative_locales(representative_locales)
return likely_script_dict
+def escape_script_variable_name(script):
+ """Escape characters, e.g. '~', in a C++ variable name"""
+ return script.replace("~", "_")
def read_parent_data(icu_data_dir):
"""Read locale parent data from ICU data files."""
@@ -221,7 +224,7 @@ def dump_parent_data(script_organized_dict):
for script in sorted_scripts:
parent_dict = script_organized_dict[script]
print ('const std::unordered_map<uint32_t, uint32_t> %s_PARENTS({'
- % script.upper())
+ % escape_script_variable_name(script.upper()))
for locale in sorted(parent_dict.keys()):
parent = parent_dict[locale]
print ' {0x%08Xu, 0x%08Xu}, // %s -> %s' % (
@@ -239,7 +242,7 @@ def dump_parent_data(script_organized_dict):
for script in sorted_scripts:
print " {{'%c', '%c', '%c', '%c'}, &%s_PARENTS}," % (
script[0], script[1], script[2], script[3],
- script.upper())
+ escape_script_variable_name(script.upper()))
print '};'
diff --git a/tools/stats_log_api_gen/Android.bp b/tools/stats_log_api_gen/Android.bp
index 7733761eebcc..15c327852001 100644
--- a/tools/stats_log_api_gen/Android.bp
+++ b/tools/stats_log_api_gen/Android.bp
@@ -21,6 +21,7 @@ cc_binary_host {
name: "stats-log-api-gen",
srcs: [
"Collation.cpp",
+ "atoms_info_writer.cpp",
"java_writer.cpp",
"java_writer_q.cpp",
"main.cpp",
@@ -102,13 +103,19 @@ genrule {
cc_library {
name: "libstatslog",
host_supported: true,
- generated_sources: ["statslog.cpp"],
- generated_headers: ["statslog.h"],
+ generated_sources: [
+ "statslog.cpp",
+ ],
+ generated_headers: [
+ "statslog.h"
+ ],
cflags: [
"-Wall",
"-Werror",
],
- export_generated_headers: ["statslog.h"],
+ export_generated_headers: [
+ "statslog.h"
+ ],
shared_libs: [
"liblog",
"libcutils",
@@ -127,3 +134,4 @@ cc_library {
},
},
}
+
diff --git a/tools/stats_log_api_gen/Collation.cpp b/tools/stats_log_api_gen/Collation.cpp
index 373adca994a1..fa556010646c 100644
--- a/tools/stats_log_api_gen/Collation.cpp
+++ b/tools/stats_log_api_gen/Collation.cpp
@@ -379,6 +379,7 @@ int collate_atoms(const Descriptor *descriptor, Atoms *atoms) {
int errorCount = 0;
const bool dbg = false;
+ int maxPushedAtomId = 2;
for (int i = 0; i < descriptor->field_count(); i++) {
const FieldDescriptor *atomField = descriptor->field(i);
@@ -447,8 +448,14 @@ int collate_atoms(const Descriptor *descriptor, Atoms *atoms) {
}
atoms->non_chained_decls.insert(nonChainedAtomDecl);
}
+
+ if (atomDecl.code < PULL_ATOM_START_ID && atomDecl.code > maxPushedAtomId) {
+ maxPushedAtomId = atomDecl.code;
+ }
}
+ atoms->maxPushedAtomId = maxPushedAtomId;
+
if (dbg) {
printf("signatures = [\n");
for (map<vector<java_type_t>, set<string>>::const_iterator it =
diff --git a/tools/stats_log_api_gen/Collation.h b/tools/stats_log_api_gen/Collation.h
index 44746c96df1b..3efdd520d7f5 100644
--- a/tools/stats_log_api_gen/Collation.h
+++ b/tools/stats_log_api_gen/Collation.h
@@ -111,6 +111,7 @@ struct Atoms {
set<AtomDecl> decls;
set<AtomDecl> non_chained_decls;
map<vector<java_type_t>, set<string>> non_chained_signatures_to_modules;
+ int maxPushedAtomId;
};
/**
@@ -123,4 +124,4 @@ int collate_atom(const Descriptor *atom, AtomDecl *atomDecl, vector<java_type_t>
} // namespace android
-#endif // ANDROID_STATS_LOG_API_GEN_COLLATION_H \ No newline at end of file
+#endif // ANDROID_STATS_LOG_API_GEN_COLLATION_H
diff --git a/tools/stats_log_api_gen/atoms_info_writer.cpp b/tools/stats_log_api_gen/atoms_info_writer.cpp
new file mode 100644
index 000000000000..54a9982bb5c2
--- /dev/null
+++ b/tools/stats_log_api_gen/atoms_info_writer.cpp
@@ -0,0 +1,227 @@
+/*
+ * Copyright (C) 2019, 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.
+ */
+
+#include "atoms_info_writer.h"
+#include "utils.h"
+
+#include <map>
+#include <set>
+#include <vector>
+
+namespace android {
+namespace stats_log_api_gen {
+
+static void write_atoms_info_header_body(FILE* out, const Atoms& atoms) {
+ fprintf(out, "struct StateAtomFieldOptions {\n");
+ fprintf(out, " std::vector<int> primaryFields;\n");
+ fprintf(out, " int exclusiveField;\n");
+ fprintf(out, "};\n");
+ fprintf(out, "\n");
+
+ fprintf(out, "struct AtomsInfo {\n");
+ fprintf(out,
+ " const static std::set<int> "
+ "kTruncatingTimestampAtomBlackList;\n");
+ fprintf(out, " const static std::map<int, int> kAtomsWithUidField;\n");
+ fprintf(out,
+ " const static std::set<int> kAtomsWithAttributionChain;\n");
+ fprintf(out,
+ " const static std::map<int, StateAtomFieldOptions> "
+ "kStateAtomsFieldOptions;\n");
+ fprintf(out,
+ " const static std::map<int, std::vector<int>> "
+ "kBytesFieldAtoms;\n");
+ fprintf(out,
+ " const static std::set<int> kWhitelistedAtoms;\n");
+ fprintf(out, "};\n");
+ fprintf(out, "const static int kMaxPushedAtomId = %d;\n\n", atoms.maxPushedAtomId);
+
+}
+
+static void write_atoms_info_cpp_body(FILE* out, const Atoms& atoms) {
+ std::set<string> kTruncatingAtomNames = {"mobile_radio_power_state_changed",
+ "audio_state_changed",
+ "call_state_changed",
+ "phone_signal_strength_changed",
+ "mobile_bytes_transfer_by_fg_bg",
+ "mobile_bytes_transfer"};
+ fprintf(out,
+ "const std::set<int> "
+ "AtomsInfo::kTruncatingTimestampAtomBlackList = {\n");
+ for (set<string>::const_iterator blacklistedAtom = kTruncatingAtomNames.begin();
+ blacklistedAtom != kTruncatingAtomNames.end(); blacklistedAtom++) {
+ fprintf(out, " %s,\n", make_constant_name(*blacklistedAtom).c_str());
+ }
+ fprintf(out, "};\n");
+ fprintf(out, "\n");
+
+ fprintf(out,
+ "const std::set<int> AtomsInfo::kAtomsWithAttributionChain = {\n");
+ for (set<AtomDecl>::const_iterator atom = atoms.decls.begin();
+ atom != atoms.decls.end(); atom++) {
+ for (vector<AtomField>::const_iterator field = atom->fields.begin();
+ field != atom->fields.end(); field++) {
+ if (field->javaType == JAVA_TYPE_ATTRIBUTION_CHAIN) {
+ string constant = make_constant_name(atom->name);
+ fprintf(out, " %s,\n", constant.c_str());
+ break;
+ }
+ }
+ }
+
+ fprintf(out, "};\n");
+ fprintf(out, "\n");
+
+ fprintf(out,
+ "const std::set<int> AtomsInfo::kWhitelistedAtoms = {\n");
+ for (set<AtomDecl>::const_iterator atom = atoms.decls.begin();
+ atom != atoms.decls.end(); atom++) {
+ if (atom->whitelisted) {
+ string constant = make_constant_name(atom->name);
+ fprintf(out, " %s,\n", constant.c_str());
+ }
+ }
+
+ fprintf(out, "};\n");
+ fprintf(out, "\n");
+
+ fprintf(out, "static std::map<int, int> getAtomUidField() {\n");
+ fprintf(out, " std::map<int, int> uidField;\n");
+ for (set<AtomDecl>::const_iterator atom = atoms.decls.begin();
+ atom != atoms.decls.end(); atom++) {
+ if (atom->uidField == 0) {
+ continue;
+ }
+ fprintf(out,
+ "\n // Adding uid field for atom "
+ "(%d)%s\n",
+ atom->code, atom->name.c_str());
+ fprintf(out, " uidField[static_cast<int>(%s)] = %d;\n",
+ make_constant_name(atom->name).c_str(), atom->uidField);
+ }
+
+ fprintf(out, " return uidField;\n");
+ fprintf(out, "};\n");
+
+ fprintf(out,
+ "const std::map<int, int> AtomsInfo::kAtomsWithUidField = "
+ "getAtomUidField();\n");
+
+ fprintf(out,
+ "static std::map<int, StateAtomFieldOptions> "
+ "getStateAtomFieldOptions() {\n");
+ fprintf(out, " std::map<int, StateAtomFieldOptions> options;\n");
+ fprintf(out, " StateAtomFieldOptions opt;\n");
+ for (set<AtomDecl>::const_iterator atom = atoms.decls.begin();
+ atom != atoms.decls.end(); atom++) {
+ if (atom->primaryFields.size() == 0 && atom->exclusiveField == 0) {
+ continue;
+ }
+ fprintf(out,
+ "\n // Adding primary and exclusive fields for atom "
+ "(%d)%s\n",
+ atom->code, atom->name.c_str());
+ fprintf(out, " opt.primaryFields.clear();\n");
+ for (const auto& field : atom->primaryFields) {
+ fprintf(out, " opt.primaryFields.push_back(%d);\n", field);
+ }
+
+ fprintf(out, " opt.exclusiveField = %d;\n", atom->exclusiveField);
+ fprintf(out, " options[static_cast<int>(%s)] = opt;\n",
+ make_constant_name(atom->name).c_str());
+ }
+
+ fprintf(out, " return options;\n");
+ fprintf(out, "}\n");
+
+ fprintf(out,
+ "const std::map<int, StateAtomFieldOptions> "
+ "AtomsInfo::kStateAtomsFieldOptions = "
+ "getStateAtomFieldOptions();\n");
+
+ fprintf(out,
+ "static std::map<int, std::vector<int>> "
+ "getBinaryFieldAtoms() {\n");
+ fprintf(out, " std::map<int, std::vector<int>> options;\n");
+ for (set<AtomDecl>::const_iterator atom = atoms.decls.begin();
+ atom != atoms.decls.end(); atom++) {
+ if (atom->binaryFields.size() == 0) {
+ continue;
+ }
+ fprintf(out,
+ "\n // Adding binary fields for atom "
+ "(%d)%s\n",
+ atom->code, atom->name.c_str());
+
+ for (const auto& field : atom->binaryFields) {
+ fprintf(out, " options[static_cast<int>(%s)].push_back(%d);\n",
+ make_constant_name(atom->name).c_str(), field);
+ }
+ }
+
+ fprintf(out, " return options;\n");
+ fprintf(out, "}\n");
+
+ fprintf(out,
+ "const std::map<int, std::vector<int>> "
+ "AtomsInfo::kBytesFieldAtoms = "
+ "getBinaryFieldAtoms();\n");
+
+}
+
+int write_atoms_info_header(FILE* out, const Atoms &atoms, const string& namespaceStr) {
+ // Print prelude
+ fprintf(out, "// This file is autogenerated\n");
+ fprintf(out, "\n");
+ fprintf(out, "#pragma once\n");
+ fprintf(out, "\n");
+ fprintf(out, "#include <vector>\n");
+ fprintf(out, "#include <map>\n");
+ fprintf(out, "#include <set>\n");
+ fprintf(out, "\n");
+
+ write_namespace(out, namespaceStr);
+
+ write_atoms_info_header_body(out, atoms);
+
+ fprintf(out, "\n");
+ write_closing_namespace(out, namespaceStr);
+
+ return 0;
+}
+
+int write_atoms_info_cpp(FILE *out, const Atoms &atoms, const string& namespaceStr,
+ const string& importHeader, const string& statslogHeader) {
+ // Print prelude
+ fprintf(out, "// This file is autogenerated\n");
+ fprintf(out, "\n");
+ fprintf(out, "#include <%s>\n", importHeader.c_str());
+ fprintf(out, "#include <%s>\n", statslogHeader.c_str());
+ fprintf(out, "\n");
+
+ write_namespace(out, namespaceStr);
+
+ write_atoms_info_cpp_body(out, atoms);
+
+ // Print footer
+ fprintf(out, "\n");
+ write_closing_namespace(out, namespaceStr);
+
+ return 0;
+}
+
+} // namespace stats_log_api_gen
+} // namespace android
diff --git a/tools/stats_log_api_gen/atoms_info_writer.h b/tools/stats_log_api_gen/atoms_info_writer.h
new file mode 100644
index 000000000000..bc677825181f
--- /dev/null
+++ b/tools/stats_log_api_gen/atoms_info_writer.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2019, 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.
+ */
+
+#pragma once
+
+#include "Collation.h"
+
+#include <stdio.h>
+#include <string.h>
+
+namespace android {
+namespace stats_log_api_gen {
+
+using namespace std;
+
+int write_atoms_info_cpp(FILE* out, const Atoms& atoms, const string& namespaceStr,
+ const string& importHeader, const string& statslogHeader
+);
+
+int write_atoms_info_header(FILE* out, const Atoms& atoms, const string& namespaceStr);
+
+} // namespace stats_log_api_gen
+} // namespace android
diff --git a/tools/stats_log_api_gen/java_writer.cpp b/tools/stats_log_api_gen/java_writer.cpp
index d45c4e7efb12..712b48edbc1b 100644
--- a/tools/stats_log_api_gen/java_writer.cpp
+++ b/tools/stats_log_api_gen/java_writer.cpp
@@ -189,6 +189,7 @@ static int write_java_methods(
}
fprintf(out, "\n");
+ fprintf(out, "%s builder.usePooledBuffer();\n", indent.c_str());
fprintf(out, "%s StatsLog.write(builder.build());\n", indent.c_str());
// Add support for writing using Q schema if this is not the default module.
diff --git a/tools/stats_log_api_gen/main.cpp b/tools/stats_log_api_gen/main.cpp
index bc6d82ad267c..ad171da0511c 100644
--- a/tools/stats_log_api_gen/main.cpp
+++ b/tools/stats_log_api_gen/main.cpp
@@ -1,6 +1,7 @@
#include "Collation.h"
+#include "atoms_info_writer.h"
#if !defined(STATS_SCHEMA_LEGACY)
#include "java_writer.h"
#endif
@@ -18,8 +19,6 @@
#include <stdlib.h>
#include <string.h>
-#include "android-base/strings.h"
-
using namespace google::protobuf;
using namespace std;
@@ -28,152 +27,6 @@ namespace stats_log_api_gen {
using android::os::statsd::Atom;
-static void write_atoms_info_cpp(FILE *out, const Atoms &atoms) {
- std::set<string> kTruncatingAtomNames = {"mobile_radio_power_state_changed",
- "audio_state_changed",
- "call_state_changed",
- "phone_signal_strength_changed",
- "mobile_bytes_transfer_by_fg_bg",
- "mobile_bytes_transfer"};
- fprintf(out,
- "const std::set<int> "
- "AtomsInfo::kTruncatingTimestampAtomBlackList = {\n");
- for (set<string>::const_iterator blacklistedAtom = kTruncatingAtomNames.begin();
- blacklistedAtom != kTruncatingAtomNames.end(); blacklistedAtom++) {
- fprintf(out, " %s,\n", make_constant_name(*blacklistedAtom).c_str());
- }
- fprintf(out, "};\n");
- fprintf(out, "\n");
-
- fprintf(out,
- "const std::set<int> AtomsInfo::kAtomsWithAttributionChain = {\n");
- for (set<AtomDecl>::const_iterator atom = atoms.decls.begin();
- atom != atoms.decls.end(); atom++) {
- for (vector<AtomField>::const_iterator field = atom->fields.begin();
- field != atom->fields.end(); field++) {
- if (field->javaType == JAVA_TYPE_ATTRIBUTION_CHAIN) {
- string constant = make_constant_name(atom->name);
- fprintf(out, " %s,\n", constant.c_str());
- break;
- }
- }
- }
-
- fprintf(out, "};\n");
- fprintf(out, "\n");
-
- fprintf(out,
- "const std::set<int> AtomsInfo::kWhitelistedAtoms = {\n");
- for (set<AtomDecl>::const_iterator atom = atoms.decls.begin();
- atom != atoms.decls.end(); atom++) {
- if (atom->whitelisted) {
- string constant = make_constant_name(atom->name);
- fprintf(out, " %s,\n", constant.c_str());
- }
- }
-
- fprintf(out, "};\n");
- fprintf(out, "\n");
-
- fprintf(out, "static std::map<int, int> getAtomUidField() {\n");
- fprintf(out, " std::map<int, int> uidField;\n");
- for (set<AtomDecl>::const_iterator atom = atoms.decls.begin();
- atom != atoms.decls.end(); atom++) {
- if (atom->uidField == 0) {
- continue;
- }
- fprintf(out,
- "\n // Adding uid field for atom "
- "(%d)%s\n",
- atom->code, atom->name.c_str());
- fprintf(out, " uidField[static_cast<int>(%s)] = %d;\n",
- make_constant_name(atom->name).c_str(), atom->uidField);
- }
-
- fprintf(out, " return uidField;\n");
- fprintf(out, "};\n");
-
- fprintf(out,
- "const std::map<int, int> AtomsInfo::kAtomsWithUidField = "
- "getAtomUidField();\n");
-
- fprintf(out,
- "static std::map<int, StateAtomFieldOptions> "
- "getStateAtomFieldOptions() {\n");
- fprintf(out, " std::map<int, StateAtomFieldOptions> options;\n");
- fprintf(out, " StateAtomFieldOptions opt;\n");
- for (set<AtomDecl>::const_iterator atom = atoms.decls.begin();
- atom != atoms.decls.end(); atom++) {
- if (atom->primaryFields.size() == 0 && atom->exclusiveField == 0) {
- continue;
- }
- fprintf(out,
- "\n // Adding primary and exclusive fields for atom "
- "(%d)%s\n",
- atom->code, atom->name.c_str());
- fprintf(out, " opt.primaryFields.clear();\n");
- for (const auto& field : atom->primaryFields) {
- fprintf(out, " opt.primaryFields.push_back(%d);\n", field);
- }
-
- fprintf(out, " opt.exclusiveField = %d;\n", atom->exclusiveField);
- fprintf(out, " options[static_cast<int>(%s)] = opt;\n",
- make_constant_name(atom->name).c_str());
- }
-
- fprintf(out, " return options;\n");
- fprintf(out, "}\n");
-
- fprintf(out,
- "const std::map<int, StateAtomFieldOptions> "
- "AtomsInfo::kStateAtomsFieldOptions = "
- "getStateAtomFieldOptions();\n");
-
- fprintf(out,
- "static std::map<int, std::vector<int>> "
- "getBinaryFieldAtoms() {\n");
- fprintf(out, " std::map<int, std::vector<int>> options;\n");
- for (set<AtomDecl>::const_iterator atom = atoms.decls.begin();
- atom != atoms.decls.end(); atom++) {
- if (atom->binaryFields.size() == 0) {
- continue;
- }
- fprintf(out,
- "\n // Adding binary fields for atom "
- "(%d)%s\n",
- atom->code, atom->name.c_str());
-
- for (const auto& field : atom->binaryFields) {
- fprintf(out, " options[static_cast<int>(%s)].push_back(%d);\n",
- make_constant_name(atom->name).c_str(), field);
- }
- }
-
- fprintf(out, " return options;\n");
- fprintf(out, "}\n");
-
- fprintf(out,
- "const std::map<int, std::vector<int>> "
- "AtomsInfo::kBytesFieldAtoms = "
- "getBinaryFieldAtoms();\n");
-}
-
-// Writes namespaces for the cpp and header files, returning the number of namespaces written.
-void write_namespace(FILE* out, const string& cppNamespaces) {
- vector<string> cppNamespaceVec = android::base::Split(cppNamespaces, ",");
- for (string cppNamespace : cppNamespaceVec) {
- fprintf(out, "namespace %s {\n", cppNamespace.c_str());
- }
-}
-
-// Writes namespace closing brackets for cpp and header files.
-void write_closing_namespace(FILE* out, const string& cppNamespaces) {
- vector<string> cppNamespaceVec = android::base::Split(cppNamespaces, ",");
- for (auto it = cppNamespaceVec.rbegin(); it != cppNamespaceVec.rend(); ++it) {
- fprintf(out, "} // namespace %s\n", it->c_str());
- }
-}
-
static int write_stats_log_cpp(FILE *out, const Atoms &atoms, const AtomDecl &attributionDecl,
const string& moduleName, const string& cppNamespace,
const string& importHeader) {
@@ -202,11 +55,6 @@ static int write_stats_log_cpp(FILE *out, const Atoms &atoms, const AtomDecl &at
fprintf(out, "const static bool kStatsdEnabled = false;\n");
fprintf(out, "#endif\n");
- // AtomsInfo is only used by statsd internally and is not needed for other modules.
- if (moduleName == DEFAULT_MODULE_NAME) {
- write_atoms_info_cpp(out, atoms);
- }
-
fprintf(out, "int64_t lastRetryTimestampNs = -1;\n");
fprintf(out, "const int64_t kMinRetryIntervalNs = NS_PER_SEC * 60 * 20; // 20 minutes\n");
fprintf(out, "static std::mutex mLogdRetryMutex;\n");
@@ -543,42 +391,6 @@ static int write_stats_log_cpp(FILE *out, const Atoms &atoms, const AtomDecl &at
return 0;
}
-static void write_cpp_usage(
- FILE* out, const string& method_name, const string& atom_code_name,
- const AtomDecl& atom, const AtomDecl &attributionDecl) {
- fprintf(out, " * Usage: %s(StatsLog.%s", method_name.c_str(),
- atom_code_name.c_str());
-
- for (vector<AtomField>::const_iterator field = atom.fields.begin();
- field != atom.fields.end(); field++) {
- if (field->javaType == JAVA_TYPE_ATTRIBUTION_CHAIN) {
- for (auto chainField : attributionDecl.fields) {
- if (chainField.javaType == JAVA_TYPE_STRING) {
- fprintf(out, ", const std::vector<%s>& %s",
- cpp_type_name(chainField.javaType),
- chainField.name.c_str());
- } else {
- fprintf(out, ", const %s* %s, size_t %s_length",
- cpp_type_name(chainField.javaType),
- chainField.name.c_str(), chainField.name.c_str());
- }
- }
- } else if (field->javaType == JAVA_TYPE_KEY_VALUE_PAIR) {
- fprintf(out, ", const std::map<int, int32_t>& %s_int"
- ", const std::map<int, int64_t>& %s_long"
- ", const std::map<int, char const*>& %s_str"
- ", const std::map<int, float>& %s_float",
- field->name.c_str(),
- field->name.c_str(),
- field->name.c_str(),
- field->name.c_str());
- } else {
- fprintf(out, ", %s %s", cpp_type_name(field->javaType), field->name.c_str());
- }
- }
- fprintf(out, ");\n");
-}
-
static void write_cpp_method_header(
FILE* out,
const string& method_name,
@@ -645,45 +457,8 @@ write_stats_log_header(FILE* out, const Atoms& atoms, const AtomDecl &attributio
fprintf(out, " * API For logging statistics events.\n");
fprintf(out, " */\n");
fprintf(out, "\n");
- fprintf(out, "/**\n");
- fprintf(out, " * Constants for atom codes.\n");
- fprintf(out, " */\n");
- fprintf(out, "enum {\n");
- std::map<int, set<AtomDecl>::const_iterator> atom_code_to_non_chained_decl_map;
- build_non_chained_decl_map(atoms, &atom_code_to_non_chained_decl_map);
-
- size_t i = 0;
- int maxPushedAtomId = 2;
- // Print atom constants
- for (set<AtomDecl>::const_iterator atom = atoms.decls.begin();
- atom != atoms.decls.end(); atom++) {
- // Skip if the atom is not needed for the module.
- if (!atom_needed_for_module(*atom, moduleName)) {
- continue;
- }
- string constant = make_constant_name(atom->name);
- fprintf(out, "\n");
- fprintf(out, " /**\n");
- fprintf(out, " * %s %s\n", atom->message.c_str(), atom->name.c_str());
- write_cpp_usage(out, "stats_write", constant, *atom, attributionDecl);
-
- auto non_chained_decl = atom_code_to_non_chained_decl_map.find(atom->code);
- if (non_chained_decl != atom_code_to_non_chained_decl_map.end()) {
- write_cpp_usage(out, "stats_write_non_chained", constant, *non_chained_decl->second,
- attributionDecl);
- }
- fprintf(out, " */\n");
- char const* const comma = (i == atoms.decls.size() - 1) ? "" : ",";
- fprintf(out, " %s = %d%s\n", constant.c_str(), atom->code, comma);
- if (atom->code < PULL_ATOM_START_ID && atom->code > maxPushedAtomId) {
- maxPushedAtomId = atom->code;
- }
- i++;
- }
- fprintf(out, "\n");
- fprintf(out, "};\n");
- fprintf(out, "\n");
+ write_native_atom_constants(out, atoms, attributionDecl, moduleName);
// Print constants for the enum values.
fprintf(out, "//\n");
@@ -723,36 +498,6 @@ write_stats_log_header(FILE* out, const Atoms& atoms, const AtomDecl &attributio
fprintf(out, "};\n");
fprintf(out, "\n");
- // This metadata is only used by statsd, which uses the default libstatslog.
- if (moduleName == DEFAULT_MODULE_NAME) {
-
- fprintf(out, "struct StateAtomFieldOptions {\n");
- fprintf(out, " std::vector<int> primaryFields;\n");
- fprintf(out, " int exclusiveField;\n");
- fprintf(out, "};\n");
- fprintf(out, "\n");
-
- fprintf(out, "struct AtomsInfo {\n");
- fprintf(out,
- " const static std::set<int> "
- "kTruncatingTimestampAtomBlackList;\n");
- fprintf(out, " const static std::map<int, int> kAtomsWithUidField;\n");
- fprintf(out,
- " const static std::set<int> kAtomsWithAttributionChain;\n");
- fprintf(out,
- " const static std::map<int, StateAtomFieldOptions> "
- "kStateAtomsFieldOptions;\n");
- fprintf(out,
- " const static std::map<int, std::vector<int>> "
- "kBytesFieldAtoms;");
- fprintf(out,
- " const static std::set<int> kWhitelistedAtoms;\n");
- fprintf(out, "};\n");
-
- fprintf(out, "const static int kMaxPushedAtomId = %d;\n\n",
- maxPushedAtomId);
- }
-
// Print write methods
fprintf(out, "//\n");
fprintf(out, "// Write methods\n");
@@ -1235,15 +980,21 @@ print_usage()
fprintf(stderr, "usage: stats-log-api-gen OPTIONS\n");
fprintf(stderr, "\n");
fprintf(stderr, "OPTIONS\n");
- fprintf(stderr, " --cpp FILENAME the header file to output\n");
- fprintf(stderr, " --header FILENAME the cpp file to output\n");
+ fprintf(stderr, " --cpp FILENAME the header file to output for write helpers\n");
+ fprintf(stderr, " --header FILENAME the cpp file to output for write helpers\n");
+ fprintf(stderr,
+ " --atomsInfoCpp FILENAME the header file to output for statsd metadata\n");
+ fprintf(stderr, " --atomsInfoHeader FILENAME the cpp file to output for statsd metadata\n");
fprintf(stderr, " --help this message\n");
fprintf(stderr, " --java FILENAME the java file to output\n");
fprintf(stderr, " --jni FILENAME the jni file to output\n");
fprintf(stderr, " --module NAME optional, module name to generate outputs for\n");
fprintf(stderr, " --namespace COMMA,SEP,NAMESPACE required for cpp/header with module\n");
fprintf(stderr, " comma separated namespace of the files\n");
- fprintf(stderr, " --importHeader NAME required for cpp/jni to say which header to import\n");
+ fprintf(stderr," --importHeader NAME required for cpp/jni to say which header to import "
+ "for write helpers\n");
+ fprintf(stderr," --atomsInfoImportHeader NAME required for cpp to say which header to import "
+ "for statsd metadata\n");
fprintf(stderr, " --javaPackage PACKAGE the package for the java file.\n");
fprintf(stderr, " required for java with module\n");
fprintf(stderr, " --javaClass CLASS the class name of the java class.\n");
@@ -1260,10 +1011,13 @@ run(int argc, char const*const* argv)
string headerFilename;
string javaFilename;
string jniFilename;
+ string atomsInfoCppFilename;
+ string atomsInfoHeaderFilename;
string moduleName = DEFAULT_MODULE_NAME;
string cppNamespace = DEFAULT_CPP_NAMESPACE;
string cppHeaderImport = DEFAULT_CPP_HEADER_IMPORT;
+ string atomsInfoCppHeaderImport = DEFAULT_ATOMS_INFO_CPP_HEADER_IMPORT;
string javaPackage = DEFAULT_JAVA_PACKAGE;
string javaClass = DEFAULT_JAVA_CLASS;
@@ -1335,14 +1089,38 @@ run(int argc, char const*const* argv)
return 1;
}
javaClass = argv[index];
+ } else if (0 == strcmp("--atomsInfoHeader", argv[index])) {
+ index++;
+ if (index >= argc) {
+ print_usage();
+ return 1;
+ }
+ atomsInfoHeaderFilename = argv[index];
+ } else if (0 == strcmp("--atomsInfoCpp", argv[index])) {
+ index++;
+ if (index >= argc) {
+ print_usage();
+ return 1;
+ }
+ atomsInfoCppFilename = argv[index];
+ } else if (0 == strcmp("--atomsInfoImportHeader", argv[index])) {
+ index++;
+ if (index >= argc) {
+ print_usage();
+ return 1;
+ }
+ atomsInfoCppHeaderImport = argv[index];
}
+
index++;
}
if (cppFilename.size() == 0
&& headerFilename.size() == 0
&& javaFilename.size() == 0
- && jniFilename.size() == 0) {
+ && jniFilename.size() == 0
+ && atomsInfoHeaderFilename.size() == 0
+ && atomsInfoCppFilename.size() == 0) {
print_usage();
return 1;
}
@@ -1359,6 +1137,30 @@ run(int argc, char const*const* argv)
collate_atom(android::os::statsd::AttributionNode::descriptor(),
&attributionDecl, &attributionSignature);
+ // Write the atoms info .cpp file
+ if (atomsInfoCppFilename.size() != 0) {
+ FILE* out = fopen(atomsInfoCppFilename.c_str(), "w");
+ if (out == NULL) {
+ fprintf(stderr, "Unable to open file for write: %s\n", atomsInfoCppFilename.c_str());
+ return 1;
+ }
+ errorCount = android::stats_log_api_gen::write_atoms_info_cpp(
+ out, atoms, cppNamespace, atomsInfoCppHeaderImport, cppHeaderImport);
+ fclose(out);
+ }
+
+ // Write the atoms info .h file
+ if (atomsInfoHeaderFilename.size() != 0) {
+ FILE* out = fopen(atomsInfoHeaderFilename.c_str(), "w");
+ if (out == NULL) {
+ fprintf(stderr, "Unable to open file for write: %s\n", atomsInfoHeaderFilename.c_str());
+ return 1;
+ }
+ errorCount = android::stats_log_api_gen::write_atoms_info_header(out, atoms, cppNamespace);
+ fclose(out);
+ }
+
+
// Write the .cpp file
if (cppFilename.size() != 0) {
FILE* out = fopen(cppFilename.c_str(), "w");
diff --git a/tools/stats_log_api_gen/utils.cpp b/tools/stats_log_api_gen/utils.cpp
index 141861d443b0..d6cfe95a34f5 100644
--- a/tools/stats_log_api_gen/utils.cpp
+++ b/tools/stats_log_api_gen/utils.cpp
@@ -16,9 +16,19 @@
#include "utils.h"
+#include "android-base/strings.h"
+
namespace android {
namespace stats_log_api_gen {
+static void build_non_chained_decl_map(const Atoms& atoms,
+ std::map<int, set<AtomDecl>::const_iterator>* decl_map) {
+ for (set<AtomDecl>::const_iterator atom = atoms.non_chained_decls.begin();
+ atom != atoms.non_chained_decls.end(); atom++) {
+ decl_map->insert(std::make_pair(atom->code, atom));
+ }
+}
+
/**
* Turn lower and camel case into upper case with underscores.
*/
@@ -102,14 +112,98 @@ bool signature_needed_for_module(const set<string>& modules, const string& modul
return modules.find(moduleName) != modules.end();
}
-void build_non_chained_decl_map(const Atoms& atoms,
- std::map<int, set<AtomDecl>::const_iterator>* decl_map) {
- for (set<AtomDecl>::const_iterator atom = atoms.non_chained_decls.begin();
- atom != atoms.non_chained_decls.end(); atom++) {
- decl_map->insert(std::make_pair(atom->code, atom));
+// Native
+// Writes namespaces for the cpp and header files, returning the number of namespaces written.
+void write_namespace(FILE* out, const string& cppNamespaces) {
+ vector<string> cppNamespaceVec = android::base::Split(cppNamespaces, ",");
+ for (string cppNamespace : cppNamespaceVec) {
+ fprintf(out, "namespace %s {\n", cppNamespace.c_str());
}
}
+// Writes namespace closing brackets for cpp and header files.
+void write_closing_namespace(FILE* out, const string& cppNamespaces) {
+ vector<string> cppNamespaceVec = android::base::Split(cppNamespaces, ",");
+ for (auto it = cppNamespaceVec.rbegin(); it != cppNamespaceVec.rend(); ++it) {
+ fprintf(out, "} // namespace %s\n", it->c_str());
+ }
+}
+
+static void write_cpp_usage(
+ FILE* out, const string& method_name, const string& atom_code_name,
+ const AtomDecl& atom, const AtomDecl &attributionDecl) {
+ fprintf(out, " * Usage: %s(StatsLog.%s", method_name.c_str(),
+ atom_code_name.c_str());
+
+ for (vector<AtomField>::const_iterator field = atom.fields.begin();
+ field != atom.fields.end(); field++) {
+ if (field->javaType == JAVA_TYPE_ATTRIBUTION_CHAIN) {
+ for (auto chainField : attributionDecl.fields) {
+ if (chainField.javaType == JAVA_TYPE_STRING) {
+ fprintf(out, ", const std::vector<%s>& %s",
+ cpp_type_name(chainField.javaType),
+ chainField.name.c_str());
+ } else {
+ fprintf(out, ", const %s* %s, size_t %s_length",
+ cpp_type_name(chainField.javaType),
+ chainField.name.c_str(), chainField.name.c_str());
+ }
+ }
+ } else if (field->javaType == JAVA_TYPE_KEY_VALUE_PAIR) {
+ fprintf(out, ", const std::map<int, int32_t>& %s_int"
+ ", const std::map<int, int64_t>& %s_long"
+ ", const std::map<int, char const*>& %s_str"
+ ", const std::map<int, float>& %s_float",
+ field->name.c_str(),
+ field->name.c_str(),
+ field->name.c_str(),
+ field->name.c_str());
+ } else {
+ fprintf(out, ", %s %s", cpp_type_name(field->javaType), field->name.c_str());
+ }
+ }
+ fprintf(out, ");\n");
+}
+
+void write_native_atom_constants(FILE* out, const Atoms& atoms, const AtomDecl& attributionDecl,
+ const string& moduleName) {
+ fprintf(out, "/**\n");
+ fprintf(out, " * Constants for atom codes.\n");
+ fprintf(out, " */\n");
+ fprintf(out, "enum {\n");
+
+ std::map<int, set<AtomDecl>::const_iterator> atom_code_to_non_chained_decl_map;
+ build_non_chained_decl_map(atoms, &atom_code_to_non_chained_decl_map);
+
+ size_t i = 0;
+ // Print atom constants
+ for (set<AtomDecl>::const_iterator atom = atoms.decls.begin();
+ atom != atoms.decls.end(); atom++) {
+ // Skip if the atom is not needed for the module.
+ if (!atom_needed_for_module(*atom, moduleName)) {
+ continue;
+ }
+ string constant = make_constant_name(atom->name);
+ fprintf(out, "\n");
+ fprintf(out, " /**\n");
+ fprintf(out, " * %s %s\n", atom->message.c_str(), atom->name.c_str());
+ write_cpp_usage(out, "stats_write", constant, *atom, attributionDecl);
+
+ auto non_chained_decl = atom_code_to_non_chained_decl_map.find(atom->code);
+ if (non_chained_decl != atom_code_to_non_chained_decl_map.end()) {
+ write_cpp_usage(out, "stats_write_non_chained", constant, *non_chained_decl->second,
+ attributionDecl);
+ }
+ fprintf(out, " */\n");
+ char const* const comma = (i == atoms.decls.size() - 1) ? "" : ",";
+ fprintf(out, " %s = %d%s\n", constant.c_str(), atom->code, comma);
+ i++;
+ }
+ fprintf(out, "\n");
+ fprintf(out, "};\n");
+ fprintf(out, "\n");
+}
+
// Java
void write_java_atom_codes(FILE* out, const Atoms& atoms, const string& moduleName) {
fprintf(out, " // Constants for atom codes.\n");
diff --git a/tools/stats_log_api_gen/utils.h b/tools/stats_log_api_gen/utils.h
index e860fa9045cb..a89387f00bce 100644
--- a/tools/stats_log_api_gen/utils.h
+++ b/tools/stats_log_api_gen/utils.h
@@ -33,6 +33,7 @@ using namespace std;
const string DEFAULT_MODULE_NAME = "DEFAULT";
const string DEFAULT_CPP_NAMESPACE = "android,util";
const string DEFAULT_CPP_HEADER_IMPORT = "statslog.h";
+const string DEFAULT_ATOMS_INFO_CPP_HEADER_IMPORT = "atoms_info.h";
const string DEFAULT_JAVA_PACKAGE = "android.util";
const string DEFAULT_JAVA_CLASS = "StatsLogInternal";
@@ -49,8 +50,14 @@ bool atom_needed_for_module(const AtomDecl& atomDecl, const string& moduleName);
bool signature_needed_for_module(const set<string>& modules, const string& moduleName);
-void build_non_chained_decl_map(const Atoms& atoms,
- std::map<int, set<AtomDecl>::const_iterator>* decl_map);
+// Common Native helpers
+void write_namespace(FILE* out, const string& cppNamespaces);
+
+void write_closing_namespace(FILE* out, const string& cppNamespaces);
+
+void write_native_atom_constants(FILE* out, const Atoms& atoms, const AtomDecl& attributionDecl,
+ const string& moduleName
+);
// Common Java helpers.
void write_java_atom_codes(FILE* out, const Atoms& atoms, const string& moduleName);
diff --git a/wifi/Android.bp b/wifi/Android.bp
new file mode 100644
index 000000000000..08115ecb6b2b
--- /dev/null
+++ b/wifi/Android.bp
@@ -0,0 +1,87 @@
+// Copyright (C) 2019 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.
+
+
+filegroup {
+ name: "framework-wifi-updatable-sources",
+ srcs: [
+ "java/**/*.java",
+ "java/**/*.aidl",
+ ],
+ exclude_srcs: [
+ ":framework-wifi-non-updatable-sources"
+ ],
+ path: "java",
+}
+
+filegroup {
+ name: "framework-wifi-non-updatable-sources",
+ srcs: [
+ // TODO(b/146011398) package android.net.wifi is now split amongst 2 jars: framework.jar and
+ // framework-wifi.jar. This is not a good idea, should move WifiNetworkScoreCache
+ // to a separate package.
+ "java/android/net/wifi/WifiNetworkScoreCache.java",
+ "java/android/net/wifi/WifiCondManager.java",
+ "java/android/net/wifi/wificond/*.java",
+ ":libwificond_ipc_aidl",
+ ],
+}
+
+filegroup {
+ name: "framework-wifi-annotations",
+ srcs: ["java/android/net/wifi/WifiAnnotations.java"],
+}
+
+java_library {
+ name: "framework-wifi",
+ sdk_version: "core_platform", // TODO(b/140299412) should be core_current
+ libs: [
+ "framework-minus-apex", // TODO(b/140299412) should be framework-system-stubs
+ ],
+ srcs: [
+ ":framework-wifi-updatable-sources",
+ ],
+ installable: true,
+ optimize: {
+ enabled: false
+ }
+}
+
+droidstubs {
+ name: "framework-wifi-stubs-srcs",
+ srcs: [
+ ":framework-annotations",
+ ":framework-wifi-updatable-sources",
+ ],
+ aidl: {
+ include_dirs: ["frameworks/base/core/java"],
+ },
+ defaults: [ "framework-module-stubs-defaults-systemapi" ],
+ sdk_version: "core_current",
+ libs: ["android_system_stubs_current"],
+}
+
+java_library {
+ name: "framework-wifi-stubs",
+ srcs: [":framework-wifi-stubs-srcs"],
+ aidl: {
+ export_include_dirs: [
+ "java",
+ ],
+ },
+ sdk_version: "core_current",
+ libs: ["android_system_stubs_current"],
+ installable: false,
+}
+
diff --git a/wifi/java/android/net/wifi/IWifiManager.aidl b/wifi/java/android/net/wifi/IWifiManager.aidl
index b52880e29e30..1678d5a4776b 100644
--- a/wifi/java/android/net/wifi/IWifiManager.aidl
+++ b/wifi/java/android/net/wifi/IWifiManager.aidl
@@ -108,7 +108,9 @@ interface IWifiManager
String getCountryCode();
- boolean isDualBandSupported();
+ boolean is5GHzBandSupported();
+
+ boolean is6GHzBandSupported();
boolean needs5GHzToAnyApBandConversion();
@@ -186,7 +188,7 @@ interface IWifiManager
byte[] retrieveSoftApBackupData();
- void restoreSoftApBackupData(in byte[] data);
+ SoftApConfiguration restoreSoftApBackupData(in byte[] data);
void restoreSupplicantBackupData(in byte[] supplicantData, in byte[] ipConfigData);
diff --git a/wifi/java/android/net/wifi/ScanResult.java b/wifi/java/android/net/wifi/ScanResult.java
index 729ef61f0e4d..83a18008919d 100644
--- a/wifi/java/android/net/wifi/ScanResult.java
+++ b/wifi/java/android/net/wifi/ScanResult.java
@@ -103,6 +103,12 @@ public class ScanResult implements Parcelable {
/**
* @hide
+ * Security protocol type: WAPI.
+ */
+ public static final int PROTOCOL_WAPI = 4;
+
+ /**
+ * @hide
* No security key management scheme.
*/
public static final int KEY_MGMT_NONE = 0;
@@ -169,6 +175,18 @@ public class ScanResult implements Parcelable {
public static final int KEY_MGMT_OWE_TRANSITION = 12;
/**
* @hide
+ * Security key management scheme: WAPI_PSK.
+ */
+ @SystemApi
+ public static final int KEY_MGMT_WAPI_PSK = 13;
+ /**
+ * @hide
+ * Security key management scheme: WAPI_CERT.
+ */
+ @SystemApi
+ public static final int KEY_MGMT_WAPI_CERT = 14;
+ /**
+ * @hide
* No cipher suite.
*/
public static final int CIPHER_NONE = 0;
@@ -192,6 +210,11 @@ public class ScanResult implements Parcelable {
* Cipher suite: GCMP
*/
public static final int CIPHER_GCMP_256 = 4;
+ /**
+ * @hide
+ * Cipher suite: SMS4
+ */
+ public static final int CIPHER_SMS4 = 5;
/**
* The detected signal level in dBm, also known as the RSSI.
diff --git a/wifi/java/android/net/wifi/SoftApConfiguration.java b/wifi/java/android/net/wifi/SoftApConfiguration.java
index d755053e60d2..fd8a924bdbee 100644
--- a/wifi/java/android/net/wifi/SoftApConfiguration.java
+++ b/wifi/java/android/net/wifi/SoftApConfiguration.java
@@ -60,32 +60,77 @@ public final class SoftApConfiguration implements Parcelable {
* @hide
*/
@SystemApi
- public static final int BAND_2GHZ = 0;
+ public static final int BAND_2GHZ = 1 << 0;
/**
* 5GHz band.
* @hide
*/
@SystemApi
- public static final int BAND_5GHZ = 1;
+ public static final int BAND_5GHZ = 1 << 1;
/**
- * Device is allowed to choose the optimal band (2Ghz or 5Ghz) based on device capability,
+ * 6GHz band.
+ * @hide
+ */
+ @SystemApi
+ public static final int BAND_6GHZ = 1 << 2;
+
+ /**
+ * Device is allowed to choose the optimal band (2Ghz, 5Ghz, 6Ghz) based on device capability,
* operating country code and current radio conditions.
* @hide
*/
@SystemApi
- public static final int BAND_ANY = -1;
+ public static final int BAND_ANY = BAND_2GHZ | BAND_5GHZ | BAND_6GHZ;
/** @hide */
@Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = { "BAND_TYPE_" }, value = {
+ @IntDef(flag = true, prefix = { "BAND_TYPE_" }, value = {
BAND_2GHZ,
BAND_5GHZ,
- BAND_ANY,
+ BAND_6GHZ,
})
public @interface BandType {}
+ private static boolean isBandValid(@BandType int band) {
+ return ((band != 0) && ((band & ~BAND_ANY) == 0));
+ }
+
+ private static final int MIN_CH_2G_BAND = 1;
+ private static final int MAX_CH_2G_BAND = 14;
+ private static final int MIN_CH_5G_BAND = 34;
+ private static final int MAX_CH_5G_BAND = 196;
+ private static final int MIN_CH_6G_BAND = 1;
+ private static final int MAX_CH_6G_BAND = 253;
+
+
+
+ private static boolean isChannelBandPairValid(int channel, @BandType int band) {
+ switch (band) {
+ case BAND_2GHZ:
+ if (channel < MIN_CH_2G_BAND || channel > MAX_CH_2G_BAND) {
+ return false;
+ }
+ break;
+
+ case BAND_5GHZ:
+ if (channel < MIN_CH_5G_BAND || channel > MAX_CH_5G_BAND) {
+ return false;
+ }
+ break;
+
+ case BAND_6GHZ:
+ if (channel < MIN_CH_6G_BAND || channel > MAX_CH_6G_BAND) {
+ return false;
+ }
+ break;
+ default:
+ return false;
+ }
+ return true;
+ }
+
/**
* SSID for the AP, or null for a framework-determined SSID.
*/
@@ -439,39 +484,42 @@ public final class SoftApConfiguration implements Parcelable {
* <p>
* <li>If not set, defaults to BAND_2GHZ {@link @BandType}.</li>
*
- * @param band One of the band types from {@link @BandType}.
+ * @param band One or combination of the band types from {@link @BandType}.
* @return Builder for chaining.
*/
@NonNull
public Builder setBand(@BandType int band) {
- switch (band) {
- case BAND_2GHZ:
- break;
- case BAND_5GHZ:
- break;
- case BAND_ANY:
- break;
- default:
- throw new IllegalArgumentException("Invalid band type");
+ if (!isBandValid(band)) {
+ throw new IllegalArgumentException("Invalid band type");
}
mBand = band;
+ // Since band preference is specified, no specific channel is selected.
+ mChannel = 0;
return this;
}
/**
- * Specifies the channel for the AP.
+ * Specifies the channel and associated band for the AP.
*
* The channel which AP resides on. Valid channels are country dependent.
- * Use the special channel value 0 to have the framework auto-select a valid channel
- * from the band configured with {@link #setBand(@BandType int)}.
+ * The default for the channel is a the special value 0 to have the framework
+ * auto-select a valid channel from the band configured with
+ * {@link #setBand(@BandType int)}.
+ * Note, since 6GHz band use the same channel numbering of 2.4GHz and 5GHZ bands,
+ * the caller needs to pass the band containing the selected channel.
*
* <p>
* <li>If not set, defaults to 0.</li>
* @param channel operating channel of the AP.
+ * @param band containing this channel.
* @return Builder for chaining.
*/
@NonNull
- public Builder setChannel(int channel) {
+ public Builder setChannel(int channel, @BandType int band) {
+ if (!isChannelBandPairValid(channel, band)) {
+ throw new IllegalArgumentException("Invalid band type");
+ }
+ mBand = band;
mChannel = channel;
return this;
}
diff --git a/wifi/java/android/net/wifi/WifiAnnotations.java b/wifi/java/android/net/wifi/WifiAnnotations.java
new file mode 100644
index 000000000000..4a7dee138971
--- /dev/null
+++ b/wifi/java/android/net/wifi/WifiAnnotations.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2019 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.net.wifi;
+
+import android.annotation.IntDef;
+import android.annotation.StringDef;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Wifi annotations meant to be statically linked into client modules, since they cannot be
+ * exposed as @SystemApi.
+ *
+ * e.g. {@link IntDef}, {@link StringDef}
+ *
+ * @hide
+ */
+public final class WifiAnnotations {
+ private WifiAnnotations() {}
+
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(prefix = {"SCAN_TYPE_"}, value = {
+ WifiScanner.SCAN_TYPE_LOW_LATENCY,
+ WifiScanner.SCAN_TYPE_LOW_POWER,
+ WifiScanner.SCAN_TYPE_HIGH_ACCURACY})
+ public @interface ScanType {}
+
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(prefix = {"WIFI_BAND_"}, value = {
+ WifiScanner.WIFI_BAND_UNSPECIFIED,
+ WifiScanner.WIFI_BAND_24_GHZ,
+ WifiScanner.WIFI_BAND_5_GHZ,
+ WifiScanner.WIFI_BAND_5_GHZ_DFS_ONLY,
+ WifiScanner.WIFI_BAND_6_GHZ})
+ public @interface WifiBandBasic {}
+}
diff --git a/wifi/java/android/net/wifi/WifiCondManager.java b/wifi/java/android/net/wifi/WifiCondManager.java
new file mode 100644
index 000000000000..c05ba347ab5c
--- /dev/null
+++ b/wifi/java/android/net/wifi/WifiCondManager.java
@@ -0,0 +1,983 @@
+/*
+ * Copyright (C) 2017 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.net.wifi;
+
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.app.AlarmManager;
+import android.content.Context;
+import android.net.wifi.wificond.ChannelSettings;
+import android.net.wifi.wificond.HiddenNetwork;
+import android.net.wifi.wificond.NativeScanResult;
+import android.net.wifi.wificond.NativeWifiClient;
+import android.net.wifi.wificond.PnoSettings;
+import android.net.wifi.wificond.SingleScanSettings;
+import android.os.Binder;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.os.SystemClock;
+import android.util.Log;
+
+import com.android.internal.annotations.VisibleForTesting;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * This class provides methods for WifiNative to send control commands to wificond.
+ * NOTE: This class should only be used from WifiNative.
+ * @hide
+ */
+public class WifiCondManager implements IBinder.DeathRecipient {
+ private static final String TAG = "WifiCondManager";
+ private boolean mVerboseLoggingEnabled = false;
+
+ /**
+ * The {@link #sendMgmtFrame(String, byte[], SendMgmtFrameCallback, int) sendMgmtFrame()}
+ * timeout, in milliseconds, after which
+ * {@link SendMgmtFrameCallback#onFailure(int)} will be called with reason
+ * {@link #SEND_MGMT_FRAME_ERROR_TIMEOUT}.
+ */
+ public static final int SEND_MGMT_FRAME_TIMEOUT_MS = 1000;
+
+ private static final String TIMEOUT_ALARM_TAG = TAG + " Send Management Frame Timeout";
+
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(prefix = {"SCAN_TYPE_"},
+ value = {SCAN_TYPE_SINGLE_SCAN,
+ SCAN_TYPE_PNO_SCAN})
+ public @interface ScanResultType {}
+
+ /** Get scan results for a single scan */
+ public static final int SCAN_TYPE_SINGLE_SCAN = 0;
+
+ /** Get scan results for Pno Scan */
+ public static final int SCAN_TYPE_PNO_SCAN = 1;
+
+ private AlarmManager mAlarmManager;
+ private Handler mEventHandler;
+
+ // Cached wificond binder handlers.
+ private IWificond mWificond;
+ private HashMap<String, IClientInterface> mClientInterfaces = new HashMap<>();
+ private HashMap<String, IApInterface> mApInterfaces = new HashMap<>();
+ private HashMap<String, IWifiScannerImpl> mWificondScanners = new HashMap<>();
+ private HashMap<String, IScanEvent> mScanEventHandlers = new HashMap<>();
+ private HashMap<String, IPnoScanEvent> mPnoScanEventHandlers = new HashMap<>();
+ private HashMap<String, IApInterfaceEventCallback> mApInterfaceListeners = new HashMap<>();
+ private Runnable mDeathEventHandler;
+ /**
+ * Ensures that no more than one sendMgmtFrame operation runs concurrently.
+ */
+ private AtomicBoolean mSendMgmtFrameInProgress = new AtomicBoolean(false);
+
+ /**
+ * Interface for a callback to be used to handle scan results.
+ */
+ public interface ScanEventCallback {
+ /**
+ * Called when scan results are available.
+ */
+ void onScanResultReady();
+
+ /**
+ * Called when a scan has failed.
+ */
+ void onScanFailed();
+ }
+
+ /**
+ * Interface for a callback to provide information about PNO scan request.
+ */
+ public interface PnoScanRequestCallback {
+ /**
+ * Called when the PNO scan is requested.
+ */
+ void onPnoRequestSucceeded();
+
+ /**
+ * Called when a PNO scan request fails.
+ */
+ void onPnoRequestFailed();
+ }
+
+ private class ScanEventHandler extends IScanEvent.Stub {
+ private ScanEventCallback mCallback;
+
+ ScanEventHandler(@NonNull ScanEventCallback callback) {
+ mCallback = callback;
+ }
+
+ @Override
+ public void OnScanResultReady() {
+ Log.d(TAG, "Scan result ready event");
+ mCallback.onScanResultReady();
+ }
+
+ @Override
+ public void OnScanFailed() {
+ Log.d(TAG, "Scan failed event");
+ mCallback.onScanFailed();
+ }
+ }
+
+ /**
+ * Result of a signal poll.
+ */
+ public static class SignalPollResult {
+ // RSSI value in dBM.
+ public int currentRssi;
+ //Transmission bit rate in Mbps.
+ public int txBitrate;
+ // Association frequency in MHz.
+ public int associationFrequency;
+ //Last received packet bit rate in Mbps.
+ public int rxBitrate;
+ }
+
+ /**
+ * WiFi interface transimission counters.
+ */
+ public static class TxPacketCounters {
+ // Number of successfully transmitted packets.
+ public int txSucceeded;
+ // Number of tramsmission failures.
+ public int txFailed;
+ }
+
+ /**
+ * Callbacks for SoftAp interface.
+ */
+ public interface SoftApListener {
+ /**
+ * Invoked when there is some fatal failure in the lower layers.
+ */
+ void onFailure();
+
+ /**
+ * Invoked when the associated stations changes.
+ */
+ void onConnectedClientsChanged(NativeWifiClient client, boolean isConnected);
+
+ /**
+ * Invoked when the channel switch event happens.
+ */
+ void onSoftApChannelSwitched(int frequency, int bandwidth);
+ }
+
+ /**
+ * Callback to notify the results of a
+ * {@link #sendMgmtFrame(String, byte[], SendMgmtFrameCallback, int) sendMgmtFrame()} call.
+ * Note: no callbacks will be triggered if the iface dies while sending a frame.
+ */
+ public interface SendMgmtFrameCallback {
+ /**
+ * Called when the management frame was successfully sent and ACKed by the recipient.
+ * @param elapsedTimeMs The elapsed time between when the management frame was sent and when
+ * the ACK was processed, in milliseconds, as measured by wificond.
+ * This includes the time that the send frame spent queuing before it
+ * was sent, any firmware retries, and the time the received ACK spent
+ * queuing before it was processed.
+ */
+ void onAck(int elapsedTimeMs);
+
+ /**
+ * Called when the send failed.
+ * @param reason The error code for the failure.
+ */
+ void onFailure(@SendMgmtFrameError int reason);
+ }
+
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(prefix = {"SEND_MGMT_FRAME_ERROR_"},
+ value = {SEND_MGMT_FRAME_ERROR_UNKNOWN,
+ SEND_MGMT_FRAME_ERROR_MCS_UNSUPPORTED,
+ SEND_MGMT_FRAME_ERROR_NO_ACK,
+ SEND_MGMT_FRAME_ERROR_TIMEOUT,
+ SEND_MGMT_FRAME_ERROR_ALREADY_STARTED})
+ public @interface SendMgmtFrameError {}
+
+ // Send management frame error codes
+
+ /**
+ * Unknown error occurred during call to
+ * {@link #sendMgmtFrame(String, byte[], SendMgmtFrameCallback, int) sendMgmtFrame()}.
+ */
+ public static final int SEND_MGMT_FRAME_ERROR_UNKNOWN = 1;
+
+ /**
+ * Specifying the MCS rate in
+ * {@link #sendMgmtFrame(String, byte[], SendMgmtFrameCallback, int) sendMgmtFrame()} is not
+ * supported by this device.
+ */
+ public static final int SEND_MGMT_FRAME_ERROR_MCS_UNSUPPORTED = 2;
+
+ /**
+ * Driver reported that no ACK was received for the frame transmitted using
+ * {@link #sendMgmtFrame(String, byte[], SendMgmtFrameCallback, int) sendMgmtFrame()}.
+ */
+ public static final int SEND_MGMT_FRAME_ERROR_NO_ACK = 3;
+
+ /**
+ * Error code for when the driver fails to report on the status of the frame sent by
+ * {@link #sendMgmtFrame(String, byte[], SendMgmtFrameCallback, int) sendMgmtFrame()}
+ * after {@link #SEND_MGMT_FRAME_TIMEOUT_MS} milliseconds.
+ */
+ public static final int SEND_MGMT_FRAME_ERROR_TIMEOUT = 4;
+
+ /**
+ * An existing call to
+ * {@link #sendMgmtFrame(String, byte[], SendMgmtFrameCallback, int) sendMgmtFrame()}
+ * is in progress. Another frame cannot be sent until the first call completes.
+ */
+ public static final int SEND_MGMT_FRAME_ERROR_ALREADY_STARTED = 5;
+
+
+ public WifiCondManager(Context context) {
+ mAlarmManager = (AlarmManager) context.getSystemService(AlarmManager.class);
+ mEventHandler = new Handler(context.getMainLooper());
+ }
+
+ @VisibleForTesting
+ public WifiCondManager(Context context, IWificond wificond) {
+ this(context);
+ mWificond = wificond;
+ }
+
+ private class PnoScanEventHandler extends IPnoScanEvent.Stub {
+ private ScanEventCallback mCallback;
+
+ PnoScanEventHandler(@NonNull ScanEventCallback callback) {
+ mCallback = callback;
+ }
+
+ @Override
+ public void OnPnoNetworkFound() {
+ Log.d(TAG, "Pno scan result event");
+ mCallback.onScanResultReady();
+ }
+
+ @Override
+ public void OnPnoScanFailed() {
+ Log.d(TAG, "Pno Scan failed event");
+ mCallback.onScanFailed();
+ }
+ }
+
+ /**
+ * Listener for AP Interface events.
+ */
+ private class ApInterfaceEventCallback extends IApInterfaceEventCallback.Stub {
+ private SoftApListener mSoftApListener;
+
+ ApInterfaceEventCallback(SoftApListener listener) {
+ mSoftApListener = listener;
+ }
+
+ @Override
+ public void onConnectedClientsChanged(NativeWifiClient client, boolean isConnected) {
+ if (mVerboseLoggingEnabled) {
+ Log.d(TAG, "onConnectedClientsChanged called with "
+ + client.macAddress + " isConnected: " + isConnected);
+ }
+
+ mSoftApListener.onConnectedClientsChanged(client, isConnected);
+ }
+
+ @Override
+ public void onSoftApChannelSwitched(int frequency, int bandwidth) {
+ mSoftApListener.onSoftApChannelSwitched(frequency, bandwidth);
+ }
+ }
+
+ /**
+ * Callback triggered by wificond.
+ */
+ private class SendMgmtFrameEvent extends ISendMgmtFrameEvent.Stub {
+ private SendMgmtFrameCallback mCallback;
+ private AlarmManager.OnAlarmListener mTimeoutCallback;
+ /**
+ * ensures that mCallback is only called once
+ */
+ private boolean mWasCalled;
+
+ private void runIfFirstCall(Runnable r) {
+ if (mWasCalled) return;
+ mWasCalled = true;
+
+ mSendMgmtFrameInProgress.set(false);
+ r.run();
+ }
+
+ SendMgmtFrameEvent(@NonNull SendMgmtFrameCallback callback) {
+ mCallback = callback;
+ // called in main thread
+ mTimeoutCallback = () -> runIfFirstCall(() -> {
+ if (mVerboseLoggingEnabled) {
+ Log.e(TAG, "Timed out waiting for ACK");
+ }
+ mCallback.onFailure(SEND_MGMT_FRAME_ERROR_TIMEOUT);
+ });
+ mWasCalled = false;
+
+ mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
+ SystemClock.elapsedRealtime() + SEND_MGMT_FRAME_TIMEOUT_MS,
+ TIMEOUT_ALARM_TAG, mTimeoutCallback, mEventHandler);
+ }
+
+ // called in binder thread
+ @Override
+ public void OnAck(int elapsedTimeMs) {
+ // post to main thread
+ mEventHandler.post(() -> runIfFirstCall(() -> {
+ mAlarmManager.cancel(mTimeoutCallback);
+ mCallback.onAck(elapsedTimeMs);
+ }));
+ }
+
+ // called in binder thread
+ @Override
+ public void OnFailure(int reason) {
+ // post to main thread
+ mEventHandler.post(() -> runIfFirstCall(() -> {
+ mAlarmManager.cancel(mTimeoutCallback);
+ mCallback.onFailure(reason);
+ }));
+ }
+ }
+
+ /**
+ * Called by the binder subsystem upon remote object death.
+ * Invoke all the register death handlers and clear state.
+ */
+ @Override
+ public void binderDied() {
+ mEventHandler.post(() -> {
+ Log.e(TAG, "Wificond died!");
+ clearState();
+ // Invalidate the global wificond handle on death. Will be refreshed
+ // on the next setup call.
+ mWificond = null;
+ if (mDeathEventHandler != null) {
+ mDeathEventHandler.run();
+ }
+ });
+ }
+
+ /** Enable or disable verbose logging of WificondControl.
+ * @param enable True to enable verbose logging. False to disable verbose logging.
+ */
+ public void enableVerboseLogging(boolean enable) {
+ mVerboseLoggingEnabled = enable;
+ }
+
+ /**
+ * Initializes wificond & registers a death notification for wificond.
+ * This method clears any existing state in wificond daemon.
+ *
+ * @return Returns true on success.
+ */
+ public boolean initialize(@NonNull Runnable deathEventHandler) {
+ if (mDeathEventHandler != null) {
+ Log.e(TAG, "Death handler already present");
+ }
+ mDeathEventHandler = deathEventHandler;
+ tearDownInterfaces();
+ return true;
+ }
+
+ /**
+ * Helper method to retrieve the global wificond handle and register for
+ * death notifications.
+ */
+ private boolean retrieveWificondAndRegisterForDeath() {
+ if (mWificond != null) {
+ if (mVerboseLoggingEnabled) {
+ Log.d(TAG, "Wificond handle already retrieved");
+ }
+ // We already have a wificond handle.
+ return true;
+ }
+ IBinder binder = ServiceManager.getService(Context.WIFI_COND_SERVICE);
+ mWificond = IWificond.Stub.asInterface(binder);
+ if (mWificond == null) {
+ Log.e(TAG, "Failed to get reference to wificond");
+ return false;
+ }
+ try {
+ mWificond.asBinder().linkToDeath(this, 0);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Failed to register death notification for wificond");
+ // The remote has already died.
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Setup interface for client mode via wificond.
+ * @return true on success.
+ */
+ public boolean setupInterfaceForClientMode(@NonNull String ifaceName,
+ @NonNull ScanEventCallback scanCallback, @NonNull ScanEventCallback pnoScanCallback) {
+ Log.d(TAG, "Setting up interface for client mode");
+ if (!retrieveWificondAndRegisterForDeath()) {
+ return false;
+ }
+
+ IClientInterface clientInterface = null;
+ try {
+ clientInterface = mWificond.createClientInterface(ifaceName);
+ } catch (RemoteException e1) {
+ Log.e(TAG, "Failed to get IClientInterface due to remote exception");
+ return false;
+ }
+
+ if (clientInterface == null) {
+ Log.e(TAG, "Could not get IClientInterface instance from wificond");
+ return false;
+ }
+ Binder.allowBlocking(clientInterface.asBinder());
+
+ // Refresh Handlers
+ mClientInterfaces.put(ifaceName, clientInterface);
+ try {
+ IWifiScannerImpl wificondScanner = clientInterface.getWifiScannerImpl();
+ if (wificondScanner == null) {
+ Log.e(TAG, "Failed to get WificondScannerImpl");
+ return false;
+ }
+ mWificondScanners.put(ifaceName, wificondScanner);
+ Binder.allowBlocking(wificondScanner.asBinder());
+ ScanEventHandler scanEventHandler = new ScanEventHandler(scanCallback);
+ mScanEventHandlers.put(ifaceName, scanEventHandler);
+ wificondScanner.subscribeScanEvents(scanEventHandler);
+ PnoScanEventHandler pnoScanEventHandler = new PnoScanEventHandler(pnoScanCallback);
+ mPnoScanEventHandlers.put(ifaceName, pnoScanEventHandler);
+ wificondScanner.subscribePnoScanEvents(pnoScanEventHandler);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Failed to refresh wificond scanner due to remote exception");
+ }
+
+ return true;
+ }
+
+ /**
+ * Teardown a specific STA interface configured in wificond.
+ *
+ * @return Returns true on success.
+ */
+ public boolean tearDownClientInterface(@NonNull String ifaceName) {
+ if (getClientInterface(ifaceName) == null) {
+ Log.e(TAG, "No valid wificond client interface handler");
+ return false;
+ }
+ try {
+ IWifiScannerImpl scannerImpl = mWificondScanners.get(ifaceName);
+ if (scannerImpl != null) {
+ scannerImpl.unsubscribeScanEvents();
+ scannerImpl.unsubscribePnoScanEvents();
+ }
+ } catch (RemoteException e) {
+ Log.e(TAG, "Failed to unsubscribe wificond scanner due to remote exception");
+ return false;
+ }
+
+ if (mWificond == null) {
+ Log.e(TAG, "Reference to wifiCond is null");
+ return false;
+ }
+
+ boolean success;
+ try {
+ success = mWificond.tearDownClientInterface(ifaceName);
+ } catch (RemoteException e1) {
+ Log.e(TAG, "Failed to teardown client interface due to remote exception");
+ return false;
+ }
+ if (!success) {
+ Log.e(TAG, "Failed to teardown client interface");
+ return false;
+ }
+
+ mClientInterfaces.remove(ifaceName);
+ mWificondScanners.remove(ifaceName);
+ mScanEventHandlers.remove(ifaceName);
+ mPnoScanEventHandlers.remove(ifaceName);
+ return true;
+ }
+
+ /**
+ * Setup interface for softAp mode via wificond.
+ * @return true on success.
+ */
+ public boolean setupInterfaceForSoftApMode(@NonNull String ifaceName) {
+ Log.d(TAG, "Setting up interface for soft ap mode");
+ if (!retrieveWificondAndRegisterForDeath()) {
+ return false;
+ }
+
+ IApInterface apInterface = null;
+ try {
+ apInterface = mWificond.createApInterface(ifaceName);
+ } catch (RemoteException e1) {
+ Log.e(TAG, "Failed to get IApInterface due to remote exception");
+ return false;
+ }
+
+ if (apInterface == null) {
+ Log.e(TAG, "Could not get IApInterface instance from wificond");
+ return false;
+ }
+ Binder.allowBlocking(apInterface.asBinder());
+
+ // Refresh Handlers
+ mApInterfaces.put(ifaceName, apInterface);
+ return true;
+ }
+
+ /**
+ * Teardown a specific AP interface configured in wificond.
+ *
+ * @return Returns true on success.
+ */
+ public boolean tearDownSoftApInterface(@NonNull String ifaceName) {
+ if (getApInterface(ifaceName) == null) {
+ Log.e(TAG, "No valid wificond ap interface handler");
+ return false;
+ }
+
+ if (mWificond == null) {
+ Log.e(TAG, "Reference to wifiCond is null");
+ return false;
+ }
+
+ boolean success;
+ try {
+ success = mWificond.tearDownApInterface(ifaceName);
+ } catch (RemoteException e1) {
+ Log.e(TAG, "Failed to teardown AP interface due to remote exception");
+ return false;
+ }
+ if (!success) {
+ Log.e(TAG, "Failed to teardown AP interface");
+ return false;
+ }
+ mApInterfaces.remove(ifaceName);
+ mApInterfaceListeners.remove(ifaceName);
+ return true;
+ }
+
+ /**
+ * Teardown all interfaces configured in wificond.
+ * @return Returns true on success.
+ */
+ public boolean tearDownInterfaces() {
+ Log.d(TAG, "tearing down interfaces in wificond");
+ // Explicitly refresh the wificodn handler because |tearDownInterfaces()|
+ // could be used to cleanup before we setup any interfaces.
+ if (!retrieveWificondAndRegisterForDeath()) {
+ return false;
+ }
+
+ try {
+ for (Map.Entry<String, IWifiScannerImpl> entry : mWificondScanners.entrySet()) {
+ entry.getValue().unsubscribeScanEvents();
+ entry.getValue().unsubscribePnoScanEvents();
+ }
+ mWificond.tearDownInterfaces();
+ clearState();
+ return true;
+ } catch (RemoteException e) {
+ Log.e(TAG, "Failed to tear down interfaces due to remote exception");
+ }
+
+ return false;
+ }
+
+ /** Helper function to look up the interface handle using name */
+ private IClientInterface getClientInterface(@NonNull String ifaceName) {
+ return mClientInterfaces.get(ifaceName);
+ }
+
+ /**
+ * Request signal polling to wificond.
+ * @param ifaceName Name of the interface.
+ * Returns an SignalPollResult object.
+ * Returns null on failure.
+ */
+ public SignalPollResult signalPoll(@NonNull String ifaceName) {
+ IClientInterface iface = getClientInterface(ifaceName);
+ if (iface == null) {
+ Log.e(TAG, "No valid wificond client interface handler");
+ return null;
+ }
+
+ int[] resultArray;
+ try {
+ resultArray = iface.signalPoll();
+ if (resultArray == null || resultArray.length != 4) {
+ Log.e(TAG, "Invalid signal poll result from wificond");
+ return null;
+ }
+ } catch (RemoteException e) {
+ Log.e(TAG, "Failed to do signal polling due to remote exception");
+ return null;
+ }
+ SignalPollResult pollResult = new SignalPollResult();
+ pollResult.currentRssi = resultArray[0];
+ pollResult.txBitrate = resultArray[1];
+ pollResult.associationFrequency = resultArray[2];
+ pollResult.rxBitrate = resultArray[3];
+ return pollResult;
+ }
+
+ /**
+ * Fetch TX packet counters on current connection from wificond.
+ * @param ifaceName Name of the interface.
+ * Returns an TxPacketCounters object.
+ * Returns null on failure.
+ */
+ public TxPacketCounters getTxPacketCounters(@NonNull String ifaceName) {
+ IClientInterface iface = getClientInterface(ifaceName);
+ if (iface == null) {
+ Log.e(TAG, "No valid wificond client interface handler");
+ return null;
+ }
+
+ int[] resultArray;
+ try {
+ resultArray = iface.getPacketCounters();
+ if (resultArray == null || resultArray.length != 2) {
+ Log.e(TAG, "Invalid signal poll result from wificond");
+ return null;
+ }
+ } catch (RemoteException e) {
+ Log.e(TAG, "Failed to do signal polling due to remote exception");
+ return null;
+ }
+ TxPacketCounters counters = new TxPacketCounters();
+ counters.txSucceeded = resultArray[0];
+ counters.txFailed = resultArray[1];
+ return counters;
+ }
+
+ /** Helper function to look up the scanner impl handle using name */
+ private IWifiScannerImpl getScannerImpl(@NonNull String ifaceName) {
+ return mWificondScanners.get(ifaceName);
+ }
+
+ /**
+ * Fetch the latest scan result from kernel via wificond.
+ * @param ifaceName Name of the interface.
+ * @return Returns an array of native scan results or an empty array on failure.
+ */
+ @NonNull public List<NativeScanResult> getScanResults(@NonNull String ifaceName,
+ @ScanResultType int scanType) {
+ IWifiScannerImpl scannerImpl = getScannerImpl(ifaceName);
+ if (scannerImpl == null) {
+ Log.e(TAG, "No valid wificond scanner interface handler");
+ return new ArrayList<>();
+ }
+ List<NativeScanResult> results = null;
+ try {
+ if (scanType == SCAN_TYPE_SINGLE_SCAN) {
+ results = Arrays.asList(scannerImpl.getScanResults());
+ } else {
+ results = Arrays.asList(scannerImpl.getPnoScanResults());
+ }
+ } catch (RemoteException e1) {
+ Log.e(TAG, "Failed to create ScanDetail ArrayList");
+ }
+ if (results == null) {
+ results = new ArrayList<>();
+ }
+ if (mVerboseLoggingEnabled) {
+ Log.d(TAG, "get " + results.size() + " scan results from wificond");
+ }
+
+ return results;
+ }
+
+ /**
+ * Return scan type for the parcelable {@link SingleScanSettings}
+ */
+ private static int getScanType(@WifiAnnotations.ScanType int scanType) {
+ switch (scanType) {
+ case WifiScanner.SCAN_TYPE_LOW_LATENCY:
+ return IWifiScannerImpl.SCAN_TYPE_LOW_SPAN;
+ case WifiScanner.SCAN_TYPE_LOW_POWER:
+ return IWifiScannerImpl.SCAN_TYPE_LOW_POWER;
+ case WifiScanner.SCAN_TYPE_HIGH_ACCURACY:
+ return IWifiScannerImpl.SCAN_TYPE_HIGH_ACCURACY;
+ default:
+ throw new IllegalArgumentException("Invalid scan type " + scanType);
+ }
+ }
+
+ /**
+ * Start a scan using wificond for the given parameters.
+ * @param ifaceName Name of the interface.
+ * @param scanType Type of scan to perform.
+ * @param freqs list of frequencies to scan for, if null scan all supported channels.
+ * @param hiddenNetworkSSIDs List of hidden networks to be scanned for.
+ * @return Returns true on success.
+ */
+ public boolean scan(@NonNull String ifaceName, @WifiAnnotations.ScanType int scanType,
+ Set<Integer> freqs, List<byte[]> hiddenNetworkSSIDs) {
+ IWifiScannerImpl scannerImpl = getScannerImpl(ifaceName);
+ if (scannerImpl == null) {
+ Log.e(TAG, "No valid wificond scanner interface handler");
+ return false;
+ }
+ SingleScanSettings settings = new SingleScanSettings();
+ try {
+ settings.scanType = getScanType(scanType);
+ } catch (IllegalArgumentException e) {
+ Log.e(TAG, "Invalid scan type ", e);
+ return false;
+ }
+ settings.channelSettings = new ArrayList<>();
+ settings.hiddenNetworks = new ArrayList<>();
+
+ if (freqs != null) {
+ for (Integer freq : freqs) {
+ ChannelSettings channel = new ChannelSettings();
+ channel.frequency = freq;
+ settings.channelSettings.add(channel);
+ }
+ }
+ if (hiddenNetworkSSIDs != null) {
+ for (byte[] ssid : hiddenNetworkSSIDs) {
+ HiddenNetwork network = new HiddenNetwork();
+ network.ssid = ssid;
+
+ // settings.hiddenNetworks is expected to be very small, so this shouldn't cause
+ // any performance issues.
+ if (!settings.hiddenNetworks.contains(network)) {
+ settings.hiddenNetworks.add(network);
+ }
+ }
+ }
+
+ try {
+ return scannerImpl.scan(settings);
+ } catch (RemoteException e1) {
+ Log.e(TAG, "Failed to request scan due to remote exception");
+ }
+ return false;
+ }
+
+ /**
+ * Start PNO scan.
+ * @param ifaceName Name of the interface.
+ * @param pnoSettings Pno scan configuration.
+ * @return true on success.
+ */
+ public boolean startPnoScan(@NonNull String ifaceName, PnoSettings pnoSettings,
+ PnoScanRequestCallback callback) {
+ IWifiScannerImpl scannerImpl = getScannerImpl(ifaceName);
+ if (scannerImpl == null) {
+ Log.e(TAG, "No valid wificond scanner interface handler");
+ return false;
+ }
+
+ try {
+ boolean success = scannerImpl.startPnoScan(pnoSettings);
+ if (success) {
+ callback.onPnoRequestSucceeded();
+ } else {
+ callback.onPnoRequestFailed();
+ }
+ return success;
+ } catch (RemoteException e1) {
+ Log.e(TAG, "Failed to start pno scan due to remote exception");
+ }
+ return false;
+ }
+
+ /**
+ * Stop PNO scan.
+ * @param ifaceName Name of the interface.
+ * @return true on success.
+ */
+ public boolean stopPnoScan(@NonNull String ifaceName) {
+ IWifiScannerImpl scannerImpl = getScannerImpl(ifaceName);
+ if (scannerImpl == null) {
+ Log.e(TAG, "No valid wificond scanner interface handler");
+ return false;
+ }
+ try {
+ return scannerImpl.stopPnoScan();
+ } catch (RemoteException e1) {
+ Log.e(TAG, "Failed to stop pno scan due to remote exception");
+ }
+ return false;
+ }
+
+ /**
+ * Abort ongoing single scan.
+ * @param ifaceName Name of the interface.
+ */
+ public void abortScan(@NonNull String ifaceName) {
+ IWifiScannerImpl scannerImpl = getScannerImpl(ifaceName);
+ if (scannerImpl == null) {
+ Log.e(TAG, "No valid wificond scanner interface handler");
+ return;
+ }
+ try {
+ scannerImpl.abortScan();
+ } catch (RemoteException e1) {
+ Log.e(TAG, "Failed to request abortScan due to remote exception");
+ }
+ }
+
+ /**
+ * Query the list of valid frequencies for the provided band.
+ * The result depends on the on the country code that has been set.
+ *
+ * @param band as specified by one of the WifiScanner.WIFI_BAND_* constants.
+ * The following bands are supported {@link @WifiScanner.WifiBandBasic}:
+ * WifiScanner.WIFI_BAND_24_GHZ
+ * WifiScanner.WIFI_BAND_5_GHZ
+ * WifiScanner.WIFI_BAND_5_GHZ_DFS_ONLY
+ * WifiScanner.WIFI_BAND_6_GHZ
+ * @return frequencies vector of valid frequencies (MHz), or null for error.
+ * @throws IllegalArgumentException if band is not recognized.
+ */
+ public int [] getChannelsForBand(@WifiAnnotations.WifiBandBasic int band) {
+ if (mWificond == null) {
+ Log.e(TAG, "No valid wificond scanner interface handler");
+ return null;
+ }
+ try {
+ switch (band) {
+ case WifiScanner.WIFI_BAND_24_GHZ:
+ return mWificond.getAvailable2gChannels();
+ case WifiScanner.WIFI_BAND_5_GHZ:
+ return mWificond.getAvailable5gNonDFSChannels();
+ case WifiScanner.WIFI_BAND_5_GHZ_DFS_ONLY:
+ return mWificond.getAvailableDFSChannels();
+ case WifiScanner.WIFI_BAND_6_GHZ:
+ return mWificond.getAvailable6gChannels();
+ default:
+ throw new IllegalArgumentException("unsupported band " + band);
+ }
+ } catch (RemoteException e1) {
+ Log.e(TAG, "Failed to request getChannelsForBand due to remote exception");
+ }
+ return null;
+ }
+
+ /** Helper function to look up the interface handle using name */
+ private IApInterface getApInterface(@NonNull String ifaceName) {
+ return mApInterfaces.get(ifaceName);
+ }
+
+ /**
+ * Register the provided listener for SoftAp events.
+ *
+ * @param ifaceName Name of the interface.
+ * @param listener Callback for AP events.
+ * @return true on success, false otherwise.
+ */
+ public boolean registerApListener(@NonNull String ifaceName, SoftApListener listener) {
+ IApInterface iface = getApInterface(ifaceName);
+ if (iface == null) {
+ Log.e(TAG, "No valid ap interface handler");
+ return false;
+ }
+ try {
+ IApInterfaceEventCallback callback = new ApInterfaceEventCallback(listener);
+ mApInterfaceListeners.put(ifaceName, callback);
+ boolean success = iface.registerCallback(callback);
+ if (!success) {
+ Log.e(TAG, "Failed to register ap callback.");
+ return false;
+ }
+ } catch (RemoteException e) {
+ Log.e(TAG, "Exception in registering AP callback: " + e);
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * See {@link #sendMgmtFrame(String, byte[], SendMgmtFrameCallback, int)}
+ */
+ public void sendMgmtFrame(@NonNull String ifaceName, @NonNull byte[] frame,
+ @NonNull SendMgmtFrameCallback callback, int mcs) {
+
+ if (callback == null) {
+ Log.e(TAG, "callback cannot be null!");
+ return;
+ }
+
+ if (frame == null) {
+ Log.e(TAG, "frame cannot be null!");
+ callback.onFailure(SEND_MGMT_FRAME_ERROR_UNKNOWN);
+ return;
+ }
+
+ // TODO (b/112029045) validate mcs
+ IClientInterface clientInterface = getClientInterface(ifaceName);
+ if (clientInterface == null) {
+ Log.e(TAG, "No valid wificond client interface handler");
+ callback.onFailure(SEND_MGMT_FRAME_ERROR_UNKNOWN);
+ return;
+ }
+
+ if (!mSendMgmtFrameInProgress.compareAndSet(false, true)) {
+ Log.e(TAG, "An existing management frame transmission is in progress!");
+ callback.onFailure(SEND_MGMT_FRAME_ERROR_ALREADY_STARTED);
+ return;
+ }
+
+ SendMgmtFrameEvent sendMgmtFrameEvent = new SendMgmtFrameEvent(callback);
+ try {
+ clientInterface.SendMgmtFrame(frame, sendMgmtFrameEvent, mcs);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Exception while starting link probe: " + e);
+ // Call sendMgmtFrameEvent.OnFailure() instead of callback.onFailure() so that
+ // sendMgmtFrameEvent can clean up internal state, such as cancelling the timer.
+ sendMgmtFrameEvent.OnFailure(SEND_MGMT_FRAME_ERROR_UNKNOWN);
+ }
+ }
+
+ /**
+ * Clear all internal handles.
+ */
+ private void clearState() {
+ // Refresh handlers
+ mClientInterfaces.clear();
+ mWificondScanners.clear();
+ mPnoScanEventHandlers.clear();
+ mScanEventHandlers.clear();
+ mApInterfaces.clear();
+ mApInterfaceListeners.clear();
+ mSendMgmtFrameInProgress.set(false);
+ }
+}
diff --git a/wifi/java/android/net/wifi/WifiConfiguration.java b/wifi/java/android/net/wifi/WifiConfiguration.java
index d068fc681ae7..e3a945de7526 100644
--- a/wifi/java/android/net/wifi/WifiConfiguration.java
+++ b/wifi/java/android/net/wifi/WifiConfiguration.java
@@ -36,14 +36,9 @@ import android.os.SystemClock;
import android.os.UserHandle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
-import android.util.BackupUtils;
import android.util.Log;
import android.util.SparseArray;
-import java.io.ByteArrayOutputStream;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
@@ -123,7 +118,9 @@ public class WifiConfiguration implements Parcelable {
OWE,
SUITE_B_192,
WPA_PSK_SHA256,
- WPA_EAP_SHA256})
+ WPA_EAP_SHA256,
+ WAPI_PSK,
+ WAPI_CERT})
public @interface KeyMgmtScheme {}
/** WPA is not used; plaintext or static WEP could be used. */
@@ -190,11 +187,26 @@ public class WifiConfiguration implements Parcelable {
*/
public static final int WPA_EAP_SHA256 = 12;
+ /**
+ * WAPI pre-shared key (requires {@code preSharedKey} to be specified).
+ * @hide
+ */
+ @SystemApi
+ public static final int WAPI_PSK = 13;
+
+ /**
+ * WAPI certificate to be specified.
+ * @hide
+ */
+ @SystemApi
+ public static final int WAPI_CERT = 14;
+
public static final String varName = "key_mgmt";
public static final String[] strings = { "NONE", "WPA_PSK", "WPA_EAP",
"IEEE8021X", "WPA2_PSK", "OSEN", "FT_PSK", "FT_EAP",
- "SAE", "OWE", "SUITE_B_192", "WPA_PSK_SHA256", "WPA_EAP_SHA256" };
+ "SAE", "OWE", "SUITE_B_192", "WPA_PSK_SHA256", "WPA_EAP_SHA256",
+ "WAPI_PSK", "WAPI_CERT" };
}
/**
@@ -215,9 +227,14 @@ public class WifiConfiguration implements Parcelable {
*/
public static final int OSEN = 2;
+ /**
+ * WAPI Protocol
+ */
+ public static final int WAPI = 3;
+
public static final String varName = "proto";
- public static final String[] strings = { "WPA", "RSN", "OSEN" };
+ public static final String[] strings = { "WPA", "RSN", "OSEN", "WAPI" };
}
/**
@@ -260,10 +277,14 @@ public class WifiConfiguration implements Parcelable {
* AES in Galois/Counter Mode
*/
public static final int GCMP_256 = 3;
+ /**
+ * SMS4 cipher for WAPI
+ */
+ public static final int SMS4 = 4;
public static final String varName = "pairwise";
- public static final String[] strings = { "NONE", "TKIP", "CCMP", "GCMP_256" };
+ public static final String[] strings = { "NONE", "TKIP", "CCMP", "GCMP_256", "SMS4" };
}
/**
@@ -301,12 +322,17 @@ public class WifiConfiguration implements Parcelable {
* AES in Galois/Counter Mode
*/
public static final int GCMP_256 = 5;
+ /**
+ * SMS4 cipher for WAPI
+ */
+ public static final int SMS4 = 6;
public static final String varName = "group";
public static final String[] strings =
{ /* deprecated */ "WEP40", /* deprecated */ "WEP104",
- "TKIP", "CCMP", "GTK_NOT_USED", "GCMP_256" };
+ "TKIP", "CCMP", "GTK_NOT_USED", "GCMP_256",
+ "SMS4" };
}
/**
@@ -388,6 +414,10 @@ public class WifiConfiguration implements Parcelable {
public static final int SECURITY_TYPE_EAP_SUITE_B = 5;
/** @hide */
public static final int SECURITY_TYPE_OWE = 6;
+ /** @hide */
+ public static final int SECURITY_TYPE_WAPI_PSK = 7;
+ /** @hide */
+ public static final int SECURITY_TYPE_WAPI_CERT = 8;
/** @hide */
@Retention(RetentionPolicy.SOURCE)
@@ -398,7 +428,9 @@ public class WifiConfiguration implements Parcelable {
SECURITY_TYPE_EAP,
SECURITY_TYPE_SAE,
SECURITY_TYPE_EAP_SUITE_B,
- SECURITY_TYPE_OWE
+ SECURITY_TYPE_OWE,
+ SECURITY_TYPE_WAPI_PSK,
+ SECURITY_TYPE_WAPI_CERT
})
public @interface SecurityType {}
@@ -450,6 +482,18 @@ public class WifiConfiguration implements Parcelable {
allowedKeyManagement.set(WifiConfiguration.KeyMgmt.OWE);
requirePMF = true;
break;
+ case SECURITY_TYPE_WAPI_PSK:
+ allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WAPI_PSK);
+ allowedProtocols.set(WifiConfiguration.Protocol.WAPI);
+ allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.SMS4);
+ allowedGroupCiphers.set(WifiConfiguration.GroupCipher.SMS4);
+ break;
+ case SECURITY_TYPE_WAPI_CERT:
+ allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WAPI_CERT);
+ allowedProtocols.set(WifiConfiguration.Protocol.WAPI);
+ allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.SMS4);
+ allowedGroupCiphers.set(WifiConfiguration.GroupCipher.SMS4);
+ break;
default:
throw new IllegalArgumentException("unknown security type " + securityType);
}
@@ -2350,6 +2394,10 @@ public class WifiConfiguration implements Parcelable {
return KeyMgmt.OWE;
} else if (allowedKeyManagement.get(KeyMgmt.SUITE_B_192)) {
return KeyMgmt.SUITE_B_192;
+ } else if (allowedKeyManagement.get(KeyMgmt.WAPI_PSK)) {
+ return KeyMgmt.WAPI_PSK;
+ } else if (allowedKeyManagement.get(KeyMgmt.WAPI_CERT)) {
+ return KeyMgmt.WAPI_CERT;
}
return KeyMgmt.NONE;
}
@@ -2388,6 +2436,10 @@ public class WifiConfiguration implements Parcelable {
key = SSID + KeyMgmt.strings[KeyMgmt.SAE];
} else if (allowedKeyManagement.get(KeyMgmt.SUITE_B_192)) {
key = SSID + KeyMgmt.strings[KeyMgmt.SUITE_B_192];
+ } else if (allowedKeyManagement.get(KeyMgmt.WAPI_PSK)) {
+ key = SSID + KeyMgmt.strings[KeyMgmt.WAPI_PSK];
+ } else if (allowedKeyManagement.get(KeyMgmt.WAPI_CERT)) {
+ key = SSID + KeyMgmt.strings[KeyMgmt.WAPI_CERT];
} else {
key = SSID + KeyMgmt.strings[KeyMgmt.NONE];
}
@@ -2768,54 +2820,4 @@ public class WifiConfiguration implements Parcelable {
return new WifiConfiguration[size];
}
};
-
- /**
- * Serialize the Soft AP configuration contained in this object for backup.
- * @hide
- */
- @NonNull
- // TODO(b/144368124): this method should be removed once we migrate to SoftApConfiguration
- public byte[] getBytesForBackup() throws IOException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- DataOutputStream out = new DataOutputStream(baos);
-
- out.writeInt(BACKUP_VERSION);
- BackupUtils.writeString(out, SSID);
- out.writeInt(apBand);
- out.writeInt(apChannel);
- BackupUtils.writeString(out, preSharedKey);
- out.writeInt(getAuthType());
- out.writeBoolean(hiddenSSID);
- return baos.toByteArray();
- }
-
- /**
- * Deserialize a byte array containing Soft AP configuration into a WifiConfiguration object.
- * @return The deserialized WifiConfiguration containing Soft AP configuration, or null if
- * the version contains a bad dataset e.g. Version 1
- * @throws BackupUtils.BadVersionException if the version is unrecognized
- * @hide
- */
- @Nullable
- // TODO(b/144368124): this method should be removed once we migrate to SoftApConfiguration
- public static WifiConfiguration getWifiConfigFromBackup(@NonNull DataInputStream in)
- throws IOException, BackupUtils.BadVersionException {
- WifiConfiguration config = new WifiConfiguration();
- int version = in.readInt();
- if (version < 1 || version > BACKUP_VERSION) {
- throw new BackupUtils.BadVersionException("Unknown Backup Serialization Version");
- }
-
- if (version == 1) return null; // Version 1 is a bad dataset.
-
- config.SSID = BackupUtils.readString(in);
- config.apBand = in.readInt();
- config.apChannel = in.readInt();
- config.preSharedKey = BackupUtils.readString(in);
- config.allowedKeyManagement.set(in.readInt());
- if (version >= 3) {
- config.hiddenSSID = in.readBoolean();
- }
- return config;
- }
}
diff --git a/wifi/java/android/net/wifi/WifiEnterpriseConfig.java b/wifi/java/android/net/wifi/WifiEnterpriseConfig.java
index 449f95e8a161..7a59a4f9be30 100644
--- a/wifi/java/android/net/wifi/WifiEnterpriseConfig.java
+++ b/wifi/java/android/net/wifi/WifiEnterpriseConfig.java
@@ -22,7 +22,6 @@ import android.annotation.SystemApi;
import android.annotation.UnsupportedAppUsage;
import android.os.Parcel;
import android.os.Parcelable;
-import android.security.Credentials;
import android.text.TextUtils;
import android.util.Log;
@@ -42,6 +41,36 @@ import java.util.Map;
*/
public class WifiEnterpriseConfig implements Parcelable {
+ /** Key prefix for WAPI AS certificates. */
+ public static final String WAPI_AS_CERTIFICATE = "WAPIAS_";
+
+ /** Key prefix for WAPI user certificates. */
+ public static final String WAPI_USER_CERTIFICATE = "WAPIUSR_";
+
+ /**
+ * Intent extra: name for WAPI AS certificates
+ */
+ public static final String EXTRA_WAPI_AS_CERTIFICATE_NAME =
+ "android.net.wifi.extra.WAPI_AS_CERTIFICATE_NAME";
+
+ /**
+ * Intent extra: data for WAPI AS certificates
+ */
+ public static final String EXTRA_WAPI_AS_CERTIFICATE_DATA =
+ "android.net.wifi.extra.WAPI_AS_CERTIFICATE_DATA";
+
+ /**
+ * Intent extra: name for WAPI AS certificates
+ */
+ public static final String EXTRA_WAPI_USER_CERTIFICATE_NAME =
+ "android.net.wifi.extra.WAPI_USER_CERTIFICATE_NAME";
+
+ /**
+ * Intent extra: data for WAPI AS certificates
+ */
+ public static final String EXTRA_WAPI_USER_CERTIFICATE_DATA =
+ "android.net.wifi.extra.WAPI_USER_CERTIFICATE_DATA";
+
/** @hide */
public static final String EMPTY_VALUE = "NULL";
/** @hide */
@@ -62,6 +91,7 @@ public class WifiEnterpriseConfig implements Parcelable {
public static final String DOM_SUFFIX_MATCH_KEY = "domain_suffix_match";
/** @hide */
public static final String OPP_KEY_CACHING = "proactive_key_caching";
+
/**
* String representing the keystore OpenSSL ENGINE's ID.
* @hide
@@ -93,10 +123,26 @@ public class WifiEnterpriseConfig implements Parcelable {
*/
public static final String ENGINE_DISABLE = "0";
+ /**
+ * Key prefix for CA certificates.
+ * Note: copied from {@link android.security.Credentials#CA_CERTIFICATE} since it is @hide.
+ */
+ private static final String CA_CERTIFICATE = "CACERT_";
+ /**
+ * Key prefix for user certificates.
+ * Note: copied from {@link android.security.Credentials#USER_CERTIFICATE} since it is @hide.
+ */
+ private static final String USER_CERTIFICATE = "USRCERT_";
+ /**
+ * Key prefix for user private and secret keys.
+ * Note: copied from {@link android.security.Credentials#USER_PRIVATE_KEY} since it is @hide.
+ */
+ private static final String USER_PRIVATE_KEY = "USRPKEY_";
+
/** @hide */
- public static final String CA_CERT_PREFIX = KEYSTORE_URI + Credentials.CA_CERTIFICATE;
+ public static final String CA_CERT_PREFIX = KEYSTORE_URI + CA_CERTIFICATE;
/** @hide */
- public static final String CLIENT_CERT_PREFIX = KEYSTORE_URI + Credentials.USER_CERTIFICATE;
+ public static final String CLIENT_CERT_PREFIX = KEYSTORE_URI + USER_CERTIFICATE;
/** @hide */
public static final String CLIENT_CERT_KEY = "client_cert";
/** @hide */
@@ -115,6 +161,8 @@ public class WifiEnterpriseConfig implements Parcelable {
public static final String PLMN_KEY = "plmn";
/** @hide */
public static final String CA_CERT_ALIAS_DELIMITER = " ";
+ /** @hide */
+ public static final String WAPI_CERT_SUITE_KEY = "wapi_cert_suite";
/**
* Do not use OCSP stapling (TLS certificate status extension)
@@ -333,9 +381,12 @@ public class WifiEnterpriseConfig implements Parcelable {
public static final int AKA_PRIME = 6;
/** Hotspot 2.0 r2 OSEN */
public static final int UNAUTH_TLS = 7;
+ /** WAPI Certificate */
+ public static final int WAPI_CERT = 8;
/** @hide */
public static final String[] strings =
- { "PEAP", "TLS", "TTLS", "PWD", "SIM", "AKA", "AKA'", "WFA-UNAUTH-TLS" };
+ { "PEAP", "TLS", "TTLS", "PWD", "SIM", "AKA", "AKA'", "WFA-UNAUTH-TLS",
+ "WAPI_CERT" };
/** Prevent initialization */
private Eap() {}
@@ -479,6 +530,10 @@ public class WifiEnterpriseConfig implements Parcelable {
public void setEapMethod(int eapMethod) {
switch (eapMethod) {
/** Valid methods */
+ case Eap.WAPI_CERT:
+ mEapMethod = eapMethod;
+ setPhase2Method(Phase2.NONE);
+ break;
case Eap.TLS:
case Eap.UNAUTH_TLS:
setPhase2Method(Phase2.NONE);
@@ -659,7 +714,7 @@ public class WifiEnterpriseConfig implements Parcelable {
if (i > 0) {
sb.append(CA_CERT_ALIAS_DELIMITER);
}
- sb.append(encodeCaCertificateAlias(Credentials.CA_CERTIFICATE + aliases[i]));
+ sb.append(encodeCaCertificateAlias(CA_CERTIFICATE + aliases[i]));
}
setFieldValue(CA_CERT_KEY, sb.toString(), KEYSTORES_URI);
}
@@ -693,8 +748,8 @@ public class WifiEnterpriseConfig implements Parcelable {
String[] aliases = TextUtils.split(values, CA_CERT_ALIAS_DELIMITER);
for (int i = 0; i < aliases.length; i++) {
aliases[i] = decodeCaCertificateAlias(aliases[i]);
- if (aliases[i].startsWith(Credentials.CA_CERTIFICATE)) {
- aliases[i] = aliases[i].substring(Credentials.CA_CERTIFICATE.length());
+ if (aliases[i].startsWith(CA_CERTIFICATE)) {
+ aliases[i] = aliases[i].substring(CA_CERTIFICATE.length());
}
}
return aliases.length != 0 ? aliases : null;
@@ -832,7 +887,7 @@ public class WifiEnterpriseConfig implements Parcelable {
@SystemApi
public void setClientCertificateAlias(@Nullable String alias) {
setFieldValue(CLIENT_CERT_KEY, alias, CLIENT_CERT_PREFIX);
- setFieldValue(PRIVATE_KEY_ID_KEY, alias, Credentials.USER_PRIVATE_KEY);
+ setFieldValue(PRIVATE_KEY_ID_KEY, alias, USER_PRIVATE_KEY);
// Also, set engine parameters
if (TextUtils.isEmpty(alias)) {
setFieldValue(ENGINE_KEY, ENGINE_DISABLE);
@@ -1298,4 +1353,29 @@ public class WifiEnterpriseConfig implements Parcelable {
}
return false;
}
+
+ /**
+ * Set the WAPI certificate suite name on wpa_supplicant.
+ *
+ * If this field is not specified, WAPI-CERT uses ASU ID from WAI packet
+ * as the certificate suite name automatically.
+ *
+ * @param wapiCertSuite The name for WAPI certificate suite, or null/empty string to clear.
+ * @hide
+ */
+ @SystemApi
+ public void setWapiCertSuite(@Nullable String wapiCertSuite) {
+ setFieldValue(WAPI_CERT_SUITE_KEY, wapiCertSuite);
+ }
+
+ /**
+ * Get the WAPI certificate suite name
+ * @return the certificate suite name
+ * @hide
+ */
+ @Nullable
+ @SystemApi
+ public String getWapiCertSuite() {
+ return getFieldValue(WAPI_CERT_SUITE_KEY);
+ }
}
diff --git a/wifi/java/android/net/wifi/WifiManager.java b/wifi/java/android/net/wifi/WifiManager.java
index 86c398b770b7..b98d64dc78f1 100644
--- a/wifi/java/android/net/wifi/WifiManager.java
+++ b/wifi/java/android/net/wifi/WifiManager.java
@@ -51,16 +51,16 @@ import android.os.RemoteException;
import android.os.WorkSource;
import android.os.connectivity.WifiActivityEnergyInfo;
import android.text.TextUtils;
+import android.util.CloseGuard;
import android.util.Log;
import android.util.Pair;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
-import dalvik.system.CloseGuard;
-
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
+import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.net.InetAddress;
import java.util.ArrayList;
@@ -1069,7 +1069,7 @@ public class WifiManager {
* @deprecated This API is non-functional and will have no impact.
*/
@Deprecated
- public static final int WIFI_MODE_FULL = WifiProtoEnums.WIFI_MODE_FULL; // 1
+ public static final int WIFI_MODE_FULL = 1;
/**
* In this Wi-Fi lock mode, Wi-Fi will be kept active,
@@ -1083,7 +1083,7 @@ public class WifiManager {
* @deprecated This API is non-functional and will have no impact.
*/
@Deprecated
- public static final int WIFI_MODE_SCAN_ONLY = WifiProtoEnums.WIFI_MODE_SCAN_ONLY; // 2
+ public static final int WIFI_MODE_SCAN_ONLY = 2;
/**
* In this Wi-Fi lock mode, Wi-Fi will not go to power save.
@@ -1102,7 +1102,7 @@ public class WifiManager {
* When there is no support from the hardware, the {@link #WIFI_MODE_FULL_HIGH_PERF}
* lock will have no impact.
*/
- public static final int WIFI_MODE_FULL_HIGH_PERF = WifiProtoEnums.WIFI_MODE_FULL_HIGH_PERF; // 3
+ public static final int WIFI_MODE_FULL_HIGH_PERF = 3;
/**
* In this Wi-Fi lock mode, Wi-Fi will operate with a priority to achieve low latency.
@@ -1132,8 +1132,8 @@ public class WifiManager {
* lock will be effective when app is running in foreground and screen is on,
* while the {@link #WIFI_MODE_FULL_HIGH_PERF} lock will take effect otherwise.
*/
- public static final int WIFI_MODE_FULL_LOW_LATENCY =
- WifiProtoEnums.WIFI_MODE_FULL_LOW_LATENCY; // 4
+ public static final int WIFI_MODE_FULL_LOW_LATENCY = 4;
+
/** Anything worse than or equal to this will show 0 bars. */
@UnsupportedAppUsage
@@ -1153,6 +1153,7 @@ public class WifiManager {
@UnsupportedAppUsage
public static final int RSSI_LEVELS = 5;
+ //TODO (b/146346676): This needs to be removed, not used in the code.
/**
* Auto settings in the driver. The driver could choose to operate on both
* 2.4 GHz and 5 GHz or make a dynamic decision on selecting the band.
@@ -2156,8 +2157,6 @@ public class WifiManager {
/** @hide */
public static final long WIFI_FEATURE_INFRA = 0x0001L; // Basic infrastructure mode
/** @hide */
- public static final long WIFI_FEATURE_INFRA_5G = 0x0002L; // Support for 5 GHz Band
- /** @hide */
public static final long WIFI_FEATURE_PASSPOINT = 0x0004L; // Support for GAS/ANQP
/** @hide */
public static final long WIFI_FEATURE_P2P = 0x0008L; // Wifi-Direct
@@ -2228,7 +2227,7 @@ public class WifiManager {
/** @hide */
public static final long WIFI_FEATURE_OCE = 0x1000000000L; // OCE Support
/** @hide */
- public static final long WIFI_FEATURE_INFRA_6G = 0x2000000000L; // Support 6 GHz band
+ public static final long WIFI_FEATURE_WAPI = 0x2000000000L; // WAPI
private long getSupportedFeatures() {
try {
@@ -2242,22 +2241,7 @@ public class WifiManager {
return (getSupportedFeatures() & feature) == feature;
}
- /**
- * @return true if this adapter supports 5 GHz band
- */
- public boolean is5GHzBandSupported() {
- return isFeatureSupported(WIFI_FEATURE_INFRA_5G);
- }
-
- /**
- * @return true if the device supports operating in the 6 GHz band and Wi-Fi is enabled,
- * false otherwise.
- */
- public boolean is6GHzBandSupported() {
- return isFeatureSupported(WIFI_FEATURE_INFRA_6G);
- }
-
- /**
+ /**
* @return true if this adapter supports Passpoint
* @hide
*/
@@ -2379,6 +2363,30 @@ public class WifiManager {
}
/**
+ * Check if the chipset supports 5GHz band.
+ * @return {@code true} if supported, {@code false} otherwise.
+ */
+ public boolean is5GHzBandSupported() {
+ try {
+ return mService.is5GHzBandSupported();
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Check if the chipset supports 6GHz band.
+ * @return {@code true} if supported, {@code false} otherwise.
+ */
+ public boolean is6GHzBandSupported() {
+ try {
+ return mService.is6GHzBandSupported();
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
* Interface for Wi-Fi activity energy info listener. Should be implemented by applications and
* set when calling {@link WifiManager#getWifiActivityEnergyInfoAsync}.
*
@@ -2592,28 +2600,13 @@ public class WifiManager {
}
/**
- * Check if the chipset supports dual frequency band (2.4 GHz and 5 GHz).
- * No permissions are required to call this method.
- * @return {@code true} if supported, {@code false} otherwise.
- * @hide
- */
- @SystemApi
- public boolean isDualBandSupported() {
- try {
- return mService.isDualBandSupported();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
* Check if the device is dual mode capable i.e. supports concurrent STA + Soft AP.
*
* If the device is dual mode capable, it may require conversion of the user's Soft AP band
- * selection {@link WifiConfiguration#apBand} from {@link WifiConfiguration#AP_BAND_5GHZ} to
- * {@link WifiConfiguration#AP_BAND_ANY}, since if the device is connected to a 5GHz DFS
- * channel as a STA, it may be unable to honor a request to start Soft AP on the same DFS
- * channel.
+ * selection {@link SoftApConfiguration#mBand} from {@link SoftApConfiguration#BAND_5GHZ} to
+ * include also {@link SoftApConfiguration#BAND_2GHZ}, since if the device is connected to a
+ * 5GHz DFS channel as a STA, it may be unable to honor a request to start Soft AP on the same
+ * DFS channel.
*
* @return {@code true} if dual mode STA + AP is supported by this device, {@code false}
* otherwise.
@@ -3574,7 +3567,7 @@ public class WifiManager {
*/
public class LocalOnlyHotspotReservation implements AutoCloseable {
- private final CloseGuard mCloseGuard = CloseGuard.get();
+ private final CloseGuard mCloseGuard = new CloseGuard();
private final WifiConfiguration mConfig;
private boolean mClosed = false;
@@ -3601,6 +3594,8 @@ public class WifiManager {
}
} catch (Exception e) {
Log.e(TAG, "Failed to stop Local Only Hotspot.");
+ } finally {
+ Reference.reachabilityFence(this);
}
}
@@ -3725,7 +3720,7 @@ public class WifiManager {
* @hide
*/
public class LocalOnlyHotspotSubscription implements AutoCloseable {
- private final CloseGuard mCloseGuard = CloseGuard.get();
+ private final CloseGuard mCloseGuard = new CloseGuard();
/** @hide */
@VisibleForTesting
@@ -3740,6 +3735,8 @@ public class WifiManager {
mCloseGuard.close();
} catch (Exception e) {
Log.e(TAG, "Failed to unregister LocalOnlyHotspotObserver.");
+ } finally {
+ Reference.reachabilityFence(this);
}
}
@@ -4686,10 +4683,13 @@ public class WifiManager {
}
/**
- * Retrieve the soft ap config data to be backed to save current config data.
+ * Returns a byte stream representing the data that needs to be backed up to save the
+ * current soft ap config data.
+ *
+ * This soft ap config can be restored by calling {@link #restoreSoftApBackupData(byte[])}
* @hide
*/
- @Nullable
+ @NonNull
@SystemApi
@RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
public byte[] retrieveSoftApBackupData() {
@@ -4701,15 +4701,17 @@ public class WifiManager {
}
/**
- * Restore soft ap config from the backed up data.
+ * Returns soft ap config from the backed up data.
+ * @param data byte stream in the same format produced by {@link #retrieveSoftApBackupData()}
+ *
* @hide
*/
@Nullable
@SystemApi
@RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void restoreSoftApBackupData(@NonNull byte[] data) {
+ public SoftApConfiguration restoreSoftApBackupData(@NonNull byte[] data) {
try {
- mService.restoreSoftApBackupData(data);
+ return mService.restoreSoftApBackupData(data);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -4962,6 +4964,13 @@ public class WifiManager {
}
/**
+ * @return true if this device supports WAPI.
+ */
+ public boolean isWapiSupported() {
+ return isFeatureSupported(WIFI_FEATURE_WAPI);
+ }
+
+ /**
* Gets the factory Wi-Fi MAC addresses.
* @return Array of String representing Wi-Fi MAC addresses sorted lexically or an empty Array
* if failed.
diff --git a/wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java b/wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java
index 24aa23aec7ae..04d2e1a8b5dd 100644
--- a/wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java
+++ b/wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java
@@ -23,7 +23,6 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.net.MacAddress;
import android.net.MatchAllNetworkSpecifier;
-import android.net.NetworkAgent;
import android.net.NetworkRequest;
import android.net.NetworkSpecifier;
import android.os.Parcel;
@@ -120,7 +119,7 @@ public final class WifiNetworkAgentSpecifier extends NetworkSpecifier implements
/**
* Match {@link WifiNetworkSpecifier} in app's {@link NetworkRequest} with the
- * {@link WifiNetworkAgentSpecifier} in wifi platform's {@link NetworkAgent}.
+ * {@link WifiNetworkAgentSpecifier} in wifi platform's {@link android.net.NetworkAgent}.
*/
public boolean satisfiesNetworkSpecifier(@NonNull WifiNetworkSpecifier ns) {
// None of these should be null by construction.
diff --git a/wifi/java/android/net/wifi/WifiNetworkSuggestion.java b/wifi/java/android/net/wifi/WifiNetworkSuggestion.java
index 9fd29ae8d14a..9c1475ffc8cd 100644
--- a/wifi/java/android/net/wifi/WifiNetworkSuggestion.java
+++ b/wifi/java/android/net/wifi/WifiNetworkSuggestion.java
@@ -122,6 +122,16 @@ public final class WifiNetworkSuggestion implements Parcelable {
* Whether the setIsUserAllowedToManuallyConnect have been called.
*/
private boolean mIsUserAllowedBeenSet;
+ /**
+ * Pre-shared key for use with WAPI-PSK networks.
+ */
+ private @Nullable String mWapiPskPassphrase;
+
+ /**
+ * The enterprise configuration details specifying the EAP method,
+ * certificates and other settings associated with the WAPI networks.
+ */
+ private @Nullable WifiEnterpriseConfig mWapiEnterpriseConfig;
public Builder() {
mSsid = null;
@@ -140,6 +150,8 @@ public final class WifiNetworkSuggestion implements Parcelable {
mIsUserAllowedBeenSet = false;
mPriority = UNASSIGNED_PRIORITY;
mCarrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
+ mWapiPskPassphrase = null;
+ mWapiEnterpriseConfig = null;
}
/**
@@ -294,6 +306,39 @@ public final class WifiNetworkSuggestion implements Parcelable {
}
/**
+ * Set the ASCII WAPI passphrase for this network. Needed for authenticating to
+ * WAPI-PSK networks.
+ *
+ * @param passphrase passphrase of the network.
+ * @return Instance of {@link Builder} to enable chaining of the builder method.
+ * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
+ *
+ */
+ public @NonNull Builder setWapiPassphrase(@NonNull String passphrase) {
+ checkNotNull(passphrase);
+ final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
+ if (!asciiEncoder.canEncode(passphrase)) {
+ throw new IllegalArgumentException("passphrase not ASCII encodable");
+ }
+ mWapiPskPassphrase = passphrase;
+ return this;
+ }
+
+ /**
+ * Set the associated enterprise configuration for this network. Needed for authenticating
+ * to WAPI-CERT networks. See {@link WifiEnterpriseConfig} for description.
+ *
+ * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
+ * @return Instance of {@link Builder} to enable chaining of the builder method.
+ */
+ public @NonNull Builder setWapiEnterpriseConfig(
+ @NonNull WifiEnterpriseConfig enterpriseConfig) {
+ checkNotNull(enterpriseConfig);
+ mWapiEnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
+ return this;
+ }
+
+ /**
* Specifies whether this represents a hidden network.
* <p>
* <li>If not set, defaults to false (i.e not a hidden network).</li>
@@ -413,6 +458,13 @@ public final class WifiNetworkSuggestion implements Parcelable {
configuration.enterpriseConfig = mWpa3EnterpriseConfig;
} else if (mIsEnhancedOpen) { // OWE network
configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_OWE);
+ } else if (!TextUtils.isEmpty(mWapiPskPassphrase)) { // WAPI-PSK network.
+ configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_WAPI_PSK);
+ // WifiConfiguration.preSharedKey needs quotes around ASCII password.
+ configuration.preSharedKey = "\"" + mWapiPskPassphrase + "\"";
+ } else if (mWapiEnterpriseConfig != null) { // WAPI-CERT network
+ configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_WAPI_CERT);
+ configuration.enterpriseConfig = mWapiEnterpriseConfig;
} else { // Open network
configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_OPEN);
}
@@ -446,13 +498,16 @@ public final class WifiNetworkSuggestion implements Parcelable {
numSecurityTypes += mIsEnhancedOpen ? 1 : 0;
numSecurityTypes += !TextUtils.isEmpty(mWpa2PskPassphrase) ? 1 : 0;
numSecurityTypes += !TextUtils.isEmpty(mWpa3SaePassphrase) ? 1 : 0;
+ numSecurityTypes += !TextUtils.isEmpty(mWapiPskPassphrase) ? 1 : 0;
numSecurityTypes += mWpa2EnterpriseConfig != null ? 1 : 0;
numSecurityTypes += mWpa3EnterpriseConfig != null ? 1 : 0;
+ numSecurityTypes += mWapiEnterpriseConfig != null ? 1 : 0;
numSecurityTypes += mPasspointConfiguration != null ? 1 : 0;
if (numSecurityTypes > 1) {
throw new IllegalStateException("only one of setIsEnhancedOpen, setWpa2Passphrase,"
- + "setWpa3Passphrase, setWpa2EnterpriseConfig, setWpa3EnterpriseConfig"
- + "or setPasspointConfig can be invoked for network suggestion");
+ + " setWpa3Passphrase, setWpa2EnterpriseConfig, setWpa3EnterpriseConfig"
+ + " setWapiPassphrase, setWapiCertSuite, setIsWapiCertSuiteAuto"
+ + " or setPasspointConfig can be invoked for network suggestion");
}
}
diff --git a/wifi/java/android/net/wifi/WifiScanner.java b/wifi/java/android/net/wifi/WifiScanner.java
index 760497b727cd..8fedda48aa0d 100644
--- a/wifi/java/android/net/wifi/WifiScanner.java
+++ b/wifi/java/android/net/wifi/WifiScanner.java
@@ -89,16 +89,6 @@ public class WifiScanner {
/** 6 GHz band */
public static final int WIFI_BAND_6_GHZ = 1 << WIFI_BAND_INDEX_6_GHZ;
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"WIFI_BAND_"}, value = {
- WIFI_BAND_UNSPECIFIED,
- WIFI_BAND_24_GHZ,
- WIFI_BAND_5_GHZ,
- WIFI_BAND_5_GHZ_DFS_ONLY,
- WIFI_BAND_6_GHZ})
- public @interface WifiBandBasic {}
-
/**
* Combination of bands
* Note that those are only the common band combinations,
@@ -249,14 +239,6 @@ public class WifiScanner {
*/
public static final int REPORT_EVENT_NO_BATCH = (1 << 2);
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"SCAN_TYPE_"}, value = {
- SCAN_TYPE_LOW_LATENCY,
- SCAN_TYPE_LOW_POWER,
- SCAN_TYPE_HIGH_ACCURACY})
- public @interface ScanType {}
-
/**
* Optimize the scan for lower latency.
* @see ScanSettings#type
@@ -354,7 +336,7 @@ public class WifiScanner {
* {@link #SCAN_TYPE_HIGH_ACCURACY}.
* Default value: {@link #SCAN_TYPE_LOW_LATENCY}.
*/
- @ScanType
+ @WifiAnnotations.ScanType
@RequiresPermission(android.Manifest.permission.NETWORK_STACK)
public int type = SCAN_TYPE_LOW_LATENCY;
/**
diff --git a/wifi/java/android/net/wifi/aware/DiscoverySession.java b/wifi/java/android/net/wifi/aware/DiscoverySession.java
index d97f6fb02ac6..4d92ae174e6d 100644
--- a/wifi/java/android/net/wifi/aware/DiscoverySession.java
+++ b/wifi/java/android/net/wifi/aware/DiscoverySession.java
@@ -20,12 +20,12 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.net.NetworkSpecifier;
+import android.util.CloseGuard;
import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
-import dalvik.system.CloseGuard;
-
+import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
/**
@@ -58,7 +58,7 @@ public class DiscoverySession implements AutoCloseable {
/** @hide */
protected boolean mTerminated = false;
- private final CloseGuard mCloseGuard = CloseGuard.get();
+ private final CloseGuard mCloseGuard = new CloseGuard();
/**
* Return the maximum permitted retry count when sending messages using
@@ -108,6 +108,7 @@ public class DiscoverySession implements AutoCloseable {
mTerminated = true;
mMgr.clear();
mCloseGuard.close();
+ Reference.reachabilityFence(this);
}
/**
diff --git a/wifi/java/android/net/wifi/aware/WifiAwareSession.java b/wifi/java/android/net/wifi/aware/WifiAwareSession.java
index 3c9781323c07..fe0872caf5f8 100644
--- a/wifi/java/android/net/wifi/aware/WifiAwareSession.java
+++ b/wifi/java/android/net/wifi/aware/WifiAwareSession.java
@@ -23,12 +23,12 @@ import android.net.NetworkSpecifier;
import android.os.Binder;
import android.os.Handler;
import android.os.Looper;
+import android.util.CloseGuard;
import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
-import dalvik.system.CloseGuard;
-
+import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
/**
@@ -45,7 +45,7 @@ public class WifiAwareSession implements AutoCloseable {
private final int mClientId;
private boolean mTerminated = true;
- private final CloseGuard mCloseGuard = CloseGuard.get();
+ private final CloseGuard mCloseGuard = new CloseGuard();
/** @hide */
public WifiAwareSession(WifiAwareManager manager, Binder binder, int clientId) {
@@ -80,6 +80,7 @@ public class WifiAwareSession implements AutoCloseable {
mTerminated = true;
mMgr.clear();
mCloseGuard.close();
+ Reference.reachabilityFence(this);
}
/** @hide */
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pConfig.java b/wifi/java/android/net/wifi/p2p/WifiP2pConfig.java
index 495b1bb9ba82..c9bca4f20f03 100644
--- a/wifi/java/android/net/wifi/p2p/WifiP2pConfig.java
+++ b/wifi/java/android/net/wifi/p2p/WifiP2pConfig.java
@@ -48,21 +48,29 @@ public class WifiP2pConfig implements Parcelable {
*/
public WpsInfo wps;
- /**
- * The network name of a group, should be configured by helper method
- */
+ /** Get the network name of this P2P configuration, or null if unset. */
+ @Nullable
+ public String getNetworkName() {
+ return networkName;
+ }
+
/** @hide */
public String networkName = "";
- /**
- * The passphrase of a group, should be configured by helper method
- */
+ /** Get the passphrase of this P2P configuration, or null if unset. */
+ @Nullable
+ public String getPassphrase() {
+ return passphrase;
+ }
+
/** @hide */
public String passphrase = "";
- /**
- * The required band for Group Owner
- */
+ /** Get the required band for the group owner. */
+ public int getGroupOwnerBand() {
+ return groupOwnerBand;
+ }
+
/** @hide */
public int groupOwnerBand = GROUP_OWNER_BAND_AUTO;
@@ -123,6 +131,15 @@ public class WifiP2pConfig implements Parcelable {
@UnsupportedAppUsage
public int netId = WifiP2pGroup.PERSISTENT_NET_ID;
+ /**
+ * Get the network ID of this P2P configuration.
+ * @return either a non-negative network ID, or one of {@link WifiP2pGroup#PERSISTENT_NET_ID} or
+ * {@link WifiP2pGroup#TEMPORARY_NET_ID}.
+ */
+ public int getNetworkId() {
+ return netId;
+ }
+
public WifiP2pConfig() {
//set defaults
wps = new WpsInfo();
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pGroup.java b/wifi/java/android/net/wifi/p2p/WifiP2pGroup.java
index f9d1266cf804..d8c50f2ed5f8 100644
--- a/wifi/java/android/net/wifi/p2p/WifiP2pGroup.java
+++ b/wifi/java/android/net/wifi/p2p/WifiP2pGroup.java
@@ -39,18 +39,15 @@ public class WifiP2pGroup implements Parcelable {
/**
* The temporary network id.
- *
- * @hide
+ * @see #getNetworkId()
*/
- @UnsupportedAppUsage
public static final int TEMPORARY_NET_ID = -1;
/**
* The persistent network id.
* If a matching persistent profile is found, use it.
* Otherwise, create a new persistent profile.
- *
- * @hide
+ * @see #getNetworkId()
*/
public static final int PERSISTENT_NET_ID = -2;
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pManager.java b/wifi/java/android/net/wifi/p2p/WifiP2pManager.java
index 1c2067980a79..6120e4e8a23a 100644
--- a/wifi/java/android/net/wifi/p2p/WifiP2pManager.java
+++ b/wifi/java/android/net/wifi/p2p/WifiP2pManager.java
@@ -44,15 +44,15 @@ import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.text.TextUtils;
+import android.util.CloseGuard;
import android.util.Log;
import com.android.internal.util.AsyncChannel;
import com.android.internal.util.Protocol;
-import dalvik.system.CloseGuard;
-
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
+import java.lang.ref.Reference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -869,7 +869,7 @@ public class WifiP2pManager {
private final Object mListenerMapLock = new Object();
private int mListenerKey = 0;
- private final CloseGuard mCloseGuard = CloseGuard.get();
+ private final CloseGuard mCloseGuard = new CloseGuard();
/**
* Close the current P2P connection and indicate to the P2P service that connections
@@ -888,6 +888,7 @@ public class WifiP2pManager {
mAsyncChannel.disconnect();
mCloseGuard.close();
+ Reference.reachabilityFence(this);
}
/** @hide */
diff --git a/wifi/java/android/net/wifi/wificond/ChannelSettings.java b/wifi/java/android/net/wifi/wificond/ChannelSettings.java
new file mode 100644
index 000000000000..c2d65b581491
--- /dev/null
+++ b/wifi/java/android/net/wifi/wificond/ChannelSettings.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2016 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.net.wifi.wificond;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.util.Log;
+
+import java.util.Objects;
+
+/**
+ * ChannelSettings for wificond
+ *
+ * @hide
+ */
+public class ChannelSettings implements Parcelable {
+ private static final String TAG = "ChannelSettings";
+
+ public int frequency;
+
+ /** public constructor */
+ public ChannelSettings() { }
+
+ /** override comparator */
+ @Override
+ public boolean equals(Object rhs) {
+ if (this == rhs) return true;
+ if (!(rhs instanceof ChannelSettings)) {
+ return false;
+ }
+ ChannelSettings channel = (ChannelSettings) rhs;
+ if (channel == null) {
+ return false;
+ }
+ return frequency == channel.frequency;
+ }
+
+ /** override hash code */
+ @Override
+ public int hashCode() {
+ return Objects.hash(frequency);
+ }
+
+ /** implement Parcelable interface */
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ /**
+ * implement Parcelable interface
+ * |flags| is ignored.
+ **/
+ @Override
+ public void writeToParcel(Parcel out, int flags) {
+ out.writeInt(frequency);
+ }
+
+ /** implement Parcelable interface */
+ public static final Parcelable.Creator<ChannelSettings> CREATOR =
+ new Parcelable.Creator<ChannelSettings>() {
+ /**
+ * Caller is responsible for providing a valid parcel.
+ */
+ @Override
+ public ChannelSettings createFromParcel(Parcel in) {
+ ChannelSettings result = new ChannelSettings();
+ result.frequency = in.readInt();
+ if (in.dataAvail() != 0) {
+ Log.e(TAG, "Found trailing data after parcel parsing.");
+ }
+
+ return result;
+ }
+
+ @Override
+ public ChannelSettings[] newArray(int size) {
+ return new ChannelSettings[size];
+ }
+ };
+}
diff --git a/wifi/java/android/net/wifi/wificond/HiddenNetwork.java b/wifi/java/android/net/wifi/wificond/HiddenNetwork.java
new file mode 100644
index 000000000000..38dacea77488
--- /dev/null
+++ b/wifi/java/android/net/wifi/wificond/HiddenNetwork.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2016 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.net.wifi.wificond;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import java.util.Arrays;
+
+/**
+ * HiddenNetwork for wificond
+ *
+ * @hide
+ */
+public class HiddenNetwork implements Parcelable {
+ private static final String TAG = "HiddenNetwork";
+
+ public byte[] ssid;
+
+ /** public constructor */
+ public HiddenNetwork() { }
+
+ /** override comparator */
+ @Override
+ public boolean equals(Object rhs) {
+ if (this == rhs) return true;
+ if (!(rhs instanceof HiddenNetwork)) {
+ return false;
+ }
+ HiddenNetwork network = (HiddenNetwork) rhs;
+ return Arrays.equals(ssid, network.ssid);
+ }
+
+ /** override hash code */
+ @Override
+ public int hashCode() {
+ return Arrays.hashCode(ssid);
+ }
+
+ /** implement Parcelable interface */
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ /**
+ * implement Parcelable interface
+ * |flags| is ignored.
+ */
+ @Override
+ public void writeToParcel(Parcel out, int flags) {
+ out.writeByteArray(ssid);
+ }
+
+ /** implement Parcelable interface */
+ public static final Parcelable.Creator<HiddenNetwork> CREATOR =
+ new Parcelable.Creator<HiddenNetwork>() {
+ /**
+ * Caller is responsible for providing a valid parcel.
+ */
+ @Override
+ public HiddenNetwork createFromParcel(Parcel in) {
+ HiddenNetwork result = new HiddenNetwork();
+ result.ssid = in.createByteArray();
+ return result;
+ }
+
+ @Override
+ public HiddenNetwork[] newArray(int size) {
+ return new HiddenNetwork[size];
+ }
+ };
+}
diff --git a/wifi/java/android/net/wifi/wificond/NativeScanResult.java b/wifi/java/android/net/wifi/wificond/NativeScanResult.java
new file mode 100644
index 000000000000..ff8e935da8c0
--- /dev/null
+++ b/wifi/java/android/net/wifi/wificond/NativeScanResult.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2016 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.net.wifi.wificond;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import java.util.ArrayList;
+import java.util.BitSet;
+import java.util.List;
+
+/**
+ * ScanResult from wificond
+ *
+ * @hide
+ */
+public class NativeScanResult implements Parcelable {
+ private static final int CAPABILITY_SIZE = 16;
+
+ public byte[] ssid;
+ public byte[] bssid;
+ public byte[] infoElement;
+ public int frequency;
+ public int signalMbm;
+ public long tsf;
+ public BitSet capability;
+ public boolean associated;
+ public List<RadioChainInfo> radioChainInfos;
+
+ /** public constructor */
+ public NativeScanResult() { }
+
+ /** copy constructor */
+ public NativeScanResult(NativeScanResult source) {
+ ssid = source.ssid.clone();
+ bssid = source.bssid.clone();
+ infoElement = source.infoElement.clone();
+ frequency = source.frequency;
+ signalMbm = source.signalMbm;
+ tsf = source.tsf;
+ capability = (BitSet) source.capability.clone();
+ associated = source.associated;
+ }
+
+ /** implement Parcelable interface */
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ /** implement Parcelable interface */
+ @Override
+ public void writeToParcel(Parcel out, int flags) {
+ out.writeByteArray(ssid);
+ out.writeByteArray(bssid);
+ out.writeByteArray(infoElement);
+ out.writeInt(frequency);
+ out.writeInt(signalMbm);
+ out.writeLong(tsf);
+ int capabilityInt = 0;
+ for (int i = 0; i < CAPABILITY_SIZE; i++) {
+ if (capability.get(i)) {
+ capabilityInt |= 1 << i;
+ }
+ }
+ out.writeInt(capabilityInt);
+ out.writeInt(associated ? 1 : 0);
+ out.writeTypedList(radioChainInfos);
+ }
+
+ /** implement Parcelable interface */
+ public static final Parcelable.Creator<NativeScanResult> CREATOR =
+ new Parcelable.Creator<NativeScanResult>() {
+ @Override
+ public NativeScanResult createFromParcel(Parcel in) {
+ NativeScanResult result = new NativeScanResult();
+ result.ssid = in.createByteArray();
+ result.bssid = in.createByteArray();
+ result.infoElement = in.createByteArray();
+ result.frequency = in.readInt();
+ result.signalMbm = in.readInt();
+ result.tsf = in.readLong();
+ int capabilityInt = in.readInt();
+ result.capability = new BitSet(CAPABILITY_SIZE);
+ for (int i = 0; i < CAPABILITY_SIZE; i++) {
+ if ((capabilityInt & (1 << i)) != 0) {
+ result.capability.set(i);
+ }
+ }
+ result.associated = (in.readInt() != 0);
+ result.radioChainInfos = new ArrayList<>();
+ in.readTypedList(result.radioChainInfos, RadioChainInfo.CREATOR);
+ return result;
+ }
+
+ @Override
+ public NativeScanResult[] newArray(int size) {
+ return new NativeScanResult[size];
+ }
+ };
+}
diff --git a/wifi/java/android/net/wifi/wificond/NativeWifiClient.java b/wifi/java/android/net/wifi/wificond/NativeWifiClient.java
new file mode 100644
index 000000000000..4994ebd33216
--- /dev/null
+++ b/wifi/java/android/net/wifi/wificond/NativeWifiClient.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2019 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.net.wifi.wificond;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import java.util.Arrays;
+
+/**
+ * NativeWifiClient for wificond
+ *
+ * @hide
+ */
+public class NativeWifiClient implements Parcelable {
+ public byte[] macAddress;
+
+ /** public constructor */
+ public NativeWifiClient() { }
+
+ /** override comparator */
+ @Override
+ public boolean equals(Object rhs) {
+ if (this == rhs) return true;
+ if (!(rhs instanceof NativeWifiClient)) {
+ return false;
+ }
+ NativeWifiClient other = (NativeWifiClient) rhs;
+ return Arrays.equals(macAddress, other.macAddress);
+ }
+
+ /** override hash code */
+ @Override
+ public int hashCode() {
+ return Arrays.hashCode(macAddress);
+ }
+
+ /** implement Parcelable interface */
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ /**
+ * implement Parcelable interface
+ * |flag| is ignored.
+ */
+ @Override
+ public void writeToParcel(Parcel out, int flags) {
+ out.writeByteArray(macAddress);
+ }
+
+ /** implement Parcelable interface */
+ public static final Parcelable.Creator<NativeWifiClient> CREATOR =
+ new Parcelable.Creator<NativeWifiClient>() {
+ @Override
+ public NativeWifiClient createFromParcel(Parcel in) {
+ NativeWifiClient result = new NativeWifiClient();
+ result.macAddress = in.createByteArray();
+ return result;
+ }
+
+ @Override
+ public NativeWifiClient[] newArray(int size) {
+ return new NativeWifiClient[size];
+ }
+ };
+}
diff --git a/wifi/java/android/net/wifi/wificond/PnoNetwork.java b/wifi/java/android/net/wifi/wificond/PnoNetwork.java
new file mode 100644
index 000000000000..f923fd384a90
--- /dev/null
+++ b/wifi/java/android/net/wifi/wificond/PnoNetwork.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2016 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.net.wifi.wificond;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import java.util.Arrays;
+import java.util.Objects;
+
+/**
+ * PnoNetwork for wificond
+ *
+ * @hide
+ */
+public class PnoNetwork implements Parcelable {
+
+ public boolean isHidden;
+ public byte[] ssid;
+ public int[] frequencies;
+
+ /** public constructor */
+ public PnoNetwork() { }
+
+ /** override comparator */
+ @Override
+ public boolean equals(Object rhs) {
+ if (this == rhs) return true;
+ if (!(rhs instanceof PnoNetwork)) {
+ return false;
+ }
+ PnoNetwork network = (PnoNetwork) rhs;
+ return Arrays.equals(ssid, network.ssid)
+ && Arrays.equals(frequencies, network.frequencies)
+ && isHidden == network.isHidden;
+ }
+
+ /** override hash code */
+ @Override
+ public int hashCode() {
+ return Objects.hash(
+ isHidden,
+ Arrays.hashCode(ssid),
+ Arrays.hashCode(frequencies));
+ }
+
+ /** implement Parcelable interface */
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ /**
+ * implement Parcelable interface
+ * |flag| is ignored.
+ */
+ @Override
+ public void writeToParcel(Parcel out, int flags) {
+ out.writeInt(isHidden ? 1 : 0);
+ out.writeByteArray(ssid);
+ out.writeIntArray(frequencies);
+ }
+
+ /** implement Parcelable interface */
+ public static final Parcelable.Creator<PnoNetwork> CREATOR =
+ new Parcelable.Creator<PnoNetwork>() {
+ @Override
+ public PnoNetwork createFromParcel(Parcel in) {
+ PnoNetwork result = new PnoNetwork();
+ result.isHidden = in.readInt() != 0 ? true : false;
+ result.ssid = in.createByteArray();
+ result.frequencies = in.createIntArray();
+ return result;
+ }
+
+ @Override
+ public PnoNetwork[] newArray(int size) {
+ return new PnoNetwork[size];
+ }
+ };
+}
diff --git a/wifi/java/android/net/wifi/wificond/PnoSettings.java b/wifi/java/android/net/wifi/wificond/PnoSettings.java
new file mode 100644
index 000000000000..96cf24fdfb81
--- /dev/null
+++ b/wifi/java/android/net/wifi/wificond/PnoSettings.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright (C) 2016 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.net.wifi.wificond;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import java.util.ArrayList;
+import java.util.Objects;
+
+/**
+ * PnoSettings for wificond
+ *
+ * @hide
+ */
+public class PnoSettings implements Parcelable {
+ public int intervalMs;
+ public int min2gRssi;
+ public int min5gRssi;
+ public int min6gRssi;
+ public ArrayList<PnoNetwork> pnoNetworks;
+
+ /** public constructor */
+ public PnoSettings() { }
+
+ /** override comparator */
+ @Override
+ public boolean equals(Object rhs) {
+ if (this == rhs) return true;
+ if (!(rhs instanceof PnoSettings)) {
+ return false;
+ }
+ PnoSettings settings = (PnoSettings) rhs;
+ if (settings == null) {
+ return false;
+ }
+ return intervalMs == settings.intervalMs
+ && min2gRssi == settings.min2gRssi
+ && min5gRssi == settings.min5gRssi
+ && min6gRssi == settings.min6gRssi
+ && pnoNetworks.equals(settings.pnoNetworks);
+ }
+
+ /** override hash code */
+ @Override
+ public int hashCode() {
+ return Objects.hash(intervalMs, min2gRssi, min5gRssi, min6gRssi, pnoNetworks);
+ }
+
+ /** implement Parcelable interface */
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ /**
+ * implement Parcelable interface
+ * |flag| is ignored.
+ **/
+ @Override
+ public void writeToParcel(Parcel out, int flags) {
+ out.writeInt(intervalMs);
+ out.writeInt(min2gRssi);
+ out.writeInt(min5gRssi);
+ out.writeInt(min6gRssi);
+ out.writeTypedList(pnoNetworks);
+ }
+
+ /** implement Parcelable interface */
+ public static final Parcelable.Creator<PnoSettings> CREATOR =
+ new Parcelable.Creator<PnoSettings>() {
+ @Override
+ public PnoSettings createFromParcel(Parcel in) {
+ PnoSettings result = new PnoSettings();
+ result.intervalMs = in.readInt();
+ result.min2gRssi = in.readInt();
+ result.min5gRssi = in.readInt();
+ result.min6gRssi = in.readInt();
+
+ result.pnoNetworks = new ArrayList<PnoNetwork>();
+ in.readTypedList(result.pnoNetworks, PnoNetwork.CREATOR);
+
+ return result;
+ }
+
+ @Override
+ public PnoSettings[] newArray(int size) {
+ return new PnoSettings[size];
+ }
+ };
+}
diff --git a/wifi/java/android/net/wifi/wificond/RadioChainInfo.java b/wifi/java/android/net/wifi/wificond/RadioChainInfo.java
new file mode 100644
index 000000000000..2b03450b1357
--- /dev/null
+++ b/wifi/java/android/net/wifi/wificond/RadioChainInfo.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2016 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.net.wifi.wificond;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import java.util.Objects;
+
+/**
+ * RadioChainInfo for wificond
+ *
+ * @hide
+ */
+public class RadioChainInfo implements Parcelable {
+ private static final String TAG = "RadioChainInfo";
+
+ public int chainId;
+ public int level;
+
+
+ /** public constructor */
+ public RadioChainInfo() { }
+
+ public RadioChainInfo(int chainId, int level) {
+ this.chainId = chainId;
+ this.level = level;
+ }
+
+ /** override comparator */
+ @Override
+ public boolean equals(Object rhs) {
+ if (this == rhs) return true;
+ if (!(rhs instanceof RadioChainInfo)) {
+ return false;
+ }
+ RadioChainInfo chainInfo = (RadioChainInfo) rhs;
+ if (chainInfo == null) {
+ return false;
+ }
+ return chainId == chainInfo.chainId && level == chainInfo.level;
+ }
+
+ /** override hash code */
+ @Override
+ public int hashCode() {
+ return Objects.hash(chainId, level);
+ }
+
+
+ /** implement Parcelable interface */
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ /**
+ * implement Parcelable interface
+ * |flags| is ignored.
+ */
+ @Override
+ public void writeToParcel(Parcel out, int flags) {
+ out.writeInt(chainId);
+ out.writeInt(level);
+ }
+
+ /** implement Parcelable interface */
+ public static final Parcelable.Creator<RadioChainInfo> CREATOR =
+ new Parcelable.Creator<RadioChainInfo>() {
+ /**
+ * Caller is responsible for providing a valid parcel.
+ */
+ @Override
+ public RadioChainInfo createFromParcel(Parcel in) {
+ RadioChainInfo result = new RadioChainInfo();
+ result.chainId = in.readInt();
+ result.level = in.readInt();
+ return result;
+ }
+
+ @Override
+ public RadioChainInfo[] newArray(int size) {
+ return new RadioChainInfo[size];
+ }
+ };
+}
diff --git a/wifi/java/android/net/wifi/wificond/SingleScanSettings.java b/wifi/java/android/net/wifi/wificond/SingleScanSettings.java
new file mode 100644
index 000000000000..8065c01a7f89
--- /dev/null
+++ b/wifi/java/android/net/wifi/wificond/SingleScanSettings.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2016 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.net.wifi.wificond;
+
+import android.net.wifi.IWifiScannerImpl;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.util.Log;
+
+import java.util.ArrayList;
+import java.util.Objects;
+
+/**
+ * SingleScanSettings for wificond
+ *
+ * @hide
+ */
+public class SingleScanSettings implements Parcelable {
+ private static final String TAG = "SingleScanSettings";
+
+ public int scanType;
+ public ArrayList<ChannelSettings> channelSettings;
+ public ArrayList<HiddenNetwork> hiddenNetworks;
+
+ /** public constructor */
+ public SingleScanSettings() { }
+
+ /** override comparator */
+ @Override
+ public boolean equals(Object rhs) {
+ if (this == rhs) return true;
+ if (!(rhs instanceof SingleScanSettings)) {
+ return false;
+ }
+ SingleScanSettings settings = (SingleScanSettings) rhs;
+ if (settings == null) {
+ return false;
+ }
+ return scanType == settings.scanType
+ && channelSettings.equals(settings.channelSettings)
+ && hiddenNetworks.equals(settings.hiddenNetworks);
+ }
+
+ /** override hash code */
+ @Override
+ public int hashCode() {
+ return Objects.hash(scanType, channelSettings, hiddenNetworks);
+ }
+
+
+ /** implement Parcelable interface */
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ private static boolean isValidScanType(int scanType) {
+ return scanType == IWifiScannerImpl.SCAN_TYPE_LOW_SPAN
+ || scanType == IWifiScannerImpl.SCAN_TYPE_LOW_POWER
+ || scanType == IWifiScannerImpl.SCAN_TYPE_HIGH_ACCURACY;
+ }
+
+ /**
+ * implement Parcelable interface
+ * |flags| is ignored.
+ */
+ @Override
+ public void writeToParcel(Parcel out, int flags) {
+ if (!isValidScanType(scanType)) {
+ Log.wtf(TAG, "Invalid scan type " + scanType);
+ }
+ out.writeInt(scanType);
+ out.writeTypedList(channelSettings);
+ out.writeTypedList(hiddenNetworks);
+ }
+
+ /** implement Parcelable interface */
+ public static final Parcelable.Creator<SingleScanSettings> CREATOR =
+ new Parcelable.Creator<SingleScanSettings>() {
+ /**
+ * Caller is responsible for providing a valid parcel.
+ */
+ @Override
+ public SingleScanSettings createFromParcel(Parcel in) {
+ SingleScanSettings result = new SingleScanSettings();
+ result.scanType = in.readInt();
+ if (!isValidScanType(result.scanType)) {
+ Log.wtf(TAG, "Invalid scan type " + result.scanType);
+ }
+ result.channelSettings = new ArrayList<ChannelSettings>();
+ in.readTypedList(result.channelSettings, ChannelSettings.CREATOR);
+ result.hiddenNetworks = new ArrayList<HiddenNetwork>();
+ in.readTypedList(result.hiddenNetworks, HiddenNetwork.CREATOR);
+ if (in.dataAvail() != 0) {
+ Log.e(TAG, "Found trailing data after parcel parsing.");
+ }
+ return result;
+ }
+
+ @Override
+ public SingleScanSettings[] newArray(int size) {
+ return new SingleScanSettings[size];
+ }
+ };
+}
diff --git a/wifi/java/com/android/server/wifi/BaseWifiService.java b/wifi/java/com/android/server/wifi/BaseWifiService.java
index 524a53c03305..d58083c92df6 100644
--- a/wifi/java/com/android/server/wifi/BaseWifiService.java
+++ b/wifi/java/com/android/server/wifi/BaseWifiService.java
@@ -28,7 +28,6 @@ import android.net.wifi.INetworkRequestMatchCallback;
import android.net.wifi.IOnWifiActivityEnergyInfoListener;
import android.net.wifi.IOnWifiUsabilityStatsListener;
import android.net.wifi.IScanResultsCallback;
-import android.net.wifi.IScanResultsListener;
import android.net.wifi.ISoftApCallback;
import android.net.wifi.ISuggestionConnectionStatusListener;
import android.net.wifi.ITrafficStateCallback;
@@ -227,12 +226,23 @@ public class BaseWifiService extends IWifiManager.Stub {
throw new UnsupportedOperationException();
}
- @Override
+ /** @deprecated use {@link #is5GHzBandSupported} instead */
+ @Deprecated
public boolean isDualBandSupported() {
throw new UnsupportedOperationException();
}
@Override
+ public boolean is5GHzBandSupported() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean is6GHzBandSupported() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
public boolean needs5GHzToAnyApBandConversion() {
throw new UnsupportedOperationException();
}
@@ -414,7 +424,7 @@ public class BaseWifiService extends IWifiManager.Stub {
}
@Override
- public void restoreSoftApBackupData(byte[] data) {
+ public SoftApConfiguration restoreSoftApBackupData(byte[] data) {
throw new UnsupportedOperationException();
}
diff --git a/wifi/tests/Android.mk b/wifi/tests/Android.mk
index 3453d6ec827f..d2c385b46eb1 100644
--- a/wifi/tests/Android.mk
+++ b/wifi/tests/Android.mk
@@ -59,6 +59,8 @@ LOCAL_JAVA_LIBRARIES := \
LOCAL_PACKAGE_NAME := FrameworksWifiApiTests
LOCAL_PRIVATE_PLATFORM_APIS := true
-LOCAL_COMPATIBILITY_SUITE := device-tests
+LOCAL_COMPATIBILITY_SUITE := \
+ device-tests \
+ mts \
include $(BUILD_PACKAGE)
diff --git a/wifi/tests/AndroidTest.xml b/wifi/tests/AndroidTest.xml
index cae19e46c6af..987fee79fefd 100644
--- a/wifi/tests/AndroidTest.xml
+++ b/wifi/tests/AndroidTest.xml
@@ -14,7 +14,7 @@
limitations under the License.
-->
<configuration description="Runs Frameworks Wifi API Tests.">
- <target_preparer class="com.android.tradefed.targetprep.TestAppInstallSetup">
+ <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="test-file-name" value="FrameworksWifiApiTests.apk" />
</target_preparer>
diff --git a/wifi/tests/runtests.sh b/wifi/tests/runtests.sh
index 7a0dfb08fcfe..4024371dd97d 100755
--- a/wifi/tests/runtests.sh
+++ b/wifi/tests/runtests.sh
@@ -16,7 +16,6 @@ $ANDROID_BUILD_TOP/build/soong/soong_ui.bash --make-mode MODULES-IN-frameworks-b
set -x # print commands
-adb root
adb wait-for-device
TARGET_ARCH=$($ANDROID_BUILD_TOP/build/soong/soong_ui.bash --dumpvar-mode TARGET_ARCH)
diff --git a/wifi/tests/src/android/net/wifi/SoftApConfigurationTest.java b/wifi/tests/src/android/net/wifi/SoftApConfigurationTest.java
index b8d3e413f1d2..60125e372cd5 100644
--- a/wifi/tests/src/android/net/wifi/SoftApConfigurationTest.java
+++ b/wifi/tests/src/android/net/wifi/SoftApConfigurationTest.java
@@ -91,13 +91,13 @@ public class SoftApConfigurationTest {
SoftApConfiguration original = new SoftApConfiguration.Builder()
.setWpa2Passphrase("secretsecret")
.setBand(SoftApConfiguration.BAND_ANY)
- .setChannel(149)
+ .setChannel(149, SoftApConfiguration.BAND_5GHZ)
.setHiddenSsid(true)
.build();
assertThat(original.getWpa2Passphrase()).isEqualTo("secretsecret");
assertThat(original.getSecurityType()).isEqualTo(
SoftApConfiguration.SECURITY_TYPE_WPA2_PSK);
- assertThat(original.getBand()).isEqualTo(SoftApConfiguration.BAND_ANY);
+ assertThat(original.getBand()).isEqualTo(SoftApConfiguration.BAND_5GHZ);
assertThat(original.getChannel()).isEqualTo(149);
assertThat(original.isHiddenSsid()).isEqualTo(true);
diff --git a/wifi/tests/src/android/net/wifi/WifiCondManagerTest.java b/wifi/tests/src/android/net/wifi/WifiCondManagerTest.java
new file mode 100644
index 000000000000..48a9afa1d961
--- /dev/null
+++ b/wifi/tests/src/android/net/wifi/WifiCondManagerTest.java
@@ -0,0 +1,1281 @@
+/*
+ * Copyright (C) 2017 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.net.wifi;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Matchers.argThat;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyLong;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+import android.app.AlarmManager;
+import android.app.test.TestAlarmManager;
+import android.content.Context;
+import android.net.wifi.util.HexEncoding;
+import android.net.wifi.wificond.ChannelSettings;
+import android.net.wifi.wificond.HiddenNetwork;
+import android.net.wifi.wificond.NativeWifiClient;
+import android.net.wifi.wificond.PnoNetwork;
+import android.net.wifi.wificond.PnoSettings;
+import android.net.wifi.wificond.SingleScanSettings;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.os.test.TestLooper;
+
+import androidx.test.filters.SmallTest;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.AdditionalMatchers;
+import org.mockito.ArgumentCaptor;
+import org.mockito.ArgumentMatcher;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CharsetEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Unit tests for {@link android.net.wifi.WifiCondManager}.
+ */
+@SmallTest
+public class WifiCondManagerTest {
+ @Mock
+ private IWificond mWificond;
+ @Mock
+ private IBinder mWifiCondBinder;
+ @Mock
+ private IClientInterface mClientInterface;
+ @Mock
+ private IWifiScannerImpl mWifiScannerImpl;
+ @Mock
+ private IApInterface mApInterface;
+ @Mock
+ private WifiCondManager.SoftApListener mSoftApListener;
+ @Mock
+ private WifiCondManager.SendMgmtFrameCallback mSendMgmtFrameCallback;
+ @Mock
+ private WifiCondManager.ScanEventCallback mNormalScanCallback;
+ @Mock
+ private WifiCondManager.ScanEventCallback mPnoScanCallback;
+ @Mock
+ private WifiCondManager.PnoScanRequestCallback mPnoScanRequestCallback;
+ @Mock
+ private Context mContext;
+ private TestLooper mLooper;
+ private TestAlarmManager mTestAlarmManager;
+ private AlarmManager mAlarmManager;
+ private WifiCondManager mWificondControl;
+ private static final String TEST_INTERFACE_NAME = "test_wlan_if";
+ private static final String TEST_INTERFACE_NAME1 = "test_wlan_if1";
+ private static final String TEST_INVALID_INTERFACE_NAME = "asdf";
+ private static final byte[] TEST_SSID =
+ new byte[]{'G', 'o', 'o', 'g', 'l', 'e', 'G', 'u', 'e', 's', 't'};
+ private static final byte[] TEST_PSK =
+ new byte[]{'T', 'e', 's', 't'};
+
+ private static final Set<Integer> SCAN_FREQ_SET =
+ new HashSet<Integer>() {{
+ add(2410);
+ add(2450);
+ add(5050);
+ add(5200);
+ }};
+ private static final String TEST_QUOTED_SSID_1 = "\"testSsid1\"";
+ private static final String TEST_QUOTED_SSID_2 = "\"testSsid2\"";
+ private static final int[] TEST_FREQUENCIES_1 = {};
+ private static final int[] TEST_FREQUENCIES_2 = {2500, 5124};
+
+ private static final List<byte[]> SCAN_HIDDEN_NETWORK_SSID_LIST =
+ new ArrayList<byte[]>() {{
+ add(LocalNativeUtil.byteArrayFromArrayList(
+ LocalNativeUtil.decodeSsid(TEST_QUOTED_SSID_1)));
+ add(LocalNativeUtil.byteArrayFromArrayList(
+ LocalNativeUtil.decodeSsid(TEST_QUOTED_SSID_2)));
+ }};
+
+ private static final PnoSettings TEST_PNO_SETTINGS =
+ new PnoSettings() {{
+ intervalMs = 6000;
+ pnoNetworks = new ArrayList<>();
+ PnoNetwork network = new PnoNetwork();
+ network.ssid = LocalNativeUtil.byteArrayFromArrayList(
+ LocalNativeUtil.decodeSsid(TEST_QUOTED_SSID_1));
+ network.isHidden = true;
+ network.frequencies = TEST_FREQUENCIES_1;
+ pnoNetworks.add(network);
+ network.ssid = LocalNativeUtil.byteArrayFromArrayList(
+ LocalNativeUtil.decodeSsid(TEST_QUOTED_SSID_2));
+ network.isHidden = false;
+ network.frequencies = TEST_FREQUENCIES_2;
+ pnoNetworks.add(network);
+ }};
+
+ private static final int TEST_MCS_RATE = 5;
+ private static final int TEST_SEND_MGMT_FRAME_ELAPSED_TIME_MS = 100;
+ private static final byte[] TEST_PROBE_FRAME = {
+ 0x40, 0x00, 0x3c, 0x00, (byte) 0xa8, (byte) 0xbd, 0x27, 0x5b,
+ 0x33, 0x72, (byte) 0xf4, (byte) 0xf5, (byte) 0xe8, 0x51, (byte) 0x9e, 0x09,
+ (byte) 0xa8, (byte) 0xbd, 0x27, 0x5b, 0x33, 0x72, (byte) 0xb0, 0x66,
+ 0x00, 0x00
+ };
+
+ @Before
+ public void setUp() throws Exception {
+ // Setup mocks for successful WificondControl operation. Failure case mocks should be
+ // created in specific tests
+ MockitoAnnotations.initMocks(this);
+
+ mTestAlarmManager = new TestAlarmManager();
+ mAlarmManager = mTestAlarmManager.getAlarmManager();
+ when(mContext.getSystemServiceName(AlarmManager.class)).thenReturn(Context.ALARM_SERVICE);
+ when(mContext.getSystemService(AlarmManager.class)).thenReturn(mAlarmManager);
+
+ mLooper = new TestLooper();
+ when(mContext.getMainLooper()).thenReturn(mLooper.getLooper());
+
+ when(mWificond.asBinder()).thenReturn(mWifiCondBinder);
+ when(mClientInterface.getWifiScannerImpl()).thenReturn(mWifiScannerImpl);
+ when(mWificond.createClientInterface(any())).thenReturn(mClientInterface);
+ when(mWificond.createApInterface(any())).thenReturn(mApInterface);
+ when(mWificond.tearDownClientInterface(any())).thenReturn(true);
+ when(mWificond.tearDownApInterface(any())).thenReturn(true);
+ when(mClientInterface.getWifiScannerImpl()).thenReturn(mWifiScannerImpl);
+ when(mClientInterface.getInterfaceName()).thenReturn(TEST_INTERFACE_NAME);
+ mWificondControl = new WifiCondManager(mContext, mWificond);
+ assertEquals(true, mWificondControl.setupInterfaceForClientMode(TEST_INTERFACE_NAME,
+ mNormalScanCallback, mPnoScanCallback));
+ }
+
+ /**
+ * Verifies that setupInterfaceForClientMode(TEST_INTERFACE_NAME) calls Wificond.
+ */
+ @Test
+ public void testSetupInterfaceForClientMode() throws Exception {
+ when(mWificond.createClientInterface(TEST_INTERFACE_NAME)).thenReturn(mClientInterface);
+ verify(mWificond).createClientInterface(TEST_INTERFACE_NAME);
+ }
+
+ /**
+ * Verifies that setupInterfaceForClientMode(TEST_INTERFACE_NAME) calls subscribeScanEvents().
+ */
+ @Test
+ public void testSetupInterfaceForClientModeCallsScanEventSubscripiton() throws Exception {
+ verify(mWifiScannerImpl).subscribeScanEvents(any(IScanEvent.class));
+ }
+
+ /**
+ * Verifies that tearDownClientInterface(TEST_INTERFACE_NAME) calls Wificond.
+ */
+ @Test
+ public void testTeardownClientInterface() throws Exception {
+ when(mWificond.tearDownClientInterface(TEST_INTERFACE_NAME)).thenReturn(true);
+
+ assertTrue(mWificondControl.tearDownClientInterface(TEST_INTERFACE_NAME));
+ verify(mWifiScannerImpl).unsubscribeScanEvents();
+ verify(mWifiScannerImpl).unsubscribePnoScanEvents();
+ verify(mWificond).tearDownClientInterface(TEST_INTERFACE_NAME);
+ }
+
+ /**
+ * Verifies that tearDownClientInterface(TEST_INTERFACE_NAME) calls Wificond.
+ */
+ @Test
+ public void testTeardownClientInterfaceOnInvalidIface() throws Exception {
+ when(mWificond.tearDownClientInterface(TEST_INTERFACE_NAME1)).thenReturn(true);
+
+ assertFalse(mWificondControl.tearDownClientInterface(TEST_INTERFACE_NAME1));
+ verify(mWifiScannerImpl, never()).unsubscribeScanEvents();
+ verify(mWifiScannerImpl, never()).unsubscribePnoScanEvents();
+ verify(mWificond, never()).tearDownClientInterface(any());
+ }
+
+ /**
+ * Verifies that tearDownClientInterface(TEST_INTERFACE_NAME) calls Wificond.
+ */
+ @Test
+ public void testTeardownClientInterfaceFailDueToExceptionScannerUnsubscribe() throws Exception {
+ when(mWificond.tearDownClientInterface(TEST_INTERFACE_NAME)).thenReturn(true);
+ doThrow(new RemoteException()).when(mWifiScannerImpl).unsubscribeScanEvents();
+
+ assertFalse(mWificondControl.tearDownClientInterface(TEST_INTERFACE_NAME));
+ verify(mWifiScannerImpl).unsubscribeScanEvents();
+ verify(mWifiScannerImpl, never()).unsubscribePnoScanEvents();
+ verify(mWificond, never()).tearDownClientInterface(TEST_INTERFACE_NAME);
+ }
+
+ /**
+ * Verifies that tearDownClientInterface(TEST_INTERFACE_NAME) calls Wificond.
+ */
+ @Test
+ public void testTeardownClientInterfaceErrorWhenWificondFailed() throws Exception {
+ when(mWificond.tearDownClientInterface(TEST_INTERFACE_NAME)).thenReturn(false);
+
+ assertFalse(mWificondControl.tearDownClientInterface(TEST_INTERFACE_NAME));
+ verify(mWifiScannerImpl).unsubscribeScanEvents();
+ verify(mWifiScannerImpl).unsubscribePnoScanEvents();
+ verify(mWificond).tearDownClientInterface(TEST_INTERFACE_NAME);
+ }
+
+ /**
+ * Verifies that the client handles are cleared after teardown.
+ */
+ @Test
+ public void testTeardownClientInterfaceClearsHandles() throws Exception {
+ testTeardownClientInterface();
+
+ assertNull(mWificondControl.signalPoll(TEST_INTERFACE_NAME));
+ verify(mClientInterface, never()).signalPoll();
+
+ assertFalse(mWificondControl.scan(
+ TEST_INTERFACE_NAME, WifiScanner.SCAN_TYPE_LOW_LATENCY,
+ SCAN_FREQ_SET, SCAN_HIDDEN_NETWORK_SSID_LIST));
+ verify(mWifiScannerImpl, never()).scan(any());
+ }
+
+ /**
+ * Verifies that setupInterfaceForSoftApMode(TEST_INTERFACE_NAME) calls wificond.
+ */
+ @Test
+ public void testSetupInterfaceForSoftApMode() throws Exception {
+ when(mWificond.createApInterface(TEST_INTERFACE_NAME)).thenReturn(mApInterface);
+
+ assertEquals(true, mWificondControl.setupInterfaceForSoftApMode(TEST_INTERFACE_NAME));
+ verify(mWificond).createApInterface(TEST_INTERFACE_NAME);
+ }
+
+ /**
+ * Verifies that setupInterfaceForSoftAp() returns null when wificond is not started.
+ */
+ @Test
+ public void testSetupInterfaceForSoftApModeErrorWhenWificondIsNotStarted() throws Exception {
+ // Invoke wificond death handler to clear the handle.
+ mWificondControl.binderDied();
+ mLooper.dispatchAll();
+
+ assertEquals(false, mWificondControl.setupInterfaceForSoftApMode(TEST_INTERFACE_NAME));
+ }
+
+ /**
+ * Verifies that setupInterfaceForSoftApMode(TEST_INTERFACE_NAME) returns null when wificond
+ * failed to setup AP interface.
+ */
+ @Test
+ public void testSetupInterfaceForSoftApModeErrorWhenWificondFailedToSetupInterface()
+ throws Exception {
+ when(mWificond.createApInterface(TEST_INTERFACE_NAME)).thenReturn(null);
+
+ assertEquals(false, mWificondControl.setupInterfaceForSoftApMode(TEST_INTERFACE_NAME));
+ }
+
+ /**
+ * Verifies that tearDownClientInterface(TEST_INTERFACE_NAME) calls Wificond.
+ */
+ @Test
+ public void testTeardownSoftApInterface() throws Exception {
+ testSetupInterfaceForSoftApMode();
+ when(mWificond.tearDownApInterface(TEST_INTERFACE_NAME)).thenReturn(true);
+
+ assertTrue(mWificondControl.tearDownSoftApInterface(TEST_INTERFACE_NAME));
+ verify(mWificond).tearDownApInterface(TEST_INTERFACE_NAME);
+ }
+
+ /**
+ * Verifies that tearDownSoftapInterface(TEST_INTERFACE_NAME) calls Wificond.
+ */
+ @Test
+ public void testTeardownSoftApInterfaceOnInvalidIface() throws Exception {
+ testSetupInterfaceForSoftApMode();
+ when(mWificond.tearDownApInterface(TEST_INTERFACE_NAME1)).thenReturn(true);
+
+ assertFalse(mWificondControl.tearDownSoftApInterface(TEST_INTERFACE_NAME1));
+ verify(mWificond, never()).tearDownApInterface(any());
+ }
+
+ /**
+ * Verifies that tearDownClientInterface(TEST_INTERFACE_NAME) calls Wificond.
+ */
+ @Test
+ public void testTeardownSoftApInterfaceErrorWhenWificondFailed() throws Exception {
+ testSetupInterfaceForSoftApMode();
+ when(mWificond.tearDownApInterface(TEST_INTERFACE_NAME)).thenReturn(false);
+
+ assertFalse(mWificondControl.tearDownSoftApInterface(TEST_INTERFACE_NAME));
+ verify(mWificond).tearDownApInterface(TEST_INTERFACE_NAME);
+ }
+
+ /**
+ * Verifies that the SoftAp handles are cleared after teardown.
+ */
+ @Test
+ public void testTeardownSoftApInterfaceClearsHandles() throws Exception {
+ testTeardownSoftApInterface();
+
+ assertFalse(mWificondControl.registerApListener(
+ TEST_INTERFACE_NAME, mSoftApListener));
+ verify(mApInterface, never()).registerCallback(any());
+ }
+
+ /**
+ * Verifies that we can setup concurrent interfaces.
+ */
+ @Test
+ public void testSetupMultipleInterfaces() throws Exception {
+ when(mWificond.createApInterface(TEST_INTERFACE_NAME1)).thenReturn(mApInterface);
+
+ assertEquals(true, mWificondControl.setupInterfaceForSoftApMode(TEST_INTERFACE_NAME1));
+
+ verify(mWificond).createClientInterface(TEST_INTERFACE_NAME);
+ verify(mWificond).createApInterface(TEST_INTERFACE_NAME1);
+ }
+
+ /**
+ * Verifies that we can setup concurrent interfaces.
+ */
+ @Test
+ public void testTeardownMultipleInterfaces() throws Exception {
+ testSetupMultipleInterfaces();
+ assertTrue(mWificondControl.tearDownClientInterface(TEST_INTERFACE_NAME));
+ assertTrue(mWificondControl.tearDownSoftApInterface(TEST_INTERFACE_NAME1));
+
+ verify(mWificond).tearDownClientInterface(TEST_INTERFACE_NAME);
+ verify(mWificond).tearDownApInterface(TEST_INTERFACE_NAME1);
+ }
+
+ /**
+ * Verifies that tearDownInterfaces() calls wificond.
+ */
+ @Test
+ public void testTearDownInterfaces() throws Exception {
+ assertTrue(mWificondControl.tearDownInterfaces());
+ verify(mWificond).tearDownInterfaces();
+ }
+
+ /**
+ * Verifies that tearDownInterfaces() calls unsubscribeScanEvents() when there was
+ * a configured client interface.
+ */
+ @Test
+ public void testTearDownInterfacesRemovesScanEventSubscription() throws Exception {
+ assertTrue(mWificondControl.tearDownInterfaces());
+ verify(mWifiScannerImpl).unsubscribeScanEvents();
+ }
+
+
+ /**
+ * Verifies that tearDownInterfaces() returns false when wificond is not started.
+ */
+ @Test
+ public void testTearDownInterfacesErrorWhenWificondIsNotStarterd() throws Exception {
+ // Invoke wificond death handler to clear the handle.
+ mWificondControl.binderDied();
+ mLooper.dispatchAll();
+ assertFalse(mWificondControl.tearDownInterfaces());
+ }
+
+ /**
+ * Verifies that signalPoll() calls wificond.
+ */
+ @Test
+ public void testSignalPoll() throws Exception {
+ when(mWificond.createClientInterface(TEST_INTERFACE_NAME)).thenReturn(mClientInterface);
+
+ mWificondControl.setupInterfaceForClientMode(TEST_INTERFACE_NAME, mNormalScanCallback,
+ mPnoScanCallback);
+ mWificondControl.signalPoll(TEST_INTERFACE_NAME);
+ verify(mClientInterface).signalPoll();
+ }
+
+ /**
+ * Verifies that signalPoll() returns null when there is no configured client interface.
+ */
+ @Test
+ public void testSignalPollErrorWhenNoClientInterfaceConfigured() throws Exception {
+ when(mWificond.createClientInterface(TEST_INTERFACE_NAME)).thenReturn(mClientInterface);
+
+ // Configure client interface.
+ assertEquals(true, mWificondControl.setupInterfaceForClientMode(TEST_INTERFACE_NAME,
+ mNormalScanCallback, mPnoScanCallback));
+
+ // Tear down interfaces.
+ assertTrue(mWificondControl.tearDownInterfaces());
+
+ // Signal poll should fail.
+ assertEquals(null, mWificondControl.signalPoll(TEST_INTERFACE_NAME));
+ }
+
+ /**
+ * Verifies that getTxPacketCounters() calls wificond.
+ */
+ @Test
+ public void testGetTxPacketCounters() throws Exception {
+ when(mWificond.createClientInterface(TEST_INTERFACE_NAME)).thenReturn(mClientInterface);
+
+ mWificondControl.setupInterfaceForClientMode(TEST_INTERFACE_NAME, mNormalScanCallback,
+ mPnoScanCallback);
+ mWificondControl.getTxPacketCounters(TEST_INTERFACE_NAME);
+ verify(mClientInterface).getPacketCounters();
+ }
+
+ /**
+ * Verifies that getTxPacketCounters() returns null when there is no configured client
+ * interface.
+ */
+ @Test
+ public void testGetTxPacketCountersErrorWhenNoClientInterfaceConfigured() throws Exception {
+ when(mWificond.createClientInterface(TEST_INTERFACE_NAME)).thenReturn(mClientInterface);
+
+ // Configure client interface.
+ assertEquals(true, mWificondControl.setupInterfaceForClientMode(TEST_INTERFACE_NAME,
+ mNormalScanCallback, mPnoScanCallback));
+
+ // Tear down interfaces.
+ assertTrue(mWificondControl.tearDownInterfaces());
+
+ // Signal poll should fail.
+ assertEquals(null, mWificondControl.getTxPacketCounters(TEST_INTERFACE_NAME));
+ }
+
+ /**
+ * Verifies that getScanResults() returns null when there is no configured client
+ * interface.
+ */
+ @Test
+ public void testGetScanResultsErrorWhenNoClientInterfaceConfigured() throws Exception {
+ when(mWificond.createClientInterface(TEST_INTERFACE_NAME)).thenReturn(mClientInterface);
+
+ // Configure client interface.
+ assertEquals(true, mWificondControl.setupInterfaceForClientMode(TEST_INTERFACE_NAME,
+ mNormalScanCallback, mPnoScanCallback));
+
+ // Tear down interfaces.
+ assertTrue(mWificondControl.tearDownInterfaces());
+
+ // getScanResults should fail.
+ assertEquals(0,
+ mWificondControl.getScanResults(TEST_INTERFACE_NAME,
+ WifiCondManager.SCAN_TYPE_SINGLE_SCAN).size());
+ }
+
+ /**
+ * Verifies that Scan() can convert input parameters to SingleScanSettings correctly.
+ */
+ @Test
+ public void testScan() throws Exception {
+ when(mWifiScannerImpl.scan(any(SingleScanSettings.class))).thenReturn(true);
+ assertTrue(mWificondControl.scan(
+ TEST_INTERFACE_NAME, WifiScanner.SCAN_TYPE_LOW_POWER,
+ SCAN_FREQ_SET, SCAN_HIDDEN_NETWORK_SSID_LIST));
+ verify(mWifiScannerImpl).scan(argThat(new ScanMatcher(
+ IWifiScannerImpl.SCAN_TYPE_LOW_POWER,
+ SCAN_FREQ_SET, SCAN_HIDDEN_NETWORK_SSID_LIST)));
+ }
+
+ /**
+ * Verifies that Scan() removes duplicates hiddenSsids passed in from input.
+ */
+ @Test
+ public void testScanWithDuplicateHiddenSsids() throws Exception {
+ when(mWifiScannerImpl.scan(any(SingleScanSettings.class))).thenReturn(true);
+ // Create a list of hiddenSsid that has a duplicate element
+ List<byte[]> hiddenSsidWithDup = new ArrayList<>(SCAN_HIDDEN_NETWORK_SSID_LIST);
+ hiddenSsidWithDup.add(SCAN_HIDDEN_NETWORK_SSID_LIST.get(0));
+ assertEquals(hiddenSsidWithDup.get(0),
+ hiddenSsidWithDup.get(hiddenSsidWithDup.size() - 1));
+ // Pass the List with duplicate elements into scan()
+ assertTrue(mWificondControl.scan(
+ TEST_INTERFACE_NAME, WifiScanner.SCAN_TYPE_LOW_POWER,
+ SCAN_FREQ_SET, hiddenSsidWithDup));
+ // But the argument passed down should have the duplicate removed.
+ verify(mWifiScannerImpl).scan(argThat(new ScanMatcher(
+ IWifiScannerImpl.SCAN_TYPE_LOW_POWER,
+ SCAN_FREQ_SET, SCAN_HIDDEN_NETWORK_SSID_LIST)));
+ }
+
+ /**
+ * Verifies that Scan() can handle null input parameters correctly.
+ */
+ @Test
+ public void testScanNullParameters() throws Exception {
+ when(mWifiScannerImpl.scan(any(SingleScanSettings.class))).thenReturn(true);
+ assertTrue(mWificondControl.scan(
+ TEST_INTERFACE_NAME, WifiScanner.SCAN_TYPE_HIGH_ACCURACY, null, null));
+ verify(mWifiScannerImpl).scan(argThat(new ScanMatcher(
+ IWifiScannerImpl.SCAN_TYPE_HIGH_ACCURACY, null, null)));
+ }
+
+ /**
+ * Verifies that Scan() can handle wificond scan failure.
+ */
+ @Test
+ public void testScanFailure() throws Exception {
+ when(mWifiScannerImpl.scan(any(SingleScanSettings.class))).thenReturn(false);
+ assertFalse(mWificondControl.scan(
+ TEST_INTERFACE_NAME, WifiScanner.SCAN_TYPE_LOW_LATENCY,
+ SCAN_FREQ_SET, SCAN_HIDDEN_NETWORK_SSID_LIST));
+ verify(mWifiScannerImpl).scan(any(SingleScanSettings.class));
+ }
+
+ /**
+ * Verifies that Scan() can handle invalid type.
+ */
+ @Test
+ public void testScanFailureDueToInvalidType() throws Exception {
+ assertFalse(mWificondControl.scan(
+ TEST_INTERFACE_NAME, 100,
+ SCAN_FREQ_SET, SCAN_HIDDEN_NETWORK_SSID_LIST));
+ verify(mWifiScannerImpl, never()).scan(any(SingleScanSettings.class));
+ }
+
+ /**
+ * Verifies that startPnoScan() can convert input parameters to PnoSettings correctly.
+ */
+ @Test
+ public void testStartPnoScan() throws Exception {
+ when(mWifiScannerImpl.startPnoScan(any(PnoSettings.class))).thenReturn(true);
+ assertTrue(mWificondControl.startPnoScan(TEST_INTERFACE_NAME, TEST_PNO_SETTINGS,
+ mPnoScanRequestCallback));
+ verify(mWifiScannerImpl).startPnoScan(argThat(new PnoScanMatcher(TEST_PNO_SETTINGS)));
+ verify(mPnoScanRequestCallback).onPnoRequestSucceeded();
+ }
+
+ /**
+ * Verifies that stopPnoScan() calls underlying wificond.
+ */
+ @Test
+ public void testStopPnoScan() throws Exception {
+ when(mWifiScannerImpl.stopPnoScan()).thenReturn(true);
+ assertTrue(mWificondControl.stopPnoScan(TEST_INTERFACE_NAME));
+ verify(mWifiScannerImpl).stopPnoScan();
+ }
+
+ /**
+ * Verifies that stopPnoScan() can handle wificond failure.
+ */
+ @Test
+ public void testStopPnoScanFailure() throws Exception {
+
+ when(mWifiScannerImpl.stopPnoScan()).thenReturn(false);
+ assertFalse(mWificondControl.stopPnoScan(TEST_INTERFACE_NAME));
+ verify(mWifiScannerImpl).stopPnoScan();
+ }
+
+ /**
+ * Verifies that WificondControl can invoke WifiMonitor broadcast methods upon scan
+ * result event.
+ */
+ @Test
+ public void testScanResultEvent() throws Exception {
+ ArgumentCaptor<IScanEvent> messageCaptor = ArgumentCaptor.forClass(IScanEvent.class);
+ verify(mWifiScannerImpl).subscribeScanEvents(messageCaptor.capture());
+ IScanEvent scanEvent = messageCaptor.getValue();
+ assertNotNull(scanEvent);
+ scanEvent.OnScanResultReady();
+
+ verify(mNormalScanCallback).onScanResultReady();
+ }
+
+ /**
+ * Verifies that WificondControl can invoke WifiMonitor broadcast methods upon scan
+ * failed event.
+ */
+ @Test
+ public void testScanFailedEvent() throws Exception {
+ ArgumentCaptor<IScanEvent> messageCaptor = ArgumentCaptor.forClass(IScanEvent.class);
+ verify(mWifiScannerImpl).subscribeScanEvents(messageCaptor.capture());
+ IScanEvent scanEvent = messageCaptor.getValue();
+ assertNotNull(scanEvent);
+ scanEvent.OnScanFailed();
+
+ verify(mNormalScanCallback).onScanFailed();
+ }
+
+ /**
+ * Verifies that WificondControl can invoke WifiMonitor broadcast methods upon pno scan
+ * result event.
+ */
+ @Test
+ public void testPnoScanResultEvent() throws Exception {
+ ArgumentCaptor<IPnoScanEvent> messageCaptor = ArgumentCaptor.forClass(IPnoScanEvent.class);
+ verify(mWifiScannerImpl).subscribePnoScanEvents(messageCaptor.capture());
+ IPnoScanEvent pnoScanEvent = messageCaptor.getValue();
+ assertNotNull(pnoScanEvent);
+ pnoScanEvent.OnPnoNetworkFound();
+ verify(mPnoScanCallback).onScanResultReady();
+ }
+
+ /**
+ * Verifies that WificondControl can invoke WifiMetrics pno scan count methods upon pno event.
+ */
+ @Test
+ public void testPnoScanEventsForMetrics() throws Exception {
+ ArgumentCaptor<IPnoScanEvent> messageCaptor = ArgumentCaptor.forClass(IPnoScanEvent.class);
+ verify(mWifiScannerImpl).subscribePnoScanEvents(messageCaptor.capture());
+ IPnoScanEvent pnoScanEvent = messageCaptor.getValue();
+ assertNotNull(pnoScanEvent);
+
+ pnoScanEvent.OnPnoNetworkFound();
+ verify(mPnoScanCallback).onScanResultReady();
+
+ pnoScanEvent.OnPnoScanFailed();
+ verify(mPnoScanCallback).onScanFailed();
+ }
+
+ /**
+ * Verifies that startPnoScan() can invoke WifiMetrics pno scan count methods correctly.
+ */
+ @Test
+ public void testStartPnoScanForMetrics() throws Exception {
+ when(mWifiScannerImpl.startPnoScan(any(PnoSettings.class))).thenReturn(false);
+
+ assertFalse(mWificondControl.startPnoScan(TEST_INTERFACE_NAME, TEST_PNO_SETTINGS,
+ mPnoScanRequestCallback));
+ verify(mPnoScanRequestCallback).onPnoRequestFailed();
+ }
+
+ /**
+ * Verifies that abortScan() calls underlying wificond.
+ */
+ @Test
+ public void testAbortScan() throws Exception {
+ mWificondControl.abortScan(TEST_INTERFACE_NAME);
+ verify(mWifiScannerImpl).abortScan();
+ }
+
+ /**
+ * Ensures that the Ap interface callbacks are forwarded to the
+ * SoftApListener used for starting soft AP.
+ */
+ @Test
+ public void testSoftApListenerInvocation() throws Exception {
+ testSetupInterfaceForSoftApMode();
+
+ WifiConfiguration config = new WifiConfiguration();
+ config.SSID = new String(TEST_SSID, StandardCharsets.UTF_8);
+
+ when(mApInterface.registerCallback(any())).thenReturn(true);
+
+ final ArgumentCaptor<IApInterfaceEventCallback> apInterfaceCallbackCaptor =
+ ArgumentCaptor.forClass(IApInterfaceEventCallback.class);
+
+ assertTrue(mWificondControl.registerApListener(
+ TEST_INTERFACE_NAME, mSoftApListener));
+ verify(mApInterface).registerCallback(apInterfaceCallbackCaptor.capture());
+
+ final NativeWifiClient testClient = new NativeWifiClient();
+ apInterfaceCallbackCaptor.getValue().onConnectedClientsChanged(testClient, true);
+ verify(mSoftApListener).onConnectedClientsChanged(eq(testClient), eq(true));
+
+ int channelFrequency = 2437;
+ int channelBandwidth = IApInterfaceEventCallback.BANDWIDTH_20;
+ apInterfaceCallbackCaptor.getValue().onSoftApChannelSwitched(channelFrequency,
+ channelBandwidth);
+ verify(mSoftApListener).onSoftApChannelSwitched(eq(channelFrequency), eq(channelBandwidth));
+ }
+
+ /**
+ * Verifies registration and invocation of wificond death handler.
+ */
+ @Test
+ public void testRegisterDeathHandler() throws Exception {
+ Runnable deathHandler = mock(Runnable.class);
+ assertTrue(mWificondControl.initialize(deathHandler));
+ verify(mWificond).tearDownInterfaces();
+ mWificondControl.binderDied();
+ mLooper.dispatchAll();
+ verify(deathHandler).run();
+ }
+
+ /**
+ * Verifies handling of wificond death and ensures that all internal state is cleared and
+ * handlers are invoked.
+ */
+ @Test
+ public void testDeathHandling() throws Exception {
+ Runnable deathHandler = mock(Runnable.class);
+ assertTrue(mWificondControl.initialize(deathHandler));
+
+ testSetupInterfaceForClientMode();
+
+ mWificondControl.binderDied();
+ mLooper.dispatchAll();
+ verify(deathHandler).run();
+
+ // The handles should be cleared after death.
+ assertNull(mWificondControl.getChannelsForBand(WifiScanner.WIFI_BAND_5_GHZ));
+ verify(mWificond, never()).getAvailable5gNonDFSChannels();
+ }
+
+ /**
+ * sendMgmtFrame() should fail if a null callback is passed in.
+ */
+ @Test
+ public void testSendMgmtFrameNullCallback() throws Exception {
+ mWificondControl.sendMgmtFrame(TEST_INTERFACE_NAME, TEST_PROBE_FRAME, null, TEST_MCS_RATE);
+
+ verify(mClientInterface, never()).SendMgmtFrame(any(), any(), anyInt());
+ }
+
+ /**
+ * sendMgmtFrame() should fail if a null frame is passed in.
+ */
+ @Test
+ public void testSendMgmtFrameNullFrame() throws Exception {
+ mWificondControl.sendMgmtFrame(TEST_INTERFACE_NAME, null,
+ mSendMgmtFrameCallback, TEST_MCS_RATE);
+
+ verify(mClientInterface, never()).SendMgmtFrame(any(), any(), anyInt());
+ verify(mSendMgmtFrameCallback).onFailure(anyInt());
+ }
+
+ /**
+ * sendMgmtFrame() should fail if an interface name that does not exist is passed in.
+ */
+ @Test
+ public void testSendMgmtFrameInvalidInterfaceName() throws Exception {
+ mWificondControl.sendMgmtFrame(TEST_INVALID_INTERFACE_NAME, TEST_PROBE_FRAME,
+ mSendMgmtFrameCallback, TEST_MCS_RATE);
+
+ verify(mClientInterface, never()).SendMgmtFrame(any(), any(), anyInt());
+ verify(mSendMgmtFrameCallback).onFailure(anyInt());
+ }
+
+ /**
+ * sendMgmtFrame() should fail if it is called a second time before the first call completed.
+ */
+ @Test
+ public void testSendMgmtFrameCalledTwiceBeforeFinished() throws Exception {
+ WifiCondManager.SendMgmtFrameCallback cb1 = mock(
+ WifiCondManager.SendMgmtFrameCallback.class);
+ WifiCondManager.SendMgmtFrameCallback cb2 = mock(
+ WifiCondManager.SendMgmtFrameCallback.class);
+
+ mWificondControl.sendMgmtFrame(TEST_INTERFACE_NAME, TEST_PROBE_FRAME, cb1, TEST_MCS_RATE);
+ verify(cb1, never()).onFailure(anyInt());
+ verify(mClientInterface, times(1))
+ .SendMgmtFrame(AdditionalMatchers.aryEq(TEST_PROBE_FRAME),
+ any(), eq(TEST_MCS_RATE));
+
+ mWificondControl.sendMgmtFrame(TEST_INTERFACE_NAME, TEST_PROBE_FRAME, cb2, TEST_MCS_RATE);
+ verify(cb2).onFailure(WifiCondManager.SEND_MGMT_FRAME_ERROR_ALREADY_STARTED);
+ // verify SendMgmtFrame() still was only called once i.e. not called again
+ verify(mClientInterface, times(1))
+ .SendMgmtFrame(any(), any(), anyInt());
+ }
+
+ /**
+ * Tests that when a RemoteException is triggered on AIDL call, onFailure() is called only once.
+ */
+ @Test
+ public void testSendMgmtFrameThrowsException() throws Exception {
+ WifiCondManager.SendMgmtFrameCallback cb = mock(
+ WifiCondManager.SendMgmtFrameCallback.class);
+
+ final ArgumentCaptor<ISendMgmtFrameEvent> sendMgmtFrameEventCaptor =
+ ArgumentCaptor.forClass(ISendMgmtFrameEvent.class);
+
+ doThrow(new RemoteException()).when(mClientInterface)
+ .SendMgmtFrame(any(), sendMgmtFrameEventCaptor.capture(), anyInt());
+
+ final ArgumentCaptor<AlarmManager.OnAlarmListener> alarmListenerCaptor =
+ ArgumentCaptor.forClass(AlarmManager.OnAlarmListener.class);
+ final ArgumentCaptor<Handler> handlerCaptor = ArgumentCaptor.forClass(Handler.class);
+ doNothing().when(mAlarmManager).set(anyInt(), anyLong(), any(),
+ alarmListenerCaptor.capture(), handlerCaptor.capture());
+
+ mWificondControl.sendMgmtFrame(TEST_INTERFACE_NAME, TEST_PROBE_FRAME,
+ cb, TEST_MCS_RATE);
+ mLooper.dispatchAll();
+
+ verify(cb).onFailure(anyInt());
+ verify(mAlarmManager).cancel(eq(alarmListenerCaptor.getValue()));
+
+ sendMgmtFrameEventCaptor.getValue().OnFailure(
+ WifiCondManager.SEND_MGMT_FRAME_ERROR_UNKNOWN);
+ mLooper.dispatchAll();
+
+ handlerCaptor.getValue().post(() -> alarmListenerCaptor.getValue().onAlarm());
+ mLooper.dispatchAll();
+
+ verifyNoMoreInteractions(cb);
+ }
+
+ /**
+ * Tests that the onAck() callback is triggered correctly.
+ */
+ @Test
+ public void testSendMgmtFrameSuccess() throws Exception {
+ WifiCondManager.SendMgmtFrameCallback cb = mock(
+ WifiCondManager.SendMgmtFrameCallback.class);
+
+ final ArgumentCaptor<ISendMgmtFrameEvent> sendMgmtFrameEventCaptor =
+ ArgumentCaptor.forClass(ISendMgmtFrameEvent.class);
+ doNothing().when(mClientInterface)
+ .SendMgmtFrame(any(), sendMgmtFrameEventCaptor.capture(), anyInt());
+ final ArgumentCaptor<AlarmManager.OnAlarmListener> alarmListenerCaptor =
+ ArgumentCaptor.forClass(AlarmManager.OnAlarmListener.class);
+ final ArgumentCaptor<Handler> handlerCaptor = ArgumentCaptor.forClass(Handler.class);
+ doNothing().when(mAlarmManager).set(anyInt(), anyLong(), any(),
+ alarmListenerCaptor.capture(), handlerCaptor.capture());
+ mWificondControl.sendMgmtFrame(TEST_INTERFACE_NAME, TEST_PROBE_FRAME, cb, TEST_MCS_RATE);
+
+ sendMgmtFrameEventCaptor.getValue().OnAck(TEST_SEND_MGMT_FRAME_ELAPSED_TIME_MS);
+ mLooper.dispatchAll();
+ verify(cb).onAck(eq(TEST_SEND_MGMT_FRAME_ELAPSED_TIME_MS));
+ verify(cb, never()).onFailure(anyInt());
+ verify(mAlarmManager).cancel(eq(alarmListenerCaptor.getValue()));
+
+ // verify that even if timeout is triggered afterwards, SendMgmtFrameCallback is not
+ // triggered again
+ handlerCaptor.getValue().post(() -> alarmListenerCaptor.getValue().onAlarm());
+ mLooper.dispatchAll();
+ verify(cb, times(1)).onAck(anyInt());
+ verify(cb, never()).onFailure(anyInt());
+ }
+
+ /**
+ * Tests that the onFailure() callback is triggered correctly.
+ */
+ @Test
+ public void testSendMgmtFrameFailure() throws Exception {
+ WifiCondManager.SendMgmtFrameCallback cb = mock(
+ WifiCondManager.SendMgmtFrameCallback.class);
+
+ final ArgumentCaptor<ISendMgmtFrameEvent> sendMgmtFrameEventCaptor =
+ ArgumentCaptor.forClass(ISendMgmtFrameEvent.class);
+ doNothing().when(mClientInterface)
+ .SendMgmtFrame(any(), sendMgmtFrameEventCaptor.capture(), anyInt());
+ final ArgumentCaptor<AlarmManager.OnAlarmListener> alarmListenerCaptor =
+ ArgumentCaptor.forClass(AlarmManager.OnAlarmListener.class);
+ final ArgumentCaptor<Handler> handlerCaptor = ArgumentCaptor.forClass(Handler.class);
+ doNothing().when(mAlarmManager).set(anyInt(), anyLong(), any(),
+ alarmListenerCaptor.capture(), handlerCaptor.capture());
+ mWificondControl.sendMgmtFrame(TEST_INTERFACE_NAME, TEST_PROBE_FRAME, cb, TEST_MCS_RATE);
+
+ sendMgmtFrameEventCaptor.getValue().OnFailure(
+ WifiCondManager.SEND_MGMT_FRAME_ERROR_UNKNOWN);
+ mLooper.dispatchAll();
+ verify(cb, never()).onAck(anyInt());
+ verify(cb).onFailure(WifiCondManager.SEND_MGMT_FRAME_ERROR_UNKNOWN);
+ verify(mAlarmManager).cancel(eq(alarmListenerCaptor.getValue()));
+
+ // verify that even if timeout is triggered afterwards, SendMgmtFrameCallback is not
+ // triggered again
+ handlerCaptor.getValue().post(() -> alarmListenerCaptor.getValue().onAlarm());
+ mLooper.dispatchAll();
+ verify(cb, never()).onAck(anyInt());
+ verify(cb, times(1)).onFailure(anyInt());
+ }
+
+ /**
+ * Tests that the onTimeout() callback is triggered correctly.
+ */
+ @Test
+ public void testSendMgmtFrameTimeout() throws Exception {
+ WifiCondManager.SendMgmtFrameCallback cb = mock(
+ WifiCondManager.SendMgmtFrameCallback.class);
+
+ final ArgumentCaptor<ISendMgmtFrameEvent> sendMgmtFrameEventCaptor =
+ ArgumentCaptor.forClass(ISendMgmtFrameEvent.class);
+ doNothing().when(mClientInterface)
+ .SendMgmtFrame(any(), sendMgmtFrameEventCaptor.capture(), anyInt());
+ final ArgumentCaptor<AlarmManager.OnAlarmListener> alarmListenerCaptor =
+ ArgumentCaptor.forClass(AlarmManager.OnAlarmListener.class);
+ final ArgumentCaptor<Handler> handlerCaptor = ArgumentCaptor.forClass(Handler.class);
+ doNothing().when(mAlarmManager).set(anyInt(), anyLong(), any(),
+ alarmListenerCaptor.capture(), handlerCaptor.capture());
+ mWificondControl.sendMgmtFrame(TEST_INTERFACE_NAME, TEST_PROBE_FRAME, cb, TEST_MCS_RATE);
+
+ handlerCaptor.getValue().post(() -> alarmListenerCaptor.getValue().onAlarm());
+ mLooper.dispatchAll();
+ verify(cb, never()).onAck(anyInt());
+ verify(cb).onFailure(WifiCondManager.SEND_MGMT_FRAME_ERROR_TIMEOUT);
+
+ // verify that even if onAck() callback is triggered after timeout,
+ // SendMgmtFrameCallback is not triggered again
+ sendMgmtFrameEventCaptor.getValue().OnAck(TEST_SEND_MGMT_FRAME_ELAPSED_TIME_MS);
+ mLooper.dispatchAll();
+ verify(cb, never()).onAck(anyInt());
+ verify(cb, times(1)).onFailure(anyInt());
+ }
+
+ /**
+ * Tests every possible test outcome followed by every other test outcome to ensure that the
+ * internal state is reset correctly between calls.
+ * i.e. (success, success), (success, failure), (success, timeout),
+ * (failure, failure), (failure, success), (failure, timeout),
+ * (timeout, timeout), (timeout, success), (timeout, failure)
+ *
+ * Also tests that internal state is reset correctly after a transient AIDL RemoteException.
+ */
+ @Test
+ public void testSendMgmtFrameMixed() throws Exception {
+ testSendMgmtFrameThrowsException();
+ testSendMgmtFrameSuccess();
+ testSendMgmtFrameSuccess();
+ testSendMgmtFrameFailure();
+ testSendMgmtFrameFailure();
+ testSendMgmtFrameTimeout();
+ testSendMgmtFrameTimeout();
+ testSendMgmtFrameSuccess();
+ testSendMgmtFrameTimeout();
+ testSendMgmtFrameFailure();
+ testSendMgmtFrameSuccess();
+ }
+
+ /**
+ * Tests that OnAck() does not perform any non-thread-safe operations on the binder thread.
+ *
+ * The sequence of instructions are:
+ * 1. post onAlarm() onto main thread
+ * 2. OnAck()
+ * 3. mLooper.dispatchAll()
+ *
+ * The actual order of execution is:
+ * 1. binder thread portion of OnAck()
+ * 2. onAlarm() (which purely executes on the main thread)
+ * 3. main thread portion of OnAck()
+ *
+ * If the binder thread portion of OnAck() is not thread-safe, it can possibly mess up
+ * onAlarm(). Tests that this does not occur.
+ */
+ @Test
+ public void testSendMgmtFrameTimeoutAckThreadSafe() throws Exception {
+ final ArgumentCaptor<ISendMgmtFrameEvent> sendMgmtFrameEventCaptor =
+ ArgumentCaptor.forClass(ISendMgmtFrameEvent.class);
+ doNothing().when(mClientInterface)
+ .SendMgmtFrame(any(), sendMgmtFrameEventCaptor.capture(), anyInt());
+ final ArgumentCaptor<AlarmManager.OnAlarmListener> alarmListenerCaptor =
+ ArgumentCaptor.forClass(AlarmManager.OnAlarmListener.class);
+ final ArgumentCaptor<Handler> handlerCaptor = ArgumentCaptor.forClass(Handler.class);
+ doNothing().when(mAlarmManager).set(anyInt(), anyLong(), any(),
+ alarmListenerCaptor.capture(), handlerCaptor.capture());
+ mWificondControl.sendMgmtFrame(TEST_INTERFACE_NAME, TEST_PROBE_FRAME,
+ mSendMgmtFrameCallback, TEST_MCS_RATE);
+
+ // AlarmManager should post the onAlarm() callback onto the handler, but since we are
+ // triggering onAlarm() ourselves during the test, manually post onto handler
+ handlerCaptor.getValue().post(() -> alarmListenerCaptor.getValue().onAlarm());
+ // OnAck posts to the handler
+ sendMgmtFrameEventCaptor.getValue().OnAck(TEST_SEND_MGMT_FRAME_ELAPSED_TIME_MS);
+ mLooper.dispatchAll();
+ verify(mSendMgmtFrameCallback, never()).onAck(anyInt());
+ verify(mSendMgmtFrameCallback).onFailure(WifiCondManager.SEND_MGMT_FRAME_ERROR_TIMEOUT);
+ }
+
+ /**
+ * See {@link #testSendMgmtFrameTimeoutAckThreadSafe()}. This test replaces OnAck() with
+ * OnFailure().
+ */
+ @Test
+ public void testSendMgmtFrameTimeoutFailureThreadSafe() throws Exception {
+ final ArgumentCaptor<ISendMgmtFrameEvent> sendMgmtFrameEventCaptor =
+ ArgumentCaptor.forClass(ISendMgmtFrameEvent.class);
+ doNothing().when(mClientInterface)
+ .SendMgmtFrame(any(), sendMgmtFrameEventCaptor.capture(), anyInt());
+ final ArgumentCaptor<AlarmManager.OnAlarmListener> alarmListenerCaptor =
+ ArgumentCaptor.forClass(AlarmManager.OnAlarmListener.class);
+ final ArgumentCaptor<Handler> handlerCaptor = ArgumentCaptor.forClass(Handler.class);
+ doNothing().when(mAlarmManager).set(anyInt(), anyLong(), any(),
+ alarmListenerCaptor.capture(), handlerCaptor.capture());
+ mWificondControl.sendMgmtFrame(TEST_INTERFACE_NAME, TEST_PROBE_FRAME,
+ mSendMgmtFrameCallback, TEST_MCS_RATE);
+
+ // AlarmManager should post the onAlarm() callback onto the handler, but since we are
+ // triggering onAlarm() ourselves during the test, manually post onto handler
+ handlerCaptor.getValue().post(() -> alarmListenerCaptor.getValue().onAlarm());
+ // OnFailure posts to the handler
+ sendMgmtFrameEventCaptor.getValue().OnFailure(
+ WifiCondManager.SEND_MGMT_FRAME_ERROR_UNKNOWN);
+ mLooper.dispatchAll();
+ verify(mSendMgmtFrameCallback).onFailure(WifiCondManager.SEND_MGMT_FRAME_ERROR_TIMEOUT);
+ }
+
+ // Create a ArgumentMatcher which captures a SingleScanSettings parameter and checks if it
+ // matches the provided frequency set and ssid set.
+ private class ScanMatcher implements ArgumentMatcher<SingleScanSettings> {
+ int mExpectedScanType;
+ private final Set<Integer> mExpectedFreqs;
+ private final List<byte[]> mExpectedSsids;
+
+ ScanMatcher(int expectedScanType, Set<Integer> expectedFreqs, List<byte[]> expectedSsids) {
+ this.mExpectedScanType = expectedScanType;
+ this.mExpectedFreqs = expectedFreqs;
+ this.mExpectedSsids = expectedSsids;
+ }
+
+ @Override
+ public boolean matches(SingleScanSettings settings) {
+ if (settings.scanType != mExpectedScanType) {
+ return false;
+ }
+ ArrayList<ChannelSettings> channelSettings = settings.channelSettings;
+ ArrayList<HiddenNetwork> hiddenNetworks = settings.hiddenNetworks;
+ if (mExpectedFreqs != null) {
+ Set<Integer> freqSet = new HashSet<Integer>();
+ for (ChannelSettings channel : channelSettings) {
+ freqSet.add(channel.frequency);
+ }
+ if (!mExpectedFreqs.equals(freqSet)) {
+ return false;
+ }
+ } else {
+ if (channelSettings != null && channelSettings.size() > 0) {
+ return false;
+ }
+ }
+
+ if (mExpectedSsids != null) {
+ List<byte[]> ssidSet = new ArrayList<>();
+ for (HiddenNetwork network : hiddenNetworks) {
+ ssidSet.add(network.ssid);
+ }
+ if (!mExpectedSsids.equals(ssidSet)) {
+ return false;
+ }
+
+ } else {
+ if (hiddenNetworks != null && hiddenNetworks.size() > 0) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ return "ScanMatcher{mExpectedFreqs=" + mExpectedFreqs
+ + ", mExpectedSsids=" + mExpectedSsids + '}';
+ }
+ }
+
+ // Create a ArgumentMatcher which captures a PnoSettings parameter and checks if it
+ // matches the WifiNative.PnoSettings;
+ private class PnoScanMatcher implements ArgumentMatcher<PnoSettings> {
+ private final PnoSettings mExpectedPnoSettings;
+
+ PnoScanMatcher(PnoSettings expectedPnoSettings) {
+ this.mExpectedPnoSettings = expectedPnoSettings;
+ }
+
+ @Override
+ public boolean matches(PnoSettings settings) {
+ if (mExpectedPnoSettings == null) {
+ return false;
+ }
+ if (settings.intervalMs != mExpectedPnoSettings.intervalMs
+ || settings.min2gRssi != mExpectedPnoSettings.min2gRssi
+ || settings.min5gRssi != mExpectedPnoSettings.min5gRssi
+ || settings.min6gRssi != mExpectedPnoSettings.min6gRssi) {
+ return false;
+ }
+ if (settings.pnoNetworks == null || mExpectedPnoSettings.pnoNetworks == null) {
+ return false;
+ }
+ if (settings.pnoNetworks.size() != mExpectedPnoSettings.pnoNetworks.size()) {
+ return false;
+ }
+
+ for (int i = 0; i < settings.pnoNetworks.size(); i++) {
+ if (!Arrays.equals(settings.pnoNetworks.get(i).ssid,
+ mExpectedPnoSettings.pnoNetworks.get(i).ssid)) {
+ return false;
+ }
+ if (settings.pnoNetworks.get(i).isHidden != mExpectedPnoSettings.pnoNetworks.get(
+ i).isHidden) {
+ return false;
+ }
+ if (!Arrays.equals(settings.pnoNetworks.get(i).frequencies,
+ mExpectedPnoSettings.pnoNetworks.get(i).frequencies)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ return "PnoScanMatcher{" + "mExpectedPnoSettings=" + mExpectedPnoSettings + '}';
+ }
+ }
+
+ private static class LocalNativeUtil {
+ private static final int SSID_BYTES_MAX_LEN = 32;
+
+ /**
+ * Converts an ArrayList<Byte> of UTF_8 byte values to string.
+ * The string will either be:
+ * a) UTF-8 String encapsulated in quotes (if all the bytes are UTF-8 encodeable and non
+ * null),
+ * or
+ * b) Hex string with no delimiters.
+ *
+ * @param bytes List of bytes for ssid.
+ * @throws IllegalArgumentException for null bytes.
+ */
+ public static String bytesToHexOrQuotedString(ArrayList<Byte> bytes) {
+ if (bytes == null) {
+ throw new IllegalArgumentException("null ssid bytes");
+ }
+ byte[] byteArray = byteArrayFromArrayList(bytes);
+ // Check for 0's in the byte stream in which case we cannot convert this into a string.
+ if (!bytes.contains(Byte.valueOf((byte) 0))) {
+ CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
+ try {
+ CharBuffer decoded = decoder.decode(ByteBuffer.wrap(byteArray));
+ return "\"" + decoded.toString() + "\"";
+ } catch (CharacterCodingException cce) {
+ }
+ }
+ return hexStringFromByteArray(byteArray);
+ }
+
+ /**
+ * Converts an ssid string to an arraylist of UTF_8 byte values.
+ * These forms are acceptable:
+ * a) UTF-8 String encapsulated in quotes, or
+ * b) Hex string with no delimiters.
+ *
+ * @param ssidStr String to be converted.
+ * @throws IllegalArgumentException for null string.
+ */
+ public static ArrayList<Byte> decodeSsid(String ssidStr) {
+ ArrayList<Byte> ssidBytes = hexOrQuotedStringToBytes(ssidStr);
+ if (ssidBytes.size() > SSID_BYTES_MAX_LEN) {
+ throw new IllegalArgumentException(
+ "ssid bytes size out of range: " + ssidBytes.size());
+ }
+ return ssidBytes;
+ }
+
+ /**
+ * Convert from an array list of Byte to an array of primitive bytes.
+ */
+ public static byte[] byteArrayFromArrayList(ArrayList<Byte> bytes) {
+ byte[] byteArray = new byte[bytes.size()];
+ int i = 0;
+ for (Byte b : bytes) {
+ byteArray[i++] = b;
+ }
+ return byteArray;
+ }
+
+ /**
+ * Converts a byte array to hex string.
+ *
+ * @param bytes List of bytes for ssid.
+ * @throws IllegalArgumentException for null bytes.
+ */
+ public static String hexStringFromByteArray(byte[] bytes) {
+ if (bytes == null) {
+ throw new IllegalArgumentException("null hex bytes");
+ }
+ return new String(HexEncoding.encode(bytes)).toLowerCase();
+ }
+
+ /**
+ * Converts an string to an arraylist of UTF_8 byte values.
+ * These forms are acceptable:
+ * a) UTF-8 String encapsulated in quotes, or
+ * b) Hex string with no delimiters.
+ *
+ * @param str String to be converted.
+ * @throws IllegalArgumentException for null string.
+ */
+ public static ArrayList<Byte> hexOrQuotedStringToBytes(String str) {
+ if (str == null) {
+ throw new IllegalArgumentException("null string");
+ }
+ int length = str.length();
+ if ((length > 1) && (str.charAt(0) == '"') && (str.charAt(length - 1) == '"')) {
+ str = str.substring(1, str.length() - 1);
+ return stringToByteArrayList(str);
+ } else {
+ return byteArrayToArrayList(hexStringToByteArray(str));
+ }
+ }
+
+ /**
+ * Convert the string to byte array list.
+ *
+ * @return the UTF_8 char byte values of str, as an ArrayList.
+ * @throws IllegalArgumentException if a null or unencodable string is sent.
+ */
+ public static ArrayList<Byte> stringToByteArrayList(String str) {
+ if (str == null) {
+ throw new IllegalArgumentException("null string");
+ }
+ // Ensure that the provided string is UTF_8 encoded.
+ CharsetEncoder encoder = StandardCharsets.UTF_8.newEncoder();
+ try {
+ ByteBuffer encoded = encoder.encode(CharBuffer.wrap(str));
+ byte[] byteArray = new byte[encoded.remaining()];
+ encoded.get(byteArray);
+ return byteArrayToArrayList(byteArray);
+ } catch (CharacterCodingException cce) {
+ throw new IllegalArgumentException("cannot be utf-8 encoded", cce);
+ }
+ }
+
+ /**
+ * Convert from an array of primitive bytes to an array list of Byte.
+ */
+ public static ArrayList<Byte> byteArrayToArrayList(byte[] bytes) {
+ ArrayList<Byte> byteList = new ArrayList<>();
+ for (Byte b : bytes) {
+ byteList.add(b);
+ }
+ return byteList;
+ }
+
+ /**
+ * Converts a hex string to byte array.
+ *
+ * @param hexStr String to be converted.
+ * @throws IllegalArgumentException for null string.
+ */
+ public static byte[] hexStringToByteArray(String hexStr) {
+ if (hexStr == null) {
+ throw new IllegalArgumentException("null hex string");
+ }
+ return HexEncoding.decode(hexStr.toCharArray(), false);
+ }
+ }
+}
diff --git a/wifi/tests/src/android/net/wifi/WifiConfigurationTest.java b/wifi/tests/src/android/net/wifi/WifiConfigurationTest.java
index 7e38e147427f..5d6549ed5f13 100644
--- a/wifi/tests/src/android/net/wifi/WifiConfigurationTest.java
+++ b/wifi/tests/src/android/net/wifi/WifiConfigurationTest.java
@@ -32,9 +32,6 @@ import androidx.test.filters.SmallTest;
import org.junit.Before;
import org.junit.Test;
-import java.io.ByteArrayInputStream;
-import java.io.DataInputStream;
-
/**
* Unit tests for {@link android.net.wifi.WifiConfiguration}.
*/
@@ -196,33 +193,6 @@ public class WifiConfigurationTest {
}
/**
- * Verifies that the serialization/de-serialization for softap config works.
- */
- @Test
- public void testSoftApConfigBackupAndRestore() throws Exception {
- WifiConfiguration config = new WifiConfiguration();
- config.SSID = "TestAP";
- config.apBand = WifiConfiguration.AP_BAND_5GHZ;
- config.apChannel = 40;
- config.allowedKeyManagement.set(KeyMgmt.WPA2_PSK);
- config.preSharedKey = "TestPsk";
- config.hiddenSSID = true;
-
- byte[] data = config.getBytesForBackup();
- ByteArrayInputStream bais = new ByteArrayInputStream(data);
- DataInputStream in = new DataInputStream(bais);
- WifiConfiguration restoredConfig = WifiConfiguration.getWifiConfigFromBackup(in);
-
- assertEquals(config.SSID, restoredConfig.SSID);
- assertEquals(config.preSharedKey, restoredConfig.preSharedKey);
- assertEquals(config.getAuthType(), restoredConfig.getAuthType());
- assertEquals(config.apBand, restoredConfig.apBand);
- assertEquals(config.apChannel, restoredConfig.apChannel);
- assertEquals(config.hiddenSSID, restoredConfig.hiddenSSID);
- }
-
-
- /**
* Verifies that getKeyIdForCredentials returns the expected string for Enterprise networks
* @throws Exception
*/
@@ -317,6 +287,16 @@ public class WifiConfigurationTest {
config.allowedKeyManagement.clear();
config.allowedKeyManagement.set(KeyMgmt.NONE);
assertEquals(mSsid + KeyMgmt.strings[KeyMgmt.NONE], config.getSsidAndSecurityTypeString());
+
+ config.allowedKeyManagement.clear();
+ config.allowedKeyManagement.set(KeyMgmt.WAPI_PSK);
+ assertEquals(mSsid + KeyMgmt.strings[KeyMgmt.WAPI_PSK],
+ config.getSsidAndSecurityTypeString());
+
+ config.allowedKeyManagement.clear();
+ config.allowedKeyManagement.set(KeyMgmt.WAPI_CERT);
+ assertEquals(mSsid + KeyMgmt.strings[KeyMgmt.WAPI_CERT],
+ config.getSsidAndSecurityTypeString());
}
/**
diff --git a/wifi/tests/src/android/net/wifi/WifiManagerTest.java b/wifi/tests/src/android/net/wifi/WifiManagerTest.java
index f92d38c982b8..4a46744a2d32 100644
--- a/wifi/tests/src/android/net/wifi/WifiManagerTest.java
+++ b/wifi/tests/src/android/net/wifi/WifiManagerTest.java
@@ -1696,8 +1696,6 @@ public class WifiManagerTest {
assertTrue(mWifiManager.isPasspointSupported());
assertTrue(mWifiManager.isP2pSupported());
assertFalse(mWifiManager.isPortableHotspotSupported());
- assertFalse(mWifiManager.is5GHzBandSupported());
- assertFalse(mWifiManager.is6GHzBandSupported());
assertFalse(mWifiManager.isDeviceToDeviceRttSupported());
assertFalse(mWifiManager.isDeviceToApRttSupported());
assertFalse(mWifiManager.isPreferredNetworkOffloadSupported());
@@ -1782,13 +1780,23 @@ public class WifiManagerTest {
}
/**
- * Test behavior of {@link WifiManager#isDualBandSupported()}
+ * Test behavior of {@link WifiManager#is5GHzBandSupported()}
*/
@Test
- public void testIsDualBandSupported() throws Exception {
- when(mWifiService.isDualBandSupported()).thenReturn(true);
- assertTrue(mWifiManager.isDualBandSupported());
- verify(mWifiService).isDualBandSupported();
+ public void testIs5GHzBandSupported() throws Exception {
+ when(mWifiService.is5GHzBandSupported()).thenReturn(true);
+ assertTrue(mWifiManager.is5GHzBandSupported());
+ verify(mWifiService).is5GHzBandSupported();
+ }
+
+ /**
+ * Test behavior of {@link WifiManager#is6GHzBandSupported()}
+ */
+ @Test
+ public void testIs6GHzBandSupported() throws Exception {
+ when(mWifiService.is6GHzBandSupported()).thenReturn(true);
+ assertTrue(mWifiManager.is6GHzBandSupported());
+ verify(mWifiService).is6GHzBandSupported();
}
/**
@@ -2067,4 +2075,18 @@ public class WifiManagerTest {
verify(mWifiService).calculateSignalLevel(Integer.MAX_VALUE);
assertEquals(4, actual);
}
+
+ /*
+ * Test behavior of isWapiSupported
+ * @throws Exception
+ */
+ @Test
+ public void testIsWapiSupported() throws Exception {
+ when(mWifiService.getSupportedFeatures())
+ .thenReturn(new Long(WifiManager.WIFI_FEATURE_WAPI));
+ assertTrue(mWifiManager.isWapiSupported());
+ when(mWifiService.getSupportedFeatures())
+ .thenReturn(new Long(~WifiManager.WIFI_FEATURE_WAPI));
+ assertFalse(mWifiManager.isWapiSupported());
+ }
}
diff --git a/wifi/tests/src/android/net/wifi/WifiNetworkSuggestionTest.java b/wifi/tests/src/android/net/wifi/WifiNetworkSuggestionTest.java
index 04aaa0bbcad0..4cdc4bc2ad48 100644
--- a/wifi/tests/src/android/net/wifi/WifiNetworkSuggestionTest.java
+++ b/wifi/tests/src/android/net/wifi/WifiNetworkSuggestionTest.java
@@ -39,6 +39,7 @@ public class WifiNetworkSuggestionTest {
private static final String TEST_SSID_1 = "\"Test1234\"";
private static final String TEST_PRESHARED_KEY = "Test123";
private static final String TEST_FQDN = "fqdn";
+ private static final String TEST_WAPI_CERT_SUITE = "suite";
/**
* Validate correctness of WifiNetworkSuggestion object created by
@@ -194,6 +195,87 @@ public class WifiNetworkSuggestionTest {
/**
* Validate correctness of WifiNetworkSuggestion object created by
+ * {@link WifiNetworkSuggestion.Builder#build()} for WAPI-PSK network.
+ */
+ @Test
+ public void testWifiNetworkSuggestionBuilderForWapiPskNetwork() {
+ WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder()
+ .setSsid(TEST_SSID)
+ .setWapiPassphrase(TEST_PRESHARED_KEY)
+ .build();
+
+ assertEquals("\"" + TEST_SSID + "\"", suggestion.wifiConfiguration.SSID);
+ assertTrue(suggestion.wifiConfiguration.allowedKeyManagement
+ .get(WifiConfiguration.KeyMgmt.WAPI_PSK));
+ assertTrue(suggestion.wifiConfiguration.allowedPairwiseCiphers
+ .get(WifiConfiguration.PairwiseCipher.SMS4));
+ assertTrue(suggestion.wifiConfiguration.allowedGroupCiphers
+ .get(WifiConfiguration.GroupCipher.SMS4));
+ assertEquals("\"" + TEST_PRESHARED_KEY + "\"",
+ suggestion.wifiConfiguration.preSharedKey);
+ }
+
+
+ /**
+ * Validate correctness of WifiNetworkSuggestion object created by
+ * {@link WifiNetworkSuggestion.Builder#build()} for WAPI-CERT network.
+ */
+ @Test
+ public void testWifiNetworkSuggestionBuilderForWapiCertNetwork() {
+ WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
+ enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.WAPI_CERT);
+ enterpriseConfig.setWapiCertSuite(TEST_WAPI_CERT_SUITE);
+ WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder()
+ .setSsid(TEST_SSID)
+ .setWapiEnterpriseConfig(enterpriseConfig)
+ .build();
+
+ assertEquals("\"" + TEST_SSID + "\"", suggestion.wifiConfiguration.SSID);
+ assertTrue(suggestion.wifiConfiguration.allowedKeyManagement
+ .get(WifiConfiguration.KeyMgmt.WAPI_CERT));
+ assertTrue(suggestion.wifiConfiguration.allowedPairwiseCiphers
+ .get(WifiConfiguration.PairwiseCipher.SMS4));
+ assertTrue(suggestion.wifiConfiguration.allowedGroupCiphers
+ .get(WifiConfiguration.GroupCipher.SMS4));
+ assertNull(suggestion.wifiConfiguration.preSharedKey);
+ assertNotNull(suggestion.wifiConfiguration.enterpriseConfig);
+ assertEquals(WifiEnterpriseConfig.Eap.WAPI_CERT,
+ suggestion.wifiConfiguration.enterpriseConfig.getEapMethod());
+ assertEquals(TEST_WAPI_CERT_SUITE,
+ suggestion.wifiConfiguration.enterpriseConfig.getWapiCertSuite());
+ }
+
+ /**
+ * Validate correctness of WifiNetworkSuggestion object created by
+ * {@link WifiNetworkSuggestion.Builder#build()} for WAPI-CERT network
+ * which selects the certificate suite automatically.
+ */
+ @Test
+ public void testWifiNetworkSuggestionBuilderForWapiCertAutoNetwork() {
+ WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
+ enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.WAPI_CERT);
+ WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder()
+ .setSsid(TEST_SSID)
+ .setWapiEnterpriseConfig(enterpriseConfig)
+ .build();
+
+ assertEquals("\"" + TEST_SSID + "\"", suggestion.wifiConfiguration.SSID);
+ assertTrue(suggestion.wifiConfiguration.allowedKeyManagement
+ .get(WifiConfiguration.KeyMgmt.WAPI_CERT));
+ assertTrue(suggestion.wifiConfiguration.allowedPairwiseCiphers
+ .get(WifiConfiguration.PairwiseCipher.SMS4));
+ assertTrue(suggestion.wifiConfiguration.allowedGroupCiphers
+ .get(WifiConfiguration.GroupCipher.SMS4));
+ assertNull(suggestion.wifiConfiguration.preSharedKey);
+ assertNotNull(suggestion.wifiConfiguration.enterpriseConfig);
+ assertEquals(WifiEnterpriseConfig.Eap.WAPI_CERT,
+ suggestion.wifiConfiguration.enterpriseConfig.getEapMethod());
+ assertEquals("",
+ suggestion.wifiConfiguration.enterpriseConfig.getWapiCertSuite());
+ }
+
+ /**
+ * Validate correctness of WifiNetworkSuggestion object created by
* {@link WifiNetworkSuggestion.Builder#build()} for Passpoint network which requires
* app interaction and metered.
*/
diff --git a/wifi/tests/src/android/net/wifi/wificond/NativeScanResultTest.java b/wifi/tests/src/android/net/wifi/wificond/NativeScanResultTest.java
new file mode 100644
index 000000000000..06f12f7f37ea
--- /dev/null
+++ b/wifi/tests/src/android/net/wifi/wificond/NativeScanResultTest.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2017 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.net.wifi.wificond;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import android.os.Parcel;
+
+import androidx.test.filters.SmallTest;
+
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.BitSet;
+
+/**
+ * Unit tests for {@link android.net.wifi.wificond.NativeScanResult}.
+ */
+@SmallTest
+public class NativeScanResultTest {
+
+ private static final byte[] TEST_SSID =
+ new byte[] {'G', 'o', 'o', 'g', 'l', 'e', 'G', 'u', 'e', 's', 't'};
+ private static final byte[] TEST_BSSID =
+ new byte[] {(byte) 0x12, (byte) 0xef, (byte) 0xa1,
+ (byte) 0x2c, (byte) 0x97, (byte) 0x8b};
+ private static final byte[] TEST_INFO_ELEMENT =
+ new byte[] {(byte) 0x01, (byte) 0x03, (byte) 0x12, (byte) 0xbe, (byte) 0xff};
+ private static final int TEST_FREQUENCY = 2456;
+ private static final int TEST_SIGNAL_MBM = -45;
+ private static final long TEST_TSF = 34455441;
+ private static final BitSet TEST_CAPABILITY = new BitSet(16) {{ set(2); set(5); }};
+ private static final boolean TEST_ASSOCIATED = true;
+ private static final int[] RADIO_CHAIN_IDS = { 0, 1 };
+ private static final int[] RADIO_CHAIN_LEVELS = { -56, -65 };
+
+ /**
+ * NativeScanResult object can be serialized and deserialized, while keeping the
+ * values unchanged.
+ */
+ @Test
+ public void canSerializeAndDeserialize() {
+ NativeScanResult scanResult = new NativeScanResult();
+ scanResult.ssid = TEST_SSID;
+ scanResult.bssid = TEST_BSSID;
+ scanResult.infoElement = TEST_INFO_ELEMENT;
+ scanResult.frequency = TEST_FREQUENCY;
+ scanResult.signalMbm = TEST_SIGNAL_MBM;
+ scanResult.tsf = TEST_TSF;
+ scanResult.capability = TEST_CAPABILITY;
+ scanResult.associated = TEST_ASSOCIATED;
+ scanResult.radioChainInfos = new ArrayList<>(Arrays.asList(
+ new RadioChainInfo(RADIO_CHAIN_IDS[0], RADIO_CHAIN_LEVELS[0]),
+ new RadioChainInfo(RADIO_CHAIN_IDS[1], RADIO_CHAIN_LEVELS[1])));
+ Parcel parcel = Parcel.obtain();
+ scanResult.writeToParcel(parcel, 0);
+ // Rewind the pointer to the head of the parcel.
+ parcel.setDataPosition(0);
+ NativeScanResult scanResultDeserialized = NativeScanResult.CREATOR.createFromParcel(parcel);
+
+ assertArrayEquals(scanResult.ssid, scanResultDeserialized.ssid);
+ assertArrayEquals(scanResult.bssid, scanResultDeserialized.bssid);
+ assertArrayEquals(scanResult.infoElement, scanResultDeserialized.infoElement);
+ assertEquals(scanResult.frequency, scanResultDeserialized.frequency);
+ assertEquals(scanResult.signalMbm, scanResultDeserialized.signalMbm);
+ assertEquals(scanResult.tsf, scanResultDeserialized.tsf);
+ assertEquals(scanResult.capability, scanResultDeserialized.capability);
+ assertEquals(scanResult.associated, scanResultDeserialized.associated);
+ assertTrue(scanResult.radioChainInfos.containsAll(scanResultDeserialized.radioChainInfos));
+ }
+}
diff --git a/wifi/tests/src/android/net/wifi/wificond/PnoSettingsTest.java b/wifi/tests/src/android/net/wifi/wificond/PnoSettingsTest.java
new file mode 100644
index 000000000000..775acc70d134
--- /dev/null
+++ b/wifi/tests/src/android/net/wifi/wificond/PnoSettingsTest.java
@@ -0,0 +1,112 @@
+/*
+ * Copyright (C) 2017 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.net.wifi.wificond;
+
+import static org.junit.Assert.assertEquals;
+
+import android.os.Parcel;
+
+import androidx.test.filters.SmallTest;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+
+/**
+ * Unit tests for {@link android.net.wifi.wificond.PnoSettingsResult}.
+ */
+@SmallTest
+public class PnoSettingsTest {
+
+ private static final byte[] TEST_SSID_1 =
+ new byte[] {'G', 'o', 'o', 'g', 'l', 'e', 'G', 'u', 'e', 's', 't'};
+ private static final byte[] TEST_SSID_2 =
+ new byte[] {'A', 'n', 'd', 'r', 'o', 'i', 'd', 'T', 'e', 's', 't'};
+ private static final int[] TEST_FREQUENCIES_1 = {};
+ private static final int[] TEST_FREQUENCIES_2 = {2500, 5124};
+ private static final int TEST_INTERVAL_MS = 30000;
+ private static final int TEST_MIN_2G_RSSI = -60;
+ private static final int TEST_MIN_5G_RSSI = -65;
+ private static final int TEST_VALUE = 42;
+
+ private PnoNetwork mPnoNetwork1;
+ private PnoNetwork mPnoNetwork2;
+
+ @Before
+ public void setUp() {
+ mPnoNetwork1 = new PnoNetwork();
+ mPnoNetwork1.ssid = TEST_SSID_1;
+ mPnoNetwork1.isHidden = true;
+ mPnoNetwork1.frequencies = TEST_FREQUENCIES_1;
+
+ mPnoNetwork2 = new PnoNetwork();
+ mPnoNetwork2.ssid = TEST_SSID_2;
+ mPnoNetwork2.isHidden = false;
+ mPnoNetwork2.frequencies = TEST_FREQUENCIES_2;
+ }
+
+ /**
+ * PnoSettings object can be serialized and deserialized, while keeping the
+ * values unchanged.
+ */
+ @Test
+ public void canSerializeAndDeserialize() {
+ PnoSettings pnoSettings = new PnoSettings();
+ pnoSettings.intervalMs = TEST_INTERVAL_MS;
+ pnoSettings.min2gRssi = TEST_MIN_2G_RSSI;
+ pnoSettings.min5gRssi = TEST_MIN_5G_RSSI;
+ pnoSettings.pnoNetworks = new ArrayList<>(Arrays.asList(mPnoNetwork1, mPnoNetwork2));
+
+ Parcel parcel = Parcel.obtain();
+ pnoSettings.writeToParcel(parcel, 0);
+ // Rewind the pointer to the head of the parcel.
+ parcel.setDataPosition(0);
+ PnoSettings pnoSettingsDeserialized = PnoSettings.CREATOR.createFromParcel(parcel);
+
+ assertEquals(pnoSettings, pnoSettingsDeserialized);
+ assertEquals(pnoSettings.hashCode(), pnoSettingsDeserialized.hashCode());
+ }
+
+ /**
+ * Tests usage of {@link PnoSettings} as a HashMap key type.
+ */
+ @Test
+ public void testAsHashMapKey() {
+ PnoSettings pnoSettings1 = new PnoSettings();
+ pnoSettings1.intervalMs = TEST_INTERVAL_MS;
+ pnoSettings1.min2gRssi = TEST_MIN_2G_RSSI;
+ pnoSettings1.min5gRssi = TEST_MIN_5G_RSSI;
+ pnoSettings1.pnoNetworks = new ArrayList<>(Arrays.asList(mPnoNetwork1, mPnoNetwork2));
+
+ PnoSettings pnoSettings2 = new PnoSettings();
+ pnoSettings2.intervalMs = TEST_INTERVAL_MS;
+ pnoSettings2.min2gRssi = TEST_MIN_2G_RSSI;
+ pnoSettings2.min5gRssi = TEST_MIN_5G_RSSI;
+ pnoSettings2.pnoNetworks = new ArrayList<>(Arrays.asList(mPnoNetwork1, mPnoNetwork2));
+
+ assertEquals(pnoSettings1, pnoSettings2);
+ assertEquals(pnoSettings1.hashCode(), pnoSettings2.hashCode());
+
+ HashMap<PnoSettings, Integer> map = new HashMap<>();
+ map.put(pnoSettings1, TEST_VALUE);
+
+ assertEquals(TEST_VALUE, map.get(pnoSettings2).intValue());
+ }
+}
diff --git a/wifi/tests/src/android/net/wifi/wificond/SingleScanSettingsTest.java b/wifi/tests/src/android/net/wifi/wificond/SingleScanSettingsTest.java
new file mode 100644
index 000000000000..ef598397c12e
--- /dev/null
+++ b/wifi/tests/src/android/net/wifi/wificond/SingleScanSettingsTest.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2017 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.net.wifi.wificond;
+
+import static org.junit.Assert.assertEquals;
+
+import android.net.wifi.IWifiScannerImpl;
+import android.os.Parcel;
+
+import androidx.test.filters.SmallTest;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+
+/**
+ * Unit tests for {@link android.net.wifi.wificond.SingleScanSettingsResult}.
+ */
+@SmallTest
+public class SingleScanSettingsTest {
+
+ private static final byte[] TEST_SSID_1 =
+ new byte[] {'G', 'o', 'o', 'g', 'l', 'e', 'G', 'u', 'e', 's', 't'};
+ private static final byte[] TEST_SSID_2 =
+ new byte[] {'A', 'n', 'd', 'r', 'o', 'i', 'd', 'T', 'e', 's', 't'};
+ private static final int TEST_FREQUENCY_1 = 2456;
+ private static final int TEST_FREQUENCY_2 = 5215;
+ private static final int TEST_VALUE = 42;
+
+ private ChannelSettings mChannelSettings1;
+ private ChannelSettings mChannelSettings2;
+ private HiddenNetwork mHiddenNetwork1;
+ private HiddenNetwork mHiddenNetwork2;
+
+ @Before
+ public void setUp() {
+ mChannelSettings1 = new ChannelSettings();
+ mChannelSettings1.frequency = TEST_FREQUENCY_1;
+ mChannelSettings2 = new ChannelSettings();
+ mChannelSettings2.frequency = TEST_FREQUENCY_2;
+
+ mHiddenNetwork1 = new HiddenNetwork();
+ mHiddenNetwork1.ssid = TEST_SSID_1;
+ mHiddenNetwork2 = new HiddenNetwork();
+ mHiddenNetwork2.ssid = TEST_SSID_2;
+ }
+
+ /**
+ * SingleScanSettings object can be serialized and deserialized, while keeping the
+ * values unchanged.
+ */
+ @Test
+ public void canSerializeAndDeserialize() {
+ SingleScanSettings scanSettings = new SingleScanSettings();
+ scanSettings.scanType = IWifiScannerImpl.SCAN_TYPE_HIGH_ACCURACY;
+
+ scanSettings.channelSettings =
+ new ArrayList<>(Arrays.asList(mChannelSettings1, mChannelSettings2));
+ scanSettings.hiddenNetworks =
+ new ArrayList<>(Arrays.asList(mHiddenNetwork1, mHiddenNetwork2));
+
+ Parcel parcel = Parcel.obtain();
+ scanSettings.writeToParcel(parcel, 0);
+ // Rewind the pointer to the head of the parcel.
+ parcel.setDataPosition(0);
+ SingleScanSettings scanSettingsDeserialized =
+ SingleScanSettings.CREATOR.createFromParcel(parcel);
+
+ assertEquals(scanSettings, scanSettingsDeserialized);
+ assertEquals(scanSettings.hashCode(), scanSettingsDeserialized.hashCode());
+ }
+
+ /**
+ * Tests usage of {@link SingleScanSettings} as a HashMap key type.
+ */
+ @Test
+ public void testAsHashMapKey() {
+ SingleScanSettings scanSettings1 = new SingleScanSettings();
+ scanSettings1.scanType = IWifiScannerImpl.SCAN_TYPE_HIGH_ACCURACY;
+ scanSettings1.channelSettings =
+ new ArrayList<>(Arrays.asList(mChannelSettings1, mChannelSettings2));
+ scanSettings1.hiddenNetworks =
+ new ArrayList<>(Arrays.asList(mHiddenNetwork1, mHiddenNetwork2));
+
+ SingleScanSettings scanSettings2 = new SingleScanSettings();
+ scanSettings2.scanType = IWifiScannerImpl.SCAN_TYPE_HIGH_ACCURACY;
+ scanSettings2.channelSettings =
+ new ArrayList<>(Arrays.asList(mChannelSettings1, mChannelSettings2));
+ scanSettings2.hiddenNetworks =
+ new ArrayList<>(Arrays.asList(mHiddenNetwork1, mHiddenNetwork2));
+
+ assertEquals(scanSettings1, scanSettings2);
+ assertEquals(scanSettings1.hashCode(), scanSettings2.hashCode());
+
+ HashMap<SingleScanSettings, Integer> map = new HashMap<>();
+ map.put(scanSettings1, TEST_VALUE);
+
+ assertEquals(TEST_VALUE, map.get(scanSettings2).intValue());
+ }
+}