Merge "Remove spammy bubble logs for OLD interrupt provider" into main
diff --git a/Ravenwood.bp b/Ravenwood.bp
index 4e36075..c73e048 100644
--- a/Ravenwood.bp
+++ b/Ravenwood.bp
@@ -145,6 +145,16 @@
}
java_library {
+ name: "services.fakes.ravenwood-jarjar",
+ installable: false,
+ srcs: [":services.fakes-sources"],
+ libs: [
+ "services.core.ravenwood",
+ ],
+ jarjar_rules: ":ravenwood-services-jarjar-rules",
+}
+
+java_library {
name: "mockito-ravenwood-prebuilt",
installable: false,
static_libs: [
@@ -189,6 +199,7 @@
"ravenwood-helper-runtime",
"hoststubgen-helper-runtime.ravenwood",
"services.core.ravenwood-jarjar",
+ "services.fakes.ravenwood-jarjar",
// Provide runtime versions of utils linked in below
"junit",
diff --git a/boot/Android.bp b/boot/Android.bp
index cdfa7c80..f60bb9e 100644
--- a/boot/Android.bp
+++ b/boot/Android.bp
@@ -31,6 +31,7 @@
"car_bootclasspath_fragment",
"nfc_apex_bootclasspath_fragment",
"release_crashrecovery_module",
+ "release_package_profiling_module",
],
properties: [
"fragments",
@@ -122,10 +123,6 @@
module: "com.android.permission-bootclasspath-fragment",
},
{
- apex: "com.android.profiling",
- module: "com.android.profiling-bootclasspath-fragment",
- },
- {
apex: "com.android.scheduling",
module: "com.android.scheduling-bootclasspath-fragment",
},
@@ -179,6 +176,15 @@
},
],
},
+ release_package_profiling_module: {
+ fragments: [
+ // only used if profiling is enabled.
+ {
+ apex: "com.android.profiling",
+ module: "com.android.profiling-bootclasspath-fragment",
+ },
+ ],
+ },
},
// Additional information needed by hidden api processing.
diff --git a/core/api/current.txt b/core/api/current.txt
index 386396c..48e3fc2 100644
--- a/core/api/current.txt
+++ b/core/api/current.txt
@@ -203,7 +203,7 @@
field public static final String MANAGE_DEVICE_POLICY_SYSTEM_APPS = "android.permission.MANAGE_DEVICE_POLICY_SYSTEM_APPS";
field public static final String MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS = "android.permission.MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS";
field public static final String MANAGE_DEVICE_POLICY_SYSTEM_UPDATES = "android.permission.MANAGE_DEVICE_POLICY_SYSTEM_UPDATES";
- field @FlaggedApi("com.android.net.thread.flags.thread_user_restriction_enabled") public static final String MANAGE_DEVICE_POLICY_THREAD_NETWORK = "android.permission.MANAGE_DEVICE_POLICY_THREAD_NETWORK";
+ field @FlaggedApi("com.android.net.thread.platform.flags.thread_user_restriction_enabled") public static final String MANAGE_DEVICE_POLICY_THREAD_NETWORK = "android.permission.MANAGE_DEVICE_POLICY_THREAD_NETWORK";
field public static final String MANAGE_DEVICE_POLICY_TIME = "android.permission.MANAGE_DEVICE_POLICY_TIME";
field public static final String MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING = "android.permission.MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING";
field public static final String MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER = "android.permission.MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER";
@@ -3350,7 +3350,6 @@
method @FlaggedApi("android.view.accessibility.a11y_overlay_callbacks") public void attachAccessibilityOverlayToWindow(int, @NonNull android.view.SurfaceControl, @NonNull java.util.concurrent.Executor, @NonNull java.util.function.IntConsumer);
method public boolean clearCache();
method public boolean clearCachedSubtree(@NonNull android.view.accessibility.AccessibilityNodeInfo);
- method @FlaggedApi("android.view.accessibility.braille_display_hid") public void clearTestBrailleDisplayController();
method public final void disableSelf();
method public final boolean dispatchGesture(@NonNull android.accessibilityservice.GestureDescription, @Nullable android.accessibilityservice.AccessibilityService.GestureResultCallback, @Nullable android.os.Handler);
method public android.view.accessibility.AccessibilityNodeInfo findFocus(int);
@@ -3386,7 +3385,6 @@
method public boolean setCacheEnabled(boolean);
method public void setGestureDetectionPassthroughRegion(int, @NonNull android.graphics.Region);
method public final void setServiceInfo(android.accessibilityservice.AccessibilityServiceInfo);
- method @FlaggedApi("android.view.accessibility.braille_display_hid") public void setTestBrailleDisplayController(@NonNull android.accessibilityservice.BrailleDisplayController);
method public void setTouchExplorationPassthroughRegion(int, @NonNull android.graphics.Region);
method public void takeScreenshot(int, @NonNull java.util.concurrent.Executor, @NonNull android.accessibilityservice.AccessibilityService.TakeScreenshotCallback);
method public void takeScreenshotOfWindow(int, @NonNull java.util.concurrent.Executor, @NonNull android.accessibilityservice.AccessibilityService.TakeScreenshotCallback);
@@ -13218,7 +13216,7 @@
field public static final String FEATURE_TELEPHONY_RADIO_ACCESS = "android.hardware.telephony.radio.access";
field public static final String FEATURE_TELEPHONY_SUBSCRIPTION = "android.hardware.telephony.subscription";
field @Deprecated public static final String FEATURE_TELEVISION = "android.hardware.type.television";
- field @FlaggedApi("com.android.net.thread.flags.thread_enabled_platform") public static final String FEATURE_THREAD_NETWORK = "android.hardware.thread_network";
+ field @FlaggedApi("com.android.net.thread.platform.flags.thread_enabled_platform") public static final String FEATURE_THREAD_NETWORK = "android.hardware.thread_network";
field public static final String FEATURE_TOUCHSCREEN = "android.hardware.touchscreen";
field public static final String FEATURE_TOUCHSCREEN_MULTITOUCH = "android.hardware.touchscreen.multitouch";
field public static final String FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT = "android.hardware.touchscreen.multitouch.distinct";
@@ -13510,7 +13508,7 @@
field public static final int FLAG_USE_APP_ZYGOTE = 8; // 0x8
field @RequiresPermission(allOf={android.Manifest.permission.FOREGROUND_SERVICE_CAMERA}, anyOf={android.Manifest.permission.CAMERA}, conditional=true) public static final int FOREGROUND_SERVICE_TYPE_CAMERA = 64; // 0x40
field @RequiresPermission(allOf={android.Manifest.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE}, anyOf={android.Manifest.permission.BLUETOOTH_ADVERTISE, android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_SCAN, android.Manifest.permission.CHANGE_NETWORK_STATE, android.Manifest.permission.CHANGE_WIFI_STATE, android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE, android.Manifest.permission.NFC, android.Manifest.permission.TRANSMIT_IR, android.Manifest.permission.UWB_RANGING}, conditional=true) public static final int FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE = 16; // 0x10
- field @Deprecated @RequiresPermission(value=android.Manifest.permission.FOREGROUND_SERVICE_DATA_SYNC, conditional=true) public static final int FOREGROUND_SERVICE_TYPE_DATA_SYNC = 1; // 0x1
+ field @RequiresPermission(value=android.Manifest.permission.FOREGROUND_SERVICE_DATA_SYNC, conditional=true) public static final int FOREGROUND_SERVICE_TYPE_DATA_SYNC = 1; // 0x1
field @RequiresPermission(allOf={android.Manifest.permission.FOREGROUND_SERVICE_HEALTH}, anyOf={android.Manifest.permission.ACTIVITY_RECOGNITION, android.Manifest.permission.BODY_SENSORS, android.Manifest.permission.HIGH_SAMPLING_RATE_SENSORS}) public static final int FOREGROUND_SERVICE_TYPE_HEALTH = 256; // 0x100
field @RequiresPermission(allOf={android.Manifest.permission.FOREGROUND_SERVICE_LOCATION}, anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}, conditional=true) public static final int FOREGROUND_SERVICE_TYPE_LOCATION = 8; // 0x8
field public static final int FOREGROUND_SERVICE_TYPE_MANIFEST = -1; // 0xffffffff
@@ -34086,7 +34084,7 @@
field @FlaggedApi("android.app.admin.flags.esim_management_enabled") public static final String DISALLOW_SIM_GLOBALLY = "no_sim_globally";
field public static final String DISALLOW_SMS = "no_sms";
field public static final String DISALLOW_SYSTEM_ERROR_DIALOGS = "no_system_error_dialogs";
- field @FlaggedApi("com.android.net.thread.flags.thread_user_restriction_enabled") public static final String DISALLOW_THREAD_NETWORK = "no_thread_network";
+ field @FlaggedApi("com.android.net.thread.platform.flags.thread_user_restriction_enabled") public static final String DISALLOW_THREAD_NETWORK = "no_thread_network";
field public static final String DISALLOW_ULTRA_WIDEBAND_RADIO = "no_ultra_wideband_radio";
field public static final String DISALLOW_UNIFIED_PASSWORD = "no_unified_password";
field public static final String DISALLOW_UNINSTALL_APPS = "no_uninstall_apps";
@@ -35817,54 +35815,6 @@
field public static final String LONGITUDE = "longitude";
}
- @FlaggedApi("android.provider.user_keys") public final class ContactKeysManager {
- method @NonNull @RequiresPermission(android.Manifest.permission.READ_CONTACTS) public java.util.List<android.provider.ContactKeysManager.ContactKey> getAllContactKeys(@NonNull String);
- method @NonNull @RequiresPermission(android.Manifest.permission.READ_CONTACTS) public java.util.List<android.provider.ContactKeysManager.SelfKey> getAllSelfKeys();
- method @Nullable @RequiresPermission(android.Manifest.permission.READ_CONTACTS) public android.provider.ContactKeysManager.ContactKey getContactKey(@NonNull String, @NonNull String, @NonNull String);
- method public static int getMaxKeySizeBytes();
- method @NonNull @RequiresPermission(android.Manifest.permission.READ_CONTACTS) public java.util.List<android.provider.ContactKeysManager.ContactKey> getOwnerContactKeys(@NonNull String);
- method @NonNull @RequiresPermission(android.Manifest.permission.READ_CONTACTS) public java.util.List<android.provider.ContactKeysManager.SelfKey> getOwnerSelfKeys();
- method @Nullable @RequiresPermission(android.Manifest.permission.READ_CONTACTS) public android.provider.ContactKeysManager.SelfKey getSelfKey(@NonNull String, @NonNull String);
- method @RequiresPermission(android.Manifest.permission.WRITE_CONTACTS) public boolean removeContactKey(@NonNull String, @NonNull String, @NonNull String);
- method @RequiresPermission(android.Manifest.permission.WRITE_CONTACTS) public boolean removeSelfKey(@NonNull String, @NonNull String);
- method @RequiresPermission(android.Manifest.permission.WRITE_CONTACTS) public boolean updateContactKeyLocalVerificationState(@NonNull String, @NonNull String, @NonNull String, int);
- method @RequiresPermission(android.Manifest.permission.WRITE_CONTACTS) public boolean updateContactKeyRemoteVerificationState(@NonNull String, @NonNull String, @NonNull String, int);
- method @RequiresPermission(android.Manifest.permission.WRITE_CONTACTS) public void updateOrInsertContactKey(@NonNull String, @NonNull String, @NonNull String, @NonNull byte[]);
- method @RequiresPermission(android.Manifest.permission.WRITE_CONTACTS) public boolean updateOrInsertSelfKey(@NonNull String, @NonNull String, @NonNull byte[]);
- method @RequiresPermission(android.Manifest.permission.WRITE_CONTACTS) public boolean updateSelfKeyRemoteVerificationState(@NonNull String, @NonNull String, int);
- field public static final int VERIFICATION_STATE_UNVERIFIED = 0; // 0x0
- field public static final int VERIFICATION_STATE_VERIFICATION_FAILED = 1; // 0x1
- field public static final int VERIFICATION_STATE_VERIFIED = 2; // 0x2
- }
-
- public static final class ContactKeysManager.ContactKey implements android.os.Parcelable {
- method public int describeContents();
- method @NonNull public String getAccountId();
- method @Nullable public String getDeviceId();
- method @Nullable public String getDisplayName();
- method @Nullable public String getEmailAddress();
- method @Nullable public byte[] getKeyValue();
- method public int getLocalVerificationState();
- method @NonNull public String getOwnerPackageName();
- method @Nullable public String getPhoneNumber();
- method public int getRemoteVerificationState();
- method public long getTimeUpdated();
- method public void writeToParcel(@NonNull android.os.Parcel, int);
- field @NonNull public static final android.os.Parcelable.Creator<android.provider.ContactKeysManager.ContactKey> CREATOR;
- }
-
- public static final class ContactKeysManager.SelfKey implements android.os.Parcelable {
- method public int describeContents();
- method @NonNull public String getAccountId();
- method @Nullable public String getDeviceId();
- method @Nullable public byte[] getKeyValue();
- method @NonNull public String getOwnerPackageName();
- method public int getRemoteVerificationState();
- method public long getTimeUpdated();
- method public void writeToParcel(@NonNull android.os.Parcel, int);
- field @NonNull public static final android.os.Parcelable.Creator<android.provider.ContactKeysManager.SelfKey> CREATOR;
- }
-
@Deprecated public class Contacts {
field @Deprecated public static final String AUTHORITY = "contacts";
field @Deprecated public static final android.net.Uri CONTENT_URI;
@@ -37165,6 +37115,54 @@
method public final int update(android.net.Uri, android.content.ContentValues, String, String[]);
}
+ @FlaggedApi("android.provider.user_keys") public final class E2eeContactKeysManager {
+ method @NonNull @RequiresPermission(android.Manifest.permission.READ_CONTACTS) public java.util.List<android.provider.E2eeContactKeysManager.E2eeContactKey> getAllE2eeContactKeys(@NonNull String);
+ method @NonNull @RequiresPermission(android.Manifest.permission.READ_CONTACTS) public java.util.List<android.provider.E2eeContactKeysManager.E2eeSelfKey> getAllE2eeSelfKeys();
+ method @Nullable @RequiresPermission(android.Manifest.permission.READ_CONTACTS) public android.provider.E2eeContactKeysManager.E2eeContactKey getE2eeContactKey(@NonNull String, @NonNull String, @NonNull String);
+ method @Nullable @RequiresPermission(android.Manifest.permission.READ_CONTACTS) public android.provider.E2eeContactKeysManager.E2eeSelfKey getE2eeSelfKey(@NonNull String, @NonNull String);
+ method public static int getMaxKeySizeBytes();
+ method @NonNull @RequiresPermission(android.Manifest.permission.READ_CONTACTS) public java.util.List<android.provider.E2eeContactKeysManager.E2eeContactKey> getOwnerE2eeContactKeys(@NonNull String);
+ method @NonNull @RequiresPermission(android.Manifest.permission.READ_CONTACTS) public java.util.List<android.provider.E2eeContactKeysManager.E2eeSelfKey> getOwnerE2eeSelfKeys();
+ method @RequiresPermission(android.Manifest.permission.WRITE_CONTACTS) public boolean removeE2eeContactKey(@NonNull String, @NonNull String, @NonNull String);
+ method @RequiresPermission(android.Manifest.permission.WRITE_CONTACTS) public boolean removeE2eeSelfKey(@NonNull String, @NonNull String);
+ method @RequiresPermission(android.Manifest.permission.WRITE_CONTACTS) public boolean updateE2eeContactKeyLocalVerificationState(@NonNull String, @NonNull String, @NonNull String, int);
+ method @RequiresPermission(android.Manifest.permission.WRITE_CONTACTS) public boolean updateE2eeContactKeyRemoteVerificationState(@NonNull String, @NonNull String, @NonNull String, int);
+ method @RequiresPermission(android.Manifest.permission.WRITE_CONTACTS) public boolean updateE2eeSelfKeyRemoteVerificationState(@NonNull String, @NonNull String, int);
+ method @RequiresPermission(android.Manifest.permission.WRITE_CONTACTS) public void updateOrInsertE2eeContactKey(@NonNull String, @NonNull String, @NonNull String, @NonNull byte[]);
+ method @RequiresPermission(android.Manifest.permission.WRITE_CONTACTS) public boolean updateOrInsertE2eeSelfKey(@NonNull String, @NonNull String, @NonNull byte[]);
+ field public static final int VERIFICATION_STATE_UNVERIFIED = 0; // 0x0
+ field public static final int VERIFICATION_STATE_VERIFICATION_FAILED = 1; // 0x1
+ field public static final int VERIFICATION_STATE_VERIFIED = 2; // 0x2
+ }
+
+ public static final class E2eeContactKeysManager.E2eeContactKey implements android.os.Parcelable {
+ method public int describeContents();
+ method @NonNull public String getAccountId();
+ method @Nullable public String getDeviceId();
+ method @Nullable public String getDisplayName();
+ method @Nullable public String getEmailAddress();
+ method @Nullable public byte[] getKeyValue();
+ method public int getLocalVerificationState();
+ method @NonNull public String getOwnerPackageName();
+ method @Nullable public String getPhoneNumber();
+ method public int getRemoteVerificationState();
+ method public long getTimeUpdated();
+ method public void writeToParcel(@NonNull android.os.Parcel, int);
+ field @NonNull public static final android.os.Parcelable.Creator<android.provider.E2eeContactKeysManager.E2eeContactKey> CREATOR;
+ }
+
+ public static final class E2eeContactKeysManager.E2eeSelfKey implements android.os.Parcelable {
+ method public int describeContents();
+ method @NonNull public String getAccountId();
+ method @Nullable public String getDeviceId();
+ method @Nullable public byte[] getKeyValue();
+ method @NonNull public String getOwnerPackageName();
+ method public int getRemoteVerificationState();
+ method public long getTimeUpdated();
+ method public void writeToParcel(@NonNull android.os.Parcel, int);
+ field @NonNull public static final android.os.Parcelable.Creator<android.provider.E2eeContactKeysManager.E2eeSelfKey> CREATOR;
+ }
+
@Deprecated public final class FontRequest {
ctor @Deprecated public FontRequest(@NonNull String, @NonNull String, @NonNull String);
ctor @Deprecated public FontRequest(@NonNull String, @NonNull String, @NonNull String, @NonNull java.util.List<java.util.List<byte[]>>);
diff --git a/core/api/system-current.txt b/core/api/system-current.txt
index dfd915b..67ccd9d 100644
--- a/core/api/system-current.txt
+++ b/core/api/system-current.txt
@@ -388,7 +388,7 @@
field public static final String SYSTEM_APPLICATION_OVERLAY = "android.permission.SYSTEM_APPLICATION_OVERLAY";
field public static final String SYSTEM_CAMERA = "android.permission.SYSTEM_CAMERA";
field public static final String TETHER_PRIVILEGED = "android.permission.TETHER_PRIVILEGED";
- field @FlaggedApi("com.android.net.thread.flags.thread_enabled_platform") public static final String THREAD_NETWORK_PRIVILEGED = "android.permission.THREAD_NETWORK_PRIVILEGED";
+ field @FlaggedApi("com.android.net.thread.platform.flags.thread_enabled_platform") public static final String THREAD_NETWORK_PRIVILEGED = "android.permission.THREAD_NETWORK_PRIVILEGED";
field public static final String TIS_EXTENSION_INTERFACE = "android.permission.TIS_EXTENSION_INTERFACE";
field public static final String TOGGLE_AUTOMOTIVE_PROJECTION = "android.permission.TOGGLE_AUTOMOTIVE_PROJECTION";
field public static final String TRIGGER_LOST_MODE = "android.permission.TRIGGER_LOST_MODE";
@@ -1647,14 +1647,12 @@
method public int getDensityLevel();
method @NonNull public java.time.Instant getEndTime();
method public int getEventType();
- method @FlaggedApi("android.app.ambient_heart_rate") @IntRange(from=0xffffffff) public int getRatePerMinute();
method @NonNull public java.time.Instant getStartTime();
method @NonNull public android.os.PersistableBundle getVendorData();
method public void writeToParcel(@NonNull android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.app.ambientcontext.AmbientContextEvent> CREATOR;
field public static final int EVENT_BACK_DOUBLE_TAP = 3; // 0x3
field public static final int EVENT_COUGH = 1; // 0x1
- field @FlaggedApi("android.app.ambient_heart_rate") public static final int EVENT_HEART_RATE = 4; // 0x4
field public static final int EVENT_SNORE = 2; // 0x2
field public static final int EVENT_UNKNOWN = 0; // 0x0
field public static final int EVENT_VENDOR_WEARABLE_START = 100000; // 0x186a0
@@ -1665,7 +1663,6 @@
field public static final int LEVEL_MEDIUM_HIGH = 4; // 0x4
field public static final int LEVEL_MEDIUM_LOW = 2; // 0x2
field public static final int LEVEL_UNKNOWN = 0; // 0x0
- field @FlaggedApi("android.app.ambient_heart_rate") public static final int RATE_PER_MINUTE_UNKNOWN = -1; // 0xffffffff
}
public static final class AmbientContextEvent.Builder {
@@ -1675,7 +1672,6 @@
method @NonNull public android.app.ambientcontext.AmbientContextEvent.Builder setDensityLevel(int);
method @NonNull public android.app.ambientcontext.AmbientContextEvent.Builder setEndTime(@NonNull java.time.Instant);
method @NonNull public android.app.ambientcontext.AmbientContextEvent.Builder setEventType(int);
- method @FlaggedApi("android.app.ambient_heart_rate") @NonNull public android.app.ambientcontext.AmbientContextEvent.Builder setRatePerMinute(@IntRange(from=0xffffffff) int);
method @NonNull public android.app.ambientcontext.AmbientContextEvent.Builder setStartTime(@NonNull java.time.Instant);
method @NonNull public android.app.ambientcontext.AmbientContextEvent.Builder setVendorData(@NonNull android.os.PersistableBundle);
}
@@ -3787,7 +3783,7 @@
field public static final String SYSTEM_CONFIG_SERVICE = "system_config";
field public static final String SYSTEM_UPDATE_SERVICE = "system_update";
field public static final String TETHERING_SERVICE = "tethering";
- field @FlaggedApi("com.android.net.thread.flags.thread_enabled_platform") public static final String THREAD_NETWORK_SERVICE = "thread_network";
+ field @FlaggedApi("com.android.net.thread.platform.flags.thread_enabled_platform") public static final String THREAD_NETWORK_SERVICE = "thread_network";
field public static final String TIME_MANAGER_SERVICE = "time_manager";
field public static final String TRANSLATION_MANAGER_SERVICE = "translation";
field public static final String UI_TRANSLATION_SERVICE = "ui_translation";
@@ -11708,12 +11704,6 @@
field public static final int ERROR_UNKNOWN = 0; // 0x0
}
- @FlaggedApi("android.provider.user_keys") public final class ContactKeysManager {
- method @RequiresPermission(allOf={android.Manifest.permission.WRITE_VERIFICATION_STATE_E2EE_CONTACT_KEYS, android.Manifest.permission.WRITE_CONTACTS}) public boolean updateContactKeyLocalVerificationState(@NonNull String, @NonNull String, @NonNull String, @NonNull String, int);
- method @RequiresPermission(allOf={android.Manifest.permission.WRITE_VERIFICATION_STATE_E2EE_CONTACT_KEYS, android.Manifest.permission.WRITE_CONTACTS}) public boolean updateContactKeyRemoteVerificationState(@NonNull String, @NonNull String, @NonNull String, @NonNull String, int);
- method @RequiresPermission(allOf={android.Manifest.permission.WRITE_VERIFICATION_STATE_E2EE_CONTACT_KEYS, android.Manifest.permission.WRITE_CONTACTS}) public boolean updateSelfKeyRemoteVerificationState(@NonNull String, @NonNull String, @NonNull String, int);
- }
-
@Deprecated public static final class ContactsContract.MetadataSync implements android.provider.BaseColumns android.provider.ContactsContract.MetadataSyncColumns {
field @Deprecated public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/contact_metadata";
field @Deprecated public static final String CONTENT_TYPE = "vnd.android.cursor.dir/contact_metadata";
@@ -11771,6 +11761,12 @@
field public static final int FLAG_REMOVABLE_USB = 524288; // 0x80000
}
+ @FlaggedApi("android.provider.user_keys") public final class E2eeContactKeysManager {
+ method @RequiresPermission(allOf={android.Manifest.permission.WRITE_VERIFICATION_STATE_E2EE_CONTACT_KEYS, android.Manifest.permission.WRITE_CONTACTS}) public boolean updateE2eeContactKeyLocalVerificationState(@NonNull String, @NonNull String, @NonNull String, @NonNull String, int);
+ method @RequiresPermission(allOf={android.Manifest.permission.WRITE_VERIFICATION_STATE_E2EE_CONTACT_KEYS, android.Manifest.permission.WRITE_CONTACTS}) public boolean updateE2eeContactKeyRemoteVerificationState(@NonNull String, @NonNull String, @NonNull String, @NonNull String, int);
+ method @RequiresPermission(allOf={android.Manifest.permission.WRITE_VERIFICATION_STATE_E2EE_CONTACT_KEYS, android.Manifest.permission.WRITE_CONTACTS}) public boolean updateE2eeSelfKeyRemoteVerificationState(@NonNull String, @NonNull String, @NonNull String, int);
+ }
+
public abstract class SearchIndexableData {
ctor public SearchIndexableData();
ctor public SearchIndexableData(android.content.Context);
diff --git a/core/api/test-current.txt b/core/api/test-current.txt
index cdf232c..b8c32a4 100644
--- a/core/api/test-current.txt
+++ b/core/api/test-current.txt
@@ -251,6 +251,7 @@
method @RequiresPermission("android.permission.MANAGE_APPOPS") public void getHistoricalOpsFromDiskRaw(@NonNull android.app.AppOpsManager.HistoricalOpsRequest, @Nullable java.util.concurrent.Executor, @NonNull java.util.function.Consumer<android.app.AppOpsManager.HistoricalOps>);
method public static int getNumOps();
method public boolean isOperationActive(int, int, String);
+ method public int noteOpNoThrow(int, @NonNull android.content.AttributionSource, @Nullable String);
method @RequiresPermission("android.permission.MANAGE_APPOPS") public void offsetHistory(long);
method public static String opToPermission(int);
method public static int permissionToOpCode(String);
@@ -3966,6 +3967,7 @@
}
public final class InputMethodInfo implements android.os.Parcelable {
+ ctor public InputMethodInfo(@NonNull String, @NonNull String, @NonNull CharSequence, @NonNull String, @NonNull String, boolean, @NonNull String);
ctor @FlaggedApi("android.view.inputmethod.connectionless_handwriting") public InputMethodInfo(@NonNull String, @NonNull String, @NonNull CharSequence, @NonNull String, @NonNull String, boolean, boolean, @NonNull String);
ctor public InputMethodInfo(@NonNull String, @NonNull String, @NonNull CharSequence, @NonNull String, int);
field public static final int COMPONENT_NAME_MAX_LENGTH = 1000; // 0x3e8
diff --git a/core/java/android/accessibilityservice/AccessibilityService.java b/core/java/android/accessibilityservice/AccessibilityService.java
index 42c3272..d70fa19 100644
--- a/core/java/android/accessibilityservice/AccessibilityService.java
+++ b/core/java/android/accessibilityservice/AccessibilityService.java
@@ -81,7 +81,6 @@
import java.lang.annotation.RetentionPolicy;
import java.util.Collections;
import java.util.List;
-import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
@@ -853,7 +852,6 @@
private final SparseArray<AccessibilityButtonController> mAccessibilityButtonControllers =
new SparseArray<>(0);
private BrailleDisplayController mBrailleDisplayController;
- private BrailleDisplayController mTestBrailleDisplayController;
private int mGestureStatusCallbackSequence;
@@ -3650,46 +3648,10 @@
public BrailleDisplayController getBrailleDisplayController() {
BrailleDisplayController.checkApiFlagIsEnabled();
synchronized (mLock) {
- if (mTestBrailleDisplayController != null) {
- return mTestBrailleDisplayController;
- }
-
if (mBrailleDisplayController == null) {
mBrailleDisplayController = new BrailleDisplayControllerImpl(this, mLock);
}
return mBrailleDisplayController;
}
}
-
- /**
- * Set the {@link BrailleDisplayController} implementation that will be returned by
- * {@link #getBrailleDisplayController}, to allow this accessibility service to test its
- * interaction with BrailleDisplayController without requiring a real Braille display.
- *
- * <p>For full test fidelity, ensure that this test-only implementation follows the same
- * behavior specified in the documentation for {@link BrailleDisplayController}, including
- * thrown exceptions.
- *
- * @param controller A test-only implementation of {@link BrailleDisplayController}.
- */
- @FlaggedApi(android.view.accessibility.Flags.FLAG_BRAILLE_DISPLAY_HID)
- public void setTestBrailleDisplayController(@NonNull BrailleDisplayController controller) {
- BrailleDisplayController.checkApiFlagIsEnabled();
- Objects.requireNonNull(controller);
- synchronized (mLock) {
- mTestBrailleDisplayController = controller;
- }
- }
-
- /**
- * Clears the {@link BrailleDisplayController} previously set by
- * {@link #setTestBrailleDisplayController}.
- */
- @FlaggedApi(android.view.accessibility.Flags.FLAG_BRAILLE_DISPLAY_HID)
- public void clearTestBrailleDisplayController() {
- BrailleDisplayController.checkApiFlagIsEnabled();
- synchronized (mLock) {
- mTestBrailleDisplayController = null;
- }
- }
}
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index 074f7e9..41151c0 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -717,7 +717,7 @@
}
activity.mMainThread.handleActivityConfigurationChanged(
ActivityClientRecord.this, overrideConfig, newDisplayId,
- false /* alwaysReportChange */);
+ mActivityWindowInfo, false /* alwaysReportChange */);
}
@Override
@@ -6659,11 +6659,12 @@
/**
* Sets the supplied {@code overrideConfig} as pending for the {@code token}. Calling
* this method prevents any calls to
- * {@link #handleActivityConfigurationChanged(ActivityClientRecord, Configuration, int)} from
- * processing any configurations older than {@code overrideConfig}.
+ * {@link #handleActivityConfigurationChanged(ActivityClientRecord, Configuration, int,
+ * ActivityWindowInfo)} from processing any configurations older than {@code overrideConfig}.
*/
@Override
- public void updatePendingActivityConfiguration(IBinder token, Configuration overrideConfig) {
+ public void updatePendingActivityConfiguration(@NonNull IBinder token,
+ @NonNull Configuration overrideConfig) {
synchronized (mPendingOverrideConfigs) {
final Configuration pendingOverrideConfig = mPendingOverrideConfigs.get(token);
if (pendingOverrideConfig != null
@@ -6680,9 +6681,10 @@
}
@Override
- public void handleActivityConfigurationChanged(ActivityClientRecord r,
- @NonNull Configuration overrideConfig, int displayId) {
- handleActivityConfigurationChanged(r, overrideConfig, displayId,
+ public void handleActivityConfigurationChanged(@NonNull ActivityClientRecord r,
+ @NonNull Configuration overrideConfig, int displayId,
+ @NonNull ActivityWindowInfo activityWindowInfo) {
+ handleActivityConfigurationChanged(r, overrideConfig, displayId, activityWindowInfo,
// This is the only place that uses alwaysReportChange=true. The entry point should
// be from ActivityConfigurationChangeItem or MoveToDisplayItem, so the server side
// has confirmed the activity should handle the configuration instead of relaunch.
@@ -6700,9 +6702,11 @@
* @param overrideConfig Activity override config.
* @param displayId Id of the display where activity was moved to, -1 if there was no move and
* value didn't change.
+ * @param activityWindowInfo the window info of the given activity.
*/
- void handleActivityConfigurationChanged(ActivityClientRecord r,
- @NonNull Configuration overrideConfig, int displayId, boolean alwaysReportChange) {
+ void handleActivityConfigurationChanged(@NonNull ActivityClientRecord r,
+ @NonNull Configuration overrideConfig, int displayId,
+ @NonNull ActivityWindowInfo activityWindowInfo, boolean alwaysReportChange) {
synchronized (mPendingOverrideConfigs) {
final Configuration pendingOverrideConfig = mPendingOverrideConfigs.get(r.token);
if (overrideConfig.isOtherSeqNewer(pendingOverrideConfig)) {
@@ -6735,6 +6739,8 @@
// Perform updates.
r.overrideConfig = overrideConfig;
+ r.mActivityWindowInfo = activityWindowInfo;
+ // TODO(b/287582673): notify on ActivityWindowInfo change
final ViewRootImpl viewRoot = r.activity.mDecor != null
? r.activity.mDecor.getViewRootImpl() : null;
diff --git a/core/java/android/app/AppOpsManager.java b/core/java/android/app/AppOpsManager.java
index 39900a0..2afc78c 100644
--- a/core/java/android/app/AppOpsManager.java
+++ b/core/java/android/app/AppOpsManager.java
@@ -7800,7 +7800,7 @@
}
final List<AppOpsManager.PackageOps> result;
try {
- result = mService.getPackagesForOpsForDevice(opCodes, persistentDeviceId);
+ result = mService.getPackagesForOpsForDevice(opCodes, persistentDeviceId);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -8272,14 +8272,24 @@
cb = new IAppOpsCallback.Stub() {
public void opChanged(int op, int uid, String packageName,
String persistentDeviceId) {
- if (callback instanceof OnOpChangedInternalListener) {
- ((OnOpChangedInternalListener)callback).onOpChanged(op, packageName,
- persistentDeviceId);
- }
- if (sAppOpInfos[op].name != null) {
-
- callback.onOpChanged(sAppOpInfos[op].name, packageName,
- UserHandle.getUserId(uid), persistentDeviceId);
+ if (Flags.deviceAwarePermissionApisEnabled()) {
+ if (callback instanceof OnOpChangedInternalListener) {
+ ((OnOpChangedInternalListener)callback).onOpChanged(op, packageName,
+ persistentDeviceId);
+ }
+ if (sAppOpInfos[op].name != null) {
+ callback.onOpChanged(sAppOpInfos[op].name, packageName,
+ UserHandle.getUserId(uid), persistentDeviceId);
+ }
+ } else {
+ if (callback instanceof OnOpChangedInternalListener) {
+ ((OnOpChangedInternalListener) callback).onOpChanged(op,
+ packageName);
+ }
+ if (sAppOpInfos[op].name != null) {
+ callback.onOpChanged(sAppOpInfos[op].name, packageName,
+ UserHandle.getUserId(uid));
+ }
}
}
};
@@ -8940,6 +8950,8 @@
*
* @hide
*/
+ @TestApi
+ @SuppressLint("UnflaggedApi")
public int noteOpNoThrow(int op, @NonNull AttributionSource attributionSource,
@Nullable String message) {
return noteOpNoThrow(op, attributionSource.getUid(), attributionSource.getPackageName(),
diff --git a/core/java/android/app/ClientTransactionHandler.java b/core/java/android/app/ClientTransactionHandler.java
index 4c92dee..b5b3669 100644
--- a/core/java/android/app/ClientTransactionHandler.java
+++ b/core/java/android/app/ClientTransactionHandler.java
@@ -167,11 +167,12 @@
/** Set pending activity configuration in case it will be updated by other transaction item. */
public abstract void updatePendingActivityConfiguration(@NonNull IBinder token,
- Configuration overrideConfig);
+ @NonNull Configuration overrideConfig);
/** Deliver activity (override) configuration change. */
public abstract void handleActivityConfigurationChanged(@NonNull ActivityClientRecord r,
- Configuration overrideConfig, int displayId);
+ @NonNull Configuration overrideConfig, int displayId,
+ @NonNull ActivityWindowInfo activityWindowInfo);
/** Deliver {@link android.window.WindowContextInfo} change. */
public abstract void handleWindowContextInfoChanged(@NonNull IBinder clientToken,
diff --git a/core/java/android/app/ForegroundServiceTypePolicy.java b/core/java/android/app/ForegroundServiceTypePolicy.java
index 7e06735..d1e517b 100644
--- a/core/java/android/app/ForegroundServiceTypePolicy.java
+++ b/core/java/android/app/ForegroundServiceTypePolicy.java
@@ -62,7 +62,6 @@
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
-import android.os.Build;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.UserHandle;
@@ -128,14 +127,10 @@
* The FGS type enforcement:
* deprecating the {@link android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_DATA_SYNC}.
*
- * <p>Starting a FGS with this type from apps with targetSdkVersion
- * {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM} or later will result in a warning
- * in the log.
- *
* @hide
*/
@ChangeId
- @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+ @Disabled
@Overridable
public static final long FGS_TYPE_DATA_SYNC_DEPRECATION_CHANGE_ID = 255039210L;
diff --git a/core/java/android/app/SystemServiceRegistry.java b/core/java/android/app/SystemServiceRegistry.java
index 08c193f..d01626e 100644
--- a/core/java/android/app/SystemServiceRegistry.java
+++ b/core/java/android/app/SystemServiceRegistry.java
@@ -212,7 +212,7 @@
import android.permission.PermissionManager;
import android.print.IPrintManager;
import android.print.PrintManager;
-import android.provider.ContactKeysManager;
+import android.provider.E2eeContactKeysManager;
import android.safetycenter.SafetyCenterFrameworkInitializer;
import android.scheduling.SchedulingFrameworkInitializer;
import android.security.FileIntegrityManager;
@@ -1608,16 +1608,16 @@
}
});
- registerService(Context.CONTACT_KEYS_SERVICE, ContactKeysManager.class,
- new CachedServiceFetcher<ContactKeysManager>() {
+ registerService(Context.CONTACT_KEYS_SERVICE, E2eeContactKeysManager.class,
+ new CachedServiceFetcher<E2eeContactKeysManager>() {
@Override
- public ContactKeysManager createService(ContextImpl ctx)
+ public E2eeContactKeysManager createService(ContextImpl ctx)
throws ServiceNotFoundException {
if (!android.provider.Flags.userKeys()) {
throw new ServiceNotFoundException(
"ContactKeysManager is not supported");
}
- return new ContactKeysManager(ctx);
+ return new E2eeContactKeysManager(ctx);
}});
// DO NOT do a flag check like this unless the flag is read-only.
diff --git a/core/java/android/app/ambient_context.aconfig b/core/java/android/app/ambient_context.aconfig
deleted file mode 100644
index 3f73da2..0000000
--- a/core/java/android/app/ambient_context.aconfig
+++ /dev/null
@@ -1,8 +0,0 @@
-package: "android.app"
-
-flag {
- namespace: "biometrics_integration"
- name: "ambient_heart_rate"
- description: "Feature flag for adding heart rate api to ambient context."
- bug: "318309481"
-}
diff --git a/core/java/android/app/ambientcontext/AmbientContextEvent.java b/core/java/android/app/ambientcontext/AmbientContextEvent.java
index 5ab7991..13d959c 100644
--- a/core/java/android/app/ambientcontext/AmbientContextEvent.java
+++ b/core/java/android/app/ambientcontext/AmbientContextEvent.java
@@ -16,9 +16,7 @@
package android.app.ambientcontext;
-import android.annotation.FlaggedApi;
import android.annotation.IntDef;
-import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.SystemApi;
import android.os.Parcelable;
@@ -70,14 +68,6 @@
public static final int EVENT_BACK_DOUBLE_TAP = 3;
/**
- * The integer indicating a heart rate measurement was done.
- *
- * @see #getRatePerMinute
- */
- @Event @FlaggedApi(android.app.Flags.FLAG_AMBIENT_HEART_RATE)
- public static final int EVENT_HEART_RATE = 4;
-
- /**
* Integer indicating the start of wearable vendor defined events that can be detected.
* These depend on the vendor implementation.
*/
@@ -89,19 +79,12 @@
*/
public static final String KEY_VENDOR_WEARABLE_EVENT_NAME = "wearable_event_name";
- /**
- * Default value for {@link #getRatePerMinute}. Indicates that the rate of the event is unknown.
- */
- @FlaggedApi(android.app.Flags.FLAG_AMBIENT_HEART_RATE)
- public static final int RATE_PER_MINUTE_UNKNOWN = -1;
-
/** @hide */
@IntDef(prefix = { "EVENT_" }, value = {
EVENT_UNKNOWN,
EVENT_COUGH,
EVENT_SNORE,
EVENT_BACK_DOUBLE_TAP,
- EVENT_HEART_RATE,
EVENT_VENDOR_WEARABLE_START,
})
@Retention(RetentionPolicy.SOURCE)
@@ -187,16 +170,6 @@
return new PersistableBundle();
}
- /**
- * Rate per minute of the event during the start to end time.
- *
- * @return the rate per minute, or {@link #RATE_PER_MINUTE_UNKNOWN} if the rate is unknown.
- */
- private final @IntRange(from = -1) int mRatePerMinute;
- private static int defaultRatePerMinute() {
- return RATE_PER_MINUTE_UNKNOWN;
- }
-
// Code below generated by codegen v1.0.23.
@@ -206,8 +179,6 @@
//
// To regenerate run:
// $ codegen $ANDROID_BUILD_TOP/frameworks/base/core/java/android/app/ambientcontext/AmbientContextEvent.java
- // then manually add @FlaggedApi(android.app.Flags.FLAG_AMBIENT_HEART_RATE) back to flagged
- // APIs.
//
// To exclude the generated code from IntelliJ auto-formatting enable (one-time):
// Settings > Editor > Code Style > Formatter Control
@@ -220,7 +191,6 @@
EVENT_COUGH,
EVENT_SNORE,
EVENT_BACK_DOUBLE_TAP,
- EVENT_HEART_RATE,
EVENT_VENDOR_WEARABLE_START
})
@Retention(RetentionPolicy.SOURCE)
@@ -239,8 +209,6 @@
return "EVENT_SNORE";
case EVENT_BACK_DOUBLE_TAP:
return "EVENT_BACK_DOUBLE_TAP";
- case EVENT_HEART_RATE:
- return "EVENT_HEART_RATE";
case EVENT_VENDOR_WEARABLE_START:
return "EVENT_VENDOR_WEARABLE_START";
default: return Integer.toHexString(value);
@@ -287,8 +255,7 @@
@NonNull Instant endTime,
@LevelValue int confidenceLevel,
@LevelValue int densityLevel,
- @NonNull PersistableBundle vendorData,
- @IntRange(from = -1) int ratePerMinute) {
+ @NonNull PersistableBundle vendorData) {
this.mEventType = eventType;
com.android.internal.util.AnnotationValidations.validate(
EventCode.class, null, mEventType);
@@ -307,10 +274,6 @@
this.mVendorData = vendorData;
com.android.internal.util.AnnotationValidations.validate(
NonNull.class, null, mVendorData);
- this.mRatePerMinute = ratePerMinute;
- com.android.internal.util.AnnotationValidations.validate(
- IntRange.class, null, mRatePerMinute,
- "from", -1);
// onConstructed(); // You can define this method to get a callback
}
@@ -367,17 +330,6 @@
return mVendorData;
}
- /**
- * Rate per minute of the event during the start to end time.
- *
- * @return the rate per minute, or {@link #RATE_PER_MINUTE_UNKNOWN} if the rate is unknown.
- */
- @DataClass.Generated.Member
- @FlaggedApi(android.app.Flags.FLAG_AMBIENT_HEART_RATE)
- public @IntRange(from = -1) int getRatePerMinute() {
- return mRatePerMinute;
- }
-
@Override
@DataClass.Generated.Member
public String toString() {
@@ -390,8 +342,7 @@
"endTime = " + mEndTime + ", " +
"confidenceLevel = " + mConfidenceLevel + ", " +
"densityLevel = " + mDensityLevel + ", " +
- "vendorData = " + mVendorData + ", " +
- "ratePerMinute = " + mRatePerMinute +
+ "vendorData = " + mVendorData +
" }";
}
@@ -429,7 +380,6 @@
dest.writeInt(mConfidenceLevel);
dest.writeInt(mDensityLevel);
dest.writeTypedObject(mVendorData, flags);
- dest.writeInt(mRatePerMinute);
}
@Override
@@ -449,7 +399,6 @@
int confidenceLevel = in.readInt();
int densityLevel = in.readInt();
PersistableBundle vendorData = (PersistableBundle) in.readTypedObject(PersistableBundle.CREATOR);
- int ratePerMinute = in.readInt();
this.mEventType = eventType;
com.android.internal.util.AnnotationValidations.validate(
@@ -469,10 +418,6 @@
this.mVendorData = vendorData;
com.android.internal.util.AnnotationValidations.validate(
NonNull.class, null, mVendorData);
- this.mRatePerMinute = ratePerMinute;
- com.android.internal.util.AnnotationValidations.validate(
- IntRange.class, null, mRatePerMinute,
- "from", -1);
// onConstructed(); // You can define this method to get a callback
}
@@ -504,7 +449,6 @@
private @LevelValue int mConfidenceLevel;
private @LevelValue int mDensityLevel;
private @NonNull PersistableBundle mVendorData;
- private @IntRange(from = -1) int mRatePerMinute;
private long mBuilderFieldsSet = 0L;
@@ -581,22 +525,10 @@
return this;
}
- /**
- * Rate per minute of the event during the start to end time.
- */
- @DataClass.Generated.Member
- @FlaggedApi(android.app.Flags.FLAG_AMBIENT_HEART_RATE)
- public @NonNull Builder setRatePerMinute(@IntRange(from = -1) int value) {
- checkNotUsed();
- mBuilderFieldsSet |= 0x40;
- mRatePerMinute = value;
- return this;
- }
-
/** Builds the instance. This builder should not be touched after calling this! */
public @NonNull AmbientContextEvent build() {
checkNotUsed();
- mBuilderFieldsSet |= 0x80; // Mark builder used
+ mBuilderFieldsSet |= 0x40; // Mark builder used
if ((mBuilderFieldsSet & 0x1) == 0) {
mEventType = defaultEventType();
@@ -616,22 +548,18 @@
if ((mBuilderFieldsSet & 0x20) == 0) {
mVendorData = defaultVendorData();
}
- if ((mBuilderFieldsSet & 0x40) == 0) {
- mRatePerMinute = defaultRatePerMinute();
- }
AmbientContextEvent o = new AmbientContextEvent(
mEventType,
mStartTime,
mEndTime,
mConfidenceLevel,
mDensityLevel,
- mVendorData,
- mRatePerMinute);
+ mVendorData);
return o;
}
private void checkNotUsed() {
- if ((mBuilderFieldsSet & 0x80) != 0) {
+ if ((mBuilderFieldsSet & 0x40) != 0) {
throw new IllegalStateException(
"This Builder should not be reused. Use a new Builder instance instead");
}
@@ -639,10 +567,10 @@
}
@DataClass.Generated(
- time = 1705575046107L,
+ time = 1709014715064L,
codegenVersion = "1.0.23",
sourceFile = "frameworks/base/core/java/android/app/ambientcontext/AmbientContextEvent.java",
- inputSignatures = "public static final int EVENT_UNKNOWN\npublic static final int EVENT_COUGH\npublic static final int EVENT_SNORE\npublic static final int EVENT_BACK_DOUBLE_TAP\npublic static final @android.app.ambientcontext.AmbientContextEvent.Event @android.annotation.FlaggedApi int EVENT_HEART_RATE\npublic static final int EVENT_VENDOR_WEARABLE_START\npublic static final java.lang.String KEY_VENDOR_WEARABLE_EVENT_NAME\npublic static final @android.annotation.FlaggedApi int RATE_PER_MINUTE_UNKNOWN\npublic static final int LEVEL_UNKNOWN\npublic static final int LEVEL_LOW\npublic static final int LEVEL_MEDIUM_LOW\npublic static final int LEVEL_MEDIUM\npublic static final int LEVEL_MEDIUM_HIGH\npublic static final int LEVEL_HIGH\nprivate final @android.app.ambientcontext.AmbientContextEvent.EventCode int mEventType\nprivate final @com.android.internal.util.DataClass.ParcelWith(com.android.internal.util.Parcelling.BuiltIn.ForInstant.class) @android.annotation.NonNull java.time.Instant mStartTime\nprivate final @com.android.internal.util.DataClass.ParcelWith(com.android.internal.util.Parcelling.BuiltIn.ForInstant.class) @android.annotation.NonNull java.time.Instant mEndTime\nprivate final @android.app.ambientcontext.AmbientContextEvent.LevelValue int mConfidenceLevel\nprivate final @android.app.ambientcontext.AmbientContextEvent.LevelValue int mDensityLevel\nprivate final @android.annotation.NonNull android.os.PersistableBundle mVendorData\nprivate final @android.annotation.IntRange int mRatePerMinute\nprivate static int defaultEventType()\nprivate static @android.annotation.NonNull java.time.Instant defaultStartTime()\nprivate static @android.annotation.NonNull java.time.Instant defaultEndTime()\nprivate static int defaultConfidenceLevel()\nprivate static int defaultDensityLevel()\nprivate static android.os.PersistableBundle defaultVendorData()\nprivate static int defaultRatePerMinute()\nclass AmbientContextEvent extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genBuilder=true, genConstructor=false, genHiddenConstDefs=true, genParcelable=true, genToString=true)")
+ inputSignatures = "public static final int EVENT_UNKNOWN\npublic static final int EVENT_COUGH\npublic static final int EVENT_SNORE\npublic static final int EVENT_BACK_DOUBLE_TAP\npublic static final int EVENT_VENDOR_WEARABLE_START\npublic static final java.lang.String KEY_VENDOR_WEARABLE_EVENT_NAME\npublic static final int LEVEL_UNKNOWN\npublic static final int LEVEL_LOW\npublic static final int LEVEL_MEDIUM_LOW\npublic static final int LEVEL_MEDIUM\npublic static final int LEVEL_MEDIUM_HIGH\npublic static final int LEVEL_HIGH\nprivate final @android.app.ambientcontext.AmbientContextEvent.EventCode int mEventType\nprivate final @com.android.internal.util.DataClass.ParcelWith(com.android.internal.util.Parcelling.BuiltIn.ForInstant.class) @android.annotation.NonNull java.time.Instant mStartTime\nprivate final @com.android.internal.util.DataClass.ParcelWith(com.android.internal.util.Parcelling.BuiltIn.ForInstant.class) @android.annotation.NonNull java.time.Instant mEndTime\nprivate final @android.app.ambientcontext.AmbientContextEvent.LevelValue int mConfidenceLevel\nprivate final @android.app.ambientcontext.AmbientContextEvent.LevelValue int mDensityLevel\nprivate final @android.annotation.NonNull android.os.PersistableBundle mVendorData\nprivate static int defaultEventType()\nprivate static @android.annotation.NonNull java.time.Instant defaultStartTime()\nprivate static @android.annotation.NonNull java.time.Instant defaultEndTime()\nprivate static int defaultConfidenceLevel()\nprivate static int defaultDensityLevel()\nprivate static android.os.PersistableBundle defaultVendorData()\nclass AmbientContextEvent extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genBuilder=true, genConstructor=false, genHiddenConstDefs=true, genParcelable=true, genToString=true)")
@Deprecated
private void __metadata() {}
diff --git a/core/java/android/app/servertransaction/ActivityConfigurationChangeItem.java b/core/java/android/app/servertransaction/ActivityConfigurationChangeItem.java
index bc8fac5..48ea846 100644
--- a/core/java/android/app/servertransaction/ActivityConfigurationChangeItem.java
+++ b/core/java/android/app/servertransaction/ActivityConfigurationChangeItem.java
@@ -29,6 +29,7 @@
import android.os.IBinder;
import android.os.Parcel;
import android.os.Trace;
+import android.window.ActivityWindowInfo;
import java.util.Objects;
@@ -49,11 +50,13 @@
}
@Override
- public void execute(@NonNull ClientTransactionHandler client, @Nullable ActivityClientRecord r,
+ public void execute(@NonNull ClientTransactionHandler client, @NonNull ActivityClientRecord r,
@NonNull PendingTransactionActions pendingActions) {
// TODO(lifecycler): detect if PIP or multi-window mode changed and report it here.
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityConfigChanged");
- client.handleActivityConfigurationChanged(r, mConfiguration, INVALID_DISPLAY);
+ client.handleActivityConfigurationChanged(r, mConfiguration, INVALID_DISPLAY,
+ // TODO(b/287582673): add ActivityWindowInfo
+ new ActivityWindowInfo());
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
diff --git a/core/java/android/app/servertransaction/MoveToDisplayItem.java b/core/java/android/app/servertransaction/MoveToDisplayItem.java
index 1353d16..0702c45 100644
--- a/core/java/android/app/servertransaction/MoveToDisplayItem.java
+++ b/core/java/android/app/servertransaction/MoveToDisplayItem.java
@@ -28,6 +28,7 @@
import android.os.IBinder;
import android.os.Parcel;
import android.os.Trace;
+import android.window.ActivityWindowInfo;
import java.util.Objects;
@@ -39,6 +40,7 @@
private int mTargetDisplayId;
private Configuration mConfiguration;
+ private ActivityWindowInfo mActivityWindowInfo;
@Override
public void preExecute(@NonNull ClientTransactionHandler client) {
@@ -52,7 +54,8 @@
public void execute(@NonNull ClientTransactionHandler client, @NonNull ActivityClientRecord r,
@NonNull PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityMovedToDisplay");
- client.handleActivityConfigurationChanged(r, mConfiguration, mTargetDisplayId);
+ client.handleActivityConfigurationChanged(r, mConfiguration, mTargetDisplayId,
+ mActivityWindowInfo);
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
@@ -69,7 +72,7 @@
/** Obtain an instance initialized with provided params. */
@NonNull
public static MoveToDisplayItem obtain(@NonNull IBinder activityToken, int targetDisplayId,
- @NonNull Configuration configuration) {
+ @NonNull Configuration configuration, @NonNull ActivityWindowInfo activityWindowInfo) {
MoveToDisplayItem instance = ObjectPool.obtain(MoveToDisplayItem.class);
if (instance == null) {
instance = new MoveToDisplayItem();
@@ -77,6 +80,7 @@
instance.setActivityToken(activityToken);
instance.mTargetDisplayId = targetDisplayId;
instance.mConfiguration = new Configuration(configuration);
+ instance.mActivityWindowInfo = new ActivityWindowInfo(activityWindowInfo);
return instance;
}
@@ -86,6 +90,7 @@
super.recycle();
mTargetDisplayId = 0;
mConfiguration = null;
+ mActivityWindowInfo = null;
ObjectPool.recycle(this);
}
@@ -97,6 +102,7 @@
super.writeToParcel(dest, flags);
dest.writeInt(mTargetDisplayId);
dest.writeTypedObject(mConfiguration, flags);
+ dest.writeTypedObject(mActivityWindowInfo, flags);
}
/** Read from Parcel. */
@@ -104,6 +110,7 @@
super(in);
mTargetDisplayId = in.readInt();
mConfiguration = in.readTypedObject(Configuration.CREATOR);
+ mActivityWindowInfo = in.readTypedObject(ActivityWindowInfo.CREATOR);
}
public static final @NonNull Creator<MoveToDisplayItem> CREATOR = new Creator<>() {
@@ -126,7 +133,8 @@
}
final MoveToDisplayItem other = (MoveToDisplayItem) o;
return mTargetDisplayId == other.mTargetDisplayId
- && Objects.equals(mConfiguration, other.mConfiguration);
+ && Objects.equals(mConfiguration, other.mConfiguration)
+ && Objects.equals(mActivityWindowInfo, other.mActivityWindowInfo);
}
@Override
@@ -135,6 +143,7 @@
result = 31 * result + super.hashCode();
result = 31 * result + mTargetDisplayId;
result = 31 * result + mConfiguration.hashCode();
+ result = 31 * result + Objects.hashCode(mActivityWindowInfo);
return result;
}
@@ -142,6 +151,7 @@
public String toString() {
return "MoveToDisplayItem{" + super.toString()
+ ",targetDisplayId=" + mTargetDisplayId
- + ",configuration=" + mConfiguration + "}";
+ + ",configuration=" + mConfiguration
+ + ",activityWindowInfo=" + mActivityWindowInfo + "}";
}
}
diff --git a/core/java/android/content/ClipData.java b/core/java/android/content/ClipData.java
index 728c350..b421339 100644
--- a/core/java/android/content/ClipData.java
+++ b/core/java/android/content/ClipData.java
@@ -169,6 +169,8 @@
*/
@android.ravenwood.annotation.RavenwoodKeepWholeClass
public class ClipData implements Parcelable {
+ private static final String TAG = "ClipData";
+
static final String[] MIMETYPES_TEXT_PLAIN = new String[] {
ClipDescription.MIMETYPE_TEXT_PLAIN };
static final String[] MIMETYPES_TEXT_HTML = new String[] {
@@ -476,7 +478,6 @@
* @return Returns the item's textual representation.
*/
//BEGIN_INCLUDE(coerceToText)
- @android.ravenwood.annotation.RavenwoodThrow
public CharSequence coerceToText(Context context) {
// If this Item has an explicit textual value, simply return that.
CharSequence text = getText();
@@ -484,13 +485,20 @@
return text;
}
+ // Gracefully handle cases where resolver isn't available
+ ContentResolver resolver = null;
+ try {
+ resolver = context.getContentResolver();
+ } catch (Exception e) {
+ Log.w(TAG, "Failed to obtain ContentResolver: " + e);
+ }
+
// If this Item has a URI value, try using that.
Uri uri = getUri();
- if (uri != null) {
+ if (uri != null && resolver != null) {
// First see if the URI can be opened as a plain text stream
// (of any sub-type). If so, this is the best textual
// representation for it.
- final ContentResolver resolver = context.getContentResolver();
AssetFileDescriptor descr = null;
FileInputStream stream = null;
InputStreamReader reader = null;
@@ -499,7 +507,7 @@
// Ask for a stream of the desired type.
descr = resolver.openTypedAssetFileDescriptor(uri, "text/*", null);
} catch (SecurityException e) {
- Log.w("ClipData", "Failure opening stream", e);
+ Log.w(TAG, "Failure opening stream", e);
} catch (FileNotFoundException|RuntimeException e) {
// Unable to open content URI as text... not really an
// error, just something to ignore.
@@ -519,7 +527,7 @@
return builder.toString();
} catch (IOException e) {
// Something bad has happened.
- Log.w("ClipData", "Failure loading text", e);
+ Log.w(TAG, "Failure loading text", e);
return e.toString();
}
}
@@ -528,7 +536,8 @@
IoUtils.closeQuietly(stream);
IoUtils.closeQuietly(reader);
}
-
+ }
+ if (uri != null) {
// If we couldn't open the URI as a stream, use the URI itself as a textual
// representation (but not for "content", "android.resource" or "file" schemes).
final String scheme = uri.getScheme();
@@ -704,7 +713,7 @@
}
} catch (SecurityException e) {
- Log.w("ClipData", "Failure opening stream", e);
+ Log.w(TAG, "Failure opening stream", e);
} catch (FileNotFoundException e) {
// Unable to open content URI as text... not really an
@@ -712,7 +721,7 @@
} catch (IOException e) {
// Something bad has happened.
- Log.w("ClipData", "Failure loading text", e);
+ Log.w(TAG, "Failure loading text", e);
return Html.escapeHtml(e.toString());
} finally {
@@ -1123,7 +1132,7 @@
*
* @hide
*/
- @android.ravenwood.annotation.RavenwoodThrow
+ @android.ravenwood.annotation.RavenwoodKeep
public void prepareToLeaveProcess(boolean leavingPackage) {
// Assume that callers are going to be granting permissions
prepareToLeaveProcess(leavingPackage, Intent.FLAG_GRANT_READ_URI_PERMISSION);
@@ -1134,7 +1143,7 @@
*
* @hide
*/
- @android.ravenwood.annotation.RavenwoodThrow
+ @android.ravenwood.annotation.RavenwoodReplace
public void prepareToLeaveProcess(boolean leavingPackage, int intentFlags) {
final int size = mItems.size();
for (int i = 0; i < size; i++) {
@@ -1154,6 +1163,11 @@
}
}
+ /** @hide */
+ public void prepareToLeaveProcess$ravenwood(boolean leavingPackage, int intentFlags) {
+ // No process boundaries on Ravenwood; ignored
+ }
+
/** {@hide} */
@android.ravenwood.annotation.RavenwoodThrow
public void prepareToEnterProcess(AttributionSource source) {
diff --git a/core/java/android/content/ClipboardManager.java b/core/java/android/content/ClipboardManager.java
index 107f107..2fabcba 100644
--- a/core/java/android/content/ClipboardManager.java
+++ b/core/java/android/content/ClipboardManager.java
@@ -50,6 +50,7 @@
* </div>
*/
@SystemService(Context.CLIPBOARD_SERVICE)
+@android.ravenwood.annotation.RavenwoodKeepWholeClass
public class ClipboardManager extends android.text.ClipboardManager {
/**
@@ -143,6 +144,7 @@
*/
@SystemApi
@RequiresPermission(Manifest.permission.MANAGE_CLIPBOARD_ACCESS_NOTIFICATION)
+ @android.ravenwood.annotation.RavenwoodThrow
public boolean areClipboardAccessNotificationsEnabled() {
try {
return mService.areClipboardAccessNotificationsEnabledForUser(mContext.getUserId());
@@ -159,6 +161,7 @@
*/
@SystemApi
@RequiresPermission(Manifest.permission.MANAGE_CLIPBOARD_ACCESS_NOTIFICATION)
+ @android.ravenwood.annotation.RavenwoodThrow
public void setClipboardAccessNotificationsEnabled(boolean enable) {
try {
mService.setClipboardAccessNotificationsEnabledForUser(enable, mContext.getUserId());
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index f77ebc1..70d2c7a 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -83,6 +83,7 @@
import android.os.UserHandle;
import android.os.UserManager;
import android.os.storage.StorageManager;
+import android.provider.E2eeContactKeysManager;
import android.provider.MediaStore;
import android.telephony.TelephonyRegistryManager;
import android.util.AttributeSet;
@@ -4815,9 +4816,7 @@
* @see android.net.thread.ThreadNetworkManager
* @hide
*/
- // TODO (b/325886480): update the flag to
- // "com.android.net.thread.platform.flags.Flags.FLAG_THREAD_ENABLED_PLATFORM"
- @FlaggedApi("com.android.net.thread.flags.thread_enabled_platform")
+ @FlaggedApi(com.android.net.thread.platform.flags.Flags.FLAG_THREAD_ENABLED_PLATFORM)
@SystemApi
public static final String THREAD_NETWORK_SERVICE = "thread_network";
@@ -6566,10 +6565,10 @@
/**
* Use with {@link #getSystemService(String)} to retrieve a
- * {@link android.provider.ContactKeysManager} to managing contact keys.
+ * {@link E2eeContactKeysManager} to managing contact keys.
*
* @see #getSystemService(String)
- * @see android.provider.ContactKeysManager
+ * @see E2eeContactKeysManager
*/
@FlaggedApi(android.provider.Flags.FLAG_USER_KEYS)
public static final String CONTACT_KEYS_SERVICE = "contact_keys";
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index 7a015cd..240cff3 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -3974,9 +3974,7 @@
* The device is capable of communicating with other devices via
* <a href="https://www.threadgroup.org">Thread</a> networking protocol.
*/
- // TODO (b/325886480): update the flag to
- // "com.android.net.thread.platform.flags.Flags.FLAG_THREAD_ENABLED_PLATFORM"
- @FlaggedApi("com.android.net.thread.flags.thread_enabled_platform")
+ @FlaggedApi(com.android.net.thread.platform.flags.Flags.FLAG_THREAD_ENABLED_PLATFORM)
@SdkConstant(SdkConstantType.FEATURE)
public static final String FEATURE_THREAD_NETWORK = "android.hardware.thread_network";
diff --git a/core/java/android/content/pm/ServiceInfo.java b/core/java/android/content/pm/ServiceInfo.java
index 9c6aab4..5b0cee7 100644
--- a/core/java/android/content/pm/ServiceInfo.java
+++ b/core/java/android/content/pm/ServiceInfo.java
@@ -163,25 +163,12 @@
* Because of this, developers must make sure to stop the foreground service even if
* {@link android.app.Service#onTimeout(int, int)} is not called on such versions.
*
- * <p>Apps targeting API level {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM} and
- * later should <b>NOT</b> use this type: calling
- * {@link android.app.Service#startForeground(int, android.app.Notification, int)} with
- * this type on devices running {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM} is
- * still allowed, but it may throw an {@link android.app.InvalidForegroundServiceTypeException}
- * in future platform releases.
- *
- * <p class="note">
- * Use the {@link android.app.job.JobInfo.Builder#setUserInitiated(boolean)} API for
- * user-initiated, network data transfers.
- *
- * @deprecated Use {@link android.app.job.JobInfo.Builder} APIs or alternate FGS types
- * (like {@link #FOREGROUND_SERVICE_TYPE_MEDIA_PROCESSING}) applicable to your use-case.
+ * @see android.app.Service#onTimeout(int, int)
*/
@RequiresPermission(
value = Manifest.permission.FOREGROUND_SERVICE_DATA_SYNC,
conditional = true
)
- @Deprecated
public static final int FOREGROUND_SERVICE_TYPE_DATA_SYNC = 1 << 0;
/**
diff --git a/core/java/android/credentials/GetCandidateCredentialsResponse.java b/core/java/android/credentials/GetCandidateCredentialsResponse.java
index 6e53fd9..3d8ccaa 100644
--- a/core/java/android/credentials/GetCandidateCredentialsResponse.java
+++ b/core/java/android/credentials/GetCandidateCredentialsResponse.java
@@ -18,7 +18,7 @@
import android.annotation.Hide;
import android.annotation.NonNull;
-import android.app.PendingIntent;
+import android.content.Intent;
import android.credentials.selection.GetCredentialProviderData;
import android.os.Parcel;
import android.os.Parcelable;
@@ -39,32 +39,22 @@
@NonNull
private final List<GetCredentialProviderData> mCandidateProviderDataList;
- private final PendingIntent mPendingIntent;
+ @NonNull
+ private final Intent mIntent;
/**
* @hide
*/
@Hide
public GetCandidateCredentialsResponse(
- GetCredentialResponse getCredentialResponse
- ) {
- mCandidateProviderDataList = null;
- mPendingIntent = null;
- }
-
- /**
- * @hide
- */
- @Hide
- public GetCandidateCredentialsResponse(
- List<GetCredentialProviderData> candidateProviderDataList,
- PendingIntent pendingIntent
+ @NonNull List<GetCredentialProviderData> candidateProviderDataList,
+ @NonNull Intent intent
) {
Preconditions.checkCollectionNotEmpty(
candidateProviderDataList,
/*valueName=*/ "candidateProviderDataList");
mCandidateProviderDataList = new ArrayList<>(candidateProviderDataList);
- mPendingIntent = pendingIntent;
+ mIntent = intent;
}
/**
@@ -81,8 +71,9 @@
*
* @hide
*/
- public PendingIntent getPendingIntent() {
- return mPendingIntent;
+ @NonNull
+ public Intent getIntent() {
+ return mIntent;
}
protected GetCandidateCredentialsResponse(Parcel in) {
@@ -91,14 +82,13 @@
mCandidateProviderDataList = candidateProviderDataList;
AnnotationValidations.validate(NonNull.class, null, mCandidateProviderDataList);
-
- mPendingIntent = in.readTypedObject(PendingIntent.CREATOR);
+ mIntent = in.readTypedObject(Intent.CREATOR);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedList(mCandidateProviderDataList);
- dest.writeTypedObject(mPendingIntent, flags);
+ dest.writeTypedObject(mIntent, flags);
}
@Override
diff --git a/core/java/android/inputmethodservice/navigationbar/NavigationBarView.java b/core/java/android/inputmethodservice/navigationbar/NavigationBarView.java
index 510b14e..e28f345 100644
--- a/core/java/android/inputmethodservice/navigationbar/NavigationBarView.java
+++ b/core/java/android/inputmethodservice/navigationbar/NavigationBarView.java
@@ -99,7 +99,11 @@
mDeadZone = new android.inputmethodservice.navigationbar.DeadZone(this);
- getImeSwitchButton().setOnClickListener(view -> view.getContext()
+ getBackButton().setLongClickable(false);
+
+ final ButtonDispatcher imeSwitchButton = getImeSwitchButton();
+ imeSwitchButton.setLongClickable(false);
+ imeSwitchButton.setOnClickListener(view -> view.getContext()
.getSystemService(InputMethodManager.class).showInputMethodPicker());
}
diff --git a/core/java/android/os/HandlerThread.java b/core/java/android/os/HandlerThread.java
index 36730cb..f852d3c 100644
--- a/core/java/android/os/HandlerThread.java
+++ b/core/java/android/os/HandlerThread.java
@@ -19,6 +19,8 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
+import java.util.concurrent.Executor;
+
/**
* A {@link Thread} that has a {@link Looper}.
* The {@link Looper} can then be used to create {@link Handler}s.
@@ -30,7 +32,8 @@
int mPriority;
int mTid = -1;
Looper mLooper;
- private @Nullable Handler mHandler;
+ private volatile @Nullable Handler mHandler;
+ private volatile @Nullable Executor mExecutor;
public HandlerThread(String name) {
super(name);
@@ -131,6 +134,18 @@
}
/**
+ * @return a shared {@link Executor} associated with this thread
+ * @hide
+ */
+ @NonNull
+ public Executor getThreadExecutor() {
+ if (mExecutor == null) {
+ mExecutor = new HandlerExecutor(getThreadHandler());
+ }
+ return mExecutor;
+ }
+
+ /**
* Quits the handler thread's looper.
* <p>
* Causes the handler thread's looper to terminate without processing any
diff --git a/core/java/android/os/UserManager.java b/core/java/android/os/UserManager.java
index be17d7c..ccb534e 100644
--- a/core/java/android/os/UserManager.java
+++ b/core/java/android/os/UserManager.java
@@ -1920,9 +1920,7 @@
* @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
* @see #getUserRestrictions()
*/
- // TODO (b/325886480): update the flag to
- // "com.android.net.thread.platform.flags.Flags.FLAG_THREAD_USER_RESTRICTION_ENABLED"
- @FlaggedApi("com.android.net.thread.flags.thread_user_restriction_enabled")
+ @FlaggedApi(com.android.net.thread.platform.flags.Flags.FLAG_THREAD_USER_RESTRICTION_ENABLED)
public static final String DISALLOW_THREAD_NETWORK = "no_thread_network";
/**
diff --git a/core/java/android/os/storage/OWNERS b/core/java/android/os/storage/OWNERS
index 2cb16d337b..c21895a 100644
--- a/core/java/android/os/storage/OWNERS
+++ b/core/java/android/os/storage/OWNERS
@@ -3,11 +3,15 @@
# PLEASE ASSIGN NEW BUGS TO android-storage-triage@, NOT TO INDIVIDUAL PEOPLE
# Android Storage Team
+aibra@google.com
+akgaurav@google.com
alukin@google.com
ankitavyas@google.com
dipankarb@google.com
gargshivam@google.com
+ishneet@google.com
krishang@google.com
+oeissa@google.com
riyaghai@google.com
sahanas@google.com
shikhamalhotra@google.com
diff --git a/core/java/android/permission/PermissionUsageHelper.java b/core/java/android/permission/PermissionUsageHelper.java
index 460b4dd..141ffc9 100644
--- a/core/java/android/permission/PermissionUsageHelper.java
+++ b/core/java/android/permission/PermissionUsageHelper.java
@@ -359,8 +359,7 @@
new PermissionGroupUsage(usage.packageName, usage.uid, usage.lastAccessTime,
permGroup,
usage.isRunning, isPhone, usage.attributionTag, attributionLabel,
- usagesWithLabels.valueAt(usageNum),
- VirtualDeviceManager.PERSISTENT_DEVICE_ID_DEFAULT));
+ usagesWithLabels.valueAt(usageNum), deviceId));
}
}
diff --git a/core/java/android/provider/ContactKeysManager.java b/core/java/android/provider/E2eeContactKeysManager.java
similarity index 70%
rename from core/java/android/provider/ContactKeysManager.java
rename to core/java/android/provider/E2eeContactKeysManager.java
index 01aaa3d..b694417 100644
--- a/core/java/android/provider/ContactKeysManager.java
+++ b/core/java/android/provider/E2eeContactKeysManager.java
@@ -39,18 +39,18 @@
import java.util.Objects;
/**
- * ContactKeysManager provides access to the provider of end-to-end encryption contact keys.
- * It manages two types of keys - {@link ContactKey} and {@link SelfKey}.
+ * E2eeContactKeysManager provides access to the provider of end-to-end encryption contact keys.
+ * It manages two types of keys - {@link E2eeContactKey} and {@link E2eeSelfKey}.
* <ul>
* <li>
- * A {@link ContactKey} is a public key associated with a contact. It's used to end-to-end
+ * A {@link E2eeContactKey} is a public key associated with a contact. It's used to end-to-end
* encrypt the communications between a user and the contact. This API allows operations on
- * {@link ContactKey}s to insert/update, remove, change the verification state, and retrieving
+ * {@link E2eeContactKey}s to insert/update, remove, change the verification state, and retrieving
* keys (either created by or visible to the caller app).
* </li>
* <li>
- * A {@link SelfKey} is a key for this device, so the key represents the owner of the device.
- * This API allows operations on {@link SelfKey}s to insert/update, remove, and retrieving
+ * A {@link E2eeSelfKey} is a key for this device, so the key represents the owner of the device.
+ * This API allows operations on {@link E2eeSelfKey}s to insert/update, remove, and retrieving
* self keys (either created by or visible to the caller app).
* </li>
* </ul>
@@ -65,29 +65,30 @@
* </li>
* <li>
* accountId - the app-specified identifier for the account for which the contact key can be used.
- * Usually a phone number.
+ * Using different account IDs allows for multiple key entries representing the same user.
+ * For most apps this would be a phone number.
* </li>
* </ul>
* Contact keys also use lookupKey which is an opaque value used to identify a contact in
* ContactsProvider.
*/
@FlaggedApi(Flags.FLAG_USER_KEYS)
-public final class ContactKeysManager {
+public final class E2eeContactKeysManager {
/**
- * The authority for the contact keys provider.
+ * The authority for the end-to-end encryption contact keys provider.
* @hide
*/
public static final String AUTHORITY = "com.android.contactkeys.contactkeysprovider";
/**
- * A content:// style uri to the authority for the contact keys provider.
+ * A content:// style uri to the authority for the end-to-end encryption contact keys provider.
* @hide
*/
@NonNull
public static final Uri AUTHORITY_URI = Uri.parse("content://" + AUTHORITY);
/**
- * Maximum size of a contact key.
+ * Maximum size of an end-to-end encryption contact key.
*/
private static final int MAX_KEY_SIZE_BYTES = 5000;
@@ -100,14 +101,15 @@
private final ContentResolver mContentResolver;
/** @hide */
- public ContactKeysManager(@NonNull Context context) {
+ public E2eeContactKeysManager(@NonNull Context context) {
Objects.requireNonNull(context);
mContentResolver = context.getContentResolver();
}
/**
- * Inserts a new entry into the contact keys table or updates one if it already exists.
- * The inserted/updated contact key is owned by the caller app.
+ * Inserts a new entry into the end-to-end encryption contact keys table or updates one if it
+ * already exists.
+ * The inserted/updated end-to-end encryption contact key is owned by the caller app.
*
* @param lookupKey value that references the contact
* @param deviceId an app-specified identifier for the device
@@ -115,76 +117,77 @@
* @param keyValue the raw bytes for the key (max size is {@link #getMaxKeySizeBytes} bytes)
*/
@RequiresPermission(android.Manifest.permission.WRITE_CONTACTS)
- public void updateOrInsertContactKey(@NonNull String lookupKey,
+ public void updateOrInsertE2eeContactKey(@NonNull String lookupKey,
@NonNull String deviceId,
@NonNull String accountId,
@NonNull byte[] keyValue) {
validateKeyLength(keyValue);
Bundle extras = new Bundle();
- extras.putString(ContactKeys.LOOKUP_KEY, Objects.requireNonNull(lookupKey));
- extras.putString(ContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
- extras.putString(ContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
- extras.putByteArray(ContactKeys.KEY_VALUE, Objects.requireNonNull(keyValue));
+ extras.putString(E2eeContactKeys.LOOKUP_KEY, Objects.requireNonNull(lookupKey));
+ extras.putString(E2eeContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
+ extras.putString(E2eeContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
+ extras.putByteArray(E2eeContactKeys.KEY_VALUE, Objects.requireNonNull(keyValue));
nullSafeCall(mContentResolver,
- ContactKeys.UPDATE_OR_INSERT_CONTACT_KEY_METHOD, extras);
+ E2eeContactKeys.UPDATE_OR_INSERT_CONTACT_KEY_METHOD, extras);
}
/**
- * Retrieves a contact key entry given the lookup key, device ID, accountId and inferred
- * caller package name.
+ * Retrieves an end-to-end encryption contact key entry given the lookup key, device ID,
+ * accountId and inferred caller package name.
*
* @param lookupKey the value that references the contact
* @param deviceId an app-specified identifier for the device
* @param accountId an app-specified identifier for the account
*
- * @return a {@link ContactKey} object containing the contact key information,
+ * @return a {@link E2eeContactKey} object containing the contact key information,
* or null if no contact key is found.
*/
@RequiresPermission(android.Manifest.permission.READ_CONTACTS)
@Nullable
- public ContactKey getContactKey(
+ public E2eeContactKey getE2eeContactKey(
@NonNull String lookupKey,
@NonNull String deviceId,
@NonNull String accountId) {
Bundle extras = new Bundle();
- extras.putString(ContactKeys.LOOKUP_KEY, Objects.requireNonNull(lookupKey));
- extras.putString(ContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
- extras.putString(ContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
+ extras.putString(E2eeContactKeys.LOOKUP_KEY, Objects.requireNonNull(lookupKey));
+ extras.putString(E2eeContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
+ extras.putString(E2eeContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
Bundle response = nullSafeCall(mContentResolver,
- ContactKeys.GET_CONTACT_KEY_METHOD, extras);
+ E2eeContactKeys.GET_CONTACT_KEY_METHOD, extras);
if (response == null) {
return null;
}
- return response.getParcelable(ContactKeys.KEY_CONTACT_KEY, ContactKey.class);
+ return response.getParcelable(E2eeContactKeys.KEY_CONTACT_KEY, E2eeContactKey.class);
}
/**
- * Retrieves all contact key entries that belong to apps visible to the caller.
+ * Retrieves all end-to-end encryption contact key entries that belong to apps visible to
+ * the caller.
* The keys will be stripped of deviceId, timeUpdated and keyValue data.
*
* @param lookupKey the value that references the contact
*
- * @return a list of {@link ContactKey} objects containing the contact key
+ * @return a list of {@link E2eeContactKey} objects containing the contact key
* information, or an empty list if no keys are found.
*/
@RequiresPermission(android.Manifest.permission.READ_CONTACTS)
@NonNull
- public List<ContactKey> getAllContactKeys(@NonNull String lookupKey) {
+ public List<E2eeContactKey> getAllE2eeContactKeys(@NonNull String lookupKey) {
Bundle extras = new Bundle();
- extras.putString(ContactKeys.LOOKUP_KEY, Objects.requireNonNull(lookupKey));
+ extras.putString(E2eeContactKeys.LOOKUP_KEY, Objects.requireNonNull(lookupKey));
Bundle response = nullSafeCall(mContentResolver,
- ContactKeys.GET_ALL_CONTACT_KEYS_METHOD, extras);
+ E2eeContactKeys.GET_ALL_CONTACT_KEYS_METHOD, extras);
if (response == null) {
return new ArrayList<>();
}
- List<ContactKey> value = response.getParcelableArrayList(ContactKeys.KEY_CONTACT_KEYS,
- ContactKey.class);
+ List<E2eeContactKey> value = response.getParcelableArrayList(
+ E2eeContactKeys.KEY_CONTACT_KEYS, E2eeContactKey.class);
if (value == null) {
return new ArrayList<>();
}
@@ -192,27 +195,28 @@
}
/**
- * Retrieves all contact key entries for a given lookupKey that belong to the caller app.
+ * Retrieves all end-to-end encryption contact key entries for a given lookupKey that belong to
+ * the caller app.
*
* @param lookupKey the value that references the contact
*
- * @return a list of {@link ContactKey} objects containing the contact key
- * information, or an empty list if no keys are found.
+ * @return a list of {@link E2eeContactKey} objects containing the end-to-end encryption
+ * contact key information, or an empty list if no keys are found.
*/
@RequiresPermission(android.Manifest.permission.READ_CONTACTS)
@NonNull
- public List<ContactKey> getOwnerContactKeys(@NonNull String lookupKey) {
+ public List<E2eeContactKey> getOwnerE2eeContactKeys(@NonNull String lookupKey) {
Bundle extras = new Bundle();
- extras.putString(ContactKeys.LOOKUP_KEY, Objects.requireNonNull(lookupKey));
+ extras.putString(E2eeContactKeys.LOOKUP_KEY, Objects.requireNonNull(lookupKey));
Bundle response = nullSafeCall(mContentResolver,
- ContactKeys.GET_OWNER_CONTACT_KEYS_METHOD, extras);
+ E2eeContactKeys.GET_OWNER_CONTACT_KEYS_METHOD, extras);
if (response == null) {
return new ArrayList<>();
}
- List<ContactKey> value = response.getParcelableArrayList(ContactKeys.KEY_CONTACT_KEYS,
- ContactKey.class);
+ List<E2eeContactKey> value = response.getParcelableArrayList(
+ E2eeContactKeys.KEY_CONTACT_KEYS, E2eeContactKey.class);
if (value == null) {
return new ArrayList<>();
}
@@ -220,7 +224,8 @@
}
/**
- * Updates a contact key entry's local verification state that belongs to the caller app.
+ * Updates an end-to-end encryption contact key entry's local verification state that belongs
+ * to the caller app.
*
* @param lookupKey the value that references the contact
* @param deviceId an app-specified identifier for the device
@@ -230,27 +235,27 @@
* @return true if the entry was updated, false otherwise.
*/
@RequiresPermission(android.Manifest.permission.WRITE_CONTACTS)
- public boolean updateContactKeyLocalVerificationState(@NonNull String lookupKey,
+ public boolean updateE2eeContactKeyLocalVerificationState(@NonNull String lookupKey,
@NonNull String deviceId,
@NonNull String accountId,
@VerificationState int localVerificationState) {
validateVerificationState(localVerificationState);
Bundle extras = new Bundle();
- extras.putString(ContactKeys.LOOKUP_KEY, Objects.requireNonNull(lookupKey));
- extras.putString(ContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
- extras.putString(ContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
- extras.putInt(ContactKeys.LOCAL_VERIFICATION_STATE, localVerificationState);
+ extras.putString(E2eeContactKeys.LOOKUP_KEY, Objects.requireNonNull(lookupKey));
+ extras.putString(E2eeContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
+ extras.putString(E2eeContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
+ extras.putInt(E2eeContactKeys.LOCAL_VERIFICATION_STATE, localVerificationState);
Bundle response = nullSafeCall(mContentResolver,
- ContactKeys.UPDATE_CONTACT_KEY_LOCAL_VERIFICATION_STATE_METHOD, extras);
+ E2eeContactKeys.UPDATE_CONTACT_KEY_LOCAL_VERIFICATION_STATE_METHOD, extras);
- return response != null && response.getBoolean(ContactKeys.KEY_UPDATED_ROWS);
+ return response != null && response.getBoolean(E2eeContactKeys.KEY_UPDATED_ROWS);
}
/**
- * Updates a contact key entry's local verification state that belongs to the app identified
- * by ownerPackageName.
+ * Updates an end-to-end encryption contact key entry's local verification state that belongs
+ * to the app identified by ownerPackageName.
*
* @param lookupKey the value that references the contact
* @param deviceId an app-specified identifier for the device
@@ -266,7 +271,7 @@
@RequiresPermission(allOf = {
android.Manifest.permission.WRITE_VERIFICATION_STATE_E2EE_CONTACT_KEYS,
android.Manifest.permission.WRITE_CONTACTS})
- public boolean updateContactKeyLocalVerificationState(@NonNull String lookupKey,
+ public boolean updateE2eeContactKeyLocalVerificationState(@NonNull String lookupKey,
@NonNull String deviceId,
@NonNull String accountId,
@NonNull String ownerPackageName,
@@ -274,20 +279,22 @@
validateVerificationState(localVerificationState);
final Bundle extras = new Bundle();
- extras.putString(ContactKeys.LOOKUP_KEY, Objects.requireNonNull(lookupKey));
- extras.putString(ContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
- extras.putString(ContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
- extras.putString(ContactKeys.OWNER_PACKAGE_NAME, Objects.requireNonNull(ownerPackageName));
- extras.putInt(ContactKeys.LOCAL_VERIFICATION_STATE, localVerificationState);
+ extras.putString(E2eeContactKeys.LOOKUP_KEY, Objects.requireNonNull(lookupKey));
+ extras.putString(E2eeContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
+ extras.putString(E2eeContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
+ extras.putString(E2eeContactKeys.OWNER_PACKAGE_NAME,
+ Objects.requireNonNull(ownerPackageName));
+ extras.putInt(E2eeContactKeys.LOCAL_VERIFICATION_STATE, localVerificationState);
final Bundle response = nullSafeCall(mContentResolver,
- ContactKeys.UPDATE_CONTACT_KEY_LOCAL_VERIFICATION_STATE_METHOD, extras);
+ E2eeContactKeys.UPDATE_CONTACT_KEY_LOCAL_VERIFICATION_STATE_METHOD, extras);
- return response != null && response.getBoolean(ContactKeys.KEY_UPDATED_ROWS);
+ return response != null && response.getBoolean(E2eeContactKeys.KEY_UPDATED_ROWS);
}
/**
- * Updates a contact key entry's remote verification state that belongs to the caller app.
+ * Updates an end-to-end encryption contact key entry's remote verification state that belongs
+ * to the caller app.
*
* @param lookupKey the value that references the contact
* @param deviceId an app-specified identifier for the device
@@ -297,27 +304,27 @@
* @return true if the entry was updated, false otherwise.
*/
@RequiresPermission(android.Manifest.permission.WRITE_CONTACTS)
- public boolean updateContactKeyRemoteVerificationState(@NonNull String lookupKey,
+ public boolean updateE2eeContactKeyRemoteVerificationState(@NonNull String lookupKey,
@NonNull String deviceId,
@NonNull String accountId,
@VerificationState int remoteVerificationState) {
validateVerificationState(remoteVerificationState);
Bundle extras = new Bundle();
- extras.putString(ContactKeys.LOOKUP_KEY, Objects.requireNonNull(lookupKey));
- extras.putString(ContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
- extras.putString(ContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
- extras.putInt(ContactKeys.REMOTE_VERIFICATION_STATE, remoteVerificationState);
+ extras.putString(E2eeContactKeys.LOOKUP_KEY, Objects.requireNonNull(lookupKey));
+ extras.putString(E2eeContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
+ extras.putString(E2eeContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
+ extras.putInt(E2eeContactKeys.REMOTE_VERIFICATION_STATE, remoteVerificationState);
Bundle response = nullSafeCall(mContentResolver,
- ContactKeys.UPDATE_CONTACT_KEY_REMOTE_VERIFICATION_STATE_METHOD, extras);
+ E2eeContactKeys.UPDATE_CONTACT_KEY_REMOTE_VERIFICATION_STATE_METHOD, extras);
- return response != null && response.getBoolean(ContactKeys.KEY_UPDATED_ROWS);
+ return response != null && response.getBoolean(E2eeContactKeys.KEY_UPDATED_ROWS);
}
/**
- * Updates a contact key entry's remote verification state that belongs to the app identified
- * by ownerPackageName.
+ * Updates an end-to-end encryption contact key entry's remote verification state that belongs
+ * to the app identified by ownerPackageName.
*
* @param lookupKey the value that references the contact
* @param deviceId an app-specified identifier for the device
@@ -333,7 +340,7 @@
@RequiresPermission(allOf = {
android.Manifest.permission.WRITE_VERIFICATION_STATE_E2EE_CONTACT_KEYS,
android.Manifest.permission.WRITE_CONTACTS})
- public boolean updateContactKeyRemoteVerificationState(@NonNull String lookupKey,
+ public boolean updateE2eeContactKeyRemoteVerificationState(@NonNull String lookupKey,
@NonNull String deviceId,
@NonNull String accountId,
@NonNull String ownerPackageName,
@@ -341,19 +348,19 @@
validateVerificationState(remoteVerificationState);
final Bundle extras = new Bundle();
- extras.putString(ContactKeys.LOOKUP_KEY, Objects.requireNonNull(lookupKey));
- extras.putString(ContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
- extras.putString(ContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
- extras.putString(ContactKeys.OWNER_PACKAGE_NAME, Objects.requireNonNull(ownerPackageName));
- extras.putInt(ContactKeys.REMOTE_VERIFICATION_STATE, remoteVerificationState);
+ extras.putString(E2eeContactKeys.LOOKUP_KEY, Objects.requireNonNull(lookupKey));
+ extras.putString(E2eeContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
+ extras.putString(E2eeContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
+ extras.putString(E2eeContactKeys.OWNER_PACKAGE_NAME,
+ Objects.requireNonNull(ownerPackageName));
+ extras.putInt(E2eeContactKeys.REMOTE_VERIFICATION_STATE, remoteVerificationState);
final Bundle response = nullSafeCall(mContentResolver,
- ContactKeys.UPDATE_CONTACT_KEY_REMOTE_VERIFICATION_STATE_METHOD, extras);
+ E2eeContactKeys.UPDATE_CONTACT_KEY_REMOTE_VERIFICATION_STATE_METHOD, extras);
- return response != null && response.getBoolean(ContactKeys.KEY_UPDATED_ROWS);
+ return response != null && response.getBoolean(E2eeContactKeys.KEY_UPDATED_ROWS);
}
-
private static void validateVerificationState(int verificationState) {
if (verificationState != VERIFICATION_STATE_UNVERIFIED
&& verificationState != VERIFICATION_STATE_VERIFICATION_FAILED
@@ -364,7 +371,7 @@
}
/**
- * Removes a contact key entry that belongs to the caller app.
+ * Removes an end-to-end encryption contact key entry that belongs to the caller app.
*
* @param lookupKey the value that references the contact
* @param deviceId an app-specified identifier for the device
@@ -373,22 +380,23 @@
* @return true if the entry was removed, false otherwise.
*/
@RequiresPermission(android.Manifest.permission.WRITE_CONTACTS)
- public boolean removeContactKey(@NonNull String lookupKey,
+ public boolean removeE2eeContactKey(@NonNull String lookupKey,
@NonNull String deviceId,
@NonNull String accountId) {
final Bundle extras = new Bundle();
- extras.putString(ContactKeys.LOOKUP_KEY, Objects.requireNonNull(lookupKey));
- extras.putString(ContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
- extras.putString(ContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
+ extras.putString(E2eeContactKeys.LOOKUP_KEY, Objects.requireNonNull(lookupKey));
+ extras.putString(E2eeContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
+ extras.putString(E2eeContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
final Bundle response = nullSafeCall(mContentResolver,
- ContactKeys.REMOVE_CONTACT_KEY_METHOD, extras);
+ E2eeContactKeys.REMOVE_CONTACT_KEY_METHOD, extras);
- return response != null && response.getBoolean(ContactKeys.KEY_UPDATED_ROWS);
+ return response != null && response.getBoolean(E2eeContactKeys.KEY_UPDATED_ROWS);
}
/**
- * Inserts a new entry into the self keys table or updates one if it already exists.
+ * Inserts a new entry into the end-to-end encryption self keys table or updates one if it
+ * already exists.
* @param deviceId an app-specified identifier for the device
* @param accountId an app-specified identifier for the account
@@ -397,20 +405,20 @@
* @return true if the entry was added or updated, false otherwise.
*/
@RequiresPermission(android.Manifest.permission.WRITE_CONTACTS)
- public boolean updateOrInsertSelfKey(@NonNull String deviceId,
+ public boolean updateOrInsertE2eeSelfKey(@NonNull String deviceId,
@NonNull String accountId,
@NonNull byte[] keyValue) {
validateKeyLength(keyValue);
Bundle extras = new Bundle();
- extras.putString(ContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
- extras.putString(ContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
- extras.putByteArray(ContactKeys.KEY_VALUE, Objects.requireNonNull(keyValue));
+ extras.putString(E2eeContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
+ extras.putString(E2eeContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
+ extras.putByteArray(E2eeContactKeys.KEY_VALUE, Objects.requireNonNull(keyValue));
Bundle response = nullSafeCall(mContentResolver,
- ContactKeys.UPDATE_OR_INSERT_SELF_KEY_METHOD, extras);
+ E2eeContactKeys.UPDATE_OR_INSERT_SELF_KEY_METHOD, extras);
- return response != null && response.getBoolean(ContactKeys.KEY_UPDATED_ROWS);
+ return response != null && response.getBoolean(E2eeContactKeys.KEY_UPDATED_ROWS);
}
private static void validateKeyLength(byte[] keyValue) {
@@ -422,7 +430,7 @@
}
/**
- * Updates a self key entry's remote verification state.
+ * Updates an end-to-end encryption self key entry's remote verification state.
*
* @param deviceId an app-specified identifier for the device
* @param accountId an app-specified identifier for the account
@@ -431,25 +439,25 @@
* @return true if the entry was updated, false otherwise.
*/
@RequiresPermission(android.Manifest.permission.WRITE_CONTACTS)
- public boolean updateSelfKeyRemoteVerificationState(@NonNull String deviceId,
+ public boolean updateE2eeSelfKeyRemoteVerificationState(@NonNull String deviceId,
@NonNull String accountId,
@VerificationState int remoteVerificationState) {
validateVerificationState(remoteVerificationState);
Bundle extras = new Bundle();
- extras.putString(ContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
- extras.putString(ContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
- extras.putInt(ContactKeys.REMOTE_VERIFICATION_STATE, remoteVerificationState);
+ extras.putString(E2eeContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
+ extras.putString(E2eeContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
+ extras.putInt(E2eeContactKeys.REMOTE_VERIFICATION_STATE, remoteVerificationState);
Bundle response = nullSafeCall(mContentResolver,
- ContactKeys.UPDATE_SELF_KEY_REMOTE_VERIFICATION_STATE_METHOD, extras);
+ E2eeContactKeys.UPDATE_SELF_KEY_REMOTE_VERIFICATION_STATE_METHOD, extras);
- return response != null && response.getBoolean(ContactKeys.KEY_UPDATED_ROWS);
+ return response != null && response.getBoolean(E2eeContactKeys.KEY_UPDATED_ROWS);
}
/**
- * Updates a self key entry's remote verification state that belongs to the app identified
- * by ownerPackageName.
+ * Updates an end-to-end encryption self key entry's remote verification state that belongs to
+ * the app identified by ownerPackageName.
*
* @param deviceId an app-specified identifier for the device
* @param accountId an app-specified identifier for the account
@@ -464,77 +472,79 @@
@RequiresPermission(allOf = {
android.Manifest.permission.WRITE_VERIFICATION_STATE_E2EE_CONTACT_KEYS,
android.Manifest.permission.WRITE_CONTACTS})
- public boolean updateSelfKeyRemoteVerificationState(@NonNull String deviceId,
+ public boolean updateE2eeSelfKeyRemoteVerificationState(@NonNull String deviceId,
@NonNull String accountId,
@NonNull String ownerPackageName,
@VerificationState int remoteVerificationState) {
validateVerificationState(remoteVerificationState);
Bundle extras = new Bundle();
- extras.putString(ContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
- extras.putString(ContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
- extras.putString(ContactKeys.OWNER_PACKAGE_NAME, Objects.requireNonNull(ownerPackageName));
- extras.putInt(ContactKeys.REMOTE_VERIFICATION_STATE, remoteVerificationState);
+ extras.putString(E2eeContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
+ extras.putString(E2eeContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
+ extras.putString(E2eeContactKeys.OWNER_PACKAGE_NAME,
+ Objects.requireNonNull(ownerPackageName));
+ extras.putInt(E2eeContactKeys.REMOTE_VERIFICATION_STATE, remoteVerificationState);
Bundle response = nullSafeCall(mContentResolver,
- ContactKeys.UPDATE_SELF_KEY_REMOTE_VERIFICATION_STATE_METHOD, extras);
+ E2eeContactKeys.UPDATE_SELF_KEY_REMOTE_VERIFICATION_STATE_METHOD, extras);
- return response != null && response.getBoolean(ContactKeys.KEY_UPDATED_ROWS);
+ return response != null && response.getBoolean(E2eeContactKeys.KEY_UPDATED_ROWS);
}
/**
- * Maximum size of a contact key.
+ * Maximum size of an end-to-end encryption contact key.
*/
public static int getMaxKeySizeBytes() {
return MAX_KEY_SIZE_BYTES;
}
/**
- * Returns a self key entry given the deviceId and the inferred package name of the caller.
+ * Returns an end-to-end encryption self key entry given the deviceId and the inferred package
+ * name of the caller.
*
* @param deviceId an app-specified identifier for the device
* @param accountId an app-specified identifier for the account
*
- * @return a {@link SelfKey} object containing the self key information, or null if no self key
- * is found.
+ * @return a {@link E2eeSelfKey} object containing the end-to-end encryption self key
+ * information, or null if no self key is found.
*/
@RequiresPermission(android.Manifest.permission.READ_CONTACTS)
@Nullable
- public SelfKey getSelfKey(@NonNull String deviceId,
+ public E2eeSelfKey getE2eeSelfKey(@NonNull String deviceId,
@NonNull String accountId) {
Bundle extras = new Bundle();
- extras.putString(ContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
- extras.putString(ContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
+ extras.putString(E2eeContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
+ extras.putString(E2eeContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
Bundle response = nullSafeCall(mContentResolver,
- ContactKeys.GET_SELF_KEY_METHOD, extras);
+ E2eeContactKeys.GET_SELF_KEY_METHOD, extras);
if (response == null) {
return null;
}
- return response.getParcelable(ContactKeys.KEY_CONTACT_KEY, SelfKey.class);
+ return response.getParcelable(E2eeContactKeys.KEY_CONTACT_KEY, E2eeSelfKey.class);
}
/**
- * Returns all self key entries that belong to apps visible to the caller.
+ * Returns all end-to-end encryption self key entries that belong to apps visible to the caller.
* The keys will be stripped of deviceId, timeUpdated and keyValue data.
*
- * @return a list of {@link SelfKey} objects containing the self key information, or
- * an empty list if no keys are found.
+ * @return a list of {@link E2eeSelfKey} objects containing the end-to-end encryption self key
+ * information, or an empty list if no self keys are found.
*/
@RequiresPermission(android.Manifest.permission.READ_CONTACTS)
@NonNull
- public List<SelfKey> getAllSelfKeys() {
+ public List<E2eeSelfKey> getAllE2eeSelfKeys() {
Bundle extras = new Bundle();
- Bundle response = nullSafeCall(mContentResolver, ContactKeys.GET_ALL_SELF_KEYS_METHOD,
+ Bundle response = nullSafeCall(mContentResolver, E2eeContactKeys.GET_ALL_SELF_KEYS_METHOD,
extras);
if (response == null) {
return new ArrayList<>();
}
- List<SelfKey> value = response.getParcelableArrayList(ContactKeys.KEY_CONTACT_KEYS,
- SelfKey.class);
+ List<E2eeSelfKey> value = response.getParcelableArrayList(E2eeContactKeys.KEY_CONTACT_KEYS,
+ E2eeSelfKey.class);
if (value == null) {
return new ArrayList<>();
}
@@ -542,24 +552,24 @@
}
/**
- * Returns all self key entries that are owned by the caller app.
+ * Returns all end-to-end encryption self key entries that are owned by the caller app.
*
- * @return a list of {@link SelfKey} objects containing the self key information, or
- * an empty list if no keys are found.
+ * @return a list of {@link E2eeSelfKey} objects containing the end-to-end encryption self key
+ * information, or an empty list if no self keys are found.
*/
@RequiresPermission(android.Manifest.permission.READ_CONTACTS)
@NonNull
- public List<SelfKey> getOwnerSelfKeys() {
+ public List<E2eeSelfKey> getOwnerE2eeSelfKeys() {
Bundle extras = new Bundle();
- Bundle response = nullSafeCall(mContentResolver, ContactKeys.GET_OWNER_SELF_KEYS_METHOD,
+ Bundle response = nullSafeCall(mContentResolver, E2eeContactKeys.GET_OWNER_SELF_KEYS_METHOD,
extras);
if (response == null) {
return new ArrayList<>();
}
- List<SelfKey> value = response.getParcelableArrayList(ContactKeys.KEY_CONTACT_KEYS,
- SelfKey.class);
+ List<E2eeSelfKey> value = response.getParcelableArrayList(E2eeContactKeys.KEY_CONTACT_KEYS,
+ E2eeSelfKey.class);
if (value == null) {
return new ArrayList<>();
}
@@ -567,24 +577,24 @@
}
/**
- * Removes a self key entry given the deviceId and the inferred package name of the caller.
-
+ * Removes an end-to-end encryption self key entry given the deviceId and the inferred
+ * package name of the caller.
* @param deviceId an app-specified identifier for the device
* @param accountId an app-specified identifier for the account
*
* @return true if the entry was removed, false otherwise.
*/
@RequiresPermission(android.Manifest.permission.WRITE_CONTACTS)
- public boolean removeSelfKey(@NonNull String deviceId,
+ public boolean removeE2eeSelfKey(@NonNull String deviceId,
@NonNull String accountId) {
Bundle extras = new Bundle();
- extras.putString(ContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
- extras.putString(ContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
+ extras.putString(E2eeContactKeys.DEVICE_ID, Objects.requireNonNull(deviceId));
+ extras.putString(E2eeContactKeys.ACCOUNT_ID, Objects.requireNonNull(accountId));
Bundle response = nullSafeCall(mContentResolver,
- ContactKeys.REMOVE_SELF_KEY_METHOD, extras);
+ E2eeContactKeys.REMOVE_SELF_KEY_METHOD, extras);
- return response != null && response.getBoolean(ContactKeys.KEY_UPDATED_ROWS);
+ return response != null && response.getBoolean(E2eeContactKeys.KEY_UPDATED_ROWS);
}
private Bundle nullSafeCall(@NonNull ContentResolver resolver, @NonNull String method,
@@ -622,9 +632,9 @@
public static final int VERIFICATION_STATE_VERIFIED = 2;
/** @hide */
- public static final class ContactKeys {
+ public static final class E2eeContactKeys {
- private ContactKeys() {}
+ private E2eeContactKeys() {}
/**
* <p>
@@ -636,14 +646,16 @@
/**
* <p>
- * An app-specified identifier for the device for which the contact key can be used.
+ * An app-specified identifier for the device for which the end-to-end encryption
+ * contact key can be used.
* </p>
*/
public static final String DEVICE_ID = "device_id";
/**
* <p>
- * An app-specified identifier for the account for which the contact key can be used.
+ * An app-specified identifier for the account for which the end-to-end encryption
+ * contact key can be used.
* Usually a phone number.
* </p>
*/
@@ -718,29 +730,32 @@
public static final String GET_CONTACT_KEY_METHOD = "getContactKey";
/**
- * The method to invoke in order to retrieve all contact keys.
+ * The method to invoke in order to retrieve all end-to-end encryption contact keys.
*/
public static final String GET_ALL_CONTACT_KEYS_METHOD = "getAllContactKeys";
/**
- * The method to invoke in order to retrieve contact keys that belong to the caller.
+ * The method to invoke in order to retrieve end-to-end encryption contact keys that belong
+ * to the caller.
*/
public static final String GET_OWNER_CONTACT_KEYS_METHOD = "getOwnerContactKeys";
/**
- * The method to invoke in order to update a contact key local verification state.
+ * The method to invoke in order to update an end-to-end encryption contact key local
+ * verification state.
*/
public static final String UPDATE_CONTACT_KEY_LOCAL_VERIFICATION_STATE_METHOD =
"updateContactKeyLocalVerificationState";
/**
- * The method to invoke in order to update a contact key remote verification state.
+ * The method to invoke in order to update an end-to-end encryption contact key remote
+ * verification state.
*/
public static final String UPDATE_CONTACT_KEY_REMOTE_VERIFICATION_STATE_METHOD =
"updateContactKeyRemoteVerificationState";
/**
- * The method to invoke in order to remove a contact key.
+ * The method to invoke in order to remove a end-to-end encryption contact key.
*/
public static final String REMOVE_CONTACT_KEY_METHOD = "removeContactKey";
@@ -776,12 +791,12 @@
public static final String REMOVE_SELF_KEY_METHOD = "removeSelfKey";
/**
- * Key in the incoming Bundle for all the contact keys.
+ * Key in the incoming Bundle for all the end-to-end encryption contact keys.
*/
public static final String KEY_CONTACT_KEYS = "key_contact_keys";
/**
- * Key in the incoming Bundle for a single contact key.
+ * Key in the incoming Bundle for a single end-to-end encryption contact key.
*/
public static final String KEY_CONTACT_KEY = "key_contact_key";
@@ -790,18 +805,19 @@
*/
public static final String KEY_UPDATED_ROWS = "key_updated_rows";
}
-
/**
* A parcelable class encapsulating other users' end to end encrypted contact key.
*/
- public static final class ContactKey implements Parcelable {
+ public static final class E2eeContactKey implements Parcelable {
/**
- * An app-specified identifier for the device for which the contact key can be used.
+ * An app-specified identifier for the device for which the end-to-end encryption
+ * contact key can be used.
*/
private final String mDeviceId;
/**
- * An app-specified identifier for the account for which the contact key can be used.
+ * An app-specified identifier for the account for which the end-to-end encryption
+ * contact key can be used.
* Usually a phone number.
*/
private final String mAccountId;
@@ -851,7 +867,7 @@
/**
* @hide
*/
- public ContactKey(@Nullable String deviceId, @NonNull String accountId,
+ public E2eeContactKey(@Nullable String deviceId, @NonNull String accountId,
@NonNull String ownerPackageName, long timeUpdated, @Nullable byte[] keyValue,
@VerificationState int localVerificationState,
@VerificationState int remoteVerificationState,
@@ -870,8 +886,10 @@
}
/**
- * Gets the app-specified identifier for the device for which the contact key can be used.
- * Returns null if the app doesn't have the required visibility into the contact key.
+ * Gets the app-specified identifier for the device for which the end-to-end encryption
+ * contact key can be used.
+ * Returns null if the app doesn't have the required visibility into
+ * the end-to-end encryption contact key.
*
* @return An app-specified identifier for the device.
*/
@@ -881,7 +899,8 @@
}
/**
- * Gets the app-specified identifier for the account for which the contact key can be used.
+ * Gets the app-specified identifier for the account for which the end-to-end encryption
+ * contact key can be used.
* Usually a phone number.
*
* @return An app-specified identifier for the account.
@@ -903,7 +922,7 @@
/**
* Gets the timestamp at which the key was updated. Returns -1 if the app doesn't have the
- * required visibility into the contact key.
+ * required visibility into the end-to-end encryption contact key.
*
* @return The timestamp at which the key was updated in the System.currentTimeMillis()
* base.
@@ -914,7 +933,8 @@
/**
* Gets the raw bytes for the key.
- * Returns null if the app doesn't have the required visibility into the contact key.
+ * Returns null if the app doesn't have the required visibility into
+ * the end-to-end encryption contact key.
*
* @return A copy of the raw bytes for the key.
*/
@@ -984,7 +1004,7 @@
if (obj == null) return false;
if (obj == this) return true;
- if (!(obj instanceof ContactKey toCompare)) {
+ if (!(obj instanceof E2eeContactKey toCompare)) {
return false;
}
@@ -1023,10 +1043,10 @@
}
@NonNull
- public static final Creator<ContactKey> CREATOR =
+ public static final Creator<E2eeContactKey> CREATOR =
new Creator<>() {
@Override
- public ContactKey createFromParcel(Parcel source) {
+ public E2eeContactKey createFromParcel(Parcel source) {
String deviceId = source.readString8();
String accountId = source.readString8();
String ownerPackageName = source.readString8();
@@ -1044,14 +1064,14 @@
String displayName = source.readString8();
String number = source.readString8();
String address = source.readString8();
- return new ContactKey(deviceId, accountId, ownerPackageName,
+ return new E2eeContactKey(deviceId, accountId, ownerPackageName,
timeUpdated, keyValue, localVerificationState,
remoteVerificationState, displayName, number, address);
}
@Override
- public ContactKey[] newArray(int size) {
- return new ContactKey[size];
+ public E2eeContactKey[] newArray(int size) {
+ return new E2eeContactKey[size];
}
};
}
@@ -1059,14 +1079,16 @@
/**
* A parcelable class encapsulating self end to end encrypted contact key.
*/
- public static final class SelfKey implements Parcelable {
+ public static final class E2eeSelfKey implements Parcelable {
/**
- * An app-specified identifier for the device for which the contact key can be used.
+ * An app-specified identifier for the device for which the end-to-end encryption
+ * contact key can be used.
*/
private final String mDeviceId;
/**
- * An app-specified identifier for the account for which the contact key can be used.
+ * An app-specified identifier for the account for which the end-to-end encryption
+ * contact key can be used.
* Usually a phone number.
*/
private final String mAccountId;
@@ -1096,7 +1118,7 @@
/**
* @hide
*/
- public SelfKey(@Nullable String deviceId, @NonNull String accountId,
+ public E2eeSelfKey(@Nullable String deviceId, @NonNull String accountId,
@NonNull String ownerPackageName, long timeUpdated, @Nullable byte[] keyValue,
@VerificationState int remoteVerificationState) {
this.mDeviceId = deviceId;
@@ -1108,8 +1130,10 @@
}
/**
- * Gets the app-specified identifier for the device for which the contact key can be used.
- * Returns null if the app doesn't have the required visibility into the contact key.
+ * Gets the app-specified identifier for the device for which the end-to-end encryption
+ * contact key can be used.
+ * Returns null if the app doesn't have the required visibility into
+ * the end-to-end encryption contact key.
*
* @return An app-specified identifier for the device.
*/
@@ -1119,7 +1143,8 @@
}
/**
- * Gets the app-specified identifier for the account for which the contact key can be used.
+ * Gets the app-specified identifier for the account for which the end-to-end encryption
+ * contact key can be used.
* Usually a phone number.
*
* @return An app-specified identifier for the device.
@@ -1141,7 +1166,7 @@
/**
* Gets the timestamp at which the key was updated. Returns -1 if the app doesn't have the
- * required visibility into the contact key.
+ * required visibility into the end-to-end encryption contact key.
*
* @return The timestamp at which the key was updated in the System.currentTimeMillis()
* base.
@@ -1152,7 +1177,8 @@
/**
* Gets the raw bytes for the key.
- * Returns null if the app doesn't have the required visibility into the contact key.
+ * Returns null if the app doesn't have the required visibility into
+ * the end-to-end encryption contact key.
*
* @return A copy of the raw bytes for the key.
*/
@@ -1182,7 +1208,7 @@
if (obj == null) return false;
if (obj == this) return true;
- if (!(obj instanceof SelfKey toCompare)) {
+ if (!(obj instanceof E2eeSelfKey toCompare)) {
return false;
}
@@ -1213,10 +1239,10 @@
}
@NonNull
- public static final Creator<SelfKey> CREATOR =
+ public static final Creator<E2eeSelfKey> CREATOR =
new Creator<>() {
@Override
- public SelfKey createFromParcel(Parcel source) {
+ public E2eeSelfKey createFromParcel(Parcel source) {
String deviceId = source.readString8();
String accountId = source.readString8();
String ownerPackageName = source.readString8();
@@ -1230,13 +1256,13 @@
keyValue = null;
}
int remoteVerificationState = source.readInt();
- return new SelfKey(deviceId, accountId, ownerPackageName,
+ return new E2eeSelfKey(deviceId, accountId, ownerPackageName,
timeUpdated, keyValue, remoteVerificationState);
}
@Override
- public SelfKey[] newArray(int size) {
- return new SelfKey[size];
+ public E2eeSelfKey[] newArray(int size) {
+ return new E2eeSelfKey[size];
}
};
}
diff --git a/core/java/android/service/chooser/flags.aconfig b/core/java/android/service/chooser/flags.aconfig
index 00236df..d72441f 100644
--- a/core/java/android/service/chooser/flags.aconfig
+++ b/core/java/android/service/chooser/flags.aconfig
@@ -27,3 +27,14 @@
description: "Provides additional callbacks with information about user actions in ChooserResult"
bug: "263474465"
}
+
+flag {
+ name: "legacy_chooser_pinning_removal"
+ namespace: "intentresolver"
+ description: "Removing pinning functionality from the legacy chooser (used by partial screenshare)"
+ bug: "301068735"
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
+}
+
diff --git a/core/java/android/view/OWNERS b/core/java/android/view/OWNERS
index ad326e4..a2f767d 100644
--- a/core/java/android/view/OWNERS
+++ b/core/java/android/view/OWNERS
@@ -102,6 +102,7 @@
per-file IWindow*.aidl = file:/services/core/java/com/android/server/wm/OWNERS
per-file RemoteAnimation*.java = file:/services/core/java/com/android/server/wm/OWNERS
per-file RemoteAnimation*.aidl = file:/services/core/java/com/android/server/wm/OWNERS
+per-file ScreenRecordingCallbacks.java = file:/services/core/java/com/android/server/wm/OWNERS
per-file *SurfaceControl*.java = file:/services/core/java/com/android/server/wm/OWNERS
per-file SurfaceControl*.aidl = file:/services/core/java/com/android/server/wm/OWNERS
per-file SurfaceSession.java = file:/services/core/java/com/android/server/wm/OWNERS
diff --git a/core/java/android/view/RoundedCorners.java b/core/java/android/view/RoundedCorners.java
index f68cc69..1f841bf 100644
--- a/core/java/android/view/RoundedCorners.java
+++ b/core/java/android/view/RoundedCorners.java
@@ -198,6 +198,12 @@
radius = res.getDimensionPixelSize(R.dimen.rounded_corner_radius);
}
array.recycle();
+ // For devices with round displays (e.g. watches) that don't otherwise provide the rounded
+ // corner radius via resource overlays, we can infer the corner radius directly from the
+ // display size.
+ if (radius == 0 && res.getConfiguration().isScreenRound()) {
+ radius = res.getDisplayMetrics().widthPixels / 2;
+ }
return radius;
}
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index cbb3be7..042af1f 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -15314,6 +15314,7 @@
* {@link #isLongClickable()}, {@link #isContextClickable()},
* {@link #isScreenReaderFocusable()}, or {@link #isFocusable()}
* <li>Has an {@link AccessibilityDelegate}
+ * <li>Has an {@link AccessibilityNodeProvider}
* <li>Has an interaction listener, e.g. {@link OnTouchListener},
* {@link OnKeyListener}, etc.
* <li>Is an accessibility live region, e.g.
@@ -15346,7 +15347,8 @@
}
return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
- || hasListenersForAccessibility() || mAccessibilityDelegate != null
+ || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
+ || getAccessibilityDelegate() != null
|| getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE
|| isAccessibilityPane() || isAccessibilityHeading();
}
diff --git a/core/java/android/view/inputmethod/InputMethodInfo.java b/core/java/android/view/inputmethod/InputMethodInfo.java
index 7c9678f..16fecc1 100644
--- a/core/java/android/view/inputmethod/InputMethodInfo.java
+++ b/core/java/android/view/inputmethod/InputMethodInfo.java
@@ -497,6 +497,25 @@
* @hide
*/
@TestApi
+ public InputMethodInfo(@NonNull String packageName, @NonNull String className,
+ @NonNull CharSequence label, @NonNull String settingsActivity,
+ @NonNull String languageSettingsActivity, boolean supportStylusHandwriting,
+ @NonNull String stylusHandwritingSettingsActivityAttr) {
+ this(buildFakeResolveInfo(packageName, className, label), false /* isAuxIme */,
+ settingsActivity, languageSettingsActivity, null /* subtypes */,
+ 0 /* isDefaultResId */, false /* forceDefault */,
+ true /* supportsSwitchingToNextInputMethod */,
+ false /* inlineSuggestionsEnabled */, false /* isVrOnly */,
+ false /* isVirtualDeviceOnly */, 0 /* handledConfigChanges */,
+ supportStylusHandwriting, false /* supportConnectionlessStylusHandwriting */,
+ stylusHandwritingSettingsActivityAttr, false /* inlineSuggestionsEnabled */);
+ }
+
+ /**
+ * Test API for creating a built-in input method to verify stylus handwriting.
+ * @hide
+ */
+ @TestApi
@FlaggedApi(Flags.FLAG_CONNECTIONLESS_HANDWRITING)
public InputMethodInfo(@NonNull String packageName, @NonNull String className,
@NonNull CharSequence label, @NonNull String settingsActivity,
diff --git a/core/java/android/view/inputmethod/InputMethodManager.java b/core/java/android/view/inputmethod/InputMethodManager.java
index 3bce155..f349ae9 100644
--- a/core/java/android/view/inputmethod/InputMethodManager.java
+++ b/core/java/android/view/inputmethod/InputMethodManager.java
@@ -3490,8 +3490,7 @@
return false;
}
mServedView = mNextServedView;
- if (initiationWithoutInputConnection() && mServedView.onCheckIsTextEditor()
- && mServedView.isHandwritingDelegate()) {
+ if (initiationWithoutInputConnection() && mServedView.isHandwritingDelegate()) {
mServedView.getViewRootImpl().getHandwritingInitiator().onDelegateViewFocused(
mServedView);
}
diff --git a/core/java/android/widget/RemoteViews.java b/core/java/android/widget/RemoteViews.java
index 13dc4ef..0e5747d 100644
--- a/core/java/android/widget/RemoteViews.java
+++ b/core/java/android/widget/RemoteViews.java
@@ -3874,7 +3874,7 @@
}
}
- private static class SetDrawInstructionAction extends Action {
+ private class SetDrawInstructionAction extends Action {
@Nullable
private final DrawInstructions mInstructions;
@@ -3909,6 +3909,15 @@
}
try (ByteArrayInputStream is = new ByteArrayInputStream(bytes.get(0))) {
player.setDocument(new RemoteComposeDocument(is));
+ player.addClickListener((viewId, metadata) -> {
+ mActions.forEach(action -> {
+ if (viewId == action.mViewId
+ && action instanceof SetOnClickResponse setOnClickResponse) {
+ setOnClickResponse.mResponse.handleViewInteraction(
+ player, params.handler);
+ }
+ });
+ });
} catch (IOException e) {
Log.e(LOG_TAG, "Failed to render draw instructions", e);
}
@@ -6051,16 +6060,6 @@
RemoteViews rvToApply = getRemoteViewsToApply(context, size);
View result = inflateView(context, rvToApply, directParent,
params.applyThemeResId, params.colorResources);
- if (result instanceof RemoteComposePlayer player) {
- player.addClickListener((viewId, metadata) -> {
- mActions.forEach(action -> {
- if (viewId == action.mViewId
- && action instanceof SetOnClickResponse setOnClickResponse) {
- setOnClickResponse.mResponse.handleViewInteraction(player, params.handler);
- }
- });
- });
- }
rvToApply.performApply(result, rootParent, params);
return result;
}
diff --git a/core/java/android/window/flags/OWNERS b/core/java/android/window/flags/OWNERS
index 3fa3760..fd73d35 100644
--- a/core/java/android/window/flags/OWNERS
+++ b/core/java/android/window/flags/OWNERS
@@ -1,2 +1,3 @@
per-file responsible_apis.aconfig = file:/BAL_OWNERS
per-file large_screen_experiences_app_compat.aconfig = file:/LSE_APP_COMPAT_OWNERS
+per-file accessibility.aconfig = file:/core/java/android/view/accessibility/OWNERS
diff --git a/core/java/com/android/internal/app/ChooserActivity.java b/core/java/com/android/internal/app/ChooserActivity.java
index 86d3037..29669d3 100644
--- a/core/java/com/android/internal/app/ChooserActivity.java
+++ b/core/java/com/android/internal/app/ChooserActivity.java
@@ -96,6 +96,7 @@
import android.provider.OpenableColumns;
import android.provider.Settings;
import android.service.chooser.ChooserTarget;
+import android.service.chooser.Flags;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.HashedStringCache;
@@ -2543,6 +2544,9 @@
@Override
public boolean isComponentPinned(ComponentName name) {
+ if (Flags.legacyChooserPinningRemoval()) {
+ return false;
+ }
return mPinnedSharedPrefs.getBoolean(name.flattenToString(), false);
}
@@ -3147,6 +3151,10 @@
}
private boolean shouldShowTargetDetails(TargetInfo ti) {
+ if (Flags.legacyChooserPinningRemoval()) {
+ // Never show the long press menu if we've removed pinning.
+ return false;
+ }
ComponentName nearbyShare = getNearbySharingComponent();
// Suppress target details for nearby share to hide pin/unpin action
boolean isNearbyShare = nearbyShare != null && nearbyShare.equals(
diff --git a/core/java/com/android/internal/pm/parsing/pkg/PackageImpl.java b/core/java/com/android/internal/pm/parsing/pkg/PackageImpl.java
index 73df5e8..5e89d06 100644
--- a/core/java/com/android/internal/pm/parsing/pkg/PackageImpl.java
+++ b/core/java/com/android/internal/pm/parsing/pkg/PackageImpl.java
@@ -421,6 +421,8 @@
@NonNull
private String[] mUsesStaticLibrariesSorted;
+ private boolean mAppMetadataFileInApk = false;
+
@NonNull
public static PackageImpl forParsing(@NonNull String packageName, @NonNull String baseCodePath,
@NonNull String codePath, @NonNull TypedArray manifestArray, boolean isCoreApp,
@@ -1063,6 +1065,11 @@
return memtagMode;
}
+ @Override
+ public boolean isAppMetadataFileInApk() {
+ return mAppMetadataFileInApk;
+ }
+
@Nullable
@Override
public Bundle getMetaData() {
@@ -2151,6 +2158,12 @@
}
@Override
+ public PackageImpl setAppMetadataFileInApk(boolean fileInApk) {
+ mAppMetadataFileInApk = fileInApk;
+ return this;
+ }
+
+ @Override
public PackageImpl setMetaData(@Nullable Bundle value) {
metaData = value;
return this;
@@ -3264,6 +3277,7 @@
dest.writeLong(this.mBooleans);
dest.writeLong(this.mBooleans2);
dest.writeBoolean(this.mAllowCrossUidActivitySwitchFromBelow);
+ dest.writeBoolean(this.mAppMetadataFileInApk);
}
public PackageImpl(Parcel in) {
@@ -3426,6 +3440,7 @@
this.mBooleans = in.readLong();
this.mBooleans2 = in.readLong();
this.mAllowCrossUidActivitySwitchFromBelow = in.readBoolean();
+ this.mAppMetadataFileInApk = in.readBoolean();
assignDerivedFields();
assignDerivedFields2();
diff --git a/core/java/com/android/internal/pm/parsing/pkg/ParsedPackage.java b/core/java/com/android/internal/pm/parsing/pkg/ParsedPackage.java
index 66cfb69..3c26a7c 100644
--- a/core/java/com/android/internal/pm/parsing/pkg/ParsedPackage.java
+++ b/core/java/com/android/internal/pm/parsing/pkg/ParsedPackage.java
@@ -127,4 +127,7 @@
ParsedPackage setDirectBootAware(boolean directBootAware);
ParsedPackage setPersistent(boolean persistent);
+
+ /** Retrieves whether the apk contains a app metadata file. */
+ boolean isAppMetadataFileInApk();
}
diff --git a/core/java/com/android/internal/pm/pkg/parsing/ParsingPackage.java b/core/java/com/android/internal/pm/pkg/parsing/ParsingPackage.java
index 5d185af..5ab17a6 100644
--- a/core/java/com/android/internal/pm/pkg/parsing/ParsingPackage.java
+++ b/core/java/com/android/internal/pm/pkg/parsing/ParsingPackage.java
@@ -133,6 +133,9 @@
@Nullable SparseArray<int[]> splitDependencies
);
+ /** Sets whether the apk contains a app metadata file. */
+ ParsingPackage setAppMetadataFileInApk(boolean fileInApk);
+
ParsingPackage setMetaData(Bundle metaData);
ParsingPackage setForceQueryable(boolean forceQueryable);
diff --git a/core/java/com/android/internal/pm/pkg/parsing/ParsingPackageUtils.java b/core/java/com/android/internal/pm/pkg/parsing/ParsingPackageUtils.java
index 2e6053d..00c4827 100644
--- a/core/java/com/android/internal/pm/pkg/parsing/ParsingPackageUtils.java
+++ b/core/java/com/android/internal/pm/pkg/parsing/ParsingPackageUtils.java
@@ -46,6 +46,7 @@
import android.content.pm.ConfigurationInfo;
import android.content.pm.FeatureGroupInfo;
import android.content.pm.FeatureInfo;
+import android.content.pm.Flags;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.Property;
@@ -163,6 +164,8 @@
*/
public static final String ANDROID_MANIFEST_FILENAME = "AndroidManifest.xml";
+ public static final String APP_METADATA_FILE_NAME = "app.metadata";
+
/**
* Path prefix for apps on expanded storage
*/
@@ -636,6 +639,11 @@
pkg.setSigningDetails(SigningDetails.UNKNOWN);
}
+ if (Flags.aslInApkAppMetadataSource()
+ && ArrayUtils.contains(assets.list(""), APP_METADATA_FILE_NAME)) {
+ pkg.setAppMetadataFileInApk(true);
+ }
+
return input.success(pkg);
} catch (Exception e) {
return input.error(INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION,
@@ -686,7 +694,8 @@
*/
private ParseResult<ParsingPackage> parseBaseApk(ParseInput input, String apkPath,
String codePath, Resources res, XmlResourceParser parser, int flags,
- boolean shouldSkipComponents) throws XmlPullParserException, IOException {
+ boolean shouldSkipComponents)
+ throws XmlPullParserException, IOException {
final String splitName;
final String pkgName;
diff --git a/core/jni/com_android_internal_os_Zygote.cpp b/core/jni/com_android_internal_os_Zygote.cpp
index 0938ce17..3ed9f49 100644
--- a/core/jni/com_android_internal_os_Zygote.cpp
+++ b/core/jni/com_android_internal_os_Zygote.cpp
@@ -1965,7 +1965,7 @@
// If this zygote isn't root, it won't be able to create a process group,
// since the directory is owned by root.
- if (!is_system_server && getuid() == 0) {
+ if (getuid() == 0) {
const int rc = createProcessGroup(uid, getpid());
if (rc != 0) {
fail_fn(rc == -EROFS ? CREATE_ERROR("createProcessGroup failed, kernel missing "
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 900f9cb..487b5be 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -2281,7 +2281,7 @@
<!-- @SystemApi @hide Allows changing Thread network state and access to Thread network
credentials such as Network Key and PSKc.
<p>Not for use by third-party applications.
- @FlaggedApi("com.android.net.thread.flags.thread_enabled_platform") -->
+ @FlaggedApi("com.android.net.thread.platform.flags.thread_enabled_platform") -->
<permission android:name="android.permission.THREAD_NETWORK_PRIVILEGED"
android:protectionLevel="signature|privileged" />
@@ -3629,7 +3629,7 @@
<!-- Allows an application to set policy related to <a
href="https://www.threadgroup.org">Thread</a> network.
- @FlaggedApi("com.android.net.thread.flags.thread_user_restriction_enabled")
+ @FlaggedApi("com.android.net.thread.platform.flags.thread_user_restriction_enabled")
-->
<permission android:name="android.permission.MANAGE_DEVICE_POLICY_THREAD_NETWORK"
android:protectionLevel="internal|role" />
@@ -7986,7 +7986,7 @@
@hide
-->
<permission android:name="android.permission.GET_APP_METADATA"
- android:protectionLevel="signature|installer" />
+ android:protectionLevel="signature|installer|verifier" />
<!-- @hide @SystemApi Allows an application to stage HealthConnect's remote data so that
HealthConnect can later integrate it. -->
diff --git a/core/res/res/values/attrs_manifest.xml b/core/res/res/values/attrs_manifest.xml
index b2e0be7c..c882938 100644
--- a/core/res/res/values/attrs_manifest.xml
+++ b/core/res/res/values/attrs_manifest.xml
@@ -1618,15 +1618,13 @@
<!-- Data (photo, file, account) upload/download, backup/restore, import/export, fetch,
transfer over network between device and cloud.
- <p><b>THIS TYPE IS DEPRECATED.</b>
- <p><em>Note: For apps with <code>targetSdkVersion</code>
- {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM} and above, this type should
- <b>NOT</b> be used: calling
- {@link android.app.Service#startForeground(int, android.app.Notification, int)}
- with this type on devices running
- {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM} is still allowed, but it may
- throw an {@link android.app.InvalidForegroundServiceTypeException} in future platform
- releases.</em>
+ <p>For apps with <code>targetSdkVersion</code>
+ {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} and above, this type should NOT
+ be used: calling
+ {@link android.app.Service#startForeground(int, android.app.Notification, int)} with
+ this type on devices running {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}
+ is still allowed, but calling it with this type on devices running future platform
+ releases may get a {@link android.app.InvalidForegroundServiceTypeException}.
-->
<flag name="dataSync" value="0x01" />
<!-- Music, video, news or other media play.
diff --git a/core/tests/coretests/Android.bp b/core/tests/coretests/Android.bp
index 37e6780..e72beee 100644
--- a/core/tests/coretests/Android.bp
+++ b/core/tests/coretests/Android.bp
@@ -28,10 +28,19 @@
visibility: ["//visibility:private"],
}
+java_defaults {
+ name: "FrameworksCoreTests-resources",
+ aaptflags: [
+ "-0 .dat",
+ "-0 .gld",
+ "-c fa",
+ ],
+ resource_dirs: ["res"],
+}
+
android_test {
name: "FrameworksCoreTests",
- // FrameworksCoreTestsRavenwood references the .aapt.srcjar
- use_resource_processor: false,
+ defaults: ["FrameworksCoreTests-resources"],
srcs: [
"src/**/*.java",
@@ -117,7 +126,6 @@
certificate: "platform",
- resource_dirs: ["res"],
resource_zips: [":FrameworksCoreTests_apks_as_resources"],
java_resources: [":FrameworksCoreTests_unit_test_cert_der"],
@@ -128,6 +136,24 @@
],
}
+// FrameworksCoreTestsRavenwood pulls in the R.java class from this one.
+// Note, "FrameworksCoreTests" and "FrameworksCoreTests-resonly" _might_ not have indentical
+// R.java (not sure if there's a guarantee), but that doesn't matter as long as
+// FrameworksCoreTestsRavenwood consistently uses the R definition in this module.
+android_app {
+ name: "FrameworksCoreTests-resonly",
+ defaults: ["FrameworksCoreTests-resources"],
+
+ // FrameworksCoreTestsRavenwood references the .aapt.srcjar
+ use_resource_processor: false,
+ libs: [
+ "framework-res",
+ "android.test.runner",
+ "org.apache.http.legacy",
+ ],
+ sdk_version: "core_platform",
+}
+
// Rules to copy all the test apks to the intermediate raw resource directory
java_genrule {
name: "FrameworksCoreTests_apks_as_resources",
@@ -225,7 +251,11 @@
"src/com/android/internal/util/**/*.java",
"src/com/android/internal/power/EnergyConsumerStatsTest.java",
- ":FrameworksCoreTests{.aapt.srcjar}",
+ // Pull in R.java from FrameworksCoreTests-resonly, not from FrameworksCoreTests,
+ // to avoid having a dependency to FrameworksCoreTests.
+ // This way, when updating source files and running this test, we don't need to
+ // rebuild the entire FrameworksCoreTests, which would be slow.
+ ":FrameworksCoreTests-resonly{.aapt.srcjar}",
":FrameworksCoreTests-aidl",
":FrameworksCoreTests-helpers",
":FrameworksCoreTestDoubles-sources",
diff --git a/core/tests/coretests/src/android/app/activity/ActivityThreadTest.java b/core/tests/coretests/src/android/app/activity/ActivityThreadTest.java
index d95834f..64c17bd 100644
--- a/core/tests/coretests/src/android/app/activity/ActivityThreadTest.java
+++ b/core/tests/coretests/src/android/app/activity/ActivityThreadTest.java
@@ -395,11 +395,13 @@
olderConfig.seq = seq + 1;
final ActivityClientRecord r = getActivityClientRecord(activity);
- activityThread.handleActivityConfigurationChanged(r, olderConfig, INVALID_DISPLAY);
+ activityThread.handleActivityConfigurationChanged(r, olderConfig, INVALID_DISPLAY,
+ new ActivityWindowInfo());
assertEquals(numOfConfig, activity.mNumOfConfigChanges);
assertEquals(olderConfig.orientation, activity.mConfig.orientation);
- activityThread.handleActivityConfigurationChanged(r, newerConfig, INVALID_DISPLAY);
+ activityThread.handleActivityConfigurationChanged(r, newerConfig, INVALID_DISPLAY,
+ new ActivityWindowInfo());
assertEquals(numOfConfig + 1, activity.mNumOfConfigChanges);
assertEquals(newerConfig.orientation, activity.mConfig.orientation);
});
@@ -417,7 +419,7 @@
config.orientation = ORIENTATION_PORTRAIT;
activityThread.handleActivityConfigurationChanged(getActivityClientRecord(activity),
- config, INVALID_DISPLAY);
+ config, INVALID_DISPLAY, new ActivityWindowInfo());
});
final IApplicationThread appThread = activityThread.getApplicationThread();
@@ -488,7 +490,7 @@
config.orientation = ORIENTATION_PORTRAIT;
activityThread.handleActivityConfigurationChanged(getActivityClientRecord(activity),
- config, INVALID_DISPLAY);
+ config, INVALID_DISPLAY, new ActivityWindowInfo());
});
final int numOfConfig = activity.mNumOfConfigChanges;
@@ -618,7 +620,7 @@
activityThread.updatePendingActivityConfiguration(activity.getActivityToken(),
newActivityConfig);
activityThread.handleActivityConfigurationChanged(r, newActivityConfig,
- INVALID_DISPLAY);
+ INVALID_DISPLAY, new ActivityWindowInfo());
assertEquals("Virtual display orientation must not change when activity"
+ " configuration orientation changes.",
@@ -783,8 +785,8 @@
/**
* Calls {@link ActivityThread#handleActivityConfigurationChanged(ActivityClientRecord,
- * Configuration, int)} to try to push activity configuration to the activity for the given
- * sequence number.
+ * Configuration, int, ActivityWindowInfo)} to try to push activity configuration to the
+ * activity for the given sequence number.
* <p>
* It uses orientation to push the configuration and it tries a different orientation if the
* first attempt doesn't make through, to rule out the possibility that the previous
@@ -803,7 +805,8 @@
Configuration config = new Configuration();
config.orientation = ORIENTATION_PORTRAIT;
config.seq = seq;
- activityThread.handleActivityConfigurationChanged(r, config, INVALID_DISPLAY);
+ activityThread.handleActivityConfigurationChanged(r, config, INVALID_DISPLAY,
+ new ActivityWindowInfo());
if (activity.mNumOfConfigChanges > numOfConfig) {
return config.seq;
@@ -812,7 +815,8 @@
config = new Configuration();
config.orientation = ORIENTATION_LANDSCAPE;
config.seq = seq + 1;
- activityThread.handleActivityConfigurationChanged(r, config, INVALID_DISPLAY);
+ activityThread.handleActivityConfigurationChanged(r, config, INVALID_DISPLAY,
+ new ActivityWindowInfo());
return config.seq;
}
diff --git a/core/tests/coretests/src/android/app/servertransaction/ClientTransactionItemTest.java b/core/tests/coretests/src/android/app/servertransaction/ClientTransactionItemTest.java
index 30545f9..85a1b4e 100644
--- a/core/tests/coretests/src/android/app/servertransaction/ClientTransactionItemTest.java
+++ b/core/tests/coretests/src/android/app/servertransaction/ClientTransactionItemTest.java
@@ -177,7 +177,7 @@
@Test
public void testMoveToDisplayItem_getContextToUpdate() {
final MoveToDisplayItem item = MoveToDisplayItem
- .obtain(mActivityToken, DEFAULT_DISPLAY, mConfiguration);
+ .obtain(mActivityToken, DEFAULT_DISPLAY, mConfiguration, new ActivityWindowInfo());
final Context context = item.getContextToUpdate(mHandler);
assertEquals(mActivity, context);
diff --git a/core/tests/coretests/src/android/app/servertransaction/ObjectPoolTests.java b/core/tests/coretests/src/android/app/servertransaction/ObjectPoolTests.java
index a8466bb..906558f 100644
--- a/core/tests/coretests/src/android/app/servertransaction/ObjectPoolTests.java
+++ b/core/tests/coretests/src/android/app/servertransaction/ObjectPoolTests.java
@@ -157,7 +157,8 @@
@Test
public void testRecycleMoveToDisplayItem() {
- testRecycle(() -> MoveToDisplayItem.obtain(mActivityToken, 4, config()));
+ testRecycle(() -> MoveToDisplayItem.obtain(mActivityToken, 4, config(),
+ new ActivityWindowInfo()));
}
@Test
diff --git a/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java b/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java
index 9743e84..dbb090f 100644
--- a/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java
+++ b/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java
@@ -110,8 +110,11 @@
@Test
public void testMoveToDisplay() {
// Write to parcel
+ final ActivityWindowInfo activityWindowInfo = new ActivityWindowInfo();
+ activityWindowInfo.set(true /* isEmbedded */, new Rect(0, 0, 500, 1000),
+ new Rect(0, 0, 500, 500));
MoveToDisplayItem item = MoveToDisplayItem.obtain(mActivityToken, 4 /* targetDisplayId */,
- config());
+ config(), activityWindowInfo);
writeAndPrepareForReading(item);
// Read from parcel and assert
diff --git a/core/tests/coretests/src/android/view/RoundedCornersTest.java b/core/tests/coretests/src/android/view/RoundedCornersTest.java
index 07ef33a..ec665ad 100644
--- a/core/tests/coretests/src/android/view/RoundedCornersTest.java
+++ b/core/tests/coretests/src/android/view/RoundedCornersTest.java
@@ -16,6 +16,8 @@
package android.view;
+import static android.content.res.Configuration.SCREENLAYOUT_ROUND_NO;
+import static android.content.res.Configuration.SCREENLAYOUT_ROUND_YES;
import static android.view.RoundedCorner.POSITION_BOTTOM_LEFT;
import static android.view.RoundedCorner.POSITION_BOTTOM_RIGHT;
import static android.view.RoundedCorner.POSITION_TOP_LEFT;
@@ -28,22 +30,47 @@
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.sameInstance;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.when;
+import android.content.res.Configuration;
+import android.content.res.Resources;
+import android.content.res.TypedArray;
import android.platform.test.annotations.Presubmit;
+import android.util.DisplayMetrics;
import android.util.Pair;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
+import com.android.internal.R;
+
+import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
@RunWith(AndroidJUnit4.class)
@SmallTest
@Presubmit
public class RoundedCornersTest {
+ @Mock
+ DisplayMetrics mMockDisplayMetrics;
+ @Mock
+ Resources mMockResources;
+ @Mock TypedArray mMockTypedArray;
+ Configuration mConfiguration;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mConfiguration = Configuration.EMPTY;
+ }
+
final RoundedCorners mRoundedCorners = new RoundedCorners(
new RoundedCorner(POSITION_TOP_LEFT, 10, 10, 10),
new RoundedCorner(POSITION_TOP_RIGHT, 10, 190, 10),
@@ -199,4 +226,63 @@
assertThat(RoundedCorners.fromRadii(radius, 200, 300),
not(sameInstance(cached)));
}
+
+ @Test
+ public void testGetRoundedCornerRadius_withRoundDevice_usesDisplayRadiusAsDefault() {
+ final int displayWidth = 400;
+ mConfiguration.screenLayout = SCREENLAYOUT_ROUND_YES;
+ mMockDisplayMetrics.widthPixels = displayWidth;
+
+ when(mMockResources.getConfiguration()).thenReturn(mConfiguration);
+ when(mMockResources.getDisplayMetrics()).thenReturn(mMockDisplayMetrics);
+ when(mMockResources.getStringArray(R.array.config_displayUniqueIdArray))
+ .thenReturn(new String[]{"0"});
+ when(mMockTypedArray.length()).thenReturn(0);
+ when(mMockResources.obtainTypedArray(anyInt())).thenReturn(mMockTypedArray);
+ when(mMockResources.getDimensionPixelSize(R.dimen.rounded_corner_radius))
+ .thenReturn(0);
+
+
+ int radius = RoundedCorners.getRoundedCornerRadius(mMockResources, "0");
+ assertEquals((displayWidth / 2), radius);
+ }
+
+ @Test
+ public void testGetRoundedCornerRadius_withRoundDevice_usesOverlayIfProvided() {
+ final int displayWidth = 400;
+ final int overlayValue = 199;
+ mConfiguration.screenLayout = SCREENLAYOUT_ROUND_YES;
+ mMockDisplayMetrics.widthPixels = displayWidth;
+
+ when(mMockResources.getConfiguration()).thenReturn(mConfiguration);
+ when(mMockResources.getDisplayMetrics()).thenReturn(mMockDisplayMetrics);
+ when(mMockResources.getStringArray(R.array.config_displayUniqueIdArray))
+ .thenReturn(new String[]{"0"});
+ when(mMockTypedArray.length()).thenReturn(0);
+ when(mMockResources.obtainTypedArray(anyInt())).thenReturn(mMockTypedArray);
+ when(mMockResources.getDimensionPixelSize(R.dimen.rounded_corner_radius))
+ .thenReturn(overlayValue);
+
+ int radius = RoundedCorners.getRoundedCornerRadius(mMockResources, "0");
+ assertEquals(overlayValue, radius);
+ }
+
+ @Test
+ public void testGetRoundedCornerRadius_withNonRoundDevice_noDisplayDefault() {
+ final int displayWidth = 400;
+ mConfiguration.screenLayout = SCREENLAYOUT_ROUND_NO;
+ mMockDisplayMetrics.widthPixels = displayWidth;
+
+ when(mMockResources.getConfiguration()).thenReturn(mConfiguration);
+ when(mMockResources.getDisplayMetrics()).thenReturn(mMockDisplayMetrics);
+ when(mMockResources.getStringArray(R.array.config_displayUniqueIdArray))
+ .thenReturn(new String[]{"0"});
+ when(mMockTypedArray.length()).thenReturn(0);
+ when(mMockResources.obtainTypedArray(anyInt())).thenReturn(mMockTypedArray);
+ when(mMockResources.getDimensionPixelSize(R.dimen.rounded_corner_radius))
+ .thenReturn(0);
+
+ int radius = RoundedCorners.getRoundedCornerRadius(mMockResources, "0");
+ assertEquals(0, radius);
+ }
}
diff --git a/keystore/java/android/security/KeyStore.java b/keystore/java/android/security/KeyStore.java
index 11b8271..bd9abec 100644
--- a/keystore/java/android/security/KeyStore.java
+++ b/keystore/java/android/security/KeyStore.java
@@ -21,12 +21,14 @@
import android.os.StrictMode;
/**
- * @hide This should not be made public in its present form because it
- * assumes that private and secret key bytes are available and would
- * preclude the use of hardware crypto.
+ * This class provides some constants and helper methods related to Android's Keystore service.
+ * This class was originally much larger, but its functionality was superseded by other classes.
+ * It now just contains a few remaining pieces for which the users haven't been updated yet.
+ * You may be looking for {@link java.security.KeyStore} instead.
+ *
+ * @hide
*/
public class KeyStore {
- private static final String TAG = "KeyStore";
// ResponseCodes - see system/security/keystore/include/keystore/keystore.h
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
@@ -42,50 +44,6 @@
return KEY_STORE;
}
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public byte[] get(String key) {
- return null;
- }
-
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public boolean delete(String key) {
- return false;
- }
-
- /**
- * List uids of all keys that are auth bound to the current user.
- * Only system is allowed to call this method.
- * @hide
- * @deprecated This function always returns null.
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public int[] listUidsOfAuthBoundKeys() {
- return null;
- }
-
-
- /**
- * @hide
- * @deprecated This function has no effect.
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public boolean unlock(String password) {
- return false;
- }
-
- /**
- *
- * @return
- * @deprecated This function always returns true.
- * @hide
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
- public boolean isEmpty() {
- return true;
- }
-
/**
* Add an authentication record to the keystore authorization table.
*
@@ -105,13 +63,4 @@
public void onDeviceOffBody() {
AndroidKeyStoreMaintenance.onDeviceOffBody();
}
-
- /**
- * Returns a {@link KeyStoreException} corresponding to the provided keystore/keymaster error
- * code.
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static KeyStoreException getKeyStoreException(int errorCode) {
- return new KeyStoreException(-10000, "Should not be called.");
- }
}
diff --git a/libs/WindowManager/Shell/res/values/dimen.xml b/libs/WindowManager/Shell/res/values/dimen.xml
index cbfa74e..48e6428 100644
--- a/libs/WindowManager/Shell/res/values/dimen.xml
+++ b/libs/WindowManager/Shell/res/values/dimen.xml
@@ -101,6 +101,10 @@
<dimen name="split_divider_bar_width">10dp</dimen>
<dimen name="split_divider_corner_size">42dp</dimen>
+ <!-- The distance from the edge of the screen to invoke splitscreen when the user is dragging
+ an intent that can be launched into split. -->
+ <dimen name="drag_launchable_intent_edge_margin">48dp</dimen>
+
<!-- One-Handed Mode -->
<!-- Threshold for dragging distance to enable one-handed mode -->
<dimen name="gestures_onehanded_drag_threshold">20dp</dimen>
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropController.java
index 1afbdf9..7da1b23 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropController.java
@@ -59,7 +59,6 @@
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
-import com.android.internal.logging.InstanceId;
import com.android.internal.logging.UiEventLogger;
import com.android.internal.protolog.common.ProtoLog;
import com.android.launcher3.icons.IconProvider;
@@ -316,12 +315,11 @@
return false;
}
// TODO(b/290391688): Also update the session data with task stack changes
- InstanceId loggerSessionId = mLogger.logStart(event);
- pd.activeDragCount++;
- pd.dragSession = new DragSession(mContext, ActivityTaskManager.getInstance(),
+ pd.dragSession = new DragSession(ActivityTaskManager.getInstance(),
mDisplayController.getDisplayLayout(displayId), event.getClipData());
pd.dragSession.update();
- pd.dragLayout.prepare(pd.dragSession, loggerSessionId);
+ pd.activeDragCount++;
+ pd.dragLayout.prepare(pd.dragSession, mLogger.logStart(pd.dragSession));
setDropTargetWindowVisibility(pd, View.VISIBLE);
notifyListeners(l -> {
l.onDragStarted();
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropEventLogger.java b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropEventLogger.java
index 2a7dd5a..75b126c 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropEventLogger.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropEventLogger.java
@@ -53,17 +53,21 @@
/**
* Logs the start of a drag.
*/
- public InstanceId logStart(DragEvent event) {
- final ClipDescription description = event.getClipDescription();
- final ClipData data = event.getClipData();
- final ClipData.Item item = data.getItemAt(0);
- mInstanceId = item.getIntent().getParcelableExtra(
- ClipDescription.EXTRA_LOGGING_INSTANCE_ID);
+ public InstanceId logStart(DragSession session) {
+ mInstanceId = session.appData != null
+ ? session.appData.getParcelableExtra(ClipDescription.EXTRA_LOGGING_INSTANCE_ID,
+ InstanceId.class)
+ : null;
if (mInstanceId == null) {
mInstanceId = mIdSequence.newInstanceId();
}
- mActivityInfo = item.getActivityInfo();
- log(getStartEnum(description), mActivityInfo);
+ mActivityInfo = session.activityInfo;
+ if (session.appData != null) {
+ log(getStartEnum(session.getClipDescription()), mActivityInfo);
+ } else {
+ // TODO(b/255649902): Update this once we have a new enum
+ log(DragAndDropUiEventEnum.GLOBAL_APP_DRAG_START_ACTIVITY, mActivityInfo);
+ }
return mInstanceId;
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropPolicy.java b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropPolicy.java
index a31a773..29fe9ab 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropPolicy.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragAndDropPolicy.java
@@ -29,6 +29,8 @@
import static android.content.Intent.EXTRA_SHORTCUT_ID;
import static android.content.Intent.EXTRA_TASK_ID;
import static android.content.Intent.EXTRA_USER;
+import static android.content.Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
+import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_BOTTOM_OR_RIGHT;
import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_TOP_OR_LEFT;
@@ -52,6 +54,7 @@
import android.graphics.Insets;
import android.graphics.Rect;
import android.graphics.RectF;
+import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.os.UserHandle;
@@ -63,8 +66,10 @@
import androidx.annotation.VisibleForTesting;
import com.android.internal.logging.InstanceId;
+import com.android.internal.protolog.common.ProtoLog;
import com.android.wm.shell.R;
import com.android.wm.shell.common.split.SplitScreenConstants.SplitPosition;
+import com.android.wm.shell.protolog.ShellProtoLogGroup;
import com.android.wm.shell.splitscreen.SplitScreenController;
import java.lang.annotation.Retention;
@@ -104,7 +109,9 @@
void start(DragSession session, InstanceId loggerSessionId) {
mLoggerSessionId = loggerSessionId;
mSession = session;
- RectF disallowHitRegion = (RectF) mSession.dragData.getExtra(EXTRA_DISALLOW_HIT_REGION);
+ RectF disallowHitRegion = mSession.appData != null
+ ? (RectF) mSession.appData.getExtra(EXTRA_DISALLOW_HIT_REGION)
+ : null;
if (disallowHitRegion == null) {
mDisallowHitRegion.setEmpty();
} else {
@@ -223,7 +230,7 @@
}
@VisibleForTesting
- void handleDrop(Target target, ClipData data) {
+ void handleDrop(Target target) {
if (target == null || !mTargets.contains(target)) {
return;
}
@@ -238,41 +245,81 @@
mSplitScreen.onDroppedToSplit(position, mLoggerSessionId);
}
- final ClipDescription description = data.getDescription();
- final Intent dragData = mSession.dragData;
- startClipDescription(description, dragData, position);
+ if (mSession.appData != null) {
+ launchApp(mSession, position);
+ } else {
+ launchIntent(mSession, position);
+ }
}
- private void startClipDescription(ClipDescription description, Intent intent,
- @SplitPosition int position) {
+ /**
+ * Launches an app provided by SysUI.
+ */
+ private void launchApp(DragSession session, @SplitPosition int position) {
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_DRAG_AND_DROP, "Launching app data at position=%d",
+ position);
+ final ClipDescription description = session.getClipDescription();
final boolean isTask = description.hasMimeType(MIMETYPE_APPLICATION_TASK);
final boolean isShortcut = description.hasMimeType(MIMETYPE_APPLICATION_SHORTCUT);
final ActivityOptions baseActivityOpts = ActivityOptions.makeBasic();
baseActivityOpts.setDisallowEnterPictureInPictureWhileLaunching(true);
final Bundle opts = baseActivityOpts.toBundle();
- if (intent.hasExtra(EXTRA_ACTIVITY_OPTIONS)) {
- opts.putAll(intent.getBundleExtra(EXTRA_ACTIVITY_OPTIONS));
+ if (session.appData.hasExtra(EXTRA_ACTIVITY_OPTIONS)) {
+ opts.putAll(session.appData.getBundleExtra(EXTRA_ACTIVITY_OPTIONS));
}
// Put BAL flags to avoid activity start aborted.
opts.putBoolean(KEY_PENDING_INTENT_BACKGROUND_ACTIVITY_ALLOWED, true);
opts.putBoolean(KEY_PENDING_INTENT_BACKGROUND_ACTIVITY_ALLOWED_BY_PERMISSION, true);
- final UserHandle user = intent.getParcelableExtra(EXTRA_USER);
+ final UserHandle user = session.appData.getParcelableExtra(EXTRA_USER);
if (isTask) {
- final int taskId = intent.getIntExtra(EXTRA_TASK_ID, INVALID_TASK_ID);
+ final int taskId = session.appData.getIntExtra(EXTRA_TASK_ID, INVALID_TASK_ID);
mStarter.startTask(taskId, position, opts);
} else if (isShortcut) {
- final String packageName = intent.getStringExtra(EXTRA_PACKAGE_NAME);
- final String id = intent.getStringExtra(EXTRA_SHORTCUT_ID);
+ final String packageName = session.appData.getStringExtra(EXTRA_PACKAGE_NAME);
+ final String id = session.appData.getStringExtra(EXTRA_SHORTCUT_ID);
mStarter.startShortcut(packageName, id, position, opts, user);
} else {
- final PendingIntent launchIntent = intent.getParcelableExtra(EXTRA_PENDING_INTENT);
+ final PendingIntent launchIntent =
+ session.appData.getParcelableExtra(EXTRA_PENDING_INTENT);
+ if (Build.IS_DEBUGGABLE) {
+ if (launchIntent.isImmutable()) {
+ throw new IllegalStateException("Expected immutable app pending intent from "
+ + "SysUI");
+ } else if (!user.equals(launchIntent.getCreatorUserHandle())) {
+ throw new IllegalStateException("Expected app intent's EXTRA_USER to match "
+ + "pending intent user");
+ }
+ }
mStarter.startIntent(launchIntent, user.getIdentifier(), null /* fillIntent */,
position, opts);
}
}
/**
+ * Launches an intent sender provided by an application.
+ */
+ private void launchIntent(DragSession session, @SplitPosition int position) {
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_DRAG_AND_DROP, "Launching intent at position=%d",
+ position);
+ final ActivityOptions baseActivityOpts = ActivityOptions.makeBasic();
+ baseActivityOpts.setDisallowEnterPictureInPictureWhileLaunching(true);
+ // TODO(b/255649902): Rework this so that SplitScreenController can always use the options
+ // instead of a fillInIntent since it's assuming that the PendingIntent is mutable
+ baseActivityOpts.setPendingIntentLaunchFlags(FLAG_ACTIVITY_NEW_TASK
+ | FLAG_ACTIVITY_MULTIPLE_TASK);
+
+ final Bundle opts = baseActivityOpts.toBundle();
+ // Put BAL flags to avoid activity start aborted.
+ opts.putBoolean(KEY_PENDING_INTENT_BACKGROUND_ACTIVITY_ALLOWED, true);
+ opts.putBoolean(KEY_PENDING_INTENT_BACKGROUND_ACTIVITY_ALLOWED_BY_PERMISSION, true);
+
+ mStarter.startIntent(session.launchableIntent,
+ session.launchableIntent.getCreatorUserHandle().getIdentifier(),
+ null /* fillIntent */, position, opts);
+ }
+
+ /**
* Interface for actually committing the task launches.
*/
public interface Starter {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragLayout.java b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragLayout.java
index 619f624..ecb53dc 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragLayout.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragLayout.java
@@ -22,6 +22,8 @@
import static android.content.pm.ActivityInfo.CONFIG_ASSETS_PATHS;
import static android.content.pm.ActivityInfo.CONFIG_UI_MODE;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
+import static android.view.ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME;
+import static android.view.ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION;
import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_BOTTOM_OR_RIGHT;
import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_TOP_OR_LEFT;
@@ -38,12 +40,15 @@
import android.app.StatusBarManager;
import android.content.Context;
import android.content.res.Configuration;
+import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Insets;
import android.graphics.Rect;
+import android.graphics.Region;
import android.graphics.drawable.Drawable;
import android.view.DragEvent;
import android.view.SurfaceControl;
+import android.view.ViewTreeObserver;
import android.view.WindowInsets;
import android.view.WindowInsets.Type;
import android.widget.LinearLayout;
@@ -65,7 +70,8 @@
/**
* Coordinates the visible drop targets for the current drag within a single display.
*/
-public class DragLayout extends LinearLayout {
+public class DragLayout extends LinearLayout
+ implements ViewTreeObserver.OnComputeInternalInsetsListener {
// While dragging the status bar is hidden.
private static final int HIDE_STATUS_BAR_FLAGS = StatusBarManager.DISABLE_NOTIFICATION_ICONS
@@ -90,7 +96,9 @@
private int mDisplayMargin;
private int mDividerSize;
+ private int mLaunchIntentEdgeMargin;
private Insets mInsets = Insets.NONE;
+ private Region mTouchableRegion;
private boolean mIsShowing;
private boolean mHasDropped;
@@ -106,10 +114,11 @@
mStatusBarManager = context.getSystemService(StatusBarManager.class);
mLastConfiguration.setTo(context.getResources().getConfiguration());
- mDisplayMargin = context.getResources().getDimensionPixelSize(
- R.dimen.drop_layout_display_margin);
- mDividerSize = context.getResources().getDimensionPixelSize(
- R.dimen.split_divider_bar_width);
+ final Resources res = context.getResources();
+ mDisplayMargin = res.getDimensionPixelSize(R.dimen.drop_layout_display_margin);
+ mDividerSize = res.getDimensionPixelSize(R.dimen.split_divider_bar_width);
+ mLaunchIntentEdgeMargin =
+ res.getDimensionPixelSize(R.dimen.drag_launchable_intent_edge_margin);
// Always use LTR because we assume dropZoneView1 is on the left and 2 is on the right when
// showing the highlight.
@@ -131,6 +140,66 @@
}
@Override
+ protected void onAttachedToWindow() {
+ super.onAttachedToWindow();
+ mTouchableRegion = Region.obtain();
+ getViewTreeObserver().addOnComputeInternalInsetsListener(this);
+ }
+
+ @Override
+ protected void onDetachedFromWindow() {
+ super.onDetachedFromWindow();
+ getViewTreeObserver().removeOnComputeInternalInsetsListener(this);
+ mTouchableRegion.recycle();
+ }
+
+ @Override
+ public void onComputeInternalInsets(ViewTreeObserver.InternalInsetsInfo inOutInfo) {
+ if (mSession != null && mSession.launchableIntent != null) {
+ inOutInfo.touchableRegion.set(mTouchableRegion);
+ inOutInfo.setTouchableInsets(TOUCHABLE_INSETS_REGION);
+ }
+ }
+
+ @Override
+ protected void onLayout(boolean changed, int l, int t, int r, int b) {
+ super.onLayout(changed, l, t, r, b);
+ updateTouchableRegion();
+ }
+
+ /**
+ * Updates the touchable region, this should be called after any configuration changes have
+ * been applied.
+ */
+ private void updateTouchableRegion() {
+ mTouchableRegion.setEmpty();
+ if (mSession != null && mSession.launchableIntent != null) {
+ final int width = getMeasuredWidth();
+ final int height = getMeasuredHeight();
+ if (mIsLeftRightSplit) {
+ mTouchableRegion.union(
+ new Rect(0, 0, mInsets.left + mLaunchIntentEdgeMargin, height));
+ mTouchableRegion.union(
+ new Rect(width - mInsets.right - mLaunchIntentEdgeMargin, 0, width,
+ height));
+ } else {
+ mTouchableRegion.union(
+ new Rect(0, 0, width, mInsets.top + mLaunchIntentEdgeMargin));
+ mTouchableRegion.union(
+ new Rect(0, height - mInsets.bottom - mLaunchIntentEdgeMargin, width,
+ height));
+ }
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_DRAG_AND_DROP,
+ "Updating drag layout width=%d height=%d touchable region=%s",
+ width, height, mTouchableRegion);
+
+ // Reapply insets to update the touchable region
+ requestApplyInsets();
+ }
+ }
+
+
+ @Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
mInsets = insets.getInsets(Type.tappableElement() | Type.displayCutout());
recomputeDropTargets();
@@ -164,6 +233,7 @@
mDropZoneView2.onThemeChange();
}
mLastConfiguration.setTo(newConfig);
+ requestLayout();
}
private void updateContainerMarginsForSingleTask() {
@@ -242,6 +312,7 @@
mSplitScreenController.getStageBounds(topOrLeftBounds, bottomOrRightBounds);
updateDropZoneSizes(topOrLeftBounds, bottomOrRightBounds);
}
+ requestLayout();
}
private void updateDropZoneSizesForSingleTask() {
@@ -392,7 +463,7 @@
mHasDropped = true;
// Process the drop
- mPolicy.handleDrop(mCurrentTarget, event.getClipData());
+ mPolicy.handleDrop(mCurrentTarget);
// Start animating the drop UI out with the drag surface
hide(event, dropCompleteCallback);
@@ -505,5 +576,7 @@
pw.println(innerPrefix + "mIsShowing=" + mIsShowing);
pw.println(innerPrefix + "mHasDropped=" + mHasDropped);
pw.println(innerPrefix + "mCurrentTarget=" + mCurrentTarget);
+ pw.println(innerPrefix + "mInsets=" + mInsets);
+ pw.println(innerPrefix + "mTouchableRegion=" + mTouchableRegion);
}
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragSession.java b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragSession.java
index 353d702..8f1bc59 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragSession.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragSession.java
@@ -21,12 +21,15 @@
import android.app.ActivityManager;
import android.app.ActivityTaskManager;
+import android.app.PendingIntent;
import android.app.WindowConfiguration;
import android.content.ClipData;
-import android.content.Context;
+import android.content.ClipDescription;
import android.content.Intent;
import android.content.pm.ActivityInfo;
+import androidx.annotation.Nullable;
+
import com.android.wm.shell.common.DisplayLayout;
import java.util.List;
@@ -39,7 +42,18 @@
private final ClipData mInitialDragData;
final DisplayLayout displayLayout;
- Intent dragData;
+ // The activity info associated with the activity in the appData or the launchableIntent
+ @Nullable
+ ActivityInfo activityInfo;
+ // The intent bundle that includes data about an app-type drag that is started by
+ // Launcher/SysUI. Only one of appDragData OR launchableIntent will be non-null for a session.
+ @Nullable
+ Intent appData;
+ // A launchable intent that is specified in the ClipData directly.
+ // Only one of appDragData OR launchableIntent will be non-null for a session.
+ @Nullable
+ PendingIntent launchableIntent;
+ // Stores the current running task at the time that the drag was initiated
ActivityManager.RunningTaskInfo runningTaskInfo;
@WindowConfiguration.WindowingMode
int runningTaskWinMode = WINDOWING_MODE_UNDEFINED;
@@ -47,7 +61,7 @@
int runningTaskActType = ACTIVITY_TYPE_STANDARD;
boolean dragItemSupportsSplitscreen;
- DragSession(Context context, ActivityTaskManager activityTaskManager,
+ DragSession(ActivityTaskManager activityTaskManager,
DisplayLayout dispLayout, ClipData data) {
mActivityTaskManager = activityTaskManager;
mInitialDragData = data;
@@ -55,6 +69,14 @@
}
/**
+ * Returns the clip description associated with the drag.
+ * @return
+ */
+ ClipDescription getClipDescription() {
+ return mInitialDragData.getDescription();
+ }
+
+ /**
* Updates the session data based on the current state of the system.
*/
void update() {
@@ -67,9 +89,11 @@
runningTaskActType = task.getActivityType();
}
- final ActivityInfo info = mInitialDragData.getItemAt(0).getActivityInfo();
- dragItemSupportsSplitscreen = info == null
- || ActivityInfo.isResizeableMode(info.resizeMode);
- dragData = mInitialDragData.getItemAt(0).getIntent();
+ activityInfo = mInitialDragData.getItemAt(0).getActivityInfo();
+ // TODO: This should technically check & respect config_supportsNonResizableMultiWindow
+ dragItemSupportsSplitscreen = activityInfo == null
+ || ActivityInfo.isResizeableMode(activityInfo.resizeMode);
+ appData = mInitialDragData.getItemAt(0).getIntent();
+ launchableIntent = DragUtils.getLaunchIntent(mInitialDragData);
}
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragUtils.java b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragUtils.java
index f7bcc94..24f8e18 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragUtils.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/draganddrop/DragUtils.java
@@ -36,8 +36,21 @@
* Returns whether we can handle this particular drag.
*/
public static boolean canHandleDrag(DragEvent event) {
- return event.getClipData().getItemCount() > 0
- && (isAppDrag(event.getClipDescription()));
+ if (event.getClipData().getItemCount() <= 0) {
+ // No clip data, ignore this drag
+ return false;
+ }
+ if (isAppDrag(event.getClipDescription())) {
+ // Clip data contains an app drag initiated from SysUI, handle it
+ return true;
+ }
+ if (com.android.window.flags.Flags.delegateUnhandledDrags()
+ && getLaunchIntent(event) != null) {
+ // Clip data contains a launchable intent drag, handle it
+ return true;
+ }
+ // Otherwise ignore
+ return false;
}
/**
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenController.java
index 53dd981..32be419 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenController.java
@@ -806,6 +806,9 @@
@Override
public void startIntent(PendingIntent intent, int userId1, @Nullable Intent fillInIntent,
@SplitPosition int position, @Nullable Bundle options) {
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_SPLIT_SCREEN,
+ "startIntent(): intent=%s user=%d fillInIntent=%s position=%d", intent, userId1,
+ fillInIntent, position);
// Flag this as a no-user-action launch to prevent sending user leaving event to the current
// top activity since it's going to be put into another side of the split. This prevents the
// current top activity from going into pip mode due to user leaving event.
@@ -824,6 +827,8 @@
.map(recentTasks -> recentTasks.findTaskInBackground(component, userId1))
.orElse(null);
if (taskInfo != null) {
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_SPLIT_SCREEN,
+ "Found suitable background task=%s", taskInfo);
if (ENABLE_SHELL_TRANSITIONS) {
mStageCoordinator.startTask(taskInfo.taskId, position, options);
} else {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java
index c70a821..9130edf 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java
@@ -470,10 +470,12 @@
}
final float cornerRadius;
- if (a.hasRoundedCorners() && isTask) {
- // hasRoundedCorners is currently only enabled for tasks
+ if (a.hasRoundedCorners()) {
+ final int displayId = isTask ? change.getTaskInfo().displayId
+ : info.getRoot(TransitionUtil.rootIndexFor(change, info))
+ .getDisplayId();
final Context displayContext =
- mDisplayController.getDisplayContext(change.getTaskInfo().displayId);
+ mDisplayController.getDisplayContext(displayId);
cornerRadius = displayContext == null ? 0
: ScreenDecorationsUtils.getWindowCornerRadius(displayContext);
} else {
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/draganddrop/DragAndDropPolicyTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/draganddrop/DragAndDropPolicyTest.java
index 1b347e0..5dd9d8a 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/draganddrop/DragAndDropPolicyTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/draganddrop/DragAndDropPolicyTest.java
@@ -22,9 +22,11 @@
import static android.content.ClipDescription.MIMETYPE_APPLICATION_ACTIVITY;
import static android.content.ClipDescription.MIMETYPE_APPLICATION_SHORTCUT;
import static android.content.ClipDescription.MIMETYPE_APPLICATION_TASK;
+import static android.content.ClipDescription.MIMETYPE_TEXT_INTENT;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession;
import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_BOTTOM_OR_RIGHT;
import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_TOP_OR_LEFT;
import static com.android.wm.shell.common.split.SplitScreenConstants.SPLIT_POSITION_UNDEFINED;
@@ -46,6 +48,8 @@
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.mockito.quality.Strictness.LENIENT;
import android.app.ActivityManager;
import android.app.ActivityTaskManager;
@@ -61,6 +65,7 @@
import android.graphics.Insets;
import android.os.RemoteException;
import android.view.DisplayInfo;
+import android.view.DragEvent;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
@@ -70,12 +75,15 @@
import com.android.wm.shell.common.DisplayLayout;
import com.android.wm.shell.draganddrop.DragAndDropPolicy.Target;
import com.android.wm.shell.splitscreen.SplitScreenController;
+import com.android.wm.shell.startingsurface.TaskSnapshotWindow;
+import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.mockito.MockitoSession;
import java.util.ArrayList;
import java.util.Collections;
@@ -107,6 +115,7 @@
private DragAndDropPolicy mPolicy;
private ClipData mActivityClipData;
+ private ClipData mLaunchableIntentClipData;
private ClipData mNonResizeableActivityClipData;
private ClipData mTaskClipData;
private ClipData mShortcutClipData;
@@ -115,9 +124,16 @@
private ActivityManager.RunningTaskInfo mFullscreenAppTask;
private ActivityManager.RunningTaskInfo mNonResizeableFullscreenAppTask;
+ private MockitoSession mMockitoSession;
+
@Before
public void setUp() throws RemoteException {
MockitoAnnotations.initMocks(this);
+ mMockitoSession = mockitoSession()
+ .strictness(LENIENT)
+ .mockStatic(DragUtils.class)
+ .startMocking();
+ when(DragUtils.canHandleDrag(any())).thenReturn(true);
Resources res = mock(Resources.class);
Configuration config = new Configuration();
@@ -134,11 +150,12 @@
mInsets = Insets.of(0, 0, 0, 0);
mPolicy = spy(new DragAndDropPolicy(mContext, mSplitScreenStarter, mSplitScreenStarter));
- mActivityClipData = createClipData(MIMETYPE_APPLICATION_ACTIVITY);
- mNonResizeableActivityClipData = createClipData(MIMETYPE_APPLICATION_ACTIVITY);
+ mActivityClipData = createAppClipData(MIMETYPE_APPLICATION_ACTIVITY);
+ mLaunchableIntentClipData = createIntentClipData();
+ mNonResizeableActivityClipData = createAppClipData(MIMETYPE_APPLICATION_ACTIVITY);
setClipDataResizeable(mNonResizeableActivityClipData, false);
- mTaskClipData = createClipData(MIMETYPE_APPLICATION_TASK);
- mShortcutClipData = createClipData(MIMETYPE_APPLICATION_SHORTCUT);
+ mTaskClipData = createAppClipData(MIMETYPE_APPLICATION_TASK);
+ mShortcutClipData = createAppClipData(MIMETYPE_APPLICATION_SHORTCUT);
mHomeTask = createTaskInfo(WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME);
mFullscreenAppTask = createTaskInfo(WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
@@ -149,10 +166,15 @@
setRunningTask(mFullscreenAppTask);
}
+ @After
+ public void tearDown() {
+ mMockitoSession.finishMocking();
+ }
+
/**
- * Creates a clip data that is by default resizeable.
+ * Creates an app-based clip data that is by default resizeable.
*/
- private ClipData createClipData(String mimeType) {
+ private ClipData createAppClipData(String mimeType) {
ClipDescription clipDescription = new ClipDescription(mimeType, new String[] { mimeType });
Intent i = new Intent();
switch (mimeType) {
@@ -164,7 +186,9 @@
i.putExtra(Intent.EXTRA_TASK_ID, 12345);
break;
case MIMETYPE_APPLICATION_ACTIVITY:
- i.putExtra(ClipDescription.EXTRA_PENDING_INTENT, mock(PendingIntent.class));
+ final PendingIntent pi = mock(PendingIntent.class);
+ doReturn(android.os.Process.myUserHandle()).when(pi).getCreatorUserHandle();
+ i.putExtra(ClipDescription.EXTRA_PENDING_INTENT, pi);
break;
}
i.putExtra(Intent.EXTRA_USER, android.os.Process.myUserHandle());
@@ -175,6 +199,22 @@
return data;
}
+ /**
+ * Creates an intent-based clip data that is by default resizeable.
+ */
+ private ClipData createIntentClipData() {
+ ClipDescription clipDescription = new ClipDescription("Intent",
+ new String[] { MIMETYPE_TEXT_INTENT });
+ PendingIntent intent = mock(PendingIntent.class);
+ when(intent.getCreatorUserHandle()).thenReturn(android.os.Process.myUserHandle());
+ ClipData.Item item = new ClipData.Item.Builder()
+ .setIntentSender(intent.getIntentSender())
+ .build();
+ ClipData data = new ClipData(clipDescription, item);
+ when(DragUtils.getLaunchIntent((ClipData) any())).thenReturn(intent);
+ return data;
+ }
+
private ActivityManager.RunningTaskInfo createTaskInfo(int winMode, int actType) {
ActivityManager.RunningTaskInfo info = new ActivityManager.RunningTaskInfo();
info.configuration.windowConfiguration.setActivityType(actType);
@@ -204,58 +244,85 @@
@Test
public void testDragAppOverFullscreenHome_expectOnlyFullscreenTarget() {
+ dragOverFullscreenHome_expectOnlyFullscreenTarget(mActivityClipData);
+ }
+
+ @Test
+ public void testDragAppOverFullscreenApp_expectSplitScreenTargets() {
+ dragOverFullscreenApp_expectSplitScreenTargets(mActivityClipData);
+ }
+
+ @Test
+ public void testDragAppOverFullscreenAppPhone_expectVerticalSplitScreenTargets() {
+ dragOverFullscreenAppPhone_expectVerticalSplitScreenTargets(mActivityClipData);
+ }
+
+ @Test
+ public void testDragIntentOverFullscreenHome_expectOnlyFullscreenTarget() {
+ dragOverFullscreenHome_expectOnlyFullscreenTarget(mLaunchableIntentClipData);
+ }
+
+ @Test
+ public void testDragIntentOverFullscreenApp_expectSplitScreenTargets() {
+ dragOverFullscreenApp_expectSplitScreenTargets(mLaunchableIntentClipData);
+ }
+
+ @Test
+ public void testDragIntentOverFullscreenAppPhone_expectVerticalSplitScreenTargets() {
+ dragOverFullscreenAppPhone_expectVerticalSplitScreenTargets(mLaunchableIntentClipData);
+ }
+
+ private void dragOverFullscreenHome_expectOnlyFullscreenTarget(ClipData data) {
doReturn(true).when(mSplitScreenStarter).isLeftRightSplit();
setRunningTask(mHomeTask);
- DragSession dragSession = new DragSession(mContext, mActivityTaskManager,
- mLandscapeDisplayLayout, mActivityClipData);
+ DragSession dragSession = new DragSession(mActivityTaskManager,
+ mLandscapeDisplayLayout, data);
dragSession.update();
mPolicy.start(dragSession, mLoggerSessionId);
ArrayList<Target> targets = assertExactTargetTypes(
mPolicy.getTargets(mInsets), TYPE_FULLSCREEN);
- mPolicy.handleDrop(filterTargetByType(targets, TYPE_FULLSCREEN), mActivityClipData);
+ mPolicy.handleDrop(filterTargetByType(targets, TYPE_FULLSCREEN));
verify(mSplitScreenStarter).startIntent(any(), anyInt(), any(),
eq(SPLIT_POSITION_UNDEFINED), any());
}
- @Test
- public void testDragAppOverFullscreenApp_expectSplitScreenTargets() {
+ private void dragOverFullscreenApp_expectSplitScreenTargets(ClipData data) {
doReturn(true).when(mSplitScreenStarter).isLeftRightSplit();
setRunningTask(mFullscreenAppTask);
- DragSession dragSession = new DragSession(mContext, mActivityTaskManager,
- mLandscapeDisplayLayout, mActivityClipData);
+ DragSession dragSession = new DragSession(mActivityTaskManager,
+ mLandscapeDisplayLayout, data);
dragSession.update();
mPolicy.start(dragSession, mLoggerSessionId);
ArrayList<Target> targets = assertExactTargetTypes(
mPolicy.getTargets(mInsets), TYPE_SPLIT_LEFT, TYPE_SPLIT_RIGHT);
- mPolicy.handleDrop(filterTargetByType(targets, TYPE_SPLIT_LEFT), mActivityClipData);
+ mPolicy.handleDrop(filterTargetByType(targets, TYPE_SPLIT_LEFT));
verify(mSplitScreenStarter).startIntent(any(), anyInt(), any(),
eq(SPLIT_POSITION_TOP_OR_LEFT), any());
reset(mSplitScreenStarter);
- mPolicy.handleDrop(filterTargetByType(targets, TYPE_SPLIT_RIGHT), mActivityClipData);
+ mPolicy.handleDrop(filterTargetByType(targets, TYPE_SPLIT_RIGHT));
verify(mSplitScreenStarter).startIntent(any(), anyInt(), any(),
eq(SPLIT_POSITION_BOTTOM_OR_RIGHT), any());
}
- @Test
- public void testDragAppOverFullscreenAppPhone_expectVerticalSplitScreenTargets() {
+ private void dragOverFullscreenAppPhone_expectVerticalSplitScreenTargets(ClipData data) {
doReturn(false).when(mSplitScreenStarter).isLeftRightSplit();
setRunningTask(mFullscreenAppTask);
- DragSession dragSession = new DragSession(mContext, mActivityTaskManager,
- mPortraitDisplayLayout, mActivityClipData);
+ DragSession dragSession = new DragSession(mActivityTaskManager,
+ mPortraitDisplayLayout, data);
dragSession.update();
mPolicy.start(dragSession, mLoggerSessionId);
ArrayList<Target> targets = assertExactTargetTypes(
mPolicy.getTargets(mInsets), TYPE_SPLIT_TOP, TYPE_SPLIT_BOTTOM);
- mPolicy.handleDrop(filterTargetByType(targets, TYPE_SPLIT_TOP), mActivityClipData);
+ mPolicy.handleDrop(filterTargetByType(targets, TYPE_SPLIT_TOP));
verify(mSplitScreenStarter).startIntent(any(), anyInt(), any(),
eq(SPLIT_POSITION_TOP_OR_LEFT), any());
reset(mSplitScreenStarter);
- mPolicy.handleDrop(filterTargetByType(targets, TYPE_SPLIT_BOTTOM), mActivityClipData);
+ mPolicy.handleDrop(filterTargetByType(targets, TYPE_SPLIT_BOTTOM));
verify(mSplitScreenStarter).startIntent(any(), anyInt(), any(),
eq(SPLIT_POSITION_BOTTOM_OR_RIGHT), any());
}
@@ -263,7 +330,7 @@
@Test
public void testTargetHitRects() {
setRunningTask(mFullscreenAppTask);
- DragSession dragSession = new DragSession(mContext, mActivityTaskManager,
+ DragSession dragSession = new DragSession(mActivityTaskManager,
mLandscapeDisplayLayout, mActivityClipData);
dragSession.update();
mPolicy.start(dragSession, mLoggerSessionId);
diff --git a/media/java/android/media/AudioFormat.java b/media/java/android/media/AudioFormat.java
index ea136ed..c90c441 100644
--- a/media/java/android/media/AudioFormat.java
+++ b/media/java/android/media/AudioFormat.java
@@ -1079,7 +1079,7 @@
* @return one of the values that can be set in {@link Builder#setEncoding(int)} or
* {@link AudioFormat#ENCODING_INVALID} if not set.
*/
- public @Encoding int getEncoding() {
+ public @EncodingCanBeInvalid int getEncoding() {
return mEncoding;
}
@@ -1486,6 +1486,44 @@
@Retention(RetentionPolicy.SOURCE)
public @interface Encoding {}
+ /** @hide same as @Encoding, but adding ENCODING_INVALID */
+ @IntDef(flag = false, prefix = "ENCODING", value = {
+ ENCODING_INVALID,
+ ENCODING_DEFAULT,
+ ENCODING_PCM_16BIT,
+ ENCODING_PCM_8BIT,
+ ENCODING_PCM_FLOAT,
+ ENCODING_AC3,
+ ENCODING_E_AC3,
+ ENCODING_DTS,
+ ENCODING_DTS_HD,
+ ENCODING_MP3,
+ ENCODING_AAC_LC,
+ ENCODING_AAC_HE_V1,
+ ENCODING_AAC_HE_V2,
+ ENCODING_IEC61937,
+ ENCODING_DOLBY_TRUEHD,
+ ENCODING_AAC_ELD,
+ ENCODING_AAC_XHE,
+ ENCODING_AC4,
+ ENCODING_E_AC3_JOC,
+ ENCODING_DOLBY_MAT,
+ ENCODING_OPUS,
+ ENCODING_PCM_24BIT_PACKED,
+ ENCODING_PCM_32BIT,
+ ENCODING_MPEGH_BL_L3,
+ ENCODING_MPEGH_BL_L4,
+ ENCODING_MPEGH_LC_L3,
+ ENCODING_MPEGH_LC_L4,
+ ENCODING_DTS_UHD_P1,
+ ENCODING_DRA,
+ ENCODING_DTS_HD_MA,
+ ENCODING_DTS_UHD_P2,
+ ENCODING_DSD }
+ )
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface EncodingCanBeInvalid {}
+
/** @hide */
public static final int[] SURROUND_SOUND_ENCODING = {
ENCODING_AC3,
diff --git a/packages/CrashRecovery/framework/Android.bp b/packages/CrashRecovery/framework/Android.bp
index c0d93531..9480327 100644
--- a/packages/CrashRecovery/framework/Android.bp
+++ b/packages/CrashRecovery/framework/Android.bp
@@ -3,7 +3,7 @@
module_type: "filegroup",
config_namespace: "ANDROID",
bool_variables: [
- "move_crashrecovery_files",
+ "crashrecovery_files_in_platform",
],
properties: [
"srcs",
@@ -12,14 +12,13 @@
platform_filegroup {
name: "framework-crashrecovery-sources",
- srcs: [
- "java/**/*.java",
- "java/**/*.aidl",
- ],
soong_config_variables: {
- // if the flag is enabled, then files would be moved to module
- move_crashrecovery_files: {
- srcs: [],
+ // if this flag is enabled, then files are part of platform
+ crashrecovery_files_in_platform: {
+ srcs: [
+ "java/**/*.java",
+ "java/**/*.aidl",
+ ],
},
},
path: "java",
@@ -31,7 +30,7 @@
module_type: "filegroup",
config_namespace: "ANDROID",
bool_variables: [
- "move_crashrecovery_files",
+ "crashrecovery_files_in_module",
],
properties: [
"srcs",
@@ -40,10 +39,9 @@
module_filegroup {
name: "framework-crashrecovery-module-sources",
- srcs: [],
soong_config_variables: {
- // if the flag is enabled, then files would be moved to module
- move_crashrecovery_files: {
+ // if this flag is enabled, then files are part of module
+ crashrecovery_files_in_module: {
srcs: [
"java/**/*.java",
"java/**/*.aidl",
diff --git a/packages/CrashRecovery/services/Android.bp b/packages/CrashRecovery/services/Android.bp
index ab10b5a..961b41f 100644
--- a/packages/CrashRecovery/services/Android.bp
+++ b/packages/CrashRecovery/services/Android.bp
@@ -3,7 +3,7 @@
module_type: "filegroup",
config_namespace: "ANDROID",
bool_variables: [
- "move_crashrecovery_files",
+ "crashrecovery_files_in_platform",
],
properties: [
"srcs",
@@ -12,15 +12,14 @@
platform_filegroup {
name: "services-crashrecovery-sources",
- srcs: [
- "java/**/*.java",
- "java/**/*.aidl",
- ":statslog-crashrecovery-java-gen",
- ],
soong_config_variables: {
- // if the flag is enabled, then files would be moved to module
- move_crashrecovery_files: {
- srcs: [],
+ // if this flag is enabled, then files are part of platform
+ crashrecovery_files_in_platform: {
+ srcs: [
+ "java/**/*.java",
+ "java/**/*.aidl",
+ ":statslog-crashrecovery-java-gen",
+ ],
},
},
visibility: ["//frameworks/base:__subpackages__"],
@@ -31,7 +30,7 @@
module_type: "filegroup",
config_namespace: "ANDROID",
bool_variables: [
- "move_crashrecovery_files",
+ "crashrecovery_files_in_module",
],
properties: [
"srcs",
@@ -40,10 +39,9 @@
module_filegroup {
name: "services-crashrecovery-module-sources",
- srcs: [],
soong_config_variables: {
- // if the flag is enabled, then files would be moved to module
- move_crashrecovery_files: {
+ // if this flag is enabled, then files are part of module
+ crashrecovery_files_in_module: {
srcs: [
"java/**/*.java",
"java/**/*.aidl",
diff --git a/packages/CrashRecovery/services/java/com/android/server/PackageWatchdog.java b/packages/CrashRecovery/services/java/com/android/server/PackageWatchdog.java
index ce8fb65..5d71b7d 100644
--- a/packages/CrashRecovery/services/java/com/android/server/PackageWatchdog.java
+++ b/packages/CrashRecovery/services/java/com/android/server/PackageWatchdog.java
@@ -38,13 +38,13 @@
import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.AtomicFile;
+import android.util.BackgroundThread;
import android.util.LongArrayQueue;
import android.util.Slog;
import android.util.Xml;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.os.BackgroundThread;
import com.android.internal.util.IndentingPrintWriter;
import com.android.internal.util.XmlUtils;
import com.android.modules.utils.TypedXmlPullParser;
diff --git a/packages/CrashRecovery/services/java/com/android/server/rollback/RollbackPackageHealthObserver.java b/packages/CrashRecovery/services/java/com/android/server/rollback/RollbackPackageHealthObserver.java
index 5fb47dd..0fb9327 100644
--- a/packages/CrashRecovery/services/java/com/android/server/rollback/RollbackPackageHealthObserver.java
+++ b/packages/CrashRecovery/services/java/com/android/server/rollback/RollbackPackageHealthObserver.java
@@ -75,6 +75,9 @@
private static final int PERSISTENT_MASK = ApplicationInfo.FLAG_PERSISTENT
| ApplicationInfo.FLAG_SYSTEM;
+ private static final String PROP_DISABLE_HIGH_IMPACT_ROLLBACK_FLAG =
+ "persist.device_config.configuration.disable_high_impact_rollback";
+
private final Context mContext;
private final Handler mHandler;
private final ApexManager mApexManager;
@@ -605,6 +608,10 @@
// Apply all available low impact rollbacks.
mHandler.post(() -> rollbackAllLowImpact(availableRollbacks, rollbackReason));
} else if (minRollbackImpactLevel == PackageManager.ROLLBACK_USER_IMPACT_HIGH) {
+ // Check disable_high_impact_rollback device config before performing rollback
+ if (SystemProperties.getBoolean(PROP_DISABLE_HIGH_IMPACT_ROLLBACK_FLAG, false)) {
+ return;
+ }
// Rollback one package at a time. If that doesn't resolve the issue, rollback
// next with same impact level.
mHandler.post(() -> rollbackHighImpact(availableRollbacks, rollbackReason));
@@ -718,7 +725,9 @@
impact = PackageHealthObserverImpact.USER_IMPACT_LEVEL_70;
break;
case PackageManager.ROLLBACK_USER_IMPACT_HIGH:
- impact = PackageHealthObserverImpact.USER_IMPACT_LEVEL_90;
+ if (!SystemProperties.getBoolean(PROP_DISABLE_HIGH_IMPACT_ROLLBACK_FLAG, false)) {
+ impact = PackageHealthObserverImpact.USER_IMPACT_LEVEL_90;
+ }
break;
default:
impact = PackageHealthObserverImpact.USER_IMPACT_LEVEL_0;
diff --git a/packages/CrashRecovery/services/java/com/android/util/BackgroundThread.java b/packages/CrashRecovery/services/java/com/android/util/BackgroundThread.java
new file mode 100644
index 0000000..a6ae68f
--- /dev/null
+++ b/packages/CrashRecovery/services/java/com/android/util/BackgroundThread.java
@@ -0,0 +1,103 @@
+/*
+ * * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.util;
+
+import android.annotation.NonNull;
+import android.os.Handler;
+import android.os.HandlerThread;
+
+import com.android.internal.annotations.GuardedBy;
+
+import java.util.concurrent.Executor;
+
+/**
+ * Thread for asynchronous event processing. This thread is configured as
+ * {@link android.os.Process#THREAD_PRIORITY_BACKGROUND}, which means fewer CPU
+ * resources will be dedicated to it, and it will "have less chance of impacting
+ * the responsiveness of the user interface."
+ * <p>
+ * This thread is best suited for tasks that the user is not actively waiting
+ * for, or for tasks that the user expects to be executed eventually.
+ *
+ * @see com.android.internal.os.BackgroundThread
+ *
+ * TODO: b/326916057 depend on modules-utils-backgroundthread instead
+ * @hide
+ */
+public final class BackgroundThread extends HandlerThread {
+ private static final Object sLock = new Object();
+
+ @GuardedBy("sLock")
+ private static BackgroundThread sInstance;
+ @GuardedBy("sLock")
+ private static Handler sHandler;
+ @GuardedBy("sLock")
+ private static HandlerExecutor sHandlerExecutor;
+
+ private BackgroundThread() {
+ super(BackgroundThread.class.getName(), android.os.Process.THREAD_PRIORITY_BACKGROUND);
+ }
+
+ @GuardedBy("sLock")
+ private static void ensureThreadLocked() {
+ if (sInstance == null) {
+ sInstance = new BackgroundThread();
+ sInstance.start();
+ sHandler = new Handler(sInstance.getLooper());
+ sHandlerExecutor = new HandlerExecutor(sHandler);
+ }
+ }
+
+ /**
+ * Get the singleton instance of this class.
+ *
+ * @return the singleton instance of this class
+ */
+ @NonNull
+ public static BackgroundThread get() {
+ synchronized (sLock) {
+ ensureThreadLocked();
+ return sInstance;
+ }
+ }
+
+ /**
+ * Get the singleton {@link Handler} for this class.
+ *
+ * @return the singleton {@link Handler} for this class.
+ */
+ @NonNull
+ public static Handler getHandler() {
+ synchronized (sLock) {
+ ensureThreadLocked();
+ return sHandler;
+ }
+ }
+
+ /**
+ * Get the singleton {@link Executor} for this class.
+ *
+ * @return the singleton {@link Executor} for this class.
+ */
+ @NonNull
+ public static Executor getExecutor() {
+ synchronized (sLock) {
+ ensureThreadLocked();
+ return sHandlerExecutor;
+ }
+ }
+}
diff --git a/packages/CrashRecovery/services/java/com/android/util/HandlerExecutor.java b/packages/CrashRecovery/services/java/com/android/util/HandlerExecutor.java
new file mode 100644
index 0000000..948ebcca
--- /dev/null
+++ b/packages/CrashRecovery/services/java/com/android/util/HandlerExecutor.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.util;
+
+import android.annotation.NonNull;
+import android.os.Handler;
+
+import java.util.Objects;
+import java.util.concurrent.Executor;
+import java.util.concurrent.RejectedExecutionException;
+
+/**
+ * An adapter {@link Executor} that posts all executed tasks onto the given
+ * {@link Handler}.
+ *
+ * TODO: b/326916057 depend on modules-utils-backgroundthread instead
+ * @hide
+ */
+public class HandlerExecutor implements Executor {
+ private final Handler mHandler;
+
+ public HandlerExecutor(@NonNull Handler handler) {
+ mHandler = Objects.requireNonNull(handler);
+ }
+
+ @Override
+ public void execute(Runnable command) {
+ if (!mHandler.post(command)) {
+ throw new RejectedExecutionException(mHandler + " is shutting down");
+ }
+ }
+}
diff --git a/packages/CredentialManager/shared/src/com/android/credentialmanager/ktx/CredentialKtx.kt b/packages/CredentialManager/shared/src/com/android/credentialmanager/ktx/CredentialKtx.kt
index a5f227a..02320a1 100644
--- a/packages/CredentialManager/shared/src/com/android/credentialmanager/ktx/CredentialKtx.kt
+++ b/packages/CredentialManager/shared/src/com/android/credentialmanager/ktx/CredentialKtx.kt
@@ -127,10 +127,10 @@
userName = credentialEntry.username.toString(),
displayName = credentialEntry.displayName?.toString(),
icon = credentialEntry.icon.loadDrawable(context),
- shouldTintIcon = credentialEntry.isDefaultIcon,
+ shouldTintIcon = credentialEntry.hasDefaultIcon,
lastUsedTimeMillis = credentialEntry.lastUsedTime,
isAutoSelectable = credentialEntry.isAutoSelectAllowed &&
- credentialEntry.autoSelectAllowedFromOption,
+ credentialEntry.isAutoSelectAllowedFromOption,
)
)
}
@@ -148,10 +148,10 @@
userName = credentialEntry.username.toString(),
displayName = credentialEntry.displayName?.toString(),
icon = credentialEntry.icon.loadDrawable(context),
- shouldTintIcon = credentialEntry.isDefaultIcon,
+ shouldTintIcon = credentialEntry.hasDefaultIcon,
lastUsedTimeMillis = credentialEntry.lastUsedTime,
isAutoSelectable = credentialEntry.isAutoSelectAllowed &&
- credentialEntry.autoSelectAllowedFromOption,
+ credentialEntry.isAutoSelectAllowedFromOption,
)
)
}
@@ -170,10 +170,10 @@
userName = credentialEntry.title.toString(),
displayName = credentialEntry.subtitle?.toString(),
icon = credentialEntry.icon.loadDrawable(context),
- shouldTintIcon = credentialEntry.isDefaultIcon,
+ shouldTintIcon = credentialEntry.hasDefaultIcon,
lastUsedTimeMillis = credentialEntry.lastUsedTime,
isAutoSelectable = credentialEntry.isAutoSelectAllowed &&
- credentialEntry.autoSelectAllowedFromOption,
+ credentialEntry.isAutoSelectAllowedFromOption,
)
)
}
diff --git a/packages/CredentialManager/src/com/android/credentialmanager/autofill/CredentialAutofillService.kt b/packages/CredentialManager/src/com/android/credentialmanager/autofill/CredentialAutofillService.kt
index 0f17217..28c42fb 100644
--- a/packages/CredentialManager/src/com/android/credentialmanager/autofill/CredentialAutofillService.kt
+++ b/packages/CredentialManager/src/com/android/credentialmanager/autofill/CredentialAutofillService.kt
@@ -213,7 +213,7 @@
autofillIdToProvidersMap.forEach { (autofillId, providers) ->
validFillResponse = processProvidersForAutofillId(
filLRequest, autofillId, providers, entryIconMap, fillResponseBuilder,
- getCredResponse.pendingIntent)
+ getCredResponse.intent)
.or(validFillResponse)
}
if (!validFillResponse) {
@@ -229,7 +229,7 @@
providerDataList: ArrayList<GetCredentialProviderData>,
entryIconMap: Map<String, Icon>,
fillResponseBuilder: FillResponse.Builder,
- bottomSheetPendingIntent: PendingIntent?
+ bottomSheetIntent: Intent
): Boolean {
val providerList = GetFlowUtils.toProviderList(
providerDataList,
@@ -267,6 +267,8 @@
}
}
}
+ bottomSheetIntent.putExtra(
+ ProviderData.EXTRA_ENABLED_PROVIDER_DATA_LIST, providerDataList)
providerDisplayInfo.sortedUserNameToCredentialEntryList.forEach usernameLoop@{
val primaryEntry = it.sortedCredentialEntryList.first()
val pendingIntent = primaryEntry.pendingIntent
@@ -330,16 +332,16 @@
datasetAdded = true
i++
- if (i == lastDropdownDatasetIndex && bottomSheetPendingIntent != null) {
- addDropdownMoreOptionsPresentation(bottomSheetPendingIntent, autofillId,
+ if (i == lastDropdownDatasetIndex) {
+ addDropdownMoreOptionsPresentation(bottomSheetIntent, autofillId,
fillResponseBuilder)
}
}
val pinnedSpec = getLastInlinePresentationSpec(inlinePresentationSpecs,
inlinePresentationSpecsCount)
- if (datasetAdded && bottomSheetPendingIntent != null && pinnedSpec != null) {
- addPinnedInlineSuggestion(bottomSheetPendingIntent, pinnedSpec, autofillId,
- fillResponseBuilder, providerDataList)
+ if (datasetAdded && pinnedSpec != null) {
+ addPinnedInlineSuggestion(pinnedSpec, autofillId,
+ fillResponseBuilder, bottomSheetIntent)
}
return datasetAdded
}
@@ -370,13 +372,14 @@
}
private fun addDropdownMoreOptionsPresentation(
- bottomSheetPendingIntent: PendingIntent,
+ bottomSheetIntent: Intent,
autofillId: AutofillId,
fillResponseBuilder: FillResponse.Builder
) {
val presentationBuilder = Presentations.Builder()
.setMenuPresentation(
RemoteViewsFactory.createMoreSignInOptionsPresentation(this))
+ val pendingIntent = setUpBottomSheetPendingIntent(bottomSheetIntent)
fillResponseBuilder.addDataset(
Dataset.Builder()
@@ -385,7 +388,7 @@
Field.Builder().setPresentations(
presentationBuilder.build())
.build())
- .setAuthentication(bottomSheetPendingIntent.intentSender)
+ .setAuthentication(pendingIntent.intentSender)
.build()
)
}
@@ -401,37 +404,41 @@
}
private fun addPinnedInlineSuggestion(
- bottomSheetPendingIntent: PendingIntent,
spec: InlinePresentationSpec,
autofillId: AutofillId,
fillResponseBuilder: FillResponse.Builder,
- providerDataList: ArrayList<GetCredentialProviderData>
+ bottomSheetIntent: Intent
) {
+ val pendingIntent = setUpBottomSheetPendingIntent(bottomSheetIntent)
+
val dataSetBuilder = Dataset.Builder()
val sliceBuilder = InlineSuggestionUi
- .newContentBuilder(bottomSheetPendingIntent)
+ .newContentBuilder(pendingIntent)
.setStartIcon(Icon.createWithResource(this,
com.android.credentialmanager.R.drawable.more_horiz_24px))
val presentationBuilder = Presentations.Builder()
.setInlinePresentation(InlinePresentation(
sliceBuilder.build().slice, spec, /* pinned= */ true))
- val extrasIntent = Intent()
- extrasIntent.putExtra(ProviderData.EXTRA_ENABLED_PROVIDER_DATA_LIST, providerDataList)
-
fillResponseBuilder.addDataset(
dataSetBuilder
.setField(
autofillId,
Field.Builder().setPresentations(
- presentationBuilder.build())
- .build())
- .setAuthentication(bottomSheetPendingIntent.intentSender)
- .setCredentialFillInIntent(extrasIntent)
+ presentationBuilder.build()
+ ).build()
+ )
+ .setAuthentication(pendingIntent.intentSender)
.build()
)
}
+ private fun setUpBottomSheetPendingIntent(intent: Intent): PendingIntent {
+ intent.setAction(java.util.UUID.randomUUID().toString())
+ return PendingIntent.getActivity(this, /*requestCode=*/0, intent,
+ PendingIntent.FLAG_MUTABLE, /*options=*/null)
+ }
+
/**
* Maps Autofill Id to provider list. For example, passing in a provider info
*
diff --git a/packages/CredentialManager/src/com/android/credentialmanager/common/ui/BottomSheet.kt b/packages/CredentialManager/src/com/android/credentialmanager/common/ui/BottomSheet.kt
index d319e4c..a7b5c36 100644
--- a/packages/CredentialManager/src/com/android/credentialmanager/common/ui/BottomSheet.kt
+++ b/packages/CredentialManager/src/com/android/credentialmanager/common/ui/BottomSheet.kt
@@ -16,8 +16,15 @@
package com.android.credentialmanager.common.ui
+import android.credentials.flags.Flags
+import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.background
-import androidx.compose.foundation.layout.ColumnScope
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.wrapContentHeight
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
@@ -25,6 +32,7 @@
import androidx.compose.ui.graphics.Color
import com.android.compose.rememberSystemUiController
import com.android.compose.theme.LocalAndroidColorScheme
+import androidx.compose.ui.unit.dp
import com.android.credentialmanager.common.material.ModalBottomSheetLayout
import com.android.credentialmanager.common.material.ModalBottomSheetValue
import com.android.credentialmanager.common.material.rememberModalBottomSheetState
@@ -34,40 +42,68 @@
/** Draws a modal bottom sheet with the same styles and effects shared by various flows. */
@Composable
+@OptIn(ExperimentalMaterial3Api::class)
fun ModalBottomSheet(
- sheetContent: @Composable ColumnScope.() -> Unit,
- onDismiss: () -> Unit,
- isInitialRender: Boolean,
- onInitialRenderComplete: () -> Unit,
- isAutoSelectFlow: Boolean,
+ sheetContent: @Composable () -> Unit,
+ onDismiss: () -> Unit,
+ isInitialRender: Boolean,
+ onInitialRenderComplete: () -> Unit,
+ isAutoSelectFlow: Boolean,
) {
- val scope = rememberCoroutineScope()
- val state = rememberModalBottomSheetState(
- initialValue = if (isAutoSelectFlow) ModalBottomSheetValue.Expanded
- else ModalBottomSheetValue.Hidden,
- skipHalfExpanded = true
- )
- val sysUiController = rememberSystemUiController()
- if (state.targetValue == ModalBottomSheetValue.Hidden || isAutoSelectFlow) {
- setTransparentSystemBarsColor(sysUiController)
+ if (Flags.selectorUiImprovementsEnabled()) {
+ val state = androidx.compose.material3.rememberModalBottomSheetState(
+ skipPartiallyExpanded = true
+ )
+ androidx.compose.material3.ModalBottomSheet(
+ onDismissRequest = onDismiss,
+ containerColor = LocalAndroidColorScheme.current.surfaceBright,
+ sheetState = state,
+ content = {
+ Box(
+ modifier = Modifier
+ .animateContentSize()
+ .wrapContentHeight()
+ .fillMaxWidth()
+ ) {
+ sheetContent()
+ }
+ },
+ scrimColor = MaterialTheme.colorScheme.scrim.copy(alpha = .32f),
+ shape = EntryShape.TopRoundedCorner,
+ dragHandle = null,
+ // Never take over the full screen. We always want to leave some top scrim space
+ // for exiting and viewing the underlying app to help a user gain context.
+ modifier = Modifier.padding(top = 56.dp),
+ )
} else {
- setBottomSheetSystemBarsColor(sysUiController)
- }
- ModalBottomSheetLayout(
- sheetBackgroundColor = LocalAndroidColorScheme.current.surfaceBright,
- modifier = Modifier.background(Color.Transparent),
- sheetState = state,
- sheetContent = sheetContent,
- sheetShape = EntryShape.TopRoundedCorner,
- ) {}
- LaunchedEffect(state.currentValue, state.targetValue) {
- if (state.currentValue == ModalBottomSheetValue.Hidden) {
- if (isInitialRender) {
- onInitialRenderComplete()
- scope.launch { state.show() }
- } else if (state.targetValue == ModalBottomSheetValue.Hidden) {
- // Only dismiss ui when the motion is downwards
- onDismiss()
+ val scope = rememberCoroutineScope()
+ val state = rememberModalBottomSheetState(
+ initialValue = if (isAutoSelectFlow) ModalBottomSheetValue.Expanded
+ else ModalBottomSheetValue.Hidden,
+ skipHalfExpanded = true
+ )
+ val sysUiController = rememberSystemUiController()
+ if (state.targetValue == ModalBottomSheetValue.Hidden || isAutoSelectFlow) {
+ setTransparentSystemBarsColor(sysUiController)
+ } else {
+ setBottomSheetSystemBarsColor(sysUiController)
+ }
+ ModalBottomSheetLayout(
+ sheetBackgroundColor = LocalAndroidColorScheme.current.surfaceBright,
+ modifier = Modifier.background(Color.Transparent),
+ sheetState = state,
+ sheetContent = { sheetContent() },
+ sheetShape = EntryShape.TopRoundedCorner,
+ ) {}
+ LaunchedEffect(state.currentValue, state.targetValue) {
+ if (state.currentValue == ModalBottomSheetValue.Hidden) {
+ if (isInitialRender) {
+ onInitialRenderComplete()
+ scope.launch { state.show() }
+ } else if (state.targetValue == ModalBottomSheetValue.Hidden) {
+ // Only dismiss ui when the motion is downwards
+ onDismiss()
+ }
}
}
}
diff --git a/packages/CredentialManager/src/com/android/credentialmanager/common/ui/Cards.kt b/packages/CredentialManager/src/com/android/credentialmanager/common/ui/Cards.kt
index bdfe399..c68ae8b 100644
--- a/packages/CredentialManager/src/com/android/credentialmanager/common/ui/Cards.kt
+++ b/packages/CredentialManager/src/com/android/credentialmanager/common/ui/Cards.kt
@@ -18,7 +18,10 @@
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.ColumnScope
+import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.asPaddingValues
+import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
@@ -66,6 +69,9 @@
horizontalAlignment = Alignment.CenterHorizontally,
content = content,
verticalArrangement = contentVerticalArrangement,
+ // The bottom sheet overlaps with the navigation bars but make sure the actual content
+ // in the bottom sheet does not.
+ contentPadding = WindowInsets.navigationBars.asPaddingValues(),
)
}
}
diff --git a/packages/CredentialManager/src/com/android/credentialmanager/common/ui/Entry.kt b/packages/CredentialManager/src/com/android/credentialmanager/common/ui/Entry.kt
index a6253b8..8ff17e0 100644
--- a/packages/CredentialManager/src/com/android/credentialmanager/common/ui/Entry.kt
+++ b/packages/CredentialManager/src/com/android/credentialmanager/common/ui/Entry.kt
@@ -29,13 +29,10 @@
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.outlined.Lock
-import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.SuggestionChipDefaults
-import androidx.compose.material3.TopAppBar
-import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@@ -278,31 +275,6 @@
}
/**
- * A single row of leading icon and text describing a benefit of passkeys, used by the
- * [com.android.credentialmanager.createflow.PasskeyIntroCard].
- */
-@Composable
-fun PasskeyBenefitRow(
- leadingIconPainter: Painter,
- text: String,
-) {
- Row(
- horizontalArrangement = Arrangement.spacedBy(16.dp),
- verticalAlignment = Alignment.CenterVertically,
- modifier = Modifier.fillMaxWidth()
- ) {
- Icon(
- modifier = Modifier.size(24.dp),
- painter = leadingIconPainter,
- tint = LocalAndroidColorScheme.current.onSurfaceVariant,
- // Decorative purpose only.
- contentDescription = null,
- )
- BodyMediumText(text = text)
- }
-}
-
-/**
* A single row of one or two CTA buttons for continuing or cancelling the current step.
*/
@Composable
@@ -327,40 +299,36 @@
}
}
-@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MoreOptionTopAppBar(
text: String,
onNavigationIconClicked: () -> Unit,
bottomPadding: Dp,
) {
- TopAppBar(
- title = {
- LargeTitleText(text = text, modifier = Modifier.padding(horizontal = 4.dp))
- },
- navigationIcon = {
- IconButton(
+ Row(
+ modifier = Modifier.padding(top = 12.dp, bottom = bottomPadding),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ IconButton(
modifier = Modifier.padding(top = 8.dp, bottom = 8.dp, start = 4.dp).size(48.dp),
onClick = onNavigationIconClicked
- ) {
- Box(
+ ) {
+ Box(
modifier = Modifier.size(48.dp),
contentAlignment = Alignment.Center,
- ) {
- Icon(
+ ) {
+ Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = stringResource(
- R.string.accessibility_back_arrow_button
+ R.string.accessibility_back_arrow_button
),
modifier = Modifier.size(24.dp).autoMirrored(),
tint = LocalAndroidColorScheme.current.onSurfaceVariant,
- )
- }
+ )
}
- },
- colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent),
- modifier = Modifier.padding(top = 12.dp, bottom = bottomPadding)
- )
+ }
+ LargeTitleText(text = text, modifier = Modifier.padding(horizontal = 4.dp))
+ }
}
private fun Modifier.autoMirrored() = composed {
diff --git a/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetCredentialComponents.kt b/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetCredentialComponents.kt
index 4ed84b9..7277550 100644
--- a/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetCredentialComponents.kt
+++ b/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetCredentialComponents.kt
@@ -653,4 +653,4 @@
contentText = stringResource(R.string.no_sign_in_info_in, lastLocked.providerDisplayName),
)
onLog(GetCredentialEvent.CREDMAN_GET_CRED_SCREEN_EMPTY_AUTH_SNACKBAR_SCREEN)
-}
\ No newline at end of file
+}
diff --git a/packages/CredentialManager/tests/robotests/Android.bp b/packages/CredentialManager/tests/robotests/Android.bp
index baebfeb..75a0dcc 100644
--- a/packages/CredentialManager/tests/robotests/Android.bp
+++ b/packages/CredentialManager/tests/robotests/Android.bp
@@ -37,7 +37,7 @@
":CredentialManagerScreenshotTestFiles",
],
- // Do not add any libraries here, instead add them to the ScreenshotTestStub
+ // Do not add any libraries here, instead add them to the ScreenshotTestRobo
static_libs: [
"androidx.compose.runtime_runtime",
"androidx.test.uiautomator_uiautomator",
@@ -45,6 +45,7 @@
"inline-mockito-robolectric-prebuilt",
"platform-parametric-runner-lib",
"uiautomator-helpers",
+ "flag-junit-base",
],
libs: [
"android.test.runner",
diff --git a/packages/CredentialManager/tests/robotests/customization/assets/phone/dark_landscape_singleCredentialScreen_newM3BottomSheet.png b/packages/CredentialManager/tests/robotests/customization/assets/phone/dark_landscape_singleCredentialScreen_newM3BottomSheet.png
new file mode 100644
index 0000000..81860e5
--- /dev/null
+++ b/packages/CredentialManager/tests/robotests/customization/assets/phone/dark_landscape_singleCredentialScreen_newM3BottomSheet.png
Binary files differ
diff --git a/packages/CredentialManager/tests/robotests/customization/assets/phone/dark_portrait_singleCredentialScreen_newM3BottomSheet.png b/packages/CredentialManager/tests/robotests/customization/assets/phone/dark_portrait_singleCredentialScreen_newM3BottomSheet.png
new file mode 100644
index 0000000..8c1fff7
--- /dev/null
+++ b/packages/CredentialManager/tests/robotests/customization/assets/phone/dark_portrait_singleCredentialScreen_newM3BottomSheet.png
Binary files differ
diff --git a/packages/CredentialManager/tests/robotests/customization/assets/phone/light_landscape_singleCredentialScreen_newM3BottomSheet.png b/packages/CredentialManager/tests/robotests/customization/assets/phone/light_landscape_singleCredentialScreen_newM3BottomSheet.png
new file mode 100644
index 0000000..4eb025f
--- /dev/null
+++ b/packages/CredentialManager/tests/robotests/customization/assets/phone/light_landscape_singleCredentialScreen_newM3BottomSheet.png
Binary files differ
diff --git a/packages/CredentialManager/tests/robotests/customization/assets/phone/light_portrait_singleCredentialScreen_newM3BottomSheet.png b/packages/CredentialManager/tests/robotests/customization/assets/phone/light_portrait_singleCredentialScreen_newM3BottomSheet.png
new file mode 100644
index 0000000..c709f93
--- /dev/null
+++ b/packages/CredentialManager/tests/robotests/customization/assets/phone/light_portrait_singleCredentialScreen_newM3BottomSheet.png
Binary files differ
diff --git a/packages/CredentialManager/tests/robotests/customization/assets/tablet/dark_landscape_singleCredentialScreen_newM3BottomSheet.png b/packages/CredentialManager/tests/robotests/customization/assets/tablet/dark_landscape_singleCredentialScreen_newM3BottomSheet.png
new file mode 100644
index 0000000..278c13f
--- /dev/null
+++ b/packages/CredentialManager/tests/robotests/customization/assets/tablet/dark_landscape_singleCredentialScreen_newM3BottomSheet.png
Binary files differ
diff --git a/packages/CredentialManager/tests/robotests/customization/assets/tablet/dark_portrait_singleCredentialScreen_newM3BottomSheet.png b/packages/CredentialManager/tests/robotests/customization/assets/tablet/dark_portrait_singleCredentialScreen_newM3BottomSheet.png
new file mode 100644
index 0000000..cb85df3
--- /dev/null
+++ b/packages/CredentialManager/tests/robotests/customization/assets/tablet/dark_portrait_singleCredentialScreen_newM3BottomSheet.png
Binary files differ
diff --git a/packages/CredentialManager/tests/robotests/customization/assets/tablet/light_landscape_singleCredentialScreen_newM3BottomSheet.png b/packages/CredentialManager/tests/robotests/customization/assets/tablet/light_landscape_singleCredentialScreen_newM3BottomSheet.png
new file mode 100644
index 0000000..2eca707
--- /dev/null
+++ b/packages/CredentialManager/tests/robotests/customization/assets/tablet/light_landscape_singleCredentialScreen_newM3BottomSheet.png
Binary files differ
diff --git a/packages/CredentialManager/tests/robotests/customization/assets/tablet/light_portrait_singleCredentialScreen_newM3BottomSheet.png b/packages/CredentialManager/tests/robotests/customization/assets/tablet/light_portrait_singleCredentialScreen_newM3BottomSheet.png
new file mode 100644
index 0000000..7ee91b3
--- /dev/null
+++ b/packages/CredentialManager/tests/robotests/customization/assets/tablet/light_portrait_singleCredentialScreen_newM3BottomSheet.png
Binary files differ
diff --git a/packages/CredentialManager/tests/robotests/screenshot/src/com/android/credentialmanager/GetCredScreenshotTest.kt b/packages/CredentialManager/tests/robotests/screenshot/src/com/android/credentialmanager/GetCredScreenshotTest.kt
index a0e1fed..e609d0c 100644
--- a/packages/CredentialManager/tests/robotests/screenshot/src/com/android/credentialmanager/GetCredScreenshotTest.kt
+++ b/packages/CredentialManager/tests/robotests/screenshot/src/com/android/credentialmanager/GetCredScreenshotTest.kt
@@ -16,7 +16,10 @@
package com.android.credentialmanager
+import android.credentials.flags.Flags
import android.content.Context
+import android.platform.test.flag.junit.SetFlagsRule
+import androidx.compose.ui.test.isPopup
import com.android.credentialmanager.getflow.RequestDisplayInfo
import com.android.credentialmanager.model.CredentialType
import com.android.credentialmanager.model.get.ProviderInfo
@@ -59,8 +62,11 @@
CredentialManagerGoldenImagePathManager(getEmulatedDevicePathConfig(emulationSpec))
)
+ @get:Rule val setFlagsRule: SetFlagsRule = SetFlagsRule()
+
@Test
- fun singleCredentialScreen() {
+ fun singleCredentialScreen_M3BottomSheetDisabled() {
+ setFlagsRule.disableFlags(Flags.FLAG_SELECTOR_UI_IMPROVEMENTS_ENABLED)
val providerInfoList = buildProviderInfoList()
val providerDisplayInfo = toProviderDisplayInfo(providerInfoList)
val activeEntry = toActiveEntry(providerDisplayInfo)
@@ -86,6 +92,39 @@
}
}
+ @Test
+ fun singleCredentialScreen_M3BottomSheetEnabled() {
+ setFlagsRule.enableFlags(Flags.FLAG_SELECTOR_UI_IMPROVEMENTS_ENABLED)
+ val providerInfoList = buildProviderInfoList()
+ val providerDisplayInfo = toProviderDisplayInfo(providerInfoList)
+ val activeEntry = toActiveEntry(providerDisplayInfo)
+ screenshotRule.screenshotTest(
+ "singleCredentialScreen_newM3BottomSheet",
+ // M3's ModalBottomSheet lives in a new window, meaning we have two windows with
+ // a root. Hence use a different matcher `isPopup`.
+ viewFinder = { screenshotRule.composeRule.onNode(isPopup()) },
+ ) {
+ ModalBottomSheet(
+ sheetContent = {
+ PrimarySelectionCard(
+ requestDisplayInfo = REQUEST_DISPLAY_INFO,
+ providerDisplayInfo = providerDisplayInfo,
+ providerInfoList = providerInfoList,
+ activeEntry = activeEntry,
+ onEntrySelected = {},
+ onConfirm = {},
+ onMoreOptionSelected = {},
+ onLog = {},
+ )
+ },
+ isInitialRender = true,
+ onDismiss = {},
+ onInitialRenderComplete = {},
+ isAutoSelectFlow = false,
+ )
+ }
+ }
+
private fun buildProviderInfoList(): List<ProviderInfo> {
val context = ApplicationProvider.getApplicationContext<Context>()
val provider1 = ProviderInfo(
diff --git a/packages/SettingsLib/aconfig/settingslib.aconfig b/packages/SettingsLib/aconfig/settingslib.aconfig
index 6a1ee3a..54c5a14 100644
--- a/packages/SettingsLib/aconfig/settingslib.aconfig
+++ b/packages/SettingsLib/aconfig/settingslib.aconfig
@@ -43,4 +43,11 @@
namespace: "pixel_cross_device_control"
description: "Gates whether to enable LE audio private broadcast sharing via QR code"
bug: "308368124"
-}
\ No newline at end of file
+}
+
+flag {
+ name: "enable_hide_exclusively_managed_bluetooth_device"
+ namespace: "dck_framework"
+ description: "Hide exclusively managed Bluetooth devices in BT settings menu."
+ bug: "324475542"
+}
diff --git a/packages/SystemUI/Android.bp b/packages/SystemUI/Android.bp
index bed95a5..e63232a 100644
--- a/packages/SystemUI/Android.bp
+++ b/packages/SystemUI/Android.bp
@@ -230,6 +230,7 @@
extra_check_modules: ["SystemUILintChecker"],
warning_checks: ["MissingApacheLicenseDetector"],
},
+ skip_jarjar_repackage: true,
}
filegroup {
diff --git a/packages/SystemUI/compose/features/Android.bp b/packages/SystemUI/compose/features/Android.bp
index c12084d..dfb3a55 100644
--- a/packages/SystemUI/compose/features/Android.bp
+++ b/packages/SystemUI/compose/features/Android.bp
@@ -44,4 +44,5 @@
],
kotlincflags: ["-Xjvm-default=all"],
+ skip_jarjar_repackage: true,
}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalHub.kt b/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalHub.kt
index 622a4f0..609f314 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalHub.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalHub.kt
@@ -274,7 +274,7 @@
widgetConfigurator: WidgetConfigurator?,
) {
var gridModifier =
- Modifier.align(Alignment.CenterStart).onGloballyPositioned { setGridCoordinates(it) }
+ Modifier.align(Alignment.TopStart).onGloballyPositioned { setGridCoordinates(it) }
var list = communalContent
var dragDropState: GridDragDropState? = null
if (viewModel.isEditMode && viewModel is CommunalEditModeViewModel) {
@@ -309,8 +309,8 @@
state = gridState,
rows = GridCells.Fixed(CommunalContentSize.FULL.span),
contentPadding = contentPadding,
- horizontalArrangement = Arrangement.spacedBy(Dimensions.Spacing),
- verticalArrangement = Arrangement.spacedBy(Dimensions.Spacing),
+ horizontalArrangement = Arrangement.spacedBy(32.dp),
+ verticalArrangement = Arrangement.spacedBy(32.dp),
) {
items(
count = list.size,
@@ -681,19 +681,20 @@
Box(
modifier = modifier,
) {
- val paddingInPx = with(LocalDensity.current) { CardOutlineWidth.toPx().toInt() }
+ val paddingInPx =
+ if (selected) with(LocalDensity.current) { CardOutlineWidth.toPx().toInt() } else 0
AndroidView(
modifier = Modifier.fillMaxSize().allowGestures(allowed = !viewModel.isEditMode),
factory = { context ->
- val view =
- model.appWidgetHost
- .createViewForCommunal(context, model.appWidgetId, model.providerInfo)
- .apply { updateAppWidgetSize(Bundle.EMPTY, listOf(size)) }
+ model.appWidgetHost
+ .createViewForCommunal(context, model.appWidgetId, model.providerInfo)
+ .apply { updateAppWidgetSize(Bundle.EMPTY, listOf(size)) }
+ },
+ update = { view ->
// Remove the extra padding applied to AppWidgetHostView to allow widgets to
// occupy the entire box. The added padding is now adjusted to leave only sufficient
// space for displaying the outline around the box when the widget is selected.
view.setPadding(paddingInPx)
- view
},
// For reusing composition in lazy lists.
onReset = {},
@@ -795,7 +796,7 @@
@Composable
private fun gridContentPadding(isEditMode: Boolean, toolbarSize: IntSize?): PaddingValues {
if (!isEditMode || toolbarSize == null) {
- return PaddingValues(horizontal = Dimensions.Spacing)
+ return PaddingValues(start = 48.dp, end = 48.dp, top = Dimensions.GridTopSpacing)
}
val configuration = LocalConfiguration.current
val density = LocalDensity.current
@@ -858,12 +859,13 @@
}
object Dimensions {
- val CardWidth = 464.dp
- val CardHeightFull = 630.dp
- val CardHeightHalf = 307.dp
- val CardHeightThird = 199.dp
+ val CardWidth = 424.dp
+ val CardHeightFull = 596.dp
+ val CardHeightHalf = 282.dp
+ val CardHeightThird = 177.33.dp
val CardOutlineWidth = 3.dp
- val GridHeight = CardHeightFull
+ val GridTopSpacing = 72.dp
+ val GridHeight = CardHeightFull + GridTopSpacing
val Spacing = 16.dp
// The sizing/padding of the toolbar in glanceable hub edit mode
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/LockSection.kt b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/LockSection.kt
index be6f022..31d3fa0 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/LockSection.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/keyguard/ui/composable/section/LockSection.kt
@@ -18,6 +18,7 @@
import android.content.Context
import android.util.DisplayMetrics
+import android.view.View
import android.view.WindowManager
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@@ -45,6 +46,7 @@
import com.android.systemui.keyguard.ui.viewmodel.DeviceEntryIconViewModel
import com.android.systemui.plugins.FalsingManager
import com.android.systemui.res.R
+import com.android.systemui.shade.NotificationPanelView
import com.android.systemui.statusbar.VibratorHelper
import dagger.Lazy
import javax.inject.Inject
@@ -63,6 +65,7 @@
private val deviceEntryBackgroundViewModel: Lazy<DeviceEntryBackgroundViewModel>,
private val falsingManager: Lazy<FalsingManager>,
private val vibratorHelper: Lazy<VibratorHelper>,
+ private val notificationPanelView: NotificationPanelView,
) {
@Composable
fun SceneScope.LockIcon(modifier: Modifier = Modifier) {
@@ -70,6 +73,10 @@
return
}
+ notificationPanelView.findViewById<View?>(R.id.lock_icon_view)?.let {
+ notificationPanelView.removeView(it)
+ }
+
val context = LocalContext.current
AndroidView(
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/widgets/CommunalWidgetHostTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/widgets/CommunalWidgetHostTest.kt
index 12611cb..88f5e1b 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/widgets/CommunalWidgetHostTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/widgets/CommunalWidgetHostTest.kt
@@ -17,8 +17,10 @@
package com.android.systemui.communal.widgets
import android.appwidget.AppWidgetManager
+import android.appwidget.AppWidgetProviderInfo
import android.content.ComponentName
import android.content.pm.UserInfo
+import android.os.Bundle
import android.os.UserHandle
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
@@ -33,8 +35,8 @@
import com.android.systemui.user.domain.interactor.SelectedUserInteractor
import com.android.systemui.user.domain.interactor.selectedUserInteractor
import com.android.systemui.util.mockito.any
-import com.android.systemui.util.mockito.nullable
import com.android.systemui.util.mockito.whenever
+import com.android.systemui.util.mockito.withArgCaptor
import com.google.common.truth.Truth.assertThat
import java.util.Optional
import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -43,6 +45,7 @@
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
+import org.mockito.ArgumentMatchers.eq
import org.mockito.Mock
import org.mockito.Mockito.verify
import org.mockito.MockitoAnnotations
@@ -91,7 +94,7 @@
any<Int>(),
any<UserHandle>(),
any<ComponentName>(),
- nullable()
+ any<Bundle>(),
)
)
.thenReturn(true)
@@ -100,8 +103,14 @@
val result = underTest.allocateIdAndBindWidget(provider)
verify(appWidgetHost).allocateAppWidgetId()
- verify(appWidgetManager).bindAppWidgetIdIfAllowed(widgetId, user, provider, null)
+ val bundle =
+ withArgCaptor<Bundle> {
+ verify(appWidgetManager)
+ .bindAppWidgetIdIfAllowed(eq(widgetId), eq(user), eq(provider), capture())
+ }
assertThat(result).isEqualTo(widgetId)
+ assertThat(bundle.getInt(AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY))
+ .isEqualTo(AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD)
}
@Test
@@ -117,7 +126,7 @@
any<Int>(),
any<UserHandle>(),
any<ComponentName>(),
- nullable()
+ any<Bundle>()
)
)
.thenReturn(true)
@@ -126,8 +135,14 @@
val result = underTest.allocateIdAndBindWidget(provider, user)
verify(appWidgetHost).allocateAppWidgetId()
- verify(appWidgetManager).bindAppWidgetIdIfAllowed(widgetId, user, provider, null)
+ val bundle =
+ withArgCaptor<Bundle> {
+ verify(appWidgetManager)
+ .bindAppWidgetIdIfAllowed(eq(widgetId), eq(user), eq(provider), capture())
+ }
assertThat(result).isEqualTo(widgetId)
+ assertThat(bundle.getInt(AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY))
+ .isEqualTo(AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD)
}
@Test
@@ -144,14 +159,15 @@
any<Int>(),
any<UserHandle>(),
any<ComponentName>(),
- nullable()
+ any<Bundle>()
)
)
.thenReturn(false)
val result = underTest.allocateIdAndBindWidget(provider, user)
verify(appWidgetHost).allocateAppWidgetId()
- verify(appWidgetManager).bindAppWidgetIdIfAllowed(widgetId, user, provider, null)
+ verify(appWidgetManager)
+ .bindAppWidgetIdIfAllowed(eq(widgetId), eq(user), eq(provider), any())
verify(appWidgetHost).deleteAppWidgetId(widgetId)
assertThat(result).isNull()
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/BaseHeadsUpManagerTest.java b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/BaseHeadsUpManagerTest.java
index 87d25dd..6456669 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/BaseHeadsUpManagerTest.java
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/BaseHeadsUpManagerTest.java
@@ -19,8 +19,6 @@
import static android.app.Notification.FLAG_FSI_REQUESTED_BUT_DENIED;
import static com.android.systemui.log.LogBufferHelperKt.logcatLogBuffer;
-import static com.android.systemui.statusbar.notification.row.NotificationRowContentBinder.FLAG_CONTENT_VIEW_CONTRACTED;
-import static com.android.systemui.util.concurrency.MockExecutorHandlerKt.mockExecutorHandler;
import static com.google.common.truth.Truth.assertThat;
@@ -41,31 +39,23 @@
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Person;
-import android.content.Context;
import android.content.Intent;
-import android.graphics.Region;
import android.os.UserHandle;
import android.service.notification.StatusBarNotification;
import android.testing.TestableLooper;
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
-import androidx.test.filters.SmallTest;
import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
-import com.android.internal.logging.UiEventLogger;
import com.android.internal.logging.testing.UiEventLoggerFake;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.res.R;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
-import com.android.systemui.util.concurrency.DelayableExecutor;
import com.android.systemui.util.concurrency.FakeExecutor;
import com.android.systemui.util.settings.FakeGlobalSettings;
-import com.android.systemui.util.settings.GlobalSettings;
import com.android.systemui.util.time.FakeSystemClock;
-import com.android.systemui.util.time.SystemClock;
import org.junit.Rule;
import org.junit.Test;
@@ -83,8 +73,8 @@
private static final String TEST_PACKAGE_NAME = "BaseHeadsUpManagerTest";
- private static final int TEST_TOUCH_ACCEPTANCE_TIME = 200;
- private static final int TEST_A11Y_AUTO_DISMISS_TIME = 1_000;
+ static final int TEST_TOUCH_ACCEPTANCE_TIME = 200;
+ static final int TEST_A11Y_AUTO_DISMISS_TIME = 1_000;
private UiEventLoggerFake mUiEventLoggerFake = new UiEventLoggerFake();
private final HeadsUpManagerLogger mLogger = spy(new HeadsUpManagerLogger(logcatLogBuffer()));
@@ -110,143 +100,6 @@
assertThat(TEST_STICKY_AUTO_DISMISS_TIME).isLessThan(TEST_A11Y_AUTO_DISMISS_TIME);
}
- private final class TestableHeadsUpManager extends BaseHeadsUpManager {
-
- private HeadsUpEntry mLastCreatedEntry;
-
- TestableHeadsUpManager(Context context,
- HeadsUpManagerLogger logger,
- DelayableExecutor executor,
- GlobalSettings globalSettings,
- SystemClock systemClock,
- AccessibilityManagerWrapper accessibilityManagerWrapper,
- UiEventLogger uiEventLogger) {
- super(context, logger, mockExecutorHandler(executor), globalSettings, systemClock,
- executor, accessibilityManagerWrapper, uiEventLogger);
-
- mTouchAcceptanceDelay = TEST_TOUCH_ACCEPTANCE_TIME;
- mMinimumDisplayTime = TEST_MINIMUM_DISPLAY_TIME;
- mAutoDismissTime = TEST_AUTO_DISMISS_TIME;
- mStickyForSomeTimeAutoDismissTime = TEST_STICKY_AUTO_DISMISS_TIME;
-
- }
-
- @Override
- protected HeadsUpEntry createHeadsUpEntry() {
- mLastCreatedEntry = spy(super.createHeadsUpEntry());
- return mLastCreatedEntry;
- }
-
- @Override
- public int getContentFlag() {
- return FLAG_CONTENT_VIEW_CONTRACTED;
- }
-
- // The following are only implemented by HeadsUpManagerPhone. If you need them, use that.
- @Override
- public void addHeadsUpPhoneListener(@NonNull OnHeadsUpPhoneListenerChange listener) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void addSwipedOutNotification(@NonNull String key) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void extendHeadsUp() {
- throw new UnsupportedOperationException();
- }
-
- @Nullable
- @Override
- public Region getTouchableRegion() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean isHeadsUpGoingAway() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void onExpandingFinished() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean removeNotification(@NonNull String key, boolean releaseImmediately,
- boolean animate) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void setAnimationStateHandler(@NonNull AnimationStateHandler handler) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void setGutsShown(@NonNull NotificationEntry entry, boolean gutsShown) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void setHeadsUpGoingAway(boolean headsUpGoingAway) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void setRemoteInputActive(@NonNull NotificationEntry entry,
- boolean remoteInputActive) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void setTrackingHeadsUp(boolean tracking) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean shouldSwallowClick(@NonNull String key) {
- throw new UnsupportedOperationException();
- }
- }
-
- protected StatusBarNotification createSbn(int id, Notification n) {
- return new StatusBarNotification(
- TEST_PACKAGE_NAME /* pkg */,
- TEST_PACKAGE_NAME,
- id,
- null /* tag */,
- TEST_UID,
- 0 /* initialPid */,
- n,
- new UserHandle(ActivityManager.getCurrentUser()),
- null /* overrideGroupKey */,
- 0 /* postTime */);
- }
-
- protected StatusBarNotification createSbn(int id, Notification.Builder n) {
- return createSbn(id, n.build());
- }
-
- protected StatusBarNotification createSbn(int id) {
- final Notification.Builder b = new Notification.Builder(mContext, "")
- .setSmallIcon(R.drawable.ic_person)
- .setContentTitle("Title")
- .setContentText("Text");
- return createSbn(id, b);
- }
-
- protected NotificationEntry createEntry(int id, Notification n) {
- return new NotificationEntryBuilder().setSbn(createSbn(id, n)).build();
- }
-
- protected NotificationEntry createEntry(int id) {
- return new NotificationEntryBuilder().setSbn(createSbn(id)).build();
- }
-
-
private BaseHeadsUpManager createHeadsUpManager() {
return new TestableHeadsUpManager(mContext, mLogger, mExecutor, mGlobalSettings,
mSystemClock, mAccessibilityMgr, mUiEventLoggerFake);
@@ -257,7 +110,7 @@
.setSmallIcon(R.drawable.ic_person)
.setFullScreenIntent(mock(PendingIntent.class), /* highPriority */ true)
.build();
- return createEntry(id, notif);
+ return HeadsUpManagerTestUtil.createEntry(id, notif);
}
private NotificationEntry createStickyForSomeTimeEntry(int id) {
@@ -265,7 +118,7 @@
.setSmallIcon(R.drawable.ic_person)
.setFlag(FLAG_FSI_REQUESTED_BUT_DENIED, true)
.build();
- return createEntry(id, notif);
+ return HeadsUpManagerTestUtil.createEntry(id, notif);
}
private PendingIntent createFullScreenIntent() {
@@ -279,7 +132,7 @@
.setSmallIcon(R.drawable.ic_person)
.setFullScreenIntent(createFullScreenIntent(), /* highPriority */ true)
.build();
- return createEntry(id, notif);
+ return HeadsUpManagerTestUtil.createEntry(id, notif);
}
@@ -296,7 +149,7 @@
@Test
public void testShowNotification_addsEntry() {
final BaseHeadsUpManager alm = createHeadsUpManager();
- final NotificationEntry entry = createEntry(/* id = */ 0);
+ final NotificationEntry entry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0, mContext);
alm.showNotification(entry);
@@ -308,7 +161,7 @@
@Test
public void testShowNotification_autoDismisses() {
final BaseHeadsUpManager alm = createHeadsUpManager();
- final NotificationEntry entry = createEntry(/* id = */ 0);
+ final NotificationEntry entry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0, mContext);
alm.showNotification(entry);
mSystemClock.advanceTime(TEST_AUTO_DISMISS_TIME * 3 / 2);
@@ -319,7 +172,7 @@
@Test
public void testRemoveNotification_removeDeferred() {
final BaseHeadsUpManager alm = createHeadsUpManager();
- final NotificationEntry entry = createEntry(/* id = */ 0);
+ final NotificationEntry entry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0, mContext);
alm.showNotification(entry);
@@ -332,7 +185,7 @@
@Test
public void testRemoveNotification_forceRemove() {
final BaseHeadsUpManager alm = createHeadsUpManager();
- final NotificationEntry entry = createEntry(/* id = */ 0);
+ final NotificationEntry entry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0, mContext);
alm.showNotification(entry);
@@ -346,7 +199,7 @@
public void testReleaseAllImmediately() {
final BaseHeadsUpManager alm = createHeadsUpManager();
for (int i = 0; i < TEST_NUM_NOTIFICATIONS; i++) {
- final NotificationEntry entry = createEntry(i);
+ final NotificationEntry entry = HeadsUpManagerTestUtil.createEntry(i, mContext);
entry.setRow(mRow);
alm.showNotification(entry);
}
@@ -359,7 +212,7 @@
@Test
public void testCanRemoveImmediately_notShownLongEnough() {
final BaseHeadsUpManager alm = createHeadsUpManager();
- final NotificationEntry entry = createEntry(/* id = */ 0);
+ final NotificationEntry entry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0, mContext);
alm.showNotification(entry);
@@ -370,7 +223,8 @@
@Test
public void testHunRemovedLogging() {
final BaseHeadsUpManager hum = createHeadsUpManager();
- final NotificationEntry notifEntry = createEntry(/* id = */ 0);
+ final NotificationEntry notifEntry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0,
+ mContext);
final BaseHeadsUpManager.HeadsUpEntry headsUpEntry = mock(
BaseHeadsUpManager.HeadsUpEntry.class);
headsUpEntry.mEntry = notifEntry;
@@ -413,7 +267,7 @@
@Test
public void testShouldHeadsUpBecomePinned_noFSI_false() {
final BaseHeadsUpManager hum = createHeadsUpManager();
- final NotificationEntry entry = createEntry(/* id = */ 0);
+ final NotificationEntry entry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0, mContext);
assertFalse(hum.shouldHeadsUpBecomePinned(entry));
}
@@ -422,7 +276,7 @@
@Test
public void testShowNotification_autoDismissesIncludingTouchAcceptanceDelay() {
final BaseHeadsUpManager hum = createHeadsUpManager();
- final NotificationEntry entry = createEntry(/* id = */ 0);
+ final NotificationEntry entry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0, mContext);
useAccessibilityTimeout(false);
hum.showNotification(entry);
@@ -435,7 +289,7 @@
@Test
public void testShowNotification_autoDismissesWithDefaultTimeout() {
final BaseHeadsUpManager hum = createHeadsUpManager();
- final NotificationEntry entry = createEntry(/* id = */ 0);
+ final NotificationEntry entry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0, mContext);
useAccessibilityTimeout(false);
hum.showNotification(entry);
@@ -476,7 +330,7 @@
@Test
public void testShowNotification_autoDismissesWithAccessibilityTimeout() {
final BaseHeadsUpManager hum = createHeadsUpManager();
- final NotificationEntry entry = createEntry(/* id = */ 0);
+ final NotificationEntry entry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0, mContext);
useAccessibilityTimeout(true);
hum.showNotification(entry);
@@ -504,7 +358,7 @@
@Test
public void testRemoveNotification_beforeMinimumDisplayTime() {
final BaseHeadsUpManager hum = createHeadsUpManager();
- final NotificationEntry entry = createEntry(/* id = */ 0);
+ final NotificationEntry entry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0, mContext);
useAccessibilityTimeout(false);
hum.showNotification(entry);
@@ -523,7 +377,7 @@
@Test
public void testRemoveNotification_afterMinimumDisplayTime() {
final BaseHeadsUpManager hum = createHeadsUpManager();
- final NotificationEntry entry = createEntry(/* id = */ 0);
+ final NotificationEntry entry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0, mContext);
useAccessibilityTimeout(false);
hum.showNotification(entry);
@@ -541,7 +395,7 @@
@Test
public void testRemoveNotification_releaseImmediately() {
final BaseHeadsUpManager hum = createHeadsUpManager();
- final NotificationEntry entry = createEntry(/* id = */ 0);
+ final NotificationEntry entry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0, mContext);
hum.showNotification(entry);
@@ -555,7 +409,8 @@
@Test
public void testIsSticky_rowPinnedAndExpanded_true() {
final BaseHeadsUpManager hum = createHeadsUpManager();
- final NotificationEntry notifEntry = createEntry(/* id = */ 0);
+ final NotificationEntry notifEntry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0,
+ mContext);
when(mRow.isPinned()).thenReturn(true);
notifEntry.setRow(mRow);
@@ -571,7 +426,8 @@
@Test
public void testIsSticky_remoteInputActive_true() {
final BaseHeadsUpManager hum = createHeadsUpManager();
- final NotificationEntry notifEntry = createEntry(/* id = */ 0);
+ final NotificationEntry notifEntry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0,
+ mContext);
hum.showNotification(notifEntry);
@@ -607,7 +463,8 @@
@Test
public void testIsSticky_false() {
final BaseHeadsUpManager hum = createHeadsUpManager();
- final NotificationEntry notifEntry = createEntry(/* id = */ 0);
+ final NotificationEntry notifEntry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0,
+ mContext);
hum.showNotification(notifEntry);
@@ -653,14 +510,14 @@
final BaseHeadsUpManager.HeadsUpEntry ongoingCall = hum.new HeadsUpEntry();
ongoingCall.setEntry(new NotificationEntryBuilder()
- .setSbn(createSbn(/* id = */ 0,
+ .setSbn(HeadsUpManagerTestUtil.createSbn(/* id = */ 0,
new Notification.Builder(mContext, "")
.setCategory(Notification.CATEGORY_CALL)
.setOngoing(true)))
.build());
final BaseHeadsUpManager.HeadsUpEntry activeRemoteInput = hum.new HeadsUpEntry();
- activeRemoteInput.setEntry(createEntry(/* id = */ 1));
+ activeRemoteInput.setEntry(HeadsUpManagerTestUtil.createEntry(/* id = */ 1, mContext));
activeRemoteInput.mRemoteInputActive = true;
assertThat(ongoingCall.compareTo(activeRemoteInput)).isLessThan(0);
@@ -675,14 +532,14 @@
final Person person = new Person.Builder().setName("person").build();
final PendingIntent intent = mock(PendingIntent.class);
incomingCall.setEntry(new NotificationEntryBuilder()
- .setSbn(createSbn(/* id = */ 0,
+ .setSbn(HeadsUpManagerTestUtil.createSbn(/* id = */ 0,
new Notification.Builder(mContext, "")
.setStyle(Notification.CallStyle
.forIncomingCall(person, intent, intent))))
.build());
final BaseHeadsUpManager.HeadsUpEntry activeRemoteInput = hum.new HeadsUpEntry();
- activeRemoteInput.setEntry(createEntry(/* id = */ 1));
+ activeRemoteInput.setEntry(HeadsUpManagerTestUtil.createEntry(/* id = */ 1, mContext));
activeRemoteInput.mRemoteInputActive = true;
assertThat(incomingCall.compareTo(activeRemoteInput)).isLessThan(0);
@@ -712,7 +569,8 @@
@Test
public void testSetUserActionMayIndirectlyRemove() {
final BaseHeadsUpManager hum = createHeadsUpManager();
- final NotificationEntry notifEntry = createEntry(/* id = */ 0);
+ final NotificationEntry notifEntry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0,
+ mContext);
hum.showNotification(notifEntry);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhoneTest.java b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/HeadsUpManagerPhoneTest.java
similarity index 88%
rename from packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhoneTest.java
rename to packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/HeadsUpManagerPhoneTest.java
index c350de2..ec23f76 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhoneTest.java
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/HeadsUpManagerPhoneTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.systemui.statusbar.phone;
+package com.android.systemui.statusbar.policy;
import static com.android.systemui.log.LogBufferHelperKt.logcatLogBuffer;
import static com.android.systemui.util.concurrency.MockExecutorHandlerKt.mockExecutorHandler;
@@ -26,10 +26,10 @@
import static org.mockito.Mockito.when;
import android.content.Context;
-import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
import androidx.test.filters.SmallTest;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.android.internal.logging.UiEventLogger;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
@@ -39,11 +39,9 @@
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.provider.VisualStabilityProvider;
import com.android.systemui.statusbar.notification.collection.render.GroupMembershipManager;
-import com.android.systemui.statusbar.policy.AccessibilityManagerWrapper;
-import com.android.systemui.statusbar.policy.BaseHeadsUpManagerTest;
-import com.android.systemui.statusbar.policy.ConfigurationController;
-import com.android.systemui.statusbar.policy.HeadsUpManager;
-import com.android.systemui.statusbar.policy.HeadsUpManagerLogger;
+import com.android.systemui.statusbar.phone.ConfigurationControllerImpl;
+import com.android.systemui.statusbar.phone.HeadsUpManagerPhone;
+import com.android.systemui.statusbar.phone.KeyguardBypassController;
import com.android.systemui.util.concurrency.DelayableExecutor;
import com.android.systemui.util.kotlin.JavaAdapter;
import com.android.systemui.util.settings.GlobalSettings;
@@ -61,7 +59,7 @@
import kotlinx.coroutines.flow.StateFlowKt;
@SmallTest
-@RunWith(AndroidTestingRunner.class)
+@RunWith(AndroidJUnit4.class)
@TestableLooper.RunWithLooper
public class HeadsUpManagerPhoneTest extends BaseHeadsUpManagerTest {
@Rule public MockitoRule rule = MockitoJUnit.rule();
@@ -152,7 +150,7 @@
@Test
public void testSnooze() {
final HeadsUpManager hmp = createHeadsUpManagerPhone();
- final NotificationEntry entry = createEntry(/* id = */ 0);
+ final NotificationEntry entry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0, mContext);
hmp.showNotification(entry);
hmp.snooze();
@@ -163,7 +161,7 @@
@Test
public void testSwipedOutNotification() {
final HeadsUpManager hmp = createHeadsUpManagerPhone();
- final NotificationEntry entry = createEntry(/* id = */ 0);
+ final NotificationEntry entry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0, mContext);
hmp.showNotification(entry);
hmp.addSwipedOutNotification(entry.getKey());
@@ -179,7 +177,7 @@
@Test
public void testCanRemoveImmediately_swipedOut() {
final HeadsUpManager hmp = createHeadsUpManagerPhone();
- final NotificationEntry entry = createEntry(/* id = */ 0);
+ final NotificationEntry entry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0, mContext);
hmp.showNotification(entry);
hmp.addSwipedOutNotification(entry.getKey());
@@ -192,8 +190,10 @@
@Test
public void testCanRemoveImmediately_notTopEntry() {
final HeadsUpManager hmp = createHeadsUpManagerPhone();
- final NotificationEntry earlierEntry = createEntry(/* id = */ 0);
- final NotificationEntry laterEntry = createEntry(/* id = */ 1);
+ final NotificationEntry earlierEntry =
+ HeadsUpManagerTestUtil.createEntry(/* id = */ 0, mContext);
+ final NotificationEntry laterEntry =
+ HeadsUpManagerTestUtil.createEntry(/* id = */ 1, mContext);
laterEntry.setRow(mRow);
hmp.showNotification(earlierEntry);
@@ -206,7 +206,7 @@
@Test
public void testExtendHeadsUp() {
final HeadsUpManagerPhone hmp = createHeadsUpManagerPhone();
- final NotificationEntry entry = createEntry(/* id = */ 0);
+ final NotificationEntry entry = HeadsUpManagerTestUtil.createEntry(/* id = */ 0, mContext);
hmp.showNotification(entry);
hmp.extendHeadsUp();
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/HeadsUpManagerTestUtil.java b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/HeadsUpManagerTestUtil.java
new file mode 100644
index 0000000..c70b03b
--- /dev/null
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/HeadsUpManagerTestUtil.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.statusbar.policy;
+import android.app.ActivityManager;
+import android.os.UserHandle;
+
+import android.content.Context;
+import android.service.notification.StatusBarNotification;
+import android.app.Notification;
+
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
+
+/**
+ * Test helper class for HeadsUpEntry creation.
+ */
+public class HeadsUpManagerTestUtil {
+
+ private static final String TEST_PACKAGE_NAME = "HeadsUpManagerTestUtil";
+ private static final int TEST_UID = 0;
+
+ protected static StatusBarNotification createSbn(int id, Notification.Builder n) {
+ return createSbn(id, n.build());
+ }
+
+ protected static StatusBarNotification createSbn(int id, Context context) {
+ final Notification.Builder b = new Notification.Builder(context, "")
+ .setSmallIcon(com.android.systemui.res.R.drawable.ic_person)
+ .setContentTitle("Title")
+ .setContentText("Text");
+ return createSbn(id, b);
+ }
+
+ protected static StatusBarNotification createSbn(int id, Notification n) {
+ return new StatusBarNotification(
+ TEST_PACKAGE_NAME /* pkg */,
+ TEST_PACKAGE_NAME,
+ id,
+ null /* tag */,
+ TEST_UID,
+ 0 /* initialPid */,
+ n,
+ new UserHandle(ActivityManager.getCurrentUser()),
+ null /* overrideGroupKey */,
+ 0 /* postTime */);
+ }
+
+ protected static NotificationEntry createEntry(int id, Notification n) {
+ return new NotificationEntryBuilder().setSbn(createSbn(id, n)).build();
+ }
+
+ protected static NotificationEntry createEntry(int id, Context context) {
+ return new NotificationEntryBuilder().setSbn(
+ HeadsUpManagerTestUtil.createSbn(id, context)).build();
+ }
+}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/TestableHeadsUpManager.java b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/TestableHeadsUpManager.java
new file mode 100644
index 0000000..2747629
--- /dev/null
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/policy/TestableHeadsUpManager.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.statusbar.policy;
+
+import static com.android.systemui.statusbar.notification.row.NotificationRowContentBinder.FLAG_CONTENT_VIEW_CONTRACTED;
+import static com.android.systemui.util.concurrency.MockExecutorHandlerKt.mockExecutorHandler;
+
+import static org.mockito.Mockito.spy;
+
+import android.content.Context;
+import android.graphics.Region;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+import com.android.internal.logging.UiEventLogger;
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.util.concurrency.DelayableExecutor;
+import com.android.systemui.util.settings.GlobalSettings;
+import com.android.systemui.util.time.SystemClock;
+
+class TestableHeadsUpManager extends BaseHeadsUpManager {
+
+ private HeadsUpEntry mLastCreatedEntry;
+
+ TestableHeadsUpManager(Context context,
+ HeadsUpManagerLogger logger,
+ DelayableExecutor executor,
+ GlobalSettings globalSettings,
+ SystemClock systemClock,
+ AccessibilityManagerWrapper accessibilityManagerWrapper,
+ UiEventLogger uiEventLogger) {
+ super(context, logger, mockExecutorHandler(executor), globalSettings, systemClock,
+ executor, accessibilityManagerWrapper, uiEventLogger);
+
+ mTouchAcceptanceDelay = BaseHeadsUpManagerTest.TEST_TOUCH_ACCEPTANCE_TIME;
+ mMinimumDisplayTime = BaseHeadsUpManagerTest.TEST_MINIMUM_DISPLAY_TIME;
+ mAutoDismissTime = BaseHeadsUpManagerTest.TEST_AUTO_DISMISS_TIME;
+ mStickyForSomeTimeAutoDismissTime = BaseHeadsUpManagerTest.TEST_STICKY_AUTO_DISMISS_TIME;
+ }
+
+ @Override
+ protected HeadsUpEntry createHeadsUpEntry() {
+ mLastCreatedEntry = spy(super.createHeadsUpEntry());
+ return mLastCreatedEntry;
+ }
+
+ @Override
+ public int getContentFlag() {
+ return FLAG_CONTENT_VIEW_CONTRACTED;
+ }
+
+ // The following are only implemented by HeadsUpManagerPhone. If you need them, use that.
+ @Override
+ public void addHeadsUpPhoneListener(@NonNull OnHeadsUpPhoneListenerChange listener) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void addSwipedOutNotification(@NonNull String key) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void extendHeadsUp() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Nullable
+ @Override
+ public Region getTouchableRegion() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean isHeadsUpGoingAway() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void onExpandingFinished() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean removeNotification(@NonNull String key, boolean releaseImmediately,
+ boolean animate) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setAnimationStateHandler(@NonNull AnimationStateHandler handler) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setGutsShown(@NonNull NotificationEntry entry, boolean gutsShown) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setHeadsUpGoingAway(boolean headsUpGoingAway) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setRemoteInputActive(@NonNull NotificationEntry entry,
+ boolean remoteInputActive) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setTrackingHeadsUp(boolean tracking) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean shouldSwallowClick(@NonNull String key) {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/packages/SystemUI/res/drawable/bg_shutdown_finder_message.xml b/packages/SystemUI/res/drawable/bg_shutdown_finder_message.xml
new file mode 100644
index 0000000..324ae0c
--- /dev/null
+++ b/packages/SystemUI/res/drawable/bg_shutdown_finder_message.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<shape xmlns:android="http://schemas.android.com/apk/res/android">
+ <corners android:radius="28dp" />
+ <solid android:color="@color/global_actions_lite_button_background" />
+</shape>
\ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/ic_finder_active.xml b/packages/SystemUI/res/drawable/ic_finder_active.xml
new file mode 100644
index 0000000..8ca221a
--- /dev/null
+++ b/packages/SystemUI/res/drawable/ic_finder_active.xml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="utf-8"?>
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:pathData="M12,0L12,0A12,12 0,0 1,24 12L24,12A12,12 0,0 1,12 24L12,24A12,12 0,0 1,0 12L0,12A12,12 0,0 1,12 0z"
+ android:fillColor="#00677D"/>
+ <path
+ android:pathData="M12.797,4.005C11.949,3.936 11.203,4.597 11.203,5.467V6.659C8.855,7.001 6.998,8.856 6.653,11.203H5.467C4.597,11.203 3.936,11.948 4.005,12.796L4.006,12.802L4.006,12.809C4.38,16.605 7.399,19.625 11.195,20C12.051,20.087 12.803,19.404 12.803,18.547V17.355C15.154,17.012 17.013,15.154 17.355,12.803H18.54C19.406,12.803 20.079,12.058 19.992,11.196C19.618,7.4 16.606,4.388 12.812,4.006L12.804,4.006L12.797,4.005ZM11.203,9.344V8.283C9.741,8.591 8.588,9.741 8.278,11.203H9.344C9.585,10.4 10.179,9.754 10.942,9.437C11.027,9.402 11.114,9.371 11.203,9.344ZM11.998,13.171C11.358,13.175 10.828,12.651 10.827,12.004H10.827C10.827,11.959 10.83,11.915 10.835,11.871C10.885,11.427 11.185,11.056 11.59,10.902C11.694,10.863 11.806,10.838 11.921,10.83C11.948,10.833 11.976,10.834 12.003,10.834C12.65,10.834 13.177,11.356 13.179,12.007C13.177,12.622 12.695,13.13 12.091,13.175C12.06,13.172 12.029,13.17 11.998,13.171ZM17.353,11.203H18.383C18.028,8.289 15.72,5.979 12.804,5.616V6.658C15.153,7 17.004,8.852 17.353,11.203ZM14.663,11.203C14.395,10.311 13.692,9.611 12.804,9.344V8.283C14.265,8.59 15.414,9.736 15.727,11.203H14.663ZM5.615,12.803H6.654C7.001,15.15 8.855,17.002 11.203,17.346V18.391C8.287,18.034 5.972,15.719 5.615,12.803ZM11.203,14.666C10.316,14.394 9.613,13.692 9.345,12.803H8.279C8.591,14.264 9.741,15.412 11.203,15.721V14.666ZM14.661,12.811H15.729C15.418,14.272 14.266,15.422 12.804,15.73V14.662C13.689,14.396 14.391,13.699 14.661,12.811Z"
+ android:fillColor="#ffffff"
+ android:fillType="evenOdd"/>
+</vector>
diff --git a/packages/SystemUI/res/layout/shutdown_dialog_finder_active.xml b/packages/SystemUI/res/layout/shutdown_dialog_finder_active.xml
new file mode 100644
index 0000000..b6db7fc
--- /dev/null
+++ b/packages/SystemUI/res/layout/shutdown_dialog_finder_active.xml
@@ -0,0 +1,72 @@
+<?xml version="1.0" encoding="utf-8"?>
+<androidx.constraintlayout.widget.ConstraintLayout
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:app="http://schemas.android.com/apk/res-auto"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent">
+
+ <TextView
+ android:id="@android:id/text1"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginBottom="24dp"
+ android:fontFamily="google-sans"
+ android:gravity="center"
+ android:text="@string/shutdown_progress"
+ android:textAppearance="?android:attr/textAppearanceMedium"
+ android:textDirection="locale"
+ android:textSize="18sp"
+ android:visibility="gone"
+ app:layout_constraintBottom_toTopOf="@android:id/text2"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintTop_toTopOf="parent"
+ app:layout_constraintVertical_bias="0.375"
+ app:layout_constraintVertical_chainStyle="packed" />
+
+ <TextView
+ android:id="@android:id/text2"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginBottom="24dp"
+ android:fontFamily="google-sans"
+ android:gravity="center"
+ android:text="@string/shutdown_progress"
+ android:textAppearance="?android:attr/textAppearanceLarge"
+ android:textDirection="locale"
+ android:textSize="24sp"
+ app:layout_constraintBottom_toTopOf="@android:id/progress"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintTop_toBottomOf="@android:id/text1" />
+
+ <ProgressBar
+ android:id="@android:id/progress"
+ style="?android:attr/progressBarStyleLarge"
+ android:layout_width="30dp"
+ android:layout_height="30dp"
+ android:importantForAccessibility="no"
+ app:layout_constraintBottom_toBottomOf="parent"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintTop_toBottomOf="@android:id/text2" />
+
+ <TextView
+ android:id="@+id/finer_hint"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_margin="32dp"
+ android:background="@drawable/bg_shutdown_finder_message"
+ android:drawablePadding="16dp"
+ android:drawableStart="@drawable/ic_finder_active"
+ android:fontFamily="google-sans"
+ android:gravity="start"
+ android:padding="20dp"
+ android:text="@string/finder_active"
+ android:textAppearance="?android:attr/textAppearanceSmall"
+ android:textColor="@android:color/secondary_text_dark"
+ android:textDirection="locale"
+ app:layout_constraintBottom_toBottomOf="parent"
+ app:layout_constraintTop_toBottomOf="@android:id/progress"
+ app:layout_constraintVertical_bias="1" />
+</androidx.constraintlayout.widget.ConstraintLayout>
\ No newline at end of file
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index 4263d94..ea0e309 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -2236,6 +2236,11 @@
<!-- Tuner string -->
<!-- Tuner string -->
+ <!-- Message shown during shutdown when Find My Device with Dead Battery Finder is active [CHAR LIMIT=300] -->
+ <string name="finder_active">You can locate this phone with Find My Device even when powered off</string>
+ <!-- Shutdown Progress Dialog. This is shown if the user chooses to power off the phone. [CHAR LIMIT=60] -->
+ <string name="shutdown_progress">Shutting down\u2026</string>
+
<!-- Text help link for care instructions for overheating devices [CHAR LIMIT=40] -->
<string name="thermal_shutdown_dialog_help_text">See care steps</string>
<!-- URL for care instructions for overheating devices -->
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/ActivityManagerWrapper.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/ActivityManagerWrapper.java
index 10393cf..ca63483 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/ActivityManagerWrapper.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/ActivityManagerWrapper.java
@@ -196,7 +196,7 @@
final RecentsAnimationListener animationHandler, final Consumer<Boolean> resultCallback,
Handler resultCallbackHandler) {
boolean result = startRecentsActivity(intent, eventTime, animationHandler);
- if (resultCallback != null) {
+ if (resultCallback != null && resultCallbackHandler != null) {
resultCallbackHandler.post(new Runnable() {
@Override
public void run() {
diff --git a/packages/SystemUI/src/com/android/systemui/communal/widgets/CommunalWidgetHost.kt b/packages/SystemUI/src/com/android/systemui/communal/widgets/CommunalWidgetHost.kt
index 080dbed..93e2b37 100644
--- a/packages/SystemUI/src/com/android/systemui/communal/widgets/CommunalWidgetHost.kt
+++ b/packages/SystemUI/src/com/android/systemui/communal/widgets/CommunalWidgetHost.kt
@@ -21,6 +21,7 @@
import android.appwidget.AppWidgetProviderInfo.WIDGET_FEATURE_CONFIGURATION_OPTIONAL
import android.appwidget.AppWidgetProviderInfo.WIDGET_FEATURE_RECONFIGURABLE
import android.content.ComponentName
+import android.os.Bundle
import android.os.UserHandle
import com.android.systemui.log.LogBuffer
import com.android.systemui.log.core.Logger
@@ -56,6 +57,7 @@
return widgetInfo.configure != null && !configurationOptional
}
}
+
private val logger = Logger(logBuffer, TAG)
/**
@@ -84,9 +86,16 @@
private fun bindWidget(widgetId: Int, user: UserHandle, provider: ComponentName): Boolean {
if (appWidgetManager.isPresent) {
+ val options =
+ Bundle().apply {
+ putInt(
+ AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY,
+ AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD,
+ )
+ }
return appWidgetManager
.get()
- .bindAppWidgetIdIfAllowed(widgetId, user, provider, /* options */ null)
+ .bindAppWidgetIdIfAllowed(widgetId, user, provider, options)
}
return false
}
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/FrameworkServicesModule.java b/packages/SystemUI/src/com/android/systemui/dagger/FrameworkServicesModule.java
index 6d9994f..ce24259 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/FrameworkServicesModule.java
+++ b/packages/SystemUI/src/com/android/systemui/dagger/FrameworkServicesModule.java
@@ -71,6 +71,7 @@
import android.media.projection.IMediaProjectionManager;
import android.media.projection.MediaProjectionManager;
import android.media.session.MediaSessionManager;
+import android.nearby.NearbyManager;
import android.net.ConnectivityManager;
import android.net.NetworkScoreManager;
import android.net.wifi.WifiManager;
@@ -441,6 +442,12 @@
@Provides
@Singleton
+ static NearbyManager provideNearbyManager(Context context) {
+ return context.getSystemService(NearbyManager.class);
+ }
+
+ @Provides
+ @Singleton
static NetworkScoreManager provideNetworkScoreManager(Context context) {
return context.getSystemService(NetworkScoreManager.class);
}
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/ReferenceSysUIComponent.java b/packages/SystemUI/src/com/android/systemui/dagger/ReferenceSysUIComponent.java
index a90980f..a431a59 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/ReferenceSysUIComponent.java
+++ b/packages/SystemUI/src/com/android/systemui/dagger/ReferenceSysUIComponent.java
@@ -16,7 +16,6 @@
package com.android.systemui.dagger;
-import com.android.systemui.globalactions.ShutdownUiModule;
import com.android.systemui.keyguard.CustomizationProvider;
import com.android.systemui.statusbar.NotificationInsetsModule;
import com.android.systemui.statusbar.QsFrameTranslateModule;
@@ -32,7 +31,6 @@
DependencyProvider.class,
NotificationInsetsModule.class,
QsFrameTranslateModule.class,
- ShutdownUiModule.class,
SystemUIBinder.class,
SystemUIModule.class,
SystemUICoreStartableModule.class,
diff --git a/packages/SystemUI/src/com/android/systemui/globalactions/ShutdownUi.java b/packages/SystemUI/src/com/android/systemui/globalactions/ShutdownUi.java
index 51978ec..ccd69ca 100644
--- a/packages/SystemUI/src/com/android/systemui/globalactions/ShutdownUi.java
+++ b/packages/SystemUI/src/com/android/systemui/globalactions/ShutdownUi.java
@@ -22,7 +22,10 @@
import android.annotation.StringRes;
import android.app.Dialog;
import android.content.Context;
+import android.nearby.NearbyManager;
+import android.net.platform.flags.Flags;
import android.os.PowerManager;
+import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
@@ -38,6 +41,8 @@
import com.android.systemui.statusbar.BlurUtils;
import com.android.systemui.statusbar.phone.ScrimController;
+import javax.inject.Inject;
+
/**
* Provides the UI shown during system shutdown.
*/
@@ -45,9 +50,13 @@
private Context mContext;
private BlurUtils mBlurUtils;
- public ShutdownUi(Context context, BlurUtils blurUtils) {
+ private NearbyManager mNearbyManager;
+
+ @Inject
+ public ShutdownUi(Context context, BlurUtils blurUtils, NearbyManager nearbyManager) {
mContext = context;
mBlurUtils = blurUtils;
+ mNearbyManager = nearbyManager;
}
/**
@@ -132,12 +141,28 @@
/**
* Returns the layout resource to use for UI while shutting down.
* @param isReboot Whether this is a reboot or a shutdown.
- * @return
*/
- public int getShutdownDialogContent(boolean isReboot) {
- return R.layout.shutdown_dialog;
+ @VisibleForTesting int getShutdownDialogContent(boolean isReboot) {
+ if (!Flags.poweredOffFindingPlatform()) {
+ return R.layout.shutdown_dialog;
+ }
+ int finderActive = mNearbyManager.getPoweredOffFindingMode();
+ if (finderActive == NearbyManager.POWERED_OFF_FINDING_MODE_DISABLED
+ || finderActive == NearbyManager.POWERED_OFF_FINDING_MODE_UNSUPPORTED) {
+ // inactive or unsupported, use regular shutdown dialog
+ return R.layout.shutdown_dialog;
+ } else if (finderActive == NearbyManager.POWERED_OFF_FINDING_MODE_ENABLED) {
+ // active, use dialog with finder info if shutting down
+ return isReboot ? R.layout.shutdown_dialog :
+ com.android.systemui.res.R.layout.shutdown_dialog_finder_active;
+ } else {
+ // that's weird? default to regular dialog
+ Log.w("ShutdownUi", "Unexpected value for finder active: " + finderActive);
+ return R.layout.shutdown_dialog;
+ }
}
+
@StringRes
@VisibleForTesting int getRebootMessage(boolean isReboot, @Nullable String reason) {
if (reason != null && reason.startsWith(PowerManager.REBOOT_RECOVERY_UPDATE)) {
diff --git a/packages/SystemUI/src/com/android/systemui/globalactions/ShutdownUiModule.kt b/packages/SystemUI/src/com/android/systemui/globalactions/ShutdownUiModule.kt
deleted file mode 100644
index b7285da..0000000
--- a/packages/SystemUI/src/com/android/systemui/globalactions/ShutdownUiModule.kt
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2023 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.systemui.globalactions
-
-import android.content.Context
-import com.android.systemui.statusbar.BlurUtils
-import dagger.Module
-import dagger.Provides
-
-/** Provides the UI shown during system shutdown. */
-@Module
-class ShutdownUiModule {
- /** Shutdown UI provider. */
- @Provides
- fun provideShutdownUi(context: Context?, blurUtils: BlurUtils?): ShutdownUi {
- return ShutdownUi(context, blurUtils)
- }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardClockRepository.kt b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardClockRepository.kt
index 59288a1..0ea5390 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardClockRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/KeyguardClockRepository.kt
@@ -41,7 +41,6 @@
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.callbackFlow
-import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.onStart
@@ -111,7 +110,6 @@
awaitClose { clockRegistry.unregisterClockChangeListener(listener) }
}
.mapNotNull { it }
- .distinctUntilChanged()
override val currentClock: StateFlow<ClockController?> =
currentClockId
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/DeviceEntryIconViewBinder.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/DeviceEntryIconViewBinder.kt
index 873cc84..f46a207 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/DeviceEntryIconViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/DeviceEntryIconViewBinder.kt
@@ -22,6 +22,7 @@
import android.util.StateSet
import android.view.HapticFeedbackConstants
import android.view.View
+import androidx.core.view.isInvisible
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.repeatOnLifecycle
import com.android.systemui.common.ui.view.LongPressHandlingView
@@ -82,6 +83,11 @@
// of the transition.
repeatOnLifecycle(Lifecycle.State.CREATED) {
launch {
+ viewModel.isVisible.collect { isVisible ->
+ longPressHandlingView.isInvisible = !isVisible
+ }
+ }
+ launch {
viewModel.isLongPressEnabled.collect { isEnabled ->
longPressHandlingView.setLongPressHandlingEnabled(isEnabled)
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/DeviceEntryForegroundViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/DeviceEntryForegroundViewModel.kt
index d657c24d..6281097 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/DeviceEntryForegroundViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/DeviceEntryForegroundViewModel.kt
@@ -33,6 +33,7 @@
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onStart
@@ -70,12 +71,13 @@
// While dozing, the display can show the AOD UI; show the AOD udfps when dozing
private val useAodIconVariant: Flow<Boolean> =
- combine(isShowingAodOrDozing, deviceEntryUdfpsInteractor.isUdfpsSupported) {
- isTransitionToAodOrDozing,
- isUdfps ->
- isTransitionToAodOrDozing && isUdfps
+ deviceEntryUdfpsInteractor.isUdfpsEnrolledAndEnabled.flatMapLatest { udfspEnrolled ->
+ if (udfspEnrolled) {
+ isShowingAodOrDozing.distinctUntilChanged()
+ } else {
+ flowOf(false)
}
- .distinctUntilChanged()
+ }
private val padding: Flow<Int> =
deviceEntryUdfpsInteractor.isUdfpsSupported.flatMapLatest { udfpsSupported ->
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/DeviceEntryIconViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/DeviceEntryIconViewModel.kt
index c9cf0c3..31e8093 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/DeviceEntryIconViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/DeviceEntryIconViewModel.kt
@@ -37,6 +37,7 @@
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
@@ -206,6 +207,7 @@
DeviceEntryIconView.IconType.LOCK
}
}
+ val isVisible: Flow<Boolean> = deviceEntryViewAlpha.map { it > 0f }.distinctUntilChanged()
val isLongPressEnabled: Flow<Boolean> =
combine(
iconType,
@@ -217,6 +219,7 @@
DeviceEntryIconView.IconType.FINGERPRINT -> false
}
}
+
val accessibilityDelegateHint: Flow<DeviceEntryIconView.AccessibilityHintType> =
combine(iconType, isLongPressEnabled) { deviceEntryStatus, longPressEnabled ->
if (longPressEnabled) {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/DeviceItemFactory.kt b/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/DeviceItemFactory.kt
index 1c9be0f..f13ecf3 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/DeviceItemFactory.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/DeviceItemFactory.kt
@@ -21,6 +21,7 @@
import android.media.AudioManager
import com.android.settingslib.bluetooth.BluetoothUtils
import com.android.settingslib.bluetooth.CachedBluetoothDevice
+import com.android.settingslib.flags.Flags
import com.android.systemui.res.R
private val backgroundOn = R.drawable.settingslib_switch_bar_bg_on
@@ -36,6 +37,7 @@
/** Factories to create different types of Bluetooth device items from CachedBluetoothDevice. */
internal abstract class DeviceItemFactory {
abstract fun isFilterMatched(
+ context: Context,
cachedDevice: CachedBluetoothDevice,
audioManager: AudioManager?
): Boolean
@@ -45,6 +47,7 @@
internal class ActiveMediaDeviceItemFactory : DeviceItemFactory() {
override fun isFilterMatched(
+ context: Context,
cachedDevice: CachedBluetoothDevice,
audioManager: AudioManager?
): Boolean {
@@ -71,6 +74,7 @@
internal class AvailableMediaDeviceItemFactory : DeviceItemFactory() {
override fun isFilterMatched(
+ context: Context,
cachedDevice: CachedBluetoothDevice,
audioManager: AudioManager?
): Boolean {
@@ -99,10 +103,18 @@
internal class ConnectedDeviceItemFactory : DeviceItemFactory() {
override fun isFilterMatched(
+ context: Context,
cachedDevice: CachedBluetoothDevice,
audioManager: AudioManager?
): Boolean {
- return BluetoothUtils.isConnectedBluetoothDevice(cachedDevice, audioManager)
+ return if (Flags.enableHideExclusivelyManagedBluetoothDevice()) {
+ !BluetoothUtils.isExclusivelyManagedBluetoothDevice(
+ context,
+ cachedDevice.getDevice()
+ ) && BluetoothUtils.isConnectedBluetoothDevice(cachedDevice, audioManager)
+ } else {
+ BluetoothUtils.isConnectedBluetoothDevice(cachedDevice, audioManager)
+ }
}
override fun create(context: Context, cachedDevice: CachedBluetoothDevice): DeviceItem {
@@ -125,10 +137,18 @@
internal class SavedDeviceItemFactory : DeviceItemFactory() {
override fun isFilterMatched(
+ context: Context,
cachedDevice: CachedBluetoothDevice,
audioManager: AudioManager?
): Boolean {
- return cachedDevice.bondState == BluetoothDevice.BOND_BONDED && !cachedDevice.isConnected
+ return if (Flags.enableHideExclusivelyManagedBluetoothDevice()) {
+ !BluetoothUtils.isExclusivelyManagedBluetoothDevice(
+ context,
+ cachedDevice.getDevice()
+ ) && cachedDevice.bondState == BluetoothDevice.BOND_BONDED && !cachedDevice.isConnected
+ } else {
+ cachedDevice.bondState == BluetoothDevice.BOND_BONDED && !cachedDevice.isConnected
+ }
}
override fun create(context: Context, cachedDevice: CachedBluetoothDevice): DeviceItem {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/DeviceItemInteractor.kt b/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/DeviceItemInteractor.kt
index fcd45a6..1df496b 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/DeviceItemInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/dialog/bluetooth/DeviceItemInteractor.kt
@@ -133,7 +133,7 @@
bluetoothTileDialogRepository.cachedDevices
.mapNotNull { cachedDevice ->
deviceItemFactoryList
- .firstOrNull { it.isFilterMatched(cachedDevice, audioManager) }
+ .firstOrNull { it.isFilterMatched(context, cachedDevice, audioManager) }
?.create(context, cachedDevice)
}
.sort(displayPriority, bluetoothAdapter?.mostRecentlyConnectedDevices)
diff --git a/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java b/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
index 7068f5f..d5bbaa5 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
@@ -1539,6 +1539,7 @@
@Override
public void setOpenCloseListener(OpenCloseListener openCloseListener) {
+ SceneContainerFlag.assertInLegacyMode();
mOpenCloseListener = openCloseListener;
}
diff --git a/packages/SystemUI/src/com/android/systemui/shade/ShadeControllerImpl.java b/packages/SystemUI/src/com/android/systemui/shade/ShadeControllerImpl.java
index ea41912..e6555f2e 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/ShadeControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/ShadeControllerImpl.java
@@ -32,6 +32,7 @@
import com.android.systemui.log.dagger.ShadeTouchLog;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.scene.domain.interactor.WindowRootViewVisibilityInteractor;
+import com.android.systemui.scene.shared.flag.SceneContainerFlag;
import com.android.systemui.statusbar.CommandQueue;
import com.android.systemui.statusbar.NotificationShadeWindowController;
import com.android.systemui.statusbar.StatusBarState;
@@ -98,6 +99,7 @@
statusBarKeyguardViewManager,
notificationShadeWindowController,
assistManagerLazy);
+ SceneContainerFlag.assertInLegacyMode();
mCommandQueue = commandQueue;
mMainExecutor = mainExecutor;
mWindowRootViewVisibilityInteractor = windowRootViewVisibilityInteractor;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/lockscreen/LockscreenSmartspaceController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/lockscreen/LockscreenSmartspaceController.kt
index 599600d6..0fd0555 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/lockscreen/LockscreenSmartspaceController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/lockscreen/LockscreenSmartspaceController.kt
@@ -39,7 +39,6 @@
import com.android.keyguard.KeyguardUpdateMonitor
import com.android.settingslib.Utils
import com.android.systemui.Dumpable
-import com.android.systemui.res.R
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dagger.qualifiers.Background
import com.android.systemui.dagger.qualifiers.Main
@@ -54,6 +53,7 @@
import com.android.systemui.plugins.FalsingManager
import com.android.systemui.plugins.clocks.WeatherData
import com.android.systemui.plugins.statusbar.StatusBarStateController
+import com.android.systemui.res.R
import com.android.systemui.settings.UserTracker
import com.android.systemui.shared.regionsampling.RegionSampler
import com.android.systemui.smartspace.dagger.SmartspaceModule.Companion.DATE_SMARTSPACE_DATA_PLUGIN
@@ -68,11 +68,14 @@
import com.android.systemui.util.time.SystemClock
import java.io.PrintWriter
import java.time.Instant
+import java.util.Deque
+import java.util.LinkedList
import java.util.Optional
import java.util.concurrent.Executor
import javax.inject.Inject
import javax.inject.Named
+
/** Controller for managing the smartspace view on the lockscreen */
@SysUISingleton
class LockscreenSmartspaceController
@@ -106,6 +109,8 @@
) : Dumpable {
companion object {
private const val TAG = "LockscreenSmartspaceController"
+
+ private const val MAX_RECENT_SMARTSPACE_DATA_FOR_DUMP = 5
}
private var session: SmartspaceSession? = null
@@ -114,6 +119,9 @@
private val plugin: BcSmartspaceDataPlugin? = optionalPlugin.orElse(null)
private val configPlugin: BcSmartspaceConfigPlugin? = optionalConfigPlugin.orElse(null)
+ // This stores recently received Smartspace pushes to be included in dumpsys.
+ private val recentSmartspaceData: Deque<List<SmartspaceTarget>> = LinkedList()
+
// Smartspace can be used on multiple displays, such as when the user casts their screen
private var smartspaceViews = mutableSetOf<SmartspaceView>()
private var regionSamplers =
@@ -173,6 +181,7 @@
// The weather data plugin takes unfiltered targets and performs the filtering internally.
weatherPlugin?.onTargetsAvailable(targets)
+
val now = Instant.ofEpochMilli(systemClock.currentTimeMillis())
val weatherTarget = targets.find { t ->
t.featureType == SmartspaceTarget.FEATURE_WEATHER &&
@@ -201,6 +210,14 @@
}
val filteredTargets = targets.filter(::filterSmartspaceTarget)
+
+ synchronized(recentSmartspaceData) {
+ recentSmartspaceData.offerLast(filteredTargets)
+ if (recentSmartspaceData.size > MAX_RECENT_SMARTSPACE_DATA_FOR_DUMP) {
+ recentSmartspaceData.pollFirst()
+ }
+ }
+
plugin?.onTargetsAvailable(filteredTargets)
}
@@ -588,9 +605,26 @@
return null
}
- override fun dump(pw: PrintWriter, args: Array<out String>) = pw.asIndenting().run {
- printCollection("Region Samplers", regionSamplers.values) {
- it.dump(this)
+ override fun dump(pw: PrintWriter, args: Array<out String>) {
+ pw.asIndenting().run {
+ printCollection("Region Samplers", regionSamplers.values) {
+ it.dump(this)
+ }
+ }
+
+ pw.println("Recent BC Smartspace Targets (most recent first)")
+ synchronized(recentSmartspaceData) {
+ if (recentSmartspaceData.size === 0) {
+ pw.println(" No data\n")
+ return
+ }
+ recentSmartspaceData.descendingIterator().forEachRemaining { smartspaceTargets ->
+ pw.println(" Number of targets: ${smartspaceTargets.size}")
+ for (target in smartspaceTargets) {
+ pw.println(" $target")
+ }
+ pw.println()
+ }
}
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhone.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhone.java
index b07ba3c..a155e94 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhone.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhone.java
@@ -67,7 +67,7 @@
private static final String TAG = "HeadsUpManagerPhone";
@VisibleForTesting
- final int mExtensionTime;
+ public final int mExtensionTime;
private final KeyguardBypassController mBypassController;
private final GroupMembershipManager mGroupMembershipManager;
private final List<OnHeadsUpPhoneListenerChange> mHeadsUpPhoneListeners = new ArrayList<>();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java
index 5a8b636..d975009 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java
@@ -22,6 +22,7 @@
import android.app.ActivityTaskManager;
import android.app.AlarmManager;
import android.app.AlarmManager.AlarmClockInfo;
+import android.app.NotificationManager;
import android.app.admin.DevicePolicyManager;
import android.content.BroadcastReceiver;
import android.content.Context;
@@ -379,7 +380,7 @@
}
@Override
- public void onConfigChanged(ZenModeConfig config) {
+ public void onConsolidatedPolicyChanged(NotificationManager.Policy policy) {
updateVolumeZen();
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/deviceentry/domain/ui/viewmodel/UdfpsAccessibilityOverlayViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/deviceentry/domain/ui/viewmodel/UdfpsAccessibilityOverlayViewModelTest.kt
index e97edcb..9b8cf59 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/deviceentry/domain/ui/viewmodel/UdfpsAccessibilityOverlayViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/deviceentry/domain/ui/viewmodel/UdfpsAccessibilityOverlayViewModelTest.kt
@@ -27,7 +27,7 @@
import com.android.systemui.flags.Flags.FULL_SCREEN_USER_SWITCHER
import com.android.systemui.flags.fakeFeatureFlagsClassic
import com.android.systemui.keyguard.data.repository.deviceEntryFingerprintAuthRepository
-import com.android.systemui.keyguard.data.repository.fakeKeyguardRepository
+import com.android.systemui.keyguard.data.repository.fakeBiometricSettingsRepository
import com.android.systemui.keyguard.data.repository.fakeKeyguardTransitionRepository
import com.android.systemui.keyguard.shared.model.KeyguardState
import com.android.systemui.keyguard.shared.model.TransitionState
@@ -39,6 +39,7 @@
import com.google.common.truth.Truth.assertThat
import kotlin.test.Test
import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.runner.RunWith
@@ -52,7 +53,7 @@
}
private val deviceEntryIconTransition = kosmos.fakeDeviceEntryIconViewModelTransition
private val testScope = kosmos.testScope
- private val keyguardRepository = kosmos.fakeKeyguardRepository
+ private val biometricSettingsRepository = kosmos.fakeBiometricSettingsRepository
private val accessibilityRepository = kosmos.fakeAccessibilityRepository
private val keyguardTransitionRepository = kosmos.fakeKeyguardTransitionRepository
private val fingerprintPropertyRepository = kosmos.fingerprintPropertyRepository
@@ -85,22 +86,12 @@
setupVisibleStateOnLockscreen()
// AOD
- keyguardTransitionRepository.sendTransitionStep(
- TransitionStep(
- from = KeyguardState.LOCKSCREEN,
- to = KeyguardState.AOD,
- value = 0f,
- transitionState = TransitionState.STARTED,
- )
+ keyguardTransitionRepository.sendTransitionSteps(
+ from = KeyguardState.LOCKSCREEN,
+ to = KeyguardState.AOD,
+ this,
)
- keyguardTransitionRepository.sendTransitionStep(
- TransitionStep(
- from = KeyguardState.LOCKSCREEN,
- to = KeyguardState.AOD,
- value = 1f,
- transitionState = TransitionState.FINISHED,
- )
- )
+ runCurrent()
assertThat(visible).isFalse()
}
fun fpNotRunning_overlayNotVisible() =
@@ -129,6 +120,7 @@
// Listening for UDFPS
fingerprintPropertyRepository.supportsUdfps()
+ biometricSettingsRepository.setIsFingerprintAuthEnrolledAndEnabled(true)
deviceEntryFingerprintAuthRepository.setIsRunning(true)
deviceEntryRepository.setUnlocked(false)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/globalactions/ShutdownUiTest.java b/packages/SystemUI/tests/src/com/android/systemui/globalactions/ShutdownUiTest.java
index 9d9b263..2d3ca60 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/globalactions/ShutdownUiTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/globalactions/ShutdownUiTest.java
@@ -19,7 +19,13 @@
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNull;
+import static org.mockito.Mockito.when;
+
+import android.nearby.NearbyManager;
+import android.net.platform.flags.Flags;
import android.os.PowerManager;
+import android.platform.test.annotations.DisableFlags;
+import android.platform.test.annotations.EnableFlags;
import android.testing.AndroidTestingRunner;
import androidx.test.filters.SmallTest;
@@ -32,6 +38,7 @@
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
@SmallTest
@@ -41,10 +48,13 @@
ShutdownUi mShutdownUi;
@Mock
BlurUtils mBlurUtils;
+ @Mock
+ NearbyManager mNearbyManager;
@Before
public void setUp() throws Exception {
- mShutdownUi = new ShutdownUi(getContext(), mBlurUtils);
+ MockitoAnnotations.initMocks(this);
+ mShutdownUi = new ShutdownUi(getContext(), mBlurUtils, mNearbyManager);
}
@Test
@@ -82,4 +92,53 @@
String message = mShutdownUi.getReasonMessage("anything-else");
assertNull(message);
}
+
+ @EnableFlags(Flags.FLAG_POWERED_OFF_FINDING_PLATFORM)
+ @Test
+ public void getDialog_whenPowerOffFindingModeEnabled_returnsFinderDialog() {
+ when(mNearbyManager.getPoweredOffFindingMode()).thenReturn(
+ NearbyManager.POWERED_OFF_FINDING_MODE_ENABLED);
+
+ int actualLayout = mShutdownUi.getShutdownDialogContent(false);
+
+ int expectedLayout = com.android.systemui.res.R.layout.shutdown_dialog_finder_active;
+ assertEquals(actualLayout, expectedLayout);
+ }
+
+ @DisableFlags(Flags.FLAG_POWERED_OFF_FINDING_PLATFORM)
+ @Test
+ public void getDialog_whenPowerOffFindingModeEnabledFlagDisabled_returnsFinderDialog() {
+ when(mNearbyManager.getPoweredOffFindingMode()).thenReturn(
+ NearbyManager.POWERED_OFF_FINDING_MODE_ENABLED);
+
+ int actualLayout = mShutdownUi.getShutdownDialogContent(false);
+
+ int expectedLayout = R.layout.shutdown_dialog;
+ assertEquals(actualLayout, expectedLayout);
+ }
+
+ @EnableFlags(Flags.FLAG_POWERED_OFF_FINDING_PLATFORM)
+ @Test
+ public void getDialog_whenPowerOffFindingModeDisabled_returnsDefaultDialog() {
+ when(mNearbyManager.getPoweredOffFindingMode()).thenReturn(
+ NearbyManager.POWERED_OFF_FINDING_MODE_DISABLED);
+
+ int actualLayout = mShutdownUi.getShutdownDialogContent(false);
+
+ int expectedLayout = R.layout.shutdown_dialog;
+ assertEquals(actualLayout, expectedLayout);
+ }
+
+ @EnableFlags(Flags.FLAG_POWERED_OFF_FINDING_PLATFORM)
+ @Test
+ public void getDialog_whenPowerOffFindingModeEnabledAndIsReboot_returnsDefaultDialog() {
+ when(mNearbyManager.getPoweredOffFindingMode()).thenReturn(
+ NearbyManager.POWERED_OFF_FINDING_MODE_ENABLED);
+
+ int actualLayout = mShutdownUi.getShutdownDialogContent(true);
+
+ int expectedLayout = R.layout.shutdown_dialog;
+ assertEquals(actualLayout, expectedLayout);
+ }
+
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/DeviceEntryIconViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/DeviceEntryIconViewModelTest.kt
new file mode 100644
index 0000000..02bd810
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/DeviceEntryIconViewModelTest.kt
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.keyguard.ui.viewmodel
+
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.biometrics.data.repository.FakeFingerprintPropertyRepository
+import com.android.systemui.biometrics.data.repository.fingerprintPropertyRepository
+import com.android.systemui.coroutines.collectLastValue
+import com.android.systemui.keyguard.data.repository.FakeDeviceEntryFingerprintAuthRepository
+import com.android.systemui.keyguard.data.repository.FakeKeyguardRepository
+import com.android.systemui.keyguard.data.repository.fakeDeviceEntryFingerprintAuthRepository
+import com.android.systemui.keyguard.data.repository.fakeKeyguardRepository
+import com.android.systemui.keyguard.data.repository.keyguardRepository
+import com.android.systemui.kosmos.testScope
+import com.android.systemui.testKosmos
+import com.google.common.truth.Truth.assertThat
+import kotlin.test.Test
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.runner.RunWith
+
+@ExperimentalCoroutinesApi
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class DeviceEntryIconViewModelTest : SysuiTestCase() {
+ private val kosmos = testKosmos()
+ private val testScope = kosmos.testScope
+ private lateinit var keyguardRepository: FakeKeyguardRepository
+ private lateinit var fingerprintPropertyRepository: FakeFingerprintPropertyRepository
+ private lateinit var fingerprintAuthRepository: FakeDeviceEntryFingerprintAuthRepository
+ private lateinit var deviceEntryIconTransition: FakeDeviceEntryIconTransition
+ private lateinit var underTest: DeviceEntryIconViewModel
+
+ @Before
+ fun setUp() {
+ keyguardRepository = kosmos.fakeKeyguardRepository
+ fingerprintPropertyRepository = kosmos.fingerprintPropertyRepository
+ fingerprintAuthRepository = kosmos.fakeDeviceEntryFingerprintAuthRepository
+ deviceEntryIconTransition = kosmos.fakeDeviceEntryIconViewModelTransition
+ underTest = kosmos.deviceEntryIconViewModel
+ }
+
+ @Test
+ fun isLongPressEnabled_udfpsRunning() =
+ testScope.runTest {
+ val isLongPressEnabled by collectLastValue(underTest.isLongPressEnabled)
+ fingerprintPropertyRepository.supportsUdfps()
+ fingerprintAuthRepository.setIsRunning(true)
+ keyguardRepository.setKeyguardDismissible(false)
+ assertThat(isLongPressEnabled).isFalse()
+ }
+
+ @Test
+ fun isLongPressEnabled_unlocked() =
+ testScope.runTest {
+ val isLongPressEnabled by collectLastValue(underTest.isLongPressEnabled)
+ keyguardRepository.setKeyguardDismissible(true)
+ assertThat(isLongPressEnabled).isTrue()
+ }
+
+ @Test
+ fun isLongPressEnabled_lock() =
+ testScope.runTest {
+ val isLongPressEnabled by collectLastValue(underTest.isLongPressEnabled)
+ keyguardRepository.setKeyguardDismissible(false)
+
+ // udfps supported
+ fingerprintPropertyRepository.supportsUdfps()
+ assertThat(isLongPressEnabled).isTrue()
+
+ // udfps isn't supported
+ fingerprintPropertyRepository.supportsRearFps()
+ assertThat(isLongPressEnabled).isFalse()
+ }
+
+ @Test
+ fun isVisible() =
+ testScope.runTest {
+ val isVisible by collectLastValue(underTest.isVisible)
+ deviceEntryIconTransitionAlpha(1f)
+ assertThat(isVisible).isTrue()
+
+ deviceEntryIconTransitionAlpha(0f)
+ assertThat(isVisible).isFalse()
+
+ deviceEntryIconTransitionAlpha(.5f)
+ assertThat(isVisible).isTrue()
+ }
+
+ private fun deviceEntryIconTransitionAlpha(alpha: Float) {
+ deviceEntryIconTransition.setDeviceEntryParentViewAlpha(alpha)
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/DeviceItemFactoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/DeviceItemFactoryTest.kt
index 92c7326..a8cd8c8 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/DeviceItemFactoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/DeviceItemFactoryTest.kt
@@ -16,10 +16,18 @@
package com.android.systemui.qs.tiles.dialog.bluetooth
+import android.bluetooth.BluetoothDevice
+import android.content.pm.PackageInfo
+import android.content.pm.PackageManager
+import android.media.AudioManager
+import android.platform.test.annotations.DisableFlags
+import android.platform.test.annotations.EnableFlags
import android.testing.AndroidTestingRunner
import android.testing.TestableLooper
import androidx.test.filters.SmallTest
+import com.android.settingslib.bluetooth.BluetoothUtils
import com.android.settingslib.bluetooth.CachedBluetoothDevice
+import com.android.settingslib.flags.Flags
import com.android.systemui.SysuiTestCase
import com.google.common.truth.Truth.assertThat
import org.junit.Before
@@ -35,19 +43,26 @@
@RunWith(AndroidTestingRunner::class)
@TestableLooper.RunWithLooper(setAsMainLooper = true)
class DeviceItemFactoryTest : SysuiTestCase() {
-
@get:Rule val mockitoRule: MockitoRule = MockitoJUnit.rule()
@Mock private lateinit var cachedDevice: CachedBluetoothDevice
+ @Mock private lateinit var bluetoothDevice: BluetoothDevice
+ @Mock private lateinit var packageManager: PackageManager
private val availableMediaDeviceItemFactory = AvailableMediaDeviceItemFactory()
private val connectedDeviceItemFactory = ConnectedDeviceItemFactory()
private val savedDeviceItemFactory = SavedDeviceItemFactory()
+ private val audioManager = context.getSystemService(AudioManager::class.java)!!
+
@Before
fun setup() {
`when`(cachedDevice.name).thenReturn(DEVICE_NAME)
+ `when`(cachedDevice.address).thenReturn(DEVICE_ADDRESS)
+ `when`(cachedDevice.device).thenReturn(bluetoothDevice)
`when`(cachedDevice.connectionSummary).thenReturn(CONNECTION_SUMMARY)
+
+ context.setMockPackageManager(packageManager)
}
@Test
@@ -72,6 +87,225 @@
assertThat(deviceItem.background).isNotNull()
}
+ @Test
+ @DisableFlags(Flags.FLAG_ENABLE_HIDE_EXCLUSIVELY_MANAGED_BLUETOOTH_DEVICE)
+ fun testSavedFactory_isFilterMatched_bondedAndNotConnected_returnsTrue() {
+ `when`(cachedDevice.bondState).thenReturn(BluetoothDevice.BOND_BONDED)
+ `when`(cachedDevice.isConnected).thenReturn(false)
+
+ assertThat(savedDeviceItemFactory.isFilterMatched(context, cachedDevice, audioManager))
+ .isTrue()
+ }
+
+ @Test
+ @DisableFlags(Flags.FLAG_ENABLE_HIDE_EXCLUSIVELY_MANAGED_BLUETOOTH_DEVICE)
+ fun testSavedFactory_isFilterMatched_connected_returnsFalse() {
+ `when`(cachedDevice.bondState).thenReturn(BluetoothDevice.BOND_BONDED)
+ `when`(cachedDevice.isConnected).thenReturn(true)
+
+ assertThat(savedDeviceItemFactory.isFilterMatched(context, cachedDevice, audioManager))
+ .isFalse()
+ }
+
+ @Test
+ @DisableFlags(Flags.FLAG_ENABLE_HIDE_EXCLUSIVELY_MANAGED_BLUETOOTH_DEVICE)
+ fun testSavedFactory_isFilterMatched_notBonded_returnsFalse() {
+ `when`(cachedDevice.bondState).thenReturn(BluetoothDevice.BOND_NONE)
+ `when`(cachedDevice.isConnected).thenReturn(false)
+
+ assertThat(savedDeviceItemFactory.isFilterMatched(context, cachedDevice, audioManager))
+ .isFalse()
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_HIDE_EXCLUSIVELY_MANAGED_BLUETOOTH_DEVICE)
+ fun testSavedFactory_isFilterMatched_exclusivelyManaged_returnsFalse() {
+ val exclusiveManagerName =
+ BluetoothUtils.getExclusiveManagers().firstOrNull() ?: FAKE_EXCLUSIVE_MANAGER_NAME
+ `when`(bluetoothDevice.getMetadata(BluetoothDevice.METADATA_EXCLUSIVE_MANAGER))
+ .thenReturn(exclusiveManagerName.toByteArray())
+ `when`(packageManager.getPackageInfo(exclusiveManagerName, 0)).thenReturn(PackageInfo())
+ `when`(cachedDevice.bondState).thenReturn(BluetoothDevice.BOND_BONDED)
+ `when`(cachedDevice.isConnected).thenReturn(false)
+
+ assertThat(savedDeviceItemFactory.isFilterMatched(context, cachedDevice, audioManager))
+ .isFalse()
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_HIDE_EXCLUSIVELY_MANAGED_BLUETOOTH_DEVICE)
+ fun testSavedFactory_isFilterMatched_noExclusiveManager_returnsTrue() {
+ `when`(cachedDevice.bondState).thenReturn(BluetoothDevice.BOND_BONDED)
+ `when`(cachedDevice.isConnected).thenReturn(false)
+
+ assertThat(savedDeviceItemFactory.isFilterMatched(context, cachedDevice, audioManager))
+ .isTrue()
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_HIDE_EXCLUSIVELY_MANAGED_BLUETOOTH_DEVICE)
+ fun testSavedFactory_isFilterMatched_notAllowedExclusiveManager_returnsTrue() {
+ `when`(bluetoothDevice.getMetadata(BluetoothDevice.METADATA_EXCLUSIVE_MANAGER))
+ .thenReturn(FAKE_EXCLUSIVE_MANAGER_NAME.toByteArray())
+ `when`(packageManager.getPackageInfo(FAKE_EXCLUSIVE_MANAGER_NAME, 0))
+ .thenReturn(PackageInfo())
+ `when`(cachedDevice.bondState).thenReturn(BluetoothDevice.BOND_BONDED)
+ `when`(cachedDevice.isConnected).thenReturn(false)
+
+ assertThat(savedDeviceItemFactory.isFilterMatched(context, cachedDevice, audioManager))
+ .isTrue()
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_HIDE_EXCLUSIVELY_MANAGED_BLUETOOTH_DEVICE)
+ fun testSavedFactory_isFilterMatched_uninstalledExclusiveManager_returnsTrue() {
+ val exclusiveManagerName =
+ BluetoothUtils.getExclusiveManagers().firstOrNull() ?: FAKE_EXCLUSIVE_MANAGER_NAME
+ `when`(bluetoothDevice.getMetadata(BluetoothDevice.METADATA_EXCLUSIVE_MANAGER))
+ .thenReturn(exclusiveManagerName.toByteArray())
+ `when`(packageManager.getPackageInfo(exclusiveManagerName, 0))
+ .thenThrow(PackageManager.NameNotFoundException("Test!"))
+ `when`(cachedDevice.bondState).thenReturn(BluetoothDevice.BOND_BONDED)
+ `when`(cachedDevice.isConnected).thenReturn(false)
+
+ assertThat(savedDeviceItemFactory.isFilterMatched(context, cachedDevice, audioManager))
+ .isTrue()
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_HIDE_EXCLUSIVELY_MANAGED_BLUETOOTH_DEVICE)
+ fun testSavedFactory_isFilterMatched_notExclusivelyManaged_notBonded_returnsFalse() {
+ `when`(cachedDevice.bondState).thenReturn(BluetoothDevice.BOND_NONE)
+ `when`(cachedDevice.isConnected).thenReturn(false)
+
+ assertThat(savedDeviceItemFactory.isFilterMatched(context, cachedDevice, audioManager))
+ .isFalse()
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_HIDE_EXCLUSIVELY_MANAGED_BLUETOOTH_DEVICE)
+ fun testSavedFactory_isFilterMatched_notExclusivelyManaged_connected_returnsFalse() {
+ `when`(cachedDevice.bondState).thenReturn(BluetoothDevice.BOND_BONDED)
+ `when`(cachedDevice.isConnected).thenReturn(true)
+
+ assertThat(savedDeviceItemFactory.isFilterMatched(context, cachedDevice, audioManager))
+ .isFalse()
+ }
+
+ @Test
+ @DisableFlags(Flags.FLAG_ENABLE_HIDE_EXCLUSIVELY_MANAGED_BLUETOOTH_DEVICE)
+ fun testConnectedFactory_isFilterMatched_bondedAndConnected_returnsTrue() {
+ `when`(bluetoothDevice.bondState).thenReturn(BluetoothDevice.BOND_BONDED)
+ `when`(bluetoothDevice.isConnected).thenReturn(true)
+ audioManager.setMode(AudioManager.MODE_NORMAL)
+
+ assertThat(connectedDeviceItemFactory.isFilterMatched(context, cachedDevice, audioManager))
+ .isTrue()
+ }
+
+ @Test
+ @DisableFlags(Flags.FLAG_ENABLE_HIDE_EXCLUSIVELY_MANAGED_BLUETOOTH_DEVICE)
+ fun testConnectedFactory_isFilterMatched_notConnected_returnsFalse() {
+ `when`(bluetoothDevice.bondState).thenReturn(BluetoothDevice.BOND_BONDED)
+ `when`(bluetoothDevice.isConnected).thenReturn(false)
+ audioManager.setMode(AudioManager.MODE_NORMAL)
+
+ assertThat(connectedDeviceItemFactory.isFilterMatched(context, cachedDevice, audioManager))
+ .isFalse()
+ }
+
+ @Test
+ @DisableFlags(Flags.FLAG_ENABLE_HIDE_EXCLUSIVELY_MANAGED_BLUETOOTH_DEVICE)
+ fun testConnectedFactory_isFilterMatched_notBonded_returnsFalse() {
+ `when`(bluetoothDevice.bondState).thenReturn(BluetoothDevice.BOND_NONE)
+ `when`(bluetoothDevice.isConnected).thenReturn(true)
+ audioManager.setMode(AudioManager.MODE_NORMAL)
+
+ assertThat(connectedDeviceItemFactory.isFilterMatched(context, cachedDevice, audioManager))
+ .isFalse()
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_HIDE_EXCLUSIVELY_MANAGED_BLUETOOTH_DEVICE)
+ fun testConnectedFactory_isFilterMatched_exclusivelyManaged_returnsFalse() {
+ val exclusiveManagerName =
+ BluetoothUtils.getExclusiveManagers().firstOrNull() ?: FAKE_EXCLUSIVE_MANAGER_NAME
+ `when`(bluetoothDevice.getMetadata(BluetoothDevice.METADATA_EXCLUSIVE_MANAGER))
+ .thenReturn(exclusiveManagerName.toByteArray())
+ `when`(packageManager.getPackageInfo(exclusiveManagerName, 0)).thenReturn(PackageInfo())
+ `when`(bluetoothDevice.bondState).thenReturn(BluetoothDevice.BOND_BONDED)
+ `when`(bluetoothDevice.isConnected).thenReturn(true)
+ audioManager.setMode(AudioManager.MODE_NORMAL)
+
+ assertThat(connectedDeviceItemFactory.isFilterMatched(context, cachedDevice, audioManager))
+ .isFalse()
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_HIDE_EXCLUSIVELY_MANAGED_BLUETOOTH_DEVICE)
+ fun testConnectedFactory_isFilterMatched_noExclusiveManager_returnsTrue() {
+ `when`(bluetoothDevice.bondState).thenReturn(BluetoothDevice.BOND_BONDED)
+ `when`(bluetoothDevice.isConnected).thenReturn(true)
+ audioManager.setMode(AudioManager.MODE_NORMAL)
+
+ assertThat(connectedDeviceItemFactory.isFilterMatched(context, cachedDevice, audioManager))
+ .isTrue()
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_HIDE_EXCLUSIVELY_MANAGED_BLUETOOTH_DEVICE)
+ fun testConnectedFactory_isFilterMatched_notAllowedExclusiveManager_returnsTrue() {
+ `when`(bluetoothDevice.getMetadata(BluetoothDevice.METADATA_EXCLUSIVE_MANAGER))
+ .thenReturn(FAKE_EXCLUSIVE_MANAGER_NAME.toByteArray())
+ `when`(packageManager.getPackageInfo(FAKE_EXCLUSIVE_MANAGER_NAME, 0))
+ .thenReturn(PackageInfo())
+ `when`(bluetoothDevice.bondState).thenReturn(BluetoothDevice.BOND_BONDED)
+ `when`(bluetoothDevice.isConnected).thenReturn(true)
+ audioManager.setMode(AudioManager.MODE_NORMAL)
+
+ assertThat(connectedDeviceItemFactory.isFilterMatched(context, cachedDevice, audioManager))
+ .isTrue()
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_HIDE_EXCLUSIVELY_MANAGED_BLUETOOTH_DEVICE)
+ fun testConnectedFactory_isFilterMatched_uninstalledExclusiveManager_returnsTrue() {
+ val exclusiveManagerName =
+ BluetoothUtils.getExclusiveManagers().firstOrNull() ?: FAKE_EXCLUSIVE_MANAGER_NAME
+ `when`(bluetoothDevice.getMetadata(BluetoothDevice.METADATA_EXCLUSIVE_MANAGER))
+ .thenReturn(exclusiveManagerName.toByteArray())
+ `when`(packageManager.getPackageInfo(exclusiveManagerName, 0))
+ .thenThrow(PackageManager.NameNotFoundException("Test!"))
+ `when`(bluetoothDevice.bondState).thenReturn(BluetoothDevice.BOND_BONDED)
+ `when`(bluetoothDevice.isConnected).thenReturn(true)
+ audioManager.setMode(AudioManager.MODE_NORMAL)
+
+ assertThat(connectedDeviceItemFactory.isFilterMatched(context, cachedDevice, audioManager))
+ .isTrue()
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_HIDE_EXCLUSIVELY_MANAGED_BLUETOOTH_DEVICE)
+ fun testConnectedFactory_isFilterMatched_notExclusivelyManaged_notBonded_returnsFalse() {
+ `when`(bluetoothDevice.bondState).thenReturn(BluetoothDevice.BOND_NONE)
+ `when`(bluetoothDevice.isConnected).thenReturn(true)
+ audioManager.setMode(AudioManager.MODE_NORMAL)
+
+ assertThat(connectedDeviceItemFactory.isFilterMatched(context, cachedDevice, audioManager))
+ .isFalse()
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_HIDE_EXCLUSIVELY_MANAGED_BLUETOOTH_DEVICE)
+ fun testConnectedFactory_isFilterMatched_notExclusivelyManaged_notConnected_returnsFalse() {
+ `when`(bluetoothDevice.bondState).thenReturn(BluetoothDevice.BOND_BONDED)
+ `when`(bluetoothDevice.isConnected).thenReturn(false)
+ audioManager.setMode(AudioManager.MODE_NORMAL)
+
+ assertThat(connectedDeviceItemFactory.isFilterMatched(context, cachedDevice, audioManager))
+ .isFalse()
+ }
+
private fun assertDeviceItem(deviceItem: DeviceItem?, deviceItemType: DeviceItemType) {
assertThat(deviceItem).isNotNull()
assertThat(deviceItem!!.type).isEqualTo(deviceItemType)
@@ -83,5 +317,7 @@
companion object {
const val DEVICE_NAME = "DeviceName"
const val CONNECTION_SUMMARY = "ConnectionSummary"
+ private const val FAKE_EXCLUSIVE_MANAGER_NAME = "com.fake.name"
+ private const val DEVICE_ADDRESS = "04:52:C7:0B:D8:3C"
}
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/DeviceItemInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/DeviceItemInteractorTest.kt
index e236f4a..ddf0b9a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/DeviceItemInteractorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/dialog/bluetooth/DeviceItemInteractorTest.kt
@@ -279,6 +279,7 @@
): DeviceItemFactory {
return object : DeviceItemFactory() {
override fun isFilterMatched(
+ context: Context,
cachedDevice: CachedBluetoothDevice,
audioManager: AudioManager?
) = isFilterMatchFunc(cachedDevice)
diff --git a/ravenwood/framework-minus-apex-ravenwood-policies.txt b/ravenwood/framework-minus-apex-ravenwood-policies.txt
index 6b67364..371c3ac 100644
--- a/ravenwood/framework-minus-apex-ravenwood-policies.txt
+++ b/ravenwood/framework-minus-apex-ravenwood-policies.txt
@@ -55,3 +55,5 @@
method getSystemService (Ljava/lang/Class;)Ljava/lang/Object; stub
class android.content.pm.PackageManager stub
method <init> ()V stub
+class android.text.ClipboardManager stub
+ method <init> ()V stub
diff --git a/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodContext.java b/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodContext.java
index 3668b03..c17d090 100644
--- a/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodContext.java
+++ b/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodContext.java
@@ -16,18 +16,28 @@
package android.platform.test.ravenwood;
+import android.content.ClipboardManager;
import android.content.Context;
import android.hardware.ISerialManager;
import android.hardware.SerialManager;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.Looper;
import android.os.PermissionEnforcer;
import android.os.ServiceManager;
+import android.os.UserHandle;
import android.test.mock.MockContext;
import android.util.ArrayMap;
import android.util.Singleton;
+import java.util.Objects;
+import java.util.concurrent.Executor;
import java.util.function.Supplier;
public class RavenwoodContext extends MockContext {
+ private final String mPackageName;
+ private final HandlerThread mMainThread;
+
private final RavenwoodPermissionEnforcer mEnforcer = new RavenwoodPermissionEnforcer();
private final ArrayMap<Class<?>, String> mClassToName = new ArrayMap<>();
@@ -39,7 +49,13 @@
mNameToFactory.put(serviceName, serviceSupplier);
}
- public RavenwoodContext() {
+ public RavenwoodContext(String packageName, HandlerThread mainThread) {
+ mPackageName = packageName;
+ mMainThread = mainThread;
+
+ registerService(ClipboardManager.class,
+ Context.CLIPBOARD_SERVICE, asSingleton(() ->
+ new ClipboardManager(this, getMainThreadHandler())));
registerService(PermissionEnforcer.class,
Context.PERMISSION_ENFORCER_SERVICE, () -> mEnforcer);
registerService(SerialManager.class,
@@ -73,18 +89,79 @@
}
}
+ @Override
+ public Looper getMainLooper() {
+ Objects.requireNonNull(mMainThread,
+ "Test must request setProvideMainThread() via RavenwoodRule");
+ return mMainThread.getLooper();
+ }
+
+ @Override
+ public Handler getMainThreadHandler() {
+ Objects.requireNonNull(mMainThread,
+ "Test must request setProvideMainThread() via RavenwoodRule");
+ return mMainThread.getThreadHandler();
+ }
+
+ @Override
+ public Executor getMainExecutor() {
+ Objects.requireNonNull(mMainThread,
+ "Test must request setProvideMainThread() via RavenwoodRule");
+ return mMainThread.getThreadExecutor();
+ }
+
+ @Override
+ public String getPackageName() {
+ return Objects.requireNonNull(mPackageName,
+ "Test must request setPackageName() via RavenwoodRule");
+ }
+
+ @Override
+ public String getOpPackageName() {
+ return Objects.requireNonNull(mPackageName,
+ "Test must request setPackageName() via RavenwoodRule");
+ }
+
+ @Override
+ public String getAttributionTag() {
+ return null;
+ }
+
+ @Override
+ public UserHandle getUser() {
+ return android.os.UserHandle.of(android.os.UserHandle.myUserId());
+ }
+
+ @Override
+ public int getUserId() {
+ return android.os.UserHandle.myUserId();
+ }
+
+ @Override
+ public int getDeviceId() {
+ return Context.DEVICE_ID_DEFAULT;
+ }
+
/**
* Wrap the given {@link Supplier} to become a memoized singleton.
*/
- private static <T> Supplier<T> asSingleton(Supplier<T> supplier) {
+ private static <T> Supplier<T> asSingleton(ThrowingSupplier<T> supplier) {
final Singleton<T> singleton = new Singleton<>() {
@Override
protected T create() {
- return supplier.get();
+ try {
+ return supplier.get();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
}
};
return () -> {
return singleton.get();
};
}
+
+ public interface ThrowingSupplier<T> {
+ T get() throws Exception;
+ }
}
diff --git a/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodRuleImpl.java b/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodRuleImpl.java
index 231cce9..56a3c64 100644
--- a/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodRuleImpl.java
+++ b/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodRuleImpl.java
@@ -110,13 +110,16 @@
ActivityManager.init$ravenwood(rule.mCurrentUser);
+ final HandlerThread main;
if (rule.mProvideMainThread) {
- final HandlerThread main = new HandlerThread(MAIN_THREAD_NAME);
+ main = new HandlerThread(MAIN_THREAD_NAME);
main.start();
Looper.setMainLooperForTest(main.getLooper());
+ } else {
+ main = null;
}
- rule.mContext = new RavenwoodContext();
+ rule.mContext = new RavenwoodContext(rule.mPackageName, main);
rule.mInstrumentation = new Instrumentation();
rule.mInstrumentation.basicInit(rule.mContext);
InstrumentationRegistry.registerInstance(rule.mInstrumentation, Bundle.EMPTY);
diff --git a/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodSystemServer.java b/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodSystemServer.java
index bb280f4..3de96c0 100644
--- a/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodSystemServer.java
+++ b/ravenwood/junit-impl-src/android/platform/test/ravenwood/RavenwoodSystemServer.java
@@ -16,6 +16,7 @@
package android.platform.test.ravenwood;
+import android.content.ClipboardManager;
import android.hardware.SerialManager;
import android.os.SystemClock;
import android.util.ArrayMap;
@@ -40,7 +41,10 @@
// authors to exhaustively declare all transitive services
static {
- sKnownServices.put(SerialManager.class, "com.android.server.SerialService$Lifecycle");
+ sKnownServices.put(ClipboardManager.class,
+ "com.android.server.FakeClipboardService$Lifecycle");
+ sKnownServices.put(SerialManager.class,
+ "com.android.server.SerialService$Lifecycle");
}
private static TimingsTraceAndSlog sTimings;
diff --git a/ravenwood/junit-src/android/platform/test/ravenwood/RavenwoodRule.java b/ravenwood/junit-src/android/platform/test/ravenwood/RavenwoodRule.java
index a8c24fc..a520d4c 100644
--- a/ravenwood/junit-src/android/platform/test/ravenwood/RavenwoodRule.java
+++ b/ravenwood/junit-src/android/platform/test/ravenwood/RavenwoodRule.java
@@ -121,6 +121,8 @@
int mUid = NOBODY_UID;
int mPid = sNextPid.getAndIncrement();
+ String mPackageName;
+
boolean mProvideMainThread = false;
final RavenwoodSystemProperties mSystemProperties = new RavenwoodSystemProperties();
@@ -158,6 +160,15 @@
}
/**
+ * Configure the identity of this process to be the given package name for the duration
+ * of the test. Has no effect on non-Ravenwood environments.
+ */
+ public Builder setPackageName(/* @NonNull */ String packageName) {
+ mRule.mPackageName = Objects.requireNonNull(packageName);
+ return this;
+ }
+
+ /**
* Configure a "main" thread to be available for the duration of the test, as defined
* by {@code Looper.getMainLooper()}. Has no effect on non-Ravenwood environments.
*/
diff --git a/ravenwood/ravenwood-annotation-allowed-classes.txt b/ravenwood/ravenwood-annotation-allowed-classes.txt
index eb3c55c..9b4d378 100644
--- a/ravenwood/ravenwood-annotation-allowed-classes.txt
+++ b/ravenwood/ravenwood-annotation-allowed-classes.txt
@@ -186,6 +186,7 @@
android.content.ClipData
android.content.ClipData$Item
android.content.ClipDescription
+android.content.ClipboardManager
android.content.ComponentName
android.content.ContentUris
android.content.ContentValues
diff --git a/rs/java/android/renderscript/ScriptC.java b/rs/java/android/renderscript/ScriptC.java
index 4a2f3da..e9f6031 100644
--- a/rs/java/android/renderscript/ScriptC.java
+++ b/rs/java/android/renderscript/ScriptC.java
@@ -38,12 +38,12 @@
private static final String TAG = "ScriptC";
/**
- * In targetSdkVersion 35 and above, Renderscript's ScriptC stops being supported
+ * In targetSdkVersion 36 and above, Renderscript's ScriptC stops being supported
* and an exception is thrown when the class is instantiated.
- * In targetSdkVersion 34 and below, Renderscript's ScriptC still works.
+ * In targetSdkVersion 35 and below, Renderscript's ScriptC still works.
*/
@ChangeId
- @EnabledAfter(targetSdkVersion = 35)
+ @EnabledAfter(targetSdkVersion = 36)
private static final long RENDERSCRIPT_SCRIPTC_DEPRECATION_CHANGE_ID = 297019750L;
/**
@@ -113,9 +113,9 @@
throw new UnsupportedOperationException(s);
}
- // Throw an exception if the target API is 35 or above
+ // Throw an exception if the target API is 36 or above
String message =
- "ScriptC scripts are not supported when targeting an API Level >= 35. Please refer "
+ "ScriptC scripts are not supported when targeting an API Level >= 36. Please refer "
+ "to https://developer.android.com/guide/topics/renderscript/migration-guide "
+ "for proposed alternatives.";
Slog.w(TAG, message);
diff --git a/services/autofill/java/com/android/server/autofill/Session.java b/services/autofill/java/com/android/server/autofill/Session.java
index c7b844b..d779fbf 100644
--- a/services/autofill/java/com/android/server/autofill/Session.java
+++ b/services/autofill/java/com/android/server/autofill/Session.java
@@ -193,7 +193,6 @@
import com.android.server.wm.ActivityTaskManagerInternal;
import java.io.PrintWriter;
-import java.io.Serializable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
@@ -2821,8 +2820,9 @@
mSessionFlags.mExpiredResponse = false;
final Parcelable result = data.getParcelable(AutofillManager.EXTRA_AUTHENTICATION_RESULT);
- final Serializable exception = data.getSerializable(
- CredentialProviderService.EXTRA_GET_CREDENTIAL_EXCEPTION);
+ final GetCredentialException exception = data.getSerializable(
+ CredentialProviderService.EXTRA_GET_CREDENTIAL_EXCEPTION,
+ GetCredentialException.class);
final Bundle newClientState = data.getBundle(AutofillManager.EXTRA_CLIENT_STATE);
if (sDebug) {
@@ -5126,6 +5126,10 @@
toIpcFriendlyResultReceiver(resultReceiver);
Intent metadataIntent = dataset.getCredentialFillInIntent();
+ if (metadataIntent == null) {
+ metadataIntent = new Intent();
+ }
+
metadataIntent.putExtra(
android.credentials.selection.Constants.EXTRA_FINAL_RESPONSE_RECEIVER,
ipcFriendlyResultReceiver);
diff --git a/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java b/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java
index 966fe5b..d1bda79 100644
--- a/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java
+++ b/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java
@@ -126,6 +126,7 @@
"arc_next",
"avic",
"bluetooth",
+ "brownout_mitigation_audio",
"build",
"biometrics",
"biometrics_framework",
diff --git a/services/core/java/com/android/server/ambientcontext/AmbientContextManagerService.java b/services/core/java/com/android/server/ambientcontext/AmbientContextManagerService.java
index 5f12ce1..9f31f37 100644
--- a/services/core/java/com/android/server/ambientcontext/AmbientContextManagerService.java
+++ b/services/core/java/com/android/server/ambientcontext/AmbientContextManagerService.java
@@ -73,8 +73,7 @@
private static final Set<Integer> DEFAULT_EVENT_SET = Sets.newHashSet(
AmbientContextEvent.EVENT_COUGH,
AmbientContextEvent.EVENT_SNORE,
- AmbientContextEvent.EVENT_BACK_DOUBLE_TAP,
- AmbientContextEvent.EVENT_HEART_RATE);
+ AmbientContextEvent.EVENT_BACK_DOUBLE_TAP);
/** Default value in absence of {@link DeviceConfig} override. */
private static final boolean DEFAULT_SERVICE_ENABLED = true;
diff --git a/services/core/java/com/android/server/appop/AppOpsService.java b/services/core/java/com/android/server/appop/AppOpsService.java
index 0cc6494..fb62785 100644
--- a/services/core/java/com/android/server/appop/AppOpsService.java
+++ b/services/core/java/com/android/server/appop/AppOpsService.java
@@ -661,8 +661,12 @@
@NonNull OpEntry createEntryLocked(String persistentDeviceId) {
// TODO(b/308201969): Update this method when we introduce disk persistence of events
// for accesses on external devices.
- final ArrayMap<String, AttributedOp> attributedOps = mDeviceAttributedOps.get(
+ ArrayMap<String, AttributedOp> attributedOps = mDeviceAttributedOps.get(
persistentDeviceId);
+ if (attributedOps == null) {
+ attributedOps = new ArrayMap<>();
+ }
+
final ArrayMap<String, AppOpsManager.AttributedOpEntry> attributionEntries =
new ArrayMap<>(attributedOps.size());
for (int i = 0; i < attributedOps.size(); i++) {
@@ -680,8 +684,12 @@
@NonNull OpEntry createSingleAttributionEntryLocked(@Nullable String attributionTag) {
// TODO(b/308201969): Update this method when we introduce disk persistence of events
// for accesses on external devices.
- final ArrayMap<String, AttributedOp> attributedOps = mDeviceAttributedOps.get(
+ ArrayMap<String, AttributedOp> attributedOps = mDeviceAttributedOps.get(
PERSISTENT_DEVICE_ID_DEFAULT);
+ if (attributedOps == null) {
+ attributedOps = new ArrayMap<>();
+ }
+
final ArrayMap<String, AttributedOpEntry> attributionEntries = new ArrayMap<>(1);
if (attributedOps.get(attributionTag) != null) {
attributionEntries.put(attributionTag,
diff --git a/services/core/java/com/android/server/pm/InstallPackageHelper.java b/services/core/java/com/android/server/pm/InstallPackageHelper.java
index 8cc242c..5bd8ca6 100644
--- a/services/core/java/com/android/server/pm/InstallPackageHelper.java
+++ b/services/core/java/com/android/server/pm/InstallPackageHelper.java
@@ -17,6 +17,8 @@
package com.android.server.pm;
import static android.content.pm.Flags.disallowSdkLibsToBeApps;
+import static android.content.pm.PackageManager.APP_METADATA_SOURCE_APK;
+import static android.content.pm.PackageManager.APP_METADATA_SOURCE_INSTALLER;
import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
@@ -43,11 +45,11 @@
import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
import static android.os.storage.StorageManager.FLAG_STORAGE_EXTERNAL;
+import static com.android.internal.pm.pkg.parsing.ParsingPackageUtils.APP_METADATA_FILE_NAME;
import static com.android.server.pm.DexOptHelper.useArtService;
import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
-import static com.android.server.pm.PackageManagerService.APP_METADATA_FILE_NAME;
import static com.android.server.pm.PackageManagerService.DEBUG_COMPRESSION;
import static com.android.server.pm.PackageManagerService.DEBUG_INSTALL;
import static com.android.server.pm.PackageManagerService.DEBUG_PACKAGE_SCANNING;
@@ -2225,10 +2227,16 @@
if (appMetadataFile.exists()) {
ps.setAppMetadataFilePath(appMetadataFile.getAbsolutePath());
if (Flags.aslInApkAppMetadataSource()) {
- ps.setAppMetadataSource(PackageManager.APP_METADATA_SOURCE_INSTALLER);
+ ps.setAppMetadataSource(APP_METADATA_SOURCE_INSTALLER);
}
} else {
- ps.setAppMetadataFilePath(null);
+ if (Flags.aslInApkAppMetadataSource()
+ && parsedPackage.isAppMetadataFileInApk()) {
+ ps.setAppMetadataFilePath(appMetadataFile.getAbsolutePath());
+ ps.setAppMetadataSource(APP_METADATA_SOURCE_APK);
+ } else {
+ ps.setAppMetadataFilePath(null);
+ }
}
}
if (installRequest.getReturnCode() == PackageManager.INSTALL_SUCCEEDED) {
diff --git a/services/core/java/com/android/server/pm/PackageInstallerSession.java b/services/core/java/com/android/server/pm/PackageInstallerSession.java
index 5792d86..ba90378 100644
--- a/services/core/java/com/android/server/pm/PackageInstallerSession.java
+++ b/services/core/java/com/android/server/pm/PackageInstallerSession.java
@@ -358,7 +358,7 @@
/** Default byte size limit for app metadata */
private static final long DEFAULT_APP_METADATA_BYTE_SIZE_LIMIT = 32000;
- private static final int APP_METADATA_FILE_ACCESS_MODE = 0640;
+ static final int APP_METADATA_FILE_ACCESS_MODE = 0640;
/**
* Throws IllegalArgumentException if the {@link IntentSender} from an immutable
@@ -964,7 +964,7 @@
private boolean isEmergencyInstallerEnabled(String packageName, Computer snapshot) {
final PackageStateInternal ps = snapshot.getPackageStateInternal(packageName);
- if (ps == null || ps.getPkg() == null || !ps.isSystem()) {
+ if (ps == null || ps.getPkg() == null) {
return false;
}
String emergencyInstaller = ps.getPkg().getEmergencyInstaller();
@@ -1782,8 +1782,7 @@
}
private File getStagedAppMetadataFile() {
- File file = new File(stageDir, APP_METADATA_FILE_NAME);
- return file.exists() ? file : null;
+ return new File(stageDir, APP_METADATA_FILE_NAME);
}
private static boolean isAppMetadata(String name) {
@@ -1799,7 +1798,7 @@
assertCallerIsOwnerOrRoot();
synchronized (mLock) {
assertPreparedAndNotCommittedOrDestroyedLocked("getAppMetadataFd");
- if (getStagedAppMetadataFile() == null) {
+ if (!getStagedAppMetadataFile().exists()) {
return null;
}
try {
@@ -1813,12 +1812,12 @@
@Override
public void removeAppMetadata() {
File file = getStagedAppMetadataFile();
- if (file != null) {
+ if (file.exists()) {
file.delete();
}
}
- private static long getAppMetadataSizeLimit() {
+ static long getAppMetadataSizeLimit() {
final long token = Binder.clearCallingIdentity();
try {
return DeviceConfig.getLong(NAMESPACE_PACKAGE_MANAGER_SERVICE,
@@ -2131,7 +2130,7 @@
}
File appMetadataFile = getStagedAppMetadataFile();
- if (appMetadataFile != null) {
+ if (appMetadataFile.exists()) {
long sizeLimit = getAppMetadataSizeLimit();
if (appMetadataFile.length() > sizeLimit) {
appMetadataFile.delete();
@@ -3419,7 +3418,7 @@
final List<ApkLite> addedFiles = getAddedApkLitesLocked();
if (addedFiles.isEmpty()
- && (removeSplitList.size() == 0 || getStagedAppMetadataFile() != null)) {
+ && (removeSplitList.size() == 0 || getStagedAppMetadataFile().exists())) {
throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
TextUtils.formatSimple("Session: %d. No packages staged in %s", sessionId,
stageDir.getAbsolutePath()));
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 3c256b1..69f7906 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -18,6 +18,8 @@
import static android.Manifest.permission.MANAGE_DEVICE_ADMINS;
import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS;
import static android.app.AppOpsManager.MODE_IGNORED;
+import static android.content.pm.PackageManager.APP_METADATA_SOURCE_APK;
+import static android.content.pm.PackageManager.APP_METADATA_SOURCE_UNKNOWN;
import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
@@ -596,7 +598,8 @@
static final String RANDOM_DIR_PREFIX = "~~";
static final char RANDOM_CODEPATH_PREFIX = '-';
- static final String APP_METADATA_FILE_NAME = "app.metadata";
+ public static final String APP_METADATA_FILE_NAME = "app.metadata";
+ public static final String APP_METADATA_FILE_IN_APK_PATH = "assets/" + APP_METADATA_FILE_NAME;
static final int DEFAULT_FILE_ACCESS_MODE = 0644;
@@ -5227,15 +5230,30 @@
new PackageManager.NameNotFoundException(packageName));
}
String filePath = ps.getAppMetadataFilePath();
- if (filePath != null) {
- File file = new File(filePath);
- try {
- return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
- } catch (FileNotFoundException e) {
+ if (filePath == null) {
+ return null;
+ }
+ File file = new File(filePath);
+ if (Flags.aslInApkAppMetadataSource() && !file.exists()
+ && ps.getAppMetadataSource() == APP_METADATA_SOURCE_APK) {
+ String apkPath = ps.getPkg().getSplits().get(0).getPath();
+ if (!PackageManagerServiceUtils.extractAppMetadataFromApk(apkPath, file)) {
+ if (file.exists()) {
+ file.delete();
+ }
+ synchronized (mLock) {
+ PackageSetting pkgSetting = mSettings.getPackageLPr(packageName);
+ pkgSetting.setAppMetadataFilePath(null);
+ pkgSetting.setAppMetadataSource(APP_METADATA_SOURCE_UNKNOWN);
+ }
return null;
}
}
- return null;
+ try {
+ return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
+ } catch (FileNotFoundException e) {
+ return null;
+ }
}
@android.annotation.EnforcePermission(android.Manifest.permission.GET_APP_METADATA)
diff --git a/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java b/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java
index 0a3dfc0..189a138 100644
--- a/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java
+++ b/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java
@@ -27,6 +27,9 @@
import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
import static com.android.internal.util.FrameworkStatsLog.UNSAFE_INTENT_EVENT_REPORTED__EVENT_TYPE__EXPLICIT_INTENT_FILTER_UNMATCH;
import static com.android.server.LocalManagerRegistry.ManagerNotFoundException;
+import static com.android.server.pm.PackageInstallerSession.APP_METADATA_FILE_ACCESS_MODE;
+import static com.android.server.pm.PackageInstallerSession.getAppMetadataSizeLimit;
+import static com.android.server.pm.PackageManagerService.APP_METADATA_FILE_IN_APK_PATH;
import static com.android.server.pm.PackageManagerService.COMPRESSED_EXTENSION;
import static com.android.server.pm.PackageManagerService.DEBUG_COMPRESSION;
import static com.android.server.pm.PackageManagerService.DEBUG_INTENT_MATCHING;
@@ -142,6 +145,8 @@
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.zip.GZIPInputStream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
/**
* Class containing helper methods for the PackageManagerService.
@@ -1559,6 +1564,35 @@
return initiatingPackageName == null || SHELL_PACKAGE_NAME.equals(initiatingPackageName);
}
+ /**
+ * Extract the app.metadata file from apk.
+ */
+ public static boolean extractAppMetadataFromApk(String apkPath, File appMetadataFile) {
+ boolean found = false;
+ try (ZipInputStream zipInputStream =
+ new ZipInputStream(new FileInputStream(new File(apkPath)))) {
+ ZipEntry zipEntry = null;
+ while ((zipEntry = zipInputStream.getNextEntry()) != null) {
+ if (zipEntry.getName().equals(APP_METADATA_FILE_IN_APK_PATH)) {
+ found = true;
+ try (FileOutputStream out = new FileOutputStream(appMetadataFile)) {
+ FileUtils.copy(zipInputStream, out);
+ }
+ if (appMetadataFile.length() > getAppMetadataSizeLimit()) {
+ appMetadataFile.delete();
+ return false;
+ }
+ Os.chmod(appMetadataFile.getAbsolutePath(), APP_METADATA_FILE_ACCESS_MODE);
+ break;
+ }
+ }
+ } catch (Exception e) {
+ Slog.e(TAG, e.getMessage());
+ return false;
+ }
+ return found;
+ }
+
public static void linkFilesToOldDirs(@NonNull Installer installer,
@NonNull String packageName,
@NonNull File newPath,
diff --git a/services/core/java/com/android/server/policy/PermissionPolicyService.java b/services/core/java/com/android/server/policy/PermissionPolicyService.java
index f15646f..98499417 100644
--- a/services/core/java/com/android/server/policy/PermissionPolicyService.java
+++ b/services/core/java/com/android/server/policy/PermissionPolicyService.java
@@ -237,7 +237,7 @@
mAppOpsCallback = new IAppOpsCallback.Stub() {
public void opChanged(int op, int uid, @Nullable String packageName,
String persistentDeviceId) {
- if (Objects.equals(persistentDeviceId,
+ if (!Objects.equals(persistentDeviceId,
VirtualDeviceManager.PERSISTENT_DEVICE_ID_DEFAULT)) {
return;
}
diff --git a/services/core/java/com/android/server/stats/pull/AggregatedMobileDataStatsPuller.java b/services/core/java/com/android/server/stats/pull/AggregatedMobileDataStatsPuller.java
index b0dcf95..881583a 100644
--- a/services/core/java/com/android/server/stats/pull/AggregatedMobileDataStatsPuller.java
+++ b/services/core/java/com/android/server/stats/pull/AggregatedMobileDataStatsPuller.java
@@ -282,10 +282,7 @@
Slog.d(TAG,
"pullDataBytesTransferLocked() done. results count " + pulledData.size());
}
- if (!pulledData.isEmpty()) {
- return StatsManager.PULL_SUCCESS;
- }
- return StatsManager.PULL_SKIP;
+ return StatsManager.PULL_SUCCESS;
}
private static boolean isEmpty(NetworkStats stats) {
diff --git a/services/core/java/com/android/server/vcn/TelephonySubscriptionTracker.java b/services/core/java/com/android/server/vcn/TelephonySubscriptionTracker.java
index 17f5e95..7206c03 100644
--- a/services/core/java/com/android/server/vcn/TelephonySubscriptionTracker.java
+++ b/services/core/java/com/android/server/vcn/TelephonySubscriptionTracker.java
@@ -164,7 +164,6 @@
registerCarrierPrivilegesCallbacks();
}
- // TODO(b/221306368): Refactor with the new onCarrierServiceChange in the new CPCallback
private void registerCarrierPrivilegesCallbacks() {
final HandlerExecutor executor = new HandlerExecutor(mHandler);
final int modemCount = mTelephonyManager.getActiveModemCount();
diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java
index 5036fc6..90cff39 100644
--- a/services/core/java/com/android/server/wm/ActivityRecord.java
+++ b/services/core/java/com/android/server/wm/ActivityRecord.java
@@ -1456,7 +1456,8 @@
mSizeConfigurations = sizeConfigurations;
}
- private void scheduleActivityMovedToDisplay(int displayId, Configuration config) {
+ private void scheduleActivityMovedToDisplay(int displayId, @NonNull Configuration config,
+ @NonNull ActivityWindowInfo activityWindowInfo) {
if (!attachedToProcess()) {
ProtoLog.w(WM_DEBUG_SWITCH, "Can't report activity moved "
+ "to display - client not running, activityRecord=%s, displayId=%d",
@@ -1469,7 +1470,7 @@
config);
mAtmService.getLifecycleManager().scheduleTransactionItem(app.getThread(),
- MoveToDisplayItem.obtain(token, displayId, config));
+ MoveToDisplayItem.obtain(token, displayId, config, activityWindowInfo));
} catch (RemoteException e) {
// If process died, whatever.
}
@@ -9799,8 +9800,10 @@
// Update last reported values.
final Configuration newMergedOverrideConfig = getMergedOverrideConfiguration();
+ final ActivityWindowInfo newActivityWindowInfo = getActivityWindowInfo();
setLastReportedConfiguration(getProcessGlobalConfiguration(), newMergedOverrideConfig);
+ setLastReportedActivityWindowInfo(newActivityWindowInfo);
if (mState == INITIALIZING) {
// No need to relaunch or schedule new config for activity that hasn't been launched
@@ -9817,7 +9820,8 @@
// There are no significant differences, so we won't relaunch but should still deliver
// the new configuration to the client process.
if (displayChanged) {
- scheduleActivityMovedToDisplay(newDisplayId, newMergedOverrideConfig);
+ scheduleActivityMovedToDisplay(newDisplayId, newMergedOverrideConfig,
+ newActivityWindowInfo);
} else {
scheduleConfigurationChanged(newMergedOverrideConfig);
}
@@ -9884,7 +9888,8 @@
// changes is always sent to all processes when they happen so it can just use whatever
// system level configuration it last got.
if (displayChanged) {
- scheduleActivityMovedToDisplay(newDisplayId, newMergedOverrideConfig);
+ scheduleActivityMovedToDisplay(newDisplayId, newMergedOverrideConfig,
+ newActivityWindowInfo);
} else {
scheduleConfigurationChanged(newMergedOverrideConfig);
}
diff --git a/services/core/java/com/android/server/wm/DragDropController.java b/services/core/java/com/android/server/wm/DragDropController.java
index b68e67e..34ea4ac 100644
--- a/services/core/java/com/android/server/wm/DragDropController.java
+++ b/services/core/java/com/android/server/wm/DragDropController.java
@@ -18,6 +18,7 @@
import static android.view.View.DRAG_FLAG_GLOBAL;
import static android.view.View.DRAG_FLAG_GLOBAL_SAME_APPLICATION;
+import static android.view.View.DRAG_FLAG_START_INTENT_SENDER_ON_UNHANDLED_DRAG;
import static com.android.input.flags.Flags.enablePointerChoreographer;
import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_DRAG;
@@ -373,8 +374,11 @@
boolean notifyUnhandledDrop(DragEvent dropEvent, String reason) {
final boolean isLocalDrag =
(mDragState.mFlags & (DRAG_FLAG_GLOBAL_SAME_APPLICATION | DRAG_FLAG_GLOBAL)) == 0;
+ final boolean shouldDelegateUnhandledDrag =
+ (mDragState.mFlags & DRAG_FLAG_START_INTENT_SENDER_ON_UNHANDLED_DRAG) != 0;
if (!com.android.window.flags.Flags.delegateUnhandledDrags()
|| mGlobalDragListener == null
+ || !shouldDelegateUnhandledDrag
|| isLocalDrag) {
// Skip if the flag is disabled, there is no unhandled-drag listener, or if this is a
// purely local drag
diff --git a/services/core/java/com/android/server/wm/DragState.java b/services/core/java/com/android/server/wm/DragState.java
index 76038b9..b266caa 100644
--- a/services/core/java/com/android/server/wm/DragState.java
+++ b/services/core/java/com/android/server/wm/DragState.java
@@ -216,8 +216,7 @@
mIsClosing = true;
// Unregister the input interceptor.
if (mInputInterceptor != null) {
- if (DEBUG_DRAG)
- Slog.d(TAG_WM, "unregistering drag input channel");
+ if (DEBUG_DRAG) Slog.d(TAG_WM, "Unregistering drag input channel");
// Input channel should be disposed on the thread where the input is being handled.
mDragDropController.sendHandlerMessage(
@@ -227,9 +226,7 @@
// Send drag end broadcast if drag start has been sent.
if (mDragInProgress) {
- if (DEBUG_DRAG) {
- Slog.d(TAG_WM, "broadcasting DRAG_ENDED");
- }
+ if (DEBUG_DRAG) Slog.d(TAG_WM, "Broadcasting DRAG_ENDED");
for (WindowState ws : mNotifiedWindows) {
float x = 0;
float y = 0;
@@ -248,6 +245,7 @@
x, y, mThumbOffsetX, mThumbOffsetY, null, null, null, dragSurface, null,
mDragResult);
try {
+ if (DEBUG_DRAG) Slog.d(TAG_WM, "Sending DRAG_ENDED to " + ws);
ws.mClient.dispatchDragEvent(event);
} catch (RemoteException e) {
Slog.w(TAG_WM, "Unable to drag-end window " + ws);
@@ -364,7 +362,7 @@
return false;
}
- if (DEBUG_DRAG) Slog.d(TAG_WM, "sending DROP to " + touchedWin);
+ if (DEBUG_DRAG) Slog.d(TAG_WM, "Sending DROP to " + touchedWin);
final IBinder clientToken = touchedWin.mClient.asBinder();
final DragEvent event = createDropEvent(x, y, touchedWin, false /* includePrivateInfo */);
@@ -460,7 +458,7 @@
*/
CompletableFuture<Void> register(Display display) {
display.getRealSize(mDisplaySize);
- if (DEBUG_DRAG) Slog.d(TAG_WM, "registering drag input channel");
+ if (DEBUG_DRAG) Slog.d(TAG_WM, "Registering drag input channel");
if (mInputInterceptor != null) {
Slog.e(TAG_WM, "Duplicate register of drag input channel");
return completedFuture(null);
@@ -489,7 +487,7 @@
mSourceUserId, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
if (DEBUG_DRAG) {
- Slog.d(TAG_WM, "broadcasting DRAG_STARTED at (" + touchX + ", " + touchY + ")");
+ Slog.d(TAG_WM, "Broadcasting DRAG_STARTED at (" + touchX + ", " + touchY + ")");
}
final boolean containsAppExtras = containsApplicationExtras(mDataDescription);
diff --git a/services/credentials/java/com/android/server/credentials/CredentialManagerUi.java b/services/credentials/java/com/android/server/credentials/CredentialManagerUi.java
index 9d45cfb..027337f 100644
--- a/services/credentials/java/com/android/server/credentials/CredentialManagerUi.java
+++ b/services/credentials/java/com/android/server/credentials/CredentialManagerUi.java
@@ -18,7 +18,6 @@
import static android.credentials.selection.Constants.EXTRA_FINAL_RESPONSE_RECEIVER;
import android.annotation.NonNull;
-import android.annotation.Nullable;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
@@ -161,26 +160,6 @@
*/
public PendingIntent createPendingIntent(
RequestInfo requestInfo, ArrayList<ProviderData> providerDataList) {
- return createPendingIntent(requestInfo, providerDataList, /*forAutofill=*/ false);
- }
-
- /**
- * Creates a {@link PendingIntent} to be used to invoke the credential manager selector UI,
- * by the calling app process. This intent is invoked from the Autofill flow, when the user
- * requests to bring up the 'All Options' page of the credential bottom-sheet. When the user
- * clicks on the pinned entry, the intent will bring up the 'All Options' page of the
- * bottom-sheet. The provider data list is processed by the credential autofill service for
- * each autofill id and passed in as an auth extra.
- *
- * @param requestInfo the information about the request
- */
- public PendingIntent createPendingIntentForAutofill(RequestInfo requestInfo) {
- return createPendingIntent(requestInfo, /*providerDataList=*/ null, /*forAutofill=*/ true);
- }
-
- private PendingIntent createPendingIntent(
- RequestInfo requestInfo, @Nullable ArrayList<ProviderData> providerDataList,
- boolean forAutofill) {
List<CredentialProviderInfo> allProviders =
CredentialProviderInfoFactory.getCredentialProviderServices(
mContext,
@@ -196,15 +175,9 @@
disabledProvider.getComponentName().flattenToString())).toList();
Intent intent;
- if (forAutofill) {
- intent = IntentFactory.createCredentialSelectorIntentForAutofill(
- mContext, requestInfo, new ArrayList<>(disabledProviderDataList),
- mResultReceiver);
- } else {
- intent = IntentFactory.createCredentialSelectorIntent(
- mContext, requestInfo, providerDataList,
- new ArrayList<>(disabledProviderDataList), mResultReceiver);
- }
+ intent = IntentFactory.createCredentialSelectorIntent(
+ mContext, requestInfo, providerDataList,
+ new ArrayList<>(disabledProviderDataList), mResultReceiver);
intent.setAction(UUID.randomUUID().toString());
//TODO: Create unique pending intent using request code and cancel any pre-existing pending
// intents
@@ -213,4 +186,21 @@
PendingIntent.FLAG_MUTABLE, /*options=*/null,
UserHandle.of(mUserId));
}
+
+ /**
+ * Creates an {@link Intent} to be used to invoke the credential manager selector UI,
+ * by the calling app process. This intent is invoked from the Autofill flow, when the user
+ * requests to bring up the 'All Options' page of the credential bottom-sheet. When the user
+ * clicks on the pinned entry, the intent will bring up the 'All Options' page of the
+ * bottom-sheet. The provider data list is processed by the credential autofill service for
+ * each autofill id and passed in as extras in the pending intent set as authentication
+ * of the pinned entry.
+ *
+ * @param requestInfo the information about the request
+ */
+ public Intent createIntentForAutofill(RequestInfo requestInfo) {
+ return IntentFactory.createCredentialSelectorIntentForAutofill(
+ mContext, requestInfo, new ArrayList<>(),
+ mResultReceiver);
+ }
}
diff --git a/services/credentials/java/com/android/server/credentials/GetCandidateRequestSession.java b/services/credentials/java/com/android/server/credentials/GetCandidateRequestSession.java
index ca72638..3cb98eb 100644
--- a/services/credentials/java/com/android/server/credentials/GetCandidateRequestSession.java
+++ b/services/credentials/java/com/android/server/credentials/GetCandidateRequestSession.java
@@ -20,6 +20,7 @@
import android.annotation.Nullable;
import android.content.ComponentName;
import android.content.Context;
+import android.content.Intent;
import android.credentials.Constants;
import android.credentials.CredentialProviderInfo;
import android.credentials.GetCandidateCredentialsException;
@@ -114,8 +115,7 @@
return;
}
- cancelExistingPendingIntent();
- mPendingIntent = mCredentialManagerUi.createPendingIntentForAutofill(
+ Intent intent = mCredentialManagerUi.createIntentForAutofill(
RequestInfo.newGetRequestInfo(
mRequestId, mClientRequest, mClientAppInfo.getPackageName(),
PermissionUtils.hasPermission(mContext, mClientAppInfo.getPackageName(),
@@ -129,7 +129,7 @@
try {
invokeClientCallbackSuccess(new GetCandidateCredentialsResponse(
- candidateProviderDataList, mPendingIntent));
+ candidateProviderDataList, intent));
} catch (RemoteException e) {
Slog.e(TAG, "Issue while responding to client with error : " + e);
}
diff --git a/services/credentials/java/com/android/server/credentials/ProviderGetSession.java b/services/credentials/java/com/android/server/credentials/ProviderGetSession.java
index fa63bc8..cad9a09 100644
--- a/services/credentials/java/com/android/server/credentials/ProviderGetSession.java
+++ b/services/credentials/java/com/android/server/credentials/ProviderGetSession.java
@@ -93,7 +93,7 @@
android.credentials.GetCredentialRequest filteredRequest =
filterOptions(providerInfo.getCapabilities(),
getRequestSession.mClientRequest,
- providerInfo);
+ providerInfo, getRequestSession.mHybridService);
if (filteredRequest != null) {
Map<String, CredentialOption> beginGetOptionToCredentialOptionMap =
new HashMap<>();
@@ -129,7 +129,7 @@
android.credentials.GetCredentialRequest filteredRequest =
filterOptions(providerInfo.getCapabilities(),
getRequestSession.mClientRequest,
- providerInfo);
+ providerInfo, getRequestSession.mHybridService);
if (filteredRequest != null) {
Map<String, CredentialOption> beginGetOptionToCredentialOptionMap =
new HashMap<>();
@@ -179,9 +179,19 @@
private static android.credentials.GetCredentialRequest filterOptions(
List<String> providerCapabilities,
android.credentials.GetCredentialRequest clientRequest,
- CredentialProviderInfo info
- ) {
+ CredentialProviderInfo info,
+ String hybridService) {
Slog.i(TAG, "Filtering request options for: " + info.getComponentName());
+ if (android.credentials.flags.Flags.hybridFilterFixEnabled()) {
+ ComponentName hybridComponentName = ComponentName.unflattenFromString(hybridService);
+ if (hybridComponentName != null && hybridComponentName
+ .equals(info.getComponentName())) {
+ Slog.i(TAG, "Skipping filtering of options for hybrid service");
+ return clientRequest;
+ }
+ Slog.w(TAG, "Could not parse hybrid service while filtering options");
+ }
+
List<CredentialOption> filteredOptions = new ArrayList<>();
for (CredentialOption option : clientRequest.getCredentialOptions()) {
if (providerCapabilities.contains(option.getType())
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/EnterpriseSpecificIdCalculator.java b/services/devicepolicy/java/com/android/server/devicepolicy/EnterpriseSpecificIdCalculator.java
index df7f308..1000bfa 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/EnterpriseSpecificIdCalculator.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/EnterpriseSpecificIdCalculator.java
@@ -53,7 +53,17 @@
TelephonyManager telephonyService = context.getSystemService(TelephonyManager.class);
Preconditions.checkState(telephonyService != null, "Unable to access telephony service");
mImei = telephonyService.getImei(0);
- mMeid = telephonyService.getMeid(0);
+ String meid;
+ try {
+ meid = telephonyService.getMeid(0);
+ } catch (UnsupportedOperationException doesNotSupportCdma) {
+ // Instead of catching the exception, we could check for FEATURE_TELEPHONY_CDMA.
+ // However that runs the risk of changing a device's existing ESID if on these devices
+ // telephonyService.getMeid() actually returns non-null even when the device does not
+ // declare FEATURE_TELEPHONY_CDMA.
+ meid = null;
+ }
+ mMeid = meid;
mSerialNumber = Build.getSerial();
WifiManager wifiManager = context.getSystemService(WifiManager.class);
Preconditions.checkState(wifiManager != null, "Unable to access WiFi service");
diff --git a/services/fakes/Android.bp b/services/fakes/Android.bp
new file mode 100644
index 0000000..148054b
--- /dev/null
+++ b/services/fakes/Android.bp
@@ -0,0 +1,20 @@
+package {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "frameworks_base_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-Apache-2.0
+ default_applicable_licenses: ["frameworks_base_license"],
+}
+
+// NOTE: These "fake" services are intended for use under the Ravenwood
+// deviceless test environment, and should *not* be included in the build
+// artifacts for physical devices, as they already supply "real" services
+filegroup {
+ name: "services.fakes-sources",
+ srcs: [
+ "java/**/*.java",
+ ],
+ path: "java",
+ visibility: ["//frameworks/base"],
+}
diff --git a/services/fakes/java/com/android/server/FakeClipboardService.java b/services/fakes/java/com/android/server/FakeClipboardService.java
new file mode 100644
index 0000000..0101621
--- /dev/null
+++ b/services/fakes/java/com/android/server/FakeClipboardService.java
@@ -0,0 +1,165 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server;
+
+import android.content.ClipData;
+import android.content.ClipDescription;
+import android.content.Context;
+import android.content.IClipboard;
+import android.content.IOnPrimaryClipChangedListener;
+import android.os.PermissionEnforcer;
+import android.os.RemoteCallbackList;
+import android.os.RemoteException;
+import android.os.UserHandle;
+
+import com.android.internal.util.Preconditions;
+
+/**
+ * Fake implementation of {@code ClipboardManager} since the real implementation is tightly
+ * coupled with many other internal services.
+ */
+public class FakeClipboardService extends IClipboard.Stub {
+ private final RemoteCallbackList<IOnPrimaryClipChangedListener> mListeners =
+ new RemoteCallbackList<>();
+
+ private ClipData mPrimaryClip;
+ private String mPrimaryClipSource;
+
+ public FakeClipboardService(Context context) {
+ super(PermissionEnforcer.fromContext(context));
+ }
+
+ public static class Lifecycle extends SystemService {
+ private FakeClipboardService mService;
+
+ public Lifecycle(Context context) {
+ super(context);
+ }
+
+ @Override
+ public void onStart() {
+ mService = new FakeClipboardService(getContext());
+ publishBinderService(Context.CLIPBOARD_SERVICE, mService);
+ }
+ }
+
+ private static void checkArguments(int userId, int deviceId) {
+ Preconditions.checkArgument(userId == UserHandle.USER_SYSTEM,
+ "Fake only supports USER_SYSTEM user");
+ Preconditions.checkArgument(deviceId == Context.DEVICE_ID_DEFAULT,
+ "Fake only supports DEVICE_ID_DEFAULT device");
+ }
+
+ private void dispatchPrimaryClipChanged() {
+ mListeners.broadcast((listener) -> {
+ try {
+ listener.dispatchPrimaryClipChanged();
+ } catch (RemoteException ignored) {
+ }
+ });
+ }
+
+ @Override
+ public void setPrimaryClip(ClipData clip, String callingPackage, String attributionTag,
+ int userId, int deviceId) {
+ checkArguments(userId, deviceId);
+ mPrimaryClip = clip;
+ mPrimaryClipSource = callingPackage;
+ dispatchPrimaryClipChanged();
+ }
+
+ @Override
+ @android.annotation.EnforcePermission(android.Manifest.permission.SET_CLIP_SOURCE)
+ public void setPrimaryClipAsPackage(ClipData clip, String callingPackage, String attributionTag,
+ int userId, int deviceId, String sourcePackage) {
+ setPrimaryClipAsPackage_enforcePermission();
+ checkArguments(userId, deviceId);
+ mPrimaryClip = clip;
+ mPrimaryClipSource = sourcePackage;
+ dispatchPrimaryClipChanged();
+ }
+
+ @Override
+ public void clearPrimaryClip(String callingPackage, String attributionTag, int userId,
+ int deviceId) {
+ checkArguments(userId, deviceId);
+ mPrimaryClip = null;
+ mPrimaryClipSource = null;
+ dispatchPrimaryClipChanged();
+ }
+
+ @Override
+ public ClipData getPrimaryClip(String pkg, String attributionTag, int userId, int deviceId) {
+ checkArguments(userId, deviceId);
+ return mPrimaryClip;
+ }
+
+ @Override
+ public ClipDescription getPrimaryClipDescription(String callingPackage, String attributionTag,
+ int userId, int deviceId) {
+ checkArguments(userId, deviceId);
+ return (mPrimaryClip != null) ? mPrimaryClip.getDescription() : null;
+ }
+
+ @Override
+ public boolean hasPrimaryClip(String callingPackage, String attributionTag, int userId,
+ int deviceId) {
+ checkArguments(userId, deviceId);
+ return mPrimaryClip != null;
+ }
+
+ @Override
+ public void addPrimaryClipChangedListener(IOnPrimaryClipChangedListener listener,
+ String callingPackage, String attributionTag, int userId, int deviceId) {
+ checkArguments(userId, deviceId);
+ mListeners.register(listener);
+ }
+
+ @Override
+ public void removePrimaryClipChangedListener(IOnPrimaryClipChangedListener listener,
+ String callingPackage, String attributionTag, int userId, int deviceId) {
+ checkArguments(userId, deviceId);
+ mListeners.unregister(listener);
+ }
+
+ @Override
+ public boolean hasClipboardText(String callingPackage, String attributionTag, int userId,
+ int deviceId) {
+ checkArguments(userId, deviceId);
+ return (mPrimaryClip != null) && (mPrimaryClip.getItemCount() > 0)
+ && (mPrimaryClip.getItemAt(0).getText() != null);
+ }
+
+ @Override
+ @android.annotation.EnforcePermission(android.Manifest.permission.SET_CLIP_SOURCE)
+ public String getPrimaryClipSource(String callingPackage, String attributionTag, int userId,
+ int deviceId) {
+ getPrimaryClipSource_enforcePermission();
+ checkArguments(userId, deviceId);
+ return mPrimaryClipSource;
+ }
+
+ @Override
+ public boolean areClipboardAccessNotificationsEnabledForUser(int userId) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void setClipboardAccessNotificationsEnabledForUser(boolean enable, int userId) {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/parsing/parcelling/AndroidPackageTest.kt b/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/parsing/parcelling/AndroidPackageTest.kt
index d4b57f1..96e9ca0 100644
--- a/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/parsing/parcelling/AndroidPackageTest.kt
+++ b/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/parsing/parcelling/AndroidPackageTest.kt
@@ -275,6 +275,7 @@
AndroidPackage::isUpdatableSystem,
AndroidPackage::getEmergencyInstaller,
AndroidPackage::isAllowCrossUidActivitySwitchFromBelow,
+ PackageImpl::isAppMetadataFileInApk,
)
override fun extraParams() = listOf(
diff --git a/services/tests/mockingservicestests/src/com/android/server/rollback/RollbackPackageHealthObserverTest.java b/services/tests/mockingservicestests/src/com/android/server/rollback/RollbackPackageHealthObserverTest.java
index d6e246f..6e41685 100644
--- a/services/tests/mockingservicestests/src/com/android/server/rollback/RollbackPackageHealthObserverTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/rollback/RollbackPackageHealthObserverTest.java
@@ -25,6 +25,8 @@
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
@@ -42,6 +44,7 @@
import android.crashrecovery.flags.Flags;
import android.os.Handler;
import android.os.MessageQueue;
+import android.os.SystemProperties;
import android.platform.test.flag.junit.SetFlagsRule;
import androidx.test.runner.AndroidJUnit4;
@@ -65,6 +68,7 @@
import org.mockito.stubbing.Answer;
import java.time.Duration;
+import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -90,7 +94,7 @@
@Rule
public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
-
+ private HashMap<String, String> mSystemSettingsMap;
private MockitoSession mSession;
private static final String APP_A = "com.package.a";
private static final String APP_B = "com.package.b";
@@ -99,6 +103,9 @@
private static final long VERSION_CODE_2 = 2L;
private static final String LOG_TAG = "RollbackPackageHealthObserverTest";
+ private static final String PROP_DISABLE_HIGH_IMPACT_ROLLBACK_FLAG =
+ "persist.device_config.configuration.disable_high_impact_rollback";
+
private SystemConfig mSysConfig;
@Rule public TemporaryFolder mTemporaryFolder = new TemporaryFolder();
@@ -111,11 +118,34 @@
.initMocks(this)
.strictness(Strictness.LENIENT)
.spyStatic(PackageWatchdog.class)
+ .spyStatic(SystemProperties.class)
.startMocking();
+ mSystemSettingsMap = new HashMap<>();
// Mock PackageWatchdog
doAnswer((Answer<PackageWatchdog>) invocationOnMock -> mMockPackageWatchdog)
.when(() -> PackageWatchdog.getInstance(mMockContext));
+
+ // Mock SystemProperties setter and various getters
+ doAnswer((Answer<Void>) invocationOnMock -> {
+ String key = invocationOnMock.getArgument(0);
+ String value = invocationOnMock.getArgument(1);
+
+ mSystemSettingsMap.put(key, value);
+ return null;
+ }
+ ).when(() -> SystemProperties.set(anyString(), anyString()));
+
+ doAnswer((Answer<Boolean>) invocationOnMock -> {
+ String key = invocationOnMock.getArgument(0);
+ boolean defaultValue = invocationOnMock.getArgument(1);
+
+ String storedValue = mSystemSettingsMap.get(key);
+ return storedValue == null ? defaultValue : Boolean.parseBoolean(storedValue);
+ }
+ ).when(() -> SystemProperties.getBoolean(anyString(), anyBoolean()));
+
+ SystemProperties.set(PROP_DISABLE_HIGH_IMPACT_ROLLBACK_FLAG, Boolean.toString(false));
}
@After
@@ -609,6 +639,32 @@
observer.onBootLoop(1));
}
+ @Test
+ public void onBootLoop_impactLevelHighDisableHighImpactRollback_onePackage()
+ throws PackageManager.NameNotFoundException {
+ mSetFlagsRule.enableFlags(Flags.FLAG_RECOVERABILITY_DETECTION);
+ SystemProperties.set(PROP_DISABLE_HIGH_IMPACT_ROLLBACK_FLAG, Boolean.toString(true));
+ VersionedPackage appAFrom = new VersionedPackage(APP_A, VERSION_CODE_2);
+ VersionedPackage appATo = new VersionedPackage(APP_A, VERSION_CODE);
+ PackageRollbackInfo packageRollbackInfo = new PackageRollbackInfo(appAFrom, appATo,
+ null, null, false, false,
+ null);
+ RollbackInfo rollbackInfo1 = new RollbackInfo(1, List.of(packageRollbackInfo),
+ false, null, 111,
+ PackageManager.ROLLBACK_USER_IMPACT_HIGH);
+ RollbackPackageHealthObserver observer =
+ spy(new RollbackPackageHealthObserver(mMockContext, mApexManager));
+
+ when(mMockContext.getSystemService(RollbackManager.class)).thenReturn(mRollbackManager);
+ // Make the rollbacks available
+ when(mRollbackManager.getAvailableRollbacks()).thenReturn(List.of(rollbackInfo1));
+ when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager);
+ when(mMockPackageManager.getModuleInfo(any(), eq(0))).thenReturn(null);
+
+ assertEquals(PackageWatchdog.PackageHealthObserverImpact.USER_IMPACT_LEVEL_0,
+ observer.onBootLoop(1));
+ }
+
/**
* When the rollback impact level is manual only return user impact level 0. (User impact level
* 0 is ignored by package watchdog)
@@ -924,6 +980,50 @@
assertThat(argument.getAllValues()).isEqualTo(List.of(rollbackId2));
}
+ /**
+ * Don't roll back if kill switch is enabled.
+ */
+ @Test
+ public void executeBootLoopMitigation_impactLevelHighKillSwitchTrue_rollbackHigh()
+ throws PackageManager.NameNotFoundException {
+ mSetFlagsRule.enableFlags(Flags.FLAG_RECOVERABILITY_DETECTION);
+ SystemProperties.set(PROP_DISABLE_HIGH_IMPACT_ROLLBACK_FLAG, Boolean.toString(true));
+ int rollbackId1 = 1;
+ VersionedPackage appBFrom = new VersionedPackage(APP_B, VERSION_CODE_2);
+ VersionedPackage appBTo = new VersionedPackage(APP_B, VERSION_CODE);
+ PackageRollbackInfo packageRollbackInfoB = new PackageRollbackInfo(appBFrom, appBTo,
+ null, null , false, false,
+ null);
+ RollbackInfo rollbackInfo1 = new RollbackInfo(rollbackId1, List.of(packageRollbackInfoB),
+ false, null, 111,
+ PackageManager.ROLLBACK_USER_IMPACT_HIGH);
+ int rollbackId2 = 2;
+ VersionedPackage appAFrom = new VersionedPackage(APP_A, VERSION_CODE_2);
+ VersionedPackage appATo = new VersionedPackage(APP_A, VERSION_CODE);
+ PackageRollbackInfo packageRollbackInfoA = new PackageRollbackInfo(appAFrom, appATo,
+ null, null , false, false,
+ null);
+ RollbackInfo rollbackInfo2 = new RollbackInfo(rollbackId2, List.of(packageRollbackInfoA),
+ false, null, 111,
+ PackageManager.ROLLBACK_USER_IMPACT_HIGH);
+ RollbackPackageHealthObserver observer =
+ spy(new RollbackPackageHealthObserver(mMockContext, mApexManager));
+ ArgumentCaptor<Integer> argument = ArgumentCaptor.forClass(Integer.class);
+
+ when(mMockContext.getSystemService(RollbackManager.class)).thenReturn(mRollbackManager);
+ // Make the rollbacks available
+ when(mRollbackManager.getAvailableRollbacks()).thenReturn(
+ List.of(rollbackInfo1, rollbackInfo2));
+ when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager);
+ when(mMockPackageManager.getModuleInfo(any(), eq(0))).thenReturn(null);
+
+ observer.executeBootLoopMitigation(1);
+ waitForIdleHandler(observer.getHandler(), Duration.ofSeconds(10));
+
+ verify(mRollbackManager, never()).commitRollback(
+ argument.capture(), any(), any());
+ }
+
private void waitForIdleHandler(Handler handler, Duration timeout) {
final MessageQueue queue = handler.getLooper().getQueue();
final CountDownLatch latch = new CountDownLatch(1);
diff --git a/services/tests/servicestests/Android.bp b/services/tests/servicestests/Android.bp
index 3743483..37967fa 100644
--- a/services/tests/servicestests/Android.bp
+++ b/services/tests/servicestests/Android.bp
@@ -85,6 +85,7 @@
"ravenwood-junit",
"net_flags_lib",
"CtsVirtualDeviceCommonLib",
+ "com_android_server_accessibility_flags_lib",
],
libs: [
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityWindowManagerTest.java b/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityWindowManagerTest.java
index 89d146d..8717a05 100644
--- a/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityWindowManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityWindowManagerTest.java
@@ -47,6 +47,9 @@
import android.os.LocaleList;
import android.os.RemoteException;
import android.os.UserHandle;
+import android.platform.test.annotations.RequiresFlagsDisabled;
+import android.platform.test.flag.junit.CheckFlagsRule;
+import android.platform.test.flag.junit.DeviceFlagsValueProvider;
import android.util.SparseArray;
import android.view.Display;
import android.view.IWindow;
@@ -67,6 +70,7 @@
import org.hamcrest.TypeSafeMatcher;
import org.junit.After;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
@@ -77,9 +81,16 @@
import java.util.Arrays;
import java.util.List;
+// This test verifies deprecated codepath. Probably changing this file means
+// AccessibilityWindowManagerWithAccessibilityWindowTest also needs to be updated.
+// LINT.IfChange
+
/**
- * Tests for the AccessibilityWindowManager
+ * Tests for the AccessibilityWindowManager with Flags.FLAG_COMPUTE_WINDOW_CHANGES_ON_A11Y enabled.
+ * TODO(b/322444245): Merge with AccessibilityWindowManagerWithAccessibilityWindowTest
+ * after completing the flag migration.
*/
+@RequiresFlagsDisabled(Flags.FLAG_COMPUTE_WINDOW_CHANGES_ON_A11Y)
public class AccessibilityWindowManagerTest {
private static final String PACKAGE_NAME = "com.android.server.accessibility";
private static final boolean FORCE_SEND = true;
@@ -132,6 +143,9 @@
@Mock private IBinder mMockEmbeddedToken;
@Mock private IBinder mMockInvalidToken;
+ @Rule
+ public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule();
+
@Before
public void setUp() throws RemoteException {
MockitoAnnotations.initMocks(this);
@@ -1227,3 +1241,4 @@
}
}
}
+// LINT.ThenChange(/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityWindowManagerWithAccessibilityWindowTest.java)
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityWindowManagerWithAccessibilityWindowTest.java b/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityWindowManagerWithAccessibilityWindowTest.java
new file mode 100644
index 0000000..4db27d2
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityWindowManagerWithAccessibilityWindowTest.java
@@ -0,0 +1,1247 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.accessibility;
+
+import static com.android.server.accessibility.AbstractAccessibilityServiceConnection.DISPLAY_TYPE_DEFAULT;
+import static com.android.server.accessibility.AccessibilityWindowManagerTest.DisplayIdMatcher.displayId;
+import static com.android.server.accessibility.AccessibilityWindowManagerTest.WindowChangesMatcher.a11yWindowChanges;
+import static com.android.server.accessibility.AccessibilityWindowManagerTest.WindowIdMatcher.a11yWindowId;
+
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertNotNull;
+import static junit.framework.Assert.assertNull;
+import static junit.framework.Assert.assertTrue;
+
+import static org.hamcrest.Matchers.allOf;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.not;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertThat;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.annotation.Nullable;
+import android.graphics.Region;
+import android.os.IBinder;
+import android.os.LocaleList;
+import android.os.RemoteException;
+import android.os.UserHandle;
+import android.platform.test.annotations.RequiresFlagsEnabled;
+import android.platform.test.flag.junit.CheckFlagsRule;
+import android.platform.test.flag.junit.DeviceFlagsValueProvider;
+import android.util.SparseArray;
+import android.view.Display;
+import android.view.IWindow;
+import android.view.WindowInfo;
+import android.view.WindowManager;
+import android.view.accessibility.AccessibilityEvent;
+import android.view.accessibility.AccessibilityNodeInfo;
+import android.view.accessibility.AccessibilityWindowAttributes;
+import android.view.accessibility.AccessibilityWindowInfo;
+import android.view.accessibility.IAccessibilityInteractionConnection;
+
+import com.android.server.accessibility.AccessibilityWindowManager.RemoteAccessibilityConnection;
+import com.android.server.accessibility.test.MessageCapturingHandler;
+import com.android.server.wm.WindowManagerInternal;
+import com.android.server.wm.WindowManagerInternal.WindowsForAccessibilityCallback;
+
+import org.hamcrest.Description;
+import org.hamcrest.TypeSafeMatcher;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Tests for the AccessibilityWindowManager with Flags.FLAG_COMPUTE_WINDOW_CHANGES_ON_A11Y
+ * TODO(b/322444245): Merge with AccessibilityWindowManagerTest
+ * after completing the flag migration.
+ */
+@RequiresFlagsEnabled(Flags.FLAG_COMPUTE_WINDOW_CHANGES_ON_A11Y)
+public class AccessibilityWindowManagerWithAccessibilityWindowTest {
+ private static final String PACKAGE_NAME = "com.android.server.accessibility";
+ private static final boolean FORCE_SEND = true;
+ private static final boolean SEND_ON_WINDOW_CHANGES = false;
+ private static final int USER_SYSTEM_ID = UserHandle.USER_SYSTEM;
+ private static final int USER_PROFILE = 11;
+ private static final int USER_PROFILE_PARENT = 1;
+ private static final int SECONDARY_DISPLAY_ID = Display.DEFAULT_DISPLAY + 1;
+ private static final int NUM_GLOBAL_WINDOWS = 4;
+ private static final int NUM_APP_WINDOWS = 4;
+ private static final int NUM_OF_WINDOWS = (NUM_GLOBAL_WINDOWS + NUM_APP_WINDOWS);
+ private static final int DEFAULT_FOCUSED_INDEX = 1;
+ private static final int SCREEN_WIDTH = 1080;
+ private static final int SCREEN_HEIGHT = 1920;
+ private static final int INVALID_ID = AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
+ private static final int HOST_WINDOW_ID = 10;
+ private static final int EMBEDDED_WINDOW_ID = 11;
+ private static final int OTHER_WINDOW_ID = 12;
+
+ private AccessibilityWindowManager mA11yWindowManager;
+ // Window manager will support multiple focused window if config_perDisplayFocusEnabled is true,
+ // i.e., each display would have its current focused window, and one of all focused windows
+ // would be top focused window. Otherwise, window manager only supports one focused window
+ // at all displays, and that focused window would be top focused window.
+ private boolean mSupportPerDisplayFocus = false;
+ private int mTopFocusedDisplayId = Display.INVALID_DISPLAY;
+ private IBinder mTopFocusedWindowToken = null;
+
+ // List of window token, mapping from windowId -> window token.
+ private final SparseArray<IWindow> mA11yWindowTokens = new SparseArray<>();
+ // List of window info lists, mapping from displayId -> window info lists.
+ private final SparseArray<ArrayList<WindowInfo>> mWindowInfos =
+ new SparseArray<>();
+ // List of callback, mapping from displayId -> callback.
+ private final SparseArray<WindowsForAccessibilityCallback> mCallbackOfWindows =
+ new SparseArray<>();
+ // List of display ID.
+ private final ArrayList<Integer> mExpectedDisplayList = new ArrayList<>(Arrays.asList(
+ Display.DEFAULT_DISPLAY, SECONDARY_DISPLAY_ID));
+
+ private final MessageCapturingHandler mHandler = new MessageCapturingHandler(null);
+
+ @Mock
+ private WindowManagerInternal mMockWindowManagerInternal;
+ @Mock
+ private AccessibilityWindowManager.AccessibilityEventSender mMockA11yEventSender;
+ @Mock
+ private AccessibilitySecurityPolicy mMockA11ySecurityPolicy;
+ @Mock
+ private AccessibilitySecurityPolicy.AccessibilityUserManager mMockA11yUserManager;
+ @Mock
+ private AccessibilityTraceManager mMockA11yTraceManager;
+
+ @Mock
+ private IBinder mMockHostToken;
+ @Mock
+ private IBinder mMockEmbeddedToken;
+ @Mock
+ private IBinder mMockInvalidToken;
+
+ @Rule
+ public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule();
+
+ @Before
+ public void setUp() throws RemoteException {
+ MockitoAnnotations.initMocks(this);
+ when(mMockA11yUserManager.getCurrentUserIdLocked()).thenReturn(USER_SYSTEM_ID);
+ when(mMockA11ySecurityPolicy.resolveCallingUserIdEnforcingPermissionsLocked(
+ USER_PROFILE)).thenReturn(USER_PROFILE_PARENT);
+ when(mMockA11ySecurityPolicy.resolveCallingUserIdEnforcingPermissionsLocked(
+ USER_SYSTEM_ID)).thenReturn(USER_SYSTEM_ID);
+ when(mMockA11ySecurityPolicy.resolveValidReportedPackageLocked(
+ anyString(), anyInt(), anyInt(), anyInt())).thenReturn(PACKAGE_NAME);
+
+ doAnswer((invocation) -> {
+ onWindowsForAccessibilityChanged(invocation.getArgument(0), false);
+ return null;
+ }).when(mMockWindowManagerInternal).computeWindowsForAccessibility(anyInt());
+
+ mA11yWindowManager = new AccessibilityWindowManager(new Object(), mHandler,
+ mMockWindowManagerInternal,
+ mMockA11yEventSender,
+ mMockA11ySecurityPolicy,
+ mMockA11yUserManager,
+ mMockA11yTraceManager);
+ // Starts tracking window of default display and sets the default display
+ // as top focused display before each testing starts.
+ startTrackingPerDisplay(Display.DEFAULT_DISPLAY);
+
+ // AccessibilityEventSender is invoked during onWindowsForAccessibilityChanged.
+ // Resets it for mockito verify of further test case.
+ Mockito.reset(mMockA11yEventSender);
+
+ registerLeashedTokenAndWindowId();
+ }
+
+ @After
+ public void tearDown() {
+ mHandler.removeAllMessages();
+ }
+
+ @Test
+ public void startTrackingWindows_shouldEnableWindowManagerCallback() {
+ // AccessibilityWindowManager#startTrackingWindows already invoked in setup.
+ assertTrue(mA11yWindowManager.isTrackingWindowsLocked(Display.DEFAULT_DISPLAY));
+ final WindowsForAccessibilityCallback callbacks =
+ mCallbackOfWindows.get(Display.DEFAULT_DISPLAY);
+ verify(mMockWindowManagerInternal).setWindowsForAccessibilityCallback(
+ eq(Display.DEFAULT_DISPLAY), eq(callbacks));
+ }
+
+ @Test
+ public void stopTrackingWindows_shouldDisableWindowManagerCallback() {
+ assertTrue(mA11yWindowManager.isTrackingWindowsLocked(Display.DEFAULT_DISPLAY));
+ Mockito.reset(mMockWindowManagerInternal);
+
+ mA11yWindowManager.stopTrackingWindows(Display.DEFAULT_DISPLAY);
+ assertFalse(mA11yWindowManager.isTrackingWindowsLocked(Display.DEFAULT_DISPLAY));
+ verify(mMockWindowManagerInternal).setWindowsForAccessibilityCallback(
+ eq(Display.DEFAULT_DISPLAY), isNull());
+
+ }
+
+ @Test
+ public void stopTrackingWindows_shouldClearWindows() {
+ assertTrue(mA11yWindowManager.isTrackingWindowsLocked(Display.DEFAULT_DISPLAY));
+ final int activeWindowId = mA11yWindowManager.getActiveWindowId(USER_SYSTEM_ID);
+
+ mA11yWindowManager.stopTrackingWindows(Display.DEFAULT_DISPLAY);
+ assertNull(mA11yWindowManager.getWindowListLocked(Display.DEFAULT_DISPLAY));
+ assertEquals(mA11yWindowManager.getFocusedWindowId(AccessibilityNodeInfo.FOCUS_INPUT),
+ AccessibilityWindowInfo.UNDEFINED_WINDOW_ID);
+ assertEquals(mA11yWindowManager.getActiveWindowId(USER_SYSTEM_ID),
+ activeWindowId);
+ }
+
+ @Test
+ public void stopTrackingWindows_onNonTopFocusedDisplay_shouldNotResetTopFocusWindow()
+ throws RemoteException {
+ // At setup, the default display sets be the top focused display and
+ // its current focused window sets be the top focused window.
+ // Starts tracking window of second display.
+ startTrackingPerDisplay(SECONDARY_DISPLAY_ID);
+ assertTrue(mA11yWindowManager.isTrackingWindowsLocked(SECONDARY_DISPLAY_ID));
+ // Stops tracking windows of second display.
+ mA11yWindowManager.stopTrackingWindows(SECONDARY_DISPLAY_ID);
+ assertNotEquals(mA11yWindowManager.getFocusedWindowId(AccessibilityNodeInfo.FOCUS_INPUT),
+ AccessibilityWindowInfo.UNDEFINED_WINDOW_ID);
+ }
+
+ @Test
+ public void onWindowsChanged_duringTouchInteractAndFocusChange_shouldChangeActiveWindow() {
+ final int activeWindowId = mA11yWindowManager.getActiveWindowId(USER_SYSTEM_ID);
+ WindowInfo focusedWindowInfo =
+ mWindowInfos.get(Display.DEFAULT_DISPLAY).get(DEFAULT_FOCUSED_INDEX);
+ assertEquals(activeWindowId, mA11yWindowManager.findWindowIdLocked(
+ USER_SYSTEM_ID, focusedWindowInfo.token));
+
+ focusedWindowInfo.focused = false;
+ focusedWindowInfo =
+ mWindowInfos.get(Display.DEFAULT_DISPLAY).get(DEFAULT_FOCUSED_INDEX + 1);
+ focusedWindowInfo.focused = true;
+
+ mA11yWindowManager.onTouchInteractionStart();
+ setTopFocusedWindowAndDisplay(Display.DEFAULT_DISPLAY, DEFAULT_FOCUSED_INDEX + 1);
+ onWindowsForAccessibilityChanged(Display.DEFAULT_DISPLAY, SEND_ON_WINDOW_CHANGES);
+
+ assertNotEquals(activeWindowId, mA11yWindowManager.getActiveWindowId(USER_SYSTEM_ID));
+ }
+
+ @Test
+ public void
+ onWindowsChanged_focusChangeOnNonTopFocusedDisplay_perDisplayFocusOn_notChangeWindow()
+ throws RemoteException {
+ // At setup, the default display sets be the top focused display and
+ // its current focused window sets be the top focused window.
+ // Sets supporting multiple focused window, i.e., config_perDisplayFocusEnabled is true.
+ mSupportPerDisplayFocus = true;
+ // Starts tracking window of second display.
+ startTrackingPerDisplay(SECONDARY_DISPLAY_ID);
+ // Gets the active window.
+ final int activeWindowId = mA11yWindowManager.getActiveWindowId(USER_SYSTEM_ID);
+ // Gets the top focused window.
+ final int topFocusedWindowId =
+ mA11yWindowManager.getFocusedWindowId(AccessibilityNodeInfo.FOCUS_INPUT);
+ // Changes the current focused window at second display.
+ changeFocusedWindowOnDisplayPerDisplayFocusConfig(SECONDARY_DISPLAY_ID,
+ DEFAULT_FOCUSED_INDEX + 1, Display.DEFAULT_DISPLAY, DEFAULT_FOCUSED_INDEX);
+
+ onWindowsForAccessibilityChanged(SECONDARY_DISPLAY_ID, SEND_ON_WINDOW_CHANGES);
+ // The active window should not be changed.
+ assertEquals(activeWindowId, mA11yWindowManager.getActiveWindowId(USER_SYSTEM_ID));
+ // The top focused window should not be changed.
+ assertEquals(topFocusedWindowId,
+ mA11yWindowManager.getFocusedWindowId(AccessibilityNodeInfo.FOCUS_INPUT));
+ }
+
+ @Test
+ public void
+ onWindowChange_focusChangeToNonTopFocusedDisplay_perDisplayFocusOff_shouldChangeWindow()
+ throws RemoteException {
+ // At setup, the default display sets be the top focused display and
+ // its current focused window sets be the top focused window.
+ // Sets not supporting multiple focused window, i.e., config_perDisplayFocusEnabled is
+ // false.
+ mSupportPerDisplayFocus = false;
+ // Starts tracking window of second display.
+ startTrackingPerDisplay(SECONDARY_DISPLAY_ID);
+ // Gets the active window.
+ final int activeWindowId = mA11yWindowManager.getActiveWindowId(USER_SYSTEM_ID);
+ // Gets the top focused window.
+ final int topFocusedWindowId =
+ mA11yWindowManager.getFocusedWindowId(AccessibilityNodeInfo.FOCUS_INPUT);
+ // Changes the current focused window from default display to second display.
+ changeFocusedWindowOnDisplayPerDisplayFocusConfig(SECONDARY_DISPLAY_ID,
+ DEFAULT_FOCUSED_INDEX, Display.DEFAULT_DISPLAY, DEFAULT_FOCUSED_INDEX);
+
+ onWindowsForAccessibilityChanged(Display.DEFAULT_DISPLAY, SEND_ON_WINDOW_CHANGES);
+ onWindowsForAccessibilityChanged(SECONDARY_DISPLAY_ID, SEND_ON_WINDOW_CHANGES);
+ // The active window should be changed.
+ assertNotEquals(activeWindowId, mA11yWindowManager.getActiveWindowId(USER_SYSTEM_ID));
+ // The top focused window should be changed.
+ assertNotEquals(topFocusedWindowId,
+ mA11yWindowManager.getFocusedWindowId(AccessibilityNodeInfo.FOCUS_INPUT));
+ }
+
+ @Test
+ public void onWindowsChanged_shouldReportCorrectLayer() {
+ // AccessibilityWindowManager#onWindowsForAccessibilityChanged already invoked in setup.
+ List<AccessibilityWindowInfo> a11yWindows =
+ mA11yWindowManager.getWindowListLocked(Display.DEFAULT_DISPLAY);
+ for (int i = 0; i < a11yWindows.size(); i++) {
+ final AccessibilityWindowInfo a11yWindow = a11yWindows.get(i);
+ final WindowInfo windowInfo = mWindowInfos.get(Display.DEFAULT_DISPLAY).get(i);
+ assertThat(mWindowInfos.get(Display.DEFAULT_DISPLAY).size() - windowInfo.layer - 1,
+ is(a11yWindow.getLayer()));
+ }
+ }
+
+ @Test
+ public void onWindowsChanged_shouldReportCorrectOrder() {
+ // AccessibilityWindowManager#onWindowsForAccessibilityChanged already invoked in setup.
+ List<AccessibilityWindowInfo> a11yWindows =
+ mA11yWindowManager.getWindowListLocked(Display.DEFAULT_DISPLAY);
+ for (int i = 0; i < a11yWindows.size(); i++) {
+ final AccessibilityWindowInfo a11yWindow = a11yWindows.get(i);
+ final IBinder windowToken = mA11yWindowManager
+ .getWindowTokenForUserAndWindowIdLocked(USER_SYSTEM_ID, a11yWindow.getId());
+ final WindowInfo windowInfo = mWindowInfos.get(Display.DEFAULT_DISPLAY).get(i);
+ assertThat(windowToken, is(windowInfo.token));
+ }
+ }
+
+ @Test
+ public void onWindowsChangedAndForceSend_shouldUpdateWindows() {
+ final WindowInfo windowInfo = mWindowInfos.get(Display.DEFAULT_DISPLAY).get(0);
+ final int correctLayer =
+ mA11yWindowManager.getWindowListLocked(Display.DEFAULT_DISPLAY).get(0).getLayer();
+ windowInfo.layer += 1;
+
+ onWindowsForAccessibilityChanged(Display.DEFAULT_DISPLAY, FORCE_SEND);
+ assertNotEquals(correctLayer,
+ mA11yWindowManager.getWindowListLocked(Display.DEFAULT_DISPLAY).get(0).getLayer());
+ }
+
+ @Test
+ public void onWindowsChangedNoForceSend_layerChanged_shouldNotUpdateWindows() {
+ final WindowInfo windowInfo = mWindowInfos.get(Display.DEFAULT_DISPLAY).get(0);
+ final int correctLayer =
+ mA11yWindowManager.getWindowListLocked(Display.DEFAULT_DISPLAY).get(0).getLayer();
+ windowInfo.layer += 1;
+
+ onWindowsForAccessibilityChanged(Display.DEFAULT_DISPLAY, SEND_ON_WINDOW_CHANGES);
+ assertEquals(correctLayer,
+ mA11yWindowManager.getWindowListLocked(Display.DEFAULT_DISPLAY).get(0).getLayer());
+ }
+
+ @Test
+ public void onWindowsChangedNoForceSend_windowChanged_shouldUpdateWindows()
+ throws RemoteException {
+ final AccessibilityWindowInfo oldWindow =
+ mA11yWindowManager.getWindowListLocked(Display.DEFAULT_DISPLAY).get(0);
+ final IWindow token = addAccessibilityInteractionConnection(Display.DEFAULT_DISPLAY,
+ true, USER_SYSTEM_ID);
+ final WindowInfo windowInfo = WindowInfo.obtain();
+ windowInfo.type = AccessibilityWindowInfo.TYPE_APPLICATION;
+ windowInfo.token = token.asBinder();
+ windowInfo.layer = 0;
+ windowInfo.regionInScreen.set(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
+ mWindowInfos.get(Display.DEFAULT_DISPLAY).set(0, windowInfo);
+
+ onWindowsForAccessibilityChanged(Display.DEFAULT_DISPLAY, SEND_ON_WINDOW_CHANGES);
+ assertNotEquals(oldWindow,
+ mA11yWindowManager.getWindowListLocked(Display.DEFAULT_DISPLAY).get(0));
+ }
+
+ @Test
+ public void onWindowsChangedNoForceSend_focusChanged_shouldUpdateWindows() {
+ final WindowInfo focusedWindowInfo =
+ mWindowInfos.get(Display.DEFAULT_DISPLAY).get(DEFAULT_FOCUSED_INDEX);
+ final WindowInfo windowInfo = mWindowInfos.get(Display.DEFAULT_DISPLAY).get(0);
+ focusedWindowInfo.focused = false;
+ windowInfo.focused = true;
+
+ onWindowsForAccessibilityChanged(Display.DEFAULT_DISPLAY, SEND_ON_WINDOW_CHANGES);
+ assertTrue(mA11yWindowManager.getWindowListLocked(Display.DEFAULT_DISPLAY).get(0)
+ .isFocused());
+ }
+
+ @Test
+ public void removeAccessibilityInteractionConnection_byWindowToken_shouldRemoved() {
+ for (int i = 0; i < NUM_OF_WINDOWS; i++) {
+ final int windowId = mA11yWindowTokens.keyAt(i);
+ final IWindow windowToken = mA11yWindowTokens.valueAt(i);
+ assertNotNull(mA11yWindowManager.getConnectionLocked(USER_SYSTEM_ID, windowId));
+
+ mA11yWindowManager.removeAccessibilityInteractionConnection(windowToken);
+ assertNull(mA11yWindowManager.getConnectionLocked(USER_SYSTEM_ID, windowId));
+ }
+ }
+
+ @Test
+ public void remoteAccessibilityConnection_binderDied_shouldRemoveConnection() {
+ for (int i = 0; i < NUM_OF_WINDOWS; i++) {
+ final int windowId = mA11yWindowTokens.keyAt(i);
+ final RemoteAccessibilityConnection remoteA11yConnection =
+ mA11yWindowManager.getConnectionLocked(USER_SYSTEM_ID, windowId);
+ assertNotNull(remoteA11yConnection);
+
+ remoteA11yConnection.binderDied();
+ assertNull(mA11yWindowManager.getConnectionLocked(USER_SYSTEM_ID, windowId));
+ }
+ }
+
+ @Test
+ public void getWindowTokenForUserAndWindowId_shouldNotNull() {
+ final List<AccessibilityWindowInfo> windows =
+ mA11yWindowManager.getWindowListLocked(Display.DEFAULT_DISPLAY);
+ for (int i = 0; i < windows.size(); i++) {
+ final int windowId = windows.get(i).getId();
+
+ assertNotNull(mA11yWindowManager.getWindowTokenForUserAndWindowIdLocked(
+ USER_SYSTEM_ID, windowId));
+ }
+ }
+
+ @Test
+ public void findWindowId() {
+ final List<AccessibilityWindowInfo> windows =
+ mA11yWindowManager.getWindowListLocked(Display.DEFAULT_DISPLAY);
+ for (int i = 0; i < windows.size(); i++) {
+ final int windowId = windows.get(i).getId();
+ final IBinder windowToken = mA11yWindowManager.getWindowTokenForUserAndWindowIdLocked(
+ USER_SYSTEM_ID, windowId);
+
+ assertEquals(mA11yWindowManager.findWindowIdLocked(
+ USER_SYSTEM_ID, windowToken), windowId);
+ }
+ }
+
+ @Test
+ public void resolveParentWindowId_windowIsNotEmbedded_shouldReturnGivenId()
+ throws RemoteException {
+ final int windowId = addAccessibilityInteractionConnection(Display.DEFAULT_DISPLAY, false,
+ Mockito.mock(IBinder.class), USER_SYSTEM_ID);
+ assertEquals(windowId, mA11yWindowManager.resolveParentWindowIdLocked(windowId));
+ }
+
+ @Test
+ public void resolveParentWindowId_windowIsNotRegistered_shouldReturnGivenId() {
+ final int windowId = -1;
+ assertEquals(windowId, mA11yWindowManager.resolveParentWindowIdLocked(windowId));
+ }
+
+ @Test
+ public void resolveParentWindowId_windowIsAssociated_shouldReturnParentWindowId()
+ throws RemoteException {
+ final IBinder mockHostToken = Mockito.mock(IBinder.class);
+ final IBinder mockEmbeddedToken = Mockito.mock(IBinder.class);
+ final int hostWindowId = addAccessibilityInteractionConnection(Display.DEFAULT_DISPLAY,
+ false, mockHostToken, USER_SYSTEM_ID);
+ final int embeddedWindowId = addAccessibilityInteractionConnection(Display.DEFAULT_DISPLAY,
+ false, mockEmbeddedToken, USER_SYSTEM_ID);
+
+ mA11yWindowManager.associateEmbeddedHierarchyLocked(mockHostToken, mockEmbeddedToken);
+
+ final int resolvedWindowId = mA11yWindowManager.resolveParentWindowIdLocked(
+ embeddedWindowId);
+ assertEquals(hostWindowId, resolvedWindowId);
+ }
+
+ @Test
+ public void resolveParentWindowId_windowIsDisassociated_shouldReturnGivenId()
+ throws RemoteException {
+ final IBinder mockHostToken = Mockito.mock(IBinder.class);
+ final IBinder mockEmbeddedToken = Mockito.mock(IBinder.class);
+ final int hostWindowId = addAccessibilityInteractionConnection(Display.DEFAULT_DISPLAY,
+ false, mockHostToken, USER_SYSTEM_ID);
+ final int embeddedWindowId = addAccessibilityInteractionConnection(Display.DEFAULT_DISPLAY,
+ false, mockEmbeddedToken, USER_SYSTEM_ID);
+
+ mA11yWindowManager.associateEmbeddedHierarchyLocked(mockHostToken, mockEmbeddedToken);
+ mA11yWindowManager.disassociateEmbeddedHierarchyLocked(mockEmbeddedToken);
+
+ final int resolvedWindowId = mA11yWindowManager.resolveParentWindowIdLocked(
+ embeddedWindowId);
+ assertNotEquals(hostWindowId, resolvedWindowId);
+ assertEquals(embeddedWindowId, resolvedWindowId);
+ }
+
+ @Test
+ public void computePartialInteractiveRegionForWindow_wholeVisible_returnWholeRegion() {
+ // Updates top 2 z-order WindowInfo are whole visible.
+ WindowInfo windowInfo = mWindowInfos.get(Display.DEFAULT_DISPLAY).get(0);
+ windowInfo.regionInScreen.set(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 2);
+ windowInfo = mWindowInfos.get(Display.DEFAULT_DISPLAY).get(1);
+ windowInfo.regionInScreen.set(0, SCREEN_HEIGHT / 2,
+ SCREEN_WIDTH, SCREEN_HEIGHT);
+ onWindowsForAccessibilityChanged(Display.DEFAULT_DISPLAY, SEND_ON_WINDOW_CHANGES);
+
+ final List<AccessibilityWindowInfo> a11yWindows =
+ mA11yWindowManager.getWindowListLocked(Display.DEFAULT_DISPLAY);
+ final Region outBounds = new Region();
+ int windowId = a11yWindows.get(0).getId();
+
+ mA11yWindowManager.computePartialInteractiveRegionForWindowLocked(windowId, outBounds);
+ assertThat(outBounds.getBounds().width(), is(SCREEN_WIDTH));
+ assertThat(outBounds.getBounds().height(), is(SCREEN_HEIGHT / 2));
+
+ windowId = a11yWindows.get(1).getId();
+
+ mA11yWindowManager.computePartialInteractiveRegionForWindowLocked(windowId, outBounds);
+ assertThat(outBounds.getBounds().width(), is(SCREEN_WIDTH));
+ assertThat(outBounds.getBounds().height(), is(SCREEN_HEIGHT / 2));
+ }
+
+ @Test
+ public void computePartialInteractiveRegionForWindow_halfVisible_returnHalfRegion() {
+ // Updates z-order #1 WindowInfo is half visible.
+ WindowInfo windowInfo = mWindowInfos.get(Display.DEFAULT_DISPLAY).get(0);
+ windowInfo.regionInScreen.set(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 2);
+
+ onWindowsForAccessibilityChanged(Display.DEFAULT_DISPLAY, SEND_ON_WINDOW_CHANGES);
+ final List<AccessibilityWindowInfo> a11yWindows =
+ mA11yWindowManager.getWindowListLocked(Display.DEFAULT_DISPLAY);
+ final Region outBounds = new Region();
+ int windowId = a11yWindows.get(1).getId();
+
+ mA11yWindowManager.computePartialInteractiveRegionForWindowLocked(windowId, outBounds);
+ assertThat(outBounds.getBounds().width(), is(SCREEN_WIDTH));
+ assertThat(outBounds.getBounds().height(), is(SCREEN_HEIGHT / 2));
+ }
+
+ @Test
+ public void computePartialInteractiveRegionForWindow_notVisible_returnEmptyRegion() {
+ // Since z-order #0 WindowInfo is full screen, z-order #1 WindowInfo should be invisible.
+ final List<AccessibilityWindowInfo> a11yWindows =
+ mA11yWindowManager.getWindowListLocked(Display.DEFAULT_DISPLAY);
+ final Region outBounds = new Region();
+ int windowId = a11yWindows.get(1).getId();
+
+ mA11yWindowManager.computePartialInteractiveRegionForWindowLocked(windowId, outBounds);
+ assertTrue(outBounds.getBounds().isEmpty());
+ }
+
+ @Test
+ public void computePartialInteractiveRegionForWindow_partialVisible_returnVisibleRegion() {
+ // Updates z-order #0 WindowInfo to have two interact-able areas.
+ Region region = new Region(0, 0, SCREEN_WIDTH, 200);
+ region.op(0, SCREEN_HEIGHT - 200, SCREEN_WIDTH, SCREEN_HEIGHT, Region.Op.UNION);
+ WindowInfo windowInfo = mWindowInfos.get(Display.DEFAULT_DISPLAY).get(0);
+ windowInfo.regionInScreen.set(region);
+ onWindowsForAccessibilityChanged(Display.DEFAULT_DISPLAY, SEND_ON_WINDOW_CHANGES);
+
+ final List<AccessibilityWindowInfo> a11yWindows =
+ mA11yWindowManager.getWindowListLocked(Display.DEFAULT_DISPLAY);
+ final Region outBounds = new Region();
+ int windowId = a11yWindows.get(1).getId();
+
+ mA11yWindowManager.computePartialInteractiveRegionForWindowLocked(windowId, outBounds);
+ assertFalse(outBounds.getBounds().isEmpty());
+ assertThat(outBounds.getBounds().width(), is(SCREEN_WIDTH));
+ assertThat(outBounds.getBounds().height(), is(SCREEN_HEIGHT - 400));
+ }
+
+ @Test
+ public void updateActiveAndA11yFocusedWindow_windowStateChangedEvent_noTracking_shouldUpdate() {
+ final IBinder eventWindowToken =
+ mWindowInfos.get(Display.DEFAULT_DISPLAY).get(DEFAULT_FOCUSED_INDEX + 1).token;
+ final int eventWindowId = mA11yWindowManager.findWindowIdLocked(
+ USER_SYSTEM_ID, eventWindowToken);
+ when(mMockWindowManagerInternal.getFocusedWindowTokenFromWindowStates())
+ .thenReturn(eventWindowToken);
+
+ final int noUse = 0;
+ mA11yWindowManager.stopTrackingWindows(Display.DEFAULT_DISPLAY);
+ mA11yWindowManager.updateActiveAndAccessibilityFocusedWindowLocked(USER_SYSTEM_ID,
+ eventWindowId,
+ noUse,
+ AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
+ noUse);
+ assertThat(mA11yWindowManager.getActiveWindowId(USER_SYSTEM_ID), is(eventWindowId));
+ assertThat(mA11yWindowManager.getFocusedWindowId(AccessibilityNodeInfo.FOCUS_INPUT),
+ is(eventWindowId));
+ }
+
+ @Test
+ public void updateActiveAndA11yFocusedWindow_hoverEvent_touchInteract_shouldSetActiveWindow() {
+ final int eventWindowId = getWindowIdFromWindowInfosForDisplay(Display.DEFAULT_DISPLAY,
+ DEFAULT_FOCUSED_INDEX + 1);
+ final int currentActiveWindowId = mA11yWindowManager.getActiveWindowId(USER_SYSTEM_ID);
+ assertThat(currentActiveWindowId, is(not(eventWindowId)));
+
+ final int noUse = 0;
+ mA11yWindowManager.onTouchInteractionStart();
+ mA11yWindowManager.updateActiveAndAccessibilityFocusedWindowLocked(USER_SYSTEM_ID,
+ eventWindowId,
+ noUse,
+ AccessibilityEvent.TYPE_VIEW_HOVER_ENTER,
+ noUse);
+ assertThat(mA11yWindowManager.getActiveWindowId(USER_SYSTEM_ID), is(eventWindowId));
+ final ArgumentCaptor<AccessibilityEvent> captor =
+ ArgumentCaptor.forClass(AccessibilityEvent.class);
+ verify(mMockA11yEventSender, times(2))
+ .sendAccessibilityEventForCurrentUserLocked(captor.capture());
+ assertThat(captor.getAllValues().get(0),
+ allOf(displayId(Display.DEFAULT_DISPLAY),
+ a11yWindowId(currentActiveWindowId),
+ a11yWindowChanges(AccessibilityEvent.WINDOWS_CHANGE_ACTIVE)));
+ assertThat(captor.getAllValues().get(1),
+ allOf(displayId(Display.DEFAULT_DISPLAY),
+ a11yWindowId(eventWindowId),
+ a11yWindowChanges(AccessibilityEvent.WINDOWS_CHANGE_ACTIVE)));
+ }
+
+ @Test
+ public void updateActiveAndA11yFocusedWindow_a11yFocusEvent_shouldUpdateA11yFocus() {
+ final int eventWindowId = getWindowIdFromWindowInfosForDisplay(Display.DEFAULT_DISPLAY,
+ DEFAULT_FOCUSED_INDEX);
+ final int currentA11yFocusedWindowId = mA11yWindowManager.getFocusedWindowId(
+ AccessibilityNodeInfo.FOCUS_ACCESSIBILITY);
+ assertThat(currentA11yFocusedWindowId, is(AccessibilityWindowInfo.UNDEFINED_WINDOW_ID));
+
+ final int noUse = 0;
+ mA11yWindowManager.updateActiveAndAccessibilityFocusedWindowLocked(USER_SYSTEM_ID,
+ eventWindowId,
+ AccessibilityNodeInfo.ROOT_NODE_ID,
+ AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED,
+ noUse);
+ assertThat(mA11yWindowManager.getFocusedWindowId(
+ AccessibilityNodeInfo.FOCUS_ACCESSIBILITY), is(eventWindowId));
+ final ArgumentCaptor<AccessibilityEvent> captor =
+ ArgumentCaptor.forClass(AccessibilityEvent.class);
+ verify(mMockA11yEventSender, times(1))
+ .sendAccessibilityEventForCurrentUserLocked(captor.capture());
+ assertThat(captor.getAllValues().get(0),
+ allOf(displayId(Display.DEFAULT_DISPLAY),
+ a11yWindowId(eventWindowId),
+ a11yWindowChanges(
+ AccessibilityEvent.WINDOWS_CHANGE_ACCESSIBILITY_FOCUSED)));
+ }
+
+ @Test
+ public void updateActiveAndA11yFocusedWindow_a11yFocusEvent_multiDisplay_defaultToSecondary()
+ throws RemoteException {
+ runUpdateActiveAndA11yFocusedWindow_MultiDisplayTest(
+ Display.DEFAULT_DISPLAY, SECONDARY_DISPLAY_ID);
+ }
+
+ @Test
+ public void updateActiveAndA11yFocusedWindow_a11yFocusEvent_multiDisplay_SecondaryToDefault()
+ throws RemoteException {
+ runUpdateActiveAndA11yFocusedWindow_MultiDisplayTest(
+ SECONDARY_DISPLAY_ID, Display.DEFAULT_DISPLAY);
+ }
+
+ private void runUpdateActiveAndA11yFocusedWindow_MultiDisplayTest(
+ int initialDisplayId, int eventDisplayId) throws RemoteException {
+ startTrackingPerDisplay(SECONDARY_DISPLAY_ID);
+ final int initialWindowId = getWindowIdFromWindowInfosForDisplay(
+ initialDisplayId, DEFAULT_FOCUSED_INDEX);
+ final int noUse = 0;
+ mA11yWindowManager.updateActiveAndAccessibilityFocusedWindowLocked(USER_SYSTEM_ID,
+ initialWindowId,
+ AccessibilityNodeInfo.ROOT_NODE_ID,
+ AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED,
+ noUse);
+ assertThat(mA11yWindowManager.getFocusedWindowId(
+ AccessibilityNodeInfo.FOCUS_ACCESSIBILITY), is(initialWindowId));
+ Mockito.reset(mMockA11yEventSender);
+
+ final int eventWindowId = getWindowIdFromWindowInfosForDisplay(
+ eventDisplayId, DEFAULT_FOCUSED_INDEX);
+ mA11yWindowManager.updateActiveAndAccessibilityFocusedWindowLocked(USER_SYSTEM_ID,
+ eventWindowId,
+ AccessibilityNodeInfo.ROOT_NODE_ID,
+ AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED,
+ noUse);
+ assertThat(mA11yWindowManager.getFocusedWindowId(
+ AccessibilityNodeInfo.FOCUS_ACCESSIBILITY), is(eventWindowId));
+ final ArgumentCaptor<AccessibilityEvent> captor =
+ ArgumentCaptor.forClass(AccessibilityEvent.class);
+ verify(mMockA11yEventSender, times(2))
+ .sendAccessibilityEventForCurrentUserLocked(captor.capture());
+ assertThat(captor.getAllValues().get(0),
+ allOf(displayId(initialDisplayId),
+ a11yWindowId(initialWindowId),
+ a11yWindowChanges(
+ AccessibilityEvent.WINDOWS_CHANGE_ACCESSIBILITY_FOCUSED)));
+ assertThat(captor.getAllValues().get(1),
+ allOf(displayId(eventDisplayId),
+ a11yWindowId(eventWindowId),
+ a11yWindowChanges(
+ AccessibilityEvent.WINDOWS_CHANGE_ACCESSIBILITY_FOCUSED)));
+ }
+
+ @Test
+ public void updateActiveAndA11yFocusedWindow_clearA11yFocusEvent_shouldClearA11yFocus() {
+ final int eventWindowId = getWindowIdFromWindowInfosForDisplay(Display.DEFAULT_DISPLAY,
+ DEFAULT_FOCUSED_INDEX);
+ final int currentA11yFocusedWindowId = mA11yWindowManager.getFocusedWindowId(
+ AccessibilityNodeInfo.FOCUS_ACCESSIBILITY);
+ assertThat(currentA11yFocusedWindowId, is(not(eventWindowId)));
+
+ final int noUse = 0;
+ mA11yWindowManager.updateActiveAndAccessibilityFocusedWindowLocked(USER_SYSTEM_ID,
+ eventWindowId,
+ AccessibilityNodeInfo.ROOT_NODE_ID,
+ AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED,
+ noUse);
+ assertThat(mA11yWindowManager.getFocusedWindowId(
+ AccessibilityNodeInfo.FOCUS_ACCESSIBILITY), is(eventWindowId));
+ mA11yWindowManager.updateActiveAndAccessibilityFocusedWindowLocked(USER_SYSTEM_ID,
+ eventWindowId,
+ AccessibilityNodeInfo.ROOT_NODE_ID,
+ AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED,
+ noUse);
+ assertThat(mA11yWindowManager.getFocusedWindowId(
+ AccessibilityNodeInfo.FOCUS_ACCESSIBILITY),
+ is(AccessibilityWindowInfo.UNDEFINED_WINDOW_ID));
+ }
+
+ @Test
+ public void onTouchInteractionEnd_shouldRollbackActiveWindow() {
+ final int eventWindowId = getWindowIdFromWindowInfosForDisplay(Display.DEFAULT_DISPLAY,
+ DEFAULT_FOCUSED_INDEX + 1);
+ final int currentActiveWindowId = mA11yWindowManager.getActiveWindowId(USER_SYSTEM_ID);
+ assertThat(currentActiveWindowId, is(not(eventWindowId)));
+
+ final int noUse = 0;
+ mA11yWindowManager.onTouchInteractionStart();
+ mA11yWindowManager.updateActiveAndAccessibilityFocusedWindowLocked(USER_SYSTEM_ID,
+ eventWindowId,
+ noUse,
+ AccessibilityEvent.TYPE_VIEW_HOVER_ENTER,
+ noUse);
+ assertThat(mA11yWindowManager.getActiveWindowId(USER_SYSTEM_ID), is(eventWindowId));
+ // AccessibilityEventSender is invoked after active window changed. Reset it.
+ Mockito.reset(mMockA11yEventSender);
+
+ mA11yWindowManager.onTouchInteractionEnd();
+ final ArgumentCaptor<AccessibilityEvent> captor =
+ ArgumentCaptor.forClass(AccessibilityEvent.class);
+ verify(mMockA11yEventSender, times(2))
+ .sendAccessibilityEventForCurrentUserLocked(captor.capture());
+ assertThat(captor.getAllValues().get(0),
+ allOf(displayId(Display.DEFAULT_DISPLAY),
+ a11yWindowId(eventWindowId),
+ a11yWindowChanges(AccessibilityEvent.WINDOWS_CHANGE_ACTIVE)));
+ assertThat(captor.getAllValues().get(1),
+ allOf(displayId(Display.DEFAULT_DISPLAY),
+ a11yWindowId(currentActiveWindowId),
+ a11yWindowChanges(AccessibilityEvent.WINDOWS_CHANGE_ACTIVE)));
+ }
+
+ @Test
+ public void onTouchInteractionEnd_noServiceInteractiveWindow_shouldClearA11yFocus()
+ throws RemoteException {
+ final IBinder defaultFocusWinToken =
+ mWindowInfos.get(Display.DEFAULT_DISPLAY).get(DEFAULT_FOCUSED_INDEX).token;
+ final int defaultFocusWindowId = mA11yWindowManager.findWindowIdLocked(
+ USER_SYSTEM_ID, defaultFocusWinToken);
+ when(mMockWindowManagerInternal.getFocusedWindowTokenFromWindowStates())
+ .thenReturn(defaultFocusWinToken);
+ final int newFocusWindowId = getWindowIdFromWindowInfosForDisplay(Display.DEFAULT_DISPLAY,
+ DEFAULT_FOCUSED_INDEX + 1);
+ final IAccessibilityInteractionConnection mockNewFocusConnection =
+ mA11yWindowManager.getConnectionLocked(
+ USER_SYSTEM_ID, newFocusWindowId).getRemote();
+
+ mA11yWindowManager.stopTrackingWindows(Display.DEFAULT_DISPLAY);
+ final int noUse = 0;
+ mA11yWindowManager.updateActiveAndAccessibilityFocusedWindowLocked(USER_SYSTEM_ID,
+ defaultFocusWindowId,
+ noUse,
+ AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
+ noUse);
+ assertThat(mA11yWindowManager.getActiveWindowId(USER_SYSTEM_ID), is(defaultFocusWindowId));
+ assertThat(mA11yWindowManager.getFocusedWindowId(AccessibilityNodeInfo.FOCUS_INPUT),
+ is(defaultFocusWindowId));
+
+ mA11yWindowManager.onTouchInteractionStart();
+ mA11yWindowManager.updateActiveAndAccessibilityFocusedWindowLocked(USER_SYSTEM_ID,
+ newFocusWindowId,
+ noUse,
+ AccessibilityEvent.TYPE_VIEW_HOVER_ENTER,
+ noUse);
+ mA11yWindowManager.updateActiveAndAccessibilityFocusedWindowLocked(USER_SYSTEM_ID,
+ newFocusWindowId,
+ AccessibilityNodeInfo.ROOT_NODE_ID,
+ AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED,
+ noUse);
+ assertThat(mA11yWindowManager.getActiveWindowId(USER_SYSTEM_ID), is(newFocusWindowId));
+ assertThat(mA11yWindowManager.getFocusedWindowId(
+ AccessibilityNodeInfo.FOCUS_ACCESSIBILITY), is(newFocusWindowId));
+
+ mA11yWindowManager.onTouchInteractionEnd();
+ mHandler.sendLastMessage();
+ verify(mockNewFocusConnection).clearAccessibilityFocus();
+ }
+
+ @Test
+ public void getPictureInPictureWindow_shouldNotNull() {
+ assertNull(mA11yWindowManager.getPictureInPictureWindowLocked());
+ mWindowInfos.get(Display.DEFAULT_DISPLAY).get(1).inPictureInPicture = true;
+ onWindowsForAccessibilityChanged(Display.DEFAULT_DISPLAY, SEND_ON_WINDOW_CHANGES);
+
+ assertNotNull(mA11yWindowManager.getPictureInPictureWindowLocked());
+ }
+
+ @Test
+ public void notifyOutsideTouch() throws RemoteException {
+ final int targetWindowId =
+ getWindowIdFromWindowInfosForDisplay(Display.DEFAULT_DISPLAY, 1);
+ final int outsideWindowId =
+ getWindowIdFromWindowInfosForDisplay(Display.DEFAULT_DISPLAY, 0);
+ final IAccessibilityInteractionConnection mockRemoteConnection =
+ mA11yWindowManager.getConnectionLocked(
+ USER_SYSTEM_ID, outsideWindowId).getRemote();
+ mWindowInfos.get(Display.DEFAULT_DISPLAY).get(0).hasFlagWatchOutsideTouch = true;
+ onWindowsForAccessibilityChanged(Display.DEFAULT_DISPLAY, SEND_ON_WINDOW_CHANGES);
+
+ mA11yWindowManager.notifyOutsideTouch(USER_SYSTEM_ID, targetWindowId);
+ verify(mockRemoteConnection).notifyOutsideTouch();
+ }
+
+ @Test
+ public void addAccessibilityInteractionConnection_profileUser_findInParentUser()
+ throws RemoteException {
+ final IWindow token = addAccessibilityInteractionConnection(Display.DEFAULT_DISPLAY,
+ false, USER_PROFILE);
+ final int windowId = mA11yWindowManager.findWindowIdLocked(
+ USER_PROFILE_PARENT, token.asBinder());
+ assertTrue(windowId >= 0);
+ }
+
+ @Test
+ public void getDisplayList() throws RemoteException {
+ // Starts tracking window of second display.
+ startTrackingPerDisplay(SECONDARY_DISPLAY_ID);
+
+ final ArrayList<Integer> displayList = mA11yWindowManager.getDisplayListLocked(
+ DISPLAY_TYPE_DEFAULT);
+ assertTrue(displayList.equals(mExpectedDisplayList));
+ }
+
+ @Test
+ public void setAccessibilityWindowIdToSurfaceMetadata()
+ throws RemoteException {
+ final IWindow token = addAccessibilityInteractionConnection(Display.DEFAULT_DISPLAY,
+ true, USER_SYSTEM_ID);
+ int windowId = -1;
+ for (int i = 0; i < mA11yWindowTokens.size(); i++) {
+ if (mA11yWindowTokens.valueAt(i).equals(token)) {
+ windowId = mA11yWindowTokens.keyAt(i);
+ }
+ }
+ assertNotEquals("Returned token is not found in mA11yWindowTokens", -1, windowId);
+ verify(mMockWindowManagerInternal, times(1)).setAccessibilityIdToSurfaceMetadata(
+ token.asBinder(), windowId);
+
+ mA11yWindowManager.removeAccessibilityInteractionConnection(token);
+ verify(mMockWindowManagerInternal, times(1)).setAccessibilityIdToSurfaceMetadata(
+ token.asBinder(), -1);
+ }
+
+ @Test
+ public void getHostTokenLocked_hierarchiesAreAssociated_shouldReturnHostToken() {
+ mA11yWindowManager.associateLocked(mMockEmbeddedToken, mMockHostToken);
+ final IBinder hostToken = mA11yWindowManager.getHostTokenLocked(mMockEmbeddedToken);
+ assertEquals(hostToken, mMockHostToken);
+ }
+
+ @Test
+ public void getHostTokenLocked_hierarchiesAreNotAssociated_shouldReturnNull() {
+ final IBinder hostToken = mA11yWindowManager.getHostTokenLocked(mMockEmbeddedToken);
+ assertNull(hostToken);
+ }
+
+ @Test
+ public void getHostTokenLocked_embeddedHierarchiesAreDisassociated_shouldReturnNull() {
+ mA11yWindowManager.associateLocked(mMockEmbeddedToken, mMockHostToken);
+ mA11yWindowManager.disassociateLocked(mMockEmbeddedToken);
+ final IBinder hostToken = mA11yWindowManager.getHostTokenLocked(mMockEmbeddedToken);
+ assertNull(hostToken);
+ }
+
+ @Test
+ public void getHostTokenLocked_hostHierarchiesAreDisassociated_shouldReturnNull() {
+ mA11yWindowManager.associateLocked(mMockEmbeddedToken, mMockHostToken);
+ mA11yWindowManager.disassociateLocked(mMockHostToken);
+ final IBinder hostToken = mA11yWindowManager.getHostTokenLocked(mMockHostToken);
+ assertNull(hostToken);
+ }
+
+ @Test
+ public void getWindowIdLocked_windowIsRegistered_shouldReturnWindowId() {
+ final int windowId = mA11yWindowManager.getWindowIdLocked(mMockHostToken);
+ assertEquals(windowId, HOST_WINDOW_ID);
+ }
+
+ @Test
+ public void getWindowIdLocked_windowIsNotRegistered_shouldReturnInvalidWindowId() {
+ final int windowId = mA11yWindowManager.getWindowIdLocked(mMockInvalidToken);
+ assertEquals(windowId, INVALID_ID);
+ }
+
+ @Test
+ public void getTokenLocked_windowIsRegistered_shouldReturnToken() {
+ final IBinder token = mA11yWindowManager.getLeashTokenLocked(HOST_WINDOW_ID);
+ assertEquals(token, mMockHostToken);
+ }
+
+ @Test
+ public void getTokenLocked_windowIsNotRegistered_shouldReturnNull() {
+ final IBinder token = mA11yWindowManager.getLeashTokenLocked(OTHER_WINDOW_ID);
+ assertNull(token);
+ }
+
+ @Test
+ public void setAccessibilityWindowAttributes_windowIsNotRegistered_titleIsChanged() {
+ final int windowId =
+ getWindowIdFromWindowInfosForDisplay(Display.DEFAULT_DISPLAY, 0);
+ final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
+ layoutParams.accessibilityTitle = "accessibility window title";
+ final AccessibilityWindowAttributes attributes = new AccessibilityWindowAttributes(
+ layoutParams, new LocaleList());
+
+ mA11yWindowManager.setAccessibilityWindowAttributes(Display.DEFAULT_DISPLAY, windowId,
+ USER_SYSTEM_ID, attributes);
+
+ final AccessibilityWindowInfo a11yWindow = mA11yWindowManager.findA11yWindowInfoByIdLocked(
+ windowId);
+ assertEquals(toString(layoutParams.accessibilityTitle), toString(a11yWindow.getTitle()));
+ }
+
+ @Test
+ public void sendAccessibilityEventOnWindowRemoval() {
+ final ArrayList<WindowInfo> infos = mWindowInfos.get(Display.DEFAULT_DISPLAY);
+
+ // Removing index 0 because it's not focused, and avoids unnecessary layer change.
+ final int windowId =
+ getWindowIdFromWindowInfosForDisplay(Display.DEFAULT_DISPLAY, 0);
+ infos.remove(0);
+ for (WindowInfo info : infos) {
+ // Adjust layer number because it should start from 0.
+ info.layer--;
+ }
+
+ onWindowsForAccessibilityChanged(Display.DEFAULT_DISPLAY, FORCE_SEND);
+
+ final ArgumentCaptor<AccessibilityEvent> captor =
+ ArgumentCaptor.forClass(AccessibilityEvent.class);
+ verify(mMockA11yEventSender, times(1))
+ .sendAccessibilityEventForCurrentUserLocked(captor.capture());
+ assertThat(captor.getAllValues().get(0),
+ allOf(displayId(Display.DEFAULT_DISPLAY),
+ a11yWindowId(windowId),
+ a11yWindowChanges(AccessibilityEvent.WINDOWS_CHANGE_REMOVED)));
+ }
+
+ @Test
+ public void sendAccessibilityEventOnWindowAddition() throws RemoteException {
+ final ArrayList<WindowInfo> infos = mWindowInfos.get(Display.DEFAULT_DISPLAY);
+
+ for (WindowInfo info : infos) {
+ // Adjust layer number because new window will have 0 so that layer number in
+ // A11yWindowInfo in window won't be changed.
+ info.layer++;
+ }
+
+ final IWindow token = addAccessibilityInteractionConnection(Display.DEFAULT_DISPLAY,
+ false, USER_SYSTEM_ID);
+ addWindowInfo(infos, token, 0);
+ final int windowId =
+ getWindowIdFromWindowInfosForDisplay(Display.DEFAULT_DISPLAY, infos.size() - 1);
+
+ onWindowsForAccessibilityChanged(Display.DEFAULT_DISPLAY, FORCE_SEND);
+
+ final ArgumentCaptor<AccessibilityEvent> captor =
+ ArgumentCaptor.forClass(AccessibilityEvent.class);
+ verify(mMockA11yEventSender, times(1))
+ .sendAccessibilityEventForCurrentUserLocked(captor.capture());
+ assertThat(captor.getAllValues().get(0),
+ allOf(displayId(Display.DEFAULT_DISPLAY),
+ a11yWindowId(windowId),
+ a11yWindowChanges(AccessibilityEvent.WINDOWS_CHANGE_ADDED)));
+ }
+
+ @Test
+ public void sendAccessibilityEventOnWindowChange() {
+ final ArrayList<WindowInfo> infos = mWindowInfos.get(Display.DEFAULT_DISPLAY);
+ infos.get(0).title = "new title";
+ final int windowId = getWindowIdFromWindowInfosForDisplay(Display.DEFAULT_DISPLAY, 0);
+
+ onWindowsForAccessibilityChanged(Display.DEFAULT_DISPLAY, FORCE_SEND);
+
+ final ArgumentCaptor<AccessibilityEvent> captor =
+ ArgumentCaptor.forClass(AccessibilityEvent.class);
+ verify(mMockA11yEventSender, times(1))
+ .sendAccessibilityEventForCurrentUserLocked(captor.capture());
+ assertThat(captor.getAllValues().get(0),
+ allOf(displayId(Display.DEFAULT_DISPLAY),
+ a11yWindowId(windowId),
+ a11yWindowChanges(AccessibilityEvent.WINDOWS_CHANGE_TITLE)));
+ }
+
+ private void registerLeashedTokenAndWindowId() {
+ mA11yWindowManager.registerIdLocked(mMockHostToken, HOST_WINDOW_ID);
+ mA11yWindowManager.registerIdLocked(mMockEmbeddedToken, EMBEDDED_WINDOW_ID);
+ }
+
+ private void startTrackingPerDisplay(int displayId) throws RemoteException {
+ ArrayList<WindowInfo> windowInfosForDisplay = new ArrayList<>();
+ // Adds RemoteAccessibilityConnection into AccessibilityWindowManager, and copy
+ // mock window token into mA11yWindowTokens. Also, preparing WindowInfo mWindowInfos
+ // for the test.
+ int layer = 0;
+ for (int i = 0; i < NUM_GLOBAL_WINDOWS; i++) {
+ final IWindow token = addAccessibilityInteractionConnection(displayId,
+ true, USER_SYSTEM_ID);
+ addWindowInfo(windowInfosForDisplay, token, layer++);
+
+ }
+ for (int i = 0; i < NUM_APP_WINDOWS; i++) {
+ final IWindow token = addAccessibilityInteractionConnection(displayId,
+ false, USER_SYSTEM_ID);
+ addWindowInfo(windowInfosForDisplay, token, layer++);
+ }
+ // Sets up current focused window of display.
+ // Each display has its own current focused window if config_perDisplayFocusEnabled is true.
+ // Otherwise only default display needs to current focused window.
+ if (mSupportPerDisplayFocus || displayId == Display.DEFAULT_DISPLAY) {
+ windowInfosForDisplay.get(DEFAULT_FOCUSED_INDEX).focused = true;
+ }
+ // Turns on windows tracking, and update window info.
+ mA11yWindowManager.startTrackingWindows(displayId, false);
+ // Puts window lists into array.
+ mWindowInfos.put(displayId, windowInfosForDisplay);
+ // Sets the default display is the top focused display and
+ // its current focused window is the top focused window.
+ if (displayId == Display.DEFAULT_DISPLAY) {
+ setTopFocusedWindowAndDisplay(displayId, DEFAULT_FOCUSED_INDEX);
+ }
+ // Invokes callback for sending window lists to A11y framework.
+ onWindowsForAccessibilityChanged(displayId, FORCE_SEND);
+
+ assertEquals(mA11yWindowManager.getWindowListLocked(displayId).size(),
+ windowInfosForDisplay.size());
+ }
+
+ private WindowsForAccessibilityCallback getWindowsForAccessibilityCallbacks(int displayId) {
+ ArgumentCaptor<WindowsForAccessibilityCallback> windowsForAccessibilityCallbacksCaptor =
+ ArgumentCaptor.forClass(
+ WindowsForAccessibilityCallback.class);
+ verify(mMockWindowManagerInternal)
+ .setWindowsForAccessibilityCallback(eq(displayId),
+ windowsForAccessibilityCallbacksCaptor.capture());
+ return windowsForAccessibilityCallbacksCaptor.getValue();
+ }
+
+ private IWindow addAccessibilityInteractionConnection(int displayId, boolean bGlobal,
+ int userId) throws RemoteException {
+ final IWindow mockWindowToken = Mockito.mock(IWindow.class);
+ final IAccessibilityInteractionConnection mockA11yConnection = Mockito.mock(
+ IAccessibilityInteractionConnection.class);
+ final IBinder mockConnectionBinder = Mockito.mock(IBinder.class);
+ final IBinder mockWindowBinder = Mockito.mock(IBinder.class);
+ final IBinder mockLeashToken = Mockito.mock(IBinder.class);
+ when(mockA11yConnection.asBinder()).thenReturn(mockConnectionBinder);
+ when(mockWindowToken.asBinder()).thenReturn(mockWindowBinder);
+ when(mMockA11ySecurityPolicy.isCallerInteractingAcrossUsers(userId))
+ .thenReturn(bGlobal);
+ when(mMockWindowManagerInternal.getDisplayIdForWindow(mockWindowBinder))
+ .thenReturn(displayId);
+
+ int windowId = mA11yWindowManager.addAccessibilityInteractionConnection(
+ mockWindowToken, mockLeashToken, mockA11yConnection, PACKAGE_NAME, userId);
+ mA11yWindowTokens.put(windowId, mockWindowToken);
+ return mockWindowToken;
+ }
+
+ private int addAccessibilityInteractionConnection(int displayId, boolean bGlobal,
+ IBinder leashToken, int userId) throws RemoteException {
+ final IWindow mockWindowToken = Mockito.mock(IWindow.class);
+ final IAccessibilityInteractionConnection mockA11yConnection = Mockito.mock(
+ IAccessibilityInteractionConnection.class);
+ final IBinder mockConnectionBinder = Mockito.mock(IBinder.class);
+ final IBinder mockWindowBinder = Mockito.mock(IBinder.class);
+ when(mockA11yConnection.asBinder()).thenReturn(mockConnectionBinder);
+ when(mockWindowToken.asBinder()).thenReturn(mockWindowBinder);
+ when(mMockA11ySecurityPolicy.isCallerInteractingAcrossUsers(userId))
+ .thenReturn(bGlobal);
+ when(mMockWindowManagerInternal.getDisplayIdForWindow(mockWindowBinder))
+ .thenReturn(displayId);
+
+ int windowId = mA11yWindowManager.addAccessibilityInteractionConnection(
+ mockWindowToken, leashToken, mockA11yConnection, PACKAGE_NAME, userId);
+ mA11yWindowTokens.put(windowId, mockWindowToken);
+ return windowId;
+ }
+
+ private void addWindowInfo(ArrayList<WindowInfo> windowInfos, IWindow windowToken, int layer) {
+ final WindowInfo windowInfo = WindowInfo.obtain();
+ windowInfo.type = AccessibilityWindowInfo.TYPE_APPLICATION;
+ windowInfo.token = windowToken.asBinder();
+ windowInfo.layer = layer;
+ windowInfo.regionInScreen.set(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
+ windowInfos.add(windowInfo);
+ }
+
+ private int getWindowIdFromWindowInfosForDisplay(int displayId, int index) {
+ final IBinder windowToken = mWindowInfos.get(displayId).get(index).token;
+ return mA11yWindowManager.findWindowIdLocked(
+ USER_SYSTEM_ID, windowToken);
+ }
+
+ private void setTopFocusedWindowAndDisplay(int displayId, int index) {
+ // Sets the top focus window.
+ mTopFocusedWindowToken = mWindowInfos.get(displayId).get(index).token;
+ // Sets the top focused display.
+ mTopFocusedDisplayId = displayId;
+ }
+
+ private void onWindowsForAccessibilityChanged(int displayId, boolean forceSend) {
+ WindowsForAccessibilityCallback callbacks = mCallbackOfWindows.get(displayId);
+ if (callbacks == null) {
+ callbacks = getWindowsForAccessibilityCallbacks(displayId);
+ mCallbackOfWindows.put(displayId, callbacks);
+ }
+ callbacks.onWindowsForAccessibilityChanged(forceSend, mTopFocusedDisplayId,
+ mTopFocusedWindowToken, mWindowInfos.get(displayId));
+ }
+
+ private void changeFocusedWindowOnDisplayPerDisplayFocusConfig(
+ int changeFocusedDisplayId, int newFocusedWindowIndex, int oldTopFocusedDisplayId,
+ int oldFocusedWindowIndex) {
+ if (mSupportPerDisplayFocus) {
+ // Gets the old focused window of display which wants to change focused window.
+ WindowInfo focusedWindowInfo =
+ mWindowInfos.get(changeFocusedDisplayId).get(oldFocusedWindowIndex);
+ // Resets the focus of old focused window.
+ focusedWindowInfo.focused = false;
+ // Gets the new window of display which wants to change focused window.
+ focusedWindowInfo =
+ mWindowInfos.get(changeFocusedDisplayId).get(newFocusedWindowIndex);
+ // Sets the focus of new focused window.
+ focusedWindowInfo.focused = true;
+ } else {
+ // Gets the window of display which wants to change focused window.
+ WindowInfo focusedWindowInfo =
+ mWindowInfos.get(changeFocusedDisplayId).get(newFocusedWindowIndex);
+ // Sets the focus of new focused window.
+ focusedWindowInfo.focused = true;
+ // Gets the old focused window of old top focused display.
+ focusedWindowInfo =
+ mWindowInfos.get(oldTopFocusedDisplayId).get(oldFocusedWindowIndex);
+ // Resets the focus of old focused window.
+ focusedWindowInfo.focused = false;
+ // Changes the top focused display and window.
+ setTopFocusedWindowAndDisplay(changeFocusedDisplayId, newFocusedWindowIndex);
+ }
+ }
+
+ @Nullable
+ private static String toString(@Nullable CharSequence cs) {
+ return cs == null ? null : cs.toString();
+ }
+
+ static class DisplayIdMatcher extends TypeSafeMatcher<AccessibilityEvent> {
+ private final int mDisplayId;
+
+ DisplayIdMatcher(int displayId) {
+ super();
+ mDisplayId = displayId;
+ }
+
+ static DisplayIdMatcher displayId(int displayId) {
+ return new DisplayIdMatcher(displayId);
+ }
+
+ @Override
+ protected boolean matchesSafely(AccessibilityEvent event) {
+ return event.getDisplayId() == mDisplayId;
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendText("Matching to displayId " + mDisplayId);
+ }
+ }
+
+ static class WindowIdMatcher extends TypeSafeMatcher<AccessibilityEvent> {
+ private int mWindowId;
+
+ WindowIdMatcher(int windowId) {
+ super();
+ mWindowId = windowId;
+ }
+
+ static WindowIdMatcher a11yWindowId(int windowId) {
+ return new WindowIdMatcher(windowId);
+ }
+
+ @Override
+ protected boolean matchesSafely(AccessibilityEvent event) {
+ return event.getWindowId() == mWindowId;
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendText("Matching to windowId " + mWindowId);
+ }
+ }
+
+ static class WindowChangesMatcher extends TypeSafeMatcher<AccessibilityEvent> {
+ private int mWindowChanges;
+
+ WindowChangesMatcher(int windowChanges) {
+ super();
+ mWindowChanges = windowChanges;
+ }
+
+ static WindowChangesMatcher a11yWindowChanges(int windowChanges) {
+ return new WindowChangesMatcher(windowChanges);
+ }
+
+ @Override
+ protected boolean matchesSafely(AccessibilityEvent event) {
+ return event.getWindowChanges() == mWindowChanges;
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendText("Matching to window changes " + mWindowChanges);
+ }
+ }
+}
diff --git a/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java
index 4c32a58..a0461a6 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java
@@ -42,6 +42,7 @@
import static org.junit.Assume.assumeTrue;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -541,7 +542,7 @@
}
@Test
- public void testUnhandledDragListenerNotCalledForNormalDrags() throws RemoteException {
+ public void testUnhandledDragNotCalledForNormalDrags() throws RemoteException {
assumeTrue(com.android.window.flags.Flags.delegateUnhandledDrags());
final IGlobalDragListener listener = mock(IGlobalDragListener.class);
@@ -552,15 +553,16 @@
}
@Test
- public void testUnhandledDragListenerReceivesUnhandledDropOverWindow() {
+ public void testUnhandledDragReceivesUnhandledDropOverWindow() {
assumeTrue(com.android.window.flags.Flags.delegateUnhandledDrags());
final IGlobalDragListener listener = mock(IGlobalDragListener.class);
doReturn(mock(Binder.class)).when(listener).asBinder();
mTarget.setGlobalDragListener(listener);
final int invalidXY = 100_000;
- startDrag(View.DRAG_FLAG_GLOBAL, ClipData.newPlainText("label", "Test"), () -> {
- // Notify the unhandled drag listener
+ startDrag(View.DRAG_FLAG_GLOBAL | View.DRAG_FLAG_START_INTENT_SENDER_ON_UNHANDLED_DRAG,
+ ClipData.newPlainText("label", "Test"), () -> {
+ // Trigger an unhandled drop and verify the global drag listener was called
mTarget.reportDropWindow(mWindow.mInputChannelToken, invalidXY, invalidXY);
mTarget.handleMotionEvent(false /* keepHandling */, invalidXY, invalidXY);
mTarget.reportDropResult(mWindow.mClient, false);
@@ -575,15 +577,16 @@
}
@Test
- public void testUnhandledDragListenerReceivesUnhandledDropOverNoValidWindow() {
+ public void testUnhandledDragReceivesUnhandledDropOverNoValidWindow() {
assumeTrue(com.android.window.flags.Flags.delegateUnhandledDrags());
final IGlobalDragListener listener = mock(IGlobalDragListener.class);
doReturn(mock(Binder.class)).when(listener).asBinder();
mTarget.setGlobalDragListener(listener);
final int invalidXY = 100_000;
- startDrag(View.DRAG_FLAG_GLOBAL, ClipData.newPlainText("label", "Test"), () -> {
- // Notify the unhandled drag listener
+ startDrag(View.DRAG_FLAG_GLOBAL | View.DRAG_FLAG_START_INTENT_SENDER_ON_UNHANDLED_DRAG,
+ ClipData.newPlainText("label", "Test"), () -> {
+ // Trigger an unhandled drop and verify the global drag listener was called
mTarget.reportDropWindow(mock(IBinder.class), invalidXY, invalidXY);
mTarget.handleMotionEvent(false /* keepHandling */, invalidXY, invalidXY);
mTarget.onUnhandledDropCallback(true);
@@ -597,15 +600,38 @@
}
@Test
- public void testUnhandledDragListenerCallbackTimeout() {
+ public void testUnhandledDragDoesNotReceiveUnhandledDropWithoutDragFlag() {
assumeTrue(com.android.window.flags.Flags.delegateUnhandledDrags());
final IGlobalDragListener listener = mock(IGlobalDragListener.class);
doReturn(mock(Binder.class)).when(listener).asBinder();
mTarget.setGlobalDragListener(listener);
final int invalidXY = 100_000;
- startDrag(View.DRAG_FLAG_GLOBAL, ClipData.newPlainText("label", "Test"), () -> {
- // Notify the unhandled drag listener
+ startDrag(View.DRAG_FLAG_GLOBAL,
+ ClipData.newPlainText("label", "Test"), () -> {
+ // Trigger an unhandled drop and verify the global drag listener was not called
+ mTarget.reportDropWindow(mock(IBinder.class), invalidXY, invalidXY);
+ mTarget.handleMotionEvent(false /* keepHandling */, invalidXY, invalidXY);
+ mToken = null;
+ try {
+ verify(listener, never()).onUnhandledDrop(any(), any());
+ } catch (RemoteException e) {
+ fail("Failed to verify unhandled drop: " + e);
+ }
+ });
+ }
+
+ @Test
+ public void testUnhandledDragCallbackTimeout() {
+ assumeTrue(com.android.window.flags.Flags.delegateUnhandledDrags());
+
+ final IGlobalDragListener listener = mock(IGlobalDragListener.class);
+ doReturn(mock(Binder.class)).when(listener).asBinder();
+ mTarget.setGlobalDragListener(listener);
+ final int invalidXY = 100_000;
+ startDrag(View.DRAG_FLAG_GLOBAL | View.DRAG_FLAG_START_INTENT_SENDER_ON_UNHANDLED_DRAG,
+ ClipData.newPlainText("label", "Test"), () -> {
+ // Trigger an unhandled drop and verify the global drag listener was called
mTarget.reportDropWindow(mock(IBinder.class), invalidXY, invalidXY);
mTarget.handleMotionEvent(false /* keepHandling */, invalidXY, invalidXY);
diff --git a/tests/CtsSurfaceControlTestsStaging/src/main/java/android/view/surfacecontroltests/GraphicsActivity.java b/tests/CtsSurfaceControlTestsStaging/src/main/java/android/view/surfacecontroltests/GraphicsActivity.java
index 217659e..700856c 100644
--- a/tests/CtsSurfaceControlTestsStaging/src/main/java/android/view/surfacecontroltests/GraphicsActivity.java
+++ b/tests/CtsSurfaceControlTestsStaging/src/main/java/android/view/surfacecontroltests/GraphicsActivity.java
@@ -726,7 +726,7 @@
.map(Object::toString)
.collect(Collectors.joining(", ")));
int initialNumEvents = mModeChangedEvents.size();
- surface.setFrameRate(30.f, compatibility);
+ surface.setFrameRate(70.f, compatibility);
verifyFrameRates(expectedFrameRates, surface);
verifyModeSwitchesDontChangeResolution(initialNumEvents, mModeChangedEvents.size());
});
@@ -824,7 +824,7 @@
Display display = getDisplay();
List<Float> expectedFrameRates = getRefreshRates(display.getMode(), display)
.stream()
- .filter(rate -> rate >= 30.f)
+ .filter(rate -> rate >= 70.f)
.collect(Collectors.toList());
assumeTrue("**** testSurfaceControlFrameRateCompatibility SKIPPED because no refresh rate "