diff options
author | Elliot Sisteron <elliotsisteron@google.com> | 2023-06-09 12:28:54 +0000 |
---|---|---|
committer | Elliot Sisteron <elliotsisteron@google.com> | 2023-06-13 14:28:36 +0000 |
commit | e647f2e32eed00d27ffee869b3cddb1c5ebfe6c5 (patch) | |
tree | 4fe84a11c6108e58222d6569d074f7ada462f86a | |
parent | 76e26acf61b2df5797062e30abf093809e00afef (diff) | |
download | Permission-e647f2e32eed00d27ffee869b3cddb1c5ebfe6c5.tar.gz |
Rename SafetyCenterResourcesContext to SafetyCenterResourcesApk.
It's not really a Context anymore.
Bug: 283100177
Test: atest CtsSafetyCenterTestCases
Relnote: N/A
Change-Id: Iab9d28440f10c02a5e1a90fd0fbb95c53ab6b383
25 files changed, 1168 insertions, 1032 deletions
diff --git a/PermissionController/src/com/android/permissioncontroller/permission/utils/KotlinUtils.kt b/PermissionController/src/com/android/permissioncontroller/permission/utils/KotlinUtils.kt index f9345ef58..49a35cadf 100644 --- a/PermissionController/src/com/android/permissioncontroller/permission/utils/KotlinUtils.kt +++ b/PermissionController/src/com/android/permissioncontroller/permission/utils/KotlinUtils.kt @@ -86,7 +86,7 @@ import com.android.permissioncontroller.permission.model.livedatatypes.LightPerm import com.android.permissioncontroller.permission.model.livedatatypes.PermState import com.android.permissioncontroller.permission.service.LocationAccessCheck import com.android.permissioncontroller.permission.ui.handheld.SettingsWithLargeHeader -import com.android.safetycenter.resources.SafetyCenterResourcesContext +import com.android.safetycenter.resources.SafetyCenterResourcesApk import java.time.Duration import java.util.concurrent.atomic.AtomicReference import kotlin.coroutines.Continuation @@ -106,13 +106,14 @@ object KotlinUtils { private const val LOG_TAG = "PermissionController Utils" - private const val PERMISSION_CONTROLLER_CHANGED_FLAG_MASK = FLAG_PERMISSION_USER_SET or - FLAG_PERMISSION_USER_FIXED or - FLAG_PERMISSION_ONE_TIME or - FLAG_PERMISSION_REVOKED_COMPAT or - FLAG_PERMISSION_ONE_TIME or - FLAG_PERMISSION_REVIEW_REQUIRED or - FLAG_PERMISSION_AUTO_REVOKED + private const val PERMISSION_CONTROLLER_CHANGED_FLAG_MASK = + FLAG_PERMISSION_USER_SET or + FLAG_PERMISSION_USER_FIXED or + FLAG_PERMISSION_ONE_TIME or + FLAG_PERMISSION_REVOKED_COMPAT or + FLAG_PERMISSION_ONE_TIME or + FLAG_PERMISSION_REVIEW_REQUIRED or + FLAG_PERMISSION_AUTO_REVOKED private const val KILL_REASON_APP_OP_CHANGE = "Permission related app op changed" private const val SAFETY_PROTECTION_RESOURCES_ENABLED = "safety_protection_enabled" @@ -131,10 +132,10 @@ object KotlinUtils { private val ONE_TIME_PACKAGE_IMPORTANCE_LEVEL_TO_KEEP_SESSION_ALIVE = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE - /** Whether to show the Permissions Hub. */ + /** Whether to show the Permissions Hub. */ private const val PROPERTY_PERMISSIONS_HUB_2_ENABLED = "permissions_hub_2_enabled" - /** Whether to show the mic and camera icons. */ + /** Whether to show the mic and camera icons. */ private const val PROPERTY_CAMERA_MIC_ICONS_ENABLED = "camera_mic_icons_enabled" /** Whether to show the location indicators. */ @@ -143,18 +144,18 @@ object KotlinUtils { /** Whether location accuracy feature is enabled */ private const val PROPERTY_LOCATION_ACCURACY_ENABLED = "location_accuracy_enabled" - /** Whether to show 7-day toggle in privacy hub. */ + /** Whether to show 7-day toggle in privacy hub. */ private const val PRIVACY_DASHBOARD_7_DAY_TOGGLE = "privacy_dashboard_7_day_toggle" /** Default location precision */ private const val PROPERTY_LOCATION_PRECISION = "location_precision" - /** Whether to show the photo picker option in permission prompts. */ + /** Whether to show the photo picker option in permission prompts. */ private const val PROPERTY_PHOTO_PICKER_PROMPT_ENABLED = "photo_picker_prompt_enabled" /** - * The minimum amount of time to wait, after scheduling the safety label changes job, before - * the job actually runs for the first time. + * The minimum amount of time to wait, after scheduling the safety label changes job, before the + * job actually runs for the first time. */ private const val PROPERTY_SAFETY_LABEL_CHANGES_JOB_DELAY_MILLIS = "safety_label_changes_job_delay_millis" @@ -178,8 +179,12 @@ object KotlinUtils { */ @ChecksSdkIntAtLeast(Build.VERSION_CODES.S) fun isPermissionsHub2FlagEnabled(): Boolean { - return SdkLevel.isAtLeastS() && DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_PRIVACY, - PROPERTY_PERMISSIONS_HUB_2_ENABLED, false) + return SdkLevel.isAtLeastS() && + DeviceConfig.getBoolean( + DeviceConfig.NAMESPACE_PRIVACY, + PROPERTY_PERMISSIONS_HUB_2_ENABLED, + false + ) } /** * Whether to show the Permissions Dashboard @@ -198,13 +203,17 @@ object KotlinUtils { */ @ChecksSdkIntAtLeast(Build.VERSION_CODES.S) fun isCameraMicIconsFlagEnabled(): Boolean { - return SdkLevel.isAtLeastS() && DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_PRIVACY, - PROPERTY_CAMERA_MIC_ICONS_ENABLED, true) + return SdkLevel.isAtLeastS() && + DeviceConfig.getBoolean( + DeviceConfig.NAMESPACE_PRIVACY, + PROPERTY_CAMERA_MIC_ICONS_ENABLED, + true + ) } /** - * Whether to show Camera and Mic Icons. They should be shown if the permission hub, or the icons - * specifically, are enabled. + * Whether to show Camera and Mic Icons. They should be shown if the permission hub, or the + * icons specifically, are enabled. * * @return whether to show the icons. */ @@ -220,36 +229,42 @@ object KotlinUtils { */ @ChecksSdkIntAtLeast(Build.VERSION_CODES.S) fun isLocationIndicatorsFlagEnabled(): Boolean { - return SdkLevel.isAtLeastS() && DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_PRIVACY, - PROPERTY_LOCATION_INDICATORS_ENABLED, false) + return SdkLevel.isAtLeastS() && + DeviceConfig.getBoolean( + DeviceConfig.NAMESPACE_PRIVACY, + PROPERTY_LOCATION_INDICATORS_ENABLED, + false + ) } /** - * Whether to show the location indicators. The location indicators are enable if the - * permission hub, or location indicator specifically are enabled. + * Whether to show the location indicators. The location indicators are enable if the permission + * hub, or location indicator specifically are enabled. */ @ChecksSdkIntAtLeast(Build.VERSION_CODES.S) fun shouldShowLocationIndicators(): Boolean { return isLocationIndicatorsFlagEnabled() || isPermissionsHub2FlagEnabled() } - /** - * Whether the location accuracy feature is enabled - */ + /** Whether the location accuracy feature is enabled */ @ChecksSdkIntAtLeast(Build.VERSION_CODES.S) fun isLocationAccuracyEnabled(): Boolean { - return SdkLevel.isAtLeastS() && DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_PRIVACY, - PROPERTY_LOCATION_ACCURACY_ENABLED, true) + return SdkLevel.isAtLeastS() && + DeviceConfig.getBoolean( + DeviceConfig.NAMESPACE_PRIVACY, + PROPERTY_LOCATION_ACCURACY_ENABLED, + true + ) } - /** - * Default state of location precision - * true: default is FINE. - * false: default is COARSE. - */ + /** Default state of location precision true: default is FINE. false: default is COARSE. */ fun getDefaultPrecision(): Boolean { - return !SdkLevel.isAtLeastS() || DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_PRIVACY, - PROPERTY_LOCATION_PRECISION, true) + return !SdkLevel.isAtLeastS() || + DeviceConfig.getBoolean( + DeviceConfig.NAMESPACE_PRIVACY, + PROPERTY_LOCATION_PRECISION, + true + ) } /** @@ -259,8 +274,12 @@ object KotlinUtils { */ @ChecksSdkIntAtLeast(Build.VERSION_CODES.S) fun is7DayToggleEnabled(): Boolean { - return SdkLevel.isAtLeastS() && DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_PRIVACY, - PRIVACY_DASHBOARD_7_DAY_TOGGLE, false) + return SdkLevel.isAtLeastS() && + DeviceConfig.getBoolean( + DeviceConfig.NAMESPACE_PRIVACY, + PRIVACY_DASHBOARD_7_DAY_TOGGLE, + false + ) } /** @@ -271,10 +290,15 @@ object KotlinUtils { @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.UPSIDE_DOWN_CAKE, codename = "UpsideDownCake") fun isPhotoPickerPromptEnabled(): Boolean { val app = PermissionControllerApplication.get() - return SdkLevel.isAtLeastU() && !DeviceUtils.isAuto(app) && - !DeviceUtils.isTelevision(app) && !DeviceUtils.isWear(app) && - DeviceConfig.getBoolean( - DeviceConfig.NAMESPACE_PRIVACY, PROPERTY_PHOTO_PICKER_PROMPT_ENABLED, true) + return SdkLevel.isAtLeastU() && + !DeviceUtils.isAuto(app) && + !DeviceUtils.isTelevision(app) && + !DeviceUtils.isWear(app) && + DeviceConfig.getBoolean( + DeviceConfig.NAMESPACE_PRIVACY, + PROPERTY_PHOTO_PICKER_PROMPT_ENABLED, + true + ) } /* @@ -284,8 +308,12 @@ object KotlinUtils { */ @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.UPSIDE_DOWN_CAKE, codename = "UpsideDownCake") fun isPermissionRationaleEnabled(): Boolean { - return SdkLevel.isAtLeastU() && DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_PRIVACY, - PERMISSION_RATIONALE_ENABLED, true) + return SdkLevel.isAtLeastU() && + DeviceConfig.getBoolean( + DeviceConfig.NAMESPACE_PRIVACY, + PERMISSION_RATIONALE_ENABLED, + true + ) } /** @@ -293,8 +321,12 @@ object KotlinUtils { */ @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.UPSIDE_DOWN_CAKE, codename = "UpsideDownCake") fun isSafetyLabelChangeNotificationsEnabled(context: Context): Boolean { - return SdkLevel.isAtLeastU() && DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_PRIVACY, - SAFETY_LABEL_CHANGE_NOTIFICATIONS_ENABLED, true) && + return SdkLevel.isAtLeastU() && + DeviceConfig.getBoolean( + DeviceConfig.NAMESPACE_PRIVACY, + SAFETY_LABEL_CHANGE_NOTIFICATIONS_ENABLED, + true + ) && !DeviceUtils.isAuto(context) && !DeviceUtils.isTelevision(context) && !DeviceUtils.isWear(context) @@ -306,8 +338,12 @@ object KotlinUtils { */ @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.UPSIDE_DOWN_CAKE, codename = "UpsideDownCake") fun safetyLabelChangesJobServiceKillSwitch(): Boolean { - return SdkLevel.isAtLeastU() && DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_PRIVACY, - PROPERTY_SAFETY_LABEL_CHANGES_JOB_SERVICE_KILL_SWITCH, false) + return SdkLevel.isAtLeastU() && + DeviceConfig.getBoolean( + DeviceConfig.NAMESPACE_PRIVACY, + PROPERTY_SAFETY_LABEL_CHANGES_JOB_SERVICE_KILL_SWITCH, + false + ) } /** How often the safety label changes job will run. */ @@ -316,7 +352,8 @@ object KotlinUtils { return DeviceConfig.getLong( DeviceConfig.NAMESPACE_PRIVACY, PROPERTY_SAFETY_LABEL_CHANGES_JOB_INTERVAL_MILLIS, - Duration.ofDays(30).toMillis()) + Duration.ofDays(30).toMillis() + ) } /** Whether the safety label changes job should only be run when the device is idle. */ @@ -325,19 +362,19 @@ object KotlinUtils { return DeviceConfig.getBoolean( DeviceConfig.NAMESPACE_PRIVACY, PROPERTY_SAFETY_LABEL_CHANGES_JOB_RUN_WHEN_IDLE, - true) + true + ) } /** - * Given a Map, and a List, determines which elements are in the list, but not the map, and - * vice versa. Used primarily for determining which liveDatas are already being watched, and - * which need to be removed or added + * Given a Map, and a List, determines which elements are in the list, but not the map, and vice + * versa. Used primarily for determining which liveDatas are already being watched, and which + * need to be removed or added * * @param oldValues A map of key type K, with any value type * @param newValues A list of type K - * * @return A pair, where the first value is all items in the list, but not the map, and the - * second is all keys in the map, but not the list + * second is all keys in the map, but not the list */ fun <K> getMapAndListDifferences( newValues: Collection<K>, @@ -359,7 +396,7 @@ object KotlinUtils { * * @param compare The function comparing two preferences, which will be used to sort * @param hasHeader Whether the group contains a LargeHeaderPreference, which will be kept at - * the top of the list + * the top of the list */ fun sortPreferenceGroup( group: PreferenceGroup, @@ -372,15 +409,17 @@ object KotlinUtils { } if (hasHeader) { - preferences.sortWith(Comparator { lhs, rhs -> - if (lhs is SettingsWithLargeHeader.LargeHeaderPreference) { - -1 - } else if (rhs is SettingsWithLargeHeader.LargeHeaderPreference) { - 1 - } else { - compare(lhs, rhs) + preferences.sortWith( + Comparator { lhs, rhs -> + if (lhs is SettingsWithLargeHeader.LargeHeaderPreference) { + -1 + } else if (rhs is SettingsWithLargeHeader.LargeHeaderPreference) { + 1 + } else { + compare(lhs, rhs) + } } - }) + ) } else { preferences.sortWith(Comparator(compare)) } @@ -395,17 +434,15 @@ object KotlinUtils { * * @param context The context from which to get the icon * @param groupName The name of the permission group whose icon we want - * * @return The permission group's icon, the ic_perm_device_info icon if the group has no icon, - * or the group does not exist + * or the group does not exist */ @JvmOverloads fun getPermGroupIcon(context: Context, groupName: String, tint: Int? = null): Drawable? { val groupInfo = Utils.getGroupInfo(groupName, context) var icon: Drawable? = null if (groupInfo != null && groupInfo.icon != 0) { - icon = Utils.loadDrawable(context.packageManager, groupInfo.packageName, - groupInfo.icon) + icon = Utils.loadDrawable(context.packageManager, groupInfo.packageName, groupInfo.icon) } if (icon == null) { @@ -425,13 +462,15 @@ object KotlinUtils { * * @param context The context from which to get the label * @param groupName The name of the permission group whose label we want - * * @return The permission group's label, or the group name, if the group is invalid */ fun getPermGroupLabel(context: Context, groupName: String): CharSequence { val groupInfo = Utils.getGroupInfo(groupName, context) ?: return groupName - return groupInfo.loadSafeLabel(context.packageManager, 0f, - TextUtils.SAFE_STRING_FLAG_FIRST_LINE or TextUtils.SAFE_STRING_FLAG_TRIM) + return groupInfo.loadSafeLabel( + context.packageManager, + 0f, + TextUtils.SAFE_STRING_FLAG_FIRST_LINE or TextUtils.SAFE_STRING_FLAG_TRIM + ) } /** @@ -439,9 +478,8 @@ object KotlinUtils { * * @param context The context from which to get the description * @param groupName The name of the permission group whose description we want - * * @return The permission group's description, or an empty string, if the group is invalid, or - * its description does not exist + * its description does not exist */ fun getPermGroupDescription(context: Context, groupName: String): CharSequence { val groupInfo = Utils.getGroupInfo(groupName, context) @@ -457,15 +495,20 @@ object KotlinUtils { /** * Gets a permission's label from the system. + * * @param context The context from which to get the label * @param permName The name of the permission whose label we want - * * @return The permission's label, or the permission name, if the permission is invalid */ fun getPermInfoLabel(context: Context, permName: String): CharSequence { return try { - context.packageManager.getPermissionInfo(permName, 0).loadSafeLabel( - context.packageManager, 20000.toFloat(), TextUtils.SAFE_STRING_FLAG_TRIM) + context.packageManager + .getPermissionInfo(permName, 0) + .loadSafeLabel( + context.packageManager, + 20000.toFloat(), + TextUtils.SAFE_STRING_FLAG_TRIM + ) } catch (e: PackageManager.NameNotFoundException) { permName } @@ -473,19 +516,23 @@ object KotlinUtils { /** * Gets a permission's icon from the system. + * * @param context The context from which to get the icon * @param permName The name of the permission whose icon we want - * - * @return The permission's icon, or the permission's group icon if the icon isn't set, or - * the ic_perm_device_info icon if the permission is invalid. + * @return The permission's icon, or the permission's group icon if the icon isn't set, or the + * ic_perm_device_info icon if the permission is invalid. */ fun getPermInfoIcon(context: Context, permName: String): Drawable? { return try { val permInfo = context.packageManager.getPermissionInfo(permName, 0) var icon: Drawable? = null if (permInfo.icon != 0) { - icon = Utils.applyTint(context, permInfo.loadUnbadgedIcon(context.packageManager), - android.R.attr.colorControlNormal) + icon = + Utils.applyTint( + context, + permInfo.loadUnbadgedIcon(context.packageManager), + android.R.attr.colorControlNormal + ) } if (icon == null) { @@ -495,8 +542,11 @@ object KotlinUtils { icon } catch (e: PackageManager.NameNotFoundException) { - Utils.applyTint(context, context.getDrawable(R.drawable.ic_perm_device_info), - android.R.attr.colorControlNormal) + Utils.applyTint( + context, + context.getDrawable(R.drawable.ic_perm_device_info), + android.R.attr.colorControlNormal + ) } } @@ -505,9 +555,8 @@ object KotlinUtils { * * @param context The context from which to get the description * @param permName The name of the permission whose description we want - * - * @return The permission's description, or an empty string, if the group is invalid, or - * its description does not exist + * @return The permission's description, or an empty string, if the group is invalid, or its + * description does not exist */ fun getPermInfoDescription(context: Context, permName: String): CharSequence { return try { @@ -524,14 +573,9 @@ object KotlinUtils { * @param app The current application * @param packageName The name of the package whose icon we want * @param user The user for whom we want the package icon - * * @return The package's icon, or null, if the package does not exist */ - fun getBadgedPackageIcon( - app: Application, - packageName: String, - user: UserHandle - ): Drawable? { + fun getBadgedPackageIcon(app: Application, packageName: String, user: UserHandle): Drawable? { return try { val userContext = Utils.getUserContext(app, user) val appInfo = userContext.packageManager.getApplicationInfo(packageName, 0) @@ -547,7 +591,6 @@ object KotlinUtils { * @param app The current application * @param packageName The name of the package whose label we want * @param user The user for whom we want the package label - * * @return The package's label */ fun getPackageLabel(app: Application, packageName: String, user: UserHandle): String { @@ -561,8 +604,12 @@ object KotlinUtils { } fun convertToBitmap(pkgIcon: Drawable): Bitmap { - val pkgIconBmp = Bitmap.createBitmap(pkgIcon.intrinsicWidth, pkgIcon.intrinsicHeight, - Bitmap.Config.ARGB_8888) + val pkgIconBmp = + Bitmap.createBitmap( + pkgIcon.intrinsicWidth, + pkgIcon.intrinsicHeight, + Bitmap.Config.ARGB_8888 + ) // Draw the icon so it can be displayed. val canvas = Canvas(pkgIconBmp) pkgIcon.setBounds(0, 0, pkgIcon.intrinsicWidth, pkgIcon.intrinsicHeight) @@ -577,13 +624,13 @@ object KotlinUtils { * @param app The current application * @param packageName The name of the package whose uid we want * @param user The user we want the package uid for - * * @return The package's UID, or null if the package or user is invalid */ fun getPackageUid(app: Application, packageName: String, user: UserHandle): Int? { val liveData = LightPackageInfoLiveData[packageName, user] val liveDataUid = liveData.value?.uid - return if (liveDataUid != null && liveData.hasActiveObservers()) liveDataUid else { + return if (liveDataUid != null && liveData.hasActiveObservers()) liveDataUid + else { val userContext = Utils.getUserContext(app, user) try { val appInfo = userContext.packageManager.getApplicationInfo(packageName, 0) @@ -594,9 +641,7 @@ object KotlinUtils { } } - /** - * Return a specific MIME type, if a set of permissions is associated with one - */ + /** Return a specific MIME type, if a set of permissions is associated with one */ fun getMimeTypeForPermissions(permissions: List<String>): String? { if (permissions.contains(READ_MEDIA_IMAGES) && !permissions.contains(READ_MEDIA_VIDEO)) { return "image/*" @@ -614,30 +659,33 @@ object KotlinUtils { * @param app The currenct application * @param packageName The package name to check * @param user The user whose package we want to check - * * @return true if the package is R+ (and not a work profile) or has auto revoke enabled */ fun isROrAutoRevokeEnabled(app: Application, packageName: String, user: UserHandle): Boolean { val userContext = Utils.getUserContext(app, user) val liveDataValue = LightPackageInfoLiveData[packageName, user].value - val (targetSdk, uid) = if (liveDataValue != null) { - liveDataValue.targetSdkVersion to liveDataValue.uid - } else { - val appInfo = userContext.packageManager.getApplicationInfo(packageName, 0) - appInfo.targetSdkVersion to appInfo.uid - } + val (targetSdk, uid) = + if (liveDataValue != null) { + liveDataValue.targetSdkVersion to liveDataValue.uid + } else { + val appInfo = userContext.packageManager.getApplicationInfo(packageName, 0) + appInfo.targetSdkVersion to appInfo.uid + } if (targetSdk <= Build.VERSION_CODES.Q) { val opsManager = app.getSystemService(AppOpsManager::class.java)!! - return opsManager.unsafeCheckOpNoThrow(OPSTR_AUTO_REVOKE_PERMISSIONS_IF_UNUSED, uid, - packageName) == MODE_ALLOWED + return opsManager.unsafeCheckOpNoThrow( + OPSTR_AUTO_REVOKE_PERMISSIONS_IF_UNUSED, + uid, + packageName + ) == MODE_ALLOWED } return true } /** - * Determine if the given permission should be treated as split from a - * non-runtime permission for an application targeting the given SDK level. + * Determine if the given permission should be treated as split from a non-runtime permission + * for an application targeting the given SDK level. */ private fun isPermissionSplitFromNonRuntime( app: Application, @@ -664,8 +712,7 @@ object KotlinUtils { * @param group: The LightAppPermGroup whose permission flags we wish to set * @param flags: Pairs of <FlagInt, ShouldSetFlag> * @param filterPermissions: A list of permissions to filter by. Only the filtered permissions - * will be set - * + * will be set * @return A new LightAppPermGroup with the flags set. */ fun setGroupFlags( @@ -690,14 +737,29 @@ object KotlinUtils { } // Check if flags need to be updated if (flagMask and (perm.flags xor flagsToSet) != 0) { - app.packageManager.updatePermissionFlags(permName, group.packageName, - group.userHandle, *flags) + app.packageManager.updatePermissionFlags( + permName, + group.packageName, + group.userHandle, + *flags + ) } - newPerms[permName] = LightPermission(group.packageInfo, perm.permInfo, - perm.isGrantedIncludingAppOp, perm.flags or flagsToSet, perm.foregroundPerms) + newPerms[permName] = + LightPermission( + group.packageInfo, + perm.permInfo, + perm.isGrantedIncludingAppOp, + perm.flags or flagsToSet, + perm.foregroundPerms + ) } - return LightAppPermGroup(group.packageInfo, group.permGroupInfo, newPerms, - group.hasInstallToRuntimeSplit, group.specialLocationGrant) + return LightAppPermGroup( + group.packageInfo, + group.permGroupInfo, + newPerms, + group.hasInstallToRuntimeSplit, + group.specialLocationGrant + ) } /** @@ -708,9 +770,7 @@ object KotlinUtils { * @param app The current application * @param group The group whose permissions should be granted * @param filterPermissions If not specified, all permissions of the group will be granted. - * Otherwise only permissions in {@code filterPermissions} will be - * granted. - * + * Otherwise only permissions in {@code filterPermissions} will be granted. * @return a new LightAppPermGroup, reflecting the new state */ @JvmOverloads @@ -722,8 +782,15 @@ object KotlinUtils { userFixed: Boolean = false, withoutAppOps: Boolean = false, ): LightAppPermGroup { - return grantRuntimePermissions(app, group, false, isOneTime, userFixed, - withoutAppOps, filterPermissions) + return grantRuntimePermissions( + app, + group, + false, + isOneTime, + userFixed, + withoutAppOps, + filterPermissions + ) } /** @@ -734,9 +801,7 @@ object KotlinUtils { * @param app The current application * @param group The group whose permissions should be granted * @param filterPermissions If not specified, all permissions of the group will be granted. - * Otherwise only permissions in {@code filterPermissions} will be - * granted. - * + * Otherwise only permissions in {@code filterPermissions} will be granted. * @return a new LightAppPermGroup, reflecting the new state */ @JvmOverloads @@ -745,8 +810,7 @@ object KotlinUtils { group: LightAppPermGroup, filterPermissions: List<String> = group.permissions.keys.toList() ): LightAppPermGroup { - return grantRuntimePermissions(app, group, true, false, false, false, - filterPermissions) + return grantRuntimePermissions(app, group, true, false, false, false, filterPermissions) } private fun grantRuntimePermissions( @@ -764,8 +828,8 @@ object KotlinUtils { val perm = group.permissions[permName] ?: continue val isBackgroundPerm = permName in group.backgroundPermNames if (isBackgroundPerm == grantBackground) { - val (newPerm, shouldKill) = grantRuntimePermission(app, perm, group, isOneTime, - userFixed, withoutAppOps) + val (newPerm, shouldKill) = + grantRuntimePermission(app, perm, group, isOneTime, userFixed, withoutAppOps) newPerms[newPerm.name] = newPerm shouldKillForAnyPermission = shouldKillForAnyPermission || shouldKill } @@ -776,32 +840,48 @@ object KotlinUtils { var permFlags = groupPerm.flags permFlags = permFlags.clearFlag(FLAG_PERMISSION_AUTO_REVOKED) if (groupPerm.flags != permFlags) { - app.packageManager.updatePermissionFlags(groupPerm.name, - group.packageInfo.packageName, PERMISSION_CONTROLLER_CHANGED_FLAG_MASK, - permFlags, user) + app.packageManager.updatePermissionFlags( + groupPerm.name, + group.packageInfo.packageName, + PERMISSION_CONTROLLER_CHANGED_FLAG_MASK, + permFlags, + user + ) } } } if (shouldKillForAnyPermission) { (app.getSystemService(ActivityManager::class.java) as ActivityManager).killUid( - group.packageInfo.uid, KILL_REASON_APP_OP_CHANGE) + group.packageInfo.uid, + KILL_REASON_APP_OP_CHANGE + ) } - val newGroup = LightAppPermGroup(group.packageInfo, group.permGroupInfo, newPerms, - group.hasInstallToRuntimeSplit, group.specialLocationGrant) + val newGroup = + LightAppPermGroup( + group.packageInfo, + group.permGroupInfo, + newPerms, + group.hasInstallToRuntimeSplit, + group.specialLocationGrant + ) // If any permission in the group is one time granted, start one time permission session. if (newGroup.permissions.any { it.value.isOneTime && it.value.isGrantedIncludingAppOp }) { if (SdkLevel.isAtLeastT()) { app.getSystemService(PermissionManager::class.java)!!.startOneTimePermissionSession( - group.packageName, Utils.getOneTimePermissionsTimeout(), - Utils.getOneTimePermissionsKilledDelay(false), - ONE_TIME_PACKAGE_IMPORTANCE_LEVEL_TO_RESET_TIMER, - ONE_TIME_PACKAGE_IMPORTANCE_LEVEL_TO_KEEP_SESSION_ALIVE) + group.packageName, + Utils.getOneTimePermissionsTimeout(), + Utils.getOneTimePermissionsKilledDelay(false), + ONE_TIME_PACKAGE_IMPORTANCE_LEVEL_TO_RESET_TIMER, + ONE_TIME_PACKAGE_IMPORTANCE_LEVEL_TO_KEEP_SESSION_ALIVE + ) } else { app.getSystemService(PermissionManager::class.java)!!.startOneTimePermissionSession( - group.packageName, Utils.getOneTimePermissionsTimeout(), - ONE_TIME_PACKAGE_IMPORTANCE_LEVEL_TO_RESET_TIMER, - ONE_TIME_PACKAGE_IMPORTANCE_LEVEL_TO_KEEP_SESSION_ALIVE) + group.packageName, + Utils.getOneTimePermissionsTimeout(), + ONE_TIME_PACKAGE_IMPORTANCE_LEVEL_TO_RESET_TIMER, + ONE_TIME_PACKAGE_IMPORTANCE_LEVEL_TO_KEEP_SESSION_ALIVE + ) } } return newGroup @@ -813,14 +893,13 @@ object KotlinUtils { * @param app The current application * @param perm The permission which should be granted. * @param group An app permission group in which to look for background or foreground - * @param isOneTime Whether this is a one-time permission grant - * permissions + * @param isOneTime Whether this is a one-time permission grant permissions * @param userFixed Whether to mark the permissions as user fixed when granted * @param withoutAppOps If these permission have app ops associated, and this value is true, - * then do not grant the app op when the permission is granted, and add the REVOKED_COMPAT flag. - * + * then do not grant the app op when the permission is granted, and add the REVOKED_COMPAT + * flag. * @return a LightPermission and boolean pair <permission with updated state (or the original - * state, if it wasn't changed), should kill app> + * state, if it wasn't changed), should kill app> */ private fun grantRuntimePermission( app: Application, @@ -833,8 +912,9 @@ object KotlinUtils { val pkgInfo = group.packageInfo val user = UserHandle.getUserHandleForUid(pkgInfo.uid) val supportsRuntime = pkgInfo.targetSdkVersion >= Build.VERSION_CODES.M - val isGrantingAllowed = (!pkgInfo.isInstantApp || perm.isInstantPerm) && - (supportsRuntime || !perm.isRuntimeOnly) + val isGrantingAllowed = + (!pkgInfo.isInstantApp || perm.isInstantPerm) && + (supportsRuntime || !perm.isRuntimeOnly) // Do not touch permissions fixed by the system, or permissions that cannot be granted if (!isGrantingAllowed || perm.isSystemFixed) { return perm to false @@ -855,8 +935,13 @@ object KotlinUtils { // flag, so that the PermissionPolicyService doesn't reset the app op state if (affectsAppOp && withoutAppOps) { oldFlags = oldFlags.setFlag(PackageManager.FLAG_PERMISSION_REVOKED_COMPAT) - app.packageManager.updatePermissionFlags(perm.name, group.packageName, - PERMISSION_CONTROLLER_CHANGED_FLAG_MASK, oldFlags, user) + app.packageManager.updatePermissionFlags( + perm.name, + group.packageName, + PERMISSION_CONTROLLER_CHANGED_FLAG_MASK, + oldFlags, + user + ) disallowAppOp(app, perm, group) } app.packageManager.grantRuntimePermission(group.packageName, perm.name, user) @@ -869,11 +954,12 @@ object KotlinUtils { shouldKill = true isGranted = true } - newFlags = if (affectsAppOp && withoutAppOps) { - newFlags.setFlag(PackageManager.FLAG_PERMISSION_REVOKED_COMPAT) - } else { - newFlags.clearFlag(PackageManager.FLAG_PERMISSION_REVOKED_COMPAT) - } + newFlags = + if (affectsAppOp && withoutAppOps) { + newFlags.setFlag(PackageManager.FLAG_PERMISSION_REVOKED_COMPAT) + } else { + newFlags.clearFlag(PackageManager.FLAG_PERMISSION_REVOKED_COMPAT) + } newFlags = newFlags.clearFlag(PackageManager.FLAG_PERMISSION_REVOKE_WHEN_REQUESTED) // If this permission affects an app op, ensure the permission app op is enabled @@ -898,11 +984,12 @@ object KotlinUtils { } newFlags = newFlags.clearFlag(FLAG_PERMISSION_AUTO_REVOKED) - newFlags = if (isOneTime) { - newFlags.setFlag(FLAG_PERMISSION_ONE_TIME) - } else { - newFlags.clearFlag(FLAG_PERMISSION_ONE_TIME) - } + newFlags = + if (isOneTime) { + newFlags.setFlag(FLAG_PERMISSION_ONE_TIME) + } else { + newFlags.clearFlag(FLAG_PERMISSION_ONE_TIME) + } // If we newly grant background access to the fine location, double-guess the user some // time later if this was really the right choice. @@ -922,13 +1009,18 @@ object KotlinUtils { } if (oldFlags != newFlags) { - app.packageManager.updatePermissionFlags(perm.name, group.packageInfo.packageName, - PERMISSION_CONTROLLER_CHANGED_FLAG_MASK, newFlags, user) + app.packageManager.updatePermissionFlags( + perm.name, + group.packageInfo.packageName, + PERMISSION_CONTROLLER_CHANGED_FLAG_MASK, + newFlags, + user + ) } val newState = PermState(newFlags, isGranted) - return LightPermission(perm.pkgInfo, perm.permInfo, newState, - perm.foregroundPerms) to shouldKill + return LightPermission(perm.pkgInfo, perm.permInfo, newState, perm.foregroundPerms) to + shouldKill } /** @@ -941,9 +1033,7 @@ object KotlinUtils { * @param userFixed If the user requested that they do not want to be asked again * @param oneTime If the permission should be mark as one-time * @param filterPermissions If not specified, all permissions of the group will be revoked. - * Otherwise only permissions in {@code filterPermissions} will be - * revoked. - * + * Otherwise only permissions in {@code filterPermissions} will be revoked. * @return a LightAppPermGroup representing the new state */ @JvmOverloads @@ -955,8 +1045,15 @@ object KotlinUtils { forceRemoveRevokedCompat: Boolean = false, filterPermissions: List<String> = group.permissions.keys.toList() ): LightAppPermGroup { - return revokeRuntimePermissions(app, group, false, userFixed, oneTime, - forceRemoveRevokedCompat, filterPermissions) + return revokeRuntimePermissions( + app, + group, + false, + userFixed, + oneTime, + forceRemoveRevokedCompat, + filterPermissions + ) } /** @@ -968,9 +1065,7 @@ object KotlinUtils { * @param group The group whose permissions should be revoked * @param userFixed If the user requested that they do not want to be asked again * @param filterPermissions If not specified, all permissions of the group will be revoked. - * Otherwise only permissions in {@code filterPermissions} will be - * revoked. - * + * Otherwise only permissions in {@code filterPermissions} will be revoked. * @return a LightAppPermGroup representing the new state */ @JvmOverloads @@ -982,8 +1077,15 @@ object KotlinUtils { forceRemoveRevokedCompat: Boolean = false, filterPermissions: List<String> = group.permissions.keys.toList() ): LightAppPermGroup { - return revokeRuntimePermissions(app, group, true, userFixed, oneTime, - forceRemoveRevokedCompat, filterPermissions) + return revokeRuntimePermissions( + app, + group, + true, + userFixed, + oneTime, + forceRemoveRevokedCompat, + filterPermissions + ) } private fun revokeRuntimePermissions( @@ -1003,8 +1105,14 @@ object KotlinUtils { val isBackgroundPerm = permName in group.backgroundPermNames if (isBackgroundPerm == revokeBackground) { val (newPerm, shouldKill) = - revokeRuntimePermission(app, perm, userFixed, oneTime, forceRemoveRevokedCompat, - group) + revokeRuntimePermission( + app, + perm, + userFixed, + oneTime, + forceRemoveRevokedCompat, + group + ) newPerms[newPerm.name] = newPerm shouldKillForAnyPermission = shouldKillForAnyPermission || shouldKill } @@ -1012,15 +1120,24 @@ object KotlinUtils { if (shouldKillForAnyPermission && !shouldSkipKillForGroup(app, group)) { (app.getSystemService(ActivityManager::class.java) as ActivityManager).killUid( - group.packageInfo.uid, KILL_REASON_APP_OP_CHANGE) + group.packageInfo.uid, + KILL_REASON_APP_OP_CHANGE + ) } - val newGroup = LightAppPermGroup(group.packageInfo, group.permGroupInfo, newPerms, - group.hasInstallToRuntimeSplit, group.specialLocationGrant) + val newGroup = + LightAppPermGroup( + group.packageInfo, + group.permGroupInfo, + newPerms, + group.hasInstallToRuntimeSplit, + group.specialLocationGrant + ) if (wasOneTime && !anyPermsOfPackageOneTimeGranted(app, newGroup.packageInfo, newGroup)) { app.getSystemService(PermissionManager::class.java)!!.stopOneTimePermissionSession( - group.packageName) + group.packageName + ) } return newGroup } @@ -1042,8 +1159,9 @@ object KotlinUtils { postRevokeHandler: Runnable? ) { GlobalScope.launch(Dispatchers.Main) { - val group = LightAppPermGroupLiveData[packageName, permissionGroupName, user] - .getInitializedValue() + val group = + LightAppPermGroupLiveData[packageName, permissionGroupName, user] + .getInitializedValue() if (group != null) { revokeBackgroundRuntimePermissions(context.application, group) } @@ -1059,7 +1177,6 @@ object KotlinUtils { * @param app The current application * @param packageInfo The packageInfo we wish to examine * @param group Optional, the current app permission group we are examining - * * @return true if any permission in the package is granted for one time, false otherwise */ private fun anyPermsOfPackageOneTimeGranted( @@ -1075,11 +1192,12 @@ object KotlinUtils { if (permName in group?.permissions ?: emptyMap()) { continue } - val flags = app.packageManager.getPermissionFlags(permName, packageInfo.packageName, - user) and FLAG_PERMISSION_ONE_TIME - val granted = packageInfo.requestedPermissionsFlags[idx] == - PackageManager.PERMISSION_GRANTED && - (flags and FLAG_PERMISSION_REVOKED_COMPAT) == 0 + val flags = + app.packageManager.getPermissionFlags(permName, packageInfo.packageName, user) and + FLAG_PERMISSION_ONE_TIME + val granted = + packageInfo.requestedPermissionsFlags[idx] == PackageManager.PERMISSION_GRANTED && + (flags and FLAG_PERMISSION_REVOKED_COMPAT) == 0 if (granted && (flags and FLAG_PERMISSION_ONE_TIME) != 0) { return true } @@ -1093,10 +1211,9 @@ object KotlinUtils { * @param perm The permission which should be revoked. * @param userFixed If the user requested that they do not want to be asked again * @param group An optional app permission group in which to look for background or foreground - * permissions - * + * permissions * @return a LightPermission and boolean pair <permission with updated state (or the original - * state, if it wasn't changed), should kill app> + * state, if it wasn't changed), should kill app> */ private fun revokeRuntimePermission( app: Application, @@ -1120,11 +1237,20 @@ object KotlinUtils { val affectsAppOp = permissionToOp(perm.name) != null || perm.isBackgroundPermission if (perm.isGrantedIncludingAppOp || (perm.isCompatRevoked && forceRemoveRevokedCompat)) { - if (supportsRuntime && !isPermissionSplitFromNonRuntime(app, perm.name, - group.packageInfo.targetSdkVersion)) { + if ( + supportsRuntime && + !isPermissionSplitFromNonRuntime( + app, + perm.name, + group.packageInfo.targetSdkVersion + ) + ) { // Revoke the permission if needed. - app.packageManager.revokeRuntimePermission(group.packageInfo.packageName, - perm.name, user) + app.packageManager.revokeRuntimePermission( + group.packageInfo.packageName, + perm.name, + user + ) isGranted = false if (forceRemoveRevokedCompat) { newFlags = newFlags.clearFlag(PackageManager.FLAG_PERMISSION_REVOKED_COMPAT) @@ -1149,18 +1275,26 @@ object KotlinUtils { // Update the permission flags. // Take a note that the user fixed the permission, if applicable. - newFlags = if (userFixed) newFlags.setFlag(PackageManager.FLAG_PERMISSION_USER_FIXED) - else newFlags.clearFlag(PackageManager.FLAG_PERMISSION_USER_FIXED) - newFlags = if (oneTime) newFlags.clearFlag(PackageManager.FLAG_PERMISSION_USER_SET) - else newFlags.setFlag(PackageManager.FLAG_PERMISSION_USER_SET) - newFlags = if (oneTime) newFlags.setFlag(PackageManager.FLAG_PERMISSION_ONE_TIME) - else newFlags.clearFlag(PackageManager.FLAG_PERMISSION_ONE_TIME) + newFlags = + if (userFixed) newFlags.setFlag(PackageManager.FLAG_PERMISSION_USER_FIXED) + else newFlags.clearFlag(PackageManager.FLAG_PERMISSION_USER_FIXED) + newFlags = + if (oneTime) newFlags.clearFlag(PackageManager.FLAG_PERMISSION_USER_SET) + else newFlags.setFlag(PackageManager.FLAG_PERMISSION_USER_SET) + newFlags = + if (oneTime) newFlags.setFlag(PackageManager.FLAG_PERMISSION_ONE_TIME) + else newFlags.clearFlag(PackageManager.FLAG_PERMISSION_ONE_TIME) newFlags = newFlags.clearFlag(PackageManager.FLAG_PERMISSION_AUTO_REVOKED) newFlags = newFlags.clearFlag(PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) if (perm.flags != newFlags) { - app.packageManager.updatePermissionFlags(perm.name, group.packageInfo.packageName, - PERMISSION_CONTROLLER_CHANGED_FLAG_MASK, newFlags, user) + app.packageManager.updatePermissionFlags( + perm.name, + group.packageInfo.packageName, + PERMISSION_CONTROLLER_CHANGED_FLAG_MASK, + newFlags, + user + ) } // If we revoke background access to the fine location, we trigger a check to remove @@ -1176,17 +1310,18 @@ object KotlinUtils { } if (cancelLocationAccessWarning) { // cancel location access warning notification - LocationAccessCheck(app, null).cancelBackgroundAccessWarningNotification( - group.packageInfo.packageName, - user, - true - ) + LocationAccessCheck(app, null) + .cancelBackgroundAccessWarningNotification( + group.packageInfo.packageName, + user, + true + ) } } val newState = PermState(newFlags, isGranted) - return LightPermission(perm.pkgInfo, perm.permInfo, newState, - perm.foregroundPerms) to shouldKill + return LightPermission(perm.pkgInfo, perm.permInfo, newState, perm.foregroundPerms) to + shouldKill } private fun Int.setFlag(flagToSet: Int): Int { @@ -1200,27 +1335,20 @@ object KotlinUtils { /** * Allow the app op for a permission/uid. * - * <p>There are three cases: - * <dl> - * <dt>The permission is not split into foreground/background</dt> - * <dd>The app op matching the permission will be set to {@link AppOpsManager#MODE_ALLOWED}</dd> - * <dt>The permission is a foreground permission:</dt> - * <dd><dl><dt>The background permission permission is granted</dt> - * <dd>The app op matching the permission will be set to {@link AppOpsManager#MODE_ALLOWED}</dd> - * <dt>The background permission permission is <u>not</u> granted</dt> - * <dd>The app op matching the permission will be set to - * {@link AppOpsManager#MODE_FOREGROUND}</dd> - * </dl></dd> - * <dt>The permission is a background permission:</dt> - * <dd>All granted foreground permissions for this background permission will be set to - * {@link AppOpsManager#MODE_ALLOWED}</dd> - * </dl> + * <p>There are three cases: <dl> <dt>The permission is not split into + * foreground/background</dt> <dd>The app op matching the permission will be set to {@link + * AppOpsManager#MODE_ALLOWED}</dd> <dt>The permission is a foreground permission:</dt> + * <dd><dl><dt>The background permission permission is granted</dt> <dd>The app op matching the + * permission will be set to {@link AppOpsManager#MODE_ALLOWED}</dd> <dt>The background + * permission permission is <u>not</u> granted</dt> <dd>The app op matching the permission will + * be set to {@link AppOpsManager#MODE_FOREGROUND}</dd> </dl></dd> <dt>The permission is a + * background permission:</dt> <dd>All granted foreground permissions for this background + * permission will be set to {@link AppOpsManager#MODE_ALLOWED}</dd> </dl> * * @param app The current application * @param perm The LightPermission whose app op should be allowed - * @param group The LightAppPermGroup which will be looked in for foreground or - * background LightPermission objects - * + * @param group The LightAppPermGroup which will be looked in for foreground or background + * LightPermission objects * @return {@code true} iff app-op was changed */ private fun allowAppOp( @@ -1239,25 +1367,29 @@ object KotlinUtils { val appOpName = permissionToOp(foregroundPermName) ?: continue if (fgPerm != null && fgPerm.isGrantedIncludingAppOp) { - wasChanged = setOpMode(appOpName, uid, packageName, MODE_ALLOWED, - appOpsManager) || wasChanged + wasChanged = + setOpMode(appOpName, uid, packageName, MODE_ALLOWED, appOpsManager) || + wasChanged } } } else { val appOpName = permissionToOp(perm.name) ?: return false if (perm.backgroundPermission != null) { - wasChanged = if (group.permissions.containsKey(perm.backgroundPermission)) { - val bgPerm = group.permissions[perm.backgroundPermission] - val mode = if (bgPerm != null && bgPerm.isGrantedIncludingAppOp) MODE_ALLOWED - else MODE_FOREGROUND - - setOpMode(appOpName, uid, packageName, mode, appOpsManager) - } else { - // The app requested a permission that has a background permission but it did - // not request the background permission, hence it can never get background - // access - setOpMode(appOpName, uid, packageName, MODE_FOREGROUND, appOpsManager) - } + wasChanged = + if (group.permissions.containsKey(perm.backgroundPermission)) { + val bgPerm = group.permissions[perm.backgroundPermission] + val mode = + if (bgPerm != null && bgPerm.isGrantedIncludingAppOp) MODE_ALLOWED + else MODE_FOREGROUND + + setOpMode(appOpName, uid, packageName, mode, appOpsManager) + } else { + // The app requested a permission that has a background permission but it + // did + // not request the background permission, hence it can never get background + // access + setOpMode(appOpName, uid, packageName, MODE_FOREGROUND, appOpsManager) + } } else { wasChanged = setOpMode(appOpName, uid, packageName, MODE_ALLOWED, appOpsManager) } @@ -1268,22 +1400,17 @@ object KotlinUtils { /** * Disallow the app op for a permission/uid. * - * <p>There are three cases: - * <dl> - * <dt>The permission is not split into foreground/background</dt> - * <dd>The app op matching the permission will be set to {@link AppOpsManager#MODE_IGNORED}</dd> - * <dt>The permission is a foreground permission:</dt> - * <dd>The app op matching the permission will be set to {@link AppOpsManager#MODE_IGNORED}</dd> - * <dt>The permission is a background permission:</dt> - * <dd>All granted foreground permissions for this background permission will be set to - * {@link AppOpsManager#MODE_FOREGROUND}</dd> - * </dl> + * <p>There are three cases: <dl> <dt>The permission is not split into + * foreground/background</dt> <dd>The app op matching the permission will be set to {@link + * AppOpsManager#MODE_IGNORED}</dd> <dt>The permission is a foreground permission:</dt> <dd>The + * app op matching the permission will be set to {@link AppOpsManager#MODE_IGNORED}</dd> <dt>The + * permission is a background permission:</dt> <dd>All granted foreground permissions for this + * background permission will be set to {@link AppOpsManager#MODE_FOREGROUND}</dd> </dl> * * @param app The current application * @param perm The LightPermission whose app op should be allowed - * @param group The LightAppPermGroup which will be looked in for foreground or - * background LightPermission objects - * + * @param group The LightAppPermGroup which will be looked in for foreground or background + * LightPermission objects * @return {@code true} iff app-op was changed */ private fun disallowAppOp( @@ -1301,8 +1428,9 @@ object KotlinUtils { val fgPerm = group.permissions[foregroundPermName] if (fgPerm != null && fgPerm.isGrantedIncludingAppOp) { val appOpName = permissionToOp(foregroundPermName) ?: return false - wasChanged = wasChanged || setOpMode(appOpName, uid, packageName, - MODE_FOREGROUND, appOpsManager) + wasChanged = + wasChanged || + setOpMode(appOpName, uid, packageName, MODE_FOREGROUND, appOpsManager) } } } else { @@ -1320,7 +1448,6 @@ object KotlinUtils { * @param packageName The package the app-op belongs to * @param mode The new mode * @param manager The app ops manager to use to change the app op - * * @return {@code true} iff app-op was changed */ private fun setOpMode( @@ -1343,22 +1470,25 @@ object KotlinUtils { return false } - return shouldSkipKillOnPermDeny(app, POST_NOTIFICATIONS, group.packageName, - group.userHandle) + return shouldSkipKillOnPermDeny( + app, + POST_NOTIFICATIONS, + group.packageName, + group.userHandle + ) } /** * Determine if the usual "kill app on permission denial" should be skipped. It should be - * skipped if the permission is POST_NOTIFICATIONS, the app holds the BACKUP permission, and - * a backup restore is currently in progress. + * skipped if the permission is POST_NOTIFICATIONS, the app holds the BACKUP permission, and a + * backup restore is currently in progress. * * @param app the current application * @param permission the permission being denied * @param packageName the package the permission was denied for * @param user the user whose package the permission was denied for - * * @return true if the permission denied was POST_NOTIFICATIONS, the app is a backup app, and a - * backup restore is in progress, false otherwise + * backup restore is in progress, false otherwise */ fun shouldSkipKillOnPermDeny( app: Application, @@ -1367,17 +1497,27 @@ object KotlinUtils { user: UserHandle ): Boolean { val userContext: Context = Utils.getUserContext(app, user) - if (permission != POST_NOTIFICATIONS || userContext.packageManager - .checkPermission(BACKUP, packageName) != PackageManager.PERMISSION_GRANTED) { + if ( + permission != POST_NOTIFICATIONS || + userContext.packageManager.checkPermission(BACKUP, packageName) != + PackageManager.PERMISSION_GRANTED + ) { return false } return try { - val isInSetup = Settings.Secure.getInt(userContext.contentResolver, - Settings.Secure.USER_SETUP_COMPLETE, user.identifier) == 0 - val isInDeferredSetup = Settings.Secure.getInt(userContext.contentResolver, - Settings.Secure.USER_SETUP_PERSONALIZATION_STATE, user.identifier) == - Settings.Secure.USER_SETUP_PERSONALIZATION_STARTED + val isInSetup = + Settings.Secure.getInt( + userContext.contentResolver, + Settings.Secure.USER_SETUP_COMPLETE, + user.identifier + ) == 0 + val isInDeferredSetup = + Settings.Secure.getInt( + userContext.contentResolver, + Settings.Secure.USER_SETUP_PERSONALIZATION_STATE, + user.identifier + ) == Settings.Secure.USER_SETUP_PERSONALIZATION_STARTED isInSetup || isInDeferredSetup } catch (e: Settings.SettingNotFoundException) { Log.w(LOG_TAG, "Failed to check if the user is in restore: $e") @@ -1391,22 +1531,27 @@ object KotlinUtils { * * @param context: The context from which to retrieve the package * @param packageName: The package name to check - * * @return whether or not the given package has a launch intent */ fun packageHasLaunchIntent(context: Context, packageName: String): Boolean { val intentToResolve = Intent(ACTION_MAIN) intentToResolve.addCategory(CATEGORY_INFO) intentToResolve.setPackage(packageName) - var resolveInfos = context.packageManager.queryIntentActivities(intentToResolve, - MATCH_DIRECT_BOOT_AWARE or MATCH_DIRECT_BOOT_UNAWARE) + var resolveInfos = + context.packageManager.queryIntentActivities( + intentToResolve, + MATCH_DIRECT_BOOT_AWARE or MATCH_DIRECT_BOOT_UNAWARE + ) if (resolveInfos.size <= 0) { intentToResolve.removeCategory(CATEGORY_INFO) intentToResolve.addCategory(CATEGORY_LAUNCHER) intentToResolve.setPackage(packageName) - resolveInfos = context.packageManager.queryIntentActivities(intentToResolve, - MATCH_DIRECT_BOOT_AWARE or MATCH_DIRECT_BOOT_UNAWARE) + resolveInfos = + context.packageManager.queryIntentActivities( + intentToResolve, + MATCH_DIRECT_BOOT_AWARE or MATCH_DIRECT_BOOT_UNAWARE + ) } return resolveInfos.size > 0 } @@ -1424,39 +1569,55 @@ object KotlinUtils { isFineSelected: Boolean ) { if (isFineSelected) { - setGroupFlags(app, group, + setGroupFlags( + app, + group, PackageManager.FLAG_PERMISSION_SELECTED_LOCATION_ACCURACY to true, - filterPermissions = listOf(ACCESS_FINE_LOCATION)) - setGroupFlags(app, group, + filterPermissions = listOf(ACCESS_FINE_LOCATION) + ) + setGroupFlags( + app, + group, PackageManager.FLAG_PERMISSION_SELECTED_LOCATION_ACCURACY to false, - filterPermissions = listOf(Manifest.permission.ACCESS_COARSE_LOCATION)) + filterPermissions = listOf(Manifest.permission.ACCESS_COARSE_LOCATION) + ) } else { - setGroupFlags(app, group, + setGroupFlags( + app, + group, PackageManager.FLAG_PERMISSION_SELECTED_LOCATION_ACCURACY to false, - filterPermissions = listOf(ACCESS_FINE_LOCATION)) - setGroupFlags(app, group, + filterPermissions = listOf(ACCESS_FINE_LOCATION) + ) + setGroupFlags( + app, + group, PackageManager.FLAG_PERMISSION_SELECTED_LOCATION_ACCURACY to true, - filterPermissions = listOf(Manifest.permission.ACCESS_COARSE_LOCATION)) + filterPermissions = listOf(Manifest.permission.ACCESS_COARSE_LOCATION) + ) } } /** - * Determines whether we should show the safety protection resources. - * We show the resources only if - * (1) the build version is T or after and - * (2) the feature flag safety_protection_enabled is enabled and - * (3) the config value config_safetyProtectionEnabled is enabled/true and - * (4) the resources exist (currently the resources only exist on GMS devices) + * Determines whether we should show the safety protection resources. We show the resources only + * if (1) the build version is T or after and (2) the feature flag safety_protection_enabled is + * enabled and (3) the config value config_safetyProtectionEnabled is enabled/true and (4) the + * resources exist (currently the resources only exist on GMS devices) */ @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.TIRAMISU) fun shouldShowSafetyProtectionResources(context: Context): Boolean { return try { SdkLevel.isAtLeastT() && DeviceConfig.getBoolean( - DeviceConfig.NAMESPACE_PRIVACY, SAFETY_PROTECTION_RESOURCES_ENABLED, false) && - context.getResources().getBoolean( - Resources.getSystem() - .getIdentifier("config_safetyProtectionEnabled", "bool", "android")) && + DeviceConfig.NAMESPACE_PRIVACY, + SAFETY_PROTECTION_RESOURCES_ENABLED, + false + ) && + context + .getResources() + .getBoolean( + Resources.getSystem() + .getIdentifier("config_safetyProtectionEnabled", "bool", "android") + ) && context.getDrawable(android.R.drawable.ic_safety_protection) != null && !context.getString(android.R.string.safety_protection_display_text).isNullOrEmpty() } catch (e: Resources.NotFoundException) { @@ -1480,8 +1641,7 @@ object KotlinUtils { installerPackageName: String?, packageName: String? ): Intent? { - val intent: Intent = Intent(Intent.ACTION_SHOW_APP_INFO) - .setPackage(installerPackageName) + val intent: Intent = Intent(Intent.ACTION_SHOW_APP_INFO).setPackage(installerPackageName) val result: Intent? = resolveActivityForIntent(context, intent) if (result != null) { result.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName) @@ -1512,9 +1672,10 @@ object KotlinUtils { val color: Int // If U resources are available, and this is a U+ device, use those if (SdkLevel.isAtLeastU()) { - val scContext = SafetyCenterResourcesContext(context) - val uIcon = scContext.getIconByDrawableName("ic_notification_badge_general") - val uColor = scContext.getColorByName("notification_tint_normal") + val safetyCenterResourcesApk = SafetyCenterResourcesApk(context) + val uIcon = + safetyCenterResourcesApk.getIconByDrawableName("ic_notification_badge_general") + val uColor = safetyCenterResourcesApk.getColorByName("notification_tint_normal") if (uIcon != null && uColor != null) { appLabel = context.getString(R.string.safety_privacy_qs_tile_title) return NotificationResources(appLabel, uIcon, uColor) @@ -1523,24 +1684,21 @@ object KotlinUtils { // Use PbA branding if available, otherwise default to more generic branding if (shouldShowSafetyProtectionResources(context)) { - appLabel = Html.fromHtml(context.getString( - android.R.string.safety_protection_display_text), 0).toString() - smallIcon = - Icon.createWithResource(context, android.R.drawable.ic_safety_protection) + appLabel = + Html.fromHtml(context.getString(android.R.string.safety_protection_display_text), 0) + .toString() + smallIcon = Icon.createWithResource(context, android.R.drawable.ic_safety_protection) color = context.getColor(R.color.safety_center_info) } else { appLabel = context.getString(R.string.safety_center_notification_app_label) - smallIcon = - Icon.createWithResource(context, R.drawable.ic_settings_notification) + smallIcon = Icon.createWithResource(context, R.drawable.ic_settings_notification) color = context.getColor(android.R.color.system_notification_accent_color) } return NotificationResources(appLabel, smallIcon, color) } } -/** - * Get the [value][LiveData.getValue], suspending until [isInitialized] if not yet so - */ +/** Get the [value][LiveData.getValue], suspending until [isInitialized] if not yet so */ suspend fun <T, LD : LiveData<T>> LD.getInitializedValue( observe: LD.(Observer<T>) -> Unit = { observeForever(it) }, isInitialized: LD.() -> Boolean = { value != null } @@ -1550,20 +1708,20 @@ suspend fun <T, LD : LiveData<T>> LD.getInitializedValue( } else { suspendCoroutine { continuation: Continuation<T> -> val observer = AtomicReference<Observer<T>>() - observer.set(Observer { newValue -> - if (isInitialized()) { - GlobalScope.launch(Dispatchers.Main) { - observer.getAndSet(null)?.let { observerSnapshot -> - removeObserver(observerSnapshot) - continuation.resume(newValue) + observer.set( + Observer { newValue -> + if (isInitialized()) { + GlobalScope.launch(Dispatchers.Main) { + observer.getAndSet(null)?.let { observerSnapshot -> + removeObserver(observerSnapshot) + continuation.resume(newValue) + } } } } - }) + ) - GlobalScope.launch(Dispatchers.Main) { - observe(observer.get()) - } + GlobalScope.launch(Dispatchers.Main) { observe(observer.get()) } } } } @@ -1571,8 +1729,8 @@ suspend fun <T, LD : LiveData<T>> LD.getInitializedValue( /** * A parallel equivalent of [map] * - * Starts the given suspending function for each item in the collection without waiting for - * previous ones to complete, then suspends until all the started operations finish. + * Starts the given suspending function for each item in the collection without waiting for previous + * ones to complete, then suspends until all the started operations finish. */ suspend inline fun <T, R> Iterable<T>.mapInParallel( context: CoroutineContext, @@ -1594,8 +1752,8 @@ suspend inline fun <T> Iterable<T>.forEachInParallel( } /** - * Check that we haven't already started transitioning to a given destination. If we haven't, - * start navigating to that destination. + * Check that we haven't already started transitioning to a given destination. If we haven't, start + * navigating to that destination. * * @param destResId The ID of the desired destination * @param args The optional bundle of args to be passed to the destination diff --git a/PermissionController/src/com/android/permissioncontroller/privacysources/NotificationListenerPregrants.kt b/PermissionController/src/com/android/permissioncontroller/privacysources/NotificationListenerPregrants.kt index aaf2d32e6..4063ec8b2 100644 --- a/PermissionController/src/com/android/permissioncontroller/privacysources/NotificationListenerPregrants.kt +++ b/PermissionController/src/com/android/permissioncontroller/privacysources/NotificationListenerPregrants.kt @@ -18,32 +18,34 @@ package com.android.permissioncontroller.privacysources import android.content.Context import androidx.annotation.VisibleForTesting -import com.android.safetycenter.resources.SafetyCenterResourcesContext +import com.android.safetycenter.resources.SafetyCenterResourcesApk // (TODO:b/242573074) Remove for Android U. class NotificationListenerPregrants(private val context: Context) { @VisibleForTesting val pregrantedPackagesDelegate = lazy { hashSetOf( - "android", - "com.android.cellbroadcastreceiver", - "com.android.server.telecom", - "com.android.settings", - "com.android.systemui", - "com.android.launcher3", - "com.android.dynsystem", - "com.android.providers.settings", - "com.android.inputdevices", - "com.android.keychain", - "com.android.localtransport", - "com.android.wallpaperbackup", - "com.android.location.fused" - ).also { - it.addAll( - SafetyCenterResourcesContext(context) - .getStringByName("config_NotificationListenerServicePregrants") - .split(",")) - } + "android", + "com.android.cellbroadcastreceiver", + "com.android.server.telecom", + "com.android.settings", + "com.android.systemui", + "com.android.launcher3", + "com.android.dynsystem", + "com.android.providers.settings", + "com.android.inputdevices", + "com.android.keychain", + "com.android.localtransport", + "com.android.wallpaperbackup", + "com.android.location.fused" + ) + .also { + it.addAll( + SafetyCenterResourcesApk(context) + .getStringByName("config_NotificationListenerServicePregrants") + .split(",") + ) + } } val pregrantedPackages: Set<String> by pregrantedPackagesDelegate } diff --git a/PermissionController/src/com/android/permissioncontroller/safetycenter/service/SafetyCenterSearchIndexablesProvider.kt b/PermissionController/src/com/android/permissioncontroller/safetycenter/service/SafetyCenterSearchIndexablesProvider.kt index 463288c64..88dd8a6e3 100644 --- a/PermissionController/src/com/android/permissioncontroller/safetycenter/service/SafetyCenterSearchIndexablesProvider.kt +++ b/PermissionController/src/com/android/permissioncontroller/safetycenter/service/SafetyCenterSearchIndexablesProvider.kt @@ -52,7 +52,7 @@ import com.android.permissioncontroller.safetycenter.ui.model.PrivacyControlsVie import com.android.safetycenter.internaldata.SafetyCenterBundles import com.android.safetycenter.internaldata.SafetyCenterEntryId import com.android.safetycenter.internaldata.SafetyCenterIds -import com.android.safetycenter.resources.SafetyCenterResourcesContext +import com.android.safetycenter.resources.SafetyCenterResourcesApk /** [android.provider.SearchIndexablesProvider] for Safety Center. */ @RequiresApi(Build.VERSION_CODES.TIRAMISU) @@ -67,7 +67,7 @@ class SafetyCenterSearchIndexablesProvider : BaseSearchIndexablesProvider() { val context = requireContext() val safetyCenterManager = context.getSystemService(SafetyCenterManager::class.java) ?: return cursor - val resourcesContext = SafetyCenterResourcesContext(context) + val safetyCenterResourcesApk = SafetyCenterResourcesApk(context) val screenTitle = context.getString(R.string.safety_center_dashboard_page_title) @@ -76,7 +76,11 @@ class SafetyCenterSearchIndexablesProvider : BaseSearchIndexablesProvider() { SdkLevel.isAtLeastU() && safetySourcesGroup.type == SAFETY_SOURCES_GROUP_TYPE_STATEFUL ) { - cursor.addSafetySourcesGroupRow(safetySourcesGroup, resourcesContext, screenTitle) + cursor.addSafetySourcesGroupRow( + safetySourcesGroup, + safetyCenterResourcesApk, + screenTitle + ) } safetySourcesGroup.safetySources .asSequence() @@ -85,7 +89,7 @@ class SafetyCenterSearchIndexablesProvider : BaseSearchIndexablesProvider() { cursor.addSafetySourceRow( context, safetySource, - resourcesContext, + safetyCenterResourcesApk, safetyCenterManager, screenTitle ) @@ -139,11 +143,12 @@ class SafetyCenterSearchIndexablesProvider : BaseSearchIndexablesProvider() { private fun MatrixCursor.addSafetySourcesGroupRow( safetySourcesGroups: SafetySourcesGroup, - resourcesContext: SafetyCenterResourcesContext, + safetyCenterResourcesApk: SafetyCenterResourcesApk, screenTitle: String, ) { val groupTitle = - resourcesContext.getNotEmptyStringOrNull(safetySourcesGroups.titleResId) ?: return + safetyCenterResourcesApk.getNotEmptyStringOrNull(safetySourcesGroups.titleResId) + ?: return newRow() .add(COLUMN_RANK, 0) @@ -157,11 +162,12 @@ class SafetyCenterSearchIndexablesProvider : BaseSearchIndexablesProvider() { private fun MatrixCursor.addSafetySourceRow( context: Context, safetySource: SafetySource, - resourcesContext: SafetyCenterResourcesContext, + safetyCenterResourcesApk: SafetyCenterResourcesApk, safetyCenterManager: SafetyCenterManager, screenTitle: String, ) { - val searchTerms = resourcesContext.getNotEmptyStringOrNull(safetySource.searchTermsResId) + val searchTerms = + safetyCenterResourcesApk.getNotEmptyStringOrNull(safetySource.searchTermsResId) var isPersonalEntryAdded = false var isWorkEntryAdded = false @@ -194,19 +200,19 @@ class SafetyCenterSearchIndexablesProvider : BaseSearchIndexablesProvider() { } if (!isPersonalEntryAdded) { - resourcesContext.getNotEmptyStringOrNull(safetySource.titleResId)?.let { + safetyCenterResourcesApk.getNotEmptyStringOrNull(safetySource.titleResId)?.let { addIndexableRow(title = it, isWorkProfile = false) } } if (!isWorkEntryAdded && safetySource.profile == SafetySource.PROFILE_ALL) { - resourcesContext.getNotEmptyStringOrNull(safetySource.titleForWorkResId)?.let { + safetyCenterResourcesApk.getNotEmptyStringOrNull(safetySource.titleForWorkResId)?.let { addIndexableRow(title = it, isWorkProfile = true) } } } - private fun SafetyCenterResourcesContext.getNotEmptyStringOrNull(resId: Int): String? = + private fun SafetyCenterResourcesApk.getNotEmptyStringOrNull(resId: Int): String? = if (resId != Resources.ID_NULL) { getString(resId).takeIf { it.isNotEmpty() } } else { diff --git a/PermissionController/src/com/android/permissioncontroller/safetycenter/ui/SafetyCenterDashboardFragment.java b/PermissionController/src/com/android/permissioncontroller/safetycenter/ui/SafetyCenterDashboardFragment.java index c42dfc2c2..57462c20e 100644 --- a/PermissionController/src/com/android/permissioncontroller/safetycenter/ui/SafetyCenterDashboardFragment.java +++ b/PermissionController/src/com/android/permissioncontroller/safetycenter/ui/SafetyCenterDashboardFragment.java @@ -53,7 +53,7 @@ import com.android.permissioncontroller.R; import com.android.permissioncontroller.safetycenter.ui.model.SafetyCenterUiData; import com.android.permissioncontroller.safetycenter.ui.model.StatusUiData; import com.android.safetycenter.internaldata.SafetyCenterBundles; -import com.android.safetycenter.resources.SafetyCenterResourcesContext; +import com.android.safetycenter.resources.SafetyCenterResourcesApk; import kotlin.Unit; @@ -178,10 +178,10 @@ public final class SafetyCenterDashboardFragment extends SafetyCenterFragment { private void updateStatus(StatusUiData statusUiData) { if (mIsQuickSettingsFragment) { - SafetyCenterResourcesContext safetyCenterResourcesContext = - new SafetyCenterResourcesContext(requireContext()); + SafetyCenterResourcesApk safetyCenterResourcesApk = + new SafetyCenterResourcesApk(requireContext()); boolean hasPendingActions = - safetyCenterResourcesContext + safetyCenterResourcesApk .getStringByName("overall_severity_level_ok_review_summary") .equals(statusUiData.getOriginalSummary().toString()); diff --git a/PermissionController/src/com/android/permissioncontroller/safetycenter/ui/SafetyCenterFragment.kt b/PermissionController/src/com/android/permissioncontroller/safetycenter/ui/SafetyCenterFragment.kt index 7d5dbb3cb..365dc0efa 100644 --- a/PermissionController/src/com/android/permissioncontroller/safetycenter/ui/SafetyCenterFragment.kt +++ b/PermissionController/src/com/android/permissioncontroller/safetycenter/ui/SafetyCenterFragment.kt @@ -32,7 +32,7 @@ import com.android.permissioncontroller.safetycenter.ui.ParsedSafetyCenterIntent import com.android.permissioncontroller.safetycenter.ui.model.LiveSafetyCenterViewModelFactory import com.android.permissioncontroller.safetycenter.ui.model.SafetyCenterUiData import com.android.permissioncontroller.safetycenter.ui.model.SafetyCenterViewModel -import com.android.safetycenter.resources.SafetyCenterResourcesContext +import com.android.safetycenter.resources.SafetyCenterResourcesApk /** A base fragment that represents a page in Safety Center. */ @RequiresApi(TIRAMISU) @@ -72,7 +72,7 @@ abstract class SafetyCenterFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { sameTaskSourceIds = - SafetyCenterResourcesContext(requireContext()) + SafetyCenterResourcesApk(requireContext()) .getStringByName("config_same_task_safety_source_ids") .split(",") safetyCenterSessionId = requireArguments().getLong(EXTRA_SESSION_ID, INVALID_SESSION_ID) diff --git a/PermissionController/src/com/android/permissioncontroller/safetycenter/ui/SafetyCenterSubpageFragment.kt b/PermissionController/src/com/android/permissioncontroller/safetycenter/ui/SafetyCenterSubpageFragment.kt index 5e45d2b3c..02bf6278e 100644 --- a/PermissionController/src/com/android/permissioncontroller/safetycenter/ui/SafetyCenterSubpageFragment.kt +++ b/PermissionController/src/com/android/permissioncontroller/safetycenter/ui/SafetyCenterSubpageFragment.kt @@ -26,7 +26,7 @@ import com.android.permissioncontroller.Constants.EXTRA_SESSION_ID import com.android.permissioncontroller.R import com.android.permissioncontroller.safetycenter.ui.SafetyBrandChipPreference.Companion.closeSubpage import com.android.permissioncontroller.safetycenter.ui.model.SafetyCenterUiData -import com.android.safetycenter.resources.SafetyCenterResourcesContext +import com.android.safetycenter.resources.SafetyCenterResourcesApk import com.android.settingslib.widget.FooterPreference /** A fragment that represents a generic subpage in Safety Center. */ @@ -88,8 +88,7 @@ class SafetyCenterSubpageFragment : SafetyCenterFragment() { private fun setupIllustration() { val resName = "illustration_${SnakeCaseConverter.fromCamelCase(sourceGroupId)}" val context = requireContext() - val drawable = - SafetyCenterResourcesContext(context).getDrawableByName(resName, context.theme) + val drawable = SafetyCenterResourcesApk(context).getDrawableByName(resName, context.theme) if (drawable == null) { Log.w(TAG, "$sourceGroupId doesn't have any matching illustration") subpageIllustration.setVisible(false) @@ -100,7 +99,7 @@ class SafetyCenterSubpageFragment : SafetyCenterFragment() { private fun setupFooter() { val resName = "${SnakeCaseConverter.fromCamelCase(sourceGroupId)}_footer" - val footerText = SafetyCenterResourcesContext(requireContext()).getStringByName(resName) + val footerText = SafetyCenterResourcesApk(requireContext()).getStringByName(resName) if (footerText.isEmpty()) { Log.w(TAG, "$sourceGroupId doesn't have any matching footer") subpageFooter.setVisible(false) diff --git a/SafetyCenter/ResourcesLib/java/com/android/safetycenter/resources/SafetyCenterResourcesContext.java b/SafetyCenter/ResourcesLib/java/com/android/safetycenter/resources/SafetyCenterResourcesApk.java index 25455dc7a..b0063d051 100644 --- a/SafetyCenter/ResourcesLib/java/com/android/safetycenter/resources/SafetyCenterResourcesContext.java +++ b/SafetyCenter/ResourcesLib/java/com/android/safetycenter/resources/SafetyCenterResourcesApk.java @@ -46,9 +46,9 @@ import java.util.List; * <p>This class isn't thread safe. Thread safety must be handled by the caller, or this may cause * the resources APK {@link Context} to be initialized multiple times. */ -public final class SafetyCenterResourcesContext { +public final class SafetyCenterResourcesApk { - private static final String TAG = "SafetyCenterResContext"; + private static final String TAG = "SafetyCenterResApk"; /** Intent action that is used to identify the Safety Center resources APK */ private static final String RESOURCES_APK_ACTION = @@ -86,11 +86,11 @@ public final class SafetyCenterResourcesContext { // Cached context from the resources APK. @Nullable private Context mResourcesApkContext; - public SafetyCenterResourcesContext(Context context) { + public SafetyCenterResourcesApk(Context context) { this(context, /* shouldFallbackIfNamedResourceNotFound */ true); } - private SafetyCenterResourcesContext( + private SafetyCenterResourcesApk( Context context, boolean shouldFallbackIfNamedResourceNotFound) { this( context, @@ -101,7 +101,7 @@ public final class SafetyCenterResourcesContext { } @VisibleForTesting - SafetyCenterResourcesContext( + SafetyCenterResourcesApk( Context context, String resourcesApkAction, String resourcesApkPath, @@ -114,11 +114,11 @@ public final class SafetyCenterResourcesContext { mShouldFallbackIfNamedResourceNotFound = shouldFallbackIfNamedResourceNotFound; } - /** Creates a new {@link SafetyCenterResourcesContext} for testing. */ + /** Creates a new {@link SafetyCenterResourcesApk} for testing. */ @VisibleForTesting - public static SafetyCenterResourcesContext forTests(Context contextBase) { - return new SafetyCenterResourcesContext( - contextBase, /* shouldFallbackIfNamedResourceNotFound */ false); + public static SafetyCenterResourcesApk forTests(Context context) { + return new SafetyCenterResourcesApk( + context, /* shouldFallbackIfNamedResourceNotFound */ false); } /** @@ -140,7 +140,7 @@ public final class SafetyCenterResourcesContext { * * <p>Throws an {@link IllegalStateException} if the resources APK is not available */ - public Context getResourcesApkContext() { + public Context getContext() { if (mResourcesApkContext != null) { return mResourcesApkContext; } @@ -213,7 +213,7 @@ public final class SafetyCenterResourcesContext { /** Calls {@link Context#getResources()} for the resources APK {@link Context}. */ public Resources getResources() { - return getResourcesApkContext().getResources(); + return getContext().getResources(); } /** @@ -228,21 +228,21 @@ public final class SafetyCenterResourcesContext { @VisibleForTesting @Nullable InputStream getSafetyCenterConfig(String configName) { - int id = getResIdAndMaybeThrowIfNull(configName, "raw"); - if (id == Resources.ID_NULL) { + int resId = getResIdAndMaybeThrowIfNull(configName, "raw"); + if (resId == Resources.ID_NULL) { return null; } - return getResources().openRawResource(id); + return getResources().openRawResource(resId); } /** Calls {@link Context#getString(int)} for the resources APK {@link Context}. */ public String getString(@StringRes int stringId) { - return getResourcesApkContext().getString(stringId); + return getContext().getString(stringId); } /** Same as {@link #getString(int)} but with the given {@code formatArgs}. */ public String getString(@StringRes int stringId, Object... formatArgs) { - return getResourcesApkContext().getString(stringId, formatArgs); + return getContext().getString(stringId, formatArgs); } /** @@ -317,7 +317,7 @@ public final class SafetyCenterResourcesContext { if (resId == Resources.ID_NULL) { return null; } - return Icon.createWithResource(getResourcesApkContext().getPackageName(), resId); + return Icon.createWithResource(getContext().getPackageName(), resId); } /** @@ -333,7 +333,7 @@ public final class SafetyCenterResourcesContext { if (resId == Resources.ID_NULL) { return null; } - return getResources().getColor(resId, getResourcesApkContext().getTheme()); + return getResources().getColor(resId, getContext().getTheme()); } private int getResIdAndMaybeThrowIfNull(String name, String type) { @@ -351,6 +351,6 @@ public final class SafetyCenterResourcesContext { private int getResId(String name, String type) { // TODO(b/227738283): profile the performance of this operation and consider adding caching // or finding some alternative solution. - return getResources().getIdentifier(name, type, getResourcesApkContext().getPackageName()); + return getResources().getIdentifier(name, type, getContext().getPackageName()); } } diff --git a/SafetyCenter/ResourcesLib/tests/java/com/android/safetycenter/resources/SafetyCenterResourcesApkTest.kt b/SafetyCenter/ResourcesLib/tests/java/com/android/safetycenter/resources/SafetyCenterResourcesApkTest.kt new file mode 100644 index 000000000..b52595b13 --- /dev/null +++ b/SafetyCenter/ResourcesLib/tests/java/com/android/safetycenter/resources/SafetyCenterResourcesApkTest.kt @@ -0,0 +1,440 @@ +/* + * Copyright (C) 2022 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.safetycenter.resources + +import android.content.Context +import android.content.pm.PackageManager +import android.content.res.Resources +import androidx.test.core.app.ApplicationProvider.getApplicationContext +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.google.common.truth.Truth.assertThat +import java.lang.IllegalStateException +import kotlin.test.assertFailsWith +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class SafetyCenterResourcesApkTest { + private val context: Context = getApplicationContext() + + @Test + fun init_withValidInputs_returnsTrue() { + val resourcesApk = newSafetyCenterResourcesApk() + + val initialized = resourcesApk.init() + + assertThat(initialized).isTrue() + } + + @Test + fun init_withWrongAction_returnsFalse() { + val resourcesApk = newSafetyCenterResourcesApk(resourcesApkAction = "wrong") + + val initialized = resourcesApk.init() + + assertThat(initialized).isFalse() + } + + @Test + fun init_withWrongPath_returnsFalse() { + val resourcesApk = + newSafetyCenterResourcesApk(resourcesApkPath = "/apex/com.android.permission") + + val initialized = resourcesApk.init() + + assertThat(initialized).isFalse() + } + + @Test + fun init_withWrongFlags_returnsFalse() { + val resourcesApk = newSafetyCenterResourcesApk(flags = PackageManager.MATCH_SYSTEM_ONLY) + + val initialized = resourcesApk.init() + + assertThat(initialized).isFalse() + } + + @Test + fun getContext_withValidInputs_returnsResourcesApkContext() { + val resourcesApk = newSafetyCenterResourcesApk() + + val resourcesApkContext = resourcesApk.context + + assertThat(resourcesApkContext.packageName).isEqualTo(RESOURCES_APK_PKG_NAME) + } + + @Test + fun getContext_withWrongAction_throws() { + val resourcesApk = newSafetyCenterResourcesApk(resourcesApkAction = "wrong") + + assertFailsWith(IllegalStateException::class) { resourcesApk.context } + } + + @Test + fun getContext_withWrongPath_throws() { + val resourcesApk = + newSafetyCenterResourcesApk(resourcesApkPath = "/apex/com.android.permission") + + assertFailsWith(IllegalStateException::class) { resourcesApk.context } + } + + @Test + fun getContext_withWrongFlags_throws() { + val resourcesApk = newSafetyCenterResourcesApk(flags = PackageManager.MATCH_SYSTEM_ONLY) + + assertFailsWith(IllegalStateException::class) { resourcesApk.context } + } + + @Test + fun getResources_withValidInputs_returnsResourcesApkContextResources() { + val resourcesApk = newSafetyCenterResourcesApk() + + val resources = resourcesApk.resources + + assertThat(resources).isEqualTo(resourcesApk.context.resources) + } + + @Test + fun getResources_nullContext_throwsRegardlessOfFallback() { + val resourcesApk = + newSafetyCenterResourcesApk(resourcesApkAction = "wrong", fallback = true) + + assertFailsWith(IllegalStateException::class) { resourcesApk.resources } + } + + @Test + fun getSafetyCenterConfig_withValidInputs_returnsConfigContent() { + val resourcesApk = newSafetyCenterResourcesApk() + + val config = resourcesApk.safetyCenterConfig + val configContent = config?.bufferedReader().use { it?.readText() } + + assertThat(config).isNotNull() + assertThat(configContent).isEqualTo(CONFIG_CONTENT) + } + + @Test + fun getSafetyCenterConfig_anotherValidConfigName_returnsConfigContent() { + val resourcesApk = newSafetyCenterResourcesApk() + + val config = resourcesApk.getSafetyCenterConfig(CONFIG_NAME) + val configContent = config?.bufferedReader().use { it?.readText() } + + assertThat(config).isNotNull() + assertThat(configContent).isEqualTo(CONFIG_CONTENT) + } + + @Test + fun getSafetyCenterConfig_invalidConfigNameWithFallback_returnsNull() { + val resourcesApk = newSafetyCenterResourcesApk(fallback = true) + + assertThat(resourcesApk.getSafetyCenterConfig("wrong")).isNull() + } + + @Test + fun getSafetyCenterConfig_invalidConfigNameWithoutFallback_throws() { + val resourcesApk = newSafetyCenterResourcesApk(fallback = false) + + assertFailsWith(Resources.NotFoundException::class) { + resourcesApk.getSafetyCenterConfig("wrong") + } + } + + @Test + fun getSafetyCenterConfig_nullContext_throwsRegardlessOfFallback() { + val resourcesApk = + newSafetyCenterResourcesApk(resourcesApkAction = "wrong", fallback = true) + + assertFailsWith(IllegalStateException::class) { resourcesApk.safetyCenterConfig } + } + + @Test + fun getString_validString_returnsString() { + val resourcesApk = newSafetyCenterResourcesApk() + + val ok = resourcesApk.getString(android.R.string.ok) + + assertThat(ok).isEqualTo("OK") + } + + @Test + fun getString_nullContext_throwsRegardlessOfFallback() { + val resourcesApk = + newSafetyCenterResourcesApk(resourcesApkAction = "wrong", fallback = true) + + assertFailsWith(IllegalStateException::class) { + resourcesApk.getString(android.R.string.ok) + } + } + + @Test + fun getStringWithFormatArgs_validString_returnsString() { + val resourcesApk = newSafetyCenterResourcesApk() + + val ok = resourcesApk.getString(android.R.string.ok, "") + + assertThat(ok).isEqualTo("OK") + } + + @Test + fun getStringWithFormatArgs_nullContext_throwsRegardlessOfFallback() { + val resourcesApk = + newSafetyCenterResourcesApk(resourcesApkAction = "wrong", fallback = true) + + assertFailsWith(IllegalStateException::class) { + resourcesApk.getString(android.R.string.ok, "") + } + } + + @Test + fun getStringByName_validString_returnsString() { + val resourcesApk = newSafetyCenterResourcesApk() + + assertThat(resourcesApk.getStringByName("valid_string")).isEqualTo("I exist!") + } + + @Test + fun getStringByName_invalidStringWithFallback_returnsEmptyString() { + val resourcesApk = newSafetyCenterResourcesApk(fallback = true) + + assertThat(resourcesApk.getStringByName("invalid_string")).isEqualTo("") + } + + @Test + fun getStringByName_invalidStringWithoutFallback_throws() { + val resourcesApk = newSafetyCenterResourcesApk(fallback = false) + + assertFailsWith(Resources.NotFoundException::class) { + resourcesApk.getStringByName("invalid_string") + } + } + + @Test + fun getStringByName_nullContext_throwsRegardlessOfFallback() { + val resourcesApk = + newSafetyCenterResourcesApk(resourcesApkAction = "wrong", fallback = true) + + assertFailsWith(IllegalStateException::class) { + resourcesApk.getStringByName("valid_string") + } + } + + @Test + fun getStringByNameWithFormatArgs_validString_returnsString() { + val resourcesApk = newSafetyCenterResourcesApk() + + assertThat(resourcesApk.getStringByName("valid_string", "")).isEqualTo("I exist!") + } + + @Test + fun getStringByNameWithFormatArgs_invalidStringWithFallback_returnsEmptyString() { + val resourcesApk = newSafetyCenterResourcesApk(fallback = true) + + assertThat(resourcesApk.getStringByName("invalid_string", "")).isEqualTo("") + } + + @Test + fun getStringByNameWithFormatArgs_invalidStringWithoutFallback_throws() { + val resourcesApk = newSafetyCenterResourcesApk(fallback = false) + + assertFailsWith(Resources.NotFoundException::class) { + resourcesApk.getStringByName("invalid_string", "") + } + } + + @Test + fun getStringByNameWithFormatArgs_nullContext_throwsRegardlessOfFallback() { + val resourcesApk = + newSafetyCenterResourcesApk(resourcesApkAction = "wrong", fallback = true) + + assertFailsWith(IllegalStateException::class) { + resourcesApk.getStringByName("valid_string", "") + } + } + + @Test + fun getOptionalString_validString_returnsString() { + val resourcesApk = newSafetyCenterResourcesApk() + + val ok = resourcesApk.getOptionalString(android.R.string.ok) + + assertThat(ok).isEqualTo("OK") + } + + @Test + fun getOptionalString_resourceIdNull_returnsNull() { + val resourcesApk = newSafetyCenterResourcesApk() + + val string = resourcesApk.getOptionalString(Resources.ID_NULL) + + assertThat(string).isNull() + } + + @Test + fun getOptionalString_nullContext_throwsRegardlessOfFallback() { + val resourcesApk = + newSafetyCenterResourcesApk(resourcesApkAction = "wrong", fallback = true) + + assertFailsWith(IllegalStateException::class) { + resourcesApk.getOptionalString(android.R.string.ok) + } + } + + @Test + fun getOptionalStringByName_validString_returnsString() { + val resourcesApk = newSafetyCenterResourcesApk() + + assertThat(resourcesApk.getOptionalStringByName("valid_string")).isEqualTo("I exist!") + } + + @Test + fun getOptionalStringByName_invalidStringWithFallback_returnsNull() { + val resourcesApk = newSafetyCenterResourcesApk(fallback = true) + + assertThat(resourcesApk.getOptionalStringByName("invalid_string")).isNull() + } + + @Test + fun getOptionalStringByName_invalidStringWithoutFallback_returnsNull() { + val resourcesApk = newSafetyCenterResourcesApk(fallback = false) + + assertThat(resourcesApk.getOptionalStringByName("invalid_string")).isNull() + } + + @Test + fun getOptionalStringByName_nullContext_throwsRegardlessOfFallback() { + val resourcesApk = + newSafetyCenterResourcesApk(resourcesApkAction = "wrong", fallback = true) + + assertFailsWith(IllegalStateException::class) { + resourcesApk.getOptionalStringByName("valid_string") + } + } + + @Test + fun getDrawableByName_validDrawable_returnsDrawable() { + val resourcesApk = newSafetyCenterResourcesApk() + + assertThat(resourcesApk.getDrawableByName("valid_drawable", context.theme)).isNotNull() + } + + @Test + fun getDrawableByName_invalidDrawableWithFallback_returnsNull() { + val resourcesApk = newSafetyCenterResourcesApk(fallback = true) + + assertThat(resourcesApk.getDrawableByName("invalid_drawable", context.theme)).isNull() + } + + @Test + fun getDrawableByName_invalidDrawableWithoutFallback_throws() { + val resourcesApk = newSafetyCenterResourcesApk(fallback = false) + + assertFailsWith(Resources.NotFoundException::class) { + resourcesApk.getDrawableByName("invalid_drawable", context.theme) + } + } + + @Test + fun getDrawableByName_nullContext_throwsRegardlessOfFallback() { + val resourcesApk = + newSafetyCenterResourcesApk(resourcesApkAction = "wrong", fallback = true) + + assertFailsWith(IllegalStateException::class) { + resourcesApk.getDrawableByName("valid_drawable", context.theme) + } + } + + @Test + fun getIconByDrawableName_validDrawable_returnsIcon() { + val resourcesApk = newSafetyCenterResourcesApk() + + assertThat(resourcesApk.getIconByDrawableName("valid_drawable")).isNotNull() + } + + @Test + fun getIconByDrawableName_invalidDrawableWithFallback_returnsNull() { + val resourcesApk = newSafetyCenterResourcesApk(fallback = true) + + assertThat(resourcesApk.getIconByDrawableName("invalid_drawable")).isNull() + } + + @Test + fun getIconByDrawableName_invalidDrawableWithoutFallback_throws() { + val resourcesApk = newSafetyCenterResourcesApk(fallback = false) + + assertFailsWith(Resources.NotFoundException::class) { + resourcesApk.getIconByDrawableName("invalid_drawable") + } + } + + @Test + fun getIconByDrawableByName_nullContext_throwsRegardlessOfFallback() { + val resourcesApk = + newSafetyCenterResourcesApk(resourcesApkAction = "wrong", fallback = true) + + assertFailsWith(IllegalStateException::class) { + resourcesApk.getIconByDrawableName("valid_drawable") + } + } + + @Test + fun getColorByName_validColor_returnsColor() { + val resourcesApk = newSafetyCenterResourcesApk() + + assertThat(resourcesApk.getColorByName("valid_color")).isNotNull() + } + + @Test + fun getColorByName_invalidColorWithFallback_returnsNull() { + val resourcesApk = newSafetyCenterResourcesApk(fallback = true) + + assertThat(resourcesApk.getColorByName("invalid_color")).isNull() + } + + @Test + fun getColorByName_invalidColorWithoutFallback_throws() { + val resourcesApk = newSafetyCenterResourcesApk(fallback = false) + + assertFailsWith(Resources.NotFoundException::class) { + resourcesApk.getColorByName("invalid_color") + } + } + + @Test + fun getColorByName_nullContext_throwsRegardlessOfFallback() { + val resourcesApk = + newSafetyCenterResourcesApk(resourcesApkAction = "wrong", fallback = true) + + assertFailsWith(IllegalStateException::class) { resourcesApk.getColorByName("valid_color") } + } + + private fun newSafetyCenterResourcesApk( + resourcesApkAction: String = RESOURCES_APK_ACTION, + resourcesApkPath: String = "", + flags: Int = 0, + fallback: Boolean = false + ) = SafetyCenterResourcesApk(context, resourcesApkAction, resourcesApkPath, flags, fallback) + + companion object { + const val RESOURCES_APK_ACTION = + "com.android.safetycenter.tests.intent.action.SAFETY_CENTER_TEST_RESOURCES_APK" + const val RESOURCES_APK_PKG_NAME = + "com.android.safetycenter.tests.config.safetycenterresourceslibtestresources" + const val CONFIG_NAME = "test" + const val CONFIG_CONTENT = "TEST" + } +} diff --git a/SafetyCenter/ResourcesLib/tests/java/com/android/safetycenter/resources/SafetyCenterResourcesContextTest.kt b/SafetyCenter/ResourcesLib/tests/java/com/android/safetycenter/resources/SafetyCenterResourcesContextTest.kt deleted file mode 100644 index 33ff7543e..000000000 --- a/SafetyCenter/ResourcesLib/tests/java/com/android/safetycenter/resources/SafetyCenterResourcesContextTest.kt +++ /dev/null @@ -1,442 +0,0 @@ -/* - * Copyright (C) 2022 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.safetycenter.resources - -import android.content.Context -import android.content.pm.PackageManager -import android.content.res.Resources -import androidx.test.core.app.ApplicationProvider.getApplicationContext -import androidx.test.ext.junit.runners.AndroidJUnit4 -import com.google.common.truth.Truth.assertThat -import java.lang.IllegalStateException -import kotlin.test.assertFailsWith -import org.junit.Test -import org.junit.runner.RunWith - -@RunWith(AndroidJUnit4::class) -class SafetyCenterResourcesContextTest { - private val context: Context = getApplicationContext() - - @Test - fun init_withValidInputs_returnsTrue() { - val resourcesContext = createNewResourcesContext() - - val initialized = resourcesContext.init() - - assertThat(initialized).isTrue() - } - - @Test - fun init_withWrongAction_returnsFalse() { - val resourcesContext = createNewResourcesContext(resourcesApkAction = "wrong") - - val initialized = resourcesContext.init() - - assertThat(initialized).isFalse() - } - - @Test - fun init_withWrongPath_returnsFalse() { - val resourcesContext = - createNewResourcesContext(resourcesApkPath = "/apex/com.android.permission") - - val initialized = resourcesContext.init() - - assertThat(initialized).isFalse() - } - - @Test - fun init_withWrongFlags_returnsFalse() { - val resourcesContext = createNewResourcesContext(flags = PackageManager.MATCH_SYSTEM_ONLY) - - val initialized = resourcesContext.init() - - assertThat(initialized).isFalse() - } - - @Test - fun getResourcesApkContext_withValidInputs_returnsResourcesApkContext() { - val resourcesContext = createNewResourcesContext() - - val resourcesApkContext = resourcesContext.resourcesApkContext - - assertThat(resourcesApkContext.packageName).isEqualTo(RESOURCES_APK_PKG_NAME) - } - - @Test - fun getResourcesApkContext_withWrongAction_throws() { - val resourcesContext = createNewResourcesContext(resourcesApkAction = "wrong") - - assertFailsWith(IllegalStateException::class) { resourcesContext.resourcesApkContext } - } - - @Test - fun getResourcesApkContext_withWrongPath_throws() { - val resourcesContext = - createNewResourcesContext(resourcesApkPath = "/apex/com.android.permission") - - assertFailsWith(IllegalStateException::class) { resourcesContext.resourcesApkContext } - } - - @Test - fun getResourcesApkContext_withWrongFlags_throws() { - val resourcesContext = createNewResourcesContext(flags = PackageManager.MATCH_SYSTEM_ONLY) - - assertFailsWith(IllegalStateException::class) { resourcesContext.resourcesApkContext } - } - - @Test - fun getResources_withValidInputs_returnsResourcesApkContextResources() { - val resourcesContext = createNewResourcesContext() - - val resources = resourcesContext.resources - - assertThat(resources).isEqualTo(resourcesContext.resourcesApkContext.resources) - } - - @Test - fun getResources_nullContext_throwsRegardlessOfFallback() { - val resourcesContext = - createNewResourcesContext(resourcesApkAction = "wrong", fallback = true) - - assertFailsWith(IllegalStateException::class) { resourcesContext.resources } - } - - @Test - fun getSafetyCenterConfig_withValidInputs_returnsConfigContent() { - val resourcesContext = createNewResourcesContext() - - val config = resourcesContext.safetyCenterConfig - val configContent = config?.bufferedReader().use { it?.readText() } - - assertThat(config).isNotNull() - assertThat(configContent).isEqualTo(CONFIG_CONTENT) - } - - @Test - fun getSafetyCenterConfig_anotherValidConfigName_returnsConfigContent() { - val resourcesContext = createNewResourcesContext() - - val config = resourcesContext.getSafetyCenterConfig(CONFIG_NAME) - val configContent = config?.bufferedReader().use { it?.readText() } - - assertThat(config).isNotNull() - assertThat(configContent).isEqualTo(CONFIG_CONTENT) - } - - @Test - fun getSafetyCenterConfig_invalidConfigNameWithFallback_returnsNull() { - val resourcesContext = createNewResourcesContext(fallback = true) - - assertThat(resourcesContext.getSafetyCenterConfig("wrong")).isNull() - } - - @Test - fun getSafetyCenterConfig_invalidConfigNameWithoutFallback_throws() { - val resourcesContext = createNewResourcesContext(fallback = false) - - assertFailsWith(Resources.NotFoundException::class) { - resourcesContext.getSafetyCenterConfig("wrong") - } - } - - @Test - fun getSafetyCenterConfig_nullContext_throwsRegardlessOfFallback() { - val resourcesContext = - createNewResourcesContext(resourcesApkAction = "wrong", fallback = true) - - assertFailsWith(IllegalStateException::class) { resourcesContext.safetyCenterConfig } - } - - @Test - fun getString_validString_returnsString() { - val resourcesContext = createNewResourcesContext() - - val ok = resourcesContext.getString(android.R.string.ok) - - assertThat(ok).isEqualTo("OK") - } - - @Test - fun getString_nullContext_throwsRegardlessOfFallback() { - val resourcesContext = - createNewResourcesContext(resourcesApkAction = "wrong", fallback = true) - - assertFailsWith(IllegalStateException::class) { - resourcesContext.getString(android.R.string.ok) - } - } - - @Test - fun getStringWithFormatArgs_validString_returnsString() { - val resourcesContext = createNewResourcesContext() - - val ok = resourcesContext.getString(android.R.string.ok, "") - - assertThat(ok).isEqualTo("OK") - } - - @Test - fun getStringWithFormatArgs_nullContext_throwsRegardlessOfFallback() { - val resourcesContext = - createNewResourcesContext(resourcesApkAction = "wrong", fallback = true) - - assertFailsWith(IllegalStateException::class) { - resourcesContext.getString(android.R.string.ok, "") - } - } - - @Test - fun getStringByName_validString_returnsString() { - val resourcesContext = createNewResourcesContext() - - assertThat(resourcesContext.getStringByName("valid_string")).isEqualTo("I exist!") - } - - @Test - fun getStringByName_invalidStringWithFallback_returnsEmptyString() { - val resourcesContext = createNewResourcesContext(fallback = true) - - assertThat(resourcesContext.getStringByName("invalid_string")).isEqualTo("") - } - - @Test - fun getStringByName_invalidStringWithoutFallback_throws() { - val resourcesContext = createNewResourcesContext(fallback = false) - - assertFailsWith(Resources.NotFoundException::class) { - resourcesContext.getStringByName("invalid_string") - } - } - - @Test - fun getStringByName_nullContext_throwsRegardlessOfFallback() { - val resourcesContext = - createNewResourcesContext(resourcesApkAction = "wrong", fallback = true) - - assertFailsWith(IllegalStateException::class) { - resourcesContext.getStringByName("valid_string") - } - } - - @Test - fun getStringByNameWithFormatArgs_validString_returnsString() { - val resourcesContext = createNewResourcesContext() - - assertThat(resourcesContext.getStringByName("valid_string", "")).isEqualTo("I exist!") - } - - @Test - fun getStringByNameWithFormatArgs_invalidStringWithFallback_returnsEmptyString() { - val resourcesContext = createNewResourcesContext(fallback = true) - - assertThat(resourcesContext.getStringByName("invalid_string", "")).isEqualTo("") - } - - @Test - fun getStringByNameWithFormatArgs_invalidStringWithoutFallback_throws() { - val resourcesContext = createNewResourcesContext(fallback = false) - - assertFailsWith(Resources.NotFoundException::class) { - resourcesContext.getStringByName("invalid_string", "") - } - } - - @Test - fun getStringByNameWithFormatArgs_nullContext_throwsRegardlessOfFallback() { - val resourcesContext = - createNewResourcesContext(resourcesApkAction = "wrong", fallback = true) - - assertFailsWith(IllegalStateException::class) { - resourcesContext.getStringByName("valid_string", "") - } - } - - @Test - fun getOptionalString_validString_returnsString() { - val resourcesContext = createNewResourcesContext() - - val ok = resourcesContext.getOptionalString(android.R.string.ok) - - assertThat(ok).isEqualTo("OK") - } - - @Test - fun getOptionalString_resourceIdNull_returnsNull() { - val resourcesContext = createNewResourcesContext() - - val string = resourcesContext.getOptionalString(Resources.ID_NULL) - - assertThat(string).isNull() - } - - @Test - fun getOptionalString_nullContext_throwsRegardlessOfFallback() { - val resourcesContext = - createNewResourcesContext(resourcesApkAction = "wrong", fallback = true) - - assertFailsWith(IllegalStateException::class) { - resourcesContext.getOptionalString(android.R.string.ok) - } - } - - @Test - fun getOptionalStringByName_validString_returnsString() { - val resourcesContext = createNewResourcesContext() - - assertThat(resourcesContext.getOptionalStringByName("valid_string")).isEqualTo("I exist!") - } - - @Test - fun getOptionalStringByName_invalidStringWithFallback_returnsNull() { - val resourcesContext = createNewResourcesContext(fallback = true) - - assertThat(resourcesContext.getOptionalStringByName("invalid_string")).isNull() - } - - @Test - fun getOptionalStringByName_invalidStringWithoutFallback_returnsNull() { - val resourcesContext = createNewResourcesContext(fallback = false) - - assertThat(resourcesContext.getOptionalStringByName("invalid_string")).isNull() - } - - @Test - fun getOptionalStringByName_nullContext_throwsRegardlessOfFallback() { - val resourcesContext = - createNewResourcesContext(resourcesApkAction = "wrong", fallback = true) - - assertFailsWith(IllegalStateException::class) { - resourcesContext.getOptionalStringByName("valid_string") - } - } - - @Test - fun getDrawableByName_validDrawable_returnsDrawable() { - val resourcesContext = createNewResourcesContext() - - assertThat(resourcesContext.getDrawableByName("valid_drawable", context.theme)).isNotNull() - } - - @Test - fun getDrawableByName_invalidDrawableWithFallback_returnsNull() { - val resourcesContext = createNewResourcesContext(fallback = true) - - assertThat(resourcesContext.getDrawableByName("invalid_drawable", context.theme)).isNull() - } - - @Test - fun getDrawableByName_invalidDrawableWithoutFallback_throws() { - val resourcesContext = createNewResourcesContext(fallback = false) - - assertFailsWith(Resources.NotFoundException::class) { - resourcesContext.getDrawableByName("invalid_drawable", context.theme) - } - } - - @Test - fun getDrawableByName_nullContext_throwsRegardlessOfFallback() { - val resourcesContext = - createNewResourcesContext(resourcesApkAction = "wrong", fallback = true) - - assertFailsWith(IllegalStateException::class) { - resourcesContext.getDrawableByName("valid_drawable", context.theme) - } - } - - @Test - fun getIconByDrawableName_validDrawable_returnsIcon() { - val resourcesContext = createNewResourcesContext() - - assertThat(resourcesContext.getIconByDrawableName("valid_drawable")).isNotNull() - } - - @Test - fun getIconByDrawableName_invalidDrawableWithFallback_returnsNull() { - val resourcesContext = createNewResourcesContext(fallback = true) - - assertThat(resourcesContext.getIconByDrawableName("invalid_drawable")).isNull() - } - - @Test - fun getIconByDrawableName_invalidDrawableWithoutFallback_throws() { - val resourcesContext = createNewResourcesContext(fallback = false) - - assertFailsWith(Resources.NotFoundException::class) { - resourcesContext.getIconByDrawableName("invalid_drawable") - } - } - - @Test - fun getIconByDrawableByName_nullContext_throwsRegardlessOfFallback() { - val resourcesContext = - createNewResourcesContext(resourcesApkAction = "wrong", fallback = true) - - assertFailsWith(IllegalStateException::class) { - resourcesContext.getIconByDrawableName("valid_drawable") - } - } - - @Test - fun getColorByName_validColor_returnsColor() { - val resourcesContext = createNewResourcesContext() - - assertThat(resourcesContext.getColorByName("valid_color")).isNotNull() - } - - @Test - fun getColorByName_invalidColorWithFallback_returnsNull() { - val resourcesContext = createNewResourcesContext(fallback = true) - - assertThat(resourcesContext.getColorByName("invalid_color")).isNull() - } - - @Test - fun getColorByName_invalidColorWithoutFallback_throws() { - val resourcesContext = createNewResourcesContext(fallback = false) - - assertFailsWith(Resources.NotFoundException::class) { - resourcesContext.getColorByName("invalid_color") - } - } - - @Test - fun getColorByName_nullContext_throwsRegardlessOfFallback() { - val resourcesContext = - createNewResourcesContext(resourcesApkAction = "wrong", fallback = true) - - assertFailsWith(IllegalStateException::class) { - resourcesContext.getColorByName("valid_color") - } - } - - private fun createNewResourcesContext( - resourcesApkAction: String = RESOURCES_APK_ACTION, - resourcesApkPath: String = "", - flags: Int = 0, - fallback: Boolean = false - ) = SafetyCenterResourcesContext(context, resourcesApkAction, resourcesApkPath, flags, fallback) - - companion object { - const val RESOURCES_APK_ACTION = - "com.android.safetycenter.tests.intent.action.SAFETY_CENTER_TEST_RESOURCES_APK" - const val RESOURCES_APK_PKG_NAME = - "com.android.safetycenter.tests.config.safetycenterresourceslibtestresources" - const val CONFIG_NAME = "test" - const val CONFIG_CONTENT = "TEST" - } -} diff --git a/service/java/com/android/safetycenter/DevicePolicyResources.java b/service/java/com/android/safetycenter/DevicePolicyResources.java index 2368425f7..da51b0190 100644 --- a/service/java/com/android/safetycenter/DevicePolicyResources.java +++ b/service/java/com/android/safetycenter/DevicePolicyResources.java @@ -28,7 +28,7 @@ import android.os.Binder; import androidx.annotation.RequiresApi; -import com.android.safetycenter.resources.SafetyCenterResourcesContext; +import com.android.safetycenter.resources.SafetyCenterResourcesApk; import java.util.function.Supplier; @@ -46,31 +46,30 @@ final class DevicePolicyResources { * DevicePolicyResourcesManager#getString}. */ static String getSafetySourceWorkString( - SafetyCenterResourcesContext safetyCenterResourcesContext, + SafetyCenterResourcesApk safetyCenterResourcesApk, String safetySourceId, @StringRes int workResId) { return getEnterpriseString( - safetyCenterResourcesContext.getResourcesApkContext(), + safetyCenterResourcesApk.getContext(), safetySourceId, - () -> safetyCenterResourcesContext.getString(workResId)); + () -> safetyCenterResourcesApk.getString(workResId)); } /** * Returns the updated string for the {@code work_profile_paused} string by calling {@link * DevicePolicyResourcesManager#getString}. */ - static String getWorkProfilePausedString( - SafetyCenterResourcesContext safetyCenterResourcesContext) { + static String getWorkProfilePausedString(SafetyCenterResourcesApk safetyCenterResourcesApk) { return getEnterpriseString( - safetyCenterResourcesContext.getResourcesApkContext(), + safetyCenterResourcesApk.getContext(), WORK_PROFILE_PAUSED_TITLE, - () -> safetyCenterResourcesContext.getStringByName("work_profile_paused")); + () -> safetyCenterResourcesApk.getStringByName("work_profile_paused")); } private static String getEnterpriseString( Context context, String devicePolicyIdentifier, Supplier<String> defaultValueLoader) { // This call requires the caller’s identity to match the package name of the given context. - // However, the SafetyCenterResourcesContext’s has package name "android", which does not + // However, the SafetyCenterResourceApk Context's has package name "android", which does not // necessarily match the caller’s package when making Binder calls, so the calling identity // has to be cleared. final long callingId = Binder.clearCallingIdentity(); diff --git a/service/java/com/android/safetycenter/PendingIntentFactory.java b/service/java/com/android/safetycenter/PendingIntentFactory.java index 4f54e0b82..da9915968 100644 --- a/service/java/com/android/safetycenter/PendingIntentFactory.java +++ b/service/java/com/android/safetycenter/PendingIntentFactory.java @@ -34,7 +34,7 @@ import android.util.Log; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; -import com.android.safetycenter.resources.SafetyCenterResourcesContext; +import com.android.safetycenter.resources.SafetyCenterResourcesApk; import java.util.Arrays; @@ -53,12 +53,11 @@ public final class PendingIntentFactory { private static final String IS_SETTINGS_HOMEPAGE = "is_from_settings_homepage"; private final Context mContext; - private final SafetyCenterResourcesContext mSafetyCenterResourcesContext; + private final SafetyCenterResourcesApk mSafetyCenterResourcesApk; - PendingIntentFactory( - Context context, SafetyCenterResourcesContext safetyCenterResourcesContext) { + PendingIntentFactory(Context context, SafetyCenterResourcesApk safetyCenterResourcesApk) { mContext = context; - mSafetyCenterResourcesContext = safetyCenterResourcesContext; + mSafetyCenterResourcesApk = safetyCenterResourcesApk; } /** @@ -146,7 +145,7 @@ public final class PendingIntentFactory { private boolean shouldAddSettingsHomepageExtra(String sourceId) { return Arrays.asList( - mSafetyCenterResourcesContext + mSafetyCenterResourcesApk .getStringByName("config_useSettingsHomepageIntentExtra") .split(",")) .contains(sourceId); diff --git a/service/java/com/android/safetycenter/SafetyCenterConfigReader.java b/service/java/com/android/safetycenter/SafetyCenterConfigReader.java index 49417369a..bbd35eb5e 100644 --- a/service/java/com/android/safetycenter/SafetyCenterConfigReader.java +++ b/service/java/com/android/safetycenter/SafetyCenterConfigReader.java @@ -33,7 +33,7 @@ import androidx.annotation.RequiresApi; import com.android.safetycenter.config.ParseException; import com.android.safetycenter.config.SafetyCenterConfigParser; -import com.android.safetycenter.resources.SafetyCenterResourcesContext; +import com.android.safetycenter.resources.SafetyCenterResourcesApk; import java.io.InputStream; import java.io.PrintWriter; @@ -56,15 +56,15 @@ public final class SafetyCenterConfigReader { private static final String TAG = "SafetyCenterConfigReade"; - private final SafetyCenterResourcesContext mSafetyCenterResourcesContext; + private final SafetyCenterResourcesApk mSafetyCenterResourcesApk; @Nullable private SafetyCenterConfigInternal mConfigInternalFromXml; @Nullable private SafetyCenterConfigInternal mConfigInternalOverrideForTests; - /** Creates a {@link SafetyCenterConfigReader} from a {@link SafetyCenterResourcesContext}. */ - SafetyCenterConfigReader(SafetyCenterResourcesContext safetyCenterResourcesContext) { - mSafetyCenterResourcesContext = safetyCenterResourcesContext; + /** Creates a {@link SafetyCenterConfigReader} from a {@link SafetyCenterResourcesApk}. */ + SafetyCenterConfigReader(SafetyCenterResourcesApk safetyCenterResourcesApk) { + mSafetyCenterResourcesApk = safetyCenterResourcesApk; } /** @@ -226,13 +226,13 @@ public final class SafetyCenterConfigReader { @Nullable private SafetyCenterConfig loadSafetyCenterConfig() { - InputStream in = mSafetyCenterResourcesContext.getSafetyCenterConfig(); + InputStream in = mSafetyCenterResourcesApk.getSafetyCenterConfig(); if (in == null) { Log.e(TAG, "Cannot access Safety Center config file"); return null; } - Resources resources = mSafetyCenterResourcesContext.getResources(); + Resources resources = mSafetyCenterResourcesApk.getResources(); try { SafetyCenterConfig safetyCenterConfig = SafetyCenterConfigParser.parseXmlResource(in, resources); diff --git a/service/java/com/android/safetycenter/SafetyCenterDataFactory.java b/service/java/com/android/safetycenter/SafetyCenterDataFactory.java index 69c8a58c9..198ce1631 100644 --- a/service/java/com/android/safetycenter/SafetyCenterDataFactory.java +++ b/service/java/com/android/safetycenter/SafetyCenterDataFactory.java @@ -63,7 +63,7 @@ import com.android.safetycenter.internaldata.SafetyCenterIds; import com.android.safetycenter.internaldata.SafetyCenterIssueActionId; import com.android.safetycenter.internaldata.SafetyCenterIssueId; import com.android.safetycenter.internaldata.SafetyCenterIssueKey; -import com.android.safetycenter.resources.SafetyCenterResourcesContext; +import com.android.safetycenter.resources.SafetyCenterResourcesApk; import java.util.ArrayList; import java.util.List; @@ -89,7 +89,7 @@ public final class SafetyCenterDataFactory { private static final String ANDROID_LOCK_SCREEN_SOURCES_GROUP_ID = "AndroidLockScreenSources"; private final Context mContext; - private final SafetyCenterResourcesContext mSafetyCenterResourcesContext; + private final SafetyCenterResourcesApk mSafetyCenterResourcesApk; private final SafetyCenterConfigReader mSafetyCenterConfigReader; private final SafetyCenterRefreshTracker mSafetyCenterRefreshTracker; private final PendingIntentFactory mPendingIntentFactory; @@ -98,13 +98,13 @@ public final class SafetyCenterDataFactory { SafetyCenterDataFactory( Context context, - SafetyCenterResourcesContext safetyCenterResourcesContext, + SafetyCenterResourcesApk safetyCenterResourcesApk, SafetyCenterConfigReader safetyCenterConfigReader, SafetyCenterRefreshTracker safetyCenterRefreshTracker, PendingIntentFactory pendingIntentFactory, SafetyCenterDataManager safetyCenterDataManager) { mContext = context; - mSafetyCenterResourcesContext = safetyCenterResourcesContext; + mSafetyCenterResourcesApk = safetyCenterResourcesApk; mSafetyCenterConfigReader = safetyCenterConfigReader; mSafetyCenterRefreshTracker = safetyCenterRefreshTracker; mPendingIntentFactory = pendingIntentFactory; @@ -336,7 +336,7 @@ public final class SafetyCenterDataFactory { if (SdkLevel.isAtLeastU()) { CharSequence issueAttributionTitle = TextUtils.isEmpty(safetySourceIssue.getAttributionTitle()) - ? mSafetyCenterResourcesContext.getOptionalString( + ? mSafetyCenterResourcesApk.getOptionalString( safetySourcesGroup.getTitleResId()) : safetySourceIssue.getAttributionTitle(); safetyCenterIssueBuilder.setAttributionTitle(issueAttributionTitle); @@ -445,7 +445,7 @@ public final class SafetyCenterDataFactory { new SafetyCenterEntryOrGroup( new SafetyCenterEntryGroup.Builder( safetySourcesGroup.getId(), - mSafetyCenterResourcesContext.getString( + mSafetyCenterResourcesApk.getString( safetySourcesGroup.getTitleResId())) .setSeverityLevel(groupSafetyCenterEntryLevel) .setSummary(groupSummary) @@ -514,7 +514,7 @@ public final class SafetyCenterDataFactory { return getRefreshErrorString(); } } - return mSafetyCenterResourcesContext.getStringByName("group_unknown_summary"); + return mSafetyCenterResourcesApk.getStringByName("group_unknown_summary"); } Log.w( @@ -528,8 +528,7 @@ public final class SafetyCenterDataFactory { private CharSequence getDefaultGroupSummary( SafetySourcesGroup safetySourcesGroup, List<SafetyCenterEntry> entries) { CharSequence groupSummary = - mSafetyCenterResourcesContext.getOptionalString( - safetySourcesGroup.getSummaryResId()); + mSafetyCenterResourcesApk.getOptionalString(safetySourcesGroup.getSummaryResId()); if (safetySourcesGroup.getId().equals(ANDROID_LOCK_SCREEN_SOURCES_GROUP_ID) && TextUtils.isEmpty(groupSummary)) { @@ -648,7 +647,7 @@ public final class SafetyCenterDataFactory { .setSummary( inQuietMode ? DevicePolicyResources.getWorkProfilePausedString( - mSafetyCenterResourcesContext) + mSafetyCenterResourcesApk) : safetySourceStatus.getSummary()) .setEnabled(enabled) .setSeverityUnspecifiedIconType(severityUnspecifiedIconType) @@ -709,20 +708,19 @@ public final class SafetyCenterDataFactory { CharSequence title = isUserManaged ? DevicePolicyResources.getSafetySourceWorkString( - mSafetyCenterResourcesContext, + mSafetyCenterResourcesApk, safetySource.getId(), safetySource.getTitleForWorkResId()) - : mSafetyCenterResourcesContext.getString(safetySource.getTitleResId()); + : mSafetyCenterResourcesApk.getString(safetySource.getTitleResId()); CharSequence summary = mSafetyCenterDataManager.sourceHasError( SafetySourceKey.of(safetySource.getId(), userId)) ? getRefreshErrorString() - : mSafetyCenterResourcesContext.getOptionalString( + : mSafetyCenterResourcesApk.getOptionalString( safetySource.getSummaryResId()); if (isQuietModeEnabled) { enabled = false; - summary = - DevicePolicyResources.getWorkProfilePausedString(mSafetyCenterResourcesContext); + summary = DevicePolicyResources.getWorkProfilePausedString(mSafetyCenterResourcesApk); } return new SafetyCenterEntry.Builder( SafetyCenterIds.encodeToString(safetyCenterEntryId), title) @@ -784,7 +782,7 @@ public final class SafetyCenterDataFactory { safetyCenterStaticEntryGroups.add( new SafetyCenterStaticEntryGroup( - mSafetyCenterResourcesContext.getString(safetySourcesGroup.getTitleResId()), + mSafetyCenterResourcesApk.getString(safetySourcesGroup.getTitleResId()), staticEntries)); } @@ -863,7 +861,7 @@ public final class SafetyCenterDataFactory { .setSummary( inQuietMode ? DevicePolicyResources.getWorkProfilePausedString( - mSafetyCenterResourcesContext) + mSafetyCenterResourcesApk) : safetySourceStatus.getSummary()) .setPendingIntent(entryPendingIntent) .build(); @@ -913,19 +911,18 @@ public final class SafetyCenterDataFactory { CharSequence title = isUserManaged ? DevicePolicyResources.getSafetySourceWorkString( - mSafetyCenterResourcesContext, + mSafetyCenterResourcesApk, safetySource.getId(), safetySource.getTitleForWorkResId()) - : mSafetyCenterResourcesContext.getString(safetySource.getTitleResId()); + : mSafetyCenterResourcesApk.getString(safetySource.getTitleResId()); CharSequence summary = mSafetyCenterDataManager.sourceHasError( SafetySourceKey.of(safetySource.getId(), userId)) ? getRefreshErrorString() - : mSafetyCenterResourcesContext.getOptionalString( + : mSafetyCenterResourcesApk.getOptionalString( safetySource.getSummaryResId()); if (isQuietModeEnabled) { - summary = - DevicePolicyResources.getWorkProfilePausedString(mSafetyCenterResourcesContext); + summary = DevicePolicyResources.getWorkProfilePausedString(mSafetyCenterResourcesApk); } return new SafetyCenterStaticEntry.Builder(title) .setSummary(summary) @@ -1087,11 +1084,10 @@ public final class SafetyCenterDataFactory { case SafetyCenterStatus.OVERALL_SEVERITY_LEVEL_UNKNOWN: case SafetyCenterStatus.OVERALL_SEVERITY_LEVEL_OK: if (hasSettingsToReview) { - return mSafetyCenterResourcesContext.getStringByName( + return mSafetyCenterResourcesApk.getStringByName( "overall_severity_level_ok_review_title"); } - return mSafetyCenterResourcesContext.getStringByName( - "overall_severity_level_ok_title"); + return mSafetyCenterResourcesApk.getStringByName("overall_severity_level_ok_title"); case SafetyCenterStatus.OVERALL_SEVERITY_LEVEL_RECOMMENDATION: return getStatusTitleFromIssueCategories( topNonDismissedIssueInfo, @@ -1125,7 +1121,7 @@ public final class SafetyCenterDataFactory { String dataResourceName, String passwordsResourceName, String personalSafetyResourceName) { - String generalString = mSafetyCenterResourcesContext.getStringByName(generalResourceName); + String generalString = mSafetyCenterResourcesApk.getStringByName(generalResourceName); if (topNonDismissedIssueInfo == null) { Log.w(TAG, "No safety center issues found in a non-green status"); return generalString; @@ -1133,17 +1129,17 @@ public final class SafetyCenterDataFactory { int issueCategory = topNonDismissedIssueInfo.getSafetySourceIssue().getIssueCategory(); switch (issueCategory) { case SafetySourceIssue.ISSUE_CATEGORY_DEVICE: - return mSafetyCenterResourcesContext.getStringByName(deviceResourceName); + return mSafetyCenterResourcesApk.getStringByName(deviceResourceName); case SafetySourceIssue.ISSUE_CATEGORY_ACCOUNT: - return mSafetyCenterResourcesContext.getStringByName(accountResourceName); + return mSafetyCenterResourcesApk.getStringByName(accountResourceName); case SafetySourceIssue.ISSUE_CATEGORY_GENERAL: return generalString; case SafetySourceIssue.ISSUE_CATEGORY_DATA: - return mSafetyCenterResourcesContext.getStringByName(dataResourceName); + return mSafetyCenterResourcesApk.getStringByName(dataResourceName); case SafetySourceIssue.ISSUE_CATEGORY_PASSWORDS: - return mSafetyCenterResourcesContext.getStringByName(passwordsResourceName); + return mSafetyCenterResourcesApk.getStringByName(passwordsResourceName); case SafetySourceIssue.ISSUE_CATEGORY_PERSONAL_SAFETY: - return mSafetyCenterResourcesContext.getStringByName(personalSafetyResourceName); + return mSafetyCenterResourcesApk.getStringByName(personalSafetyResourceName); } Log.w(TAG, "Unexpected SafetySourceIssue.IssueCategory: " + issueCategory); @@ -1167,17 +1163,17 @@ public final class SafetyCenterDataFactory { case SafetyCenterStatus.OVERALL_SEVERITY_LEVEL_OK: if (topNonDismissedIssue == null) { if (safetyCenterOverallState.hasSettingsToReview()) { - return mSafetyCenterResourcesContext.getStringByName( + return mSafetyCenterResourcesApk.getStringByName( "overall_severity_level_ok_review_summary"); } - return mSafetyCenterResourcesContext.getStringByName( + return mSafetyCenterResourcesApk.getStringByName( "overall_severity_level_ok_summary"); } else if (isTip(topNonDismissedIssue.getSafetySourceIssue())) { - return mSafetyCenterResourcesContext.getStringByName( + return mSafetyCenterResourcesApk.getStringByName( "overall_severity_level_tip_summary", numTipIssues); } else if (isAutomatic(topNonDismissedIssue.getSafetySourceIssue())) { - return mSafetyCenterResourcesContext.getStringByName( + return mSafetyCenterResourcesApk.getStringByName( "overall_severity_level_action_taken_summary", numAutomaticIssues); } // Fall through. @@ -1209,7 +1205,7 @@ public final class SafetyCenterDataFactory { private String getIcuPluralsString(String name, int count, Object... formatArgs) { MessageFormat messageFormat = new MessageFormat( - mSafetyCenterResourcesContext.getStringByName(name, formatArgs), + mSafetyCenterResourcesApk.getStringByName(name, formatArgs), Locale.getDefault()); ArrayMap<String, Object> arguments = new ArrayMap<>(); arguments.put("count", count); @@ -1228,7 +1224,7 @@ public final class SafetyCenterDataFactory { } // Fall through. case SafetyCenterStatus.REFRESH_STATUS_FULL_RESCAN_IN_PROGRESS: - return mSafetyCenterResourcesContext.getStringByName("scanning_title"); + return mSafetyCenterResourcesApk.getStringByName("scanning_title"); } Log.w(TAG, "Unexpected SafetyCenterStatus.RefreshStatus: " + refreshStatus); @@ -1243,7 +1239,7 @@ public final class SafetyCenterDataFactory { return null; case SafetyCenterStatus.REFRESH_STATUS_DATA_FETCH_IN_PROGRESS: case SafetyCenterStatus.REFRESH_STATUS_FULL_RESCAN_IN_PROGRESS: - return mSafetyCenterResourcesContext.getStringByName("loading_summary"); + return mSafetyCenterResourcesApk.getStringByName("loading_summary"); } Log.w(TAG, "Unexpected SafetyCenterStatus.RefreshStatus: " + refreshStatus); diff --git a/service/java/com/android/safetycenter/SafetyCenterFlags.java b/service/java/com/android/safetycenter/SafetyCenterFlags.java index 62855f532..018a5525e 100644 --- a/service/java/com/android/safetycenter/SafetyCenterFlags.java +++ b/service/java/com/android/safetycenter/SafetyCenterFlags.java @@ -30,7 +30,7 @@ import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import com.android.modules.utils.build.SdkLevel; -import com.android.safetycenter.resources.SafetyCenterResourcesContext; +import com.android.safetycenter.resources.SafetyCenterResourcesApk; import java.io.PrintWriter; import java.time.Duration; @@ -134,24 +134,27 @@ public final class SafetyCenterFlags { private static volatile String sRefreshOnPageOpenSourcesDefault = "AndroidBiometrics,AndroidLockScreen"; - static void init(SafetyCenterResourcesContext resourceContext) { + static void init(SafetyCenterResourcesApk safetyCenterResourcesApk) { String untrackedSourcesDefault = - resourceContext.getOptionalStringByName("config_defaultUntrackedSources"); + safetyCenterResourcesApk.getOptionalStringByName("config_defaultUntrackedSources"); if (untrackedSourcesDefault != null) { sUntrackedSourcesDefault = untrackedSourcesDefault; } String backgroundRefreshDenyDefault = - resourceContext.getOptionalStringByName("config_defaultBackgroundRefreshDeny"); + safetyCenterResourcesApk.getOptionalStringByName( + "config_defaultBackgroundRefreshDeny"); if (backgroundRefreshDenyDefault != null) { sBackgroundRefreshDenyDefault = backgroundRefreshDenyDefault; } String issueCategoryAllowlistDefault = - resourceContext.getOptionalStringByName("config_defaultIssueCategoryAllowlist"); + safetyCenterResourcesApk.getOptionalStringByName( + "config_defaultIssueCategoryAllowlist"); if (issueCategoryAllowlistDefault != null) { sIssueCategoryAllowlistDefault = issueCategoryAllowlistDefault; } String refreshOnPageOpenSourcesDefault = - resourceContext.getOptionalStringByName("config_defaultRefreshOnPageOpenSources"); + safetyCenterResourcesApk.getOptionalStringByName( + "config_defaultRefreshOnPageOpenSources"); if (refreshOnPageOpenSourcesDefault != null) { sRefreshOnPageOpenSourcesDefault = refreshOnPageOpenSourcesDefault; } diff --git a/service/java/com/android/safetycenter/SafetyCenterService.java b/service/java/com/android/safetycenter/SafetyCenterService.java index 2b1cd93be..3270f0cea 100644 --- a/service/java/com/android/safetycenter/SafetyCenterService.java +++ b/service/java/com/android/safetycenter/SafetyCenterService.java @@ -86,7 +86,7 @@ import com.android.safetycenter.notifications.SafetyCenterNotificationChannels; import com.android.safetycenter.notifications.SafetyCenterNotificationReceiver; import com.android.safetycenter.notifications.SafetyCenterNotificationSender; import com.android.safetycenter.pendingintents.PendingIntentSender; -import com.android.safetycenter.resources.SafetyCenterResourcesContext; +import com.android.safetycenter.resources.SafetyCenterResourcesApk; import com.android.server.SystemService; import java.io.FileDescriptor; @@ -114,7 +114,7 @@ public final class SafetyCenterService extends SystemService { private final SafetyCenterTimeouts mSafetyCenterTimeouts = new SafetyCenterTimeouts(); @GuardedBy("mApiLock") - private final SafetyCenterResourcesContext mSafetyCenterResourcesContext; + private final SafetyCenterResourcesApk mSafetyCenterResourcesApk; @GuardedBy("mApiLock") private final SafetyCenterNotificationChannels mNotificationChannels; @@ -150,8 +150,8 @@ public final class SafetyCenterService extends SystemService { public SafetyCenterService(Context context) { super(context); - mSafetyCenterResourcesContext = new SafetyCenterResourcesContext(context); - mSafetyCenterConfigReader = new SafetyCenterConfigReader(mSafetyCenterResourcesContext); + mSafetyCenterResourcesApk = new SafetyCenterResourcesApk(context); + mSafetyCenterConfigReader = new SafetyCenterConfigReader(mSafetyCenterResourcesApk); mSafetyCenterRefreshTracker = new SafetyCenterRefreshTracker(context); mSafetyCenterDataManager = new SafetyCenterDataManager( @@ -159,17 +159,17 @@ public final class SafetyCenterService extends SystemService { mSafetyCenterDataFactory = new SafetyCenterDataFactory( context, - mSafetyCenterResourcesContext, + mSafetyCenterResourcesApk, mSafetyCenterConfigReader, mSafetyCenterRefreshTracker, - new PendingIntentFactory(context, mSafetyCenterResourcesContext), + new PendingIntentFactory(context, mSafetyCenterResourcesApk), mSafetyCenterDataManager); mSafetyCenterListeners = new SafetyCenterListeners(mSafetyCenterDataFactory); - mNotificationChannels = new SafetyCenterNotificationChannels(mSafetyCenterResourcesContext); + mNotificationChannels = new SafetyCenterNotificationChannels(mSafetyCenterResourcesApk); mNotificationSender = SafetyCenterNotificationSender.newInstance( context, - mSafetyCenterResourcesContext, + mSafetyCenterResourcesApk, mNotificationChannels, mSafetyCenterDataManager); mSafetyCenterBroadcastDispatcher = @@ -197,13 +197,13 @@ public final class SafetyCenterService extends SystemService { } synchronized (mApiLock) { - boolean safetyCenterResourcesInitialized = mSafetyCenterResourcesContext.init(); + boolean safetyCenterResourcesInitialized = mSafetyCenterResourcesApk.init(); if (!safetyCenterResourcesInitialized) { Log.e(TAG, "Cannot init Safety Center resources, Safety Center will be disabled"); return; } - SafetyCenterFlags.init(mSafetyCenterResourcesContext); + SafetyCenterFlags.init(mSafetyCenterResourcesApk); if (!mSafetyCenterConfigReader.loadConfig()) { Log.e(TAG, "Cannot init Safety Center config, Safety Center will be disabled"); @@ -376,7 +376,7 @@ public final class SafetyCenterService extends SystemService { == SAFETY_EVENT_TYPE_RESOLVING_ACTION_FAILED) { safetyCenterErrorDetails = new SafetyCenterErrorDetails( - mSafetyCenterResourcesContext.getStringByName( + mSafetyCenterResourcesApk.getStringByName( "resolving_action_error")); } if (hasUpdate) { @@ -921,8 +921,7 @@ public final class SafetyCenterService extends SystemService { mSafetyCenterListeners.deliverErrorForUserProfileGroup( mUserProfileGroup, new SafetyCenterErrorDetails( - mSafetyCenterResourcesContext.getStringByName( - "refresh_timeout"))); + mSafetyCenterResourcesApk.getStringByName("refresh_timeout"))); } } } @@ -971,7 +970,7 @@ public final class SafetyCenterService extends SystemService { mSafetyCenterListeners.deliverErrorForUserProfileGroup( mUserProfileGroup, new SafetyCenterErrorDetails( - mSafetyCenterResourcesContext.getStringByName( + mSafetyCenterResourcesApk.getStringByName( "resolving_action_error"))); Log.w( TAG, @@ -1177,10 +1176,9 @@ public final class SafetyCenterService extends SystemService { CharSequence errorMessage; if (safetySourceIssueAction.willResolve()) { errorMessage = - mSafetyCenterResourcesContext.getStringByName("resolving_action_error"); + mSafetyCenterResourcesApk.getStringByName("resolving_action_error"); } else { - errorMessage = - mSafetyCenterResourcesContext.getStringByName("redirecting_error"); + errorMessage = mSafetyCenterResourcesApk.getStringByName("redirecting_error"); } mSafetyCenterListeners.deliverErrorForUserProfileGroup( userProfileGroup, new SafetyCenterErrorDetails(errorMessage)); diff --git a/service/java/com/android/safetycenter/notifications/SafetyCenterNotificationChannels.java b/service/java/com/android/safetycenter/notifications/SafetyCenterNotificationChannels.java index 4de16feb6..749e887f1 100644 --- a/service/java/com/android/safetycenter/notifications/SafetyCenterNotificationChannels.java +++ b/service/java/com/android/safetycenter/notifications/SafetyCenterNotificationChannels.java @@ -34,7 +34,7 @@ import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import com.android.permission.util.UserUtils; -import com.android.safetycenter.resources.SafetyCenterResourcesContext; +import com.android.safetycenter.resources.SafetyCenterResourcesApk; import java.util.List; @@ -53,11 +53,10 @@ public final class SafetyCenterNotificationChannels { private static final String CHANNEL_ID_RECOMMENDATION = "safety_center_recommendation"; private static final String CHANNEL_ID_CRITICAL_WARNING = "safety_center_critical_warning"; - private final SafetyCenterResourcesContext mResourcesContext; + private final SafetyCenterResourcesApk mSafetyCenterResourcesApk; - public SafetyCenterNotificationChannels( - SafetyCenterResourcesContext safetyCenterResourceContext) { - mResourcesContext = safetyCenterResourceContext; + public SafetyCenterNotificationChannels(SafetyCenterResourcesApk safetyCenterResourcesApk) { + mSafetyCenterResourcesApk = safetyCenterResourcesApk; } /** Returns a {@link NotificationManager} which will send notifications to the given user. */ @@ -219,6 +218,6 @@ public final class SafetyCenterNotificationChannels { } private String getString(String name) { - return mResourcesContext.getStringByName(name); + return mSafetyCenterResourcesApk.getStringByName(name); } } diff --git a/service/java/com/android/safetycenter/notifications/SafetyCenterNotificationFactory.java b/service/java/com/android/safetycenter/notifications/SafetyCenterNotificationFactory.java index cc3d0c4f3..4e88cf320 100644 --- a/service/java/com/android/safetycenter/notifications/SafetyCenterNotificationFactory.java +++ b/service/java/com/android/safetycenter/notifications/SafetyCenterNotificationFactory.java @@ -46,7 +46,7 @@ import com.android.safetycenter.PendingIntentFactory; import com.android.safetycenter.internaldata.SafetyCenterIds; import com.android.safetycenter.internaldata.SafetyCenterIssueActionId; import com.android.safetycenter.internaldata.SafetyCenterIssueKey; -import com.android.safetycenter.resources.SafetyCenterResourcesContext; +import com.android.safetycenter.resources.SafetyCenterResourcesApk; import java.time.Duration; import java.util.List; @@ -63,15 +63,15 @@ final class SafetyCenterNotificationFactory { private final Context mContext; private final SafetyCenterNotificationChannels mNotificationChannels; - private final SafetyCenterResourcesContext mResourcesContext; + private final SafetyCenterResourcesApk mSafetyCenterResourcesApk; SafetyCenterNotificationFactory( Context context, SafetyCenterNotificationChannels notificationChannels, - SafetyCenterResourcesContext resourcesContext) { + SafetyCenterResourcesApk safetyCenterResourcesApk) { mContext = context; mNotificationChannels = notificationChannels; - mResourcesContext = resourcesContext; + mSafetyCenterResourcesApk = safetyCenterResourcesApk; } /** @@ -229,7 +229,7 @@ final class SafetyCenterNotificationFactory { if (severityLevel == SafetySourceData.SEVERITY_LEVEL_CRITICAL_WARNING) { iconResName = "ic_notification_badge_critical"; } - Icon icon = mResourcesContext.getIconByDrawableName(iconResName); + Icon icon = mSafetyCenterResourcesApk.getIconByDrawableName(iconResName); if (icon == null) { // In case it was impossible to fetch the above drawable for any reason use this // fallback which should be present on all Android devices: @@ -245,12 +245,13 @@ final class SafetyCenterNotificationFactory { if (severityLevel == SafetySourceData.SEVERITY_LEVEL_CRITICAL_WARNING) { colorResName = "notification_tint_critical"; } - return mResourcesContext.getColorByName(colorResName); + return mSafetyCenterResourcesApk.getColorByName(colorResName); } private Bundle getNotificationExtras() { Bundle extras = new Bundle(); - String appName = mResourcesContext.getStringByName("notification_channel_group_name"); + String appName = + mSafetyCenterResourcesApk.getStringByName("notification_channel_group_name"); if (!TextUtils.isEmpty(appName)) { extras.putString(Notification.EXTRA_SUBSTITUTE_APP_NAME, appName); } diff --git a/service/java/com/android/safetycenter/notifications/SafetyCenterNotificationSender.java b/service/java/com/android/safetycenter/notifications/SafetyCenterNotificationSender.java index 90be3618e..3804070d4 100644 --- a/service/java/com/android/safetycenter/notifications/SafetyCenterNotificationSender.java +++ b/service/java/com/android/safetycenter/notifications/SafetyCenterNotificationSender.java @@ -47,7 +47,7 @@ import com.android.safetycenter.data.SafetyCenterDataManager; import com.android.safetycenter.internaldata.SafetyCenterIds; import com.android.safetycenter.internaldata.SafetyCenterIssueKey; import com.android.safetycenter.logging.SafetyCenterStatsdLogger; -import com.android.safetycenter.resources.SafetyCenterResourcesContext; +import com.android.safetycenter.resources.SafetyCenterResourcesApk; import java.io.PrintWriter; import java.lang.annotation.Retention; @@ -120,13 +120,13 @@ public final class SafetyCenterNotificationSender { public static SafetyCenterNotificationSender newInstance( Context context, - SafetyCenterResourcesContext resourcesContext, + SafetyCenterResourcesApk safetyCenterResourcesApk, SafetyCenterNotificationChannels notificationChannels, SafetyCenterDataManager dataManager) { return new SafetyCenterNotificationSender( context, new SafetyCenterNotificationFactory( - context, notificationChannels, resourcesContext), + context, notificationChannels, safetyCenterResourcesApk), dataManager); } diff --git a/tests/cts/safetycenter/src/android/safetycenter/cts/SafetyCenterManagerTest.kt b/tests/cts/safetycenter/src/android/safetycenter/cts/SafetyCenterManagerTest.kt index 3288f71ff..7c8c82178 100644 --- a/tests/cts/safetycenter/src/android/safetycenter/cts/SafetyCenterManagerTest.kt +++ b/tests/cts/safetycenter/src/android/safetycenter/cts/SafetyCenterManagerTest.kt @@ -40,7 +40,7 @@ import android.safetycenter.cts.testing.FakeExecutor import androidx.test.core.app.ApplicationProvider.getApplicationContext import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SdkSuppress -import com.android.safetycenter.resources.SafetyCenterResourcesContext +import com.android.safetycenter.resources.SafetyCenterResourcesApk import com.android.safetycenter.testing.Coroutines.TIMEOUT_LONG import com.android.safetycenter.testing.Coroutines.TIMEOUT_SHORT import com.android.safetycenter.testing.SafetyCenterApisWithShellPermissions.addOnSafetyCenterDataChangedListenerWithPermission @@ -105,7 +105,7 @@ import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class SafetyCenterManagerTest { private val context: Context = getApplicationContext() - private val safetyCenterResourcesContext = SafetyCenterResourcesContext.forTests(context) + private val safetyCenterResourcesApk = SafetyCenterResourcesApk.forTests(context) private val safetyCenterTestHelper = SafetyCenterTestHelper(context) private val safetySourceTestData = SafetySourceTestData(context) private val safetyCenterTestConfigs = SafetyCenterTestConfigs(context) @@ -1314,7 +1314,7 @@ class SafetyCenterManagerTest { assertThat(safetyCenterErrorDetailsFromListener) .isEqualTo( SafetyCenterErrorDetails( - safetyCenterResourcesContext.getStringByName("refresh_timeout") + safetyCenterResourcesApk.getStringByName("refresh_timeout") ) ) } @@ -1378,7 +1378,7 @@ class SafetyCenterManagerTest { assertThat(safetyCenterErrorDetailsFromListener) .isEqualTo( SafetyCenterErrorDetails( - safetyCenterResourcesContext.getStringByName("refresh_timeout") + safetyCenterResourcesApk.getStringByName("refresh_timeout") ) ) } @@ -2054,7 +2054,7 @@ class SafetyCenterManagerTest { assertThat(error) .isEqualTo( SafetyCenterErrorDetails( - safetyCenterResourcesContext.getStringByName("redirecting_error") + safetyCenterResourcesApk.getStringByName("redirecting_error") ) ) } @@ -2080,7 +2080,7 @@ class SafetyCenterManagerTest { assertThat(error) .isEqualTo( SafetyCenterErrorDetails( - safetyCenterResourcesContext.getStringByName("resolving_action_error") + safetyCenterResourcesApk.getStringByName("resolving_action_error") ) ) } diff --git a/tests/cts/safetycenter/src/android/safetycenter/cts/config/XmlConfigTest.kt b/tests/cts/safetycenter/src/android/safetycenter/cts/config/XmlConfigTest.kt index 3a1503cc2..3cf256337 100644 --- a/tests/cts/safetycenter/src/android/safetycenter/cts/config/XmlConfigTest.kt +++ b/tests/cts/safetycenter/src/android/safetycenter/cts/config/XmlConfigTest.kt @@ -24,7 +24,7 @@ import android.safetycenter.config.SafetySource.SAFETY_SOURCE_TYPE_ISSUE_ONLY import androidx.test.core.app.ApplicationProvider.getApplicationContext import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.safetycenter.config.SafetyCenterConfigParser -import com.android.safetycenter.resources.SafetyCenterResourcesContext +import com.android.safetycenter.resources.SafetyCenterResourcesApk import com.android.safetycenter.testing.SafetyCenterApisWithShellPermissions.getSafetyCenterConfigWithPermission import com.android.safetycenter.testing.SafetyCenterTestRule import com.android.safetycenter.testing.SupportsSafetyCenterRule @@ -38,7 +38,7 @@ import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class XmlConfigTest { private val context: Context = getApplicationContext() - private val safetyCenterContext = SafetyCenterResourcesContext.forTests(context) + private val safetyCenterResourcesApk = SafetyCenterResourcesApk.forTests(context) private val safetyCenterManager = context.getSystemService(SafetyCenterManager::class.java)!! @get:Rule(order = 1) val supportsSafetyCenterRule = SupportsSafetyCenterRule(context) @@ -85,8 +85,8 @@ class XmlConfigTest { private fun parseXmlConfig() = SafetyCenterConfigParser.parseXmlResource( - safetyCenterContext.safetyCenterConfig!!, - safetyCenterContext.resources + safetyCenterResourcesApk.safetyCenterConfig!!, + safetyCenterResourcesApk.resources ) companion object { diff --git a/tests/functional/safetycenter/multiusers/src/android/safetycenter/functional/multiusers/SafetyCenterMultiUsersTest.kt b/tests/functional/safetycenter/multiusers/src/android/safetycenter/functional/multiusers/SafetyCenterMultiUsersTest.kt index c534a9fb0..7d22348b4 100644 --- a/tests/functional/safetycenter/multiusers/src/android/safetycenter/functional/multiusers/SafetyCenterMultiUsersTest.kt +++ b/tests/functional/safetycenter/multiusers/src/android/safetycenter/functional/multiusers/SafetyCenterMultiUsersTest.kt @@ -51,7 +51,7 @@ import com.android.bedstead.nene.TestApis import com.android.bedstead.nene.types.OptionalBoolean.TRUE import com.android.compatibility.common.util.DisableAnimationRule import com.android.compatibility.common.util.FreezeRotationRule -import com.android.safetycenter.resources.SafetyCenterResourcesContext +import com.android.safetycenter.resources.SafetyCenterResourcesApk import com.android.safetycenter.testing.Coroutines.TIMEOUT_SHORT import com.android.safetycenter.testing.NotificationCharacteristics import com.android.safetycenter.testing.SafetyCenterActivityLauncher.launchSafetyCenterActivity @@ -111,7 +111,7 @@ class SafetyCenterMultiUsersTest { } private val context: Context = ApplicationProvider.getApplicationContext() - private val safetyCenterResourcesContext = SafetyCenterResourcesContext.forTests(context) + private val safetyCenterResourcesApk = SafetyCenterResourcesApk.forTests(context) private val safetyCenterTestHelper = SafetyCenterTestHelper(context) private val safetySourceTestData = SafetySourceTestData(context) private val safetyCenterTestData = SafetyCenterTestData(context) @@ -192,7 +192,7 @@ class SafetyCenterMultiUsersTest { // TODO(b/233188021): This needs to use the Enterprise API to override the "work" // keyword. .setSummary( - safetyCenterResourcesContext.getStringByName("work_profile_paused"), + safetyCenterResourcesApk.getStringByName("work_profile_paused"), ) .setSeverityLevel(ENTRY_SEVERITY_LEVEL_UNSPECIFIED) .setEnabled(false) @@ -219,7 +219,7 @@ class SafetyCenterMultiUsersTest { // TODO(b/233188021): This needs to use the Enterprise API to override the "work" // keyword. .setSummary( - safetyCenterResourcesContext.getStringByName("work_profile_paused"), + safetyCenterResourcesApk.getStringByName("work_profile_paused"), ) .setSeverityLevel(ENTRY_SEVERITY_LEVEL_UNSPECIFIED) .setEnabled(false) @@ -262,7 +262,7 @@ class SafetyCenterMultiUsersTest { staticAllOptionalForWorkBuilder(inQuietMode = true) // TODO(b/233188021): This needs to use the Enterprise API to override the "work" // keyword. - .setSummary(safetyCenterResourcesContext.getStringByName("work_profile_paused")) + .setSummary(safetyCenterResourcesApk.getStringByName("work_profile_paused")) .setEnabled(false) .build() @@ -299,7 +299,7 @@ class SafetyCenterMultiUsersTest { staticEntryForWorkBuilder(inQuietMode = true) // TODO(b/233188021): This needs to use the Enterprise API to override the "work" // keyword. - .setSummary(safetyCenterResourcesContext.getStringByName("work_profile_paused")) + .setSummary(safetyCenterResourcesApk.getStringByName("work_profile_paused")) .build() private val staticEntryForWorkPausedUpdated @@ -307,7 +307,7 @@ class SafetyCenterMultiUsersTest { staticEntryForWorkBuilder(title = "Unspecified title for Work", inQuietMode = true) // TODO(b/233188021): This needs to use the Enterprise API to override the "work" // keyword. - .setSummary(safetyCenterResourcesContext.getStringByName("work_profile_paused")) + .setSummary(safetyCenterResourcesApk.getStringByName("work_profile_paused")) .build() private val staticEntryForWorkUpdated = @@ -548,9 +548,7 @@ class SafetyCenterMultiUsersTest { SafetyCenterEntryGroup.Builder(DYNAMIC_GROUP_ID, "OK") .setSeverityLevel(ENTRY_SEVERITY_LEVEL_UNKNOWN) .setSummary( - safetyCenterResourcesContext.getStringByName( - "group_unknown_summary" - ) + safetyCenterResourcesApk.getStringByName("group_unknown_summary") ) .setEntries(listOf(dynamicBareboneDefault, dynamicDisabledDefault)) .setSeverityUnspecifiedIconType( @@ -586,9 +584,7 @@ class SafetyCenterMultiUsersTest { SafetyCenterEntryGroup.Builder(DYNAMIC_GROUP_ID, "OK") .setSeverityLevel(ENTRY_SEVERITY_LEVEL_UNKNOWN) .setSummary( - safetyCenterResourcesContext.getStringByName( - "group_unknown_summary" - ) + safetyCenterResourcesApk.getStringByName("group_unknown_summary") ) .setEntries( listOf( @@ -886,9 +882,7 @@ class SafetyCenterMultiUsersTest { SafetyCenterEntryGroup.Builder(SINGLE_SOURCE_GROUP_ID, "OK") .setSeverityLevel(ENTRY_SEVERITY_LEVEL_UNKNOWN) .setSummary( - safetyCenterResourcesContext.getStringByName( - "group_unknown_summary" - ) + safetyCenterResourcesApk.getStringByName("group_unknown_summary") ) .setEntries( listOf( diff --git a/tests/functional/safetycenter/singleuser/src/android/safetycenter/functional/SafetyCenterManagerTest.kt b/tests/functional/safetycenter/singleuser/src/android/safetycenter/functional/SafetyCenterManagerTest.kt index 967f4296e..c37f34d78 100644 --- a/tests/functional/safetycenter/singleuser/src/android/safetycenter/functional/SafetyCenterManagerTest.kt +++ b/tests/functional/safetycenter/singleuser/src/android/safetycenter/functional/SafetyCenterManagerTest.kt @@ -70,7 +70,7 @@ import com.android.safetycenter.internaldata.SafetyCenterBundles import com.android.safetycenter.internaldata.SafetyCenterBundles.ISSUES_TO_GROUPS_BUNDLE_KEY import com.android.safetycenter.internaldata.SafetyCenterEntryId import com.android.safetycenter.internaldata.SafetyCenterIds -import com.android.safetycenter.resources.SafetyCenterResourcesContext +import com.android.safetycenter.resources.SafetyCenterResourcesApk import com.android.safetycenter.testing.Coroutines.TIMEOUT_LONG import com.android.safetycenter.testing.Coroutines.TIMEOUT_SHORT import com.android.safetycenter.testing.Coroutines.waitForWithTimeout @@ -146,7 +146,7 @@ import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class SafetyCenterManagerTest { private val context: Context = getApplicationContext() - private val safetyCenterResourcesContext = SafetyCenterResourcesContext.forTests(context) + private val safetyCenterResourcesApk = SafetyCenterResourcesApk.forTests(context) private val safetyCenterTestHelper = SafetyCenterTestHelper(context) private val safetySourceTestData = SafetySourceTestData(context) private val safetyCenterTestData = SafetyCenterTestData(context) @@ -155,16 +155,16 @@ class SafetyCenterManagerTest { private val safetyCenterStatusOk = SafetyCenterStatus.Builder( - safetyCenterResourcesContext.getStringByName("overall_severity_level_ok_title"), - safetyCenterResourcesContext.getStringByName("overall_severity_level_ok_summary") + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_title"), + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_summary") ) .setSeverityLevel(OVERALL_SEVERITY_LEVEL_OK) .build() private val safetyCenterStatusUnknownScanning = SafetyCenterStatus.Builder( - safetyCenterResourcesContext.getStringByName("scanning_title"), - safetyCenterResourcesContext.getStringByName("loading_summary") + safetyCenterResourcesApk.getStringByName("scanning_title"), + safetyCenterResourcesApk.getStringByName("loading_summary") ) .setSeverityLevel(OVERALL_SEVERITY_LEVEL_UNKNOWN) .setRefreshStatus(REFRESH_STATUS_FULL_RESCAN_IN_PROGRESS) @@ -172,7 +172,7 @@ class SafetyCenterManagerTest { private val safetyCenterStatusOkOneAlert = SafetyCenterStatus.Builder( - safetyCenterResourcesContext.getStringByName("overall_severity_level_ok_title"), + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_title"), safetyCenterTestData.getAlertString(1) ) .setSeverityLevel(OVERALL_SEVERITY_LEVEL_OK) @@ -180,9 +180,7 @@ class SafetyCenterManagerTest { private val safetyCenterStatusOkReviewOneAlert = SafetyCenterStatus.Builder( - safetyCenterResourcesContext.getStringByName( - "overall_severity_level_ok_review_title" - ), + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_review_title"), safetyCenterTestData.getAlertString(1) ) .setSeverityLevel(OVERALL_SEVERITY_LEVEL_OK) @@ -190,19 +188,15 @@ class SafetyCenterManagerTest { private val safetyCenterStatusOkReview = SafetyCenterStatus.Builder( - safetyCenterResourcesContext.getStringByName( - "overall_severity_level_ok_review_title" - ), - safetyCenterResourcesContext.getStringByName( - "overall_severity_level_ok_review_summary" - ) + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_review_title"), + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_review_summary") ) .setSeverityLevel(OVERALL_SEVERITY_LEVEL_OK) .build() private val safetyCenterStatusGeneralRecommendationOneAlert = SafetyCenterStatus.Builder( - safetyCenterResourcesContext.getStringByName( + safetyCenterResourcesApk.getStringByName( "overall_severity_level_safety_recommendation_title" ), safetyCenterTestData.getAlertString(1) @@ -212,7 +206,7 @@ class SafetyCenterManagerTest { private val safetyCenterStatusAccountRecommendationOneAlert = SafetyCenterStatus.Builder( - safetyCenterResourcesContext.getStringByName( + safetyCenterResourcesApk.getStringByName( "overall_severity_level_account_recommendation_title" ), safetyCenterTestData.getAlertString(1) @@ -222,7 +216,7 @@ class SafetyCenterManagerTest { private val safetyCenterStatusDeviceRecommendationOneAlert = SafetyCenterStatus.Builder( - safetyCenterResourcesContext.getStringByName( + safetyCenterResourcesApk.getStringByName( "overall_severity_level_device_recommendation_title" ), safetyCenterTestData.getAlertString(1) @@ -232,7 +226,7 @@ class SafetyCenterManagerTest { private val safetyCenterStatusGeneralCriticalOneAlert = SafetyCenterStatus.Builder( - safetyCenterResourcesContext.getStringByName( + safetyCenterResourcesApk.getStringByName( "overall_severity_level_critical_safety_warning_title" ), safetyCenterTestData.getAlertString(1) @@ -242,7 +236,7 @@ class SafetyCenterManagerTest { private val safetyCenterStatusGeneralCriticalTwoAlerts = SafetyCenterStatus.Builder( - safetyCenterResourcesContext.getStringByName( + safetyCenterResourcesApk.getStringByName( "overall_severity_level_critical_safety_warning_title" ), safetyCenterTestData.getAlertString(2) @@ -252,7 +246,7 @@ class SafetyCenterManagerTest { private val safetyCenterStatusAccountCriticalOneAlert = SafetyCenterStatus.Builder( - safetyCenterResourcesContext.getStringByName( + safetyCenterResourcesApk.getStringByName( "overall_severity_level_critical_account_warning_title" ), safetyCenterTestData.getAlertString(1) @@ -262,7 +256,7 @@ class SafetyCenterManagerTest { private val safetyCenterStatusAccountCriticalTwoAlerts = SafetyCenterStatus.Builder( - safetyCenterResourcesContext.getStringByName( + safetyCenterResourcesApk.getStringByName( "overall_severity_level_critical_account_warning_title" ), safetyCenterTestData.getAlertString(2) @@ -272,7 +266,7 @@ class SafetyCenterManagerTest { private val safetyCenterStatusDeviceCriticalOneAlert = SafetyCenterStatus.Builder( - safetyCenterResourcesContext.getStringByName( + safetyCenterResourcesApk.getStringByName( "overall_severity_level_critical_device_warning_title" ), safetyCenterTestData.getAlertString(1) @@ -282,7 +276,7 @@ class SafetyCenterManagerTest { private val safetyCenterStatusDeviceCriticalTwoAlerts = SafetyCenterStatus.Builder( - safetyCenterResourcesContext.getStringByName( + safetyCenterResourcesApk.getStringByName( "overall_severity_level_critical_device_warning_title" ), safetyCenterTestData.getAlertString(2) @@ -302,7 +296,7 @@ class SafetyCenterManagerTest { SafetyCenterEntryOrGroup( SafetyCenterEntryGroup.Builder(MIXED_STATEFUL_GROUP_ID, "OK") .setSeverityLevel(ENTRY_SEVERITY_LEVEL_UNKNOWN) - .setSummary(safetyCenterResourcesContext.getStringByName("group_unknown_summary")) + .setSummary(safetyCenterResourcesApk.getStringByName("group_unknown_summary")) .setEntries( listOf( safetyCenterTestData.safetyCenterEntryDefault(DYNAMIC_IN_STATEFUL_ID), @@ -604,7 +598,7 @@ class SafetyCenterManagerTest { SafetyCenterEntryGroup.Builder(DYNAMIC_GROUP_ID, "OK") .setSeverityLevel(ENTRY_SEVERITY_LEVEL_UNKNOWN) .setSummary( - safetyCenterResourcesContext.getStringByName("group_unknown_summary") + safetyCenterResourcesApk.getStringByName("group_unknown_summary") ) .setSeverityUnspecifiedIconType(SEVERITY_UNSPECIFIED_ICON_TYPE_PRIVACY) .setEntries( @@ -791,9 +785,9 @@ class SafetyCenterManagerTest { val status1 = listener.receiveSafetyCenterData().status assertThat(status1.refreshStatus).isEqualTo(REFRESH_STATUS_FULL_RESCAN_IN_PROGRESS) assertThat(status1.title.toString()) - .isEqualTo(safetyCenterResourcesContext.getStringByName("scanning_title")) + .isEqualTo(safetyCenterResourcesApk.getStringByName("scanning_title")) assertThat(status1.summary.toString()) - .isEqualTo(safetyCenterResourcesContext.getStringByName("loading_summary")) + .isEqualTo(safetyCenterResourcesApk.getStringByName("loading_summary")) val status2 = listener.receiveSafetyCenterData().status assertThat(status2.refreshStatus).isEqualTo(REFRESH_STATUS_NONE) assertThat(status2).isEqualTo(safetyCenterStatusOk) @@ -815,9 +809,9 @@ class SafetyCenterManagerTest { val status1 = listener.receiveSafetyCenterData().status assertThat(status1.refreshStatus).isEqualTo(REFRESH_STATUS_DATA_FETCH_IN_PROGRESS) assertThat(status1.title.toString()) - .isEqualTo(safetyCenterResourcesContext.getStringByName("scanning_title")) + .isEqualTo(safetyCenterResourcesApk.getStringByName("scanning_title")) assertThat(status1.summary.toString()) - .isEqualTo(safetyCenterResourcesContext.getStringByName("loading_summary")) + .isEqualTo(safetyCenterResourcesApk.getStringByName("loading_summary")) val status2 = listener.receiveSafetyCenterData().status assertThat(status2.refreshStatus).isEqualTo(REFRESH_STATUS_NONE) assertThat(status2).isEqualTo(safetyCenterStatusOk) @@ -841,7 +835,7 @@ class SafetyCenterManagerTest { assertThat(status1.refreshStatus).isEqualTo(REFRESH_STATUS_DATA_FETCH_IN_PROGRESS) assertThat(status1.title.toString()).isEqualTo(safetyCenterStatusOk.title.toString()) assertThat(status1.summary.toString()) - .isEqualTo(safetyCenterResourcesContext.getStringByName("loading_summary")) + .isEqualTo(safetyCenterResourcesApk.getStringByName("loading_summary")) val status2 = listener.receiveSafetyCenterData().status assertThat(status2.refreshStatus).isEqualTo(REFRESH_STATUS_NONE) assertThat(status2).isEqualTo(safetyCenterStatusOk) @@ -2814,7 +2808,7 @@ class SafetyCenterManagerTest { safetyCenterManager.getSafetyCenterDataWithPermission().getGroup(SUMMARY_TEST_GROUP_ID) assertThat(group.summary) - .isEqualTo(safetyCenterResourcesContext.getStringByName("group_unknown_summary")) + .isEqualTo(safetyCenterResourcesApk.getStringByName("group_unknown_summary")) assertThat(group.severityLevel).isEqualTo(ENTRY_SEVERITY_LEVEL_UNKNOWN) } @@ -2828,7 +2822,7 @@ class SafetyCenterManagerTest { .getGroup(ANDROID_LOCK_SCREEN_SOURCES_GROUP_ID) assertThat(initialGroup.summary) - .isEqualTo(safetyCenterResourcesContext.getStringByName("group_unknown_summary")) + .isEqualTo(safetyCenterResourcesApk.getStringByName("group_unknown_summary")) assertThat(initialGroup.severityLevel).isEqualTo(ENTRY_SEVERITY_LEVEL_UNKNOWN) safetyCenterTestHelper.setData(DYNAMIC_BAREBONE_ID, safetySourceTestData.unspecified) @@ -3323,7 +3317,7 @@ class SafetyCenterManagerTest { assertThat(error) .isEqualTo( SafetyCenterErrorDetails( - safetyCenterResourcesContext.getStringByName("resolving_action_error") + safetyCenterResourcesApk.getStringByName("resolving_action_error") ) ) } @@ -3357,7 +3351,7 @@ class SafetyCenterManagerTest { assertThat(error) .isEqualTo( SafetyCenterErrorDetails( - safetyCenterResourcesContext.getStringByName("resolving_action_error") + safetyCenterResourcesApk.getStringByName("resolving_action_error") ) ) } diff --git a/tests/functional/safetycenter/singleuser/src/android/safetycenter/functional/ui/SafetyCenterStatusCardTest.kt b/tests/functional/safetycenter/singleuser/src/android/safetycenter/functional/ui/SafetyCenterStatusCardTest.kt index 326e805a3..5655b935b 100644 --- a/tests/functional/safetycenter/singleuser/src/android/safetycenter/functional/ui/SafetyCenterStatusCardTest.kt +++ b/tests/functional/safetycenter/singleuser/src/android/safetycenter/functional/ui/SafetyCenterStatusCardTest.kt @@ -22,7 +22,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.uiautomator.By import com.android.compatibility.common.util.DisableAnimationRule import com.android.compatibility.common.util.FreezeRotationRule -import com.android.safetycenter.resources.SafetyCenterResourcesContext +import com.android.safetycenter.resources.SafetyCenterResourcesApk import com.android.safetycenter.testing.SafetyCenterActivityLauncher.launchSafetyCenterActivity import com.android.safetycenter.testing.SafetyCenterTestConfigs import com.android.safetycenter.testing.SafetyCenterTestConfigs.Companion.SINGLE_SOURCE_ID @@ -49,7 +49,7 @@ import org.junit.runner.RunWith class SafetyCenterStatusCardTest { private val context: Context = getApplicationContext() - private val safetyCenterResourcesContext = SafetyCenterResourcesContext.forTests(context) + private val safetyCenterResourcesApk = SafetyCenterResourcesApk.forTests(context) private val safetyCenterTestHelper = SafetyCenterTestHelper(context) private val safetySourceTestData = SafetySourceTestData(context) private val safetyCenterTestData = SafetyCenterTestData(context) @@ -66,8 +66,8 @@ class SafetyCenterStatusCardTest { context.launchSafetyCenterActivity { waitAllTextDisplayed( - safetyCenterResourcesContext.getStringByName("scanning_title"), - safetyCenterResourcesContext.getStringByName("loading_summary") + safetyCenterResourcesApk.getStringByName("scanning_title"), + safetyCenterResourcesApk.getStringByName("loading_summary") ) } } @@ -82,8 +82,8 @@ class SafetyCenterStatusCardTest { context.launchSafetyCenterActivity { waitAllTextDisplayed( - safetyCenterResourcesContext.getStringByName("overall_severity_level_ok_title"), - safetyCenterResourcesContext.getStringByName("loading_summary") + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_title"), + safetyCenterResourcesApk.getStringByName("loading_summary") ) } } @@ -95,12 +95,8 @@ class SafetyCenterStatusCardTest { context.launchSafetyCenterActivity(withReceiverPermission = true) { waitAllTextDisplayed( - safetyCenterResourcesContext.getStringByName( - "overall_severity_level_ok_review_title" - ), - safetyCenterResourcesContext.getStringByName( - "overall_severity_level_ok_review_summary" - ) + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_review_title"), + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_review_summary") ) waitButtonDisplayed(RESCAN_BUTTON_LABEL) } @@ -116,8 +112,8 @@ class SafetyCenterStatusCardTest { context.launchSafetyCenterActivity(withReceiverPermission = true) { waitAllTextDisplayed( - safetyCenterResourcesContext.getStringByName("overall_severity_level_ok_title"), - safetyCenterResourcesContext.getStringByName("overall_severity_level_ok_summary") + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_title"), + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_summary") ) waitButtonDisplayed(RESCAN_BUTTON_LABEL) } @@ -147,7 +143,7 @@ class SafetyCenterStatusCardTest { context.launchSafetyCenterActivity(withReceiverPermission = true) { waitAllTextDisplayed( - safetyCenterResourcesContext.getStringByName("overall_severity_level_ok_title"), + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_title"), safetyCenterTestData.getAlertString(1) ) waitButtonNotDisplayed(RESCAN_BUTTON_LABEL) @@ -164,7 +160,7 @@ class SafetyCenterStatusCardTest { context.launchSafetyCenterActivity(withReceiverPermission = true) { waitAllTextDisplayed( - safetyCenterResourcesContext.getStringByName( + safetyCenterResourcesApk.getStringByName( "overall_severity_level_safety_recommendation_title" ), safetyCenterTestData.getAlertString(1) @@ -183,7 +179,7 @@ class SafetyCenterStatusCardTest { context.launchSafetyCenterActivity(withReceiverPermission = true) { waitAllTextDisplayed( - safetyCenterResourcesContext.getStringByName( + safetyCenterResourcesApk.getStringByName( "overall_severity_level_critical_safety_warning_title" ), safetyCenterTestData.getAlertString(1) @@ -202,15 +198,15 @@ class SafetyCenterStatusCardTest { context.launchSafetyCenterActivity(withReceiverPermission = true) { waitAllTextDisplayed( - safetyCenterResourcesContext.getStringByName("overall_severity_level_ok_title"), - safetyCenterResourcesContext.getStringByName("overall_severity_level_ok_summary") + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_title"), + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_summary") ) waitButtonDisplayed(RESCAN_BUTTON_LABEL) { it.click() } waitAllTextDisplayed( - safetyCenterResourcesContext.getStringByName("scanning_title"), - safetyCenterResourcesContext.getStringByName("loading_summary") + safetyCenterResourcesApk.getStringByName("scanning_title"), + safetyCenterResourcesApk.getStringByName("loading_summary") ) } } @@ -229,14 +225,14 @@ class SafetyCenterStatusCardTest { context.launchSafetyCenterActivity(withReceiverPermission = true) { waitAllTextDisplayed( - safetyCenterResourcesContext.getStringByName("overall_severity_level_ok_title"), - safetyCenterResourcesContext.getStringByName("overall_severity_level_ok_summary") + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_title"), + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_summary") ) waitButtonDisplayed(RESCAN_BUTTON_LABEL) { it.click() } waitAllTextDisplayed( - safetyCenterResourcesContext.getStringByName( + safetyCenterResourcesApk.getStringByName( "overall_severity_level_safety_recommendation_title" ), safetyCenterTestData.getAlertString(1) diff --git a/tests/functional/safetycenter/singleuser/src/android/safetycenter/functional/ui/SafetyCenterSubpagesTest.kt b/tests/functional/safetycenter/singleuser/src/android/safetycenter/functional/ui/SafetyCenterSubpagesTest.kt index ad3ce3344..932f99917 100644 --- a/tests/functional/safetycenter/singleuser/src/android/safetycenter/functional/ui/SafetyCenterSubpagesTest.kt +++ b/tests/functional/safetycenter/singleuser/src/android/safetycenter/functional/ui/SafetyCenterSubpagesTest.kt @@ -35,7 +35,7 @@ import com.android.compatibility.common.util.DisableAnimationRule import com.android.compatibility.common.util.FreezeRotationRule import com.android.compatibility.common.util.RetryRule import com.android.compatibility.common.util.UiAutomatorUtils2 -import com.android.safetycenter.resources.SafetyCenterResourcesContext +import com.android.safetycenter.resources.SafetyCenterResourcesApk import com.android.safetycenter.testing.Coroutines.TIMEOUT_LONG import com.android.safetycenter.testing.Coroutines.TIMEOUT_SHORT import com.android.safetycenter.testing.SafetyCenterActivityLauncher.launchSafetyCenterActivity @@ -94,7 +94,7 @@ class SafetyCenterSubpagesTest { private val safetyCenterTestHelper = SafetyCenterTestHelper(context) private val safetySourceTestData = SafetySourceTestData(context) private val safetyCenterTestConfigs = SafetyCenterTestConfigs(context) - private val safetyCenterResourcesContext = SafetyCenterResourcesContext.forTests(context) + private val safetyCenterResourcesApk = SafetyCenterResourcesApk.forTests(context) @get:Rule(order = 1) val supportsSafetyCenterRule = SupportsSafetyCenterRule(context) @get:Rule(order = 2) val safetyCenterTestRule = SafetyCenterTestRule(safetyCenterTestHelper) @@ -957,9 +957,7 @@ class SafetyCenterSubpagesTest { waitAllTextDisplayed( context.getString(source.titleResId), context.getString(source.summaryResId), - safetyCenterResourcesContext.getStringByName( - "test_single_source_group_id_footer" - ) + safetyCenterResourcesApk.getStringByName("test_single_source_group_id_footer") ) } } diff --git a/tests/utils/safetycenter/java/com/android/safetycenter/testing/SafetyCenterTestData.kt b/tests/utils/safetycenter/java/com/android/safetycenter/testing/SafetyCenterTestData.kt index 5ff42e23c..bc5395d74 100644 --- a/tests/utils/safetycenter/java/com/android/safetycenter/testing/SafetyCenterTestData.kt +++ b/tests/utils/safetycenter/java/com/android/safetycenter/testing/SafetyCenterTestData.kt @@ -48,7 +48,7 @@ import com.android.safetycenter.internaldata.SafetyCenterIds import com.android.safetycenter.internaldata.SafetyCenterIssueActionId import com.android.safetycenter.internaldata.SafetyCenterIssueId import com.android.safetycenter.internaldata.SafetyCenterIssueKey -import com.android.safetycenter.resources.SafetyCenterResourcesContext +import com.android.safetycenter.resources.SafetyCenterResourcesApk import com.android.safetycenter.testing.SafetyCenterTestConfigs.Companion.SINGLE_SOURCE_GROUP_ID import com.android.safetycenter.testing.SafetySourceTestData.Companion.CRITICAL_ISSUE_ACTION_ID import com.android.safetycenter.testing.SafetySourceTestData.Companion.CRITICAL_ISSUE_ID @@ -66,7 +66,7 @@ import java.util.Locale @RequiresApi(TIRAMISU) class SafetyCenterTestData(context: Context) { - private val safetyCenterResourcesContext = SafetyCenterResourcesContext.forTests(context) + private val safetyCenterResourcesApk = SafetyCenterResourcesApk.forTests(context) private val safetySourceTestData = SafetySourceTestData(context) /** @@ -74,12 +74,8 @@ class SafetyCenterTestData(context: Context) { */ val safetyCenterStatusUnknown = SafetyCenterStatus.Builder( - safetyCenterResourcesContext.getStringByName( - "overall_severity_level_ok_review_title" - ), - safetyCenterResourcesContext.getStringByName( - "overall_severity_level_ok_review_summary" - ) + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_review_title"), + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_review_summary") ) .setSeverityLevel(OVERALL_SEVERITY_LEVEL_UNKNOWN) .build() @@ -103,7 +99,7 @@ class SafetyCenterTestData(context: Context) { numAlerts: Int, ): SafetyCenterStatus = SafetyCenterStatus.Builder( - safetyCenterResourcesContext.getStringByName(statusResource), + safetyCenterResourcesApk.getStringByName(statusResource), getAlertString(numAlerts) ) .setSeverityLevel(overallSeverityLevel) @@ -117,8 +113,8 @@ class SafetyCenterTestData(context: Context) { numTipIssues: Int, ): SafetyCenterStatus = SafetyCenterStatus.Builder( - safetyCenterResourcesContext.getStringByName("overall_severity_level_ok_title"), - safetyCenterResourcesContext.getStringByName( + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_title"), + safetyCenterResourcesApk.getStringByName( "overall_severity_level_tip_summary", numTipIssues ) @@ -134,8 +130,8 @@ class SafetyCenterTestData(context: Context) { numAutomaticIssues: Int, ): SafetyCenterStatus = SafetyCenterStatus.Builder( - safetyCenterResourcesContext.getStringByName("overall_severity_level_ok_title"), - safetyCenterResourcesContext.getStringByName( + safetyCenterResourcesApk.getStringByName("overall_severity_level_ok_title"), + safetyCenterResourcesApk.getStringByName( "overall_severity_level_action_taken_summary", numAutomaticIssues ) @@ -149,7 +145,7 @@ class SafetyCenterTestData(context: Context) { */ fun safetyCenterStatusCritical(numAlerts: Int) = SafetyCenterStatus.Builder( - safetyCenterResourcesContext.getStringByName( + safetyCenterResourcesApk.getStringByName( "overall_severity_level_critical_safety_warning_title" ), getAlertString(numAlerts) @@ -428,7 +424,7 @@ class SafetyCenterTestData(context: Context) { private fun getIcuPluralsString(name: String, count: Int, vararg formatArgs: Any): String { val messageFormat = MessageFormat( - safetyCenterResourcesContext.getStringByName(name, formatArgs), + safetyCenterResourcesApk.getStringByName(name, formatArgs), Locale.getDefault() ) val arguments = ArrayMap<String, Any>() |