Merge "MediaController2: Revisit Javadoc of onPlaybackActiveChanged"
diff --git a/Android.bp b/Android.bp
index 7bdedc7..183121b 100644
--- a/Android.bp
+++ b/Android.bp
@@ -602,6 +602,7 @@
"telephony/java/com/android/internal/telephony/IOnSubscriptionsChangedListener.aidl",
"telephony/java/com/android/internal/telephony/IPhoneStateListener.aidl",
"telephony/java/com/android/internal/telephony/IPhoneSubInfo.aidl",
+ "telephony/java/com/android/internal/telephony/ISetOpportunisticDataCallback.aidl",
"telephony/java/com/android/internal/telephony/ISms.aidl",
"telephony/java/com/android/internal/telephony/ISub.aidl",
"telephony/java/com/android/internal/telephony/IOns.aidl",
@@ -741,10 +742,8 @@
static_libs: [
"apex_aidl_interface-java",
- "networkstack-aidl-interfaces-java",
"framework-protos",
"game-driver-protos",
- "mediaplayer2-protos",
"android.hidl.base-V1.0-java",
"android.hardware.cas-V1.1-java",
"android.hardware.cas-V1.0-java",
@@ -804,6 +803,7 @@
srcs: [
"core/java/android/os/IStatsCompanionService.aidl",
"core/java/android/os/IStatsManager.aidl",
+ "core/java/android/os/IStatsPullerCallback.aidl",
],
}
@@ -1187,58 +1187,12 @@
"org/apache/http/params",
]
-// The since flag (-since N.xml API_LEVEL) is used to add API Level information
-// to the reference documentation. Must be in order of oldest to newest.
-//
-// Conscrypt (com.android.org.conscrypt) is an implementation detail and should
-// not be referenced in the documentation.
-framework_docs_args = "-android -manifest $(location core/res/AndroidManifest.xml) " +
- "-hidePackage com.android.internal " +
- "-hidePackage com.android.internal.util " +
- "-hidePackage com.android.okhttp " +
- "-hidePackage com.android.org.conscrypt " +
- "-hidePackage com.android.server " +
- "-since $(location 1/public/api/android.xml) 1 " +
- "-since $(location 2/public/api/android.xml) 2 " +
- "-since $(location 3/public/api/android.xml) 3 " +
- "-since $(location 4/public/api/android.xml) 4 " +
- "-since $(location 5/public/api/android.xml) 5 " +
- "-since $(location 6/public/api/android.xml) 6 " +
- "-since $(location 7/public/api/android.xml) 7 " +
- "-since $(location 8/public/api/android.xml) 8 " +
- "-since $(location 9/public/api/android.xml) 9 " +
- "-since $(location 10/public/api/android.xml) 10 " +
- "-since $(location 11/public/api/android.xml) 11 " +
- "-since $(location 12/public/api/android.xml) 12 " +
- "-since $(location 13/public/api/android.xml) 13 " +
- "-since $(location 14/public/api/android.txt) 14 " +
- "-since $(location 15/public/api/android.txt) 15 " +
- "-since $(location 16/public/api/android.txt) 16 " +
- "-since $(location 17/public/api/android.txt) 17 " +
- "-since $(location 18/public/api/android.txt) 18 " +
- "-since $(location 19/public/api/android.txt) 19 " +
- "-since $(location 20/public/api/android.txt) 20 " +
- "-since $(location 21/public/api/android.txt) 21 " +
- "-since $(location 22/public/api/android.txt) 22 " +
- "-since $(location 23/public/api/android.txt) 23 " +
- "-since $(location 24/public/api/android.txt) 24 " +
- "-since $(location 25/public/api/android.txt) 25 " +
- "-since $(location 26/public/api/android.txt) 26 " +
- "-since $(location 27/public/api/android.txt) 27 " +
- "-since $(location 28/public/api/android.txt) 28 " +
- "-since $(location api/current.txt) Q " +
- "-werror -lerror -hide 111 -hide 113 -hide 125 -hide 126 -hide 127 -hide 128 " +
- "-overview $(location core/java/overview.html) " +
- // Federate Support Library references against local API file.
- "-federate SupportLib https://developer.android.com " +
- "-federationapi SupportLib $(location current/support-api.txt) "
-
framework_docs_only_args = " -android -manifest $(location core/res/AndroidManifest.xml) " +
"-werror -lerror -hide 111 -hide 113 -hide 125 -hide 126 -hide 127 -hide 128 " +
"-overview $(location core/java/overview.html) " +
// Federate Support Library references against local API file.
"-federate SupportLib https://developer.android.com " +
- "-federationapi SupportLib $(location current/support-api.txt) "
+ "-federationapi SupportLib $(location :current-support-api) "
framework_docs_only_libs = [
"voip-common",
diff --git a/Android.mk b/Android.mk
index 9c65948..9a91dd1 100644
--- a/Android.mk
+++ b/Android.mk
@@ -72,6 +72,9 @@
$(hide) mkdir -p $(OUT_DOCS)/offline-sdk
( unzip -qo $< -d $(OUT_DOCS)/offline-sdk && touch -f $@ ) || exit 1
+.PHONY: docs offline-sdk-docs
+docs offline-sdk-docs: $(OUT_DOCS)/offline-sdk-timestamp
+
# Run this for checkbuild
checkbuild: doc-comment-check-docs
# Check comment when you are updating the API
diff --git a/apct-tests/perftests/core/src/android/os/KernelCpuThreadReaderPerfTest.java b/apct-tests/perftests/core/src/android/os/KernelCpuThreadReaderPerfTest.java
index 9234849..0c30302 100644
--- a/apct-tests/perftests/core/src/android/os/KernelCpuThreadReaderPerfTest.java
+++ b/apct-tests/perftests/core/src/android/os/KernelCpuThreadReaderPerfTest.java
@@ -40,7 +40,7 @@
public final PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
private final KernelCpuThreadReader mKernelCpuThreadReader =
- KernelCpuThreadReader.create(8, uid -> 1000 <= uid && uid < 2000);
+ KernelCpuThreadReader.create(8, uid -> 1000 <= uid && uid < 2000, 0);
@Test
public void timeReadCurrentProcessCpuUsage() {
diff --git a/apct-tests/perftests/core/src/android/textclassifier/TextClassifierPerfTest.java b/apct-tests/perftests/core/src/android/textclassifier/TextClassifierPerfTest.java
index ec46a75..c506aec6 100644
--- a/apct-tests/perftests/core/src/android/textclassifier/TextClassifierPerfTest.java
+++ b/apct-tests/perftests/core/src/android/textclassifier/TextClassifierPerfTest.java
@@ -64,7 +64,7 @@
Context context = InstrumentationRegistry.getTargetContext();
TextClassificationManager textClassificationManager =
context.getSystemService(TextClassificationManager.class);
- mTextClassifier = textClassificationManager.getTextClassifier();
+ mTextClassifier = textClassificationManager.getLocalTextClassifier();
}
@Test
diff --git a/api/current.txt b/api/current.txt
index c0d10a6..5da83c1 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -80,7 +80,6 @@
field public static final String FOREGROUND_SERVICE = "android.permission.FOREGROUND_SERVICE";
field public static final String GET_ACCOUNTS = "android.permission.GET_ACCOUNTS";
field public static final String GET_ACCOUNTS_PRIVILEGED = "android.permission.GET_ACCOUNTS_PRIVILEGED";
- field public static final String GET_AND_REQUEST_SCREEN_LOCK_COMPLEXITY = "android.permission.GET_AND_REQUEST_SCREEN_LOCK_COMPLEXITY";
field public static final String GET_PACKAGE_SIZE = "android.permission.GET_PACKAGE_SIZE";
field @Deprecated public static final String GET_TASKS = "android.permission.GET_TASKS";
field public static final String GLOBAL_SEARCH = "android.permission.GLOBAL_SEARCH";
@@ -131,6 +130,7 @@
field public static final String REQUEST_DELETE_PACKAGES = "android.permission.REQUEST_DELETE_PACKAGES";
field public static final String REQUEST_IGNORE_BATTERY_OPTIMIZATIONS = "android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS";
field public static final String REQUEST_INSTALL_PACKAGES = "android.permission.REQUEST_INSTALL_PACKAGES";
+ field public static final String REQUEST_SCREEN_LOCK_COMPLEXITY = "android.permission.REQUEST_SCREEN_LOCK_COMPLEXITY";
field @Deprecated public static final String RESTART_PACKAGES = "android.permission.RESTART_PACKAGES";
field public static final String SEND_RESPOND_VIA_MESSAGE = "android.permission.SEND_RESPOND_VIA_MESSAGE";
field public static final String SEND_SMS = "android.permission.SEND_SMS";
@@ -6646,7 +6646,7 @@
method @Nullable public CharSequence getOrganizationName(@NonNull android.content.ComponentName);
method public java.util.List<android.telephony.data.ApnSetting> getOverrideApns(@NonNull android.content.ComponentName);
method @NonNull public android.app.admin.DevicePolicyManager getParentProfileInstance(@NonNull android.content.ComponentName);
- method @RequiresPermission(android.Manifest.permission.GET_AND_REQUEST_SCREEN_LOCK_COMPLEXITY) public int getPasswordComplexity();
+ method @RequiresPermission(android.Manifest.permission.REQUEST_SCREEN_LOCK_COMPLEXITY) public int getPasswordComplexity();
method public long getPasswordExpiration(@Nullable android.content.ComponentName);
method public long getPasswordExpirationTimeout(@Nullable android.content.ComponentName);
method public int getPasswordHistoryLength(@Nullable android.content.ComponentName);
@@ -6684,7 +6684,7 @@
method public boolean installKeyPair(@Nullable android.content.ComponentName, @NonNull java.security.PrivateKey, @NonNull java.security.cert.Certificate, @NonNull String);
method public boolean installKeyPair(@Nullable android.content.ComponentName, @NonNull java.security.PrivateKey, @NonNull java.security.cert.Certificate[], @NonNull String, boolean);
method public boolean installKeyPair(@Nullable android.content.ComponentName, @NonNull java.security.PrivateKey, @NonNull java.security.cert.Certificate[], @NonNull String, int);
- method public void installSystemUpdate(@NonNull android.content.ComponentName, @NonNull android.net.Uri, @NonNull java.util.concurrent.Executor, @NonNull android.app.admin.DevicePolicyManager.InstallUpdateCallback);
+ method public void installSystemUpdate(@NonNull android.content.ComponentName, @NonNull android.net.Uri, @NonNull java.util.concurrent.Executor, @NonNull android.app.admin.DevicePolicyManager.InstallSystemUpdateCallback);
method public boolean isActivePasswordSufficient();
method public boolean isAdminActive(@NonNull android.content.ComponentName);
method public boolean isAffiliatedUser();
@@ -6840,7 +6840,7 @@
field public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION";
field public static final String EXTRA_DELEGATION_SCOPES = "android.app.extra.DELEGATION_SCOPES";
field public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN";
- field @RequiresPermission(android.Manifest.permission.GET_AND_REQUEST_SCREEN_LOCK_COMPLEXITY) public static final String EXTRA_PASSWORD_COMPLEXITY = "android.app.extra.PASSWORD_COMPLEXITY";
+ field @RequiresPermission(android.Manifest.permission.REQUEST_SCREEN_LOCK_COMPLEXITY) public static final String EXTRA_PASSWORD_COMPLEXITY = "android.app.extra.PASSWORD_COMPLEXITY";
field public static final String EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE = "android.app.extra.PROVISIONING_ACCOUNT_TO_MIGRATE";
field public static final String EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE = "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE";
field public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME";
@@ -6951,8 +6951,8 @@
field public static final int WIPE_SILENTLY = 8; // 0x8
}
- public abstract static class DevicePolicyManager.InstallUpdateCallback {
- ctor public DevicePolicyManager.InstallUpdateCallback();
+ public abstract static class DevicePolicyManager.InstallSystemUpdateCallback {
+ ctor public DevicePolicyManager.InstallSystemUpdateCallback();
method public void onInstallUpdateError(int, String);
field public static final int UPDATE_ERROR_BATTERY_LOW = 5; // 0x5
field public static final int UPDATE_ERROR_FILE_NOT_FOUND = 4; // 0x4
@@ -9517,7 +9517,6 @@
method public static void cancelSync(android.content.SyncRequest);
method @Nullable public final android.net.Uri canonicalize(@NonNull android.net.Uri);
method public final int delete(@RequiresPermission.Write @NonNull android.net.Uri, @Nullable String, @Nullable String[]);
- method public android.os.Bundle getCache(android.net.Uri);
method @Deprecated public static android.content.SyncInfo getCurrentSync();
method public static java.util.List<android.content.SyncInfo> getCurrentSyncs();
method public static int getIsSyncable(android.accounts.Account, String);
@@ -9548,7 +9547,6 @@
method @Nullable public final android.content.res.AssetFileDescriptor openTypedAssetFile(@NonNull android.net.Uri, @NonNull String, @Nullable android.os.Bundle, @Nullable android.os.CancellationSignal) throws java.io.FileNotFoundException;
method @Nullable public final android.content.res.AssetFileDescriptor openTypedAssetFileDescriptor(@NonNull android.net.Uri, @NonNull String, @Nullable android.os.Bundle) throws java.io.FileNotFoundException;
method @Nullable public final android.content.res.AssetFileDescriptor openTypedAssetFileDescriptor(@NonNull android.net.Uri, @NonNull String, @Nullable android.os.Bundle, @Nullable android.os.CancellationSignal) throws java.io.FileNotFoundException;
- method public void putCache(android.net.Uri, android.os.Bundle);
method @Nullable public final android.database.Cursor query(@RequiresPermission.Read @NonNull android.net.Uri, @Nullable String[], @Nullable String, @Nullable String[], @Nullable String);
method @Nullable public final android.database.Cursor query(@RequiresPermission.Read @NonNull android.net.Uri, @Nullable String[], @Nullable String, @Nullable String[], @Nullable String, @Nullable android.os.CancellationSignal);
method @Nullable public final android.database.Cursor query(@RequiresPermission.Read @NonNull android.net.Uri, @Nullable String[], @Nullable android.os.Bundle, @Nullable android.os.CancellationSignal);
@@ -11482,7 +11480,6 @@
method public void setOriginatingUri(@Nullable android.net.Uri);
method public void setReferrerUri(@Nullable android.net.Uri);
method public void setSize(long);
- method public void setStaged();
method public void writeToParcel(android.os.Parcel, int);
field public static final android.os.Parcelable.Creator<android.content.pm.PackageInstaller.SessionParams> CREATOR;
field public static final int MODE_FULL_INSTALL = 1; // 0x1
@@ -15409,28 +15406,38 @@
method public float getGradientCenterY();
method public float getGradientRadius();
method public int getGradientType();
+ method public int getInnerRadius();
+ method public float getInnerRadiusRatio();
method public int getOpacity();
method public android.graphics.drawable.GradientDrawable.Orientation getOrientation();
method public int getShape();
+ method public int getThickness();
+ method public float getThicknessRatio();
method public boolean getUseLevel();
method public void setAlpha(int);
method public void setColor(@ColorInt int);
method public void setColor(@Nullable android.content.res.ColorStateList);
method public void setColorFilter(@Nullable android.graphics.ColorFilter);
method public void setColors(@ColorInt int[]);
+ method public void setColors(@ColorInt int[], @Nullable float[]);
method public void setCornerRadii(@Nullable float[]);
method public void setCornerRadius(float);
method public void setDither(boolean);
method public void setGradientCenter(float, float);
method public void setGradientRadius(float);
method public void setGradientType(int);
+ method public void setInnerRadius(int);
+ method public void setInnerRadiusRatio(float);
method public void setOrientation(android.graphics.drawable.GradientDrawable.Orientation);
+ method public void setPadding(int, int, int, int);
method public void setShape(int);
method public void setSize(int, int);
method public void setStroke(int, @ColorInt int);
method public void setStroke(int, android.content.res.ColorStateList);
method public void setStroke(int, @ColorInt int, float, float);
method public void setStroke(int, android.content.res.ColorStateList, float, float);
+ method public void setThickness(int);
+ method public void setThicknessRatio(float);
method public void setUseLevel(boolean);
field public static final int LINE = 2; // 0x2
field public static final int LINEAR_GRADIENT = 0; // 0x0
@@ -22667,6 +22674,7 @@
field public static final int MULTIPATH_INDICATOR_DETECTED = 1; // 0x1
field public static final int MULTIPATH_INDICATOR_NOT_DETECTED = 2; // 0x2
field public static final int MULTIPATH_INDICATOR_UNKNOWN = 0; // 0x0
+ field public static final int STATE_2ND_CODE_LOCK = 65536; // 0x10000
field public static final int STATE_BDS_D2_BIT_SYNC = 256; // 0x100
field public static final int STATE_BDS_D2_SUBFRAME_SYNC = 512; // 0x200
field public static final int STATE_BIT_SYNC = 2; // 0x2
@@ -30111,10 +30119,14 @@
method public void onIdentityChanged(byte[]);
}
- public final class PeerHandle implements android.os.Parcelable {
+ public final class ParcelablePeerHandle extends android.net.wifi.aware.PeerHandle implements android.os.Parcelable {
+ ctor public ParcelablePeerHandle(android.net.wifi.aware.PeerHandle);
method public int describeContents();
method public void writeToParcel(android.os.Parcel, int);
- field public static final android.os.Parcelable.Creator<android.net.wifi.aware.PeerHandle> CREATOR;
+ field public static final android.os.Parcelable.Creator<android.net.wifi.aware.ParcelablePeerHandle> CREATOR;
+ }
+
+ public class PeerHandle {
}
public final class PublishConfig implements android.os.Parcelable {
@@ -44369,6 +44381,7 @@
method public int getChannelNumber();
method public String getMccString();
method public String getMncString();
+ method public long getNci();
method public int getPci();
method public int getTac();
method public void writeToParcel(android.os.Parcel, int);
@@ -44382,6 +44395,7 @@
method public String getMccString();
method public String getMncString();
method @Nullable public String getMobileNetworkOperator();
+ method public int getUarfcn();
method public void writeToParcel(android.os.Parcel, int);
field public static final android.os.Parcelable.Creator<android.telephony.CellIdentityTdscdma> CREATOR;
}
@@ -45056,12 +45070,12 @@
method public boolean canChangeDtmfToneLength();
method @Nullable public android.telephony.TelephonyManager createForPhoneAccountHandle(android.telecom.PhoneAccountHandle);
method public android.telephony.TelephonyManager createForSubscriptionId(int);
- method @RequiresPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) public java.util.List<android.telephony.CellInfo> getAllCellInfo();
+ method @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) public java.util.List<android.telephony.CellInfo> getAllCellInfo();
method public int getCallState();
method public int getCardIdForDefaultEuicc();
method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) @WorkerThread public android.os.PersistableBundle getCarrierConfig();
method public int getCarrierIdFromSimMccMnc();
- method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public android.telephony.CellLocation getCellLocation();
+ method @Deprecated @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) public android.telephony.CellLocation getCellLocation();
method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) @Nullable public java.util.Map<java.lang.Integer,java.util.List<android.telephony.emergency.EmergencyNumber>> getCurrentEmergencyNumberList();
method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) @Nullable public java.util.Map<java.lang.Integer,java.util.List<android.telephony.emergency.EmergencyNumber>> getCurrentEmergencyNumberList(int);
method public int getDataActivity();
@@ -45091,7 +45105,7 @@
method public int getPhoneCount();
method public int getPhoneType();
method @RequiresPermission(anyOf={"android.permission.READ_PRIVILEGED_PHONE_STATE", android.Manifest.permission.READ_PHONE_STATE}) public int getPreferredOpportunisticDataSubscription();
- method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public android.telephony.ServiceState getServiceState();
+ method @RequiresPermission(allOf={android.Manifest.permission.READ_PHONE_STATE, android.Manifest.permission.ACCESS_COARSE_LOCATION}) public android.telephony.ServiceState getServiceState();
method @Nullable public android.telephony.SignalStrength getSignalStrength();
method public int getSimCarrierId();
method @Nullable public CharSequence getSimCarrierIdName();
@@ -45133,8 +45147,8 @@
method public boolean isVoicemailVibrationEnabled(android.telecom.PhoneAccountHandle);
method public boolean isWorldPhone();
method public void listen(android.telephony.PhoneStateListener, int);
- method @RequiresPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) public void requestCellInfoUpdate(@NonNull java.util.concurrent.Executor, @NonNull android.telephony.TelephonyManager.CellInfoCallback);
- method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public android.telephony.NetworkScan requestNetworkScan(android.telephony.NetworkScanRequest, java.util.concurrent.Executor, android.telephony.TelephonyScanManager.NetworkScanCallback);
+ method @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) public void requestCellInfoUpdate(@NonNull java.util.concurrent.Executor, @NonNull android.telephony.TelephonyManager.CellInfoCallback);
+ method @RequiresPermission(allOf={android.Manifest.permission.MODIFY_PHONE_STATE, android.Manifest.permission.ACCESS_FINE_LOCATION}) public android.telephony.NetworkScan requestNetworkScan(android.telephony.NetworkScanRequest, java.util.concurrent.Executor, android.telephony.TelephonyScanManager.NetworkScanCallback);
method public void sendDialerSpecialCode(String);
method public String sendEnvelopeWithStatus(String);
method @RequiresPermission(android.Manifest.permission.CALL_PHONE) public void sendUssdRequest(String, android.telephony.TelephonyManager.UssdResponseCallback, android.os.Handler);
@@ -45203,7 +45217,6 @@
field public static final String EXTRA_STATE_RINGING;
field public static final String EXTRA_SUBSCRIPTION_ID = "android.telephony.extra.SUBSCRIPTION_ID";
field public static final String EXTRA_VOICEMAIL_NUMBER = "android.telephony.extra.VOICEMAIL_NUMBER";
- field public static final int INVALID_CARD_ID = -1; // 0xffffffff
field public static final String METADATA_HIDE_VOICEMAIL_SETTINGS_MENU = "android.telephony.HIDE_VOICEMAIL_SETTINGS_MENU";
field public static final int NETWORK_TYPE_1xRTT = 7; // 0x7
field public static final int NETWORK_TYPE_CDMA = 4; // 0x4
@@ -45229,6 +45242,9 @@
field public static final int PHONE_TYPE_GSM = 1; // 0x1
field public static final int PHONE_TYPE_NONE = 0; // 0x0
field public static final int PHONE_TYPE_SIP = 3; // 0x3
+ field public static final int SET_OPPORTUNISTIC_SUB_INVALID_PARAMETER = 2; // 0x2
+ field public static final int SET_OPPORTUNISTIC_SUB_SUCCESS = 0; // 0x0
+ field public static final int SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED = 1; // 0x1
field public static final int SIM_STATE_ABSENT = 1; // 0x1
field public static final int SIM_STATE_CARD_IO_ERROR = 8; // 0x8
field public static final int SIM_STATE_CARD_RESTRICTED = 9; // 0x9
@@ -45239,7 +45255,9 @@
field public static final int SIM_STATE_PUK_REQUIRED = 3; // 0x3
field public static final int SIM_STATE_READY = 5; // 0x5
field public static final int SIM_STATE_UNKNOWN = 0; // 0x0
+ field public static final int UNINITIALIZED_CARD_ID = -2; // 0xfffffffe
field public static final int UNKNOWN_CARRIER_ID = -1; // 0xffffffff
+ field public static final int UNSUPPORTED_CARD_ID = -1; // 0xffffffff
field public static final int USSD_ERROR_SERVICE_UNAVAIL = -2; // 0xfffffffe
field public static final int USSD_RETURN_FAILURE = -1; // 0xffffffff
field public static final String VVM_TYPE_CVVM = "vvm_type_cvvm";
@@ -45593,6 +45611,483 @@
}
+package android.telephony.ims {
+
+ public class Rcs1To1Thread extends android.telephony.ims.RcsThread {
+ method @WorkerThread public long getFallbackThreadId() throws android.telephony.ims.RcsMessageStoreException;
+ method @NonNull @WorkerThread public android.telephony.ims.RcsParticipant getRecipient() throws android.telephony.ims.RcsMessageStoreException;
+ method public boolean isGroup();
+ method @WorkerThread public void setFallbackThreadId(long) throws android.telephony.ims.RcsMessageStoreException;
+ }
+
+ public abstract class RcsEvent {
+ ctor protected RcsEvent(long);
+ method public long getTimestamp();
+ }
+
+ public final class RcsEventQueryParams implements android.os.Parcelable {
+ method public int describeContents();
+ method @android.telephony.ims.RcsEventQueryParams.EventType public int getEventType();
+ method public int getLimit();
+ method public boolean getSortDirection();
+ method public int getSortingProperty();
+ method public void writeToParcel(android.os.Parcel, int);
+ field public static final int ALL_EVENTS = -1; // 0xffffffff
+ field public static final int ALL_GROUP_THREAD_EVENTS = 0; // 0x0
+ field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsEventQueryParams> CREATOR;
+ field public static final int GROUP_THREAD_ICON_CHANGED_EVENT = 8; // 0x8
+ field public static final int GROUP_THREAD_NAME_CHANGED_EVENT = 16; // 0x10
+ field public static final int GROUP_THREAD_PARTICIPANT_JOINED_EVENT = 2; // 0x2
+ field public static final int GROUP_THREAD_PARTICIPANT_LEFT_EVENT = 4; // 0x4
+ field public static final int PARTICIPANT_ALIAS_CHANGED_EVENT = 1; // 0x1
+ field public static final int SORT_BY_CREATION_ORDER = 0; // 0x0
+ field public static final int SORT_BY_TIMESTAMP = 1; // 0x1
+ }
+
+ public static class RcsEventQueryParams.Builder {
+ ctor public RcsEventQueryParams.Builder();
+ method public android.telephony.ims.RcsEventQueryParams build();
+ method @CheckResult public android.telephony.ims.RcsEventQueryParams.Builder setEventType(@android.telephony.ims.RcsEventQueryParams.EventType int);
+ method @CheckResult public android.telephony.ims.RcsEventQueryParams.Builder setGroupThread(@NonNull android.telephony.ims.RcsGroupThread);
+ method @CheckResult public android.telephony.ims.RcsEventQueryParams.Builder setResultLimit(@IntRange(from=0) int) throws java.security.InvalidParameterException;
+ method @CheckResult public android.telephony.ims.RcsEventQueryParams.Builder setSortDirection(boolean);
+ method @CheckResult public android.telephony.ims.RcsEventQueryParams.Builder setSortProperty(@android.telephony.ims.RcsEventQueryParams.SortingProperty int);
+ }
+
+ @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @IntDef({android.telephony.ims.RcsEventQueryParams.ALL_EVENTS, android.telephony.ims.RcsEventQueryParams.ALL_GROUP_THREAD_EVENTS, android.telephony.ims.RcsEventQueryParams.PARTICIPANT_ALIAS_CHANGED_EVENT, android.telephony.ims.RcsEventQueryParams.GROUP_THREAD_PARTICIPANT_JOINED_EVENT, android.telephony.ims.RcsEventQueryParams.GROUP_THREAD_PARTICIPANT_LEFT_EVENT, android.telephony.ims.RcsEventQueryParams.GROUP_THREAD_NAME_CHANGED_EVENT, android.telephony.ims.RcsEventQueryParams.GROUP_THREAD_ICON_CHANGED_EVENT}) public static @interface RcsEventQueryParams.EventType {
+ }
+
+ @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @IntDef({android.telephony.ims.RcsEventQueryParams.SORT_BY_CREATION_ORDER, android.telephony.ims.RcsEventQueryParams.SORT_BY_TIMESTAMP}) public static @interface RcsEventQueryParams.SortingProperty {
+ }
+
+ public final class RcsEventQueryResult implements android.os.Parcelable {
+ method public int describeContents();
+ method public android.telephony.ims.RcsQueryContinuationToken getContinuationToken();
+ method public java.util.List<android.telephony.ims.RcsEvent> getEvents();
+ method public void writeToParcel(android.os.Parcel, int);
+ field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsEventQueryResult> CREATOR;
+ }
+
+ public final class RcsFileTransferCreationParams implements android.os.Parcelable {
+ method public int describeContents();
+ method public String getContentMimeType();
+ method public android.net.Uri getContentUri();
+ method public long getFileSize();
+ method @android.telephony.ims.RcsFileTransferPart.RcsFileTransferStatus public int getFileTransferStatus();
+ method public int getHeight();
+ method public long getMediaDuration();
+ method public String getPreviewMimeType();
+ method public android.net.Uri getPreviewUri();
+ method public String getRcsFileTransferSessionId();
+ method public long getTransferOffset();
+ method public int getWidth();
+ method public void writeToParcel(android.os.Parcel, int);
+ field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsFileTransferCreationParams> CREATOR;
+ }
+
+ public class RcsFileTransferCreationParams.Builder {
+ ctor public RcsFileTransferCreationParams.Builder();
+ method public android.telephony.ims.RcsFileTransferCreationParams build();
+ method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setContentMimeType(String);
+ method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setContentUri(android.net.Uri);
+ method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setFileSize(long);
+ method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setFileTransferSessionId(String);
+ method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setFileTransferStatus(@android.telephony.ims.RcsFileTransferPart.RcsFileTransferStatus int);
+ method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setHeight(int);
+ method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setMediaDuration(long);
+ method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setPreviewMimeType(String);
+ method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setPreviewUri(android.net.Uri);
+ method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setTransferOffset(long);
+ method @CheckResult public android.telephony.ims.RcsFileTransferCreationParams.Builder setWidth(int);
+ }
+
+ public class RcsFileTransferPart {
+ method @WorkerThread @Nullable public String getContentMimeType() throws android.telephony.ims.RcsMessageStoreException;
+ method @Nullable @WorkerThread public android.net.Uri getContentUri() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public long getFileSize() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public String getFileTransferSessionId() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread @android.telephony.ims.RcsFileTransferPart.RcsFileTransferStatus public int getFileTransferStatus() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public int getHeight() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public long getLength() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public String getPreviewMimeType() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public android.net.Uri getPreviewUri() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public long getTransferOffset() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public int getWidth() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setContentMimeType(String) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setContentUri(android.net.Uri) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setFileSize(long) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setFileTransferSessionId(String) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setFileTransferStatus(@android.telephony.ims.RcsFileTransferPart.RcsFileTransferStatus int) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setHeight(int) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setLength(long) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setPreviewMimeType(String) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setPreviewUri(android.net.Uri) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setTransferOffset(long) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setWidth(int) throws android.telephony.ims.RcsMessageStoreException;
+ field public static final int DOWNLOADING = 6; // 0x6
+ field public static final int DOWNLOADING_CANCELLED = 9; // 0x9
+ field public static final int DOWNLOADING_FAILED = 8; // 0x8
+ field public static final int DOWNLOADING_PAUSED = 7; // 0x7
+ field public static final int DRAFT = 1; // 0x1
+ field public static final int NOT_SET = 0; // 0x0
+ field public static final int SENDING = 2; // 0x2
+ field public static final int SENDING_CANCELLED = 5; // 0x5
+ field public static final int SENDING_FAILED = 4; // 0x4
+ field public static final int SENDING_PAUSED = 3; // 0x3
+ field public static final int SUCCEEDED = 10; // 0xa
+ }
+
+ @IntDef({android.telephony.ims.RcsFileTransferPart.DRAFT, android.telephony.ims.RcsFileTransferPart.SENDING, android.telephony.ims.RcsFileTransferPart.SENDING_PAUSED, android.telephony.ims.RcsFileTransferPart.SENDING_FAILED, android.telephony.ims.RcsFileTransferPart.SENDING_CANCELLED, android.telephony.ims.RcsFileTransferPart.DOWNLOADING, android.telephony.ims.RcsFileTransferPart.DOWNLOADING_PAUSED, android.telephony.ims.RcsFileTransferPart.DOWNLOADING_FAILED, android.telephony.ims.RcsFileTransferPart.DOWNLOADING_CANCELLED, android.telephony.ims.RcsFileTransferPart.SUCCEEDED}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface RcsFileTransferPart.RcsFileTransferStatus {
+ }
+
+ public class RcsGroupThread extends android.telephony.ims.RcsThread {
+ method @WorkerThread public void addParticipant(@NonNull android.telephony.ims.RcsParticipant) throws android.telephony.ims.RcsMessageStoreException;
+ method @Nullable @WorkerThread public android.net.Uri getConferenceUri() throws android.telephony.ims.RcsMessageStoreException;
+ method @Nullable public android.net.Uri getGroupIcon() throws android.telephony.ims.RcsMessageStoreException;
+ method @Nullable @WorkerThread public String getGroupName() throws android.telephony.ims.RcsMessageStoreException;
+ method @Nullable @WorkerThread public android.telephony.ims.RcsParticipant getOwner() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread @NonNull public java.util.Set<android.telephony.ims.RcsParticipant> getParticipants() throws android.telephony.ims.RcsMessageStoreException;
+ method public boolean isGroup();
+ method @WorkerThread public void removeParticipant(@NonNull android.telephony.ims.RcsParticipant) throws android.telephony.ims.RcsMessageStoreException;
+ method @Nullable @WorkerThread public void setConferenceUri(android.net.Uri) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setGroupIcon(@Nullable android.net.Uri) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setGroupName(String) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setOwner(@Nullable android.telephony.ims.RcsParticipant) throws android.telephony.ims.RcsMessageStoreException;
+ }
+
+ public abstract class RcsGroupThreadEvent extends android.telephony.ims.RcsEvent {
+ method @NonNull public android.telephony.ims.RcsParticipant getOriginatingParticipant();
+ method @NonNull public android.telephony.ims.RcsGroupThread getRcsGroupThread();
+ }
+
+ public final class RcsGroupThreadIconChangedEvent extends android.telephony.ims.RcsGroupThreadEvent implements android.os.Parcelable {
+ ctor public RcsGroupThreadIconChangedEvent(long, @NonNull android.telephony.ims.RcsGroupThread, @NonNull android.telephony.ims.RcsParticipant, @Nullable android.net.Uri);
+ method public int describeContents();
+ method @Nullable public android.net.Uri getNewIcon();
+ method public void writeToParcel(android.os.Parcel, int);
+ field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsGroupThreadIconChangedEvent> CREATOR;
+ }
+
+ public final class RcsGroupThreadNameChangedEvent extends android.telephony.ims.RcsGroupThreadEvent implements android.os.Parcelable {
+ ctor public RcsGroupThreadNameChangedEvent(long, @NonNull android.telephony.ims.RcsGroupThread, @NonNull android.telephony.ims.RcsParticipant, @Nullable String);
+ method public int describeContents();
+ method @Nullable public String getNewName();
+ method public void writeToParcel(android.os.Parcel, int);
+ field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsGroupThreadNameChangedEvent> CREATOR;
+ }
+
+ public final class RcsGroupThreadParticipantJoinedEvent extends android.telephony.ims.RcsGroupThreadEvent implements android.os.Parcelable {
+ ctor public RcsGroupThreadParticipantJoinedEvent(long, @NonNull android.telephony.ims.RcsGroupThread, @NonNull android.telephony.ims.RcsParticipant, @NonNull android.telephony.ims.RcsParticipant);
+ method public int describeContents();
+ method public android.telephony.ims.RcsParticipant getJoinedParticipant();
+ method public void writeToParcel(android.os.Parcel, int);
+ field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsGroupThreadParticipantJoinedEvent> CREATOR;
+ }
+
+ public final class RcsGroupThreadParticipantLeftEvent extends android.telephony.ims.RcsGroupThreadEvent implements android.os.Parcelable {
+ ctor public RcsGroupThreadParticipantLeftEvent(long, @NonNull android.telephony.ims.RcsGroupThread, @NonNull android.telephony.ims.RcsParticipant, @NonNull android.telephony.ims.RcsParticipant);
+ method public int describeContents();
+ method @NonNull public android.telephony.ims.RcsParticipant getLeavingParticipantId();
+ method public void persist() throws android.telephony.ims.RcsMessageStoreException;
+ method public void writeToParcel(android.os.Parcel, int);
+ field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsGroupThreadParticipantLeftEvent> CREATOR;
+ }
+
+ public class RcsIncomingMessage extends android.telephony.ims.RcsMessage {
+ method @WorkerThread public long getArrivalTimestamp() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public long getSeenTimestamp() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public android.telephony.ims.RcsParticipant getSenderParticipant() throws android.telephony.ims.RcsMessageStoreException;
+ method public boolean isIncoming();
+ method @WorkerThread public void setArrivalTimestamp(long) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setSeenTimestamp(long) throws android.telephony.ims.RcsMessageStoreException;
+ }
+
+ public final class RcsIncomingMessageCreationParams extends android.telephony.ims.RcsMessageCreationParams implements android.os.Parcelable {
+ method public int describeContents();
+ method public long getArrivalTimestamp();
+ method public long getSeenTimestamp();
+ method public void writeToParcel(android.os.Parcel, int);
+ field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsIncomingMessageCreationParams> CREATOR;
+ }
+
+ public static class RcsIncomingMessageCreationParams.Builder extends android.telephony.ims.RcsMessageCreationParams.Builder {
+ ctor public RcsIncomingMessageCreationParams.Builder(long, long, int);
+ method public android.telephony.ims.RcsIncomingMessageCreationParams build();
+ method @CheckResult public android.telephony.ims.RcsIncomingMessageCreationParams.Builder setArrivalTimestamp(long);
+ method @CheckResult public android.telephony.ims.RcsIncomingMessageCreationParams.Builder setSeenTimestamp(long);
+ method @CheckResult public android.telephony.ims.RcsIncomingMessageCreationParams.Builder setSenderParticipant(android.telephony.ims.RcsParticipant);
+ }
+
+ public class RcsManager {
+ method public android.telephony.ims.RcsMessageStore getRcsMessageStore();
+ }
+
+ public abstract class RcsMessage {
+ method @NonNull @WorkerThread public java.util.Set<android.telephony.ims.RcsFileTransferPart> getFileTransferParts() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public double getLatitude() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public double getLongitude() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public long getOriginationTimestamp() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public String getRcsMessageId() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread @android.telephony.ims.RcsMessage.RcsMessageStatus public int getStatus() throws android.telephony.ims.RcsMessageStoreException;
+ method public int getSubscriptionId() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public String getText() throws android.telephony.ims.RcsMessageStoreException;
+ method @NonNull @WorkerThread public android.telephony.ims.RcsFileTransferPart insertFileTransfer(android.telephony.ims.RcsFileTransferCreationParams) throws android.telephony.ims.RcsMessageStoreException;
+ method public abstract boolean isIncoming();
+ method @WorkerThread public void removeFileTransferPart(@NonNull android.telephony.ims.RcsFileTransferPart) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setLatitude(double) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setLongitude(double) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setOriginationTimestamp(long) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setRcsMessageId(String) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setStatus(@android.telephony.ims.RcsMessage.RcsMessageStatus int) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setSubscriptionId(int) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setText(String) throws android.telephony.ims.RcsMessageStoreException;
+ field public static final int DRAFT = 1; // 0x1
+ field public static final int FAILED = 6; // 0x6
+ field public static final double LOCATION_NOT_SET = 4.9E-324;
+ field public static final int NOT_SET = 0; // 0x0
+ field public static final int QUEUED = 2; // 0x2
+ field public static final int RECEIVED = 7; // 0x7
+ field public static final int RETRYING = 5; // 0x5
+ field public static final int SEEN = 9; // 0x9
+ field public static final int SENDING = 3; // 0x3
+ field public static final int SENT = 4; // 0x4
+ }
+
+ @IntDef({android.telephony.ims.RcsMessage.DRAFT, android.telephony.ims.RcsMessage.QUEUED, android.telephony.ims.RcsMessage.SENDING, android.telephony.ims.RcsMessage.SENT, android.telephony.ims.RcsMessage.RETRYING, android.telephony.ims.RcsMessage.FAILED, android.telephony.ims.RcsMessage.RECEIVED, android.telephony.ims.RcsMessage.SEEN}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface RcsMessage.RcsMessageStatus {
+ }
+
+ public class RcsMessageCreationParams {
+ ctor protected RcsMessageCreationParams(android.telephony.ims.RcsMessageCreationParams.Builder);
+ method public double getLatitude();
+ method public double getLongitude();
+ method public int getMessageStatus();
+ method public long getOriginationTimestamp();
+ method @Nullable public String getRcsMessageGlobalId();
+ method public int getSubId();
+ method @Nullable public String getText();
+ }
+
+ public static class RcsMessageCreationParams.Builder {
+ method public android.telephony.ims.RcsMessageCreationParams build();
+ method @CheckResult public android.telephony.ims.RcsMessageCreationParams.Builder setLatitude(double);
+ method @CheckResult public android.telephony.ims.RcsMessageCreationParams.Builder setLongitude(double);
+ method @CheckResult public android.telephony.ims.RcsMessageCreationParams.Builder setRcsMessageId(String);
+ method @CheckResult public android.telephony.ims.RcsMessageCreationParams.Builder setStatus(@android.telephony.ims.RcsMessage.RcsMessageStatus int);
+ method @CheckResult public android.telephony.ims.RcsMessageCreationParams.Builder setText(String);
+ }
+
+ public final class RcsMessageQueryParams implements android.os.Parcelable {
+ method public int describeContents();
+ method public int getFileTransferPresence();
+ method public int getLimit();
+ method public String getMessageLike();
+ method public int getMessageType();
+ method public boolean getSortDirection();
+ method @android.telephony.ims.RcsMessageQueryParams.SortingProperty public int getSortingProperty();
+ method public void writeToParcel(android.os.Parcel, int);
+ field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsMessageQueryParams> CREATOR;
+ field public static final int MESSAGES_WITHOUT_FILE_TRANSFERS = 8; // 0x8
+ field public static final int MESSAGES_WITH_FILE_TRANSFERS = 4; // 0x4
+ field public static final int MESSAGE_TYPE_INCOMING = 1; // 0x1
+ field public static final int MESSAGE_TYPE_OUTGOING = 2; // 0x2
+ field public static final int SORT_BY_CREATION_ORDER = 0; // 0x0
+ field public static final int SORT_BY_TIMESTAMP = 1; // 0x1
+ }
+
+ public static class RcsMessageQueryParams.Builder {
+ ctor public RcsMessageQueryParams.Builder();
+ method public android.telephony.ims.RcsMessageQueryParams build();
+ method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setFileTransferPresence(int);
+ method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setMessageLike(String);
+ method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setMessageType(int);
+ method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setResultLimit(@IntRange(from=0) int) throws java.security.InvalidParameterException;
+ method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setSortDirection(boolean);
+ method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setSortProperty(@android.telephony.ims.RcsMessageQueryParams.SortingProperty int);
+ method @CheckResult public android.telephony.ims.RcsMessageQueryParams.Builder setThread(@Nullable android.telephony.ims.RcsThread);
+ }
+
+ @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @IntDef({android.telephony.ims.RcsMessageQueryParams.SORT_BY_CREATION_ORDER, android.telephony.ims.RcsMessageQueryParams.SORT_BY_TIMESTAMP}) public static @interface RcsMessageQueryParams.SortingProperty {
+ }
+
+ public final class RcsMessageQueryResult implements android.os.Parcelable {
+ method public int describeContents();
+ method @Nullable public android.telephony.ims.RcsQueryContinuationToken getContinuationToken();
+ method @NonNull public java.util.List<android.telephony.ims.RcsMessage> getMessages();
+ method public void writeToParcel(android.os.Parcel, int);
+ field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsMessageQueryResult> CREATOR;
+ }
+
+ public final class RcsMessageSnippet implements android.os.Parcelable {
+ method public int describeContents();
+ method @android.telephony.ims.RcsMessage.RcsMessageStatus public int getSnippetStatus();
+ method @Nullable public String getSnippetText();
+ method public long getSnippetTimestamp();
+ method public void writeToParcel(android.os.Parcel, int);
+ field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsMessageSnippet> CREATOR;
+ }
+
+ public class RcsMessageStore {
+ ctor public RcsMessageStore();
+ method @WorkerThread @NonNull public android.telephony.ims.RcsGroupThread createGroupThread(@Nullable java.util.List<android.telephony.ims.RcsParticipant>, @Nullable String, @Nullable android.net.Uri) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread @NonNull public android.telephony.ims.Rcs1To1Thread createRcs1To1Thread(@NonNull android.telephony.ims.RcsParticipant) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread @NonNull public android.telephony.ims.RcsParticipant createRcsParticipant(String, @Nullable String) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void deleteThread(@NonNull android.telephony.ims.RcsThread) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread @NonNull public android.telephony.ims.RcsEventQueryResult getRcsEvents(@Nullable android.telephony.ims.RcsEventQueryParams) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread @NonNull public android.telephony.ims.RcsEventQueryResult getRcsEvents(@NonNull android.telephony.ims.RcsQueryContinuationToken) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread @NonNull public android.telephony.ims.RcsMessageQueryResult getRcsMessages(@Nullable android.telephony.ims.RcsMessageQueryParams) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread @NonNull public android.telephony.ims.RcsMessageQueryResult getRcsMessages(@NonNull android.telephony.ims.RcsQueryContinuationToken) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread @NonNull public android.telephony.ims.RcsParticipantQueryResult getRcsParticipants(@Nullable android.telephony.ims.RcsParticipantQueryParams) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread @NonNull public android.telephony.ims.RcsParticipantQueryResult getRcsParticipants(@NonNull android.telephony.ims.RcsQueryContinuationToken) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread @NonNull public android.telephony.ims.RcsThreadQueryResult getRcsThreads(@Nullable android.telephony.ims.RcsThreadQueryParams) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread @NonNull public android.telephony.ims.RcsThreadQueryResult getRcsThreads(@NonNull android.telephony.ims.RcsQueryContinuationToken) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread @NonNull public void persistRcsEvent(android.telephony.ims.RcsEvent) throws android.telephony.ims.RcsMessageStoreException;
+ }
+
+ public class RcsMessageStoreException extends java.lang.Exception {
+ ctor public RcsMessageStoreException(String);
+ }
+
+ public class RcsOutgoingMessage extends android.telephony.ims.RcsMessage {
+ method @NonNull @WorkerThread public java.util.List<android.telephony.ims.RcsOutgoingMessageDelivery> getOutgoingDeliveries() throws android.telephony.ims.RcsMessageStoreException;
+ method public boolean isIncoming();
+ }
+
+ public final class RcsOutgoingMessageCreationParams extends android.telephony.ims.RcsMessageCreationParams implements android.os.Parcelable {
+ method public int describeContents();
+ method public void writeToParcel(android.os.Parcel, int);
+ field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsOutgoingMessageCreationParams> CREATOR;
+ }
+
+ public static class RcsOutgoingMessageCreationParams.Builder extends android.telephony.ims.RcsMessageCreationParams.Builder {
+ ctor public RcsOutgoingMessageCreationParams.Builder(long, int);
+ method public android.telephony.ims.RcsOutgoingMessageCreationParams build();
+ }
+
+ public class RcsOutgoingMessageDelivery {
+ method @WorkerThread public long getDeliveredTimestamp() throws android.telephony.ims.RcsMessageStoreException;
+ method @NonNull public android.telephony.ims.RcsOutgoingMessage getMessage();
+ method @NonNull public android.telephony.ims.RcsParticipant getRecipient();
+ method @WorkerThread public long getSeenTimestamp() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread @android.telephony.ims.RcsMessage.RcsMessageStatus public int getStatus() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setDeliveredTimestamp(long) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setSeenTimestamp(long) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setStatus(@android.telephony.ims.RcsMessage.RcsMessageStatus int) throws android.telephony.ims.RcsMessageStoreException;
+ }
+
+ public class RcsParticipant {
+ method @Nullable @WorkerThread public String getAlias() throws android.telephony.ims.RcsMessageStoreException;
+ method @Nullable @WorkerThread public String getCanonicalAddress() throws android.telephony.ims.RcsMessageStoreException;
+ method @Nullable @WorkerThread public String getContactId() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setAlias(String) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void setContactId(String) throws android.telephony.ims.RcsMessageStoreException;
+ }
+
+ public final class RcsParticipantAliasChangedEvent extends android.telephony.ims.RcsEvent implements android.os.Parcelable {
+ ctor public RcsParticipantAliasChangedEvent(long, @NonNull android.telephony.ims.RcsParticipant, @Nullable String);
+ method public int describeContents();
+ method @Nullable public String getNewAlias();
+ method @NonNull public android.telephony.ims.RcsParticipant getParticipantId();
+ method public void writeToParcel(android.os.Parcel, int);
+ field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsParticipantAliasChangedEvent> CREATOR;
+ }
+
+ public final class RcsParticipantQueryParams implements android.os.Parcelable {
+ method public int describeContents();
+ method public String getAliasLike();
+ method public String getCanonicalAddressLike();
+ method public int getLimit();
+ method public boolean getSortDirection();
+ method public int getSortingProperty();
+ method public void writeToParcel(android.os.Parcel, int);
+ field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsParticipantQueryParams> CREATOR;
+ field public static final int SORT_BY_ALIAS = 1; // 0x1
+ field public static final int SORT_BY_CANONICAL_ADDRESS = 2; // 0x2
+ field public static final int SORT_BY_CREATION_ORDER = 0; // 0x0
+ }
+
+ public static class RcsParticipantQueryParams.Builder {
+ ctor public RcsParticipantQueryParams.Builder();
+ method public android.telephony.ims.RcsParticipantQueryParams build();
+ method @CheckResult public android.telephony.ims.RcsParticipantQueryParams.Builder setAliasLike(String);
+ method @CheckResult public android.telephony.ims.RcsParticipantQueryParams.Builder setCanonicalAddressLike(String);
+ method @CheckResult public android.telephony.ims.RcsParticipantQueryParams.Builder setResultLimit(@IntRange(from=0) int) throws java.security.InvalidParameterException;
+ method @CheckResult public android.telephony.ims.RcsParticipantQueryParams.Builder setSortDirection(boolean);
+ method @CheckResult public android.telephony.ims.RcsParticipantQueryParams.Builder setSortProperty(@android.telephony.ims.RcsParticipantQueryParams.SortingProperty int);
+ method @CheckResult public android.telephony.ims.RcsParticipantQueryParams.Builder setThread(android.telephony.ims.RcsThread);
+ }
+
+ @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @IntDef({android.telephony.ims.RcsParticipantQueryParams.SORT_BY_CREATION_ORDER, android.telephony.ims.RcsParticipantQueryParams.SORT_BY_ALIAS, android.telephony.ims.RcsParticipantQueryParams.SORT_BY_CANONICAL_ADDRESS}) public static @interface RcsParticipantQueryParams.SortingProperty {
+ }
+
+ public final class RcsParticipantQueryResult implements android.os.Parcelable {
+ method public int describeContents();
+ method @Nullable public android.telephony.ims.RcsQueryContinuationToken getContinuationToken();
+ method @NonNull public java.util.List<android.telephony.ims.RcsParticipant> getParticipants();
+ method public void writeToParcel(android.os.Parcel, int);
+ field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsParticipantQueryResult> CREATOR;
+ }
+
+ public final class RcsQueryContinuationToken implements android.os.Parcelable {
+ method public int describeContents();
+ method @android.telephony.ims.RcsQueryContinuationToken.ContinuationTokenType public int getQueryType();
+ method public void writeToParcel(android.os.Parcel, int);
+ field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsQueryContinuationToken> CREATOR;
+ field public static final int EVENT_QUERY_CONTINUATION_TOKEN_TYPE = 0; // 0x0
+ field public static final int MESSAGE_QUERY_CONTINUATION_TOKEN_TYPE = 1; // 0x1
+ field public static final int PARTICIPANT_QUERY_CONTINUATION_TOKEN_TYPE = 2; // 0x2
+ field public static final int THREAD_QUERY_CONTINUATION_TOKEN_TYPE = 3; // 0x3
+ }
+
+ @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @IntDef({android.telephony.ims.RcsQueryContinuationToken.EVENT_QUERY_CONTINUATION_TOKEN_TYPE, android.telephony.ims.RcsQueryContinuationToken.MESSAGE_QUERY_CONTINUATION_TOKEN_TYPE, android.telephony.ims.RcsQueryContinuationToken.PARTICIPANT_QUERY_CONTINUATION_TOKEN_TYPE, android.telephony.ims.RcsQueryContinuationToken.THREAD_QUERY_CONTINUATION_TOKEN_TYPE}) public static @interface RcsQueryContinuationToken.ContinuationTokenType {
+ }
+
+ public abstract class RcsThread {
+ method @WorkerThread @NonNull public android.telephony.ims.RcsIncomingMessage addIncomingMessage(@NonNull android.telephony.ims.RcsIncomingMessageCreationParams) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread @NonNull public android.telephony.ims.RcsOutgoingMessage addOutgoingMessage(@NonNull android.telephony.ims.RcsOutgoingMessageCreationParams) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread public void deleteMessage(@NonNull android.telephony.ims.RcsMessage) throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread @NonNull public android.telephony.ims.RcsMessageQueryResult getMessages() throws android.telephony.ims.RcsMessageStoreException;
+ method @WorkerThread @NonNull public android.telephony.ims.RcsMessageSnippet getSnippet() throws android.telephony.ims.RcsMessageStoreException;
+ method public abstract boolean isGroup();
+ }
+
+ public final class RcsThreadQueryParams implements android.os.Parcelable {
+ method public int describeContents();
+ method public int getLimit();
+ method public boolean getSortDirection();
+ method @android.telephony.ims.RcsThreadQueryParams.SortingProperty public int getSortingProperty();
+ method public int getThreadType();
+ method public void writeToParcel(android.os.Parcel, int);
+ field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsThreadQueryParams> CREATOR;
+ field public static final int SORT_BY_CREATION_ORDER = 0; // 0x0
+ field public static final int SORT_BY_TIMESTAMP = 1; // 0x1
+ field public static final int THREAD_TYPE_1_TO_1 = 2; // 0x2
+ field public static final int THREAD_TYPE_GROUP = 1; // 0x1
+ }
+
+ public static class RcsThreadQueryParams.Builder {
+ ctor public RcsThreadQueryParams.Builder();
+ method public android.telephony.ims.RcsThreadQueryParams build();
+ method @CheckResult public android.telephony.ims.RcsThreadQueryParams.Builder setParticipant(@NonNull android.telephony.ims.RcsParticipant);
+ method @CheckResult public android.telephony.ims.RcsThreadQueryParams.Builder setParticipants(@NonNull java.util.List<android.telephony.ims.RcsParticipant>);
+ method @CheckResult public android.telephony.ims.RcsThreadQueryParams.Builder setResultLimit(@IntRange(from=0) int) throws java.security.InvalidParameterException;
+ method @CheckResult public android.telephony.ims.RcsThreadQueryParams.Builder setSortDirection(boolean);
+ method @CheckResult public android.telephony.ims.RcsThreadQueryParams.Builder setSortProperty(@android.telephony.ims.RcsThreadQueryParams.SortingProperty int);
+ method @CheckResult public android.telephony.ims.RcsThreadQueryParams.Builder setThreadType(int);
+ }
+
+ @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @IntDef({android.telephony.ims.RcsThreadQueryParams.SORT_BY_CREATION_ORDER, android.telephony.ims.RcsThreadQueryParams.SORT_BY_TIMESTAMP}) public static @interface RcsThreadQueryParams.SortingProperty {
+ }
+
+ public final class RcsThreadQueryResult implements android.os.Parcelable {
+ method public int describeContents();
+ method @Nullable public android.telephony.ims.RcsQueryContinuationToken getContinuationToken();
+ method @NonNull public java.util.List<android.telephony.ims.RcsThread> getThreads();
+ method public void writeToParcel(android.os.Parcel, int);
+ field public static final android.os.Parcelable.Creator<android.telephony.ims.RcsThreadQueryResult> CREATOR;
+ }
+
+}
+
package android.telephony.mbms {
public class DownloadProgressListener {
@@ -48504,6 +48999,7 @@
}
public final class StatsLog {
+ method @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public static boolean logBinaryPushStateChanged(@NonNull String, long, int, int, @NonNull long[]);
method public static boolean logEvent(int);
method public static boolean logStart(int);
method public static boolean logStop(int);
@@ -48997,6 +49493,7 @@
method public boolean[] hasKeys(int...);
method public boolean hasMicrophone();
method public boolean isEnabled();
+ method public boolean isExternal();
method public boolean isVirtual();
method public boolean supportsSource(int);
method public void writeToParcel(android.os.Parcel, int);
@@ -50310,7 +50807,7 @@
method @android.view.ViewDebug.ExportedProperty(category="drawing") public float getAlpha();
method public android.view.animation.Animation getAnimation();
method public android.os.IBinder getApplicationWindowToken();
- method @NonNull public java.util.List<java.lang.Integer> getAttributeResolutionStack();
+ method @NonNull public java.util.List<java.lang.Integer> getAttributeResolutionStack(@AttrRes int);
method @NonNull public java.util.Map<java.lang.Integer,java.lang.Integer> getAttributeSourceResourceMap();
method @android.view.ViewDebug.ExportedProperty @Nullable public String[] getAutofillHints();
method public final android.view.autofill.AutofillId getAutofillId();
@@ -50360,6 +50857,8 @@
method public void getHitRect(android.graphics.Rect);
method public int getHorizontalFadingEdgeLength();
method protected int getHorizontalScrollbarHeight();
+ method @Nullable public android.graphics.drawable.Drawable getHorizontalScrollbarThumbDrawable();
+ method @Nullable public android.graphics.drawable.Drawable getHorizontalScrollbarTrackDrawable();
method @android.view.ViewDebug.CapturedViewProperty @IdRes public int getId();
method @android.view.ViewDebug.ExportedProperty(category="accessibility", mapping={@android.view.ViewDebug.IntToString(from=android.view.View.IMPORTANT_FOR_ACCESSIBILITY_AUTO, to="auto"), @android.view.ViewDebug.IntToString(from=android.view.View.IMPORTANT_FOR_ACCESSIBILITY_YES, to="yes"), @android.view.ViewDebug.IntToString(from=android.view.View.IMPORTANT_FOR_ACCESSIBILITY_NO, to="no"), @android.view.ViewDebug.IntToString(from=android.view.View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, to="noHideDescendants")}) public int getImportantForAccessibility();
method @android.view.ViewDebug.ExportedProperty(mapping={@android.view.ViewDebug.IntToString(from=android.view.View.IMPORTANT_FOR_AUTOFILL_AUTO, to="auto"), @android.view.ViewDebug.IntToString(from=android.view.View.IMPORTANT_FOR_AUTOFILL_YES, to="yes"), @android.view.ViewDebug.IntToString(from=android.view.View.IMPORTANT_FOR_AUTOFILL_NO, to="no"), @android.view.ViewDebug.IntToString(from=android.view.View.IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS, to="yesExcludeDescendants"), @android.view.ViewDebug.IntToString(from=android.view.View.IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS, to="noExcludeDescendants")}) public int getImportantForAutofill();
@@ -50450,6 +50949,8 @@
method public long getUniqueDrawingId();
method public int getVerticalFadingEdgeLength();
method public int getVerticalScrollbarPosition();
+ method @Nullable public android.graphics.drawable.Drawable getVerticalScrollbarThumbDrawable();
+ method @Nullable public android.graphics.drawable.Drawable getVerticalScrollbarTrackDrawable();
method public int getVerticalScrollbarWidth();
method public android.view.ViewTreeObserver getViewTreeObserver();
method @android.view.ViewDebug.ExportedProperty(mapping={@android.view.ViewDebug.IntToString(from=android.view.View.VISIBLE, to="VISIBLE"), @android.view.ViewDebug.IntToString(from=android.view.View.INVISIBLE, to="INVISIBLE"), @android.view.ViewDebug.IntToString(from=android.view.View.GONE, to="GONE")}) public int getVisibility();
@@ -50693,6 +51194,8 @@
method public void setHasTransientState(boolean);
method public void setHorizontalFadingEdgeEnabled(boolean);
method public void setHorizontalScrollBarEnabled(boolean);
+ method public void setHorizontalScrollbarThumbDrawable(@Nullable android.graphics.drawable.Drawable);
+ method public void setHorizontalScrollbarTrackDrawable(@Nullable android.graphics.drawable.Drawable);
method public void setHovered(boolean);
method public void setId(@IdRes int);
method public void setImportantForAccessibility(int);
@@ -50782,6 +51285,8 @@
method public void setVerticalFadingEdgeEnabled(boolean);
method public void setVerticalScrollBarEnabled(boolean);
method public void setVerticalScrollbarPosition(int);
+ method public void setVerticalScrollbarThumbDrawable(@Nullable android.graphics.drawable.Drawable);
+ method public void setVerticalScrollbarTrackDrawable(@Nullable android.graphics.drawable.Drawable);
method public void setVisibility(int);
method @Deprecated public void setWillNotCacheDrawing(boolean);
method public void setWillNotDraw(boolean);
@@ -51240,6 +51745,7 @@
method public android.view.View getChildAt(int);
method public int getChildCount();
method protected int getChildDrawingOrder(int, int);
+ method public final int getChildDrawingOrder(int);
method public static int getChildMeasureSpec(int, int, int);
method protected boolean getChildStaticTransformation(android.view.View, android.view.animation.Transformation);
method public boolean getChildVisibleRect(android.view.View, android.graphics.Rect, android.graphics.Point);
@@ -52612,7 +53118,6 @@
public abstract class Animation implements java.lang.Cloneable {
ctor public Animation();
ctor public Animation(android.content.Context, android.util.AttributeSet);
- method public void addAnimationListener(android.view.animation.Animation.AnimationListener);
method protected void applyTransformation(float, android.view.animation.Transformation);
method public void cancel();
method protected android.view.animation.Animation clone() throws java.lang.CloneNotSupportedException;
@@ -52637,7 +53142,6 @@
method public void initialize(int, int, int, int);
method public boolean isFillEnabled();
method public boolean isInitialized();
- method public void removeAnimationListener(android.view.animation.Animation.AnimationListener);
method public void reset();
method protected float resolveSize(int, float, int, int);
method public void restrictDuration(long);
@@ -55870,11 +56374,16 @@
method public boolean executeKeyEvent(android.view.KeyEvent);
method public void fling(int);
method public boolean fullScroll(int);
+ method @ColorInt public int getLeftEdgeEffectColor();
method public int getMaxScrollAmount();
+ method @ColorInt public int getRightEdgeEffectColor();
method public boolean isFillViewport();
method public boolean isSmoothScrollingEnabled();
method public boolean pageScroll(int);
+ method public void setEdgeEffectColor(@ColorInt int);
method public void setFillViewport(boolean);
+ method public void setLeftEdgeEffectColor(@ColorInt int);
+ method public void setRightEdgeEffectColor(@ColorInt int);
method public void setSmoothScrollingEnabled(boolean);
method public final void smoothScrollBy(int, int);
method public final void smoothScrollTo(int, int);
@@ -56206,6 +56715,8 @@
method public int getMaxValue();
method public int getMinValue();
method public int getSelectionDividerHeight();
+ method @ColorInt public int getTextColor();
+ method @FloatRange(from=0.0, fromInclusive=false) public float getTextSize();
method public int getValue();
method public boolean getWrapSelectorWheel();
method public void setDisplayedValues(String[]);
@@ -56216,6 +56727,8 @@
method public void setOnScrollListener(android.widget.NumberPicker.OnScrollListener);
method public void setOnValueChangedListener(android.widget.NumberPicker.OnValueChangeListener);
method public void setSelectionDividerHeight(@IntRange(from=0) @Px int);
+ method public void setTextColor(@ColorInt int);
+ method public void setTextSize(@FloatRange(from=0.0, fromInclusive=false) float);
method public void setValue(int);
method public void setWrapSelectorWheel(boolean);
}
@@ -56375,6 +56888,7 @@
ctor public ProgressBar(android.content.Context, android.util.AttributeSet);
ctor public ProgressBar(android.content.Context, android.util.AttributeSet, int);
ctor public ProgressBar(android.content.Context, android.util.AttributeSet, int, int);
+ method @Nullable public android.graphics.drawable.Drawable getCurrentDrawable();
method public android.graphics.drawable.Drawable getIndeterminateDrawable();
method @Nullable public android.content.res.ColorStateList getIndeterminateTintList();
method @Nullable public android.graphics.PorterDuff.Mode getIndeterminateTintMode();
@@ -56672,13 +57186,18 @@
method public boolean executeKeyEvent(android.view.KeyEvent);
method public void fling(int);
method public boolean fullScroll(int);
+ method @ColorInt public int getBottomEdgeEffectColor();
method public int getMaxScrollAmount();
+ method @ColorInt public int getTopEdgeEffectColor();
method public boolean isFillViewport();
method public boolean isSmoothScrollingEnabled();
method public boolean pageScroll(int);
method public void scrollToDescendant(android.view.View);
+ method public void setBottomEdgeEffectColor(@ColorInt int);
+ method public void setEdgeEffectColor(@ColorInt int);
method public void setFillViewport(boolean);
method public void setSmoothScrollingEnabled(boolean);
+ method public void setTopEdgeEffectColor(@ColorInt int);
method public final void smoothScrollBy(int, int);
method public final void smoothScrollTo(int, int);
}
@@ -61199,9 +61718,9 @@
method public String getName();
method public int getReferenceKind();
method public default boolean isVarArgs();
- method public static boolean refKindIsField(int);
- method public static boolean refKindIsValid(int);
- method public static String refKindName(int);
+ method @Deprecated public static boolean refKindIsField(int);
+ method @Deprecated public static boolean refKindIsValid(int);
+ method @Deprecated public static String refKindName(int);
method public static String referenceKindToString(int);
method public <T extends java.lang.reflect.Member> T reflectAs(Class<T>, java.lang.invoke.MethodHandles.Lookup);
method public static String toString(int, Class<?>, String, java.lang.invoke.MethodType);
diff --git a/api/removed.txt b/api/removed.txt
index f5bd434..c4ed871 100644
--- a/api/removed.txt
+++ b/api/removed.txt
@@ -558,7 +558,7 @@
public class TelephonyManager {
method @Deprecated @RequiresPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) public java.util.List<android.telephony.NeighboringCellInfo> getNeighboringCellInfo();
- method @Deprecated @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public android.telephony.NetworkScan requestNetworkScan(android.telephony.NetworkScanRequest, android.telephony.TelephonyScanManager.NetworkScanCallback);
+ method @Deprecated @RequiresPermission(allOf={android.Manifest.permission.MODIFY_PHONE_STATE, android.Manifest.permission.ACCESS_FINE_LOCATION}) public android.telephony.NetworkScan requestNetworkScan(android.telephony.NetworkScanRequest, android.telephony.TelephonyScanManager.NetworkScanCallback);
}
}
diff --git a/api/system-current.txt b/api/system-current.txt
index 3a50239..005d1ba 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -205,6 +205,7 @@
}
public static final class R.attr {
+ field public static final int allowClearUserDataOnFailedRestore = 16844198; // 0x10105a6
field public static final int inheritShowWhenLocked = 16844194; // 0x10105a2
field public static final int isVrOnly = 16844152; // 0x1010578
field public static final int requiredSystemPropertyName = 16844133; // 0x1010565
@@ -239,6 +240,8 @@
field public static final int config_defaultAssistant = 17039393; // 0x1040021
field public static final int config_defaultBrowser = 17039394; // 0x1040022
field public static final int config_defaultDialer = 17039395; // 0x1040023
+ field public static final int config_defaultGallery = 17039398; // 0x1040026
+ field public static final int config_defaultMusic = 17039397; // 0x1040025
field public static final int config_defaultSms = 17039396; // 0x1040024
field public static final int config_feedbackIntentExtraKey = 17039391; // 0x104001f
field public static final int config_feedbackIntentNameKey = 17039392; // 0x1040020
@@ -638,7 +641,7 @@
method @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL) public boolean packageHasActiveAdmins(String);
method @Deprecated @RequiresPermission("android.permission.MANAGE_DEVICE_ADMINS") public boolean setActiveProfileOwner(@NonNull android.content.ComponentName, String) throws java.lang.IllegalArgumentException;
method @RequiresPermission(android.Manifest.permission.MANAGE_USERS) public void setDeviceProvisioningConfigApplied();
- method public void setProfileOwnerCanAccessDeviceIdsForUser(@NonNull android.content.ComponentName, @NonNull android.os.UserHandle);
+ method @RequiresPermission(value=android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS, conditional=true) public void setProfileOwnerCanAccessDeviceIdsForUser(@NonNull android.content.ComponentName, @NonNull android.os.UserHandle);
field public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED = "android.account.DEVICE_OR_PROFILE_OWNER_ALLOWED";
field public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED = "android.account.DEVICE_OR_PROFILE_OWNER_DISALLOWED";
field public static final String ACTION_PROVISION_FINALIZATION = "android.app.action.PROVISION_FINALIZATION";
@@ -1148,7 +1151,7 @@
method @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS) public int getAppStandbyBucket(String);
method @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS) public java.util.Map<java.lang.String,java.lang.Integer> getAppStandbyBuckets();
method public int getUsageSource();
- method @RequiresPermission(allOf={android.Manifest.permission.SUSPEND_APPS, android.Manifest.permission.OBSERVE_APP_USAGE}) public void registerAppUsageLimitObserver(int, @NonNull String[], long, @NonNull java.util.concurrent.TimeUnit, @NonNull android.app.PendingIntent);
+ method @RequiresPermission(allOf={android.Manifest.permission.SUSPEND_APPS, android.Manifest.permission.OBSERVE_APP_USAGE}) public void registerAppUsageLimitObserver(int, @NonNull String[], long, @NonNull java.util.concurrent.TimeUnit, android.app.PendingIntent);
method @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE) public void registerAppUsageObserver(int, @NonNull String[], long, @NonNull java.util.concurrent.TimeUnit, @NonNull android.app.PendingIntent);
method @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE) public void registerUsageSessionObserver(int, @NonNull String[], long, @NonNull java.util.concurrent.TimeUnit, long, @NonNull java.util.concurrent.TimeUnit, @NonNull android.app.PendingIntent, @Nullable android.app.PendingIntent);
method public void reportUsageStart(@NonNull android.app.Activity, @NonNull String);
@@ -1280,7 +1283,9 @@
}
public abstract class ContentResolver implements android.content.ContentInterface {
+ method public android.os.Bundle getCache(android.net.Uri);
method public android.graphics.drawable.Drawable getTypeDrawable(String);
+ method public void putCache(android.net.Uri, android.os.Bundle);
}
public abstract class Context {
@@ -1532,6 +1537,7 @@
method @RequiresPermission(android.Manifest.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS) public void setGrantedRuntimePermissions(String[]);
method public void setInstallAsInstantApp(boolean);
method public void setInstallAsVirtualPreload();
+ method @RequiresPermission(android.Manifest.permission.INSTALL_PACKAGES) public void setStaged();
}
public class PackageItemInfo {
@@ -1574,7 +1580,7 @@
method @RequiresPermission(android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) public abstract void revokeRuntimePermission(@NonNull String, @NonNull String, @NonNull android.os.UserHandle);
method public void sendDeviceCustomizationReadyBroadcast();
method @RequiresPermission(allOf={android.Manifest.permission.SET_PREFERRED_APPLICATIONS, android.Manifest.permission.INTERACT_ACROSS_USERS_FULL}) public abstract boolean setDefaultBrowserPackageNameAsUser(String, int);
- method @NonNull @RequiresPermission(android.Manifest.permission.SUSPEND_APPS) public String[] setDistractingPackageRestrictions(@NonNull String[], @android.content.pm.PackageManager.DistractionRestriction int);
+ method @NonNull @RequiresPermission(android.Manifest.permission.SUSPEND_APPS) public String[] setDistractingPackageRestrictions(@NonNull String[], int);
method @RequiresPermission(android.Manifest.permission.SET_HARMFUL_APP_WARNINGS) public void setHarmfulAppWarning(@NonNull String, @Nullable CharSequence);
method @Deprecated @Nullable @RequiresPermission(android.Manifest.permission.SUSPEND_APPS) public String[] setPackagesSuspended(@Nullable String[], boolean, @Nullable android.os.PersistableBundle, @Nullable android.os.PersistableBundle, @Nullable String);
method @Nullable @RequiresPermission(android.Manifest.permission.SUSPEND_APPS) public String[] setPackagesSuspended(@Nullable String[], boolean, @Nullable android.os.PersistableBundle, @Nullable android.os.PersistableBundle, @Nullable android.content.pm.SuspendDialogInfo);
@@ -1652,9 +1658,6 @@
method public abstract void onDexModuleRegistered(String, boolean, String);
}
- @IntDef(flag=true, prefix={"RESTRICTION_"}, value={android.content.pm.PackageManager.RESTRICTION_NONE, android.content.pm.PackageManager.RESTRICTION_HIDE_FROM_SUGGESTIONS, android.content.pm.PackageManager.RESTRICTION_HIDE_NOTIFICATIONS}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface PackageManager.DistractionRestriction {
- }
-
public static interface PackageManager.OnPermissionsChangedListener {
method public void onPermissionsChanged(int);
}
@@ -5776,6 +5779,16 @@
field public static final String PROPERTY_PERMISSIONS_HUB_ENABLED = "permissions_hub_enabled";
}
+ public static interface DeviceConfig.Rollback {
+ field public static final String ENABLE_ROLLBACK_TIMEOUT = "enable_rollback_timeout";
+ field public static final String NAMESPACE = "rollback";
+ }
+
+ public static interface DeviceConfig.Runtime {
+ field public static final String NAMESPACE = "runtime";
+ field public static final String USE_PRECOMPILED_LAYOUT = "view.precompiled_layout_enabled";
+ }
+
public static interface DeviceConfig.RuntimeNative {
field public static final String NAMESPACE = "runtime_native";
}
@@ -5784,6 +5797,11 @@
field public static final String NAMESPACE = "runtime_native_boot";
}
+ public static interface DeviceConfig.Scheduler {
+ field public static final String ENABLE_FAST_METRICS_COLLECTION = "enable_fast_metrics_collection";
+ field public static final String NAMESPACE = "scheduler";
+ }
+
public static interface DeviceConfig.Storage {
field public static final String ISOLATED_STORAGE_ENABLED = "isolated_storage_enabled";
field public static final String NAMESPACE = "storage";
@@ -6953,6 +6971,7 @@
field public static final String EXTRA_CALL_BACK_INTENT = "android.telecom.extra.CALL_BACK_INTENT";
field public static final String EXTRA_CLEAR_MISSED_CALLS_INTENT = "android.telecom.extra.CLEAR_MISSED_CALLS_INTENT";
field public static final String EXTRA_CONNECTION_SERVICE = "android.telecom.extra.CONNECTION_SERVICE";
+ field public static final String EXTRA_IS_USER_INTENT_EMERGENCY_CALL = "android.telecom.extra.IS_USER_INTENT_EMERGENCY_CALL";
field public static final int TTY_MODE_FULL = 1; // 0x1
field public static final int TTY_MODE_HCO = 2; // 0x2
field public static final int TTY_MODE_OFF = 0; // 0x0
@@ -7016,6 +7035,7 @@
method @NonNull public java.util.List<android.service.carrier.CarrierIdentifier> getExcludedCarriers();
method public int getMultiSimPolicy();
method public boolean isAllCarriersAllowed();
+ method public java.util.List<java.lang.Boolean> isCarrierIdentifiersAllowed(@NonNull java.util.List<android.service.carrier.CarrierIdentifier>);
method public void writeToParcel(android.os.Parcel, int);
field public static final int CARRIER_RESTRICTION_DEFAULT_ALLOWED = 1; // 0x1
field public static final int CARRIER_RESTRICTION_DEFAULT_NOT_ALLOWED = 0; // 0x0
@@ -7745,6 +7765,7 @@
method public void requestEmbeddedSubscriptionInfoListRefresh(int);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setDefaultDataSubId(int);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setDefaultSmsSubId(int);
+ method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setPreferredDataSubscriptionId(int, boolean, @NonNull java.util.concurrent.Executor, java.util.function.Consumer<java.lang.Integer>);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean setSubscriptionEnabled(int, boolean);
field public static final android.net.Uri ADVANCED_CALLING_ENABLED_CONTENT_URI;
field public static final int PROFILE_CLASS_DEFAULT = -1; // 0xffffffff
@@ -7831,12 +7852,13 @@
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isMultisimCarrierRestricted();
method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, android.Manifest.permission.READ_PHONE_STATE}) public boolean isOffhook();
method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, android.Manifest.permission.READ_PHONE_STATE}) public boolean isRadioOn();
+ method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isRebootRequiredForModemConfigChange();
method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, android.Manifest.permission.READ_PHONE_STATE}) public boolean isRinging();
method @RequiresPermission(anyOf={android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, android.Manifest.permission.READ_PHONE_STATE}) public boolean isVideoCallingEnabled();
method @Deprecated @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public boolean isVisualVoicemailEnabled(android.telecom.PhoneAccountHandle);
method public boolean needsOtaServiceProvisioning();
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean rebootRadio();
- method @RequiresPermission(allOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.MODIFY_PHONE_STATE}) public void requestCellInfoUpdate(@NonNull android.os.WorkSource, @NonNull java.util.concurrent.Executor, @NonNull android.telephony.TelephonyManager.CellInfoCallback);
+ method @RequiresPermission(allOf={android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.MODIFY_PHONE_STATE}) public void requestCellInfoUpdate(@NonNull android.os.WorkSource, @NonNull java.util.concurrent.Executor, @NonNull android.telephony.TelephonyManager.CellInfoCallback);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void requestNumberVerification(@NonNull android.telephony.PhoneNumberRange, long, @NonNull java.util.concurrent.Executor, @NonNull android.telephony.NumberVerificationCallback);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean resetRadioConfig();
method @Deprecated @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public int setAllowedCarriers(int, java.util.List<android.service.carrier.CarrierIdentifier>);
@@ -8224,6 +8246,7 @@
method public int getServiceType();
method public static int getVideoStateFromCallType(int);
method public static int getVideoStateFromImsCallProfile(android.telephony.ims.ImsCallProfile);
+ method public boolean hasKnownUserIntentEmergency();
method public boolean isEmergencyCallTesting();
method public boolean isVideoCall();
method public boolean isVideoPaused();
@@ -8236,6 +8259,7 @@
method public void setEmergencyCallTesting(boolean);
method public void setEmergencyServiceCategories(int);
method public void setEmergencyUrns(java.util.List<java.lang.String>);
+ method public void setHasKnownUserIntentEmergency(boolean);
method public void updateCallExtras(android.telephony.ims.ImsCallProfile);
method public void updateCallType(android.telephony.ims.ImsCallProfile);
method public void updateMediaProfile(android.telephony.ims.ImsCallProfile);
diff --git a/api/test-current.txt b/api/test-current.txt
index b2ead4a..1a7e4cb 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -1785,12 +1785,19 @@
}
public final class DeviceConfig {
+ method @RequiresPermission("android.permission.READ_DEVICE_CONFIG") public static void addOnPropertyChangedListener(@NonNull String, @NonNull java.util.concurrent.Executor, @NonNull android.provider.DeviceConfig.OnPropertyChangedListener);
method @RequiresPermission("android.permission.READ_DEVICE_CONFIG") public static String getProperty(String, String);
+ method public static void removeOnPropertyChangedListener(android.provider.DeviceConfig.OnPropertyChangedListener);
method @RequiresPermission("android.permission.WRITE_DEVICE_CONFIG") public static void resetToDefaults(int, @Nullable String);
method @RequiresPermission("android.permission.WRITE_DEVICE_CONFIG") public static boolean setProperty(String, String, String, boolean);
+ field public static final String NAMESPACE_AUTOFILL = "autofill";
field public static final String NAMESPACE_CONTENT_CAPTURE = "content_capture";
}
+ public static interface DeviceConfig.OnPropertyChangedListener {
+ method public void onPropertyChanged(String, String, String);
+ }
+
public static interface DeviceConfig.Privacy {
field public static final String NAMESPACE = "privacy";
field public static final String PROPERTY_LOCATION_ACCESS_CHECK_ENABLED = "location_access_check_enabled";
@@ -1813,7 +1820,6 @@
public static final class Settings.Global extends android.provider.Settings.NameValueTable {
field public static final String AUTOFILL_COMPAT_MODE_ALLOWED_PACKAGES = "autofill_compat_mode_allowed_packages";
- field public static final String AUTOFILL_SMART_SUGGESTION_EMULATION_FLAGS = "autofill_smart_suggestion_emulation_flags";
field public static final String AUTOMATIC_POWER_SAVER_MODE = "automatic_power_saver_mode";
field public static final String CAPTIVE_PORTAL_FALLBACK_PROBE_SPECS = "captive_portal_fallback_probe_specs";
field public static final String CAPTIVE_PORTAL_FALLBACK_URL = "captive_portal_fallback_url";
@@ -2694,6 +2700,8 @@
public final class AutofillManager {
method public void setAugmentedAutofillWhitelist(@Nullable java.util.List<java.lang.String>, @Nullable java.util.List<android.content.ComponentName>);
+ field public static final String DEVICE_CONFIG_AUTOFILL_SMART_SUGGESTION_SUPPORTED_MODES = "smart_suggestion_supported_modes";
+ field public static final int FLAG_SMART_SUGGESTION_OFF = 0; // 0x0
field public static final int FLAG_SMART_SUGGESTION_SYSTEM = 1; // 0x1
field public static final int MAX_TEMP_AUGMENTED_SERVICE_DURATION_MS = 120000; // 0x1d4c0
}
diff --git a/cmds/bootanimation/bootanim.rc b/cmds/bootanimation/bootanim.rc
index 1b3c32b..469c964 100644
--- a/cmds/bootanimation/bootanim.rc
+++ b/cmds/bootanimation/bootanim.rc
@@ -2,7 +2,6 @@
class core animation
user graphics
group graphics audio
- updatable
disabled
oneshot
writepid /dev/stune/top-app/tasks
diff --git a/cmds/statsd/Android.bp b/cmds/statsd/Android.bp
index d6f045e..04ab592 100644
--- a/cmds/statsd/Android.bp
+++ b/cmds/statsd/Android.bp
@@ -71,6 +71,7 @@
"src/external/Perfetto.cpp",
"src/external/Perfprofd.cpp",
"src/external/StatsPuller.cpp",
+ "src/external/StatsCallbackPuller.cpp",
"src/external/StatsCompanionServicePuller.cpp",
"src/external/SubsystemSleepStatePuller.cpp",
"src/external/PowerStatsPuller.cpp",
@@ -237,6 +238,7 @@
"tests/guardrail/StatsdStats_test.cpp",
"tests/metrics/metrics_test_helper.cpp",
"tests/statsd_test_util.cpp",
+ "tests/storage/StorageManager_test.cpp",
"tests/e2e/WakelockDuration_e2e_test.cpp",
"tests/e2e/MetricActivation_e2e_test.cpp",
"tests/e2e/MetricConditionLink_e2e_test.cpp",
diff --git a/cmds/statsd/benchmark/metric_util.cpp b/cmds/statsd/benchmark/metric_util.cpp
index 067b6ed..cca6d52 100644
--- a/cmds/statsd/benchmark/metric_util.cpp
+++ b/cmds/statsd/benchmark/metric_util.cpp
@@ -367,7 +367,8 @@
sp<AlarmMonitor> periodicAlarmMonitor;
sp<StatsLogProcessor> processor =
new StatsLogProcessor(uidMap, pullerManager, anomalyAlarmMonitor, periodicAlarmMonitor,
- timeBaseSec * NS_PER_SEC, [](const ConfigKey&) { return true; });
+ timeBaseSec * NS_PER_SEC, [](const ConfigKey&) { return true; },
+ [](const int&, const vector<int64_t>&) { return true; });
processor->OnConfigUpdated(timeBaseSec * NS_PER_SEC, key, config);
return processor;
}
@@ -393,4 +394,4 @@
} // namespace statsd
} // namespace os
-} // namespace android
\ No newline at end of file
+} // namespace android
diff --git a/cmds/statsd/src/StatsLogProcessor.cpp b/cmds/statsd/src/StatsLogProcessor.cpp
index dd18bd4..653ef2e 100644
--- a/cmds/statsd/src/StatsLogProcessor.cpp
+++ b/cmds/statsd/src/StatsLogProcessor.cpp
@@ -88,12 +88,15 @@
const sp<AlarmMonitor>& anomalyAlarmMonitor,
const sp<AlarmMonitor>& periodicAlarmMonitor,
const int64_t timeBaseNs,
- const std::function<bool(const ConfigKey&)>& sendBroadcast)
+ const std::function<bool(const ConfigKey&)>& sendBroadcast,
+ const std::function<bool(
+ const int&, const vector<int64_t>&)>& activateBroadcast)
: mUidMap(uidMap),
mPullerManager(pullerManager),
mAnomalyAlarmMonitor(anomalyAlarmMonitor),
mPeriodicAlarmMonitor(periodicAlarmMonitor),
mSendBroadcast(sendBroadcast),
+ mSendActivationBroadcast(activateBroadcast),
mTimeBaseNs(timeBaseNs),
mLargestTimestampSeen(0),
mLastTimestampSeen(0) {
@@ -223,11 +226,73 @@
mapIsolatedUidToHostUidIfNecessaryLocked(event);
}
+ std::unordered_set<int> uidsWithActiveConfigsChanged;
+ std::unordered_map<int, std::vector<int64_t>> activeConfigsPerUid;
// pass the event to metrics managers.
for (auto& pair : mMetricsManagers) {
+ int uid = pair.first.GetUid();
+ int64_t configId = pair.first.GetId();
+ bool isPrevActive = pair.second->isActive();
pair.second->onLogEvent(*event);
+ bool isCurActive = pair.second->isActive();
+ // Map all active configs by uid.
+ if (isCurActive) {
+ auto activeConfigs = activeConfigsPerUid.find(uid);
+ if (activeConfigs != activeConfigsPerUid.end()) {
+ activeConfigs->second.push_back(configId);
+ } else {
+ vector<int64_t> newActiveConfigs;
+ newActiveConfigs.push_back(configId);
+ activeConfigsPerUid[uid] = newActiveConfigs;
+ }
+ }
+ // The activation state of this config changed.
+ if (isPrevActive != isCurActive) {
+ VLOG("Active status changed for uid %d", uid);
+ uidsWithActiveConfigsChanged.insert(uid);
+ StatsdStats::getInstance().noteActiveStatusChanged(pair.first, isCurActive);
+ }
flushIfNecessaryLocked(event->GetElapsedTimestampNs(), pair.first, *(pair.second));
}
+
+ for (int uid : uidsWithActiveConfigsChanged) {
+ // Send broadcast so that receivers can pull data.
+ auto lastBroadcastTime = mLastActivationBroadcastTimes.find(uid);
+ if (lastBroadcastTime != mLastActivationBroadcastTimes.end()) {
+ if (currentTimestampNs - lastBroadcastTime->second <
+ StatsdStats::kMinActivationBroadcastPeriodNs) {
+ VLOG("StatsD would've sent an activation broadcast but the rate limit stopped us.");
+ return;
+ }
+ }
+ auto activeConfigs = activeConfigsPerUid.find(uid);
+ if (activeConfigs != activeConfigsPerUid.end()) {
+ if (mSendActivationBroadcast(uid, activeConfigs->second)) {
+ VLOG("StatsD sent activation notice for uid %d", uid);
+ mLastActivationBroadcastTimes[uid] = currentTimestampNs;
+ }
+ } else {
+ std::vector<int64_t> emptyActiveConfigs;
+ if (mSendActivationBroadcast(uid, emptyActiveConfigs)) {
+ VLOG("StatsD sent EMPTY activation notice for uid %d", uid);
+ mLastActivationBroadcastTimes[uid] = currentTimestampNs;
+ }
+ }
+ }
+}
+
+void StatsLogProcessor::GetActiveConfigs(const int uid, vector<int64_t>& outActiveConfigs) {
+ std::lock_guard<std::mutex> lock(mMetricsMutex);
+ GetActiveConfigsLocked(uid, outActiveConfigs);
+}
+
+void StatsLogProcessor::GetActiveConfigsLocked(const int uid, vector<int64_t>& outActiveConfigs) {
+ outActiveConfigs.clear();
+ for (auto& pair : mMetricsManagers) {
+ if (pair.first.GetUid() == uid && pair.second->isActive()) {
+ outActiveConfigs.push_back(pair.first.GetId());
+ }
+ }
}
void StatsLogProcessor::OnConfigUpdated(const int64_t timestampNs, const ConfigKey& key,
@@ -444,6 +509,18 @@
mLastBroadcastTimes.erase(key);
+ int uid = key.GetUid();
+ bool lastConfigForUid = true;
+ for (auto it : mMetricsManagers) {
+ if (it.first.GetUid() == uid) {
+ lastConfigForUid = false;
+ break;
+ }
+ }
+ if (lastConfigForUid) {
+ mLastActivationBroadcastTimes.erase(uid);
+ }
+
if (mMetricsManagers.empty()) {
mPullerManager->ForceClearPullerCache();
}
diff --git a/cmds/statsd/src/StatsLogProcessor.h b/cmds/statsd/src/StatsLogProcessor.h
index caf1a71..ea9c6e7 100644
--- a/cmds/statsd/src/StatsLogProcessor.h
+++ b/cmds/statsd/src/StatsLogProcessor.h
@@ -49,7 +49,9 @@
const sp<AlarmMonitor>& anomalyAlarmMonitor,
const sp<AlarmMonitor>& subscriberTriggerAlarmMonitor,
const int64_t timeBaseNs,
- const std::function<bool(const ConfigKey&)>& sendBroadcast);
+ const std::function<bool(const ConfigKey&)>& sendBroadcast,
+ const std::function<bool(const int&,
+ const vector<int64_t>&)>& sendActivationBroadcast);
virtual ~StatsLogProcessor();
void OnLogEvent(LogEvent* event);
@@ -60,6 +62,8 @@
size_t GetMetricsSize(const ConfigKey& key) const;
+ void GetActiveConfigs(const int uid, vector<int64_t>& outActiveConfigs);
+
void onDumpReport(const ConfigKey& key, const int64_t dumpTimeNs,
const bool include_current_partial_bucket, const bool erase_data,
const DumpReportReason dumpReportReason, vector<uint8_t>* outData);
@@ -125,6 +129,9 @@
std::unordered_map<ConfigKey, long> mLastBroadcastTimes;
+ // Last time we sent a broadcast to this uid that the active configs had changed.
+ std::unordered_map<int, long> mLastActivationBroadcastTimes;
+
// Tracks when we last checked the bytes consumed for each config key.
std::unordered_map<ConfigKey, long> mLastByteSizeTimes;
@@ -144,6 +151,8 @@
void OnConfigUpdatedLocked(
const int64_t currentTimestampNs, const ConfigKey& key, const StatsdConfig& config);
+ void GetActiveConfigsLocked(const int uid, vector<int64_t>& outActiveConfigs);
+
void WriteDataToDiskLocked(const DumpReportReason dumpReportReason);
void WriteDataToDiskLocked(const ConfigKey& key, const int64_t timestampNs,
const DumpReportReason dumpReportReason);
@@ -174,6 +183,10 @@
// to retrieve the stored data.
std::function<bool(const ConfigKey& key)> mSendBroadcast;
+ // Function used to send a broadcast so that receiver can be notified of which configs
+ // are currently active.
+ std::function<bool(const int& uid, const vector<int64_t>& configIds)> mSendActivationBroadcast;
+
const int64_t mTimeBaseNs;
// Largest timestamp of the events that we have processed.
diff --git a/cmds/statsd/src/StatsService.cpp b/cmds/statsd/src/StatsService.cpp
index 86bf3ec..d23fc62 100644
--- a/cmds/statsd/src/StatsService.cpp
+++ b/cmds/statsd/src/StatsService.cpp
@@ -31,6 +31,7 @@
#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>
#include <binder/PermissionController.h>
+#include <cutils/multiuser.h>
#include <dirent.h>
#include <frameworks/base/cmds/statsd/src/statsd_config.pb.h>
#include <private/android_filesystem_config.h>
@@ -47,12 +48,16 @@
using android::base::StringPrintf;
using android::util::FIELD_COUNT_REPEATED;
+using android::util::FIELD_TYPE_INT64;
using android::util::FIELD_TYPE_MESSAGE;
namespace android {
namespace os {
namespace statsd {
+const int FIELD_ID_EXPERIMENT_ID = 1;
+const int FIELD_ID_EXPERIMENT_ID_MSG = 7;
+
constexpr const char* kPermissionDump = "android.permission.DUMP";
constexpr const char* kPermissionUsage = "android.permission.PACKAGE_USAGE_STATS";
@@ -176,6 +181,21 @@
sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
return true;
}
+ },
+ [this](const int& uid, const vector<int64_t>& activeConfigs) {
+ auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
+ sp<IStatsCompanionService> sc = getStatsCompanionService();
+ if (sc == nullptr) {
+ VLOG("Could not access statsCompanion");
+ return false;
+ } else if (receiver == nullptr) {
+ VLOG("Could not find receiver for uid %d", uid);
+ return false;
+ } else {
+ sc->sendActiveConfigsChangedBroadcast(receiver, activeConfigs);
+ VLOG("StatsService::active configs broadcast succeeded for uid %d" , uid);
+ return true;
+ }
});
mConfigManager->AddListener(mProcessor);
@@ -357,6 +377,9 @@
if (!args[0].compare(String8("print-logs"))) {
return cmd_print_logs(out, args);
}
+ if (!args[0].compare(String8("send-active-configs"))) {
+ return cmd_trigger_active_config_broadcast(out, args);
+ }
if (!args[0].compare(String8("data-subscribe"))) {
if (mShellSubscriber == nullptr) {
mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
@@ -449,6 +472,19 @@
dprintf(out, " NAME The name of the configuration\n");
dprintf(out, "\n");
dprintf(out, "\n");
+ dprintf(out,
+ "usage: adb shell cmd stats send-active-configs [--uid=UID] [--configs] "
+ "[NAME1] [NAME2] [NAME3..]\n");
+ dprintf(out, " Send a broadcast that informs the subscriber of the current active configs.\n");
+ dprintf(out, " --uid=UID The uid of the configurations. It is only possible to pass\n");
+ dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
+ dprintf(out, " calling uid is used.\n");
+ dprintf(out, " --configs Send the list of configs in the name list instead of\n");
+ dprintf(out, " the currently active configs\n");
+ dprintf(out, " NAME LIST List of configuration names to be included in the broadcast.\n");
+
+ dprintf(out, "\n");
+ dprintf(out, "\n");
dprintf(out, "usage: adb shell cmd stats print-stats\n");
dprintf(out, " Prints some basic stats.\n");
dprintf(out, " --proto Print proto binary instead of string format.\n");
@@ -499,6 +535,59 @@
return NO_ERROR;
}
+status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
+ const int argCount = args.size();
+ int uid;
+ vector<int64_t> configIds;
+ if (argCount == 1) {
+ // Automatically pick the uid and send a broadcast that has no active configs.
+ uid = IPCThreadState::self()->getCallingUid();
+ mProcessor->GetActiveConfigs(uid, configIds);
+ } else {
+ int curArg = 1;
+ if(args[curArg].find("--uid=") == 0) {
+ string uidArgStr(args[curArg].c_str());
+ string uidStr = uidArgStr.substr(6);
+ if (!getUidFromString(uidStr.c_str(), uid)) {
+ dprintf(out, "Invalid UID. Note that the config can only be set for "
+ "other UIDs on eng or userdebug builds.\n");
+ return UNKNOWN_ERROR;
+ }
+ curArg++;
+ } else {
+ uid = IPCThreadState::self()->getCallingUid();
+ }
+ if (curArg == argCount || args[curArg] != "--configs") {
+ VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
+ mProcessor->GetActiveConfigs(uid, configIds);
+ } else {
+ // Flag specified, use the given list of configs.
+ curArg++;
+ for (int i = curArg; i < argCount; i++) {
+ char* endp;
+ int64_t configID = strtoll(args[i].c_str(), &endp, 10);
+ if (endp == args[i].c_str() || *endp != '\0') {
+ dprintf(out, "Error parsing config ID.\n");
+ return UNKNOWN_ERROR;
+ }
+ VLOG("Adding config id %ld", static_cast<long>(configID));
+ configIds.push_back(configID);
+ }
+ }
+ }
+ auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
+ sp<IStatsCompanionService> sc = getStatsCompanionService();
+ if (sc == nullptr) {
+ VLOG("Could not access statsCompanion");
+ } else if (receiver == nullptr) {
+ VLOG("Could not find receiver for uid %d", uid);
+ } else {
+ sc->sendActiveConfigsChangedBroadcast(receiver, configIds);
+ VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
+ }
+ return NO_ERROR;
+}
+
status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
const int argCount = args.size();
if (argCount >= 2) {
@@ -762,7 +851,10 @@
}
bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
- const char* s = args[uidArgIndex].c_str();
+ return getUidFromString(args[uidArgIndex].c_str(), uid);
+}
+
+bool StatsService::getUidFromString(const char* s, int32_t& uid) {
if (*s == '\0') {
return false;
}
@@ -998,8 +1090,13 @@
ENFORCE_DUMP_AND_USAGE_STATS(packageName);
IPCThreadState* ipc = IPCThreadState::self();
- mConfigManager->SetActiveConfigsChangedReceiver(ipc->getCallingUid(), intentSender);
- //TODO: Return the list of configs that are already active
+ int uid = ipc->getCallingUid();
+ mConfigManager->SetActiveConfigsChangedReceiver(uid, intentSender);
+ if (output != nullptr) {
+ mProcessor->GetActiveConfigs(uid, *output);
+ } else {
+ ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
+ }
return Status::ok();
}
@@ -1057,6 +1154,76 @@
return Status::ok();
}
+Status StatsService::registerPullerCallback(int32_t atomTag,
+ const sp<android::os::IStatsPullerCallback>& pullerCallback,
+ const String16& packageName) {
+ ENFORCE_DUMP_AND_USAGE_STATS(packageName);
+
+ VLOG("StatsService::registerPullerCallback called.");
+ mPullerManager->RegisterPullerCallback(atomTag, pullerCallback);
+ return Status::ok();
+}
+
+Status StatsService::unregisterPullerCallback(int32_t atomTag, const String16& packageName) {
+ ENFORCE_DUMP_AND_USAGE_STATS(packageName);
+
+ VLOG("StatsService::unregisterPullerCallback called.");
+ mPullerManager->UnregisterPullerCallback(atomTag);
+ return Status::ok();
+}
+
+Status StatsService::sendBinaryPushStateChangedAtom(const android::String16& trainName,
+ int64_t trainVersionCode, int options,
+ int32_t state,
+ const std::vector<int64_t>& experimentIds) {
+ uid_t uid = IPCThreadState::self()->getCallingUid();
+ // For testing
+ if (uid == AID_ROOT || uid == AID_SYSTEM || uid == AID_SHELL) {
+ return ok();
+ }
+
+ // Caller must be granted these permissions
+ if (!checkCallingPermission(String16(kPermissionDump))) {
+ return exception(binder::Status::EX_SECURITY,
+ StringPrintf("UID %d lacks permission %s", uid, kPermissionDump));
+ }
+ if (!checkCallingPermission(String16(kPermissionUsage))) {
+ return exception(binder::Status::EX_SECURITY,
+ StringPrintf("UID %d lacks permission %s", uid, kPermissionUsage));
+ }
+ // TODO: add verifier permission
+
+ userid_t userId = multiuser_get_user_id(uid);
+
+ bool requiresStaging = options | IStatsManager::FLAG_REQUIRE_STAGING;
+ bool rollbackEnabled = options | IStatsManager::FLAG_ROLLBACK_ENABLED;
+ bool requiresLowLatencyMonitor = options | IStatsManager::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
+
+ ProtoOutputStream proto;
+ uint64_t protoToken = proto.start(FIELD_TYPE_MESSAGE | FIELD_ID_EXPERIMENT_ID_MSG);
+ for (const auto& expId : experimentIds) {
+ proto.write(FIELD_TYPE_INT64 | FIELD_COUNT_REPEATED | FIELD_ID_EXPERIMENT_ID,
+ (long long)expId);
+ }
+ proto.end(protoToken);
+
+ vector<uint8_t> buffer;
+ buffer.resize(proto.size());
+ size_t pos = 0;
+ auto iter = proto.data();
+ while (iter.readBuffer() != NULL) {
+ size_t toRead = iter.currentToRead();
+ std::memcpy(&(buffer[pos]), iter.readBuffer(), toRead);
+ pos += toRead;
+ iter.rp()->move(toRead);
+ }
+ LogEvent event(std::string(String8(trainName).string()), trainVersionCode, requiresStaging,
+ rollbackEnabled, requiresLowLatencyMonitor, state, buffer, userId);
+ mProcessor->OnLogEvent(&event);
+ StorageManager::writeTrainInfo(trainVersionCode, buffer);
+ return Status::ok();
+}
+
hardware::Return<void> StatsService::reportSpeakerImpedance(
const SpeakerImpedance& speakerImpedance) {
LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), speakerImpedance);
diff --git a/cmds/statsd/src/StatsService.h b/cmds/statsd/src/StatsService.h
index cdff50f..d24565a 100644
--- a/cmds/statsd/src/StatsService.h
+++ b/cmds/statsd/src/StatsService.h
@@ -31,6 +31,7 @@
#include <android/frameworks/stats/1.0/types.h>
#include <android/os/BnStatsManager.h>
#include <android/os/IStatsCompanionService.h>
+#include <android/os/IStatsManager.h>
#include <binder/IResultReceiver.h>
#include <utils/Looper.h>
@@ -173,6 +174,26 @@
virtual Status sendAppBreadcrumbAtom(int32_t label, int32_t state) override;
/**
+ * Binder call to register a callback function for a vendor pulled atom.
+ * Note: this atom must NOT have uid as a field.
+ */
+ virtual Status registerPullerCallback(int32_t atomTag,
+ const sp<android::os::IStatsPullerCallback>& pullerCallback,
+ const String16& packageName) override;
+
+ /**
+ * Binder call to unregister any existing callback function for a vendor pulled atom.
+ */
+ virtual Status unregisterPullerCallback(int32_t atomTag, const String16& packageName) override;
+
+ /**
+ * Binder call to log BinaryPushStateChanged atom.
+ */
+ virtual Status sendBinaryPushStateChangedAtom(
+ const android::String16& trainName, int64_t trainVersionCode, int options,
+ int32_t state, const std::vector<int64_t>& experimentIds) override;
+
+ /**
* Binder call to get SpeakerImpedance atom.
*/
virtual Return<void> reportSpeakerImpedance(const SpeakerImpedance& speakerImpedance) override;
@@ -262,6 +283,12 @@
*/
status_t cmd_trigger_broadcast(int outFd, Vector<String8>& args);
+
+ /**
+ * Trigger an active configs changed broadcast.
+ */
+ status_t cmd_trigger_active_config_broadcast(int outFd, Vector<String8>& args);
+
/**
* Handle the config sub-command.
*/
@@ -328,6 +355,15 @@
bool getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid);
/**
+ * Writes the value of uidSting into uid.
+ * Returns whether the uid is reasonable (type uid_t) and whether
+ * 1. it is equal to the calling uid, or
+ * 2. the device is mEngBuild, or
+ * 3. the caller is AID_ROOT and the uid is AID_SHELL (i.e. ROOT can impersonate SHELL).
+ */
+ bool getUidFromString(const char* uidString, int32_t& uid);
+
+ /**
* Adds a configuration after checking permissions and obtaining UID from binder call.
*/
bool addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config);
diff --git a/cmds/statsd/src/atoms.proto b/cmds/statsd/src/atoms.proto
index 7ddb783..873b772 100644
--- a/cmds/statsd/src/atoms.proto
+++ b/cmds/statsd/src/atoms.proto
@@ -31,6 +31,7 @@
import "frameworks/base/core/proto/android/bluetooth/smp/enums.proto";
import "frameworks/base/core/proto/android/debug/enums.proto";
import "frameworks/base/core/proto/android/hardware/biometrics/enums.proto";
+import "frameworks/base/core/proto/android/hardware/sensor/assist/enums.proto";
import "frameworks/base/core/proto/android/net/networkcapabilities.proto";
import "frameworks/base/core/proto/android/os/enums.proto";
import "frameworks/base/core/proto/android/server/connectivity/data_stall_event.proto";
@@ -241,6 +242,9 @@
BluetoothSocketConnectionStateChanged bluetooth_socket_connection_state_changed = 171;
DeviceIdentifierAccessDenied device_identifier_access_denied = 172;
BubbleDeveloperErrorReported bubble_developer_error_reported = 173;
+ AssistGestureStageReported assist_gesture_stage_reported = 174;
+ AssistGestureFeedbackReported assist_gesture_feedback_reported = 175;
+ AssistGestureProgressReported assist_gesture_progress_reported = 176;
}
// Pulled events will start at field 10000.
@@ -297,6 +301,7 @@
NumBiometricsEnrolled num_faces_enrolled = 10048;
RoleHolder role_holder = 10049;
DangerousPermissionState dangerous_permission_state = 10050;
+ TrainInfo train_info = 10051;
}
// DO NOT USE field numbers above 100,000 in AOSP.
@@ -2176,6 +2181,7 @@
SPEAKER_SHORT = 3;
FINGERPRINT_SENSOR_BROKEN = 4;
FINGERPRINT_TOO_MANY_DEAD_PIXELS = 5;
+ DEGRADE = 6;
}
optional int32 failure_code = 3;
}
@@ -3150,6 +3156,13 @@
optional int64 order_id = 2;
}
+/**
+ * Potential experiment ids that goes with a train install.
+ */
+message TrainExperimentIds {
+ repeated int64 experiment_id = 1;
+}
+
/*
* Logs when a binary push state changes.
* Logged by the installer via public api.
@@ -3176,8 +3189,14 @@
INSTALL_FAILURE = 6;
INSTALL_CANCELLED = 7;
INSTALLER_ROLLBACK_REQUESTED = 8;
+ INSTALLER_ROLLBACK_SUCCESS = 9;
+ INSTALLER_ROLLBACK_FAILURE = 10;
}
optional State state = 6;
+ // Possible experiment ids for monitoring this push.
+ optional TrainExperimentIds experiment_ids = 7 [(log_mode) = MODE_BYTES];
+ // user id
+ optional int32 user_id = 8;
}
/** Represents USB port overheat event. */
@@ -5503,3 +5522,45 @@
// True if the package is privileged.
optional bool is_priv_app = 4;
}
+
+/**
+ * Pulls the ongoing mainline install train version code.
+ * Pulled from StatsCompanionService
+ */
+message TrainInfo {
+ optional int64 train_version_code = 1;
+
+ optional TrainExperimentIds train_experiment_id = 2;
+}
+
+/**
+ * Logs the gesture stage changed event.
+ *
+ * Logged from:
+ * frameworks/base/packages/SystemUI/
+ */
+message AssistGestureStageReported {
+ optional android.hardware.sensor.assist.AssistGestureStageEnum gesture_stage = 1;
+}
+
+/**
+ * Logs the feedback type.
+ *
+ * Logged from:
+ * frameworks/base/packages/SystemUI/
+ */
+message AssistGestureFeedbackReported {
+ // Whether or not the gesture was used.
+ optional android.hardware.sensor.assist.AssistGestureFeedbackEnum feedback_type = 1;
+}
+
+/**
+ * Logs the progress.
+ *
+ * Logged from:
+ * frameworks/base/packages/SystemUI/
+ */
+message AssistGestureProgressReported {
+ // [0,100] progress for the assist gesture.
+ optional int32 progress = 1;
+}
diff --git a/cmds/statsd/src/config/ConfigManager.cpp b/cmds/statsd/src/config/ConfigManager.cpp
index aa22333..fc949b4 100644
--- a/cmds/statsd/src/config/ConfigManager.cpp
+++ b/cmds/statsd/src/config/ConfigManager.cpp
@@ -144,10 +144,20 @@
{
lock_guard <mutex> lock(mMutex);
- auto uidIt = mConfigs.find(key.GetUid());
+ auto uid = key.GetUid();
+ auto uidIt = mConfigs.find(uid);
if (uidIt != mConfigs.end() && uidIt->second.find(key) != uidIt->second.end()) {
// Remove from map
uidIt->second.erase(key);
+
+ // No more configs for this uid, lets remove the active configs callback.
+ if (uidIt->second.empty()) {
+ auto itActiveConfigsChangedReceiver = mActiveConfigsChangedReceivers.find(uid);
+ if (itActiveConfigsChangedReceiver != mActiveConfigsChangedReceivers.end()) {
+ mActiveConfigsChangedReceivers.erase(itActiveConfigsChangedReceiver);
+ }
+ }
+
for (const sp<ConfigListener>& listener : mListeners) {
broadcastList.push_back(listener);
}
diff --git a/cmds/statsd/src/external/StatsCallbackPuller.cpp b/cmds/statsd/src/external/StatsCallbackPuller.cpp
new file mode 100644
index 0000000..d718273
--- /dev/null
+++ b/cmds/statsd/src/external/StatsCallbackPuller.cpp
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define DEBUG false // STOPSHIP if true
+#include "Log.h"
+
+#include <android/os/IStatsPullerCallback.h>
+
+#include "StatsCallbackPuller.h"
+#include "logd/LogEvent.h"
+#include "stats_log_util.h"
+
+using namespace android::binder;
+
+namespace android {
+namespace os {
+namespace statsd {
+
+StatsCallbackPuller::StatsCallbackPuller(int tagId, const sp<IStatsPullerCallback>& callback) :
+ StatsPuller(tagId), mCallback(callback) {
+ VLOG("StatsCallbackPuller created for tag %d", tagId);
+}
+
+bool StatsCallbackPuller::PullInternal(vector<shared_ptr<LogEvent>>* data) {
+ VLOG("StatsCallbackPuller called for tag %d", mTagId)
+ if(mCallback == nullptr) {
+ ALOGW("No callback registered");
+ return false;
+ }
+ int64_t wallClockTimeNs = getWallClockNs();
+ int64_t elapsedTimeNs = getElapsedRealtimeNs();
+ vector<StatsLogEventWrapper> returned_value;
+ Status status = mCallback->pullData(mTagId, elapsedTimeNs, wallClockTimeNs, &returned_value);
+ if (!status.isOk()) {
+ ALOGW("StatsCallbackPuller::pull failed for %d", mTagId);
+ return false;
+ }
+ data->clear();
+ for (const StatsLogEventWrapper& it: returned_value) {
+ LogEvent::createLogEvents(it, *data);
+ }
+ VLOG("StatsCallbackPuller::pull succeeded for %d", mTagId);
+ return true;
+}
+
+} // namespace statsd
+} // namespace os
+} // namespace android
diff --git a/cmds/statsd/src/external/StatsCallbackPuller.h b/cmds/statsd/src/external/StatsCallbackPuller.h
new file mode 100644
index 0000000..c4bfa89
--- /dev/null
+++ b/cmds/statsd/src/external/StatsCallbackPuller.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <android/os/IStatsPullerCallback.h>
+#include <utils/String16.h>
+#include "StatsPuller.h"
+
+namespace android {
+namespace os {
+namespace statsd {
+
+class StatsCallbackPuller : public StatsPuller {
+public:
+ explicit StatsCallbackPuller(int tagId, const sp<IStatsPullerCallback>& callback);
+
+private:
+ bool PullInternal(vector<std::shared_ptr<LogEvent> >* data) override;
+ const sp<IStatsPullerCallback> mCallback;
+};
+
+} // namespace statsd
+} // namespace os
+} // namespace android
diff --git a/cmds/statsd/src/external/StatsPuller.cpp b/cmds/statsd/src/external/StatsPuller.cpp
index c7c22ee..9552c0a 100644
--- a/cmds/statsd/src/external/StatsPuller.cpp
+++ b/cmds/statsd/src/external/StatsPuller.cpp
@@ -33,7 +33,7 @@
void StatsPuller::SetUidMap(const sp<UidMap>& uidMap) { mUidMap = uidMap; }
StatsPuller::StatsPuller(const int tagId)
- : mTagId(tagId) {
+ : mTagId(tagId), mLastPullTimeNs(0) {
}
bool StatsPuller::Pull(std::vector<std::shared_ptr<LogEvent>>* data) {
diff --git a/cmds/statsd/src/external/StatsPullerManager.cpp b/cmds/statsd/src/external/StatsPullerManager.cpp
index ecdcd21..ed72b29 100644
--- a/cmds/statsd/src/external/StatsPullerManager.cpp
+++ b/cmds/statsd/src/external/StatsPullerManager.cpp
@@ -18,6 +18,7 @@
#include "Log.h"
#include <android/os/IStatsCompanionService.h>
+#include <android/os/IStatsPullerCallback.h>
#include <cutils/log.h>
#include <math.h>
#include <stdint.h>
@@ -29,6 +30,7 @@
#include "PowerStatsPuller.h"
#include "ResourceHealthManagerPuller.h"
#include "StatsCompanionServicePuller.h"
+#include "StatsCallbackPuller.h"
#include "StatsPullerManager.h"
#include "SubsystemSleepStatePuller.h"
#include "statslog.h"
@@ -49,7 +51,7 @@
// Values smaller than this may require to update the alarm.
const int64_t NO_ALARM_UPDATE = INT64_MAX;
-const std::map<int, PullAtomInfo> StatsPullerManager::kAllPullAtomInfo = {
+std::map<int, PullAtomInfo> StatsPullerManager::kAllPullAtomInfo = {
// wifi_bytes_transfer
{android::util::WIFI_BYTES_TRANSFER,
{.additiveFields = {2, 3, 4, 5},
@@ -420,6 +422,30 @@
return totalCleared;
}
+void StatsPullerManager::RegisterPullerCallback(int32_t atomTag,
+ const sp<IStatsPullerCallback>& callback) {
+ AutoMutex _l(mLock);
+ // Platform pullers cannot be changed.
+ if (atomTag < StatsdStats::kMaxPlatformAtomTag) {
+ VLOG("RegisterPullerCallback: atom tag %d is less than min tag %d",
+ atomTag, StatsdStats::kMaxPlatformAtomTag);
+ return;
+ }
+ VLOG("RegisterPullerCallback: adding puller for tag %d", atomTag);
+ StatsdStats::getInstance().notePullerCallbackRegistrationChanged(atomTag, /*registered=*/true);
+ kAllPullAtomInfo[atomTag] = {.puller = new StatsCallbackPuller(atomTag, callback)};
+}
+
+void StatsPullerManager::UnregisterPullerCallback(int32_t atomTag) {
+ AutoMutex _l(mLock);
+ // Platform pullers cannot be changed.
+ if (atomTag < StatsdStats::kMaxPlatformAtomTag) {
+ return;
+ }
+ StatsdStats::getInstance().notePullerCallbackRegistrationChanged(atomTag, /*registered=*/false);
+ kAllPullAtomInfo.erase(atomTag);
+}
+
} // namespace statsd
} // namespace os
} // namespace android
diff --git a/cmds/statsd/src/external/StatsPullerManager.h b/cmds/statsd/src/external/StatsPullerManager.h
index 807e4af..45f6b35 100644
--- a/cmds/statsd/src/external/StatsPullerManager.h
+++ b/cmds/statsd/src/external/StatsPullerManager.h
@@ -17,6 +17,7 @@
#pragma once
#include <android/os/IStatsCompanionService.h>
+#include <android/os/IStatsPullerCallback.h>
#include <binder/IServiceManager.h>
#include <utils/RefBase.h>
#include <utils/threads.h>
@@ -91,7 +92,12 @@
void SetStatsCompanionService(sp<IStatsCompanionService> statsCompanionService);
- const static std::map<int, PullAtomInfo> kAllPullAtomInfo;
+ void RegisterPullerCallback(int32_t atomTag,
+ const sp<IStatsPullerCallback>& callback);
+
+ void UnregisterPullerCallback(int32_t atomTag);
+
+ static std::map<int, PullAtomInfo> kAllPullAtomInfo;
private:
sp<IStatsCompanionService> mStatsCompanionService = nullptr;
diff --git a/cmds/statsd/src/guardrail/StatsdStats.cpp b/cmds/statsd/src/guardrail/StatsdStats.cpp
index c4034ff..b433c41 100644
--- a/cmds/statsd/src/guardrail/StatsdStats.cpp
+++ b/cmds/statsd/src/guardrail/StatsdStats.cpp
@@ -82,6 +82,8 @@
const int FIELD_ID_CONFIG_STATS_ALERT_STATS = 16;
const int FIELD_ID_CONFIG_STATS_METRIC_DIMENSION_IN_CONDITION_STATS = 17;
const int FIELD_ID_CONFIG_STATS_ANNOTATION = 18;
+const int FIELD_ID_CONFIG_STATS_ACTIVATION = 22;
+const int FIELD_ID_CONFIG_STATS_DEACTIVATION = 23;
const int FIELD_ID_CONFIG_STATS_ANNOTATION_INT64 = 1;
const int FIELD_ID_CONFIG_STATS_ANNOTATION_INT32 = 2;
@@ -206,6 +208,25 @@
it->second->broadcast_sent_time_sec.push_back(timeSec);
}
+void StatsdStats::noteActiveStatusChanged(const ConfigKey& key, bool activated) {
+ noteActiveStatusChanged(key, activated, getWallClockSec());
+}
+
+void StatsdStats::noteActiveStatusChanged(const ConfigKey& key, bool activated, int32_t timeSec) {
+ lock_guard<std::mutex> lock(mLock);
+ auto it = mConfigStats.find(key);
+ if (it == mConfigStats.end()) {
+ ALOGE("Config key %s not found!", key.ToString().c_str());
+ return;
+ }
+ auto& vec = activated ? it->second->activation_time_sec
+ : it->second->deactivation_time_sec;
+ if (vec.size() == kMaxTimestampCount) {
+ vec.pop_front();
+ }
+ vec.push_back(timeSec);
+}
+
void StatsdStats::noteDataDropped(const ConfigKey& key, const size_t totalBytes) {
noteDataDropped(key, totalBytes, getWallClockSec());
}
@@ -423,6 +444,15 @@
mPulledAtomStats[atomId].emptyData++;
}
+void StatsdStats::notePullerCallbackRegistrationChanged(int atomId, bool registered) {
+ lock_guard<std::mutex> lock(mLock);
+ if (registered) {
+ mPulledAtomStats[atomId].registeredCount++;
+ } else {
+ mPulledAtomStats[atomId].unregisteredCount++;
+ }
+}
+
void StatsdStats::noteHardDimensionLimitReached(int64_t metricId) {
lock_guard<std::mutex> lock(mLock);
getAtomMetricStats(metricId).hardDimensionLimitReached++;
@@ -492,6 +522,8 @@
mLogLossStats.clear();
for (auto& config : mConfigStats) {
config.second->broadcast_sent_time_sec.clear();
+ config.second->activation_time_sec.clear();
+ config.second->deactivation_time_sec.clear();
config.second->data_drop_time_sec.clear();
config.second->data_drop_bytes.clear();
config.second->dump_report_stats.clear();
@@ -514,6 +546,8 @@
pullStats.second.dataError = 0;
pullStats.second.pullTimeout = 0;
pullStats.second.pullExceedMaxDelay = 0;
+ pullStats.second.registeredCount = 0;
+ pullStats.second.unregisteredCount = 0;
}
mAtomMetricStats.clear();
}
@@ -547,6 +581,14 @@
dprintf(out, "\tbroadcast time: %d\n", broadcastTime);
}
+ for (const int& activationTime : configStats->activation_time_sec) {
+ dprintf(out, "\tactivation time: %d\n", activationTime);
+ }
+
+ for (const int& deactivationTime : configStats->deactivation_time_sec) {
+ dprintf(out, "\tdeactivation time: %d\n", deactivationTime);
+ }
+
auto dropTimePtr = configStats->data_drop_time_sec.begin();
auto dropBytesPtr = configStats->data_drop_bytes.begin();
for (int i = 0; i < (int)configStats->data_drop_time_sec.size();
@@ -575,6 +617,14 @@
(long long)broadcastTime);
}
+ for (const int& activationTime : configStats->activation_time_sec) {
+ dprintf(out, "\tactivation time: %d\n", activationTime);
+ }
+
+ for (const int& deactivationTime : configStats->deactivation_time_sec) {
+ dprintf(out, "\tdeactivation time: %d\n", deactivationTime);
+ }
+
auto dropTimePtr = configStats->data_drop_time_sec.begin();
auto dropBytesPtr = configStats->data_drop_bytes.begin();
for (int i = 0; i < (int)configStats->data_drop_time_sec.size();
@@ -625,12 +675,14 @@
" (average pull time nanos)%lld, (max pull time nanos)%lld, (average pull delay "
"nanos)%lld, "
" (max pull delay nanos)%lld, (data error)%ld\n"
- " (pull timeout)%ld, (pull exceed max delay)%ld\n",
+ " (pull timeout)%ld, (pull exceed max delay)%ld\n"
+ " (registered count) %ld, (unregistered count) %ld\n",
(int)pair.first, (long)pair.second.totalPull, (long)pair.second.totalPullFromCache,
(long)pair.second.minPullIntervalSec, (long long)pair.second.avgPullTimeNs,
(long long)pair.second.maxPullTimeNs, (long long)pair.second.avgPullDelayNs,
(long long)pair.second.maxPullDelayNs, pair.second.dataError,
- pair.second.pullTimeout, pair.second.pullExceedMaxDelay);
+ pair.second.pullTimeout, pair.second.pullExceedMaxDelay,
+ pair.second.registeredCount, pair.second.unregisteredCount);
}
if (mAnomalyAlarmRegisteredStats > 0) {
@@ -683,6 +735,16 @@
broadcast);
}
+ for (const auto& activation : configStats.activation_time_sec) {
+ proto->write(FIELD_TYPE_INT32 | FIELD_ID_CONFIG_STATS_ACTIVATION | FIELD_COUNT_REPEATED,
+ activation);
+ }
+
+ for (const auto& deactivation : configStats.deactivation_time_sec) {
+ proto->write(FIELD_TYPE_INT32 | FIELD_ID_CONFIG_STATS_DEACTIVATION | FIELD_COUNT_REPEATED,
+ deactivation);
+ }
+
for (const auto& drop_time : configStats.data_drop_time_sec) {
proto->write(FIELD_TYPE_INT32 | FIELD_ID_CONFIG_STATS_DATA_DROP_TIME | FIELD_COUNT_REPEATED,
drop_time);
diff --git a/cmds/statsd/src/guardrail/StatsdStats.h b/cmds/statsd/src/guardrail/StatsdStats.h
index 2999b64..5275c8f 100644
--- a/cmds/statsd/src/guardrail/StatsdStats.h
+++ b/cmds/statsd/src/guardrail/StatsdStats.h
@@ -42,6 +42,13 @@
bool is_valid;
std::list<int32_t> broadcast_sent_time_sec;
+
+ // Times at which this config is activated.
+ std::list<int32_t> activation_time_sec;
+
+ // Times at which this config is deactivated.
+ std::list<int32_t> deactivation_time_sec;
+
std::list<int32_t> data_drop_time_sec;
// Number of bytes dropped at corresponding time.
std::list<int64_t> data_drop_bytes;
@@ -132,6 +139,9 @@
/* Min period between two checks of byte size per config key in nanoseconds. */
static const int64_t kMinByteSizeCheckPeriodNs = 60 * NS_PER_SEC;
+ /* Minimum period between two activation broadcasts in nanoseconds. */
+ static const int64_t kMinActivationBroadcastPeriodNs = 10 * NS_PER_SEC;
+
// Maximum age (30 days) that files on disk can exist in seconds.
static const int kMaxAgeSecond = 60 * 60 * 24 * 30;
@@ -146,6 +156,10 @@
// Max time to do a pull.
static const int64_t kPullMaxDelayNs = 10 * NS_PER_SEC;
+
+ // Max platform atom tag number.
+ static const int32_t kMaxPlatformAtomTag = 100000;
+
/**
* Report a new config has been received and report the static stats about the config.
*
@@ -171,6 +185,13 @@
void noteBroadcastSent(const ConfigKey& key);
/**
+ * Report that a config has become activated or deactivated.
+ * This can be different from whether or not a broadcast is sent if the
+ * guardrail prevented the broadcast from being sent.
+ */
+ void noteActiveStatusChanged(const ConfigKey& key, bool activate);
+
+ /**
* Report a config's metrics data has been dropped.
*/
void noteDataDropped(const ConfigKey& key, const size_t totalBytes);
@@ -340,6 +361,13 @@
void noteEmptyData(int atomId);
/**
+ * Records that a puller callback for the given atomId was registered or unregistered.
+ *
+ * @param registered True if the callback was registered, false if was unregistered.
+ */
+ void notePullerCallbackRegistrationChanged(int atomId, bool registered);
+
+ /**
* Hard limit was reached in the cardinality of an atom
*/
void noteHardDimensionLimitReached(int64_t metricId);
@@ -416,6 +444,8 @@
long statsCompanionPullFailed = 0;
long statsCompanionPullBinderTransactionFailed = 0;
long emptyData = 0;
+ long registeredCount = 0;
+ long unregisteredCount = 0;
} PulledAtomStats;
typedef struct {
@@ -494,6 +524,8 @@
void noteBroadcastSent(const ConfigKey& key, int32_t timeSec);
+ void noteActiveStatusChanged(const ConfigKey& key, bool activate, int32_t timeSec);
+
void addToIceBoxLocked(std::shared_ptr<ConfigStats>& stats);
/**
@@ -511,6 +543,7 @@
FRIEND_TEST(StatsdStatsTest, TestAnomalyMonitor);
FRIEND_TEST(StatsdStatsTest, TestSystemServerCrash);
FRIEND_TEST(StatsdStatsTest, TestPullAtomStats);
+ FRIEND_TEST(StatsdStatsTest, TestAtomMetricsStats);
};
} // namespace statsd
diff --git a/cmds/statsd/src/logd/LogEvent.cpp b/cmds/statsd/src/logd/LogEvent.cpp
index 40a4070..99ebc96 100644
--- a/cmds/statsd/src/logd/LogEvent.cpp
+++ b/cmds/statsd/src/logd/LogEvent.cpp
@@ -20,6 +20,8 @@
#include "stats_log_util.h"
#include "statslog.h"
+#include <binder/IPCThreadState.h>
+
namespace android {
namespace os {
namespace statsd {
@@ -180,6 +182,25 @@
}
}
+LogEvent::LogEvent(const string& trainName, int64_t trainVersionCode, bool requiresStaging,
+ bool rollbackEnabled, bool requiresLowLatencyMonitor, int32_t state,
+ const std::vector<uint8_t>& experimentIds, int32_t userId) {
+ mLogdTimestampNs = getWallClockNs();
+ mElapsedTimestampNs = getElapsedRealtimeNs();
+ mTagId = android::util::BINARY_PUSH_STATE_CHANGED;
+ mLogUid = android::IPCThreadState::self()->getCallingUid();
+
+ mValues.push_back(FieldValue(Field(mTagId, getSimpleField(1)), Value(trainName)));
+ mValues.push_back(FieldValue(Field(mTagId, getSimpleField(2)), Value(trainVersionCode)));
+ mValues.push_back(FieldValue(Field(mTagId, getSimpleField(3)), Value((int)requiresStaging)));
+ mValues.push_back(FieldValue(Field(mTagId, getSimpleField(4)), Value((int)rollbackEnabled)));
+ mValues.push_back(
+ FieldValue(Field(mTagId, getSimpleField(5)), Value((int)requiresLowLatencyMonitor)));
+ mValues.push_back(FieldValue(Field(mTagId, getSimpleField(6)), Value(state)));
+ mValues.push_back(FieldValue(Field(mTagId, getSimpleField(7)), Value(experimentIds)));
+ mValues.push_back(FieldValue(Field(mTagId, getSimpleField(8)), Value(userId)));
+}
+
LogEvent::LogEvent(int64_t wallClockTimestampNs, int64_t elapsedTimestampNs,
const SpeakerImpedance& speakerImpedance) {
mLogdTimestampNs = wallClockTimestampNs;
diff --git a/cmds/statsd/src/logd/LogEvent.h b/cmds/statsd/src/logd/LogEvent.h
index 784376a..6b5fa56 100644
--- a/cmds/statsd/src/logd/LogEvent.h
+++ b/cmds/statsd/src/logd/LogEvent.h
@@ -97,6 +97,11 @@
const std::map<int32_t, std::string>& string_map,
const std::map<int32_t, float>& float_map);
+ // Constructs a BinaryPushStateChanged LogEvent from API call.
+ explicit LogEvent(const std::string& trainName, int64_t trainVersionCode, bool requiresStaging,
+ bool rollbackEnabled, bool requiresLowLatencyMonitor, int32_t state,
+ const std::vector<uint8_t>& experimentIds, int32_t userId);
+
explicit LogEvent(int64_t wallClockTimestampNs, int64_t elapsedTimestampNs,
const SpeakerImpedance& speakerImpedance);
diff --git a/cmds/statsd/src/metrics/MetricProducer.cpp b/cmds/statsd/src/metrics/MetricProducer.cpp
index 495138e..65136ee 100644
--- a/cmds/statsd/src/metrics/MetricProducer.cpp
+++ b/cmds/statsd/src/metrics/MetricProducer.cpp
@@ -94,7 +94,7 @@
void MetricProducer::addActivation(int activationTrackerIndex, int64_t ttl_seconds) {
std::lock_guard<std::mutex> lock(mMutex);
// When a metric producer does not depend on any activation, its mIsActive is true.
- // Therefor, if this is the 1st activation, mIsActive will turn to false. Otherwise it does not
+ // Therefore, if this is the 1st activation, mIsActive will turn to false. Otherwise it does not
// change.
if (mEventActivationMap.empty()) {
mIsActive = false;
@@ -107,7 +107,8 @@
if (it == mEventActivationMap.end()) {
return;
}
- if (mActivationType == MetricActivation::ACTIVATE_ON_BOOT) {
+ if (mActivationType == MetricActivation::ACTIVATE_ON_BOOT &&
+ it->second.state == ActivationState::kNotActive) {
it->second.state = ActivationState::kActiveOnBoot;
return;
}
diff --git a/cmds/statsd/src/metrics/MetricsManager.cpp b/cmds/statsd/src/metrics/MetricsManager.cpp
index 6ed6ab50..4851a8d 100644
--- a/cmds/statsd/src/metrics/MetricsManager.cpp
+++ b/cmds/statsd/src/metrics/MetricsManager.cpp
@@ -118,6 +118,16 @@
ALOGE("This config has too many alerts! Reject!");
mConfigValid = false;
}
+
+ mIsAlwaysActive = (mMetricIndexesWithActivation.size() != mAllMetricProducers.size()) ||
+ (mAllMetricProducers.size() == 0);
+ bool isActive = mIsAlwaysActive;
+ for (int metric : mMetricIndexesWithActivation) {
+ isActive |= mAllMetricProducers[metric]->isActive();
+ }
+ mIsActive = isActive;
+ VLOG("mIsActive is initialized to %d", mIsActive)
+
// no matter whether this config is valid, log it in the stats.
StatsdStats::getInstance().noteConfigReceived(
key, mAllMetricProducers.size(), mAllConditionTrackers.size(), mAllAtomMatchers.size(),
@@ -332,12 +342,14 @@
int tagId = event.GetTagId();
int64_t eventTimeNs = event.GetElapsedTimestampNs();
- bool isActive = false;
+ bool isActive = mIsAlwaysActive;
for (int metric : mMetricIndexesWithActivation) {
mAllMetricProducers[metric]->flushIfExpire(eventTimeNs);
isActive |= mAllMetricProducers[metric]->isActive();
}
+ mIsActive = isActive;
+
if (mTagIds.find(tagId) == mTagIds.end()) {
// not interesting...
return;
diff --git a/cmds/statsd/src/metrics/MetricsManager.h b/cmds/statsd/src/metrics/MetricsManager.h
index cb1cefb..eab1f76 100644
--- a/cmds/statsd/src/metrics/MetricsManager.h
+++ b/cmds/statsd/src/metrics/MetricsManager.h
@@ -128,6 +128,8 @@
// Does not change the state.
virtual size_t byteSize();
+ // Returns whether or not this config is active.
+ // The config is active if any metric in the config is active.
inline bool isActive() const {
return mIsActive;
}
@@ -241,9 +243,12 @@
// The metrics that don't need to be uploaded or even reported.
std::set<int64_t> mNoReportMetricIds;
- // Any metric active means the config is active.
+ // The config is active if any metric in the config is active.
bool mIsActive;
+ // The config is always active if any metric in the config does not have an activation signal.
+ bool mIsAlwaysActive;
+
FRIEND_TEST(WakelockDurationE2eTest, TestAggregatedPredicateDimensions);
FRIEND_TEST(MetricConditionLinkE2eTest, TestMultiplePredicatesAndLinks);
FRIEND_TEST(AttributionE2eTest, TestAttributionMatchAndSliceByFirstUid);
diff --git a/cmds/statsd/src/metrics/ValueMetricProducer.cpp b/cmds/statsd/src/metrics/ValueMetricProducer.cpp
index ac6c27a..851ae99 100644
--- a/cmds/statsd/src/metrics/ValueMetricProducer.cpp
+++ b/cmds/statsd/src/metrics/ValueMetricProducer.cpp
@@ -450,6 +450,17 @@
}
mMatchedMetricDimensionKeys.clear();
mHasGlobalBase = true;
+
+ // If we reach the guardrail, we might have dropped some data which means the bucket is
+ // incomplete.
+ //
+ // The base also needs to be reset. If we do not have the full data, we might
+ // incorrectly compute the diff when mUseZeroDefaultBase is true since an existing key
+ // might be missing from mCurrentSlicedBucket.
+ if (hasReachedGuardRailLimit()) {
+ invalidateCurrentBucket();
+ mCurrentSlicedBucket.clear();
+ }
}
void ValueMetricProducer::dumpStatesLocked(FILE* out, bool verbose) const {
@@ -471,6 +482,10 @@
}
}
+bool ValueMetricProducer::hasReachedGuardRailLimit() const {
+ return mCurrentSlicedBucket.size() >= mDimensionHardLimit;
+}
+
bool ValueMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
// ===========GuardRail==============
// 1. Report the tuple count if the tuple count > soft limit
@@ -481,7 +496,7 @@
size_t newTupleCount = mCurrentSlicedBucket.size() + 1;
StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
// 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
- if (newTupleCount > mDimensionHardLimit) {
+ if (hasReachedGuardRailLimit()) {
ALOGE("ValueMetric %lld dropping data for dimension key %s", (long long)mMetricId,
newKey.toString().c_str());
StatsdStats::getInstance().noteHardDimensionLimitReached(mMetricId);
diff --git a/cmds/statsd/src/metrics/ValueMetricProducer.h b/cmds/statsd/src/metrics/ValueMetricProducer.h
index d1c2315..f26ad85 100644
--- a/cmds/statsd/src/metrics/ValueMetricProducer.h
+++ b/cmds/statsd/src/metrics/ValueMetricProducer.h
@@ -158,6 +158,7 @@
// Util function to check whether the specified dimension hits the guardrail.
bool hitGuardRailLocked(const MetricDimensionKey& newKey);
+ bool hasReachedGuardRailLimit() const;
bool hitFullBucketGuardRailLocked(const MetricDimensionKey& newKey);
@@ -244,6 +245,7 @@
FRIEND_TEST(ValueMetricProducerTest, TestResetBaseOnPullFailAfterConditionChange_EndOfBucket);
FRIEND_TEST(ValueMetricProducerTest, TestResetBaseOnPullTooLate);
FRIEND_TEST(ValueMetricProducerTest, TestInvalidBucketWhenOneConditionFailed);
+ FRIEND_TEST(ValueMetricProducerTest, TestInvalidBucketWhenGuardRailHit);
FRIEND_TEST(ValueMetricProducerTest, TestInvalidBucketWhenInitialPullFailed);
FRIEND_TEST(ValueMetricProducerTest, TestInvalidBucketWhenLastPullFailed);
FRIEND_TEST(ValueMetricProducerTest, TestResetBaseOnPullDelayExceeded);
diff --git a/cmds/statsd/src/stats_log.proto b/cmds/statsd/src/stats_log.proto
index 6a07a3f..f7428a5 100644
--- a/cmds/statsd/src/stats_log.proto
+++ b/cmds/statsd/src/stats_log.proto
@@ -367,6 +367,8 @@
optional int32 field_int32 = 2;
}
repeated Annotation annotation = 18;
+ repeated int32 activation_time_sec = 22;
+ repeated int32 deactivation_time_sec = 23;
}
repeated ConfigStats config_stats = 3;
@@ -407,6 +409,8 @@
optional int64 stats_companion_pull_failed = 13;
optional int64 stats_companion_pull_binder_transaction_failed = 14;
optional int64 empty_data = 15;
+ optional int64 registered_count = 16;
+ optional int64 unregistered_count = 17;
}
repeated PulledAtomStats pulled_atom_stats = 10;
diff --git a/cmds/statsd/src/stats_log_util.cpp b/cmds/statsd/src/stats_log_util.cpp
index aa8cfc5..01043a2 100644
--- a/cmds/statsd/src/stats_log_util.cpp
+++ b/cmds/statsd/src/stats_log_util.cpp
@@ -70,6 +70,8 @@
const int FIELD_ID_STATS_COMPANION_FAILED = 13;
const int FIELD_ID_STATS_COMPANION_BINDER_TRANSACTION_FAILED = 14;
const int FIELD_ID_EMPTY_DATA = 15;
+const int FIELD_ID_PULL_REGISTERED_COUNT = 16;
+const int FIELD_ID_PULL_UNREGISTERED_COUNT = 17;
// for AtomMetricStats proto
const int FIELD_ID_ATOM_METRIC_STATS = 17;
const int FIELD_ID_METRIC_ID = 1;
@@ -480,6 +482,10 @@
(long long)pair.second.statsCompanionPullBinderTransactionFailed);
protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_EMPTY_DATA,
(long long)pair.second.emptyData);
+ protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_PULL_REGISTERED_COUNT,
+ (long long) pair.second.registeredCount);
+ protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_PULL_UNREGISTERED_COUNT,
+ (long long) pair.second.unregisteredCount);
protoOutput->end(token);
}
@@ -487,7 +493,7 @@
util::ProtoOutputStream *protoOutput) {
uint64_t token = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_ATOM_METRIC_STATS |
FIELD_COUNT_REPEATED);
- protoOutput->write(FIELD_TYPE_INT32 | FIELD_ID_METRIC_ID, (int32_t)pair.first);
+ protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_METRIC_ID, (int32_t)pair.first);
protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_HARD_DIMENSION_LIMIT_REACHED,
(long long)pair.second.hardDimensionLimitReached);
protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_LATE_LOG_EVENT_SKIPPED,
diff --git a/cmds/statsd/src/storage/StorageManager.cpp b/cmds/statsd/src/storage/StorageManager.cpp
index 90f641a..fe465ce 100644
--- a/cmds/statsd/src/storage/StorageManager.cpp
+++ b/cmds/statsd/src/storage/StorageManager.cpp
@@ -38,10 +38,13 @@
#define STATS_DATA_DIR "/data/misc/stats-data"
#define STATS_SERVICE_DIR "/data/misc/stats-service"
+#define TRAIN_INFO_DIR "/data/misc/train-info"
// for ConfigMetricsReportList
const int FIELD_ID_REPORTS = 2;
+std::mutex StorageManager::sTrainInfoMutex;
+
using android::base::StringPrintf;
using std::unique_ptr;
@@ -92,6 +95,71 @@
close(fd);
}
+bool StorageManager::writeTrainInfo(int64_t trainVersionCode,
+ const std::vector<uint8_t>& experimentIds) {
+ std::lock_guard<std::mutex> lock(sTrainInfoMutex);
+
+ deleteAllFiles(TRAIN_INFO_DIR);
+
+ string file_name = StringPrintf("%s/%lld", TRAIN_INFO_DIR, (long long)trainVersionCode);
+
+ int fd = open(file_name.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR);
+ if (fd == -1) {
+ VLOG("Attempt to access %s but failed", file_name.c_str());
+ return false;
+ }
+
+ size_t result = write(fd, experimentIds.data(), experimentIds.size());
+ if (result == experimentIds.size()) {
+ VLOG("Successfully wrote %s", file_name.c_str());
+ } else {
+ VLOG("Failed to write %s", file_name.c_str());
+ return false;
+ }
+
+ result = fchown(fd, AID_STATSD, AID_STATSD);
+ if (result) {
+ VLOG("Failed to chown %s to statsd", file_name.c_str());
+ return false;
+ }
+
+ close(fd);
+ return true;
+}
+
+bool StorageManager::readTrainInfo(TrainInfo& trainInfo) {
+ std::lock_guard<std::mutex> lock(sTrainInfoMutex);
+
+ unique_ptr<DIR, decltype(&closedir)> dir(opendir(TRAIN_INFO_DIR), closedir);
+
+ if (dir == NULL) {
+ VLOG("Directory does not exist: %s", TRAIN_INFO_DIR);
+ return false;
+ }
+
+ dirent* de;
+ while ((de = readdir(dir.get()))) {
+ char* name = de->d_name;
+ if (name[0] == '.') {
+ continue;
+ }
+ trainInfo.trainVersionCode = StrToInt64(name);
+ string fullPath = StringPrintf("%s/%s", TRAIN_INFO_DIR, name);
+ int fd = open(fullPath.c_str(), O_RDONLY | O_CLOEXEC);
+ if (fd != -1) {
+ string str;
+ if (android::base::ReadFdToString(fd, &str)) {
+ close(fd);
+ std::copy(str.begin(), str.end(), std::back_inserter(trainInfo.experimentIds));
+ VLOG("Read train info file successful: %s", fullPath.c_str());
+ return true;
+ }
+ }
+ close(fd);
+ }
+ return false;
+}
+
void StorageManager::deleteFile(const char* file) {
if (remove(file) != 0) {
VLOG("Attempt to delete %s but is not found", file);
diff --git a/cmds/statsd/src/storage/StorageManager.h b/cmds/statsd/src/storage/StorageManager.h
index dcf3bb6..d9eca9f 100644
--- a/cmds/statsd/src/storage/StorageManager.h
+++ b/cmds/statsd/src/storage/StorageManager.h
@@ -29,6 +29,11 @@
using android::util::ProtoOutputStream;
+struct TrainInfo {
+ int64_t trainVersionCode;
+ std::vector<uint8_t> experimentIds;
+};
+
class StorageManager : public virtual RefBase {
public:
/**
@@ -37,6 +42,16 @@
static void writeFile(const char* file, const void* buffer, int numBytes);
/**
+ * Writes train info.
+ */
+ static bool writeTrainInfo(int64_t trainVersionCode, const std::vector<uint8_t>& experimentIds);
+
+ /**
+ * Reads train info.
+ */
+ static bool readTrainInfo(TrainInfo& trainInfo);
+
+ /**
* Reads the file content to the buffer.
*/
static bool readFileToString(const char* file, string* content);
@@ -109,6 +124,8 @@
* Prints disk usage statistics about a directory related to statsd.
*/
static void printDirStats(int out, const char* path);
+
+ static std::mutex sTrainInfoMutex;
};
} // namespace statsd
diff --git a/cmds/statsd/statsd.rc b/cmds/statsd/statsd.rc
index e0cbd5d..a98ecd5 100644
--- a/cmds/statsd/statsd.rc
+++ b/cmds/statsd/statsd.rc
@@ -27,3 +27,4 @@
mkdir /data/misc/stats-data/ 0770 statsd system
mkdir /data/misc/stats-service/ 0770 statsd system
mkdir /data/misc/stats-active-metric/ 0770 statsd system
+ mkdir /data/misc/train-info/ 0770 statsd system
diff --git a/cmds/statsd/tests/StatsLogProcessor_test.cpp b/cmds/statsd/tests/StatsLogProcessor_test.cpp
index 60df165..5f3aae3 100644
--- a/cmds/statsd/tests/StatsLogProcessor_test.cpp
+++ b/cmds/statsd/tests/StatsLogProcessor_test.cpp
@@ -65,7 +65,8 @@
sp<AlarmMonitor> periodicAlarmMonitor;
// Construct the processor with a dummy sendBroadcast function that does nothing.
StatsLogProcessor p(m, pullerManager, anomalyAlarmMonitor, periodicAlarmMonitor, 0,
- [](const ConfigKey& key) { return true; });
+ [](const ConfigKey& key) { return true; },
+ [](const int&, const vector<int64_t>&) {return true;});
MockMetricsManager mockMetricsManager;
@@ -88,7 +89,8 @@
[&broadcastCount](const ConfigKey& key) {
broadcastCount++;
return true;
- });
+ },
+ [](const int&, const vector<int64_t>&) {return true;});
MockMetricsManager mockMetricsManager;
@@ -118,7 +120,8 @@
[&broadcastCount](const ConfigKey& key) {
broadcastCount++;
return true;
- });
+ },
+ [](const int&, const vector<int64_t>&) {return true;});
MockMetricsManager mockMetricsManager;
@@ -162,7 +165,8 @@
[&broadcastCount](const ConfigKey& key) {
broadcastCount++;
return true;
- });
+ },
+ [](const int&, const vector<int64_t>&) {return true;});
ConfigKey key(3, 4);
StatsdConfig config = MakeConfig(true);
p.OnConfigUpdated(0, key, config);
@@ -192,7 +196,8 @@
[&broadcastCount](const ConfigKey& key) {
broadcastCount++;
return true;
- });
+ },
+ [](const int&, const vector<int64_t>&) {return true;});
ConfigKey key(3, 4);
StatsdConfig config = MakeConfig(false);
p.OnConfigUpdated(0, key, config);
@@ -218,7 +223,8 @@
[&broadcastCount](const ConfigKey& key) {
broadcastCount++;
return true;
- });
+ },
+ [](const int&, const vector<int64_t>&) {return true;});
ConfigKey key(3, 4);
StatsdConfig config;
auto annotation = config.add_annotation();
diff --git a/cmds/statsd/tests/UidMap_test.cpp b/cmds/statsd/tests/UidMap_test.cpp
index f0d9cf1..c04a40c 100644
--- a/cmds/statsd/tests/UidMap_test.cpp
+++ b/cmds/statsd/tests/UidMap_test.cpp
@@ -45,7 +45,8 @@
sp<AlarmMonitor> subscriberAlarmMonitor;
// Construct the processor with a dummy sendBroadcast function that does nothing.
StatsLogProcessor p(m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, 0,
- [](const ConfigKey& key) { return true; });
+ [](const ConfigKey& key) { return true; },
+ [](const int&, const vector<int64_t>&) {return true;});
LogEvent addEvent(android::util::ISOLATED_UID_CHANGED, 1);
addEvent.write(100); // parent UID
addEvent.write(101); // isolated UID
diff --git a/cmds/statsd/tests/guardrail/StatsdStats_test.cpp b/cmds/statsd/tests/guardrail/StatsdStats_test.cpp
index 6069516..1ff7982 100644
--- a/cmds/statsd/tests/guardrail/StatsdStats_test.cpp
+++ b/cmds/statsd/tests/guardrail/StatsdStats_test.cpp
@@ -133,6 +133,13 @@
stats.noteMetricsReportSent(key, 0);
stats.noteMetricsReportSent(key, 0);
+ // activation_time_sec -> 2
+ stats.noteActiveStatusChanged(key, true);
+ stats.noteActiveStatusChanged(key, true);
+
+ // deactivation_time_sec -> 1
+ stats.noteActiveStatusChanged(key, false);
+
vector<uint8_t> output;
stats.dumpStats(&output, true); // Dump and reset stats
StatsdStatsReport report;
@@ -146,6 +153,8 @@
EXPECT_EQ(123, configReport.data_drop_bytes(0));
EXPECT_EQ(3, configReport.dump_report_time_sec_size());
EXPECT_EQ(3, configReport.dump_report_data_size_size());
+ EXPECT_EQ(2, configReport.activation_time_sec_size());
+ EXPECT_EQ(1, configReport.deactivation_time_sec_size());
EXPECT_EQ(1, configReport.annotation_size());
EXPECT_EQ(123, configReport.annotation(0).field_int64());
EXPECT_EQ(456, configReport.annotation(0).field_int32());
@@ -259,6 +268,10 @@
stats.notePullDelay(android::util::DISK_SPACE, 3335L);
stats.notePull(android::util::DISK_SPACE);
stats.notePullFromCache(android::util::DISK_SPACE);
+ stats.notePullerCallbackRegistrationChanged(android::util::DISK_SPACE, true);
+ stats.notePullerCallbackRegistrationChanged(android::util::DISK_SPACE, false);
+ stats.notePullerCallbackRegistrationChanged(android::util::DISK_SPACE, true);
+
vector<uint8_t> output;
stats.dumpStats(&output, false);
@@ -276,6 +289,41 @@
EXPECT_EQ(3333L, report.pulled_atom_stats(0).max_pull_time_nanos());
EXPECT_EQ(2223L, report.pulled_atom_stats(0).average_pull_delay_nanos());
EXPECT_EQ(3335L, report.pulled_atom_stats(0).max_pull_delay_nanos());
+ EXPECT_EQ(2L, report.pulled_atom_stats(0).registered_count());
+ EXPECT_EQ(1L, report.pulled_atom_stats(0).unregistered_count());
+}
+
+TEST(StatsdStatsTest, TestAtomMetricsStats) {
+ StatsdStats stats;
+ time_t now = time(nullptr);
+ // old event, we get it from the stats buffer. should be ignored.
+ stats.noteBucketDropped(1000L);
+
+ stats.noteBucketBoundaryDelayNs(1000L, -1L);
+ stats.noteBucketBoundaryDelayNs(1000L, -10L);
+ stats.noteBucketBoundaryDelayNs(1000L, 2L);
+
+ stats.noteBucketBoundaryDelayNs(1001L, 1L);
+
+ vector<uint8_t> output;
+ stats.dumpStats(&output, false);
+ StatsdStatsReport report;
+ bool good = report.ParseFromArray(&output[0], output.size());
+ EXPECT_TRUE(good);
+
+ EXPECT_EQ(2, report.atom_metric_stats().size());
+
+ auto atomStats = report.atom_metric_stats(0);
+ EXPECT_EQ(1000L, atomStats.metric_id());
+ EXPECT_EQ(1L, atomStats.bucket_dropped());
+ EXPECT_EQ(-10L, atomStats.min_bucket_boundary_delay_ns());
+ EXPECT_EQ(2L, atomStats.max_bucket_boundary_delay_ns());
+
+ auto atomStats2 = report.atom_metric_stats(1);
+ EXPECT_EQ(1001L, atomStats2.metric_id());
+ EXPECT_EQ(0L, atomStats2.bucket_dropped());
+ EXPECT_EQ(0L, atomStats2.min_bucket_boundary_delay_ns());
+ EXPECT_EQ(1L, atomStats2.max_bucket_boundary_delay_ns());
}
TEST(StatsdStatsTest, TestAnomalyMonitor) {
@@ -305,6 +353,8 @@
stats.noteDataDropped(key, timestamps[i]);
stats.noteBroadcastSent(key, timestamps[i]);
stats.noteMetricsReportSent(key, 0, timestamps[i]);
+ stats.noteActiveStatusChanged(key, true, timestamps[i]);
+ stats.noteActiveStatusChanged(key, false, timestamps[i]);
}
int32_t newTimestamp = 10000;
@@ -313,6 +363,8 @@
stats.noteDataDropped(key, 123, 10000);
stats.noteBroadcastSent(key, 10000);
stats.noteMetricsReportSent(key, 0, 10000);
+ stats.noteActiveStatusChanged(key, true, 10000);
+ stats.noteActiveStatusChanged(key, false, 10000);
EXPECT_TRUE(stats.mConfigStats.find(key) != stats.mConfigStats.end());
const auto& configStats = stats.mConfigStats[key];
@@ -321,17 +373,23 @@
EXPECT_EQ(maxCount, configStats->broadcast_sent_time_sec.size());
EXPECT_EQ(maxCount, configStats->data_drop_time_sec.size());
EXPECT_EQ(maxCount, configStats->dump_report_stats.size());
+ EXPECT_EQ(maxCount, configStats->activation_time_sec.size());
+ EXPECT_EQ(maxCount, configStats->deactivation_time_sec.size());
// the oldest timestamp is the second timestamp in history
EXPECT_EQ(1, configStats->broadcast_sent_time_sec.front());
- EXPECT_EQ(1, configStats->broadcast_sent_time_sec.front());
- EXPECT_EQ(1, configStats->broadcast_sent_time_sec.front());
+ EXPECT_EQ(1, configStats->data_drop_bytes.front());
+ EXPECT_EQ(1, configStats->dump_report_stats.front().first);
+ EXPECT_EQ(1, configStats->activation_time_sec.front());
+ EXPECT_EQ(1, configStats->deactivation_time_sec.front());
// the last timestamp is the newest timestamp.
EXPECT_EQ(newTimestamp, configStats->broadcast_sent_time_sec.back());
EXPECT_EQ(newTimestamp, configStats->data_drop_time_sec.back());
EXPECT_EQ(123, configStats->data_drop_bytes.back());
EXPECT_EQ(newTimestamp, configStats->dump_report_stats.back().first);
+ EXPECT_EQ(newTimestamp, configStats->activation_time_sec.back());
+ EXPECT_EQ(newTimestamp, configStats->deactivation_time_sec.back());
}
TEST(StatsdStatsTest, TestSystemServerCrash) {
diff --git a/cmds/statsd/tests/metrics/ValueMetricProducer_test.cpp b/cmds/statsd/tests/metrics/ValueMetricProducer_test.cpp
index ae3cdbc..572b199 100644
--- a/cmds/statsd/tests/metrics/ValueMetricProducer_test.cpp
+++ b/cmds/statsd/tests/metrics/ValueMetricProducer_test.cpp
@@ -2390,6 +2390,51 @@
EXPECT_EQ(true, valueProducer.mHasGlobalBase);
}
+TEST(ValueMetricProducerTest, TestInvalidBucketWhenGuardRailHit) {
+ ValueMetric metric;
+ metric.set_id(metricId);
+ metric.set_bucket(ONE_MINUTE);
+ metric.mutable_value_field()->set_field(tagId);
+ metric.mutable_value_field()->add_child()->set_field(2);
+ metric.mutable_dimensions_in_what()->set_field(tagId);
+ metric.mutable_dimensions_in_what()->add_child()->set_field(1);
+ metric.set_condition(StringToId("SCREEN_ON"));
+ metric.set_max_pull_delay_sec(INT_MAX);
+
+ UidMap uidMap;
+ SimpleAtomMatcher atomMatcher;
+ atomMatcher.set_atom_id(tagId);
+ sp<EventMatcherWizard> eventMatcherWizard =
+ new EventMatcherWizard({new SimpleLogMatchingTracker(
+ atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)});
+ sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
+ sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>();
+ EXPECT_CALL(*pullerManager, RegisterReceiver(tagId, _, _, _)).WillOnce(Return());
+ EXPECT_CALL(*pullerManager, UnRegisterReceiver(tagId, _)).WillRepeatedly(Return());
+
+ EXPECT_CALL(*pullerManager, Pull(tagId, _))
+ // First onConditionChanged
+ .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) {
+ for (int i = 0; i < 2000; i++) {
+ shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1);
+ event->write(i);
+ event->write(i);
+ event->init();
+ data->push_back(event);
+ }
+ return true;
+ }));
+
+ ValueMetricProducer valueProducer(kConfigKey, metric, 1, wizard, logEventMatcherIndex,
+ eventMatcherWizard, tagId, bucketStartTimeNs,
+ bucketStartTimeNs, pullerManager);
+
+ valueProducer.mCondition = false;
+ valueProducer.onConditionChanged(true, bucket2StartTimeNs + 2);
+ EXPECT_EQ(true, valueProducer.mCurrentBucketIsInvalid);
+ EXPECT_EQ(0UL, valueProducer.mCurrentSlicedBucket.size());
+}
+
TEST(ValueMetricProducerTest, TestInvalidBucketWhenInitialPullFailed) {
ValueMetric metric;
metric.set_id(metricId);
diff --git a/cmds/statsd/tests/statsd_test_util.cpp b/cmds/statsd/tests/statsd_test_util.cpp
index b8b1a1d..2c4f3c7 100644
--- a/cmds/statsd/tests/statsd_test_util.cpp
+++ b/cmds/statsd/tests/statsd_test_util.cpp
@@ -461,7 +461,8 @@
[](const sp<IStatsCompanionService>&){});
sp<StatsLogProcessor> processor =
new StatsLogProcessor(uidMap, pullerManager, anomalyAlarmMonitor, periodicAlarmMonitor,
- timeBaseNs, [](const ConfigKey&) { return true; });
+ timeBaseNs, [](const ConfigKey&) { return true; },
+ [](const int&, const vector<int64_t>&) {return true;});
processor->OnConfigUpdated(currentTimeNs, key, config);
return processor;
}
@@ -826,4 +827,4 @@
} // namespace statsd
} // namespace os
-} // namespace android
\ No newline at end of file
+} // namespace android
diff --git a/cmds/statsd/tests/storage/StorageManager_test.cpp b/cmds/statsd/tests/storage/StorageManager_test.cpp
new file mode 100644
index 0000000..ce957a3
--- /dev/null
+++ b/cmds/statsd/tests/storage/StorageManager_test.cpp
@@ -0,0 +1,52 @@
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <stdio.h>
+#include "src/storage/StorageManager.h"
+
+#ifdef __ANDROID__
+
+namespace android {
+namespace os {
+namespace statsd {
+
+using namespace testing;
+using std::make_shared;
+using std::shared_ptr;
+using std::vector;
+using testing::Contains;
+
+TEST(StorageManagerTest, TrainInfoReadWriteTest) {
+ TrainInfo trainInfo;
+ trainInfo.trainVersionCode = 12345;
+ const char* expIds = "test_ids";
+ trainInfo.experimentIds.assign(expIds, expIds + strlen(expIds));
+
+ StorageManager::writeTrainInfo(trainInfo.trainVersionCode, trainInfo.experimentIds);
+
+ TrainInfo result;
+ StorageManager::readTrainInfo(result);
+ EXPECT_EQ(trainInfo.trainVersionCode, result.trainVersionCode);
+ EXPECT_EQ(trainInfo.experimentIds.size(), result.experimentIds.size());
+ EXPECT_EQ(trainInfo.experimentIds, result.experimentIds);
+}
+
+} // namespace statsd
+} // namespace os
+} // namespace android
+#else
+GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
diff --git a/config/hiddenapi-greylist.txt b/config/hiddenapi-greylist.txt
index 010e447..6fe6ee0 100644
--- a/config/hiddenapi-greylist.txt
+++ b/config/hiddenapi-greylist.txt
@@ -2439,7 +2439,6 @@
Lcom/android/internal/telephony/cat/CatService;->mCmdIf:Lcom/android/internal/telephony/CommandsInterface;
Lcom/android/internal/telephony/cat/CatService;->mContext:Landroid/content/Context;
Lcom/android/internal/telephony/cat/CatService;->mCurrntCmd:Lcom/android/internal/telephony/cat/CatCmdMessage;
-Lcom/android/internal/telephony/cat/CatService;->mHandlerThread:Landroid/os/HandlerThread;
Lcom/android/internal/telephony/cat/CatService;->mMenuCmd:Lcom/android/internal/telephony/cat/CatCmdMessage;
Lcom/android/internal/telephony/cat/CatService;->mMsgDecoder:Lcom/android/internal/telephony/cat/RilMessageDecoder;
Lcom/android/internal/telephony/cat/CatService;->mSlotId:I
@@ -2826,7 +2825,6 @@
Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;-><init>()V
Lcom/android/internal/telephony/GsmCdmaCall;->attachFake(Lcom/android/internal/telephony/Connection;Lcom/android/internal/telephony/Call$State;)V
Lcom/android/internal/telephony/GsmCdmaCallTracker;->clearDisconnected()V
-Lcom/android/internal/telephony/GsmCdmaCallTracker;->dialThreeWay(Ljava/lang/String;)Lcom/android/internal/telephony/Connection;
Lcom/android/internal/telephony/GsmCdmaCallTracker;->disableDataCallInEmergencyCall(Ljava/lang/String;)V
Lcom/android/internal/telephony/GsmCdmaCallTracker;->fakeHoldForegroundBeforeDial()V
Lcom/android/internal/telephony/GsmCdmaCallTracker;->getPhone()Lcom/android/internal/telephony/GsmCdmaPhone;
diff --git a/core/java/android/accessibilityservice/OWNERS b/core/java/android/accessibilityservice/OWNERS
new file mode 100644
index 0000000..265674a
--- /dev/null
+++ b/core/java/android/accessibilityservice/OWNERS
@@ -0,0 +1,3 @@
+svetoslavganov@google.com
+pweaver@google.com
+rhedjao@google.com
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index 0eadd1d..5f778da4 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -65,6 +65,7 @@
import android.os.BadParcelableException;
import android.os.Build;
import android.os.Bundle;
+import android.os.GraphicsEnvironment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
@@ -7708,6 +7709,8 @@
}
}
+ GraphicsEnvironment.getInstance().showAngleInUseDialogBox(this);
+
mActivityTransitionState.enterReady(this);
dispatchActivityPostStarted();
}
diff --git a/core/java/android/app/ActivityManager.java b/core/java/android/app/ActivityManager.java
index db3b720..ca3c726 100644
--- a/core/java/android/app/ActivityManager.java
+++ b/core/java/android/app/ActivityManager.java
@@ -2019,8 +2019,9 @@
return getTaskService().isActivityStartAllowedOnDisplay(displayId, intent,
intent.resolveTypeIfNeeded(context.getContentResolver()), context.getUserId());
} catch (RemoteException e) {
- throw new RuntimeException("Failure from system", e);
+ e.rethrowFromSystemServer();
}
+ return false;
}
/**
diff --git a/core/java/android/app/IActivityTaskManager.aidl b/core/java/android/app/IActivityTaskManager.aidl
index db6ad3d..2b765b2 100644
--- a/core/java/android/app/IActivityTaskManager.aidl
+++ b/core/java/android/app/IActivityTaskManager.aidl
@@ -247,8 +247,20 @@
boolean preserveWindows, boolean animate, int animationDuration);
boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode, boolean toTop,
boolean animate, in Rect initialBounds, boolean showRecents);
-
-
+ /**
+ * Use the offset to adjust the stack boundary with animation.
+ *
+ * @param stackId Id of the stack to adjust.
+ * @param compareBounds Offset is only applied if the current pinned stack bounds is equal to
+ * the compareBounds.
+ * @param xOffset The horizontal offset.
+ * @param yOffset The vertical offset.
+ * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
+ * default animation duration should be used.
+ * @throws RemoteException
+ */
+ void offsetPinnedStackBounds(int stackId, in Rect compareBounds, int xOffset, int yOffset,
+ int animationDuration);
/**
* Removes stacks in the input windowing modes from the system if they are of activity type
* ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
diff --git a/core/java/android/app/LoadedApk.java b/core/java/android/app/LoadedApk.java
index d46dbed..5c4c005 100644
--- a/core/java/android/app/LoadedApk.java
+++ b/core/java/android/app/LoadedApk.java
@@ -870,8 +870,9 @@
}
}
- // /vendor/lib, /odm/lib and /product/lib are added to the native lib search
- // paths of the classloader. Note that this is done AFTER the classloader is
+ // /aepx/com.android.runtime/lib, /vendor/lib, /odm/lib and /product/lib
+ // are added to the native lib search paths of the classloader.
+ // Note that this is done AFTER the classloader is
// created by ApplicationLoaders.getDefault().getClassLoader(...). The
// reason is because if we have added the paths when creating the classloader
// above, the paths are also added to the search path of the linker namespace
@@ -888,8 +889,11 @@
// System.loadLibrary(). In order to prevent the problem, we explicitly
// add the paths only to the classloader, and not to the native loader
// (linker namespace).
- List<String> extraLibPaths = new ArrayList<>(3);
+ List<String> extraLibPaths = new ArrayList<>(4);
String abiSuffix = VMRuntime.getRuntime().is64Bit() ? "64" : "";
+ if (!defaultSearchPaths.contains("/apex/com.android.runtime/lib")) {
+ extraLibPaths.add("/apex/com.android.runtime/lib" + abiSuffix);
+ }
if (!defaultSearchPaths.contains("/vendor/lib")) {
extraLibPaths.add("/vendor/lib" + abiSuffix);
}
diff --git a/core/java/android/app/StatsManager.java b/core/java/android/app/StatsManager.java
index 3119b37..7746148 100644
--- a/core/java/android/app/StatsManager.java
+++ b/core/java/android/app/StatsManager.java
@@ -24,6 +24,7 @@
import android.content.Context;
import android.os.IBinder;
import android.os.IStatsManager;
+import android.os.IStatsPullerCallback;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.util.AndroidException;
@@ -408,6 +409,39 @@
}
}
+ /**
+ * Registers a callback for an atom when that atom is to be pulled. The stats service will
+ * invoke pullData in the callback when the stats service determines that this atom needs to be
+ * pulled. Currently, this only works for atoms with tags above 100,000 that do not have a uid.
+ *
+ * @param atomTag The tag of the atom for this puller callback. Must be at least 100000.
+ * @param callback The callback to be invoked when the stats service pulls the atom.
+ * @throws StatsUnavailableException if unsuccessful due to failing to connect to stats service
+ *
+ * @hide
+ */
+ @RequiresPermission(allOf = { DUMP, PACKAGE_USAGE_STATS })
+ public void setPullerCallback(int atomTag, IStatsPullerCallback callback)
+ throws StatsUnavailableException {
+ synchronized (this) {
+ try {
+ IStatsManager service = getIStatsManagerLocked();
+ if (callback == null) {
+ service.unregisterPullerCallback(atomTag, mContext.getOpPackageName());
+ } else {
+ service.registerPullerCallback(atomTag, callback,
+ mContext.getOpPackageName());
+ }
+
+ } catch (RemoteException e) {
+ Slog.e(TAG, "Failed to connect to statsd when registering data listener.");
+ throw new StatsUnavailableException("could not connect", e);
+ } catch (SecurityException e) {
+ throw new StatsUnavailableException(e.getMessage(), e);
+ }
+ }
+ }
+
private class StatsdDeathRecipient implements IBinder.DeathRecipient {
@Override
public void binderDied() {
diff --git a/core/java/android/app/TaskInfo.java b/core/java/android/app/TaskInfo.java
index 077b177..dd00e5a 100644
--- a/core/java/android/app/TaskInfo.java
+++ b/core/java/android/app/TaskInfo.java
@@ -97,6 +97,12 @@
public long lastActiveTime;
/**
+ * The id of the display this task is associated with.
+ * @hide
+ */
+ public int displayId;
+
+ /**
* The recent activity values for the highest activity in the stack to have set the values.
* {@link Activity#setTaskDescription(android.app.ActivityManager.TaskDescription)}.
*/
@@ -152,6 +158,7 @@
userId = source.readInt();
stackId = source.readInt();
taskId = source.readInt();
+ displayId = source.readInt();
isRunning = source.readBoolean();
baseIntent = source.readInt() != 0
? Intent.CREATOR.createFromParcel(source)
@@ -179,6 +186,7 @@
dest.writeInt(userId);
dest.writeInt(stackId);
dest.writeInt(taskId);
+ dest.writeInt(displayId);
dest.writeBoolean(isRunning);
if (baseIntent != null) {
@@ -209,6 +217,7 @@
@Override
public String toString() {
return "TaskInfo{userId=" + userId + " stackId=" + stackId + " taskId=" + taskId
+ + " displayId=" + displayId
+ " isRunning=" + isRunning
+ " baseIntent=" + baseIntent + " baseActivity=" + baseActivity
+ " topActivity=" + topActivity + " origActivity=" + origActivity
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index 8861151..806536b 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -1376,7 +1376,7 @@
* complexity, and use this activity with extra {@link #EXTRA_PASSWORD_COMPLEXITY} to suggest
* to users how complex the app wants the new screen lock to be. Note that both {@link
* #getPasswordComplexity()} and the extra {@link #EXTRA_PASSWORD_COMPLEXITY} require the
- * calling app to have the permission {@link permission#GET_AND_REQUEST_SCREEN_LOCK_COMPLEXITY}.
+ * calling app to have the permission {@link permission#REQUEST_SCREEN_LOCK_COMPLEXITY}.
*
* <p>If the intent is launched from within a managed profile with a profile
* owner built against {@link android.os.Build.VERSION_CODES#M} or before,
@@ -1404,7 +1404,7 @@
*
* <p>If an invalid value is used, it will be treated as {@link #PASSWORD_COMPLEXITY_NONE}.
*/
- @RequiresPermission(android.Manifest.permission.GET_AND_REQUEST_SCREEN_LOCK_COMPLEXITY)
+ @RequiresPermission(android.Manifest.permission.REQUEST_SCREEN_LOCK_COMPLEXITY)
public static final String EXTRA_PASSWORD_COMPLEXITY =
"android.app.extra.PASSWORD_COMPLEXITY";
@@ -2125,7 +2125,7 @@
* Callback used in {@link #installSystemUpdate} to indicate that there was an error while
* trying to install an update.
*/
- public abstract static class InstallUpdateCallback {
+ public abstract static class InstallSystemUpdateCallback {
/** Represents an unknown error while trying to install an update. */
public static final int UPDATE_ERROR_UNKNOWN = 1;
@@ -2144,7 +2144,12 @@
/** Represents the battery being too low to apply an update. */
public static final int UPDATE_ERROR_BATTERY_LOW = 5;
- /** Method invoked when there was an error while installing an update. */
+ /**
+ * Method invoked when there was an error while installing an update.
+ *
+ * <p>The given error message is not intended to be user-facing. It is intended to be
+ * reported back to the IT admin to be read.
+ */
public void onInstallUpdateError(
@InstallUpdateCallbackErrorConstants int errorCode, String errorMessage) {
}
@@ -2154,11 +2159,11 @@
* @hide
*/
@IntDef(prefix = { "UPDATE_ERROR_" }, value = {
- InstallUpdateCallback.UPDATE_ERROR_UNKNOWN,
- InstallUpdateCallback.UPDATE_ERROR_INCORRECT_OS_VERSION,
- InstallUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID,
- InstallUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
- InstallUpdateCallback.UPDATE_ERROR_BATTERY_LOW
+ InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN,
+ InstallSystemUpdateCallback.UPDATE_ERROR_INCORRECT_OS_VERSION,
+ InstallSystemUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID,
+ InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
+ InstallSystemUpdateCallback.UPDATE_ERROR_BATTERY_LOW
})
@Retention(RetentionPolicy.SOURCE)
public @interface InstallUpdateCallbackErrorConstants {}
@@ -3346,10 +3351,10 @@
*
* @throws IllegalStateException if the user is not unlocked.
* @throws SecurityException if the calling application does not have the permission
- * {@link permission#GET_AND_REQUEST_SCREEN_LOCK_COMPLEXITY}
+ * {@link permission#REQUEST_SCREEN_LOCK_COMPLEXITY}
*/
@PasswordComplexity
- @RequiresPermission(android.Manifest.permission.GET_AND_REQUEST_SCREEN_LOCK_COMPLEXITY)
+ @RequiresPermission(android.Manifest.permission.REQUEST_SCREEN_LOCK_COMPLEXITY)
public int getPasswordComplexity() {
throwIfParentInstance("getPasswordComplexity");
if (mService == null) {
@@ -10431,9 +10436,9 @@
* doesn't necessarily mean that the update has been applied successfully. The caller should
* additionally check the system version with {@link android.os.Build#FINGERPRINT} or {@link
* android.os.Build.VERSION}. If an error occurs during processing the OTA before the reboot,
- * the caller will be notified by {@link InstallUpdateCallback}. If device does not have
+ * the caller will be notified by {@link InstallSystemUpdateCallback}. If device does not have
* sufficient battery level, the installation will fail with error {@link
- * InstallUpdateCallback#UPDATE_ERROR_BATTERY_LOW}.
+ * InstallSystemUpdateCallback#UPDATE_ERROR_BATTERY_LOW}.
*
* @param admin The {@link DeviceAdminReceiver} that this request is associated with.
* @param updateFilePath An Uri of the file that contains the update. The file should be
@@ -10445,7 +10450,7 @@
public void installSystemUpdate(
@NonNull ComponentName admin, @NonNull Uri updateFilePath,
@NonNull @CallbackExecutor Executor executor,
- @NonNull InstallUpdateCallback callback) {
+ @NonNull InstallSystemUpdateCallback callback) {
throwIfParentInstance("installUpdate");
if (mService == null) {
return;
@@ -10465,19 +10470,20 @@
} catch (FileNotFoundException e) {
Log.w(TAG, e);
executeCallback(
- InstallUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND, Log.getStackTraceString(e),
+ InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
+ Log.getStackTraceString(e),
executor, callback);
} catch (IOException e) {
Log.w(TAG, e);
executeCallback(
- InstallUpdateCallback.UPDATE_ERROR_UNKNOWN, Log.getStackTraceString(e),
+ InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN, Log.getStackTraceString(e),
executor, callback);
}
}
private void executeCallback(int errorCode, String errorMessage,
@NonNull @CallbackExecutor Executor executor,
- @NonNull InstallUpdateCallback callback) {
+ @NonNull InstallSystemUpdateCallback callback) {
executor.execute(() -> callback.onInstallUpdateError(errorCode, errorMessage));
}
@@ -10537,6 +10543,8 @@
* @hide
*/
@SystemApi
+ @RequiresPermission(value = android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS,
+ conditional = true)
public void setProfileOwnerCanAccessDeviceIdsForUser(
@NonNull ComponentName who, @NonNull UserHandle userHandle) {
if (mService == null) {
diff --git a/core/java/android/app/role/RoleManager.java b/core/java/android/app/role/RoleManager.java
index 04d5c5a..edd3ef98 100644
--- a/core/java/android/app/role/RoleManager.java
+++ b/core/java/android/app/role/RoleManager.java
@@ -69,6 +69,22 @@
private static final String LOG_TAG = RoleManager.class.getSimpleName();
/**
+ * The name of the assistant app role.
+ *
+ * @hide
+ */
+ @SystemApi
+ @TestApi
+ public static final String ROLE_ASSISTANT = "android.app.role.ASSISTANT";
+
+ /**
+ * The name of the browser role.
+ *
+ * @see Intent#CATEGORY_APP_BROWSER
+ */
+ public static final String ROLE_BROWSER = "android.app.role.BROWSER";
+
+ /**
* The name of the dialer role.
*
* @see Intent#ACTION_DIAL
@@ -83,25 +99,11 @@
public static final String ROLE_SMS = "android.app.role.SMS";
/**
- * The name of the browser role.
+ * The name of the emergency role
*
- * @see Intent#CATEGORY_APP_BROWSER
+ * @see android.telephony.TelephonyManager#ACTION_EMERGENCY_ASSISTANCE
*/
- public static final String ROLE_BROWSER = "android.app.role.BROWSER";
-
- /**
- * The name of the gallery role.
- *
- * @see Intent#CATEGORY_APP_GALLERY
- */
- public static final String ROLE_GALLERY = "android.app.role.GALLERY";
-
- /**
- * The name of the music player role.
- *
- * @see Intent#CATEGORY_APP_MUSIC
- */
- public static final String ROLE_MUSIC = "android.app.role.MUSIC";
+ public static final String ROLE_EMERGENCY = "android.app.role.EMERGENCY";
/**
* The name of the home role.
@@ -111,11 +113,18 @@
public static final String ROLE_HOME = "android.app.role.HOME";
/**
- * The name of the emergency role
+ * The name of the music player role.
*
- * @see android.telephony.TelephonyManager#ACTION_EMERGENCY_ASSISTANCE
+ * @see Intent#CATEGORY_APP_MUSIC
*/
- public static final String ROLE_EMERGENCY = "android.app.role.EMERGENCY";
+ public static final String ROLE_MUSIC = "android.app.role.MUSIC";
+
+ /**
+ * The name of the gallery role.
+ *
+ * @see Intent#CATEGORY_APP_GALLERY
+ */
+ public static final String ROLE_GALLERY = "android.app.role.GALLERY";
/**
* The name of the car mode dialer app role.
@@ -173,15 +182,6 @@
public static final String ROLE_CALL_COMPANION = "android.app.role.CALL_COMPANION";
/**
- * The name of the assistant app role.
- *
- * @hide
- */
- @SystemApi
- @TestApi
- public static final String ROLE_ASSISTANT = "android.app.role.ASSISTANT";
-
- /**
* @hide
*/
@IntDef(flag = true, value = { MANAGE_HOLDERS_FLAG_DONT_KILL_APP })
diff --git a/core/java/android/app/usage/UsageStatsManager.java b/core/java/android/app/usage/UsageStatsManager.java
index 51397a2..dc5bdc6 100644
--- a/core/java/android/app/usage/UsageStatsManager.java
+++ b/core/java/android/app/usage/UsageStatsManager.java
@@ -745,7 +745,11 @@
* Registering an {@code observerId} that was already registered will override the previous one.
* No more than 1000 unique {@code observerId} may be registered by a single uid
* at any one time.
- * A limit may be unregistered via {@link #unregisterAppUsageLimitObserver}
+ * A limit is not cleared when the usage time is exceeded. It needs to be unregistered via
+ * {@link #unregisterAppUsageLimitObserver}.
+ * <p>
+ * Note: usage limits are not persisted in the system and are cleared on reboots. Callers
+ * must reset any limits that they need on reboots.
* <p>
* This method is similar to {@link #registerAppUsageObserver}, but the usage limit set here
* will be visible to the launcher so that it can report the limit to the user and how much
@@ -757,12 +761,15 @@
* @param observedEntities The list of packages and token to observe for usage time. Cannot be
* null and must include at least one package or token.
* @param timeLimit The total time the set of apps can be in the foreground before the
- * callbackIntent is delivered. Must be at least one minute.
+ * callbackIntent is delivered. Must be at least one minute. Note: a limit of
+ * 0 can be set to indicate that the user has already exhausted the limit for
+ * a group, in which case, the given {@code callbackIntent} will be ignored.
* @param timeUnit The unit for time specified in {@code timeLimit}. Cannot be null.
- * @param callbackIntent The PendingIntent that will be dispatched when the usage limit is
+ * @param callbackIntent The PendingIntent that will be dispatched when the usage limit is
* exceeded by the group of apps. The delivered Intent will also contain
* the extras {@link #EXTRA_OBSERVER_ID}, {@link #EXTRA_TIME_LIMIT} and
- * {@link #EXTRA_TIME_USED}. Cannot be null.
+ * {@link #EXTRA_TIME_USED}. Cannot be {@code null} unless the observer is
+ * being registered with a {@code timeLimit} of 0.
* @throws SecurityException if the caller doesn't have both SUSPEND_APPS and OBSERVE_APP_USAGE
* permissions.
* @hide
@@ -772,7 +779,7 @@
android.Manifest.permission.SUSPEND_APPS,
android.Manifest.permission.OBSERVE_APP_USAGE})
public void registerAppUsageLimitObserver(int observerId, @NonNull String[] observedEntities,
- long timeLimit, @NonNull TimeUnit timeUnit, @NonNull PendingIntent callbackIntent) {
+ long timeLimit, @NonNull TimeUnit timeUnit, PendingIntent callbackIntent) {
try {
mService.registerAppUsageLimitObserver(observerId, observedEntities,
timeUnit.toMillis(timeLimit), callbackIntent, mContext.getOpPackageName());
diff --git a/core/java/android/content/ContentResolver.java b/core/java/android/content/ContentResolver.java
index f1bfe86..7672ccf 100644
--- a/core/java/android/content/ContentResolver.java
+++ b/core/java/android/content/ContentResolver.java
@@ -2998,7 +2998,9 @@
*
* @param key the key to add
* @param value the value to add
+ * {@hide}
*/
+ @SystemApi
public void putCache(Uri key, Bundle value) {
try {
getContentService().putCache(mContext.getPackageName(), key, value,
@@ -3014,7 +3016,9 @@
* @param key the key to get the value
* @return the matched value. If the key doesn't exist, will return null.
* @see #putCache(Uri, Bundle)
+ * {@hide}
*/
+ @SystemApi
public Bundle getCache(Uri key) {
try {
final Bundle bundle = getContentService().getCache(mContext.getPackageName(), key,
diff --git a/core/java/android/content/pm/ActivityInfo.java b/core/java/android/content/pm/ActivityInfo.java
index 47034a6..7cc4391 100644
--- a/core/java/android/content/pm/ActivityInfo.java
+++ b/core/java/android/content/pm/ActivityInfo.java
@@ -1029,10 +1029,18 @@
}
/**
+ * Returns true if the activity has maximum or minimum aspect ratio.
+ * @hide
+ */
+ public boolean hasFixedAspectRatio() {
+ return maxAspectRatio != 0 || minAspectRatio != 0;
+ }
+
+ /**
* Returns true if the activity's orientation is fixed.
* @hide
*/
- boolean isFixedOrientation() {
+ public boolean isFixedOrientation() {
return isFixedOrientationLandscape() || isFixedOrientationPortrait()
|| screenOrientation == SCREEN_ORIENTATION_LOCKED;
}
diff --git a/core/java/android/content/pm/ApplicationInfo.java b/core/java/android/content/pm/ApplicationInfo.java
index b27c5dc..6c6fcb2 100644
--- a/core/java/android/content/pm/ApplicationInfo.java
+++ b/core/java/android/content/pm/ApplicationInfo.java
@@ -650,6 +650,18 @@
*/
public static final int PRIVATE_FLAG_USE_EMBEDDED_DEX = 1 << 25;
+ /**
+ * Value for {@link #privateFlags}: indicates whether this application's data will be cleared
+ * on a failed restore.
+ *
+ * <p>Comes from the
+ * android.R.styleable#AndroidManifestApplication_allowClearUserDataOnFailedRestore attribute
+ * of the <application> tag.
+ *
+ * @hide
+ */
+ public static final int PRIVATE_FLAG_ALLOW_CLEAR_USER_DATA_ON_FAILED_RESTORE = 1 << 26;
+
/** @hide */
@IntDef(flag = true, prefix = { "PRIVATE_FLAG_" }, value = {
PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_RESIZEABLE,
@@ -676,6 +688,7 @@
PRIVATE_FLAG_VENDOR,
PRIVATE_FLAG_VIRTUAL_PRELOAD,
PRIVATE_FLAG_HAS_FRAGILE_USER_DATA,
+ PRIVATE_FLAG_ALLOW_CLEAR_USER_DATA_ON_FAILED_RESTORE
})
@Retention(RetentionPolicy.SOURCE)
public @interface ApplicationInfoPrivateFlags {}
diff --git a/core/java/android/content/pm/PackageInstaller.java b/core/java/android/content/pm/PackageInstaller.java
index 0ac4f64..8095473 100644
--- a/core/java/android/content/pm/PackageInstaller.java
+++ b/core/java/android/content/pm/PackageInstaller.java
@@ -791,11 +791,6 @@
* individual session IDs can be added with {@link #addChildSessionId(int)}
* and commit of the multi-package session will result in all child sessions
* being committed atomically.
- * <p>
- * If a package requires to be installed only at reboot, the session should
- * be marked as a staged session by calling {@link SessionParams#setStaged()}
- * with {@code true}. This can also apply to a multi-package session, in
- * which case all the packages in the session will be applied at reboot.
*/
public static class Session implements Closeable {
/** {@hide} */
@@ -1539,7 +1534,11 @@
* Staged sessions are scheduled to be installed at next reboot. Staged sessions can also be
* multi-package. In that case, if any of the children sessions fail to install at reboot,
* all the other children sessions are aborted as well.
+ *
+ * {@hide}
*/
+ @SystemApi
+ @RequiresPermission(Manifest.permission.INSTALL_PACKAGES)
public void setStaged() {
this.isStaged = true;
}
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index eaf6c5a..3ea78df 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -5910,24 +5910,24 @@
/**
* Flag to denote no restrictions. This should be used to clear any restrictions that may have
* been previously set for the package.
- * @see PackageManager.DistractionRestriction
* @hide
+ * @see #setDistractingPackageRestrictions(String[], int)
*/
@SystemApi
public static final int RESTRICTION_NONE = 0x0;
/**
* Flag to denote that a package should be hidden from any suggestions to the user.
- * @see PackageManager.DistractionRestriction
* @hide
+ * @see #setDistractingPackageRestrictions(String[], int)
*/
@SystemApi
public static final int RESTRICTION_HIDE_FROM_SUGGESTIONS = 0x00000001;
/**
* Flag to denote that a package's notifications should be hidden.
- * @see PackageManager.DistractionRestriction
* @hide
+ * @see #setDistractingPackageRestrictions(String[], int)
*/
@SystemApi
public static final int RESTRICTION_HIDE_NOTIFICATIONS = 0x00000002;
@@ -5939,7 +5939,6 @@
* @see #setDistractingPackageRestrictions(String[], int)
* @hide
*/
- @SystemApi
@IntDef(flag = true, prefix = {"RESTRICTION_"}, value = {
RESTRICTION_NONE,
RESTRICTION_HIDE_FROM_SUGGESTIONS,
@@ -5957,14 +5956,16 @@
* <p>The caller must hold {@link android.Manifest.permission#SUSPEND_APPS} to use this API.
*
* @param packages Packages to mark as distracting.
- * @param restrictionFlags Any combination of {@link DistractionRestriction restrictions} to
- * impose on the given packages. {@link #RESTRICTION_NONE} can be used
- * to clear any existing restrictions.
+ * @param restrictionFlags Any combination of restrictions to impose on the given packages.
+ * {@link #RESTRICTION_NONE} can be used to clear any existing
+ * restrictions.
* @return A list of packages that could not have the {@code restrictionFlags} set. The system
* may prevent restricting critical packages to preserve normal device function.
*
- * @see DistractionRestriction
* @hide
+ * @see #RESTRICTION_NONE
+ * @see #RESTRICTION_HIDE_FROM_SUGGESTIONS
+ * @see #RESTRICTION_HIDE_NOTIFICATIONS
*/
@SystemApi
@RequiresPermission(android.Manifest.permission.SUSPEND_APPS)
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index 96b6eb52..0abd5ea 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -3747,6 +3747,13 @@
ai.privateFlags |= PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION;
}
+ if (sa.getBoolean(
+ com.android.internal.R.styleable
+ .AndroidManifestApplication_allowClearUserDataOnFailedRestore,
+ true)) {
+ ai.privateFlags |= ApplicationInfo.PRIVATE_FLAG_ALLOW_CLEAR_USER_DATA_ON_FAILED_RESTORE;
+ }
+
ai.maxAspectRatio = sa.getFloat(R.styleable.AndroidManifestApplication_maxAspectRatio, 0);
ai.minAspectRatio = sa.getFloat(R.styleable.AndroidManifestApplication_minAspectRatio, 0);
diff --git a/core/java/android/content/pm/ShortcutInfo.java b/core/java/android/content/pm/ShortcutInfo.java
index fe68b8a..b155325 100644
--- a/core/java/android/content/pm/ShortcutInfo.java
+++ b/core/java/android/content/pm/ShortcutInfo.java
@@ -2273,7 +2273,8 @@
CharSequence disabledMessage, int disabledMessageResId, String disabledMessageResName,
Set<String> categories, Intent[] intentsWithExtras, int rank, PersistableBundle extras,
long lastChangedTimestamp,
- int flags, int iconResId, String iconResName, String bitmapPath, int disabledReason) {
+ int flags, int iconResId, String iconResName, String bitmapPath, int disabledReason,
+ Person[] persons) {
mUserId = userId;
mId = id;
mPackageName = packageName;
@@ -2299,5 +2300,6 @@
mIconResName = iconResName;
mBitmapPath = bitmapPath;
mDisabledReason = disabledReason;
+ mPersons = persons;
}
}
diff --git a/core/java/android/hardware/display/ColorDisplayManager.java b/core/java/android/hardware/display/ColorDisplayManager.java
index 27f0b04..f413d7c 100644
--- a/core/java/android/hardware/display/ColorDisplayManager.java
+++ b/core/java/android/hardware/display/ColorDisplayManager.java
@@ -365,6 +365,17 @@
}
/**
+ * Gets whether or not a non-default saturation level is currently applied to the display.
+ *
+ * @return {@code true} if the display is not at full saturation
+ * @hide
+ */
+ @RequiresPermission(Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS)
+ public boolean isSaturationActivated() {
+ return mManager.isSaturationActivated();
+ }
+
+ /**
* Set the level of color saturation to apply to a specific app.
*
* @param packageName the package name of the app whose windows should be desaturated
@@ -588,6 +599,14 @@
}
}
+ boolean isSaturationActivated() {
+ try {
+ return mCdm.isSaturationActivated();
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
boolean setAppSaturationLevel(String packageName, int saturationLevel) {
try {
return mCdm.setAppSaturationLevel(packageName, saturationLevel);
diff --git a/core/java/android/hardware/display/DisplayManagerGlobal.java b/core/java/android/hardware/display/DisplayManagerGlobal.java
index f3ebd7f..ac44fe9 100644
--- a/core/java/android/hardware/display/DisplayManagerGlobal.java
+++ b/core/java/android/hardware/display/DisplayManagerGlobal.java
@@ -16,6 +16,8 @@
package android.hardware.display;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.ParceledListSlice;
@@ -229,7 +231,17 @@
return getCompatibleDisplay(displayId, DisplayAdjustments.DEFAULT_DISPLAY_ADJUSTMENTS);
}
- public void registerDisplayListener(DisplayListener listener, Handler handler) {
+ /**
+ * Register a listener for display-related changes.
+ *
+ * @param listener The listener that will be called when display changes occur.
+ * @param handler Handler for the thread that will be receiving the callbacks. May be null.
+ * If null, listener will use the handler for the current thread, and if still null,
+ * the handler for the main thread.
+ * If that is still null, a runtime exception will be thrown.
+ */
+ public void registerDisplayListener(@NonNull DisplayListener listener,
+ @Nullable Handler handler) {
if (listener == null) {
throw new IllegalArgumentException("listener must not be null");
}
@@ -237,7 +249,8 @@
synchronized (mLock) {
int index = findDisplayListenerLocked(listener);
if (index < 0) {
- mDisplayListeners.add(new DisplayListenerDelegate(listener, handler));
+ Looper looper = getLooperForHandler(handler);
+ mDisplayListeners.add(new DisplayListenerDelegate(listener, looper));
registerCallbackIfNeededLocked();
}
}
@@ -258,6 +271,17 @@
}
}
+ private static Looper getLooperForHandler(@Nullable Handler handler) {
+ Looper looper = handler != null ? handler.getLooper() : Looper.myLooper();
+ if (looper == null) {
+ looper = Looper.getMainLooper();
+ }
+ if (looper == null) {
+ throw new RuntimeException("Could not get Looper for the UI thread.");
+ }
+ return looper;
+ }
+
private int findDisplayListenerLocked(DisplayListener listener) {
final int numListeners = mDisplayListeners.size();
for (int i = 0; i < numListeners; i++) {
@@ -636,8 +660,8 @@
private static final class DisplayListenerDelegate extends Handler {
public final DisplayListener mListener;
- public DisplayListenerDelegate(DisplayListener listener, Handler handler) {
- super(handler != null ? handler.getLooper() : Looper.myLooper(), null, true /*async*/);
+ DisplayListenerDelegate(DisplayListener listener, @NonNull Looper looper) {
+ super(looper, null, true /*async*/);
mListener = listener;
}
diff --git a/core/java/android/hardware/display/IColorDisplayManager.aidl b/core/java/android/hardware/display/IColorDisplayManager.aidl
index 30e76cf..88b59a6 100644
--- a/core/java/android/hardware/display/IColorDisplayManager.aidl
+++ b/core/java/android/hardware/display/IColorDisplayManager.aidl
@@ -24,6 +24,7 @@
boolean setSaturationLevel(int saturationLevel);
boolean setAppSaturationLevel(String packageName, int saturationLevel);
+ boolean isSaturationActivated();
int getTransformCapabilities();
diff --git a/core/java/android/net/INetworkMonitorCallbacks.aidl b/core/java/android/net/INetworkMonitorCallbacks.aidl
index a8682f9..5146585 100644
--- a/core/java/android/net/INetworkMonitorCallbacks.aidl
+++ b/core/java/android/net/INetworkMonitorCallbacks.aidl
@@ -24,7 +24,7 @@
void onNetworkMonitorCreated(in INetworkMonitor networkMonitor);
void notifyNetworkTested(int testResult, @nullable String redirectUrl);
void notifyPrivateDnsConfigResolved(in PrivateDnsConfigParcel config);
- void showProvisioningNotification(String action);
+ void showProvisioningNotification(String action, String packageName);
void hideProvisioningNotification();
void logCaptivePortalLoginEvent(int eventId, String packageName);
}
\ No newline at end of file
diff --git a/core/java/android/net/NetworkStack.java b/core/java/android/net/NetworkStack.java
index b6cd635..ca49438 100644
--- a/core/java/android/net/NetworkStack.java
+++ b/core/java/android/net/NetworkStack.java
@@ -15,6 +15,7 @@
*/
package android.net;
+import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_HIGH;
import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_NORMAL;
@@ -27,6 +28,7 @@
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
+import android.content.pm.PackageManager;
import android.net.dhcp.DhcpServingParamsParcel;
import android.net.dhcp.IDhcpServerCallbacks;
import android.net.ip.IIpClientCallbacks;
@@ -63,9 +65,6 @@
public static final String PERMISSION_MAINLINE_NETWORK_STACK =
"android.permission.MAINLINE_NETWORK_STACK";
- /** @hide */
- public static final String NETWORKSTACK_PACKAGE_NAME = "com.android.mainline.networkstack";
-
private static final int NETWORKSTACK_TIMEOUT_MS = 10_000;
@NonNull
@@ -204,7 +203,33 @@
final ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
intent.setComponent(comp);
- if (comp == null || !context.bindServiceAsUser(intent, new NetworkStackConnection(),
+ if (comp == null) {
+ Slog.wtf(TAG, "Could not resolve the network stack with " + intent);
+ // TODO: crash/reboot system server ?
+ return;
+ }
+
+ final PackageManager pm = context.getPackageManager();
+ int uid = -1;
+ try {
+ uid = pm.getPackageUid(comp.getPackageName(), UserHandle.USER_SYSTEM);
+ } catch (PackageManager.NameNotFoundException e) {
+ Slog.wtf("Network stack package not found", e);
+ // Fall through
+ }
+
+ if (uid != Process.NETWORK_STACK_UID) {
+ throw new SecurityException("Invalid network stack UID: " + uid);
+ }
+
+ final int hasPermission =
+ pm.checkPermission(PERMISSION_MAINLINE_NETWORK_STACK, comp.getPackageName());
+ if (hasPermission != PERMISSION_GRANTED) {
+ throw new SecurityException(
+ "Network stack does not have permission " + PERMISSION_MAINLINE_NETWORK_STACK);
+ }
+
+ if (!context.bindServiceAsUser(intent, new NetworkStackConnection(),
Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.SYSTEM)) {
Slog.wtf(TAG,
"Could not bind to network stack in-process, or in app with " + intent);
diff --git a/core/java/android/os/AsyncTask.java b/core/java/android/os/AsyncTask.java
index 1f33693..a851e04 100644
--- a/core/java/android/os/AsyncTask.java
+++ b/core/java/android/os/AsyncTask.java
@@ -21,13 +21,14 @@
import android.annotation.WorkerThread;
import java.util.ArrayDeque;
-import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.RejectedExecutionHandler;
+import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@@ -190,13 +191,19 @@
public abstract class AsyncTask<Params, Progress, Result> {
private static final String LOG_TAG = "AsyncTask";
- private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
- // We want at least 2 threads and at most 4 threads in the core pool,
- // preferring to have 1 less than the CPU count to avoid saturating
- // the CPU with background work
- private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
- private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
- private static final int KEEP_ALIVE_SECONDS = 30;
+ // We keep only a single pool thread around all the time.
+ // We let the pool grow to a fairly large number of threads if necessary,
+ // but let them time out quickly. In the unlikely case that we run out of threads,
+ // we fall back to a simple unbounded-queue executor.
+ // This combination ensures that:
+ // 1. We normally keep few threads (1) around.
+ // 2. We queue only after launching a significantly larger, but still bounded, set of threads.
+ // 3. We keep the total number of threads bounded, but still allow an unbounded set
+ // of tasks to be queued.
+ private static final int CORE_POOL_SIZE = 1;
+ private static final int MAXIMUM_POOL_SIZE = 20;
+ private static final int BACKUP_POOL_SIZE = 5;
+ private static final int KEEP_ALIVE_SECONDS = 3;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
@@ -206,8 +213,29 @@
}
};
- private static final BlockingQueue<Runnable> sPoolWorkQueue =
- new LinkedBlockingQueue<Runnable>(128);
+ // Used only for rejected executions.
+ // Initialization protected by sRunOnSerialPolicy lock.
+ private static ThreadPoolExecutor sBackupExecutor;
+ private static LinkedBlockingQueue<Runnable> sBackupExecutorQueue;
+
+ private static final RejectedExecutionHandler sRunOnSerialPolicy =
+ new RejectedExecutionHandler() {
+ public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
+ android.util.Log.w(LOG_TAG, "Exceeded ThreadPoolExecutor pool size");
+ // As a last ditch fallback, run it on an executor with an unbounded queue.
+ // Create this executor lazily, hopefully almost never.
+ synchronized (this) {
+ if (sBackupExecutor == null) {
+ sBackupExecutorQueue = new LinkedBlockingQueue<Runnable>();
+ sBackupExecutor = new ThreadPoolExecutor(
+ BACKUP_POOL_SIZE, BACKUP_POOL_SIZE, KEEP_ALIVE_SECONDS,
+ TimeUnit.SECONDS, sBackupExecutorQueue, sThreadFactory);
+ sBackupExecutor.allowCoreThreadTimeOut(true);
+ }
+ }
+ sBackupExecutor.execute(r);
+ }
+ };
/**
* An {@link Executor} that can be used to execute tasks in parallel.
@@ -217,8 +245,8 @@
static {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
- sPoolWorkQueue, sThreadFactory);
- threadPoolExecutor.allowCoreThreadTimeOut(true);
+ new SynchronousQueue<Runnable>(), sThreadFactory);
+ threadPoolExecutor.setRejectedExecutionHandler(sRunOnSerialPolicy);
THREAD_POOL_EXECUTOR = threadPoolExecutor;
}
diff --git a/core/java/android/os/FileUtils.java b/core/java/android/os/FileUtils.java
index 629289b..0384faa 100644
--- a/core/java/android/os/FileUtils.java
+++ b/core/java/android/os/FileUtils.java
@@ -1093,6 +1093,12 @@
return buildUniqueFileWithExtension(parent, parts[0], parts[1]);
}
+ /** {@hide} */
+ public static File buildNonUniqueFile(File parent, String mimeType, String displayName) {
+ final String[] parts = splitFileName(mimeType, displayName);
+ return buildFile(parent, parts[0], parts[1]);
+ }
+
/**
* Generates a unique file name under the given parent directory, keeping
* any extension intact.
diff --git a/core/java/android/os/GraphicsEnvironment.java b/core/java/android/os/GraphicsEnvironment.java
index 269c781..d12ace8 100644
--- a/core/java/android/os/GraphicsEnvironment.java
+++ b/core/java/android/os/GraphicsEnvironment.java
@@ -16,6 +16,7 @@
package android.os;
+import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
@@ -24,14 +25,10 @@
import android.content.pm.ResolveInfo;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
-import android.gamedriver.GameDriverProto.Blacklist;
-import android.gamedriver.GameDriverProto.Blacklists;
import android.opengl.EGL14;
import android.provider.Settings;
-import android.util.Base64;
import android.util.Log;
-
-import com.android.framework.protobuf.InvalidProtocolBufferException;
+import android.widget.Toast;
import dalvik.system.VMRuntime;
@@ -67,8 +64,6 @@
private static final String ANGLE_RULES_FILE = "a4a_rules.json";
private static final String ANGLE_TEMP_RULES = "debug.angle.rules";
private static final String ACTION_ANGLE_FOR_ANDROID = "android.app.action.ANGLE_FOR_ANDROID";
- private static final String GAME_DRIVER_BLACKLIST_FLAG = "blacklist";
- private static final int BASE64_FLAGS = Base64.NO_PADDING | Base64.NO_WRAP;
private ClassLoader mClassLoader;
private String mLayerPath;
@@ -222,9 +217,17 @@
}
- private static List<String> getGlobalSettingsString(Bundle bundle, String globalSetting) {
- List<String> valueList = null;
- final String settingsValue = bundle.getString(globalSetting);
+ private static List<String> getGlobalSettingsString(ContentResolver contentResolver,
+ Bundle bundle,
+ String globalSetting) {
+ final List<String> valueList;
+ final String settingsValue;
+
+ if (bundle != null) {
+ settingsValue = bundle.getString(globalSetting);
+ } else {
+ settingsValue = Settings.Global.getString(contentResolver, globalSetting);
+ }
if (settingsValue != null) {
valueList = new ArrayList<>(Arrays.asList(settingsValue.split(",")));
@@ -246,17 +249,27 @@
return -1;
}
- private static String getDriverForPkg(Bundle bundle, String packageName) {
- final String allUseAngle =
- bundle.getString(Settings.Global.GLOBAL_SETTINGS_ANGLE_GL_DRIVER_ALL_ANGLE);
+ private static String getDriverForPkg(Context context, Bundle bundle, String packageName) {
+ final String allUseAngle;
+ if (bundle != null) {
+ allUseAngle =
+ bundle.getString(Settings.Global.GLOBAL_SETTINGS_ANGLE_GL_DRIVER_ALL_ANGLE);
+ } else {
+ ContentResolver contentResolver = context.getContentResolver();
+ allUseAngle = Settings.Global.getString(contentResolver,
+ Settings.Global.GLOBAL_SETTINGS_ANGLE_GL_DRIVER_ALL_ANGLE);
+ }
if ((allUseAngle != null) && allUseAngle.equals("1")) {
return sDriverMap.get(OpenGlDriverChoice.ANGLE);
}
- final List<String> globalSettingsDriverPkgs = getGlobalSettingsString(
- bundle, Settings.Global.GLOBAL_SETTINGS_ANGLE_GL_DRIVER_SELECTION_PKGS);
- final List<String> globalSettingsDriverValues = getGlobalSettingsString(
- bundle, Settings.Global.GLOBAL_SETTINGS_ANGLE_GL_DRIVER_SELECTION_VALUES);
+ final ContentResolver contentResolver = context.getContentResolver();
+ final List<String> globalSettingsDriverPkgs =
+ getGlobalSettingsString(contentResolver, bundle,
+ Settings.Global.GLOBAL_SETTINGS_ANGLE_GL_DRIVER_SELECTION_PKGS);
+ final List<String> globalSettingsDriverValues =
+ getGlobalSettingsString(contentResolver, bundle,
+ Settings.Global.GLOBAL_SETTINGS_ANGLE_GL_DRIVER_SELECTION_VALUES);
// Make sure we have a good package name
if ((packageName == null) || (packageName.isEmpty())) {
@@ -308,7 +321,7 @@
* True: Temporary rules file was loaded.
* False: Temporary rules file was *not* loaded.
*/
- private boolean setupAngleWithTempRulesFile(Context context,
+ private static boolean setupAngleWithTempRulesFile(Context context,
String packageName,
String paths,
String devOptIn) {
@@ -372,7 +385,7 @@
* True: APK rules file was loaded.
* False: APK rules file was *not* loaded.
*/
- private boolean setupAngleRulesApk(String anglePkgName,
+ private static boolean setupAngleRulesApk(String anglePkgName,
ApplicationInfo angleInfo,
PackageManager pm,
String packageName,
@@ -405,23 +418,32 @@
/**
* Pull ANGLE whitelist from GlobalSettings and compare against current package
*/
- private boolean checkAngleWhitelist(Bundle bundle, String packageName) {
+ private static boolean checkAngleWhitelist(Context context, Bundle bundle, String packageName) {
+ final ContentResolver contentResolver = context.getContentResolver();
final List<String> angleWhitelist =
- getGlobalSettingsString(bundle, Settings.Global.GLOBAL_SETTINGS_ANGLE_WHITELIST);
+ getGlobalSettingsString(contentResolver, bundle,
+ Settings.Global.GLOBAL_SETTINGS_ANGLE_WHITELIST);
return angleWhitelist.contains(packageName);
}
/**
* Pass ANGLE details down to trigger enable logic
+ *
+ * @param context
+ * @param bundle
+ * @param packageName
+ * @return true: ANGLE setup successfully
+ * false: ANGLE not setup (not on whitelist, ANGLE not present, etc.)
*/
- public void setupAngle(Context context, Bundle bundle, PackageManager pm, String packageName) {
+ public boolean setupAngle(Context context, Bundle bundle, PackageManager pm,
+ String packageName) {
if (packageName.isEmpty()) {
Log.v(TAG, "No package name available yet, skipping ANGLE setup");
- return;
+ return false;
}
- final String devOptIn = getDriverForPkg(bundle, packageName);
+ final String devOptIn = getDriverForPkg(context, bundle, packageName);
if (DEBUG) {
Log.v(TAG, "ANGLE Developer option for '" + packageName + "' "
+ "set to: '" + devOptIn + "'");
@@ -439,11 +461,11 @@
// load a driver, GraphicsEnv::shouldUseAngle() has seen the package name before
// and can confidently answer yes/no based on the previously set developer
// option value.
- final boolean whitelisted = checkAngleWhitelist(bundle, packageName);
+ final boolean whitelisted = checkAngleWhitelist(context, bundle, packageName);
final boolean defaulted = devOptIn.equals(sDriverMap.get(OpenGlDriverChoice.DEFAULT));
final boolean rulesCheck = (whitelisted || !defaulted);
if (!rulesCheck) {
- return;
+ return false;
}
if (whitelisted) {
@@ -456,7 +478,7 @@
final String anglePkgName = getAnglePackageName(pm);
if (anglePkgName.isEmpty()) {
Log.e(TAG, "Failed to find ANGLE package.");
- return;
+ return false;
}
final ApplicationInfo angleInfo;
@@ -464,7 +486,7 @@
angleInfo = pm.getApplicationInfo(anglePkgName, PackageManager.MATCH_SYSTEM_ONLY);
} catch (PackageManager.NameNotFoundException e) {
Log.w(TAG, "ANGLE package '" + anglePkgName + "' not installed");
- return;
+ return false;
}
final String abi = chooseAbi(angleInfo);
@@ -480,12 +502,62 @@
if (setupAngleWithTempRulesFile(context, packageName, paths, devOptIn)) {
// We setup ANGLE with a temp rules file, so we're done here.
- return;
+ return true;
}
if (setupAngleRulesApk(anglePkgName, angleInfo, pm, packageName, paths, devOptIn)) {
// We setup ANGLE with rules from the APK, so we're done here.
- return;
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the "ANGLE In Use" dialog box should be shown.
+ */
+ private boolean shouldShowAngleInUseDialogBox(Context context) {
+ try {
+ ContentResolver contentResolver = context.getContentResolver();
+ final int showDialogBox = Settings.Global.getInt(contentResolver,
+ Settings.Global.GLOBAL_SETTINGS_SHOW_ANGLE_IN_USE_DIALOG_BOX);
+
+ return (showDialogBox == 1);
+ } catch (Settings.SettingNotFoundException | SecurityException e) {
+ // Do nothing and move on
+ }
+
+ // No setting, so assume false
+ return false;
+ }
+
+ /**
+ * Determine if ANGLE should be used.
+ */
+ private boolean shouldUseAngle(Context context, String packageName) {
+ // Need to make sure we are evaluating ANGLE usage for the correct circumstances
+ if (!setupAngle(context, null, context.getPackageManager(), packageName)) {
+ Log.v(TAG, "Package '" + packageName + "' should use not ANGLE");
+ return false;
+ }
+
+ final boolean useAngle = getShouldUseAngle(packageName);
+ Log.v(TAG, "Package '" + packageName + "' should use ANGLE = '" + useAngle + "'");
+
+ return useAngle;
+ }
+
+ /**
+ * Show the ANGLE in Use Dialog Box
+ * @param context
+ */
+ public void showAngleInUseDialogBox(Context context) {
+ final String packageName = context.getPackageName();
+
+ if (shouldShowAngleInUseDialogBox(context) && shouldUseAngle(context, packageName)) {
+ final String toastMsg = packageName + " is using ANGLE";
+ final Toast toast = Toast.makeText(context, toastMsg, Toast.LENGTH_LONG);
+ toast.show();
}
}
@@ -541,53 +613,32 @@
if (gameDriverAllApps != 1) {
// GAME_DRIVER_OPT_OUT_APPS has higher priority than GAME_DRIVER_OPT_IN_APPS
- if (getGlobalSettingsString(coreSettings, Settings.Global.GAME_DRIVER_OPT_OUT_APPS)
- .contains(packageName)) {
+ if (getGlobalSettingsString(null, coreSettings,
+ Settings.Global.GAME_DRIVER_OPT_OUT_APPS).contains(packageName)) {
if (DEBUG) {
Log.w(TAG, packageName + " opts out from Game Driver.");
}
return false;
}
final boolean isOptIn =
- getGlobalSettingsString(coreSettings, Settings.Global.GAME_DRIVER_OPT_IN_APPS)
- .contains(packageName);
+ getGlobalSettingsString(null, coreSettings,
+ Settings.Global.GAME_DRIVER_OPT_IN_APPS).contains(packageName);
if (!isOptIn
- && !getGlobalSettingsString(coreSettings, Settings.Global.GAME_DRIVER_WHITELIST)
- .contains(packageName)) {
+ && !getGlobalSettingsString(null, coreSettings,
+ Settings.Global.GAME_DRIVER_WHITELIST).contains(packageName)) {
if (DEBUG) {
Log.w(TAG, packageName + " is not on the whitelist.");
}
return false;
}
- if (!isOptIn) {
- // At this point, the application is on the whitelist only, check whether it's
- // on the blacklist, terminate early when it's on the blacklist.
- try {
- // TODO(b/121350991) Switch to DeviceConfig with property listener.
- final String base64String =
- coreSettings.getString(Settings.Global.GAME_DRIVER_BLACKLIST);
- if (base64String != null && !base64String.isEmpty()) {
- final Blacklists blacklistsProto =
- Blacklists.parseFrom(Base64.decode(base64String, BASE64_FLAGS));
- final List<Blacklist> blacklists = blacklistsProto.getBlacklistsList();
- final long driverVersionCode = driverAppInfo.longVersionCode;
- for (Blacklist blacklist : blacklists) {
- if (blacklist.getVersionCode() == driverVersionCode) {
- for (String pkgName : blacklist.getPackageNamesList()) {
- if (pkgName == packageName) {
- return false;
- }
- }
- break;
- }
- }
- }
- } catch (InvalidProtocolBufferException e) {
- if (DEBUG) {
- Log.w(TAG, "Can't parse blacklist, skip and continue...");
- }
- }
+ // If the application is not opted-in and check whether it's on the blacklist,
+ // terminate early if it's on the blacklist and fallback to system driver.
+ if (!isOptIn
+ && getGlobalSettingsString(null, coreSettings,
+ Settings.Global.GAME_DRIVER_BLACKLIST)
+ .contains(ai.packageName)) {
+ return false;
}
}
@@ -660,4 +711,5 @@
long driverVersionCode, String appPackageName);
private static native void setAngleInfo(String path, String appPackage, String devOptIn,
FileDescriptor rulesFd, long rulesOffset, long rulesLength);
+ private static native boolean getShouldUseAngle(String packageName);
}
diff --git a/core/java/android/os/IStatsCompanionService.aidl b/core/java/android/os/IStatsCompanionService.aidl
index dde46cd..0751b96 100644
--- a/core/java/android/os/IStatsCompanionService.aidl
+++ b/core/java/android/os/IStatsCompanionService.aidl
@@ -69,6 +69,12 @@
oneway void sendDataBroadcast(in IBinder intentSender, long lastReportTimeNs);
/**
+ * Send a broadcast to the specified PendingIntent's as IBinder notifying it that the list
+ * of active configs has changed.
+ */
+ oneway void sendActiveConfigsChangedBroadcast(in IBinder intentSender, in long[] configIds);
+
+ /**
* Requests StatsCompanionService to send a broadcast using the given intentSender
* (which should cast to an IIntentSender), along with the other information specified.
*/
diff --git a/core/java/android/os/IStatsManager.aidl b/core/java/android/os/IStatsManager.aidl
index 93d6f4c..6d4c5a0 100644
--- a/core/java/android/os/IStatsManager.aidl
+++ b/core/java/android/os/IStatsManager.aidl
@@ -16,6 +16,8 @@
package android.os;
+import android.os.IStatsPullerCallback;
+
/**
* Binder interface to communicate with the statistics management service.
* {@hide}
@@ -178,4 +180,41 @@
* this label. This allows building custom metrics and predicates.
*/
void sendAppBreadcrumbAtom(int label, int state);
+
+ /**
+ * Registers a puller callback function that, when invoked, pulls the data
+ * for the specified vendor atom tag.
+ *
+ * Requires Manifest.permission.DUMP and Manifest.permission.PACKAGE_USAGE_STATS
+ */
+ oneway void registerPullerCallback(int atomTag, IStatsPullerCallback pullerCallback,
+ String packageName);
+
+ /**
+ * Unregisters a puller callback function for the given vendor atom.
+ *
+ * Requires Manifest.permission.DUMP and Manifest.permission.PACKAGE_USAGE_STATS
+ */
+ oneway void unregisterPullerCallback(int atomTag, String packageName);
+
+ /**
+ * The install requires staging.
+ */
+ const int FLAG_REQUIRE_STAGING = 0x01;
+
+ /**
+ * Rollback is enabled with this install.
+ */
+ const int FLAG_ROLLBACK_ENABLED = 0x02;
+
+ /**
+ * Requires low latency monitoring.
+ */
+ const int FLAG_REQUIRE_LOW_LATENCY_MONITOR = 0x04;
+
+ /**
+ * Logs an event for binary push for module updates.
+ */
+ oneway void sendBinaryPushStateChangedAtom(in String trainName, in long trainVersionCode,
+ in int options, in int state, in long[] experimentId);
}
diff --git a/core/java/android/os/IStatsPullerCallback.aidl b/core/java/android/os/IStatsPullerCallback.aidl
new file mode 100644
index 0000000..1684aeb
--- /dev/null
+++ b/core/java/android/os/IStatsPullerCallback.aidl
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.os;
+
+import android.os.StatsLogEventWrapper;
+
+/**
+ * Binder interface to pull atoms for the stats service.
+ * {@hide}
+ */
+interface IStatsPullerCallback {
+ /**
+ * Pull data for the specified atom tag. Returns an array of StatsLogEventWrapper containing
+ * the data.
+ *
+ * Note: These pulled atoms should not have uid/attribution chain. Additionally, the event
+ * timestamps will be truncated to the nearest 5 minutes.
+ */
+ StatsLogEventWrapper[] pullData(int atomTag, long elapsedNanos, long wallClocknanos);
+
+}
diff --git a/core/java/android/os/ParcelFileDescriptor.aidl b/core/java/android/os/ParcelFileDescriptor.aidl
deleted file mode 100644
index c07b980..0000000
--- a/core/java/android/os/ParcelFileDescriptor.aidl
+++ /dev/null
@@ -1,20 +0,0 @@
-/* //device/java/android/android/os/ParcelFileDescriptor.aidl
-**
-** Copyright 2007, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-** http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
-
-package android.os;
-
-parcelable ParcelFileDescriptor cpp_header "binder/ParcelFileDescriptor.h";
diff --git a/core/java/android/os/RecoverySystem.java b/core/java/android/os/RecoverySystem.java
index 8492b0c..3ee54ce 100644
--- a/core/java/android/os/RecoverySystem.java
+++ b/core/java/android/os/RecoverySystem.java
@@ -32,6 +32,7 @@
import android.provider.Settings;
import android.telephony.euicc.EuiccManager;
import android.text.TextUtils;
+import android.text.format.DateFormat;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
@@ -762,7 +763,8 @@
String reasonArg = null;
if (!TextUtils.isEmpty(reason)) {
- reasonArg = "--reason=" + sanitizeArg(reason);
+ String timeStamp = DateFormat.format("yyyy-MM-ddTHH:mm:ssZ", System.currentTimeMillis()).toString();
+ reasonArg = "--reason=" + sanitizeArg(reason + "," + timeStamp);
}
final String localeArg = "--locale=" + Locale.getDefault().toLanguageTag() ;
diff --git a/core/java/android/os/StatsLogEventWrapper.java b/core/java/android/os/StatsLogEventWrapper.java
index acb9eac..2334242 100644
--- a/core/java/android/os/StatsLogEventWrapper.java
+++ b/core/java/android/os/StatsLogEventWrapper.java
@@ -57,20 +57,18 @@
public static final Parcelable.Creator<StatsLogEventWrapper> CREATOR = new
Parcelable.Creator<StatsLogEventWrapper>() {
public StatsLogEventWrapper createFromParcel(Parcel in) {
- android.util.EventLog.writeEvent(0x534e4554, "112550251",
- android.os.Binder.getCallingUid(), "");
- // Purposefully leaving this method not implemented.
- throw new RuntimeException("Not implemented");
+ return new StatsLogEventWrapper(in);
}
public StatsLogEventWrapper[] newArray(int size) {
- android.util.EventLog.writeEvent(0x534e4554, "112550251",
- android.os.Binder.getCallingUid(), "");
- // Purposefully leaving this method not implemented.
- throw new RuntimeException("Not implemented");
+ return new StatsLogEventWrapper[size];
}
};
+ private StatsLogEventWrapper(Parcel in) {
+ readFromParcel(in);
+ }
+
/**
* Set work source if any.
*/
@@ -197,6 +195,70 @@
}
/**
+ * Reads from parcel and appropriately fills member fields.
+ */
+ public void readFromParcel(Parcel in) {
+ mTypes = new ArrayList<>();
+ mValues = new ArrayList<>();
+ mWorkSource = null;
+
+ mTag = in.readInt();
+ mElapsedTimeNs = in.readLong();
+ mWallClockTimeNs = in.readLong();
+
+ // Clear any data.
+ if (DEBUG) {
+ Slog.d(TAG, "Reading " + mTag + " " + mElapsedTimeNs + " " + mWallClockTimeNs);
+ }
+ // Set up worksource if present.
+ int numWorkChains = in.readInt();
+ if (numWorkChains > 0) {
+ mWorkSource = new WorkSource();
+ for (int i = 0; i < numWorkChains; i++) {
+ android.os.WorkSource.WorkChain workChain = mWorkSource.createWorkChain();
+ int workChainSize = in.readInt();
+ for (int j = 0; j < workChainSize; j++) {
+ int uid = in.readInt();
+ String tag = in.readString();
+ workChain.addNode(uid, tag);
+ }
+ }
+ }
+
+ // Do the rest of the types.
+ int numTypes = in.readInt();
+ if (DEBUG) {
+ Slog.d(TAG, "Reading " + numTypes + " elements");
+ }
+ for (int i = 0; i < numTypes; i++) {
+ int type = in.readInt();
+ mTypes.add(type);
+ switch (type) {
+ case EVENT_TYPE_INT:
+ mValues.add(in.readInt());
+ break;
+ case EVENT_TYPE_LONG:
+ mValues.add(in.readLong());
+ break;
+ case EVENT_TYPE_FLOAT:
+ mValues.add(in.readFloat());
+ break;
+ case EVENT_TYPE_DOUBLE:
+ mValues.add(in.readDouble());
+ break;
+ case EVENT_TYPE_STRING:
+ mValues.add(in.readString());
+ break;
+ case EVENT_TYPE_STORAGE:
+ mValues.add(in.createByteArray());
+ break;
+ default:
+ break;
+ }
+ }
+ }
+
+ /**
* Boilerplate for Parcel.
*/
public int describeContents() {
diff --git a/core/java/android/os/connectivity/CellularBatteryStats.java b/core/java/android/os/connectivity/CellularBatteryStats.java
index 2593c85..c99ecb32 100644
--- a/core/java/android/os/connectivity/CellularBatteryStats.java
+++ b/core/java/android/os/connectivity/CellularBatteryStats.java
@@ -44,6 +44,7 @@
private long[] mTimeInRatMs;
private long[] mTimeInRxSignalStrengthLevelMs;
private long[] mTxTimeMs;
+ private long mMonitoredRailChargeConsumedMaMs;
public static final Parcelable.Creator<CellularBatteryStats> CREATOR = new
Parcelable.Creator<CellularBatteryStats>() {
@@ -74,6 +75,7 @@
out.writeLongArray(mTimeInRatMs);
out.writeLongArray(mTimeInRxSignalStrengthLevelMs);
out.writeLongArray(mTxTimeMs);
+ out.writeLong(mMonitoredRailChargeConsumedMaMs);
}
public void readFromParcel(Parcel in) {
@@ -90,6 +92,7 @@
in.readLongArray(mTimeInRatMs);
in.readLongArray(mTimeInRxSignalStrengthLevelMs);
in.readLongArray(mTxTimeMs);
+ mMonitoredRailChargeConsumedMaMs = in.readLong();
}
public long getLoggingDurationMs() {
@@ -144,6 +147,10 @@
return mTxTimeMs;
}
+ public long getMonitoredRailChargeConsumedMaMs() {
+ return mMonitoredRailChargeConsumedMaMs;
+ }
+
public void setLoggingDurationMs(long t) {
mLoggingDurationMs = t;
return;
@@ -211,6 +218,11 @@
return;
}
+ public void setMonitoredRailChargeConsumedMaMs(long monitoredRailEnergyConsumedMaMs) {
+ mMonitoredRailChargeConsumedMaMs = monitoredRailEnergyConsumedMaMs;
+ return;
+ }
+
public int describeContents() {
return 0;
}
@@ -237,6 +249,7 @@
Arrays.fill(mTimeInRxSignalStrengthLevelMs, 0);
mTxTimeMs = new long[ModemActivityInfo.TX_POWER_LEVELS];
Arrays.fill(mTxTimeMs, 0);
+ mMonitoredRailChargeConsumedMaMs = 0;
return;
}
}
\ No newline at end of file
diff --git a/core/java/android/os/storage/StorageManager.java b/core/java/android/os/storage/StorageManager.java
index 735f4f2..43c9064 100644
--- a/core/java/android/os/storage/StorageManager.java
+++ b/core/java/android/os/storage/StorageManager.java
@@ -1545,7 +1545,7 @@
public static boolean hasIsolatedStorage() {
// Prefer to use snapshot for current boot when available
return SystemProperties.getBoolean(PROP_ISOLATED_STORAGE_SNAPSHOT,
- SystemProperties.getBoolean(PROP_ISOLATED_STORAGE, false));
+ SystemProperties.getBoolean(PROP_ISOLATED_STORAGE, true));
}
/**
diff --git a/core/java/android/provider/DeviceConfig.java b/core/java/android/provider/DeviceConfig.java
index 41d3cbb..104b61d 100644
--- a/core/java/android/provider/DeviceConfig.java
+++ b/core/java/android/provider/DeviceConfig.java
@@ -69,6 +69,7 @@
* @hide
*/
@SystemApi
+ @TestApi
public static final String NAMESPACE_AUTOFILL = "autofill";
/**
@@ -122,6 +123,21 @@
}
/**
+ * Namespace for all runtime related features.
+ *
+ * @hide
+ */
+ @SystemApi
+ public interface Runtime {
+ String NAMESPACE = "runtime";
+
+ /**
+ * Whether or not we use the precompiled layout.
+ */
+ String USE_PRECOMPILED_LAYOUT = "view.precompiled_layout_enabled";
+ }
+
+ /**
* Namespace for all runtime native related features.
*
* @hide
@@ -292,6 +308,21 @@
}
/**
+ * Namespace for Rollback.
+ *
+ * @hide
+ */
+ @SystemApi
+ public interface Rollback {
+ String NAMESPACE = "rollback";
+
+ /**
+ * Timeout in milliseconds for enabling package rollback.
+ */
+ String ENABLE_ROLLBACK_TIMEOUT = "enable_rollback_timeout";
+ }
+
+ /**
* Namespace for storage-related features.
*
* @hide
@@ -308,6 +339,25 @@
String ISOLATED_STORAGE_ENABLED = "isolated_storage_enabled";
}
+ /**
+ * Namespace for system scheduler related features. These features will be applied
+ * immediately upon change.
+ *
+ * @hide
+ */
+ @SystemApi
+ public interface Scheduler {
+ String NAMESPACE = "scheduler";
+
+ /**
+ * Flag for enabling fast metrics collection in system scheduler.
+ * A flag value of '' or '0' means the fast metrics collection is not
+ * enabled. Otherwise fast metrics collection is enabled and flag value
+ * is the order id.
+ */
+ String ENABLE_FAST_METRICS_COLLECTION = "enable_fast_metrics_collection";
+ }
+
private static final Object sLock = new Object();
@GuardedBy("sLock")
private static Map<OnPropertyChangedListener, Pair<String, Executor>> sListeners =
@@ -399,6 +449,7 @@
* @see #removeOnPropertyChangedListener(OnPropertyChangedListener)
*/
@SystemApi
+ @TestApi
@RequiresPermission(READ_DEVICE_CONFIG)
public static void addOnPropertyChangedListener(
@NonNull String namespace,
@@ -432,6 +483,7 @@
* @see #addOnPropertyChangedListener(String, Executor, OnPropertyChangedListener)
*/
@SystemApi
+ @TestApi
public static void removeOnPropertyChangedListener(
OnPropertyChangedListener onPropertyChangedListener) {
synchronized (sLock) {
@@ -528,6 +580,7 @@
* @hide
*/
@SystemApi
+ @TestApi
public interface OnPropertyChangedListener {
/**
* Called when a property has changed.
diff --git a/core/java/android/provider/DocumentsContract.java b/core/java/android/provider/DocumentsContract.java
index 5f1c560..5708342 100644
--- a/core/java/android/provider/DocumentsContract.java
+++ b/core/java/android/provider/DocumentsContract.java
@@ -853,10 +853,8 @@
private static final String PATH_DOCUMENT = "document";
private static final String PATH_CHILDREN = "children";
private static final String PATH_SEARCH = "search";
- // TODO(b/72055774): make private again once ScopedAccessProvider is refactored
- /** {@hide} */
@UnsupportedAppUsage
- public static final String PATH_TREE = "tree";
+ private static final String PATH_TREE = "tree";
private static final String PARAM_QUERY = "query";
private static final String PARAM_MANAGE = "manage";
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index de84e71..452d09d 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -6103,7 +6103,7 @@
* Indicates which clock face to show on lock screen and AOD while docked.
* @hide
*/
- private static final String DOCKED_CLOCK_FACE = "docked_clock_face";
+ public static final String DOCKED_CLOCK_FACE = "docked_clock_face";
/**
* Set by the system to track if the user needs to see the call to action for
@@ -12318,6 +12318,14 @@
"angle_whitelist";
/**
+ * Show the "ANGLE In Use" dialog box to the user when ANGLE is the OpenGL driver.
+ * The value is a boolean (1 or 0).
+ * @hide
+ */
+ public static final String GLOBAL_SETTINGS_SHOW_ANGLE_IN_USE_DIALOG_BOX =
+ "show_angle_in_use_dialog_box";
+
+ /**
* Game Driver global preference for all Apps.
* 0 = Default
* 1 = All Apps use Game Driver
@@ -12347,6 +12355,12 @@
public static final String GAME_DRIVER_BLACKLIST = "game_driver_blacklist";
/**
+ * List of blacklists, each blacklist is a blacklist for a specific version of Game Driver.
+ * @hide
+ */
+ public static final String GAME_DRIVER_BLACKLISTS = "game_driver_blacklists";
+
+ /**
* Apps on the whitelist that are allowed to use Game Driver.
* The string is a list of application package names, seperated by comma.
* i.e. <apk1>,<apk2>,...,<apkN>
@@ -13285,17 +13299,6 @@
public static final String AUTOFILL_MAX_VISIBLE_DATASETS = "autofill_max_visible_datasets";
/**
- * Used to emulate Smart Suggestion for Augmented Autofill during development
- *
- * <p>Valid values: {@code 0x1} for IME and/or {@code 0x2} for popup window.
- *
- * @hide
- */
- @TestApi
- public static final String AUTOFILL_SMART_SUGGESTION_EMULATION_FLAGS =
- "autofill_smart_suggestion_emulation_flags";
-
- /**
* Exemptions to the hidden API blacklist.
*
* @hide
@@ -13354,6 +13357,14 @@
public static final String ISOLATED_STORAGE_REMOTE = "isolated_storage_remote";
/**
+ * Indicates whether aware is available in the current location.
+ * @hide
+ */
+ public static final String AWARE_ALLOWED = "aware_allowed";
+
+ private static final Validator AWARE_ALLOWED_VALIDATOR = BOOLEAN_VALIDATOR;
+
+ /**
* Settings to backup. This is here so that it's in the same place as the settings
* keys and easy to update.
*
@@ -13399,6 +13410,7 @@
SOFT_AP_TIMEOUT_ENABLED,
ZEN_DURATION,
CHARGING_VIBRATION_ENABLED,
+ AWARE_ALLOWED,
};
/**
@@ -13459,6 +13471,7 @@
VALIDATORS.put(WIFI_PNO_RECENCY_SORTING_ENABLED,
WIFI_PNO_RECENCY_SORTING_ENABLED_VALIDATOR);
VALIDATORS.put(WIFI_LINK_PROBING_ENABLED, WIFI_LINK_PROBING_ENABLED_VALIDATOR);
+ VALIDATORS.put(AWARE_ALLOWED, AWARE_ALLOWED_VALIDATOR);
}
/**
@@ -14355,6 +14368,7 @@
* <pre>
* num_buckets (int)
* collected_uids (string)
+ * minimum_total_cpu_usage_millis (int)
* </pre>
*
* @hide
diff --git a/core/java/android/service/contentcapture/ContentCaptureEventsRequest.java b/core/java/android/service/contentcapture/ContentCaptureEventsRequest.java
index ca6676d..bbcf7a9 100644
--- a/core/java/android/service/contentcapture/ContentCaptureEventsRequest.java
+++ b/core/java/android/service/contentcapture/ContentCaptureEventsRequest.java
@@ -28,7 +28,8 @@
/**
* Not needed anymore...
*
- * @deprecated
+ * @deprecated ContentCaptureService should use
+ * {@code #onContentCaptureEvent(ContentCaptureSessionId, ContentCaptureEvent)} instead.
*
* @hide
*/
diff --git a/core/java/android/service/euicc/EuiccService.java b/core/java/android/service/euicc/EuiccService.java
index ffb524d..a46d047 100644
--- a/core/java/android/service/euicc/EuiccService.java
+++ b/core/java/android/service/euicc/EuiccService.java
@@ -76,6 +76,11 @@
* filter with the appropriate action, the {@link #CATEGORY_EUICC_UI} category, and a non-zero
* priority.
*
+ * <p>Old implementations of EuiccService may support passing in slot IDs equal to
+ * {@link android.telephony.SubscriptionManager#INVALID_SIM_SLOT_INDEX}, which allows the LPA to
+ * decide which eUICC to target when there are multiple eUICCs. This behavior is not supported in
+ * Android Q or later.
+ *
* @hide
*/
@SystemApi
@@ -546,7 +551,7 @@
int resultCode = EuiccService.this.onDownloadSubscription(
slotId, subscription, switchAfterDownload, forceDeactivateSim);
result = new DownloadSubscriptionResult(resultCode,
- 0 /* resolvableErrors */, TelephonyManager.INVALID_CARD_ID);
+ 0 /* resolvableErrors */, TelephonyManager.UNSUPPORTED_CARD_ID);
}
try {
callback.onComplete(result);
diff --git a/core/java/android/service/textclassifier/TEST_MAPPING b/core/java/android/service/textclassifier/TEST_MAPPING
new file mode 100644
index 0000000..ccf2631
--- /dev/null
+++ b/core/java/android/service/textclassifier/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+ "imports": [
+ {
+ "path": "frameworks/base/core/java/android/view/textclassifier"
+ }
+ ]
+}
diff --git a/core/java/android/text/style/DynamicDrawableSpan.java b/core/java/android/text/style/DynamicDrawableSpan.java
index be772af..5754014 100644
--- a/core/java/android/text/style/DynamicDrawableSpan.java
+++ b/core/java/android/text/style/DynamicDrawableSpan.java
@@ -77,6 +77,13 @@
*/
public static final int ALIGN_BASELINE = 1;
+ /**
+ * A constant indicating that this span should be vertically centered between
+ * the top and the lowest descender.
+ * @hide
+ */
+ public static final int ALIGN_CENTER = 2;
+
protected final int mVerticalAlignment;
@UnsupportedAppUsage
@@ -142,6 +149,8 @@
int transY = bottom - b.getBounds().bottom;
if (mVerticalAlignment == ALIGN_BASELINE) {
transY -= paint.getFontMetricsInt().descent;
+ } else if (mVerticalAlignment == ALIGN_CENTER) {
+ transY = (bottom - top) / 2 - b.getBounds().height() / 2;
}
canvas.translate(x, transY);
diff --git a/core/java/android/util/MathUtils.java b/core/java/android/util/MathUtils.java
index 56558d0..0eeef70 100644
--- a/core/java/android/util/MathUtils.java
+++ b/core/java/android/util/MathUtils.java
@@ -166,6 +166,26 @@
}
/**
+ * Returns the interpolation scalar (s) that satisfies the equation: {@code value = }{@link
+ * #lerp}{@code (a, b, s)}
+ *
+ * <p>If {@code a == b}, then this function will return 0.
+ */
+ public static float lerpInv(float a, float b, float value) {
+ return a != b ? ((value - a) / (b - a)) : 0.0f;
+ }
+
+ /** Returns the single argument constrained between [0.0, 1.0]. */
+ public static float saturate(float value) {
+ return constrain(value, 0.0f, 1.0f);
+ }
+
+ /** Returns the saturated (constrained between [0, 1]) result of {@link #lerpInv}. */
+ public static float lerpInvSat(float a, float b, float value) {
+ return saturate(lerpInv(a, b, value));
+ }
+
+ /**
* Returns an interpolated angle in degrees between a set of start and end
* angles.
* <p>
@@ -195,6 +215,32 @@
}
/**
+ * Calculates a value in [rangeMin, rangeMax] that maps value in [valueMin, valueMax] to
+ * returnVal in [rangeMin, rangeMax].
+ * <p>
+ * Always returns a constrained value in the range [rangeMin, rangeMax], even if value is
+ * outside [valueMin, valueMax].
+ * <p>
+ * Eg:
+ * constrainedMap(0f, 100f, 0f, 1f, 0.5f) = 50f
+ * constrainedMap(20f, 200f, 10f, 20f, 20f) = 200f
+ * constrainedMap(20f, 200f, 10f, 20f, 50f) = 200f
+ * constrainedMap(10f, 50f, 10f, 20f, 5f) = 10f
+ *
+ * @param rangeMin minimum of the range that should be returned.
+ * @param rangeMax maximum of the range that should be returned.
+ * @param valueMin minimum of range to map {@code value} to.
+ * @param valueMax maximum of range to map {@code value} to.
+ * @param value to map to the range [{@code valueMin}, {@code valueMax}]. Note, can be outside
+ * this range, resulting in a clamped value.
+ * @return the mapped value, constrained to [{@code rangeMin}, {@code rangeMax}.
+ */
+ public static float constrainedMap(
+ float rangeMin, float rangeMax, float valueMin, float valueMax, float value) {
+ return lerp(rangeMin, rangeMax, lerpInvSat(valueMin, valueMax, value));
+ }
+
+ /**
* Perform Hermite interpolation between two values.
* Eg:
* smoothStep(0, 0.5f, 0.5f) = 1f
diff --git a/core/java/android/util/StatsLog.java b/core/java/android/util/StatsLog.java
index ace4bf4..29ced3e 100644
--- a/core/java/android/util/StatsLog.java
+++ b/core/java/android/util/StatsLog.java
@@ -16,7 +16,14 @@
package android.util;
+import static android.Manifest.permission.DUMP;
+import static android.Manifest.permission.PACKAGE_USAGE_STATS;
+
+import android.Manifest;
import android.annotation.NonNull;
+import android.annotation.RequiresPermission;
+import android.app.IActivityManager;
+import android.content.Context;
import android.os.IStatsManager;
import android.os.RemoteException;
import android.os.ServiceManager;
@@ -31,7 +38,10 @@
private static IStatsManager sService;
- private StatsLog() {}
+ private static Object sLogLock = new Object();
+
+ private StatsLog() {
+ }
/**
* Logs a start event.
@@ -40,11 +50,13 @@
* @return True if the log request was sent to statsd.
*/
public static boolean logStart(int label) {
- synchronized (StatsLog.class) {
+ synchronized (sLogLock) {
try {
IStatsManager service = getIStatsManagerLocked();
if (service == null) {
- if (DEBUG) Slog.d(TAG, "Failed to find statsd when logging start");
+ if (DEBUG) {
+ Slog.d(TAG, "Failed to find statsd when logging start");
+ }
return false;
}
service.sendAppBreadcrumbAtom(label,
@@ -52,7 +64,9 @@
return true;
} catch (RemoteException e) {
sService = null;
- if (DEBUG) Slog.d(TAG, "Failed to connect to statsd when logging start");
+ if (DEBUG) {
+ Slog.d(TAG, "Failed to connect to statsd when logging start");
+ }
return false;
}
}
@@ -65,18 +79,22 @@
* @return True if the log request was sent to statsd.
*/
public static boolean logStop(int label) {
- synchronized (StatsLog.class) {
+ synchronized (sLogLock) {
try {
IStatsManager service = getIStatsManagerLocked();
if (service == null) {
- if (DEBUG) Slog.d(TAG, "Failed to find statsd when logging stop");
+ if (DEBUG) {
+ Slog.d(TAG, "Failed to find statsd when logging stop");
+ }
return false;
}
service.sendAppBreadcrumbAtom(label, StatsLog.APP_BREADCRUMB_REPORTED__STATE__STOP);
return true;
} catch (RemoteException e) {
sService = null;
- if (DEBUG) Slog.d(TAG, "Failed to connect to statsd when logging stop");
+ if (DEBUG) {
+ Slog.d(TAG, "Failed to connect to statsd when logging stop");
+ }
return false;
}
}
@@ -89,11 +107,13 @@
* @return True if the log request was sent to statsd.
*/
public static boolean logEvent(int label) {
- synchronized (StatsLog.class) {
+ synchronized (sLogLock) {
try {
IStatsManager service = getIStatsManagerLocked();
if (service == null) {
- if (DEBUG) Slog.d(TAG, "Failed to find statsd when logging event");
+ if (DEBUG) {
+ Slog.d(TAG, "Failed to find statsd when logging event");
+ }
return false;
}
service.sendAppBreadcrumbAtom(
@@ -101,7 +121,51 @@
return true;
} catch (RemoteException e) {
sService = null;
- if (DEBUG) Slog.d(TAG, "Failed to connect to statsd when logging event");
+ if (DEBUG) {
+ Slog.d(TAG, "Failed to connect to statsd when logging event");
+ }
+ return false;
+ }
+ }
+ }
+
+ /**
+ * Logs an event for binary push for module updates.
+ *
+ * @param trainName name of install train.
+ * @param trainVersionCode version code of the train.
+ * @param options optional flags about this install.
+ * @param state current install state.
+ * @param experimentIds experiment ids.
+ * @return True if the log request was sent to statsd.
+ */
+ @RequiresPermission(allOf = {DUMP, PACKAGE_USAGE_STATS})
+ public static boolean logBinaryPushStateChanged(@NonNull String trainName,
+ long trainVersionCode, int options, int state,
+ @NonNull long[] experimentIds) {
+ synchronized (sLogLock) {
+ try {
+ IStatsManager service = getIStatsManagerLocked();
+ if (service == null) {
+ if (DEBUG) {
+ Slog.d(TAG, "Failed to find statsd when logging event");
+ }
+ return false;
+ }
+ int userId = IActivityManager.Stub.asInterface(
+ ServiceManager.getService("activity"))
+ .getCurrentUser()
+ .id;
+ service.sendBinaryPushStateChangedAtom(
+ trainName, trainVersionCode, options, state, experimentIds);
+ return true;
+ } catch (RemoteException e) {
+ sService = null;
+ if (DEBUG) {
+ Slog.d(TAG,
+ "Failed to connect to StatsCompanionService when logging "
+ + "BinaryPushStateChanged");
+ }
return false;
}
}
@@ -118,7 +182,7 @@
/**
* Add a log to the stats log.
*
- * @param id The id of the atom
+ * @param id The id of the atom
* @param params The parameters of the atom's message.
*/
public static void write(int id, @NonNull Object... params) {
@@ -128,4 +192,13 @@
(boolean) params[4], (int) params[5]);
}
}
+
+ private static void enforceDumpCallingPermission(Context context) {
+ context.enforceCallingPermission(android.Manifest.permission.DUMP, "Need DUMP permission.");
+ }
+
+ private static void enforcesageStatsCallingPermission(Context context) {
+ context.enforceCallingPermission(Manifest.permission.PACKAGE_USAGE_STATS,
+ "Need PACKAGE_USAGE_STATS permission.");
+ }
}
diff --git a/core/java/android/view/Display.java b/core/java/android/view/Display.java
index 49bae28..cb5100a 100644
--- a/core/java/android/view/Display.java
+++ b/core/java/android/view/Display.java
@@ -76,7 +76,7 @@
private final int mLayerStack;
private final int mFlags;
private final int mType;
- private final String mAddress;
+ private final DisplayAddress mAddress;
private final int mOwnerUid;
private final String mOwnerPackageName;
private final Resources mResources;
@@ -557,7 +557,7 @@
* @hide
*/
@UnsupportedAppUsage
- public String getAddress() {
+ public DisplayAddress getAddress() {
return mAddress;
}
diff --git a/core/java/android/view/DisplayAddress.java b/core/java/android/view/DisplayAddress.java
new file mode 100644
index 0000000..17ea4c4
--- /dev/null
+++ b/core/java/android/view/DisplayAddress.java
@@ -0,0 +1,174 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.view;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+/** Display identifier that is stable across reboots.
+ *
+ * @hide
+ */
+public abstract class DisplayAddress implements Parcelable {
+ /**
+ * Creates an address for a physical display given its stable ID.
+ *
+ * A physical display ID is stable if the display can be identified using EDID information.
+ *
+ * @param physicalDisplayId A physical display ID.
+ * @return The {@link Physical} address, or {@code null} if the ID is not stable.
+ * @see SurfaceControl#getPhysicalDisplayIds
+ */
+ @Nullable
+ public static Physical fromPhysicalDisplayId(long physicalDisplayId) {
+ final Physical address = new Physical(physicalDisplayId);
+ return address.getModel() == 0 ? null : address;
+ }
+
+ /**
+ * Creates an address for a network display given its MAC address.
+ *
+ * @param macAddress A MAC address in colon notation.
+ * @return The {@link Network} address.
+ */
+ @NonNull
+ public static Network fromMacAddress(String macAddress) {
+ return new Network(macAddress);
+ }
+
+ /**
+ * Address for a physically connected display.
+ *
+ * A {@link Physical} address is represented by a 64-bit identifier combining the port and model
+ * of a display. The port, located in the least significant byte, uniquely identifies a physical
+ * connector on the device for display output like eDP or HDMI. The model, located in the upper
+ * bits, uniquely identifies a display model across manufacturers by encoding EDID information.
+ */
+ public static final class Physical extends DisplayAddress {
+ private static final int PHYSICAL_DISPLAY_ID_MODEL_SHIFT = 8;
+ private static final int PORT_MASK = 0xFF;
+
+ private final long mPhysicalDisplayId;
+
+ /**
+ * Physical port to which the display is connected.
+ */
+ public byte getPort() {
+ return (byte) mPhysicalDisplayId;
+ }
+
+ /**
+ * Model identifier unique across manufacturers.
+ */
+ public long getModel() {
+ return mPhysicalDisplayId >>> PHYSICAL_DISPLAY_ID_MODEL_SHIFT;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ return other instanceof Physical
+ && mPhysicalDisplayId == ((Physical) other).mPhysicalDisplayId;
+ }
+
+ @Override
+ public String toString() {
+ return new StringBuilder("{")
+ .append("port=").append(getPort() & PORT_MASK)
+ .append(", model=0x").append(Long.toHexString(getModel()))
+ .append("}")
+ .toString();
+ }
+
+ @Override
+ public int hashCode() {
+ return Long.hashCode(mPhysicalDisplayId);
+ }
+
+ @Override
+ public void writeToParcel(Parcel out, int flags) {
+ out.writeLong(mPhysicalDisplayId);
+ }
+
+ private Physical(long physicalDisplayId) {
+ mPhysicalDisplayId = physicalDisplayId;
+ }
+
+ public static final Parcelable.Creator<Physical> CREATOR =
+ new Parcelable.Creator<Physical>() {
+ @Override
+ public Physical createFromParcel(Parcel in) {
+ return new Physical(in.readLong());
+ }
+
+ @Override
+ public Physical[] newArray(int size) {
+ return new Physical[size];
+ }
+ };
+ }
+
+ /**
+ * Address for a network-connected display.
+ */
+ public static final class Network extends DisplayAddress {
+ private final String mMacAddress;
+
+ @Override
+ public boolean equals(Object other) {
+ return other instanceof Network && mMacAddress.equals(((Network) other).mMacAddress);
+ }
+
+ @Override
+ public String toString() {
+ return mMacAddress;
+ }
+
+ @Override
+ public int hashCode() {
+ return mMacAddress.hashCode();
+ }
+
+ @Override
+ public void writeToParcel(Parcel out, int flags) {
+ out.writeString(mMacAddress);
+ }
+
+ private Network(String macAddress) {
+ mMacAddress = macAddress;
+ }
+
+ public static final Parcelable.Creator<Network> CREATOR =
+ new Parcelable.Creator<Network>() {
+ @Override
+ public Network createFromParcel(Parcel in) {
+ return new Network(in.readString());
+ }
+
+ @Override
+ public Network[] newArray(int size) {
+ return new Network[size];
+ }
+ };
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+}
diff --git a/core/java/android/view/DisplayInfo.java b/core/java/android/view/DisplayInfo.java
index ad8fee9..3aa779b 100644
--- a/core/java/android/view/DisplayInfo.java
+++ b/core/java/android/view/DisplayInfo.java
@@ -61,7 +61,7 @@
* Display address, or null if none.
* Interpretation varies by display type.
*/
- public String address;
+ public DisplayAddress address;
/**
* The human-readable name of the display.
@@ -385,7 +385,7 @@
layerStack = source.readInt();
flags = source.readInt();
type = source.readInt();
- address = source.readString();
+ address = source.readParcelable(null);
name = source.readString();
appWidth = source.readInt();
appHeight = source.readInt();
@@ -432,7 +432,7 @@
dest.writeInt(layerStack);
dest.writeInt(this.flags);
dest.writeInt(type);
- dest.writeString(address);
+ dest.writeParcelable(address, flags);
dest.writeString(name);
dest.writeInt(appWidth);
dest.writeInt(appHeight);
diff --git a/core/java/android/view/GhostView.java b/core/java/android/view/GhostView.java
index 74c801b..3286bd6 100644
--- a/core/java/android/view/GhostView.java
+++ b/core/java/android/view/GhostView.java
@@ -20,6 +20,7 @@
import android.graphics.Matrix;
import android.graphics.RecordingCanvas;
import android.graphics.RenderNode;
+import android.os.Build;
import android.widget.FrameLayout;
import java.util.ArrayList;
@@ -135,12 +136,12 @@
return ghostView;
}
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
public static GhostView addGhost(View view, ViewGroup viewGroup) {
return addGhost(view, viewGroup, null);
}
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
public static void removeGhost(View view) {
GhostView ghostView = view.mGhostView;
if (ghostView != null) {
diff --git a/core/java/android/view/InputDevice.java b/core/java/android/view/InputDevice.java
index 7295259..868a9de 100644
--- a/core/java/android/view/InputDevice.java
+++ b/core/java/android/view/InputDevice.java
@@ -22,6 +22,7 @@
import android.content.Context;
import android.hardware.input.InputDeviceIdentifier;
import android.hardware.input.InputManager;
+import android.os.Build;
import android.os.NullVibrator;
import android.os.Parcel;
import android.os.Parcelable;
@@ -54,7 +55,7 @@
private final int mProductId;
private final String mDescriptor;
private final InputDeviceIdentifier mIdentifier;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
private final boolean mIsExternal;
private final int mSources;
private final int mKeyboardType;
@@ -608,10 +609,7 @@
* peripheral bus), otherwise it is built-in.
*
* @return True if the device is external.
- *
- * @hide
*/
- @UnsupportedAppUsage
public boolean isExternal() {
return mIsExternal;
}
diff --git a/core/java/android/view/LayoutInflater.java b/core/java/android/view/LayoutInflater.java
index 3f18d8b..f13cb5a 100644
--- a/core/java/android/view/LayoutInflater.java
+++ b/core/java/android/view/LayoutInflater.java
@@ -33,6 +33,8 @@
import android.os.Message;
import android.os.SystemProperties;
import android.os.Trace;
+import android.provider.DeviceConfig;
+import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
@@ -80,8 +82,6 @@
private static final String TAG = LayoutInflater.class.getSimpleName();
private static final boolean DEBUG = false;
- private static final String USE_PRECOMPILED_LAYOUT_SYSTEM_PROPERTY
- = "view.precompiled_layout_enabled";
private static final String COMPILED_VIEW_DEX_FILE_NAME = "/compiled_view.dex";
/** Empty stack trace used to avoid log spam in re-throw exceptions. */
@@ -95,7 +95,12 @@
protected final Context mContext;
// these are optional, set by the caller
- @UnsupportedAppUsage
+ /**
+ * If any developer has desire to change this value, they should instead use
+ * {@link #cloneInContext(Context)} and set the new factory in thew newly-created
+ * LayoutInflater.
+ */
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
private boolean mFactorySet;
@UnsupportedAppUsage
private Factory mFactory;
@@ -124,7 +129,7 @@
static final Class<?>[] mConstructorSignature = new Class[] {
Context.class, AttributeSet.class};
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123769490)
private static final HashMap<String, Constructor<? extends View>> sConstructorMap =
new HashMap<String, Constructor<? extends View>>();
@@ -407,8 +412,24 @@
}
private void initPrecompiledViews() {
- initPrecompiledViews(
- SystemProperties.getBoolean(USE_PRECOMPILED_LAYOUT_SYSTEM_PROPERTY, false));
+ // Use the device config if enabled, otherwise default to the system property.
+ String usePrecompiledLayout = null;
+ try {
+ usePrecompiledLayout = DeviceConfig.getProperty(
+ DeviceConfig.Runtime.NAMESPACE,
+ DeviceConfig.Runtime.USE_PRECOMPILED_LAYOUT);
+ } catch (Exception e) {
+ // May be caused by permission errors reading the property (i.e. instant apps).
+ }
+ boolean enabled = false;
+ if (TextUtils.isEmpty(usePrecompiledLayout)) {
+ enabled = SystemProperties.getBoolean(
+ DeviceConfig.Runtime.USE_PRECOMPILED_LAYOUT,
+ false);
+ } else {
+ enabled = Boolean.parseBoolean(usePrecompiledLayout);
+ }
+ initPrecompiledViews(enabled);
}
private void initPrecompiledViews(boolean enablePrecompiledViews) {
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 3f2795b..ba1b517 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -24,6 +24,7 @@
import android.animation.AnimatorInflater;
import android.animation.StateListAnimator;
+import android.annotation.AttrRes;
import android.annotation.CallSuper;
import android.annotation.ColorInt;
import android.annotation.DrawableRes;
@@ -4030,8 +4031,24 @@
/**
* {@hide}
+ *
+ * Not available for general use. If you need help, hang up and then dial one of the following
+ * public APIs:
+ *
+ * @see #isAttachedToWindow() for current attach state
+ * @see #onAttachedToWindow() for subclasses performing work when becoming attached
+ * @see #onDetachedFromWindow() for subclasses performing work when becoming detached
+ * @see OnAttachStateChangeListener for other code performing work on attach/detach
+ * @see #getHandler() for posting messages to this view's UI thread/looper
+ * @see #getParent() for interacting with the parent chain
+ * @see #getWindowToken() for the current window token
+ * @see #getRootView() for the view at the root of the attached hierarchy
+ * @see #getDisplay() for the Display this view is presented on
+ * @see #getRootWindowInsets() for the current insets applied to the whole attached window
+ * @see #hasWindowFocus() for whether the attached window is currently focused
+ * @see #getWindowVisibility() for checking the visibility of the attached window
*/
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
AttachInfo mAttachInfo;
/**
@@ -5092,7 +5109,7 @@
private SparseIntArray mAttributeSourceResId;
@Nullable
- private int[] mAttributeResolutionStack;
+ private SparseArray<int[]> mAttributeResolutionStacks;
@StyleRes
private int mExplicitStyle;
@@ -5947,11 +5964,12 @@
* <b>Note:</b> this method will only return actual values if the view attribute debugging
* is enabled in Android developer options.
*
+ * @param attribute Attribute resource ID for which the resolution stack should be returned.
* @return ordered list of resource ID that are considered when resolving attribute values for
* this {@link View}.
*/
@NonNull
- public List<Integer> getAttributeResolutionStack() {
+ public List<Integer> getAttributeResolutionStack(@AttrRes int attribute) {
ArrayList<Integer> stack = new ArrayList<>();
if (!sDebugViewAttributes) {
return stack;
@@ -5959,8 +5977,12 @@
if (mSourceLayoutId != ID_NULL) {
stack.add(mSourceLayoutId);
}
- for (int i = 0; i < mAttributeResolutionStack.length; i++) {
- stack.add(mAttributeResolutionStack[i]);
+ int[] attributeResolutionStack = mAttributeResolutionStacks.get(attribute);
+ if (attributeResolutionStack == null) {
+ return stack;
+ }
+ for (int i = 0; i < attributeResolutionStack.length; i++) {
+ stack.add(attributeResolutionStack[i]);
}
return stack;
}
@@ -6127,9 +6149,13 @@
return;
}
- mAttributeResolutionStack = context.getTheme().getAttributeResolutionStack(
+ int[] attributeResolutionStack = context.getTheme().getAttributeResolutionStack(
defStyleAttr, defStyleRes, mExplicitStyle);
+ if (mAttributeResolutionStacks == null) {
+ mAttributeResolutionStacks = new SparseArray<>();
+ }
+
if (mAttributeSourceResId == null) {
mAttributeSourceResId = new SparseIntArray();
}
@@ -6138,6 +6164,7 @@
for (int j = 0; j < indexCount; ++j) {
final int index = t.getIndex(j);
mAttributeSourceResId.append(styleable[index], t.getSourceResourceId(index, 0));
+ mAttributeResolutionStacks.append(styleable[index], attributeResolutionStack);
}
}
@@ -6440,6 +6467,16 @@
arr.recycle();
}
+ private void initializeScrollBarDrawable() {
+ initScrollCache();
+
+ if (mScrollCache.scrollBar == null) {
+ mScrollCache.scrollBar = new ScrollBarDrawable();
+ mScrollCache.scrollBar.setState(getDrawableState());
+ mScrollCache.scrollBar.setCallback(this);
+ }
+ }
+
/**
* <p>
* Initializes the scrollbars from a given set of styled attributes. This
@@ -6525,6 +6562,106 @@
resolvePadding();
}
+ /**
+ * Defines the vertical scrollbar thumb drawable
+ * @attr ref android.R.styleable#View_scrollbarThumbVertical
+ *
+ * @see #awakenScrollBars(int)
+ * @see #isVerticalScrollBarEnabled()
+ * @see #setVerticalScrollBarEnabled(boolean)
+ */
+ public void setVerticalScrollbarThumbDrawable(@Nullable Drawable drawable) {
+ initializeScrollBarDrawable();
+ mScrollCache.scrollBar.setVerticalThumbDrawable(drawable);
+ }
+
+ /**
+ * Defines the vertical scrollbar track drawable
+ * @attr ref android.R.styleable#View_scrollbarTrackVertical
+ *
+ * @see #awakenScrollBars(int)
+ * @see #isVerticalScrollBarEnabled()
+ * @see #setVerticalScrollBarEnabled(boolean)
+ */
+ public void setVerticalScrollbarTrackDrawable(@Nullable Drawable drawable) {
+ initializeScrollBarDrawable();
+ mScrollCache.scrollBar.setVerticalTrackDrawable(drawable);
+ }
+
+ /**
+ * Defines the horizontal thumb drawable
+ * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
+ *
+ * @see #awakenScrollBars(int)
+ * @see #isHorizontalScrollBarEnabled()
+ * @see #setHorizontalScrollBarEnabled(boolean)
+ */
+ public void setHorizontalScrollbarThumbDrawable(@Nullable Drawable drawable) {
+ initializeScrollBarDrawable();
+ mScrollCache.scrollBar.setHorizontalThumbDrawable(drawable);
+ }
+
+ /**
+ * Defines the horizontal track drawable
+ * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
+ *
+ * @see #awakenScrollBars(int)
+ * @see #isHorizontalScrollBarEnabled()
+ * @see #setHorizontalScrollBarEnabled(boolean)
+ */
+ public void setHorizontalScrollbarTrackDrawable(@Nullable Drawable drawable) {
+ initializeScrollBarDrawable();
+ mScrollCache.scrollBar.setHorizontalTrackDrawable(drawable);
+ }
+
+ /**
+ * Returns the currently configured Drawable for the thumb of the vertical scroll bar if it
+ * exists, null otherwise.
+ *
+ * @see #awakenScrollBars(int)
+ * @see #isVerticalScrollBarEnabled()
+ * @see #setVerticalScrollBarEnabled(boolean)
+ */
+ public @Nullable Drawable getVerticalScrollbarThumbDrawable() {
+ return mScrollCache != null ? mScrollCache.scrollBar.getVerticalThumbDrawable() : null;
+ }
+
+ /**
+ * Returns the currently configured Drawable for the track of the vertical scroll bar if it
+ * exists, null otherwise.
+ *
+ * @see #awakenScrollBars(int)
+ * @see #isVerticalScrollBarEnabled()
+ * @see #setVerticalScrollBarEnabled(boolean)
+ */
+ public @Nullable Drawable getVerticalScrollbarTrackDrawable() {
+ return mScrollCache != null ? mScrollCache.scrollBar.getVerticalTrackDrawable() : null;
+ }
+
+ /**
+ * Returns the currently configured Drawable for the thumb of the horizontal scroll bar if it
+ * exists, null otherwise.
+ *
+ * @see #awakenScrollBars(int)
+ * @see #isHorizontalScrollBarEnabled()
+ * @see #setHorizontalScrollBarEnabled(boolean)
+ */
+ public @Nullable Drawable getHorizontalScrollbarThumbDrawable() {
+ return mScrollCache != null ? mScrollCache.scrollBar.getHorizontalThumbDrawable() : null;
+ }
+
+ /**
+ * Returns the currently configured Drawable for the track of the horizontal scroll bar if it
+ * exists, null otherwise.
+ *
+ * @see #awakenScrollBars(int)
+ * @see #isHorizontalScrollBarEnabled()
+ * @see #setHorizontalScrollBarEnabled(boolean)
+ */
+ public @Nullable Drawable getHorizontalScrollbarTrackDrawable() {
+ return mScrollCache != null ? mScrollCache.scrollBar.getHorizontalTrackDrawable() : null;
+ }
+
private void initializeScrollIndicatorsInternal() {
// Some day maybe we'll break this into top/left/start/etc. and let the
// client control it. Until then, you can have any scroll indicator you
@@ -28193,18 +28330,6 @@
View mViewRequestingLayout;
/**
- * Used to track views that need (at least) a partial relayout at their current size
- * during the next traversal.
- */
- List<View> mPartialLayoutViews = new ArrayList<>();
-
- /**
- * Swapped with mPartialLayoutViews during layout to avoid concurrent
- * modification. Lazily assigned during ViewRootImpl layout.
- */
- List<View> mEmptyPartialLayoutViews;
-
- /**
* Used to track the identity of the current drag operation.
*/
IBinder mDragToken;
diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java
index d2b40f7..f2474a5 100644
--- a/core/java/android/view/ViewGroup.java
+++ b/core/java/android/view/ViewGroup.java
@@ -703,7 +703,9 @@
private void initFromAttributes(
Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
- final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ViewGroup, defStyleAttr,
+ final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ViewGroup,
+ defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.ViewGroup, attrs, a, defStyleAttr,
defStyleRes);
final int N = a.getIndexCount();
@@ -4299,6 +4301,20 @@
return i;
}
+ /**
+ * The public version of getChildDrawingOrder().
+ *
+ * Returns the index of the child to draw for this iteration.
+ *
+ * @param i The current iteration.
+ * @return The index of the child to draw this iteration.
+ *
+ * @see #getChildDrawingOrder(int, int)}
+ */
+ public final int getChildDrawingOrder(int i) {
+ return getChildDrawingOrder(getChildCount(), i);
+ }
+
private boolean hasChildWithZ() {
for (int i = 0; i < mChildrenCount; i++) {
if (mChildren[i].getZ() != 0) return true;
diff --git a/core/java/android/view/ViewStub.java b/core/java/android/view/ViewStub.java
index e9d1b87..9ca1632 100644
--- a/core/java/android/view/ViewStub.java
+++ b/core/java/android/view/ViewStub.java
@@ -108,6 +108,9 @@
final TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.ViewStub, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.ViewStub, attrs, a, defStyleAttr,
+ defStyleRes);
+
mInflatedId = a.getResourceId(R.styleable.ViewStub_inflatedId, NO_ID);
mLayoutResource = a.getResourceId(R.styleable.ViewStub_layout, 0);
mID = a.getResourceId(R.styleable.ViewStub_id, NO_ID);
diff --git a/core/java/android/view/accessibility/AccessibilityManager.java b/core/java/android/view/accessibility/AccessibilityManager.java
index 06207a9..384cdbb 100644
--- a/core/java/android/view/accessibility/AccessibilityManager.java
+++ b/core/java/android/view/accessibility/AccessibilityManager.java
@@ -174,7 +174,7 @@
final Handler.Callback mCallback;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
boolean mIsEnabled;
int mRelevantEventTypes = AccessibilityEvent.TYPES_ALL_MASK;
diff --git a/core/java/android/view/accessibility/OWNERS b/core/java/android/view/accessibility/OWNERS
new file mode 100644
index 0000000..265674a
--- /dev/null
+++ b/core/java/android/view/accessibility/OWNERS
@@ -0,0 +1,3 @@
+svetoslavganov@google.com
+pweaver@google.com
+rhedjao@google.com
diff --git a/core/java/android/view/animation/Animation.java b/core/java/android/view/animation/Animation.java
index dfd9a2e..e095094 100644
--- a/core/java/android/view/animation/Animation.java
+++ b/core/java/android/view/animation/Animation.java
@@ -23,6 +23,7 @@
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.RectF;
+import android.os.Build;
import android.os.Handler;
import android.os.SystemProperties;
import android.util.AttributeSet;
@@ -30,9 +31,6 @@
import dalvik.system.CloseGuard;
-import java.util.ArrayList;
-import java.util.List;
-
/**
* Abstraction for an Animation that can be applied to Views, Surfaces, or
* other objects. See the {@link android.view.animation animation package
@@ -187,15 +185,12 @@
/**
* An animation listener to be notified when the animation starts, ends or repeats.
*/
- @UnsupportedAppUsage
+ // If you need to chain the AnimationListener, wrap the existing Animation into an AnimationSet
+ // and add your new listener to that set
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 117519981)
private AnimationListener mListener;
/**
- * A list of animation listeners to be notified when the animation starts, ends or repeats.
- */
- private List<AnimationListener> mListeners;
-
- /**
* Desired Z order mode during animation.
*/
private int mZAdjustment;
@@ -833,7 +828,7 @@
}
private boolean hasAnimationListener() {
- return mListener != null || (mListeners != null && !mListeners.isEmpty());
+ return mListener != null;
}
/**
@@ -848,32 +843,6 @@
}
/**
- * <p>Adds an animation listener to this animation. The animation listener
- * is notified of animation events such as the end of the animation or the
- * repetition of the animation.</p>
- *
- * @param listener the animation listener to be notified
- */
- public void addAnimationListener(AnimationListener listener) {
- if (mListeners == null) {
- mListeners = new ArrayList<>(1);
- }
- mListeners.add(listener);
- }
-
- /**
- * <p>Removes an animation listener that has been added with
- * {@link #addAnimationListener(AnimationListener)}.</p>
- *
- * @param listener the animation listener to be removed
- */
- public void removeAnimationListener(AnimationListener listener) {
- if (mListeners != null) {
- mListeners.remove(listener);
- }
- }
-
- /**
* Gurantees that this animation has an interpolator. Will use
* a AccelerateDecelerateInterpolator is nothing else was specified.
*/
@@ -1003,33 +972,18 @@
if (mListener != null) {
mListener.onAnimationStart(this);
}
- if (mListeners != null && !mListeners.isEmpty()) {
- for (AnimationListener listener : mListeners) {
- listener.onAnimationStart(this);
- }
- }
}
void dispatchAnimationRepeat() {
if (mListener != null) {
mListener.onAnimationRepeat(this);
}
- if (mListeners != null && !mListeners.isEmpty()) {
- for (AnimationListener listener : mListeners) {
- listener.onAnimationRepeat(this);
- }
- }
}
void dispatchAnimationEnd() {
if (mListener != null) {
mListener.onAnimationEnd(this);
}
- if (mListeners != null && !mListeners.isEmpty()) {
- for (AnimationListener listener : mListeners) {
- listener.onAnimationEnd(this);
- }
- }
}
/**
diff --git a/core/java/android/view/autofill/AutofillManager.java b/core/java/android/view/autofill/AutofillManager.java
index 83fc0173..5e5c826 100644
--- a/core/java/android/view/autofill/AutofillManager.java
+++ b/core/java/android/view/autofill/AutofillManager.java
@@ -17,7 +17,6 @@
package android.view.autofill;
import static android.service.autofill.FillRequest.FLAG_MANUAL_REQUEST;
-import static android.util.DebugUtils.flagsToString;
import static android.view.autofill.Helper.sDebug;
import static android.view.autofill.Helper.sVerbose;
@@ -338,6 +337,14 @@
public static final int MAX_TEMP_AUGMENTED_SERVICE_DURATION_MS = 1_000 * 60 * 2; // 2 minutes
/**
+ * Disables Augmented Autofill.
+ *
+ * @hide
+ */
+ @TestApi
+ public static final int FLAG_SMART_SUGGESTION_OFF = 0x0;
+
+ /**
* Displays the Augment Autofill window using the same mechanism (such as a popup-window
* attached to the focused view) as the standard autofill.
*
@@ -347,13 +354,21 @@
public static final int FLAG_SMART_SUGGESTION_SYSTEM = 0x1;
/** @hide */
- @IntDef(flag = true, prefix = { "FLAG_SMART_SUGGESTION_" }, value = {
- FLAG_SMART_SUGGESTION_SYSTEM
- })
+ @IntDef(flag = false, value = { FLAG_SMART_SUGGESTION_OFF, FLAG_SMART_SUGGESTION_SYSTEM })
@Retention(RetentionPolicy.SOURCE)
public @interface SmartSuggestionMode {}
/**
+ * {@code DeviceConfig} property used to set which Smart Suggestion modes for Augmented Autofill
+ * are available.
+ *
+ * @hide
+ */
+ @TestApi
+ public static final String DEVICE_CONFIG_AUTOFILL_SMART_SUGGESTION_SUPPORTED_MODES =
+ "smart_suggestion_supported_modes";
+
+ /**
* Makes an authentication id from a request id and a dataset id.
*
* @param requestId The request id.
@@ -2347,7 +2362,14 @@
/** @hide */
public static String getSmartSuggestionModeToString(@SmartSuggestionMode int flags) {
- return flagsToString(AutofillManager.class, "FLAG_SMART_SUGGESTION_", flags);
+ switch (flags) {
+ case FLAG_SMART_SUGGESTION_OFF:
+ return "OFF";
+ case FLAG_SMART_SUGGESTION_SYSTEM:
+ return "SYSTEM";
+ default:
+ return "INVALID:" + flags;
+ }
}
@GuardedBy("mLock")
diff --git a/core/java/android/view/inputmethod/InputMethodManager.java b/core/java/android/view/inputmethod/InputMethodManager.java
index 8a09788..e63a406 100644
--- a/core/java/android/view/inputmethod/InputMethodManager.java
+++ b/core/java/android/view/inputmethod/InputMethodManager.java
@@ -1373,7 +1373,7 @@
* @hide
*/
@Deprecated
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123768499)
public void showSoftInputUnchecked(int flags, ResultReceiver resultReceiver) {
try {
Log.w(TAG, "showSoftInputUnchecked() is a hidden method, which will be removed "
diff --git a/core/java/android/view/textclassifier/TEST_MAPPING b/core/java/android/view/textclassifier/TEST_MAPPING
new file mode 100644
index 0000000..01a6ede
--- /dev/null
+++ b/core/java/android/view/textclassifier/TEST_MAPPING
@@ -0,0 +1,15 @@
+{
+ "presubmit": [
+ {
+ "name": "FrameworksCoreTests",
+ "options": [
+ {
+ "include-filter": "android.view.textclassifier"
+ },
+ {
+ "exclude-annotation": "androidx.test.filters.FlakyTest"
+ }
+ ]
+ }
+ ]
+}
diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java
index 2171fc5..3555822 100644
--- a/core/java/android/webkit/WebView.java
+++ b/core/java/android/webkit/WebView.java
@@ -760,7 +760,7 @@
* <p>
* The {@code encoding} parameter specifies whether the data is base64 or URL
* encoded. If the data is base64 encoded, the value of the encoding
- * parameter must be 'base64'. HTML can be encoded with {@link
+ * parameter must be {@code "base64"}. HTML can be encoded with {@link
* android.util.Base64#encodeToString(byte[],int)} like so:
* <pre>
* String unencodedHtml =
@@ -768,11 +768,15 @@
* String encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(), Base64.NO_PADDING);
* webView.loadData(encodedHtml, "text/html", "base64");
* </pre>
- * <p>
+ * <p class="note">
* For all other values of {@code encoding} (including {@code null}) it is assumed that the
* data uses ASCII encoding for octets inside the range of safe URL characters and use the
* standard %xx hex encoding of URLs for octets outside that range. See <a
* href="https://tools.ietf.org/html/rfc3986#section-2.2">RFC 3986</a> for more information.
+ * Applications targeting {@link android.os.Build.VERSION_CODES#Q} or later must either use
+ * base64 or encode any {@code #} characters in the content as {@code %23}, otherwise they
+ * will be treated as the end of the content and the remaining text used as a document
+ * fragment identifier.
* <p>
* The {@code mimeType} parameter specifies the format of the data.
* If WebView can't handle the specified MIME type, it will download the data.
@@ -820,7 +824,8 @@
* <p>
* If the base URL uses the data scheme, this method is equivalent to
* calling {@link #loadData(String,String,String) loadData()} and the
- * historyUrl is ignored, and the data will be treated as part of a data: URL.
+ * historyUrl is ignored, and the data will be treated as part of a data: URL,
+ * including the requirement that the content be URL-encoded or base64 encoded.
* If the base URL uses any other scheme, then the data will be loaded into
* the WebView as a plain string (i.e. not part of a data URL) and any URL-encoded
* entities in the string will not be decoded.
diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java
index 9d7a482..f01babe 100644
--- a/core/java/android/widget/AbsListView.java
+++ b/core/java/android/widget/AbsListView.java
@@ -325,13 +325,13 @@
/**
* The current position of the selector in the list.
*/
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
int mSelectorPosition = INVALID_POSITION;
/**
* Defines the selector's location and dimension at drawing time
*/
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
Rect mSelectorRect = new Rect();
/**
@@ -657,7 +657,7 @@
private Runnable mClearScrollingCache;
Runnable mPositionScrollAfterLayout;
private int mMinimumVelocity;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124051740)
private int mMaximumVelocity;
private float mVelocityScale = 1.0f;
@@ -875,6 +875,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.AbsListView, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.AbsListView, attrs, a, defStyleAttr,
+ defStyleRes);
final Drawable selector = a.getDrawable(R.styleable.AbsListView_listSelector);
if (selector != null) {
diff --git a/core/java/android/widget/AbsSeekBar.java b/core/java/android/widget/AbsSeekBar.java
index c8be1d6..cd5f2e2 100644
--- a/core/java/android/widget/AbsSeekBar.java
+++ b/core/java/android/widget/AbsSeekBar.java
@@ -107,6 +107,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.SeekBar, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.SeekBar, attrs, a, defStyleAttr,
+ defStyleRes);
final Drawable thumb = a.getDrawable(R.styleable.SeekBar_thumb);
setThumb(thumb);
diff --git a/core/java/android/widget/AbsSpinner.java b/core/java/android/widget/AbsSpinner.java
index 816c949..3dcba48 100644
--- a/core/java/android/widget/AbsSpinner.java
+++ b/core/java/android/widget/AbsSpinner.java
@@ -82,6 +82,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.AbsSpinner, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.AbsSpinner, attrs, a, defStyleAttr,
+ defStyleRes);
final CharSequence[] entries = a.getTextArray(R.styleable.AbsSpinner_entries);
if (entries != null) {
diff --git a/core/java/android/widget/ActivityChooserView.java b/core/java/android/widget/ActivityChooserView.java
index 58715ee..89ea074 100644
--- a/core/java/android/widget/ActivityChooserView.java
+++ b/core/java/android/widget/ActivityChooserView.java
@@ -232,6 +232,8 @@
TypedArray attributesArray = context.obtainStyledAttributes(attrs,
R.styleable.ActivityChooserView, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.ActivityChooserView, attrs,
+ attributesArray, defStyleAttr, defStyleRes);
mInitialActivityCount = attributesArray.getInt(
R.styleable.ActivityChooserView_initialActivityCount,
diff --git a/core/java/android/widget/AdapterViewAnimator.java b/core/java/android/widget/AdapterViewAnimator.java
index 6f29368..5174c1a 100644
--- a/core/java/android/widget/AdapterViewAnimator.java
+++ b/core/java/android/widget/AdapterViewAnimator.java
@@ -180,6 +180,9 @@
final TypedArray a = context.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.AdapterViewAnimator, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, com.android.internal.R.styleable.AdapterViewAnimator,
+ attrs, a, defStyleAttr, defStyleRes);
+
int resource = a.getResourceId(
com.android.internal.R.styleable.AdapterViewAnimator_inAnimation, 0);
if (resource > 0) {
diff --git a/core/java/android/widget/AdapterViewFlipper.java b/core/java/android/widget/AdapterViewFlipper.java
index 18d7470..065089f5 100644
--- a/core/java/android/widget/AdapterViewFlipper.java
+++ b/core/java/android/widget/AdapterViewFlipper.java
@@ -69,6 +69,8 @@
final TypedArray a = context.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.AdapterViewFlipper, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, com.android.internal.R.styleable.AdapterViewFlipper,
+ attrs, a, defStyleAttr, defStyleRes);
mFlipInterval = a.getInt(
com.android.internal.R.styleable.AdapterViewFlipper_flipInterval, DEFAULT_INTERVAL);
mAutoStart = a.getBoolean(
diff --git a/core/java/android/widget/AnalogClock.java b/core/java/android/widget/AnalogClock.java
index 795b034..339947a 100644
--- a/core/java/android/widget/AnalogClock.java
+++ b/core/java/android/widget/AnalogClock.java
@@ -81,6 +81,8 @@
final Resources r = context.getResources();
final TypedArray a = context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.AnalogClock, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, com.android.internal.R.styleable.AnalogClock,
+ attrs, a, defStyleAttr, defStyleRes);
mDial = a.getDrawable(com.android.internal.R.styleable.AnalogClock_dial);
if (mDial == null) {
diff --git a/core/java/android/widget/AutoCompleteTextView.java b/core/java/android/widget/AutoCompleteTextView.java
index 7ed7aa2..904a862 100644
--- a/core/java/android/widget/AutoCompleteTextView.java
+++ b/core/java/android/widget/AutoCompleteTextView.java
@@ -227,6 +227,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.AutoCompleteTextView, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.AutoCompleteTextView,
+ attrs, a, defStyleAttr, defStyleRes);
if (popupTheme != null) {
mPopupContext = new ContextThemeWrapper(context, popupTheme);
@@ -245,6 +247,8 @@
if (mPopupContext != context) {
pa = mPopupContext.obtainStyledAttributes(
attrs, R.styleable.AutoCompleteTextView, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.AutoCompleteTextView,
+ attrs, a, defStyleAttr, defStyleRes);
} else {
pa = a;
}
diff --git a/core/java/android/widget/CalendarView.java b/core/java/android/widget/CalendarView.java
index 6c74c8c..b552aa6 100644
--- a/core/java/android/widget/CalendarView.java
+++ b/core/java/android/widget/CalendarView.java
@@ -112,6 +112,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.CalendarView, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.CalendarView,
+ attrs, a, defStyleAttr, defStyleRes);
final int mode = a.getInt(R.styleable.CalendarView_calendarViewMode, MODE_HOLO);
a.recycle();
diff --git a/core/java/android/widget/CheckedTextView.java b/core/java/android/widget/CheckedTextView.java
index b7fdcbe..99440f8 100644
--- a/core/java/android/widget/CheckedTextView.java
+++ b/core/java/android/widget/CheckedTextView.java
@@ -90,6 +90,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.CheckedTextView, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.CheckedTextView,
+ attrs, a, defStyleAttr, defStyleRes);
final Drawable d = a.getDrawable(R.styleable.CheckedTextView_checkMark);
if (d != null) {
diff --git a/core/java/android/widget/Chronometer.java b/core/java/android/widget/Chronometer.java
index 66c35d9..0b67cad 100644
--- a/core/java/android/widget/Chronometer.java
+++ b/core/java/android/widget/Chronometer.java
@@ -116,6 +116,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.Chronometer, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, com.android.internal.R.styleable.Chronometer,
+ attrs, a, defStyleAttr, defStyleRes);
setFormat(a.getString(R.styleable.Chronometer_format));
setCountDown(a.getBoolean(R.styleable.Chronometer_countDown, false));
a.recycle();
diff --git a/core/java/android/widget/CompoundButton.java b/core/java/android/widget/CompoundButton.java
index a0f93da..3cfd373 100644
--- a/core/java/android/widget/CompoundButton.java
+++ b/core/java/android/widget/CompoundButton.java
@@ -100,6 +100,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.CompoundButton, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, com.android.internal.R.styleable.CompoundButton,
+ attrs, a, defStyleAttr, defStyleRes);
final Drawable d = a.getDrawable(com.android.internal.R.styleable.CompoundButton_button);
if (d != null) {
diff --git a/core/java/android/widget/DatePicker.java b/core/java/android/widget/DatePicker.java
index cca951c..ada4f00 100644
--- a/core/java/android/widget/DatePicker.java
+++ b/core/java/android/widget/DatePicker.java
@@ -161,6 +161,8 @@
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DatePicker,
defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.DatePicker,
+ attrs, a, defStyleAttr, defStyleRes);
final boolean isDialogMode = a.getBoolean(R.styleable.DatePicker_dialogMode, false);
final int requestedMode = a.getInt(R.styleable.DatePicker_datePickerMode, MODE_SPINNER);
final int firstDayOfWeek = a.getInt(R.styleable.DatePicker_firstDayOfWeek, 0);
diff --git a/core/java/android/widget/DayPickerView.java b/core/java/android/widget/DayPickerView.java
index f712d5f..67fef13 100644
--- a/core/java/android/widget/DayPickerView.java
+++ b/core/java/android/widget/DayPickerView.java
@@ -82,6 +82,8 @@
final TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.CalendarView, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.CalendarView,
+ attrs, a, defStyleAttr, defStyleRes);
final int firstDayOfWeek = a.getInt(R.styleable.CalendarView_firstDayOfWeek,
LocaleData.get(Locale.getDefault()).firstDayOfWeek);
diff --git a/core/java/android/widget/Editor.java b/core/java/android/widget/Editor.java
index 9c21ba6..ded3be4e 100644
--- a/core/java/android/widget/Editor.java
+++ b/core/java/android/widget/Editor.java
@@ -6020,9 +6020,6 @@
}
updateSelection(event);
- if (mTextView.hasSelection() && mEndHandle != null) {
- mEndHandle.updateMagnifier(event);
- }
break;
case MotionEvent.ACTION_UP:
@@ -6030,9 +6027,6 @@
break;
}
updateSelection(event);
- if (mEndHandle != null) {
- mEndHandle.dismissMagnifier();
- }
// No longer dragging to select text, let the parent intercept events.
mTextView.getParent().requestDisallowInterceptTouchEvent(false);
diff --git a/core/java/android/widget/ExpandableListView.java b/core/java/android/widget/ExpandableListView.java
index 33d1539..2cc013e 100644
--- a/core/java/android/widget/ExpandableListView.java
+++ b/core/java/android/widget/ExpandableListView.java
@@ -242,6 +242,8 @@
final TypedArray a = context.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.ExpandableListView, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, com.android.internal.R.styleable.ExpandableListView,
+ attrs, a, defStyleAttr, defStyleRes);
mGroupIndicator = a.getDrawable(
com.android.internal.R.styleable.ExpandableListView_groupIndicator);
diff --git a/core/java/android/widget/FrameLayout.java b/core/java/android/widget/FrameLayout.java
index 5723b94..3570c79 100644
--- a/core/java/android/widget/FrameLayout.java
+++ b/core/java/android/widget/FrameLayout.java
@@ -100,6 +100,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.FrameLayout, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.FrameLayout,
+ attrs, a, defStyleAttr, defStyleRes);
if (a.getBoolean(R.styleable.FrameLayout_measureAllChildren, false)) {
setMeasureAllChildren(true);
diff --git a/core/java/android/widget/Gallery.java b/core/java/android/widget/Gallery.java
index d6a0ae4..64192aa 100644
--- a/core/java/android/widget/Gallery.java
+++ b/core/java/android/widget/Gallery.java
@@ -213,6 +213,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.Gallery, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, com.android.internal.R.styleable.Gallery,
+ attrs, a, defStyleAttr, defStyleRes);
int index = a.getInt(com.android.internal.R.styleable.Gallery_gravity, -1);
if (index >= 0) {
diff --git a/core/java/android/widget/GridLayout.java b/core/java/android/widget/GridLayout.java
index c8abf18..1c8bb04 100644
--- a/core/java/android/widget/GridLayout.java
+++ b/core/java/android/widget/GridLayout.java
@@ -303,6 +303,8 @@
mDefaultGap = context.getResources().getDimensionPixelOffset(R.dimen.default_gap);
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.GridLayout, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.GridLayout,
+ attrs, a, defStyleAttr, defStyleRes);
try {
setRowCount(a.getInt(ROW_COUNT, DEFAULT_COUNT));
setColumnCount(a.getInt(COLUMN_COUNT, DEFAULT_COUNT));
diff --git a/core/java/android/widget/GridView.java b/core/java/android/widget/GridView.java
index bbbe369..a6129b0 100644
--- a/core/java/android/widget/GridView.java
+++ b/core/java/android/widget/GridView.java
@@ -150,6 +150,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.GridView, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.GridView,
+ attrs, a, defStyleAttr, defStyleRes);
int hSpacing = a.getDimensionPixelOffset(
R.styleable.GridView_horizontalSpacing, 0);
diff --git a/core/java/android/widget/HorizontalScrollView.java b/core/java/android/widget/HorizontalScrollView.java
index 1c5f837..25cfdc7 100644
--- a/core/java/android/widget/HorizontalScrollView.java
+++ b/core/java/android/widget/HorizontalScrollView.java
@@ -16,6 +16,7 @@
package android.widget;
+import android.annotation.ColorInt;
import android.annotation.NonNull;
import android.annotation.UnsupportedAppUsage;
import android.content.Context;
@@ -80,10 +81,24 @@
private final Rect mTempRect = new Rect();
@UnsupportedAppUsage
private OverScroller mScroller;
- @UnsupportedAppUsage
- private EdgeEffect mEdgeGlowLeft;
- @UnsupportedAppUsage
- private EdgeEffect mEdgeGlowRight;
+ /**
+ * Tracks the state of the left edge glow.
+ *
+ * Even though this field is practically final, we cannot make it final because there are apps
+ * setting it via reflection and they need to keep working until they target Q.
+ */
+ @NonNull
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124053130)
+ private EdgeEffect mEdgeGlowLeft = new EdgeEffect(getContext());
+
+ /**
+ * Tracks the state of the bottom edge glow.
+ *
+ * Even though this field is practically final, we cannot make it final because there are apps
+ * setting it via reflection and they need to keep working until they target Q.
+ */
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124052619)
+ private EdgeEffect mEdgeGlowRight = new EdgeEffect(getContext());
/**
* Position of the last motion event.
@@ -175,6 +190,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, android.R.styleable.HorizontalScrollView, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, android.R.styleable.HorizontalScrollView,
+ attrs, a, defStyleAttr, defStyleRes);
setFillViewport(a.getBoolean(android.R.styleable.HorizontalScrollView_fillViewport, false));
@@ -216,6 +233,74 @@
}
/**
+ * Sets the edge effect color for both left and right edge effects.
+ *
+ * @param color The color for the edge effects.
+ * @see #setLeftEdgeEffectColor(int)
+ * @see #setRightEdgeEffectColor(int)
+ * @see #getLeftEdgeEffectColor()
+ * @see #getRightEdgeEffectColor()
+ */
+ public void setEdgeEffectColor(@ColorInt int color) {
+ setLeftEdgeEffectColor(color);
+ setRightEdgeEffectColor(color);
+ }
+
+ /**
+ * Sets the right edge effect color.
+ *
+ * @param color The color for the right edge effect.
+ * @see #setLeftEdgeEffectColor(int)
+ * @see #setEdgeEffectColor(int)
+ * @see #getLeftEdgeEffectColor()
+ * @see #getRightEdgeEffectColor()
+ */
+ public void setRightEdgeEffectColor(@ColorInt int color) {
+ mEdgeGlowRight.setColor(color);
+ }
+
+ /**
+ * Sets the left edge effect color.
+ *
+ * @param color The color for the left edge effect.
+ * @see #setRightEdgeEffectColor(int)
+ * @see #setEdgeEffectColor(int)
+ * @see #getLeftEdgeEffectColor()
+ * @see #getRightEdgeEffectColor()
+ */
+ public void setLeftEdgeEffectColor(@ColorInt int color) {
+ mEdgeGlowLeft.setColor(color);
+ }
+
+ /**
+ * Returns the left edge effect color.
+ *
+ * @return The left edge effect color.
+ * @see #setEdgeEffectColor(int)
+ * @see #setLeftEdgeEffectColor(int)
+ * @see #setRightEdgeEffectColor(int)
+ * @see #getRightEdgeEffectColor()
+ */
+ @ColorInt
+ public int getLeftEdgeEffectColor() {
+ return mEdgeGlowLeft.getColor();
+ }
+
+ /**
+ * Returns the right edge effect color.
+ *
+ * @return The right edge effect color.
+ * @see #setEdgeEffectColor(int)
+ * @see #setLeftEdgeEffectColor(int)
+ * @see #setRightEdgeEffectColor(int)
+ * @see #getLeftEdgeEffectColor()
+ */
+ @ColorInt
+ public int getRightEdgeEffectColor() {
+ return mEdgeGlowRight.getColor();
+ }
+
+ /**
* @return The maximum amount this scroll view will scroll in response to
* an arrow event.
*/
@@ -665,7 +750,7 @@
mEdgeGlowLeft.onRelease();
}
}
- if (mEdgeGlowLeft != null
+ if (shouldDisplayEdgeEffects()
&& (!mEdgeGlowLeft.isFinished() || !mEdgeGlowRight.isFinished())) {
postInvalidateOnAnimation();
}
@@ -693,7 +778,7 @@
mIsBeingDragged = false;
recycleVelocityTracker();
- if (mEdgeGlowLeft != null) {
+ if (shouldDisplayEdgeEffects()) {
mEdgeGlowLeft.onRelease();
mEdgeGlowRight.onRelease();
}
@@ -708,7 +793,7 @@
mIsBeingDragged = false;
recycleVelocityTracker();
- if (mEdgeGlowLeft != null) {
+ if (shouldDisplayEdgeEffects()) {
mEdgeGlowLeft.onRelease();
mEdgeGlowRight.onRelease();
}
@@ -1650,26 +1735,15 @@
}
}
- @Override
- public void setOverScrollMode(int mode) {
- if (mode != OVER_SCROLL_NEVER) {
- if (mEdgeGlowLeft == null) {
- Context context = getContext();
- mEdgeGlowLeft = new EdgeEffect(context);
- mEdgeGlowRight = new EdgeEffect(context);
- }
- } else {
- mEdgeGlowLeft = null;
- mEdgeGlowRight = null;
- }
- super.setOverScrollMode(mode);
+ private boolean shouldDisplayEdgeEffects() {
+ return getOverScrollMode() != OVER_SCROLL_NEVER;
}
@SuppressWarnings({"SuspiciousNameCombination"})
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
- if (mEdgeGlowLeft != null) {
+ if (shouldDisplayEdgeEffects()) {
final int scrollX = mScrollX;
if (!mEdgeGlowLeft.isFinished()) {
final int restoreCount = canvas.save();
diff --git a/core/java/android/widget/ImageView.java b/core/java/android/widget/ImageView.java
index 800b19c..9ae62ef 100644
--- a/core/java/android/widget/ImageView.java
+++ b/core/java/android/widget/ImageView.java
@@ -200,6 +200,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.ImageView, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.ImageView,
+ attrs, a, defStyleAttr, defStyleRes);
final Drawable d = a.getDrawable(R.styleable.ImageView_src);
if (d != null) {
diff --git a/core/java/android/widget/LinearLayout.java b/core/java/android/widget/LinearLayout.java
index 64769b5..e833df9 100644
--- a/core/java/android/widget/LinearLayout.java
+++ b/core/java/android/widget/LinearLayout.java
@@ -264,6 +264,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.LinearLayout, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, com.android.internal.R.styleable.LinearLayout,
+ attrs, a, defStyleAttr, defStyleRes);
int index = a.getInt(com.android.internal.R.styleable.LinearLayout_orientation, -1);
if (index >= 0) {
diff --git a/core/java/android/widget/ListView.java b/core/java/android/widget/ListView.java
index 311f896..2aa019b 100644
--- a/core/java/android/widget/ListView.java
+++ b/core/java/android/widget/ListView.java
@@ -236,6 +236,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.ListView, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.ListView,
+ attrs, a, defStyleAttr, defStyleRes);
final CharSequence[] entries = a.getTextArray(R.styleable.ListView_entries);
if (entries != null) {
diff --git a/core/java/android/widget/NumberPicker.java b/core/java/android/widget/NumberPicker.java
index 157992a..dad2669 100644
--- a/core/java/android/widget/NumberPicker.java
+++ b/core/java/android/widget/NumberPicker.java
@@ -17,6 +17,8 @@
package android.widget;
import android.annotation.CallSuper;
+import android.annotation.ColorInt;
+import android.annotation.FloatRange;
import android.annotation.IntDef;
import android.annotation.IntRange;
import android.annotation.Px;
@@ -340,7 +342,7 @@
/**
* The {@link Paint} for drawing the selector.
*/
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
private final Paint mSelectorWheelPaint;
/**
@@ -639,6 +641,8 @@
// process style attributes
final TypedArray attributesArray = context.obtainStyledAttributes(
attrs, R.styleable.NumberPicker, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.NumberPicker,
+ attrs, attributesArray, defStyleAttr, defStyleRes);
final int layoutResId = attributesArray.getResourceId(
R.styleable.NumberPicker_internalLayout, DEFAULT_LAYOUT_RESOURCE_ID);
@@ -1716,6 +1720,44 @@
}
/**
+ * Sets the text color for all the states (normal, selected, focused) to be the given color.
+ *
+ * @param color A color value in the form 0xAARRGGBB.
+ */
+ public void setTextColor(@ColorInt int color) {
+ mSelectorWheelPaint.setColor(color);
+ mInputText.setTextColor(color);
+ invalidate();
+ }
+
+ /**
+ * @return the text color.
+ */
+ @ColorInt
+ public int getTextColor() {
+ return mSelectorWheelPaint.getColor();
+ }
+
+ /**
+ * Sets the text size to the given value. This value must be > 0
+ *
+ * @param size The size in pixel units.
+ */
+ public void setTextSize(@FloatRange(from = 0.0, fromInclusive = false) float size) {
+ mSelectorWheelPaint.setTextSize(size);
+ mInputText.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
+ invalidate();
+ }
+
+ /**
+ * @return the size (in pixels) of the text size in this NumberPicker.
+ */
+ @FloatRange(from = 0.0, fromInclusive = false)
+ public float getTextSize() {
+ return mSelectorWheelPaint.getTextSize();
+ }
+
+ /**
* Makes a measure spec that tries greedily to use the max value.
*
* @param measureSpec The measure spec.
diff --git a/core/java/android/widget/ProgressBar.java b/core/java/android/widget/ProgressBar.java
index 6b48c65..29f070e 100644
--- a/core/java/android/widget/ProgressBar.java
+++ b/core/java/android/widget/ProgressBar.java
@@ -203,7 +203,7 @@
private int mDuration;
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
private boolean mIndeterminate;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(trackingBug = 124049927)
private boolean mOnlyIndeterminate;
private Transformation mTransformation;
private AlphaAnimation mAnimation;
@@ -211,7 +211,12 @@
private Drawable mIndeterminateDrawable;
private Drawable mProgressDrawable;
- @UnsupportedAppUsage
+ /**
+ * Outside the framework, instead of accessing this directly, please use
+ * {@link #getCurrentDrawable()}, {@link #setProgressDrawable(Drawable)},
+ * {@link #setIndeterminateDrawable(Drawable)} and their tiled versions.
+ */
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
private Drawable mCurrentDrawable;
private ProgressTintInfo mProgressTintInfo;
@@ -262,6 +267,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.ProgressBar, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.ProgressBar,
+ attrs, a, defStyleAttr, defStyleRes);
mNoInvalidate = true;
@@ -1298,9 +1305,14 @@
}
/**
- * @return The drawable currently used to draw the progress bar
+ * Returns the drawable currently used to draw the progress bar. This will be
+ * either {@link #getProgressDrawable()} or {@link #getIndeterminateDrawable()}
+ * depending on whether the progress bar is in determinate or indeterminate mode.
+ *
+ * @return the drawable currently used to draw the progress bar
*/
- Drawable getCurrentDrawable() {
+ @Nullable
+ public Drawable getCurrentDrawable() {
return mCurrentDrawable;
}
diff --git a/core/java/android/widget/RadialTimePickerView.java b/core/java/android/widget/RadialTimePickerView.java
index 757a4ca..f3600b0 100644
--- a/core/java/android/widget/RadialTimePickerView.java
+++ b/core/java/android/widget/RadialTimePickerView.java
@@ -404,6 +404,8 @@
final Context context = getContext();
final TypedArray a = getContext().obtainStyledAttributes(attrs,
R.styleable.TimePicker, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.TimePicker,
+ attrs, a, defStyleAttr, defStyleRes);
final ColorStateList numbersTextColor = a.getColorStateList(
R.styleable.TimePicker_numbersTextColor);
diff --git a/core/java/android/widget/RadioGroup.java b/core/java/android/widget/RadioGroup.java
index ab12eac..c62c16c 100644
--- a/core/java/android/widget/RadioGroup.java
+++ b/core/java/android/widget/RadioGroup.java
@@ -98,6 +98,8 @@
// XML layout file
TypedArray attributes = context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.RadioGroup, com.android.internal.R.attr.radioButtonStyle, 0);
+ saveAttributeDataForStyleable(context, com.android.internal.R.styleable.RadioGroup,
+ attrs, attributes, com.android.internal.R.attr.radioButtonStyle, 0);
int value = attributes.getResourceId(R.styleable.RadioGroup_checkedButton, View.NO_ID);
if (value != View.NO_ID) {
diff --git a/core/java/android/widget/RatingBar.java b/core/java/android/widget/RatingBar.java
index 9f9fdee..3cf3d91 100644
--- a/core/java/android/widget/RatingBar.java
+++ b/core/java/android/widget/RatingBar.java
@@ -93,6 +93,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.RatingBar, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.RatingBar,
+ attrs, a, defStyleAttr, defStyleRes);
final int numStars = a.getInt(R.styleable.RatingBar_numStars, mNumStars);
setIsIndicator(a.getBoolean(R.styleable.RatingBar_isIndicator, !mIsUserSeekable));
final float rating = a.getFloat(R.styleable.RatingBar_rating, -1);
diff --git a/core/java/android/widget/RelativeLayout.java b/core/java/android/widget/RelativeLayout.java
index 556bfd1..109c0a4 100644
--- a/core/java/android/widget/RelativeLayout.java
+++ b/core/java/android/widget/RelativeLayout.java
@@ -257,6 +257,8 @@
Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.RelativeLayout, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.RelativeLayout,
+ attrs, a, defStyleAttr, defStyleRes);
mIgnoreGravity = a.getResourceId(R.styleable.RelativeLayout_ignoreGravity, View.NO_ID);
mGravity = a.getInt(R.styleable.RelativeLayout_gravity, mGravity);
a.recycle();
diff --git a/core/java/android/widget/ScrollBarDrawable.java b/core/java/android/widget/ScrollBarDrawable.java
index e91f87e..1bed32ec 100644
--- a/core/java/android/widget/ScrollBarDrawable.java
+++ b/core/java/android/widget/ScrollBarDrawable.java
@@ -17,12 +17,15 @@
package android.widget;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.annotation.UnsupportedAppUsage;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
+import android.os.Build;
+import android.view.View;
import com.android.internal.widget.ScrollBarUtils;
@@ -36,7 +39,7 @@
public class ScrollBarDrawable extends Drawable implements Drawable.Callback {
private Drawable mVerticalTrack;
private Drawable mHorizontalTrack;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123768422)
private Drawable mVerticalThumb;
private Drawable mHorizontalThumb;
@@ -226,7 +229,10 @@
}
}
- @UnsupportedAppUsage
+ /**
+ * @see android.view.View#setVerticalThumbDrawable(Drawable)
+ */
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
public void setVerticalThumbDrawable(Drawable thumb) {
if (mVerticalThumb != null) {
mVerticalThumb.setCallback(null);
@@ -236,6 +242,37 @@
mVerticalThumb = thumb;
}
+ /**
+ * @see View#getVerticalTrackDrawable()
+ */
+ public @Nullable Drawable getVerticalTrackDrawable() {
+ return mVerticalTrack;
+ }
+
+ /**
+ * @see View#getVerticalThumbDrawable()
+ */
+ public @Nullable Drawable getVerticalThumbDrawable() {
+ return mVerticalThumb;
+ }
+
+ /**
+ * @see View#getHorizontalTrackDrawable()
+ */
+ public @Nullable Drawable getHorizontalTrackDrawable() {
+ return mHorizontalTrack;
+ }
+
+ /**
+ * @see View#getHorizontalThumbDrawable()
+ */
+ public @Nullable Drawable getHorizontalThumbDrawable() {
+ return mHorizontalThumb;
+ }
+
+ /**
+ * @see android.view.View#setVerticalTrackDrawable(Drawable)
+ */
public void setVerticalTrackDrawable(Drawable track) {
if (mVerticalTrack != null) {
mVerticalTrack.setCallback(null);
@@ -245,7 +282,10 @@
mVerticalTrack = track;
}
- @UnsupportedAppUsage
+ /**
+ * @see android.view.View#setHorizontalThumbDrawable(Drawable)
+ */
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
public void setHorizontalThumbDrawable(Drawable thumb) {
if (mHorizontalThumb != null) {
mHorizontalThumb.setCallback(null);
diff --git a/core/java/android/widget/ScrollView.java b/core/java/android/widget/ScrollView.java
index c360903..7e72c6a 100644
--- a/core/java/android/widget/ScrollView.java
+++ b/core/java/android/widget/ScrollView.java
@@ -16,6 +16,7 @@
package android.widget;
+import android.annotation.ColorInt;
import android.annotation.NonNull;
import android.annotation.UnsupportedAppUsage;
import android.content.Context;
@@ -89,10 +90,25 @@
private final Rect mTempRect = new Rect();
@UnsupportedAppUsage
private OverScroller mScroller;
- @UnsupportedAppUsage
- private EdgeEffect mEdgeGlowTop;
- @UnsupportedAppUsage
- private EdgeEffect mEdgeGlowBottom;
+ /**
+ * Tracks the state of the top edge glow.
+ *
+ * Even though this field is practically final, we cannot make it final because there are apps
+ * setting it via reflection and they need to keep working until they target Q.
+ */
+ @NonNull
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123768600)
+ private EdgeEffect mEdgeGlowTop = new EdgeEffect(getContext());
+
+ /**
+ * Tracks the state of the bottom edge glow.
+ *
+ * Even though this field is practically final, we cannot make it final because there are apps
+ * setting it via reflection and they need to keep working until they target Q.
+ */
+ @NonNull
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123769386)
+ private EdgeEffect mEdgeGlowBottom = new EdgeEffect(getContext());
/**
* Position of the last motion event.
@@ -201,6 +217,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.ScrollView, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, com.android.internal.R.styleable.ScrollView,
+ attrs, a, defStyleAttr, defStyleRes);
setFillViewport(a.getBoolean(R.styleable.ScrollView_fillViewport, false));
@@ -247,6 +265,74 @@
}
/**
+ * Sets the edge effect color for both top and bottom edge effects.
+ *
+ * @param color The color for the edge effects.
+ * @see #setTopEdgeEffectColor(int)
+ * @see #setBottomEdgeEffectColor(int)
+ * @see #getTopEdgeEffectColor()
+ * @see #getBottomEdgeEffectColor()
+ */
+ public void setEdgeEffectColor(@ColorInt int color) {
+ setTopEdgeEffectColor(color);
+ setBottomEdgeEffectColor(color);
+ }
+
+ /**
+ * Sets the bottom edge effect color.
+ *
+ * @param color The color for the bottom edge effect.
+ * @see #setTopEdgeEffectColor(int)
+ * @see #setEdgeEffectColor(int)
+ * @see #getTopEdgeEffectColor()
+ * @see #getBottomEdgeEffectColor()
+ */
+ public void setBottomEdgeEffectColor(@ColorInt int color) {
+ mEdgeGlowBottom.setColor(color);
+ }
+
+ /**
+ * Sets the top edge effect color.
+ *
+ * @param color The color for the top edge effect.
+ * @see #setBottomEdgeEffectColor(int)
+ * @see #setEdgeEffectColor(int)
+ * @see #getTopEdgeEffectColor()
+ * @see #getBottomEdgeEffectColor()
+ */
+ public void setTopEdgeEffectColor(@ColorInt int color) {
+ mEdgeGlowTop.setColor(color);
+ }
+
+ /**
+ * Returns the top edge effect color.
+ *
+ * @return The top edge effect color.
+ * @see #setEdgeEffectColor(int)
+ * @see #setTopEdgeEffectColor(int)
+ * @see #setBottomEdgeEffectColor(int)
+ * @see #getBottomEdgeEffectColor()
+ */
+ @ColorInt
+ public int getTopEdgeEffectColor() {
+ return mEdgeGlowTop.getColor();
+ }
+
+ /**
+ * Returns the bottom edge effect color.
+ *
+ * @return The bottom edge effect color.
+ * @see #setEdgeEffectColor(int)
+ * @see #setTopEdgeEffectColor(int)
+ * @see #setBottomEdgeEffectColor(int)
+ * @see #getTopEdgeEffectColor()
+ */
+ @ColorInt
+ public int getBottomEdgeEffectColor() {
+ return mEdgeGlowBottom.getColor();
+ }
+
+ /**
* @return The maximum amount this scroll view will scroll in response to
* an arrow event.
*/
@@ -624,6 +710,10 @@
return mIsBeingDragged;
}
+ private boolean shouldDisplayEdgeEffects() {
+ return getOverScrollMode() != OVER_SCROLL_NEVER;
+ }
+
@Override
public boolean onTouchEvent(MotionEvent ev) {
initVelocityTrackerIfNotExists();
@@ -732,7 +822,7 @@
mEdgeGlowTop.onRelease();
}
}
- if (mEdgeGlowTop != null
+ if (shouldDisplayEdgeEffects()
&& (!mEdgeGlowTop.isFinished() || !mEdgeGlowBottom.isFinished())) {
postInvalidateOnAnimation();
}
@@ -1670,7 +1760,7 @@
recycleVelocityTracker();
- if (mEdgeGlowTop != null) {
+ if (shouldDisplayEdgeEffects()) {
mEdgeGlowTop.onRelease();
mEdgeGlowBottom.onRelease();
}
@@ -1700,21 +1790,6 @@
}
@Override
- public void setOverScrollMode(int mode) {
- if (mode != OVER_SCROLL_NEVER) {
- if (mEdgeGlowTop == null) {
- Context context = getContext();
- mEdgeGlowTop = new EdgeEffect(context);
- mEdgeGlowBottom = new EdgeEffect(context);
- }
- } else {
- mEdgeGlowTop = null;
- mEdgeGlowBottom = null;
- }
- super.setOverScrollMode(mode);
- }
-
- @Override
public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
return (nestedScrollAxes & SCROLL_AXIS_VERTICAL) != 0;
}
@@ -1758,7 +1833,7 @@
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
- if (mEdgeGlowTop != null) {
+ if (shouldDisplayEdgeEffects()) {
final int scrollY = mScrollY;
final boolean clipToPadding = getClipToPadding();
if (!mEdgeGlowTop.isFinished()) {
diff --git a/core/java/android/widget/SearchView.java b/core/java/android/widget/SearchView.java
index af3b8c0..630c38a 100644
--- a/core/java/android/widget/SearchView.java
+++ b/core/java/android/widget/SearchView.java
@@ -283,6 +283,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.SearchView, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.SearchView,
+ attrs, a, defStyleAttr, defStyleRes);
final LayoutInflater inflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
final int layoutResId = a.getResourceId(
diff --git a/core/java/android/widget/SlidingDrawer.java b/core/java/android/widget/SlidingDrawer.java
index 8011c3a..2ab2b24 100644
--- a/core/java/android/widget/SlidingDrawer.java
+++ b/core/java/android/widget/SlidingDrawer.java
@@ -218,6 +218,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.SlidingDrawer, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.SlidingDrawer,
+ attrs, a, defStyleAttr, defStyleRes);
int orientation = a.getInt(R.styleable.SlidingDrawer_orientation, ORIENTATION_VERTICAL);
mVertical = orientation == ORIENTATION_VERTICAL;
diff --git a/core/java/android/widget/Spinner.java b/core/java/android/widget/Spinner.java
index fb56d97..d6c657b 100644
--- a/core/java/android/widget/Spinner.java
+++ b/core/java/android/widget/Spinner.java
@@ -247,6 +247,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.Spinner, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.Spinner,
+ attrs, a, defStyleAttr, defStyleRes);
if (popupTheme != null) {
mPopupContext = new ContextThemeWrapper(context, popupTheme);
diff --git a/core/java/android/widget/StackView.java b/core/java/android/widget/StackView.java
index 6cc86b9..5091eea 100644
--- a/core/java/android/widget/StackView.java
+++ b/core/java/android/widget/StackView.java
@@ -176,6 +176,8 @@
super(context, attrs, defStyleAttr, defStyleRes);
final TypedArray a = context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.StackView, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, com.android.internal.R.styleable.StackView,
+ attrs, a, defStyleAttr, defStyleRes);
mResOutColor = a.getColor(
com.android.internal.R.styleable.StackView_resOutColor, 0);
diff --git a/core/java/android/widget/Switch.java b/core/java/android/widget/Switch.java
index af4f0202..ea9cd42 100644
--- a/core/java/android/widget/Switch.java
+++ b/core/java/android/widget/Switch.java
@@ -239,6 +239,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.Switch, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, com.android.internal.R.styleable.Switch,
+ attrs, a, defStyleAttr, defStyleRes);
mThumbDrawable = a.getDrawable(com.android.internal.R.styleable.Switch_thumb);
if (mThumbDrawable != null) {
mThumbDrawable.setCallback(this);
diff --git a/core/java/android/widget/TabHost.java b/core/java/android/widget/TabHost.java
index b1fcbc3..481704c 100644
--- a/core/java/android/widget/TabHost.java
+++ b/core/java/android/widget/TabHost.java
@@ -93,6 +93,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.TabWidget, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, com.android.internal.R.styleable.TabWidget,
+ attrs, a, defStyleAttr, defStyleRes);
mTabLayoutId = a.getResourceId(R.styleable.TabWidget_tabLayout, 0);
a.recycle();
diff --git a/core/java/android/widget/TabWidget.java b/core/java/android/widget/TabWidget.java
index a90741b4..49a0f39 100644
--- a/core/java/android/widget/TabWidget.java
+++ b/core/java/android/widget/TabWidget.java
@@ -95,6 +95,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.TabWidget, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.TabWidget,
+ attrs, a, defStyleAttr, defStyleRes);
mDrawBottomStrips = a.getBoolean(R.styleable.TabWidget_tabStripEnabled, mDrawBottomStrips);
diff --git a/core/java/android/widget/TextClock.java b/core/java/android/widget/TextClock.java
index 7f462cb3..616c4b5 100644
--- a/core/java/android/widget/TextClock.java
+++ b/core/java/android/widget/TextClock.java
@@ -242,6 +242,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.TextClock, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.TextClock,
+ attrs, a, defStyleAttr, defStyleRes);
try {
mFormat12 = a.getText(R.styleable.TextClock_format12Hour);
mFormat24 = a.getText(R.styleable.TextClock_format24Hour);
@@ -610,8 +612,16 @@
resolver.registerContentObserver(uri, true,
mFormatChangeObserver, UserHandle.USER_ALL);
} else {
+ // UserHandle.myUserId() is needed. This class is supported by the
+ // remote views mechanism and as a part of that the remote views
+ // can be inflated by a context for another user without the app
+ // having interact users permission - just for loading resources.
+ // For example, when adding widgets from a managed profile to the
+ // home screen. Therefore, we register the ContentObserver with the user
+ // the app is running (e.g. the launcher) and not the user of the
+ // context (e.g. the widget's profile).
resolver.registerContentObserver(uri, true,
- mFormatChangeObserver);
+ mFormatChangeObserver, UserHandle.myUserId());
}
}
}
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index d876001..51eaa12 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -664,7 +664,7 @@
@UnsupportedAppUsage
private CharWrapper mCharWrapper;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(trackingBug = 124050217)
private Marquee mMarquee;
@UnsupportedAppUsage
private boolean mRestartMarquee;
diff --git a/core/java/android/widget/TimePicker.java b/core/java/android/widget/TimePicker.java
index b239ce6..97a8ade 100644
--- a/core/java/android/widget/TimePicker.java
+++ b/core/java/android/widget/TimePicker.java
@@ -127,6 +127,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.TimePicker, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.TimePicker,
+ attrs, a, defStyleAttr, defStyleRes);
final boolean isDialogMode = a.getBoolean(R.styleable.TimePicker_dialogMode, false);
final int requestedMode = a.getInt(R.styleable.TimePicker_timePickerMode, MODE_SPINNER);
a.recycle();
diff --git a/core/java/android/widget/ToggleButton.java b/core/java/android/widget/ToggleButton.java
index bba6da6..b76c2ca 100644
--- a/core/java/android/widget/ToggleButton.java
+++ b/core/java/android/widget/ToggleButton.java
@@ -48,6 +48,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.ToggleButton, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, com.android.internal.R.styleable.ToggleButton,
+ attrs, a, defStyleAttr, defStyleRes);
mTextOn = a.getText(com.android.internal.R.styleable.ToggleButton_textOn);
mTextOff = a.getText(com.android.internal.R.styleable.ToggleButton_textOff);
mDisabledAlpha = a.getFloat(com.android.internal.R.styleable.ToggleButton_disabledAlpha, 0.5f);
diff --git a/core/java/android/widget/Toolbar.java b/core/java/android/widget/Toolbar.java
index a33c47d8..f25109e 100644
--- a/core/java/android/widget/Toolbar.java
+++ b/core/java/android/widget/Toolbar.java
@@ -237,6 +237,8 @@
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Toolbar,
defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, R.styleable.Toolbar,
+ attrs, a, defStyleAttr, defStyleRes);
mTitleTextAppearance = a.getResourceId(R.styleable.Toolbar_titleTextAppearance, 0);
mSubtitleTextAppearance = a.getResourceId(R.styleable.Toolbar_subtitleTextAppearance, 0);
diff --git a/core/java/android/widget/TwoLineListItem.java b/core/java/android/widget/TwoLineListItem.java
index 553b86e..4c613a71 100644
--- a/core/java/android/widget/TwoLineListItem.java
+++ b/core/java/android/widget/TwoLineListItem.java
@@ -62,6 +62,8 @@
final TypedArray a = context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.TwoLineListItem, defStyleAttr, defStyleRes);
+ saveAttributeDataForStyleable(context, com.android.internal.R.styleable.TwoLineListItem,
+ attrs, a, defStyleAttr, defStyleRes);
a.recycle();
}
diff --git a/core/java/com/android/internal/app/ChooserActivity.java b/core/java/com/android/internal/app/ChooserActivity.java
index 119a015..8ebcef5 100644
--- a/core/java/com/android/internal/app/ChooserActivity.java
+++ b/core/java/com/android/internal/app/ChooserActivity.java
@@ -46,6 +46,7 @@
import android.content.pm.ResolveInfo;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
+import android.database.Cursor;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.graphics.Canvas;
@@ -69,6 +70,8 @@
import android.os.UserHandle;
import android.os.UserManager;
import android.os.storage.StorageManager;
+import android.provider.DocumentsContract;
+import android.provider.OpenableColumns;
import android.service.chooser.ChooserTarget;
import android.service.chooser.ChooserTargetService;
import android.service.chooser.IChooserTargetResult;
@@ -87,7 +90,6 @@
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
-import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
@@ -373,50 +375,6 @@
super.onCreate(savedInstanceState, target, title, defaultTitleRes, initialIntents,
null, false);
- Button copyButton = findViewById(R.id.copy_button);
- copyButton.setOnClickListener(view -> {
- Intent targetIntent = getTargetIntent();
- if (targetIntent == null) {
- finish();
- } else {
- final String action = targetIntent.getAction();
-
- ClipData clipData = null;
- if (Intent.ACTION_SEND.equals(action)) {
- String extraText = targetIntent.getStringExtra(Intent.EXTRA_TEXT);
- Uri extraStream = targetIntent.getParcelableExtra(Intent.EXTRA_STREAM);
-
- if (extraText != null) {
- clipData = ClipData.newPlainText(null, extraText);
- } else if (extraStream != null) {
- clipData = ClipData.newUri(getContentResolver(), null, extraStream);
- } else {
- Log.w(TAG, "No data available to copy to clipboard");
- return;
- }
- } else if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
- final ArrayList<Uri> streams = targetIntent.getParcelableArrayListExtra(
- Intent.EXTRA_STREAM);
- clipData = ClipData.newUri(getContentResolver(), null, streams.get(0));
- for (int i = 1; i < streams.size(); i++) {
- clipData.addItem(getContentResolver(), new ClipData.Item(streams.get(i)));
- }
- } else {
- // expected to only be visible with ACTION_SEND or ACTION_SEND_MULTIPLE
- // so warn about unexpected action
- Log.w(TAG, "Action (" + action + ") not supported for copying to clipboard");
- return;
- }
-
- ClipboardManager clipboardManager = (ClipboardManager) getSystemService(
- Context.CLIPBOARD_SERVICE);
- clipboardManager.setPrimaryClip(clipData);
- Toast.makeText(getApplicationContext(), R.string.copied, Toast.LENGTH_SHORT).show();
-
- finish();
- }
- });
-
mChooserShownTime = System.currentTimeMillis();
final long systemCost = mChooserShownTime - intentReceivedTime;
@@ -474,6 +432,10 @@
return;
}
+ if (mChooserListAdapter == null || mChooserListAdapter.getCount() == 0) {
+ return;
+ }
+
int previewType = findPreferredContentPreview(targetIntent, getContentResolver());
getMetricsLogger().write(new LogMaker(MetricsEvent.ACTION_SHARE_WITH_PREVIEW)
@@ -481,6 +443,49 @@
displayContentPreview(previewType, targetIntent);
}
+ private void onCopyButtonClicked(View v) {
+ Intent targetIntent = getTargetIntent();
+ if (targetIntent == null) {
+ finish();
+ } else {
+ final String action = targetIntent.getAction();
+
+ ClipData clipData = null;
+ if (Intent.ACTION_SEND.equals(action)) {
+ String extraText = targetIntent.getStringExtra(Intent.EXTRA_TEXT);
+ Uri extraStream = targetIntent.getParcelableExtra(Intent.EXTRA_STREAM);
+
+ if (extraText != null) {
+ clipData = ClipData.newPlainText(null, extraText);
+ } else if (extraStream != null) {
+ clipData = ClipData.newUri(getContentResolver(), null, extraStream);
+ } else {
+ Log.w(TAG, "No data available to copy to clipboard");
+ return;
+ }
+ } else if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
+ final ArrayList<Uri> streams = targetIntent.getParcelableArrayListExtra(
+ Intent.EXTRA_STREAM);
+ clipData = ClipData.newUri(getContentResolver(), null, streams.get(0));
+ for (int i = 1; i < streams.size(); i++) {
+ clipData.addItem(getContentResolver(), new ClipData.Item(streams.get(i)));
+ }
+ } else {
+ // expected to only be visible with ACTION_SEND or ACTION_SEND_MULTIPLE
+ // so warn about unexpected action
+ Log.w(TAG, "Action (" + action + ") not supported for copying to clipboard");
+ return;
+ }
+
+ ClipboardManager clipboardManager = (ClipboardManager) getSystemService(
+ Context.CLIPBOARD_SERVICE);
+ clipboardManager.setPrimaryClip(clipData);
+ Toast.makeText(getApplicationContext(), R.string.copied, Toast.LENGTH_SHORT).show();
+
+ finish();
+ }
+ }
+
private void displayContentPreview(@ContentPreviewType int previewType, Intent targetIntent) {
switch (previewType) {
case CONTENT_PREVIEW_TEXT:
@@ -501,6 +506,8 @@
ViewGroup contentPreviewLayout = findViewById(R.id.content_preview_text_area);
contentPreviewLayout.setVisibility(View.VISIBLE);
+ findViewById(R.id.copy_button).setOnClickListener(this::onCopyButtonClicked);
+
CharSequence sharingText = targetIntent.getCharSequenceExtra(Intent.EXTRA_TEXT);
if (sharingText == null) {
findViewById(R.id.content_preview_text_layout).setVisibility(View.GONE);
@@ -510,7 +517,7 @@
}
String previewTitle = targetIntent.getStringExtra(Intent.EXTRA_TITLE);
- if (previewTitle == null || previewTitle.trim().isEmpty()) {
+ if (TextUtils.isEmpty(previewTitle)) {
findViewById(R.id.content_preview_title_layout).setVisibility(View.GONE);
} else {
TextView previewTitleView = findViewById(R.id.content_preview_title);
@@ -561,6 +568,7 @@
if (imageUris.size() == 0) {
Log.i(TAG, "Attempted to display image preview area with zero"
+ " available images detected in EXTRA_STREAM list");
+ contentPreviewLayout.setVisibility(View.GONE);
return;
}
@@ -580,15 +588,95 @@
}
}
+ private static class FileInfo {
+ public final String name;
+ public final boolean hasThumbnail;
+
+ FileInfo(String name, boolean hasThumbnail) {
+ this.name = name;
+ this.hasThumbnail = hasThumbnail;
+ }
+ }
+
+ private FileInfo extractFileInfo(Uri uri, ContentResolver resolver) {
+ String fileName = null;
+ boolean hasThumbnail = false;
+ Cursor cursor = resolver.query(uri, null, null, null, null);
+ if (cursor != null && cursor.getCount() > 0) {
+ int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
+ int flagsIndex = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_FLAGS);
+
+ cursor.moveToFirst();
+ fileName = cursor.getString(nameIndex);
+ if (flagsIndex != -1) {
+ hasThumbnail = (cursor.getInt(flagsIndex)
+ & DocumentsContract.Document.FLAG_SUPPORTS_THUMBNAIL) != 0;
+ }
+ }
+
+ if (TextUtils.isEmpty(fileName)) {
+ fileName = uri.getPath();
+ int index = fileName.lastIndexOf('/');
+ if (index != -1) {
+ fileName = fileName.substring(index + 1);
+ }
+ }
+
+ return new FileInfo(fileName, hasThumbnail);
+ }
+
private void displayFileContentPreview(Intent targetIntent) {
- // support coming
+ ViewGroup contentPreviewLayout = findViewById(R.id.content_preview_file_area);
+ contentPreviewLayout.setVisibility(View.VISIBLE);
+
+ // TODO(b/120417119): Disable file copy until after moving to sysui,
+ // due to permissions issues
+ findViewById(R.id.file_copy_button).setVisibility(View.GONE);
+
+ ContentResolver resolver = getContentResolver();
+ TextView fileNameView = findViewById(R.id.content_preview_filename);
+ String action = targetIntent.getAction();
+ if (Intent.ACTION_SEND.equals(action)) {
+ Uri uri = targetIntent.getParcelableExtra(Intent.EXTRA_STREAM);
+
+ FileInfo fileInfo = extractFileInfo(uri, resolver);
+ fileNameView.setText(fileInfo.name);
+
+ if (fileInfo.hasThumbnail) {
+ loadUriIntoView(R.id.content_preview_file_thumbnail, uri);
+ } else {
+ ImageView fileIconView = findViewById(R.id.content_preview_file_icon);
+ fileIconView.setVisibility(View.VISIBLE);
+ fileIconView.setImageResource(R.drawable.ic_doc_generic);
+ }
+ } else {
+ List<Uri> uris = targetIntent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
+ if (uris.size() == 0) {
+ contentPreviewLayout.setVisibility(View.GONE);
+ Log.i(TAG,
+ "Appears to be no uris available in EXTRA_STREAM, removing preview area");
+ return;
+ }
+
+ FileInfo fileInfo = extractFileInfo(uris.get(0), resolver);
+ int remFileCount = uris.size() - 1;
+ String fileName = getResources().getQuantityString(R.plurals.file_count,
+ remFileCount, fileInfo.name, remFileCount);
+
+ fileNameView.setText(fileName);
+ ImageView fileIconView = findViewById(R.id.content_preview_file_icon);
+ fileIconView.setVisibility(View.VISIBLE);
+ fileIconView.setImageResource(R.drawable.ic_file_copy);
+ }
}
private RoundedRectImageView loadUriIntoView(int imageResourceId, Uri uri) {
RoundedRectImageView imageView = findViewById(imageResourceId);
- imageView.setVisibility(View.VISIBLE);
Bitmap bmp = loadThumbnail(uri, new Size(200, 200));
- imageView.setImageBitmap(bmp);
+ if (bmp != null) {
+ imageView.setVisibility(View.VISIBLE);
+ imageView.setImageBitmap(bmp);
+ }
return imageView;
}
@@ -1261,9 +1349,8 @@
}
try {
- return ImageUtils.decodeSampledBitmapFromStream(getContentResolver(),
- uri, size.getWidth(), size.getHeight());
- } catch (IOException | NullPointerException ex) {
+ return ImageUtils.loadThumbnail(getContentResolver(), uri, size);
+ } catch (IOException | NullPointerException | SecurityException ex) {
Log.w(TAG, "Error loading preview thumbnail for uri: " + uri.toString(), ex);
}
return null;
diff --git a/core/java/com/android/internal/os/BinderCallsStats.java b/core/java/com/android/internal/os/BinderCallsStats.java
index 2c272de..7f4d8a2 100644
--- a/core/java/com/android/internal/os/BinderCallsStats.java
+++ b/core/java/com/android/internal/os/BinderCallsStats.java
@@ -52,6 +52,8 @@
public static final boolean ENABLED_DEFAULT = true;
public static final boolean DETAILED_TRACKING_DEFAULT = true;
public static final int PERIODIC_SAMPLING_INTERVAL_DEFAULT = 100;
+ public static final boolean DEFAULT_TRACK_SCREEN_INTERACTIVE = false;
+ public static final boolean DEFAULT_TRACK_DIRECT_CALLING_UID = true;
public static final int MAX_BINDER_CALL_STATS_COUNT_DEFAULT = 5000;
private static final String DEBUG_ENTRY_PREFIX = "__DEBUG_";
@@ -85,6 +87,8 @@
private long mStartElapsedTime = SystemClock.elapsedRealtime();
private long mCallStatsCount = 0;
private boolean mAddDebugEntries = false;
+ private boolean mTrackDirectCallingUid = DEFAULT_TRACK_DIRECT_CALLING_UID;
+ private boolean mTrackScreenInteractive = DEFAULT_TRACK_SCREEN_INTERACTIVE;
private CachedDeviceState.Readonly mDeviceState;
private CachedDeviceState.TimeInStateStopwatch mBatteryStopwatch;
@@ -160,7 +164,12 @@
duration = 0;
latencyDuration = 0;
}
- final int callingUid = getCallingUid();
+ final boolean screenInteractive = mTrackScreenInteractive
+ ? mDeviceState.isScreenInteractive()
+ : OVERFLOW_SCREEN_INTERACTIVE;
+ final int callingUid = mTrackDirectCallingUid
+ ? getCallingUid()
+ : OVERFLOW_DIRECT_CALLING_UID;
synchronized (mLock) {
// This was already checked in #callStart but check again while synchronized.
@@ -177,7 +186,7 @@
final CallStat callStat = uidEntry.getOrCreate(
callingUid, s.binderClass, s.transactionCode,
- mDeviceState.isScreenInteractive(),
+ screenInteractive,
mCallStatsCount >= mMaxBinderCallStatsCount);
final boolean isNewCallStat = callStat.callCount == 0;
if (isNewCallStat) {
@@ -484,6 +493,30 @@
}
}
+ /**
+ * Whether to track the screen state.
+ */
+ public void setTrackScreenInteractive(boolean enabled) {
+ synchronized (mLock) {
+ if (enabled != mTrackScreenInteractive) {
+ mTrackScreenInteractive = enabled;
+ reset();
+ }
+ }
+ }
+
+ /**
+ * Whether to track direct caller uid.
+ */
+ public void setTrackDirectCallerUid(boolean enabled) {
+ synchronized (mLock) {
+ if (enabled != mTrackDirectCallingUid) {
+ mTrackDirectCallingUid = enabled;
+ reset();
+ }
+ }
+ }
+
public void setAddDebugEntries(boolean addDebugEntries) {
mAddDebugEntries = addDebugEntries;
}
diff --git a/core/java/com/android/internal/os/ChildZygoteInit.java b/core/java/com/android/internal/os/ChildZygoteInit.java
index cc74863..1f816c1 100644
--- a/core/java/com/android/internal/os/ChildZygoteInit.java
+++ b/core/java/com/android/internal/os/ChildZygoteInit.java
@@ -102,7 +102,7 @@
// are just isolated UIDs in the range, because for the webview zygote, there is no
// single range that captures all possible isolated UIDs.
// TODO(b/123615476) narrow this down
- if (uidGidMin < Process.FIRST_ISOLATED_UID) {
+ if (uidGidMin < Process.FIRST_APP_ZYGOTE_ISOLATED_UID) {
throw new RuntimeException("Passed in UID range does not map to isolated processes.");
}
diff --git a/core/java/com/android/internal/os/KernelCpuThreadReader.java b/core/java/com/android/internal/os/KernelCpuThreadReader.java
index b1328e8..6bbfc2b 100644
--- a/core/java/com/android/internal/os/KernelCpuThreadReader.java
+++ b/core/java/com/android/internal/os/KernelCpuThreadReader.java
@@ -109,6 +109,12 @@
private Predicate<Integer> mUidPredicate;
/**
+ * If a thread has strictly less than {@code minimumTotalCpuUsageMillis} total CPU usage, it
+ * will not be reported
+ */
+ private int mMinimumTotalCpuUsageMillis;
+
+ /**
* Where the proc filesystem is mounted
*/
private final Path mProcPath;
@@ -142,10 +148,12 @@
public KernelCpuThreadReader(
int numBuckets,
Predicate<Integer> uidPredicate,
+ int minimumTotalCpuUsageMillis,
Path procPath,
Path initialTimeInStatePath,
Injector injector) throws IOException {
mUidPredicate = uidPredicate;
+ mMinimumTotalCpuUsageMillis = minimumTotalCpuUsageMillis;
mProcPath = procPath;
mProcTimeInStateReader = new ProcTimeInStateReader(initialTimeInStatePath);
mInjector = injector;
@@ -158,11 +166,13 @@
* @return the reader, null if an exception was thrown during creation
*/
@Nullable
- public static KernelCpuThreadReader create(int numBuckets, Predicate<Integer> uidPredicate) {
+ public static KernelCpuThreadReader create(
+ int numBuckets, Predicate<Integer> uidPredicate, int minimumTotalCpuUsageMillis) {
try {
return new KernelCpuThreadReader(
numBuckets,
uidPredicate,
+ minimumTotalCpuUsageMillis,
DEFAULT_PROC_PATH,
DEFAULT_INITIAL_TIME_IN_STATE_PATH,
new Injector());
@@ -308,6 +318,18 @@
}
/**
+ * If a thread has strictly less than {@code minimumTotalCpuUsageMillis} total CPU usage, it
+ * will not be reported
+ */
+ void setMinimumTotalCpuUsageMillis(int minimumTotalCpuUsageMillis) {
+ if (minimumTotalCpuUsageMillis < 0) {
+ Slog.w(TAG, "Negative minimumTotalCpuUsageMillis: " + minimumTotalCpuUsageMillis);
+ return;
+ }
+ mMinimumTotalCpuUsageMillis = minimumTotalCpuUsageMillis;
+ }
+
+ /**
* Get the CPU frequencies that correspond to the times reported in
* {@link ThreadCpuUsage#usageTimesMillis}
*/
@@ -346,6 +368,15 @@
}
int[] cpuUsages = mFrequencyBucketCreator.getBucketedValues(cpuUsagesLong);
+ // Check if the total CPU usage below the threshold
+ int totalCpuUsage = 0;
+ for (int i = 0; i < cpuUsages.length; i++) {
+ totalCpuUsage += cpuUsages[i];
+ }
+ if (totalCpuUsage < mMinimumTotalCpuUsageMillis) {
+ return null;
+ }
+
return new ThreadCpuUsage(threadId, threadName, cpuUsages);
}
diff --git a/core/java/com/android/internal/os/KernelCpuThreadReaderSettingsObserver.java b/core/java/com/android/internal/os/KernelCpuThreadReaderSettingsObserver.java
index 77f6a17..718bcb4 100644
--- a/core/java/com/android/internal/os/KernelCpuThreadReaderSettingsObserver.java
+++ b/core/java/com/android/internal/os/KernelCpuThreadReaderSettingsObserver.java
@@ -59,6 +59,13 @@
private static final String COLLECTED_UIDS_SETTINGS_KEY = "collected_uids";
private static final String COLLECTED_UIDS_DEFAULT = "1000-1000";
+ /**
+ * Minimum total CPU usage to report
+ */
+ private static final String MINIMUM_TOTAL_CPU_USAGE_MILLIS_SETTINGS_KEY =
+ "minimum_total_cpu_usage_millis";
+ private static final int MINIMUM_TOTAL_CPU_USAGE_MILLIS_DEFAULT = 0;
+
private final Context mContext;
@Nullable
@@ -87,7 +94,8 @@
mContext = context;
mKernelCpuThreadReader = KernelCpuThreadReader.create(
NUM_BUCKETS_DEFAULT,
- UidPredicate.fromString(COLLECTED_UIDS_DEFAULT));
+ UidPredicate.fromString(COLLECTED_UIDS_DEFAULT),
+ MINIMUM_TOTAL_CPU_USAGE_MILLIS_DEFAULT);
}
@Override
@@ -124,6 +132,9 @@
mKernelCpuThreadReader.setNumBuckets(
parser.getInt(NUM_BUCKETS_SETTINGS_KEY, NUM_BUCKETS_DEFAULT));
mKernelCpuThreadReader.setUidPredicate(uidPredicate);
+ mKernelCpuThreadReader.setMinimumTotalCpuUsageMillis(parser.getInt(
+ MINIMUM_TOTAL_CPU_USAGE_MILLIS_SETTINGS_KEY,
+ MINIMUM_TOTAL_CPU_USAGE_MILLIS_DEFAULT));
}
/**
diff --git a/core/java/com/android/internal/os/LooperStats.java b/core/java/com/android/internal/os/LooperStats.java
index b3d9ca7..c059721 100644
--- a/core/java/com/android/internal/os/LooperStats.java
+++ b/core/java/com/android/internal/os/LooperStats.java
@@ -39,6 +39,7 @@
public class LooperStats implements Looper.Observer {
public static final String DEBUG_ENTRY_PREFIX = "__DEBUG_";
private static final int SESSION_POOL_SIZE = 50;
+ private static final boolean DISABLED_SCREEN_STATE_TRACKING_VALUE = false;
@GuardedBy("mLock")
private final SparseArray<Entry> mEntries = new SparseArray<>(512);
@@ -54,6 +55,7 @@
private long mStartCurrentTime = System.currentTimeMillis();
private long mStartElapsedTime = SystemClock.elapsedRealtime();
private boolean mAddDebugEntries = false;
+ private boolean mTrackScreenInteractive = false;
public LooperStats(int samplingInterval, int entriesSizeCap) {
this.mSamplingInterval = samplingInterval;
@@ -218,9 +220,15 @@
mSamplingInterval = samplingInterval;
}
+ public void setTrackScreenInteractive(boolean enabled) {
+ mTrackScreenInteractive = enabled;
+ }
+
@Nullable
private Entry findEntry(Message msg, boolean allowCreateNew) {
- final boolean isInteractive = mDeviceState.isScreenInteractive();
+ final boolean isInteractive = mTrackScreenInteractive
+ ? mDeviceState.isScreenInteractive()
+ : DISABLED_SCREEN_STATE_TRACKING_VALUE;
final int id = Entry.idFor(msg, isInteractive);
Entry entry;
synchronized (mLock) {
diff --git a/core/java/com/android/internal/util/ImageUtils.java b/core/java/com/android/internal/util/ImageUtils.java
index 195ae52..274a513 100644
--- a/core/java/com/android/internal/util/ImageUtils.java
+++ b/core/java/com/android/internal/util/ImageUtils.java
@@ -16,20 +16,25 @@
package com.android.internal.util;
+import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
-import android.graphics.BitmapFactory;
import android.graphics.Canvas;
+import android.graphics.ImageDecoder;
+import android.graphics.ImageDecoder.ImageInfo;
+import android.graphics.ImageDecoder.Source;
import android.graphics.Matrix;
import android.graphics.Paint;
+import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
+import android.os.Bundle;
+import android.util.Size;
import java.io.IOException;
-import java.io.InputStream;
/**
* Utility class for image analysis and processing.
@@ -166,21 +171,18 @@
/**
* @see https://developer.android.com/topic/performance/graphics/load-bitmap
*/
- public static int calculateInSampleSize(BitmapFactory.Options options,
- int reqWidth, int reqHeight) {
- // Raw height and width of image
- final int height = options.outHeight;
- final int width = options.outWidth;
+ public static int calculateSampleSize(Size currentSize, Size requestedSize) {
int inSampleSize = 1;
- if (height > reqHeight || width > reqWidth) {
- final int halfHeight = height / 2;
- final int halfWidth = width / 2;
+ if (currentSize.getHeight() > requestedSize.getHeight()
+ || currentSize.getWidth() > requestedSize.getWidth()) {
+ final int halfHeight = currentSize.getHeight() / 2;
+ final int halfWidth = currentSize.getWidth() / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
- while ((halfHeight / inSampleSize) >= reqHeight
- && (halfWidth / inSampleSize) >= reqWidth) {
+ while ((halfHeight / inSampleSize) >= requestedSize.getHeight()
+ && (halfWidth / inSampleSize) >= requestedSize.getWidth()) {
inSampleSize *= 2;
}
}
@@ -190,27 +192,27 @@
/**
* Load a bitmap, and attempt to downscale to the required size, to save
- * on memory.
+ * on memory. Updated to use newer and more compatible ImageDecoder.
*
* @see https://developer.android.com/topic/performance/graphics/load-bitmap
*/
- public static Bitmap decodeSampledBitmapFromStream(ContentResolver resolver,
- Uri uri, int reqWidth, int reqHeight) throws IOException {
+ public static Bitmap loadThumbnail(ContentResolver resolver, Uri uri, Size size)
+ throws IOException {
- final BitmapFactory.Options options = new BitmapFactory.Options();
- try (InputStream is = resolver.openInputStream(uri)) {
- // First decode with inJustDecodeBounds=true to check dimensions
- options.inJustDecodeBounds = true;
- BitmapFactory.decodeStream(is, null, options);
+ try (ContentProviderClient client = resolver.acquireContentProviderClient(uri)) {
+ final Bundle opts = new Bundle();
+ opts.putParcelable(ContentResolver.EXTRA_SIZE, Point.convert(size));
- options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
- }
+ return ImageDecoder.decodeBitmap(ImageDecoder.createSource(() -> {
+ return client.openTypedAssetFile(uri, "image/*", opts, null);
+ }), (ImageDecoder decoder, ImageInfo info, Source source) -> {
+ decoder.setAllocator(ImageDecoder.ALLOCATOR_SOFTWARE);
- // need to do this twice as the InputStream is consumed in the first call,
- // and not all InputStreams support marks
- try (InputStream is = resolver.openInputStream(uri)) {
- options.inJustDecodeBounds = false;
- return BitmapFactory.decodeStream(is, null, options);
+ final int sample = calculateSampleSize(info.getSize(), size);
+ if (sample > 1) {
+ decoder.setTargetSampleSize(sample);
+ }
+ });
}
}
}
diff --git a/core/jni/Android.bp b/core/jni/Android.bp
index 345058b..af0b7c3 100644
--- a/core/jni/Android.bp
+++ b/core/jni/Android.bp
@@ -287,8 +287,8 @@
"libsoundtrigger",
"libminikin",
"libprocessgroup",
- "libnativebridge",
- "libnativeloader",
+ "libnativebridge_lazy",
+ "libnativeloader_lazy",
"libmemunreachable",
"libhidlbase",
"libhidltransport",
diff --git a/core/jni/android_opengl_EGL14.cpp b/core/jni/android_opengl_EGL14.cpp
index a9d75fd..15d1944 100644
--- a/core/jni/android_opengl_EGL14.cpp
+++ b/core/jni/android_opengl_EGL14.cpp
@@ -107,6 +107,7 @@
if (obj == NULL){
jniThrowException(_env, "java/lang/IllegalArgumentException",
"Object is set to null.");
+ return nullptr;
}
jlong handle = _env->CallLongMethod(obj, mid);
@@ -238,6 +239,7 @@
}
if (_exception) {
jniThrowException(_env, _exceptionType, _exceptionMessage);
+ return false;
}
return (jboolean)_returnValue;
}
@@ -335,6 +337,7 @@
}
if (_exception) {
jniThrowException(_env, _exceptionType, _exceptionMessage);
+ return false;
}
return (jboolean)_returnValue;
}
@@ -454,6 +457,7 @@
}
if (_exception) {
jniThrowException(_env, _exceptionType, _exceptionMessage);
+ return false;
}
return (jboolean)_returnValue;
}
@@ -509,6 +513,7 @@
}
if (_exception) {
jniThrowException(_env, _exceptionType, _exceptionMessage);
+ return false;
}
return (jboolean)_returnValue;
}
@@ -582,6 +587,7 @@
}
if (_exception) {
jniThrowException(_env, _exceptionType, _exceptionMessage);
+ return nullptr;
}
return toEGLHandle(_env, eglsurfaceClass, eglsurfaceConstructor, _returnValue);
}
@@ -664,6 +670,7 @@
}
if (_exception) {
jniThrowException(_env, _exceptionType, _exceptionMessage);
+ return nullptr;
}
return toEGLHandle(_env, eglsurfaceClass, eglsurfaceConstructor, _returnValue);
}
@@ -721,6 +728,7 @@
}
if (_exception) {
jniThrowException(_env, _exceptionType, _exceptionMessage);
+ return nullptr;
}
return toEGLHandle(_env, eglsurfaceClass, eglsurfaceConstructor, _returnValue);
}
@@ -731,7 +739,7 @@
(JNIEnv *_env, jobject _this, jobject dpy, jobject config, jint pixmap, jintArray attrib_list_ref, jint offset) {
jniThrowException(_env, "java/lang/UnsupportedOperationException",
"eglCreatePixmapSurface");
- return toEGLHandle(_env, eglsurfaceClass, eglsurfaceConstructor, (EGLSurface) 0);
+ return nullptr;
}
/* EGLBoolean eglDestroySurface ( EGLDisplay dpy, EGLSurface surface ) */
@@ -800,6 +808,7 @@
}
if (_exception) {
jniThrowException(_env, _exceptionType, _exceptionMessage);
+ return false;
}
return (jboolean)_returnValue;
}
@@ -898,6 +907,7 @@
}
if (_exception) {
jniThrowException(_env, _exceptionType, _exceptionMessage);
+ return nullptr;
}
return toEGLHandle(_env, eglsurfaceClass, eglsurfaceConstructor, _returnValue);
}
@@ -1034,6 +1044,7 @@
}
if (_exception) {
jniThrowException(_env, _exceptionType, _exceptionMessage);
+ return nullptr;
}
return toEGLHandle(_env, eglcontextClass, eglcontextConstructor, _returnValue);
}
@@ -1152,6 +1163,7 @@
}
if (_exception) {
jniThrowException(_env, _exceptionType, _exceptionMessage);
+ return false;
}
return (jboolean)_returnValue;
}
diff --git a/core/jni/android_os_GraphicsEnvironment.cpp b/core/jni/android_os_GraphicsEnvironment.cpp
index e2e66ce..95f99b7 100644
--- a/core/jni/android_os_GraphicsEnvironment.cpp
+++ b/core/jni/android_os_GraphicsEnvironment.cpp
@@ -55,6 +55,11 @@
devOptInChars.c_str(), rulesFd_native, rulesOffset, rulesLength);
}
+bool shouldUseAngle_native(JNIEnv* env, jobject clazz, jstring appName) {
+ ScopedUtfChars appNameChars(env, appName);
+ return android::GraphicsEnv::getInstance().shouldUseAngle(appNameChars.c_str());
+}
+
void setLayerPaths_native(JNIEnv* env, jobject clazz, jobject classLoader, jstring layerPaths) {
android::NativeLoaderNamespace* appNamespace = android::FindNativeLoaderNamespaceByClassLoader(
env, classLoader);
@@ -81,6 +86,7 @@
{ "setDriverPath", "(Ljava/lang/String;)V", reinterpret_cast<void*>(setDriverPath) },
{ "setGpuStats", "(Ljava/lang/String;Ljava/lang/String;JLjava/lang/String;)V", reinterpret_cast<void*>(setGpuStats_native) },
{ "setAngleInfo", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/io/FileDescriptor;JJ)V", reinterpret_cast<void*>(setAngleInfo_native) },
+ { "getShouldUseAngle", "(Ljava/lang/String;)Z", reinterpret_cast<void*>(shouldUseAngle_native) },
{ "setLayerPaths", "(Ljava/lang/ClassLoader;Ljava/lang/String;)V", reinterpret_cast<void*>(setLayerPaths_native) },
{ "setDebugLayers", "(Ljava/lang/String;)V", reinterpret_cast<void*>(setDebugLayers_native) },
{ "setDebugLayersGLES", "(Ljava/lang/String;)V", reinterpret_cast<void*>(setDebugLayersGLES_native) },
diff --git a/core/jni/com_android_internal_os_Zygote.cpp b/core/jni/com_android_internal_os_Zygote.cpp
index d04db92..5cecf66a 100644
--- a/core/jni/com_android_internal_os_Zygote.cpp
+++ b/core/jni/com_android_internal_os_Zygote.cpp
@@ -742,7 +742,7 @@
return;
}
- if (GetBoolProperty(kIsolatedStorageSnapshot, GetBoolProperty(kIsolatedStorage, false))) {
+ if (GetBoolProperty(kIsolatedStorageSnapshot, GetBoolProperty(kIsolatedStorage, true))) {
if (mount_mode == MOUNT_EXTERNAL_FULL || mount_mode == MOUNT_EXTERNAL_LEGACY) {
storageSource = (mount_mode == MOUNT_EXTERNAL_FULL)
? "/mnt/runtime/full" : "/mnt/runtime/write";
diff --git a/core/jni/runtime_native_boot-flags-test.sh b/core/jni/runtime_native_boot-flags-test.sh
new file mode 100755
index 0000000..66e18bb
--- /dev/null
+++ b/core/jni/runtime_native_boot-flags-test.sh
@@ -0,0 +1,244 @@
+#!/bin/bash
+
+# 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.
+#
+
+# Test Android Runtime (Boot) device configuration flags (living in namespace
+# `runtime_native_boot`).
+
+me=$(basename $0)
+
+# Namespace containing the tested flag.
+namespace=runtime_native_boot
+# Default set of checked zygote processes.
+zygotes=
+
+# Status of whole test script.
+exit_status=0
+
+function say {
+ echo "$me: $*"
+}
+
+function banner {
+ local separator=$(echo "$@" | sed s/./=/g )
+ say "$separator"
+ say "$@"
+ say "$separator"
+}
+
+function fail {
+ say "FAILED: $@"
+ exit_status=1
+}
+
+function reboot_and_wait_for_device {
+ say "Rebooting device..."
+ adb reboot
+ adb wait-for-device >/dev/null
+ # Wait until the device has finished booting. Give the device 60 iterations
+ # (~60 seconds) to try and finish booting before declaring defeat.
+ local niters=60
+ for i in $(seq $niters); do
+ [[ $(adb shell getprop sys.boot_completed) -eq 1 ]] && return 0
+ sleep 1
+ done
+ fail "Device did not finish booting before timeout (~$niters seconds)"
+}
+
+# check_device_config_flag CONTEXT FLAG VALUE
+# -------------------------------------------
+# Check that the device configuration flag FLAG is set to VALUE. Use CONTEXT in
+# logging.
+function check_device_config_flag {
+ local context=$1
+ local flag=$2
+ local value=$3
+
+ say "[$context] Check that the device configuration flag is set..."
+ local flag_value=$(adb shell device_config get "$namespace" "$flag")
+ [[ "$flag_value" = "$value" ]] \
+ || fail "Device configuration flag \`$flag\` set to \`$flag_value\` (expected \`$value\`)"
+}
+
+# check_no_device_config_flag CONTEXT FLAG
+# ----------------------------------------
+# Check that the device configuration flag FLAG is not set. Use CONTEXT in
+# logging.
+function check_no_device_config_flag {
+ local context=$1
+ local flag=$2
+
+ say "[$context] Check that the device configuration flag is not set..."
+ local flag_value=$(adb shell device_config get "$namespace" "$flag")
+ [[ "$flag_value" = null ]] \
+ || fail "Device configuration flag \`$flag\` set to \`$flag_value\` (expected `null`)"
+}
+
+# get_system_property PROP
+# ------------------------
+# Get system property PROP associated with a device configuration flag.
+function get_system_property {
+ local prop=$1
+
+ # Note that we need to be root to read that system property.
+ adb root >/dev/null
+ local prop_value=$(adb shell getprop "$prop")
+ adb unroot >/dev/null
+ echo "$prop_value"
+}
+
+# check_system_property CONTEXT PROP VALUE
+# ----------------------------------------
+# Check that the system property PROP associated with a device configuration
+# flag is set to VALUE. Use CONTEXT in logging.
+function check_system_property {
+ local context=$1
+ local prop=$2
+ local value=$3
+
+ say "[$context] Check that the persistent system property is set..."
+ local prop_value=$(get_system_property "$prop")
+ [[ "$prop_value" = "$value" ]] \
+ || fail "System property \`$prop\` set to \`$prop_value\` (expected \`$value\`)"
+}
+
+# check_no_system_property CONTEXT PROP
+# -------------------------------------
+# Check that the system property PROP associated with a device configuration
+# flag is not set. Use CONTEXT in logging.
+function check_no_system_property {
+ local context=$1
+ local prop=$2
+
+ say "[$context] Check that the persistent system property is not set..."
+ local prop_value=$(get_system_property "$prop")
+ [[ -z "$prop_value" ]] \
+ || fail "System property \`$prop\` set to \`$prop_value\` (expected unset property)"
+}
+
+# find_zygote_runtime_option ZYGOTE RUNTIME_OPTION
+# ------------------------------------------------
+# Return whether ZYGOTE is passed RUNTIME_OPTION.
+function find_zygote_runtime_option {
+ local zygote=$1
+ local runtime_option=$2
+
+ adb logcat -d -s "$zygote" | grep -q -e "option\[[0-9]\+\]=$runtime_option"
+}
+
+# check_zygote_gc_runtime_option CONTEXT VALUE
+# --------------------------------------------
+# Check that all zygote processes are passed device configuration flag VALUE as
+# GC runtime option. Use CONTEXT in logging.
+function check_zygote_gc_runtime_option {
+ local context=$1
+ local value=$2
+
+ say \
+ "[$context] Check that all zygote processes are passed the flag value as a GC runtime option..."
+ local runtime_option="-Xgc:$value"
+ for zygote in $zygotes; do
+ find_zygote_runtime_option "$zygote" "$runtime_option"\
+ || fail "Found no \`$runtime_option\` among runtime options passed to \`$zygote\`"
+ done
+}
+
+# check_no_zygote_gc_runtime_option CONTEXT VALUE
+# -----------------------------------------------
+# Check that no zygote process is passed device configuration flag VALUE as GC
+# runtime option. Use CONTEXT in logging.
+function check_no_zygote_gc_runtime_option {
+ local context=$1
+ local value=$2
+
+ say "[$context] Check no zygote process is passed the flag value as a GC runtime option..."
+ local runtime_option="-Xgc:$value"
+ for zygote in $zygotes; do
+ find_zygote_runtime_option "$zygote" "$runtime_option"\
+ && fail "Found \`$runtime_option\` among runtime options passed to \`$zygote\`"
+ done
+}
+
+# test_android_runtime_flag FLAG VALUE
+# ------------------------------------
+# Test device configuration FLAG with VALUE.
+function test_android_runtime_flag {
+ local flag=$1
+ local value=$2
+
+ # Persistent system property (set after a reboot) associated with the device
+ # configuration flag.
+ local prop="persist.device_config.$namespace.$flag"
+
+ banner "Testing \`$flag\` value \`$value\`."
+
+ say "Setting device configuration flag..."
+ adb shell device_config put "$namespace" "$flag" "$value"
+ # Give some time to the device to digest this change before rebooting.
+ sleep 3
+
+ # Check that both the device configuration flag and the associated system
+ # property are set, but that the zygote hasn't had the flag passed to it as a
+ # GC runtime option (as we haven't rebooted yet).
+ local context="Flag set, before reboot"
+ check_device_config_flag "$context" "$flag" "$value"
+ check_system_property "$context" "$prop" "$value"
+ check_no_zygote_gc_runtime_option "$context" "$value"
+
+ # Reboot device for the flag value to take effect.
+ reboot_and_wait_for_device
+ context="Flag set, after 1st reboot"
+ check_device_config_flag "$context" "$flag" "$value"
+ check_system_property "$context" "$prop" "$value"
+ check_zygote_gc_runtime_option "$context" "$value"
+
+ # Reboot device a second time and check that the state has persisted.
+ reboot_and_wait_for_device
+ context="Flag set, after 2nd reboot"
+ check_device_config_flag "$context" "$flag" "$value"
+ check_system_property "$context" "$prop" "$value"
+ check_zygote_gc_runtime_option "$context" "$value"
+
+ say "Unsetting device configuration flag..."
+ adb shell device_config delete "$namespace" "$flag" >/dev/null
+ # Give some time to the device to digest this change before rebooting.
+ sleep 3
+
+ # Reboot and check that the device is back to its default state.
+ reboot_and_wait_for_device
+ context="Flag unset, after 3rd reboot"
+ check_no_device_config_flag "$context" "$flag"
+ check_no_system_property "$context" "$prop"
+ check_no_zygote_gc_runtime_option "$context" "$value"
+}
+
+# Enumerate Zygote processes.
+case $(adb shell getprop ro.zygote) in
+ (zygote32) zygotes="zygote";;
+ (zygote64) zygotes="zygote64";;
+ (zygote32_64|zygote64_32) zygotes="zygote zygote64";;
+esac
+
+# Test "gctype" flag values.
+test_android_runtime_flag gctype nogenerational_cc
+test_android_runtime_flag gctype generational_cc
+
+if [[ "$exit_status" -eq 0 ]]; then
+ banner "All tests passed."
+else
+ banner "Test(s) failed."
+fi
+exit $exit_status
diff --git a/core/proto/android/app/settings_enums.proto b/core/proto/android/app/settings_enums.proto
index 30b9b78..5497b86 100644
--- a/core/proto/android/app/settings_enums.proto
+++ b/core/proto/android/app/settings_enums.proto
@@ -610,6 +610,11 @@
// CATEGORY: SETTINGS
// OS: Q
ACTION_SET_NEW_PARENT_PROFILE_PASSWORD = 1646;
+
+ // ACTION: An interaction with a Slice or other component in the Panel.
+ // CATEGORY: SETTINGS
+ // OS: Q
+ ACTION_PANEL_INTERACTION = 1658;
}
/**
@@ -2214,4 +2219,16 @@
// CATEGORY: SETTINGS
// OS: Q
SET_NEW_PASSWORD_ACTIVITY = 1644;
+
+ // Panel for Internet Connectivity
+ PANEL_INTERNET_CONNECTIVITY = 1654;
+
+ // Panel for Volume
+ PANEL_VOLUME = 1655;
+
+ // Panel for NFC
+ PANEL_NFC = 1656;
+
+ // Panel for Media Output
+ PANEL_MEDIA_OUTPUT = 1657;
}
diff --git a/core/proto/android/hardware/sensor/assist/enums.proto b/core/proto/android/hardware/sensor/assist/enums.proto
new file mode 100644
index 0000000..8c5841a
--- /dev/null
+++ b/core/proto/android/hardware/sensor/assist/enums.proto
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+syntax = "proto2";
+package android.hardware.sensor.assist;
+
+option java_outer_classname = "AssistGestureProtoEnums";
+option java_multiple_files = true;
+
+enum AssistGestureStageEnum {
+ ASSIST_GESTURE_STAGE_UNKNOWN = 0;
+ ASSIST_GESTURE_STAGE_PROGRESS = 1;
+ ASSIST_GESTURE_STAGE_PRIMED = 2;
+ ASSIST_GESTURE_STAGE_DETECTED = 3;
+}
+
+enum AssistGestureFeedbackEnum {
+ ASSIST_GESTURE_FEEDBACK_UNKNOWN = 0;
+ ASSIST_GESTURE_FEEDBACK_NOT_USED = 1;
+ ASSIST_GESTURE_FEEDBACK_USED = 2;
+}
\ No newline at end of file
diff --git a/core/proto/android/providers/settings/global.proto b/core/proto/android/providers/settings/global.proto
index d577653..c9957f3 100644
--- a/core/proto/android/providers/settings/global.proto
+++ b/core/proto/android/providers/settings/global.proto
@@ -448,6 +448,11 @@
optional SettingProto game_driver_whitelist = 12;
// ANGLE - List of Apps that can check ANGLE rules
optional SettingProto angle_whitelist = 13;
+ // Game Driver - List of blacklists, each blacklist is a blacklist for
+ // a specific Game Driver version
+ optional SettingProto game_driver_blacklists = 14;
+ // ANGLE - Show a dialog box when ANGLE is selected for the currently running PKG
+ optional SettingProto show_angle_in_use_dialog = 15;
}
optional Gpu gpu = 59;
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 34ec92e..5b74d90 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -2151,13 +2151,13 @@
android:label="@string/permlab_disableKeyguard"
android:protectionLevel="normal" />
- <!-- Allows an application to get the screen lock complexity and prompt users to update the
+ <!-- Allows an application to request the screen lock complexity and prompt users to update the
screen lock to a certain complexity level.
<p>Protection level: normal
-->
- <permission android:name="android.permission.GET_AND_REQUEST_SCREEN_LOCK_COMPLEXITY"
- android:label="@string/permlab_getAndRequestScreenLockComplexity"
- android:description="@string/permdesc_getAndRequestScreenLockComplexity"
+ <permission android:name="android.permission.REQUEST_SCREEN_LOCK_COMPLEXITY"
+ android:label="@string/permlab_requestScreenLockComplexity"
+ android:description="@string/permdesc_requestScreenLockComplexity"
android:protectionLevel="normal" />
<!-- ================================== -->
diff --git a/core/res/res/drawable/bottomsheet_background.xml b/core/res/res/drawable/bottomsheet_background.xml
index bc32ba6..3a8ad71 100644
--- a/core/res/res/drawable/bottomsheet_background.xml
+++ b/core/res/res/drawable/bottomsheet_background.xml
@@ -16,7 +16,7 @@
<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">
<corners
- android:topLeftRadius="?attr/dialogCornerRadius"
- android:topRightRadius="?attr/dialogCornerRadius" />
+ android:topLeftRadius="@dimen/config_bottomDialogCornerRadius"
+ android:topRightRadius="@dimen/config_bottomDialogCornerRadius"/>
<solid android:color="?attr/colorBackgroundFloating" />
</shape>
diff --git a/core/res/res/drawable/ic_action_open.xml b/core/res/res/drawable/ic_action_open.xml
new file mode 100644
index 0000000..3d3d36e
--- /dev/null
+++ b/core/res/res/drawable/ic_action_open.xml
@@ -0,0 +1,24 @@
+<!--
+Copyright (C) 2019 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24.0"
+ android:viewportHeight="24.0">
+ <path
+ android:fillColor="#FF737373"
+ android:pathData="M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z"/>
+</vector>
\ No newline at end of file
diff --git a/core/res/res/drawable/ic_file_copy.xml b/core/res/res/drawable/ic_file_copy.xml
new file mode 100644
index 0000000..b6d5e73
--- /dev/null
+++ b/core/res/res/drawable/ic_file_copy.xml
@@ -0,0 +1,24 @@
+<!--
+ Copyright (C) 2019 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<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="M16,1L4,1c-1.1,0 -2,0.9 -2,2v14h2L4,3h12L16,1zM15,5l6,6v10c0,1.1 -0.9,2 -2,2L7.99,23C6.89,23 6,22.1 6,21l0.01,-14c0,-1.1 0.89,-2 1.99,-2h7zM14,12h5.5L14,6.5L14,12z"
+ android:fillColor="#FF737373"/>
+</vector>
diff --git a/core/res/res/layout/chooser_grid.xml b/core/res/res/layout/chooser_grid.xml
index 14a5310..3683bfd 100644
--- a/core/res/res/layout/chooser_grid.xml
+++ b/core/res/res/layout/chooser_grid.xml
@@ -213,6 +213,65 @@
</LinearLayout>
</LinearLayout>
+ <!-- Layout Option 3: File preview, icon, filename, copy-->
+ <LinearLayout
+ android:id="@+id/content_preview_file_area"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical"
+ android:paddingBottom="@dimen/chooser_view_spacing"
+ android:visibility="gone"
+ android:background="?attr/colorBackgroundFloating">
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal"
+ android:paddingLeft="@dimen/chooser_edge_margin_normal"
+ android:paddingRight="@dimen/chooser_edge_margin_normal"
+ android:layout_marginBottom="@dimen/chooser_view_spacing"
+ android:id="@+id/content_preview_file_layout">
+
+ <view class="com.android.internal.app.ChooserActivity$RoundedRectImageView"
+ android:id="@+id/content_preview_file_thumbnail"
+ android:layout_width="75dp"
+ android:layout_height="75dp"
+ android:layout_marginRight="16dp"
+ android:adjustViewBounds="true"
+ android:layout_gravity="center_vertical"
+ android:gravity="center"
+ android:scaleType="centerCrop"
+ android:visibility="gone"/>
+ <ImageView
+ android:id="@+id/content_preview_file_icon"
+ android:layout_width="36dp"
+ android:layout_height="36dp"
+ android:layout_marginRight="16dp"
+ android:adjustViewBounds="true"
+ android:layout_gravity="center_vertical"
+ android:gravity="center"
+ android:scaleType="fitCenter"
+ android:visibility="gone"/>
+ <TextView
+ android:id="@+id/content_preview_filename"
+ android:layout_width="0dp"
+ android:layout_weight="1"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_vertical"
+ android:ellipsize="middle"
+ android:gravity="start|top"
+ android:paddingRight="24dp"
+ android:singleLine="true"/>
+ <Button
+ android:id="@+id/file_copy_button"
+ android:layout_width="24dp"
+ android:layout_height="24dp"
+ android:gravity="center"
+ android:layout_gravity="center_vertical"
+ android:background="@drawable/ic_content_copy_gm2"/>
+ </LinearLayout>
+ </LinearLayout>
+
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
diff --git a/core/res/res/layout/notification_template_material_media.xml b/core/res/res/layout/notification_template_material_media.xml
index 64d91ad..13fef67 100644
--- a/core/res/res/layout/notification_template_material_media.xml
+++ b/core/res/res/layout/notification_template_material_media.xml
@@ -66,7 +66,7 @@
android:id="@+id/media_actions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:layout_gravity="bottom|end"
+ android:layout_gravity="top|end"
android:layout_marginStart="10dp"
android:layoutDirection="ltr"
android:orientation="horizontal"
diff --git a/core/res/res/values/attrs_manifest.xml b/core/res/res/values/attrs_manifest.xml
index 53cae63..1053184 100644
--- a/core/res/res/values/attrs_manifest.xml
+++ b/core/res/res/values/attrs_manifest.xml
@@ -118,7 +118,7 @@
<attr name="manageSpaceActivity" format="string" />
<!-- Option to let applications specify that user data can/cannot be
- cleared. This flag is turned on by default.
+ cleared by the user in Settings. This flag is turned on by default.
<em>This attribute is usable only by applications
included in the system image. Third-party apps cannot use it.</em> -->
<attr name="allowClearUserData" format="boolean" />
@@ -1661,7 +1661,12 @@
<!-- If {@code true} the user is prompted to keep the app's data on uninstall -->
<attr name="hasFragileUserData" />
- <attr name="zygotePreloadName" />
+ <attr name="zygotePreloadName" />
+
+ <!-- If {@code true} the system will clear app's data if a restore operation fails.
+ This flag is turned on by default. <em>This attribute is usable only by system apps.
+ </em> -->
+ <attr name="allowClearUserDataOnFailedRestore"/>
</declare-styleable>
<!-- The <code>permission</code> tag declares a security permission that can be
used to control access from other packages to specific components or
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index a501ae2..d14164f 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -1951,6 +1951,10 @@
<string name="config_defaultDialer" translatable="false">com.android.phone</string>
<!-- The name of the package that will hold the SMS role by default. -->
<string name="config_defaultSms" translatable="false">@string/default_sms_application</string>
+ <!-- The name of the package that will hold the music role by default. -->
+ <string name="config_defaultMusic" translatable="false">com.android.music</string>
+ <!-- The name of the package that will hold the gallery role by default. -->
+ <string name="config_defaultGallery" translatable="false">com.android.gallery3d</string>
<!-- Enable/disable default bluetooth profiles:
HSP_AG, ObexObjectPush, Audio, NAP -->
@@ -3421,8 +3425,14 @@
-->
<string-array translatable="false" name="config_convert_to_emergency_number_map" />
- <!-- An array of packages for which notifications cannot be blocked. -->
- <string-array translatable="false" name="config_nonBlockableNotificationPackages" />
+ <!-- An array of packages for which notifications cannot be blocked.
+ Should only be used for core device functionality that must not be
+ rendered inoperative for safety reasons, like the phone dialer and
+ SMS handler. -->
+ <string-array translatable="false" name="config_nonBlockableNotificationPackages">
+ <item>com.android.dialer</item>
+ <item>com.android.messaging</item>
+ </string-array>
<!-- An array of packages which can listen for notifications on low ram devices. -->
<string-array translatable="false" name="config_allowedManagedServicesOnLowRamDevices" />
@@ -3893,4 +3903,22 @@
The ambient color temperature (in cct) to which we fall back when the ambient brightness
drops beneath a certain threshold. -->
<item name="config_displayWhiteBalanceLowLightAmbientColorTemperature" format="float" type="dimen">6500.0</item>
+
+ <!-- See DisplayWhiteBalanceController.
+ A float array containing a list of ambient color temperatures, in Kelvin. This array,
+ together with config_displayWhiteBalanceDisplayTemperatureValues, is used to generate a
+ lookup table used in DisplayWhiteBalanceController. This lookup table is used to map
+ ambient color temperature readings to a target color temperature for the display.
+ This table is optional. If used, this array must,
+ 1) Contain at least two entries
+ 2) Be the same length as config_displayWhiteBalanceDisplayTemperatureValues. -->
+ <array name="config_displayWhiteBalanceAmbientTemperatureValues">
+ </array>
+
+ <!-- See DisplayWhiteBalanceController.
+ An array containing a list of display color temperatures, in Kelvin. See
+ config_displayWhiteBalanceAmbientTemperatureValues for additional details.
+ The same restrictions apply to this array. -->
+ <array name="config_displayWhiteBalanceDisplayTemperatureValues">
+ </array>
</resources>
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index d5cefc4..5e65605 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -2939,6 +2939,8 @@
<public name="zygotePreloadName" />
<public name="useEmbeddedDex" />
<public name="forceUriPermissions" />
+ <!-- @hide @SystemApi -->
+ <public name="allowClearUserDataOnFailedRestore"/>
</public-group>
<public-group type="drawable" first-id="0x010800b4">
@@ -2979,6 +2981,10 @@
<public name="config_defaultDialer" />
<!-- @hide @SystemApi -->
<public name="config_defaultSms" />
+ <!-- @hide @SystemApi -->
+ <public name="config_defaultMusic" />
+ <!-- @hide @SystemApi -->
+ <public name="config_defaultGallery" />
</public-group>
<public-group type="bool" first-id="0x01110000">
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 6d5bd4b..0cdf388 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -1406,9 +1406,9 @@
re-enables the keylock when the call is finished.</string>
<!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. [CHAR_LIMIT=NONE] -->
- <string name="permlab_getAndRequestScreenLockComplexity">get and request screen lock complexity</string>
+ <string name="permlab_requestScreenLockComplexity">request screen lock complexity</string>
<!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. [CHAR_LIMIT=NONE] -->
- <string name="permdesc_getAndRequestScreenLockComplexity">Allows the app to learn the screen
+ <string name="permdesc_requestScreenLockComplexity">Allows the app to learn the screen
lock complexity level (high, medium, low or none), which indicates the possible range of
length and type of the screen lock. The app can also suggest to users that they update the
screen lock to a certain level but users can freely ignore and navigate away. Note that the
@@ -5284,4 +5284,9 @@
<!-- Strings for car -->
<!-- String displayed when loading a user in the car [CHAR LIMIT=30] -->
<string name="car_loading_profile">Loading</string>
+
+ <plurals name="file_count">
+ <item quantity="one"><xliff:g id="file_name">%s</xliff:g> + <xliff:g id="count">%d</xliff:g> file</item>
+ <item quantity="other"><xliff:g id="file_name">%s</xliff:g> + <xliff:g id="count">%d</xliff:g> files</item>
+ </plurals>
</resources>
diff --git a/core/res/res/values/styles_device_defaults.xml b/core/res/res/values/styles_device_defaults.xml
index 0dc54e0..93068ea9 100644
--- a/core/res/res/values/styles_device_defaults.xml
+++ b/core/res/res/values/styles_device_defaults.xml
@@ -41,9 +41,7 @@
<item name="textAppearance">?attr/textAppearanceButton</item>
<item name="textColor">@color/btn_colored_text_material</item>
</style>
- <style name="Widget.DeviceDefault.TextView" parent="Widget.Material.TextView">
- <item name="fontFamily">@string/config_bodyFontFamily</item>
- </style>
+ <style name="Widget.DeviceDefault.TextView" parent="Widget.Material.TextView" />
<style name="Widget.DeviceDefault.CheckedTextView" parent="Widget.Material.CheckedTextView"/>
<style name="Widget.DeviceDefault.AutoCompleteTextView" parent="Widget.Material.AutoCompleteTextView"/>
<style name="Widget.DeviceDefault.CompoundButton.CheckBox" parent="Widget.Material.CompoundButton.CheckBox"/>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 410a8c16..a1bafbf 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -50,6 +50,11 @@
<java-symbol type="id" name="characterPicker" />
<java-symbol type="id" name="clearDefaultHint" />
<java-symbol type="id" name="contentPanel" />
+ <java-symbol type="id" name="content_preview_file_area" />
+ <java-symbol type="id" name="content_preview_file_icon" />
+ <java-symbol type="id" name="content_preview_file_layout" />
+ <java-symbol type="id" name="content_preview_file_thumbnail" />
+ <java-symbol type="id" name="content_preview_filename" />
<java-symbol type="id" name="content_preview_image_area" />
<java-symbol type="id" name="content_preview_image_1_large" />
<java-symbol type="id" name="content_preview_image_2_large" />
@@ -62,6 +67,7 @@
<java-symbol type="id" name="content_preview_title" />
<java-symbol type="id" name="content_preview_title_layout" />
<java-symbol type="id" name="copy_button" />
+ <java-symbol type="id" name="file_copy_button" />
<java-symbol type="id" name="current_scene" />
<java-symbol type="id" name="scene_layoutid_cache" />
<java-symbol type="id" name="customPanel" />
@@ -1266,6 +1272,7 @@
<java-symbol type="string" name="tooltip_popup_title" />
<java-symbol type="plurals" name="bugreport_countdown" />
+ <java-symbol type="plurals" name="file_count" />
<java-symbol type="plurals" name="last_num_days" />
<java-symbol type="plurals" name="matches_found" />
<java-symbol type="plurals" name="restr_pin_countdown" />
@@ -1307,6 +1314,7 @@
<java-symbol type="drawable" name="default_wallpaper" />
<java-symbol type="drawable" name="default_lock_wallpaper" />
<java-symbol type="drawable" name="indicator_input_error" />
+ <java-symbol type="drawable" name="ic_file_copy" />
<java-symbol type="drawable" name="popup_bottom_dark" />
<java-symbol type="drawable" name="popup_bottom_bright" />
<java-symbol type="drawable" name="popup_bottom_medium" />
@@ -3643,4 +3651,7 @@
<java-symbol type="array" name="config_displayWhiteBalanceDecreaseThresholds" />
<java-symbol type="dimen" name="config_displayWhiteBalanceLowLightAmbientBrightnessThreshold" />
<java-symbol type="dimen" name="config_displayWhiteBalanceLowLightAmbientColorTemperature" />
+ <java-symbol type="array" name="config_displayWhiteBalanceAmbientTemperatureValues" />
+ <java-symbol type="array" name="config_displayWhiteBalanceDisplayTemperatureValues" />
+ <java-symbol type="drawable" name="ic_action_open" />
</resources>
diff --git a/core/tests/coretests/src/android/provider/SettingsBackupTest.java b/core/tests/coretests/src/android/provider/SettingsBackupTest.java
index ec57f79..c57b609 100644
--- a/core/tests/coretests/src/android/provider/SettingsBackupTest.java
+++ b/core/tests/coretests/src/android/provider/SettingsBackupTest.java
@@ -128,7 +128,6 @@
Settings.Global.AUTOFILL_LOGGING_LEVEL,
Settings.Global.AUTOFILL_MAX_PARTITIONS_SIZE,
Settings.Global.AUTOFILL_MAX_VISIBLE_DATASETS,
- Settings.Global.AUTOFILL_SMART_SUGGESTION_EMULATION_FLAGS,
Settings.Global.AUTOMATIC_POWER_SAVER_MODE,
Settings.Global.BACKGROUND_ACTIVITY_STARTS_ENABLED,
Settings.Global.BATTERY_CHARGING_STATE_UPDATE_DELAY,
@@ -492,8 +491,10 @@
Settings.Global.GAME_DRIVER_ALL_APPS,
Settings.Global.GAME_DRIVER_OPT_IN_APPS,
Settings.Global.GAME_DRIVER_OPT_OUT_APPS,
+ Settings.Global.GAME_DRIVER_BLACKLISTS,
Settings.Global.GAME_DRIVER_BLACKLIST,
Settings.Global.GAME_DRIVER_WHITELIST,
+ Settings.Global.GLOBAL_SETTINGS_SHOW_ANGLE_IN_USE_DIALOG_BOX,
Settings.Global.GPU_DEBUG_LAYER_APP,
Settings.Global.ENABLE_GNSS_RAW_MEAS_FULL_TRACKING,
Settings.Global.INSTALL_CARRIER_APP_NOTIFICATION_PERSISTENT,
@@ -620,6 +621,7 @@
Settings.Secure.DISABLED_PRINT_SERVICES,
Settings.Secure.DISABLED_SYSTEM_INPUT_METHODS,
Settings.Secure.DISPLAY_DENSITY_FORCED,
+ Settings.Secure.DOCKED_CLOCK_FACE,
Settings.Secure.DOZE_PULSE_ON_LONG_PRESS,
Settings.Secure.EMERGENCY_ASSISTANCE_APPLICATION,
Settings.Secure.ENABLED_INPUT_METHODS, // Intentionally removed in P
diff --git a/core/tests/coretests/src/android/view/contentcapture/ViewNodeTest.java b/core/tests/coretests/src/android/view/contentcapture/ViewNodeTest.java
index 213cd40..93315f1 100644
--- a/core/tests/coretests/src/android/view/contentcapture/ViewNodeTest.java
+++ b/core/tests/coretests/src/android/view/contentcapture/ViewNodeTest.java
@@ -20,11 +20,12 @@
import android.content.Context;
import android.graphics.Matrix;
-import android.support.test.InstrumentationRegistry;
import android.view.View;
import android.view.ViewStructure.HtmlInfo;
import android.view.contentcapture.ViewNode.ViewStructureImpl;
+import androidx.test.InstrumentationRegistry;
+
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
diff --git a/core/tests/coretests/src/android/view/textclassifier/TextClassifierTest.java b/core/tests/coretests/src/android/view/textclassifier/TextClassifierTest.java
index bdd0370..d2d03e56 100644
--- a/core/tests/coretests/src/android/view/textclassifier/TextClassifierTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/TextClassifierTest.java
@@ -382,7 +382,6 @@
assertThat(textLanguage, isTextLanguage("ja"));
}
- /* DISABLED: b/122467291
@Test
public void testSuggestConversationActions_textReplyOnly_maxThree() {
if (isTextClassifierDisabled()) return;
@@ -410,7 +409,7 @@
assertThat(conversationAction,
isConversationAction(ConversationAction.TYPE_TEXT_REPLY));
}
- }*/
+ }
@Test
public void testSuggestConversationActions_textReplyOnly_noMax() {
diff --git a/core/tests/coretests/src/com/android/internal/app/ChooserActivityTest.java b/core/tests/coretests/src/com/android/internal/app/ChooserActivityTest.java
index 3d59835a..7f104b1 100644
--- a/core/tests/coretests/src/com/android/internal/app/ChooserActivityTest.java
+++ b/core/tests/coretests/src/com/android/internal/app/ChooserActivityTest.java
@@ -409,8 +409,7 @@
@Test
public void copyTextToClipboard() throws Exception {
Intent sendIntent = createSendTextIntent();
- List<ResolvedComponentInfo> resolvedComponentInfos =
- createResolvedComponentsForTestWithOtherProfile(1);
+ List<ResolvedComponentInfo> resolvedComponentInfos = createResolvedComponentsForTest(2);
when(ChooserWrapperActivity.sOverrides.resolverListController.getResolversForIntent(
Mockito.anyBoolean(),
@@ -421,6 +420,7 @@
.launchActivity(Intent.createChooser(sendIntent, null));
waitForIdle();
+ onView(withId(R.id.copy_button)).check(matches(isDisplayed()));
onView(withId(R.id.copy_button)).perform(click());
ClipboardManager clipboard = (ClipboardManager) activity.getSystemService(
Context.CLIPBOARD_SERVICE);
@@ -439,8 +439,9 @@
ArrayList<Uri> uris = new ArrayList<>();
uris.add(uri);
- Intent sendIntent = createSendImageIntentWithPreview(uris);
+ Intent sendIntent = createSendUriIntentWithPreview(uris);
sOverrides.previewThumbnail = createBitmap();
+ sOverrides.isImageType = true;
List<ResolvedComponentInfo> resolvedComponentInfos = createResolvedComponentsForTest(2);
@@ -464,8 +465,9 @@
uris.add(uri);
uris.add(uri);
- Intent sendIntent = createSendImageIntentWithPreview(uris);
+ Intent sendIntent = createSendUriIntentWithPreview(uris);
sOverrides.previewThumbnail = createBitmap();
+ sOverrides.isImageType = true;
List<ResolvedComponentInfo> resolvedComponentInfos = createResolvedComponentsForTest(2);
@@ -492,8 +494,9 @@
uris.add(uri);
uris.add(uri);
- Intent sendIntent = createSendImageIntentWithPreview(uris);
+ Intent sendIntent = createSendUriIntentWithPreview(uris);
sOverrides.previewThumbnail = createBitmap();
+ sOverrides.isImageType = true;
List<ResolvedComponentInfo> resolvedComponentInfos = createResolvedComponentsForTest(2);
@@ -538,12 +541,11 @@
ArgumentCaptor<LogMaker> logMakerCaptor = ArgumentCaptor.forClass(LogMaker.class);
mActivityRule.launchActivity(Intent.createChooser(sendIntent, "empty preview logger test"));
waitForIdle();
- verify(mockLogger, Mockito.times(2)).write(logMakerCaptor.capture());
+
+ verify(mockLogger, Mockito.times(1)).write(logMakerCaptor.capture());
// First invocation is from onCreate
- assertThat(logMakerCaptor.getAllValues().get(1).getCategory(),
- is(MetricsProto.MetricsEvent.ACTION_SHARE_WITH_PREVIEW));
- assertThat(logMakerCaptor.getAllValues().get(1).getSubtype(),
- is(CONTENT_PREVIEW_TEXT));
+ assertThat(logMakerCaptor.getAllValues().get(0).getCategory(),
+ is(MetricsProto.MetricsEvent.ACTION_ACTIVITY_CHOOSER_SHOWN));
}
@Test
@@ -552,9 +554,17 @@
MetricsLogger mockLogger = sOverrides.metricsLogger;
ArgumentCaptor<LogMaker> logMakerCaptor = ArgumentCaptor.forClass(LogMaker.class);
+
+ List<ResolvedComponentInfo> resolvedComponentInfos = createResolvedComponentsForTest(2);
+
+ when(ChooserWrapperActivity.sOverrides.resolverListController.getResolversForIntent(
+ Mockito.anyBoolean(),
+ Mockito.anyBoolean(),
+ Mockito.isA(List.class))).thenReturn(resolvedComponentInfos);
+
mActivityRule.launchActivity(Intent.createChooser(sendIntent, null));
waitForIdle();
- verify(mockLogger, Mockito.times(2)).write(logMakerCaptor.capture());
+ verify(mockLogger, Mockito.times(3)).write(logMakerCaptor.capture());
// First invocation is from onCreate
assertThat(logMakerCaptor.getAllValues().get(1).getCategory(),
is(MetricsProto.MetricsEvent.ACTION_SHARE_WITH_PREVIEW));
@@ -570,8 +580,9 @@
ArrayList<Uri> uris = new ArrayList<>();
uris.add(uri);
- Intent sendIntent = createSendImageIntentWithPreview(uris);
+ Intent sendIntent = createSendUriIntentWithPreview(uris);
sOverrides.previewThumbnail = createBitmap();
+ sOverrides.isImageType = true;
List<ResolvedComponentInfo> resolvedComponentInfos = createResolvedComponentsForTest(2);
@@ -595,6 +606,51 @@
is(CONTENT_PREVIEW_IMAGE));
}
+ @Test
+ public void oneVisibleFilePreview() throws InterruptedException {
+ Uri uri = Uri.parse("content://com.android.frameworks.coretests/app.pdf");
+
+ ArrayList<Uri> uris = new ArrayList<>();
+ uris.add(uri);
+
+ Intent sendIntent = createSendUriIntentWithPreview(uris);
+
+ List<ResolvedComponentInfo> resolvedComponentInfos = createResolvedComponentsForTest(2);
+
+ when(sOverrides.resolverListController.getResolversForIntent(Mockito.anyBoolean(),
+ Mockito.anyBoolean(),
+ Mockito.isA(List.class))).thenReturn(resolvedComponentInfos);
+ mActivityRule.launchActivity(Intent.createChooser(sendIntent, null));
+ waitForIdle();
+ onView(withId(R.id.content_preview_filename)).check(matches(isDisplayed()));
+ onView(withId(R.id.content_preview_filename)).check(matches(withText("app.pdf")));
+ onView(withId(R.id.content_preview_file_icon)).check(matches(isDisplayed()));
+ }
+
+
+ @Test
+ public void moreThanOneVisibleFilePreview() throws InterruptedException {
+ Uri uri = Uri.parse("content://com.android.frameworks.coretests/app.pdf");
+
+ ArrayList<Uri> uris = new ArrayList<>();
+ uris.add(uri);
+ uris.add(uri);
+ uris.add(uri);
+
+ Intent sendIntent = createSendUriIntentWithPreview(uris);
+
+ List<ResolvedComponentInfo> resolvedComponentInfos = createResolvedComponentsForTest(2);
+
+ when(sOverrides.resolverListController.getResolversForIntent(Mockito.anyBoolean(),
+ Mockito.anyBoolean(),
+ Mockito.isA(List.class))).thenReturn(resolvedComponentInfos);
+ mActivityRule.launchActivity(Intent.createChooser(sendIntent, null));
+ waitForIdle();
+ onView(withId(R.id.content_preview_filename)).check(matches(isDisplayed()));
+ onView(withId(R.id.content_preview_filename)).check(matches(withText("app.pdf + 2 files")));
+ onView(withId(R.id.content_preview_file_icon)).check(matches(isDisplayed()));
+ }
+
private Intent createSendTextIntent() {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
@@ -615,7 +671,7 @@
return sendIntent;
}
- private Intent createSendImageIntentWithPreview(ArrayList<Uri> uris) {
+ private Intent createSendUriIntentWithPreview(ArrayList<Uri> uris) {
Intent sendIntent = new Intent();
if (uris.size() > 1) {
diff --git a/core/tests/coretests/src/com/android/internal/app/ChooserWrapperActivity.java b/core/tests/coretests/src/com/android/internal/app/ChooserWrapperActivity.java
index f60467b..096b78b 100644
--- a/core/tests/coretests/src/com/android/internal/app/ChooserWrapperActivity.java
+++ b/core/tests/coretests/src/com/android/internal/app/ChooserWrapperActivity.java
@@ -89,11 +89,7 @@
@Override
protected boolean isImageType(String mimeType) {
- if (sOverrides.previewThumbnail != null) {
- return true;
- }
-
- return super.isImageType(mimeType);
+ return sOverrides.isImageType;
}
@Override
@@ -112,6 +108,7 @@
public Function<TargetInfo, Boolean> onSafelyStartCallback;
public ResolverListController resolverListController;
public Boolean isVoiceInteraction;
+ public boolean isImageType;
public Bitmap previewThumbnail;
public MetricsLogger metricsLogger;
@@ -120,6 +117,7 @@
isVoiceInteraction = null;
createPackageManager = null;
previewThumbnail = null;
+ isImageType = false;
resolverListController = mock(ResolverListController.class);
metricsLogger = mock(MetricsLogger.class);
}
diff --git a/core/tests/coretests/src/com/android/internal/os/BinderCallsStatsTest.java b/core/tests/coretests/src/com/android/internal/os/BinderCallsStatsTest.java
index 1d35143..e375af3 100644
--- a/core/tests/coretests/src/com/android/internal/os/BinderCallsStatsTest.java
+++ b/core/tests/coretests/src/com/android/internal/os/BinderCallsStatsTest.java
@@ -658,6 +658,67 @@
assertTrue(debugEntry3.latencyMicros >= 0);
}
+ @Test
+ public void testTrackScreenInteractiveDisabled() {
+ TestBinderCallsStats bcs = new TestBinderCallsStats();
+ bcs.setTrackScreenInteractive(false);
+ Binder binder = new Binder();
+
+ mDeviceState.setScreenInteractive(false);
+ CallSession callSession = bcs.callStarted(binder, 1, WORKSOURCE_UID);
+ bcs.time += 10;
+ bcs.callEnded(callSession, REQUEST_SIZE, REPLY_SIZE, WORKSOURCE_UID);
+
+ mDeviceState.setScreenInteractive(true);
+ callSession = bcs.callStarted(binder, 1, WORKSOURCE_UID);
+ bcs.time += 1000; // shoud be ignored.
+ bcs.callEnded(callSession, REQUEST_SIZE, REPLY_SIZE, WORKSOURCE_UID);
+
+ SparseArray<BinderCallsStats.UidEntry> uidEntries = bcs.getUidEntries();
+ assertEquals(1, uidEntries.size());
+ BinderCallsStats.UidEntry uidEntry = uidEntries.get(WORKSOURCE_UID);
+ Assert.assertNotNull(uidEntry);
+ assertEquals(2, uidEntry.callCount);
+
+ List<BinderCallsStats.CallStat> callStatsList = new ArrayList(uidEntry.getCallStatsList());
+ assertEquals(1, callStatsList.size());
+ BinderCallsStats.CallStat callStats = callStatsList.get(0);
+ assertEquals(false, callStats.screenInteractive);
+ assertEquals(2, callStats.callCount);
+ assertEquals(2, callStats.recordedCallCount);
+ }
+
+ @Test
+ public void testTrackCallingUidDisabled() {
+ TestBinderCallsStats bcs = new TestBinderCallsStats();
+ bcs.setTrackDirectCallerUid(false);
+ Binder binder = new Binder();
+
+ bcs.setCallingUid(1);
+ CallSession callSession = bcs.callStarted(binder, 1, WORKSOURCE_UID);
+ bcs.time += 10;
+ bcs.callEnded(callSession, REQUEST_SIZE, REPLY_SIZE, WORKSOURCE_UID);
+
+ bcs.setCallingUid(2);
+ callSession = bcs.callStarted(binder, 1, WORKSOURCE_UID);
+ bcs.time += 1000; // shoud be ignored.
+ bcs.callEnded(callSession, REQUEST_SIZE, REPLY_SIZE, WORKSOURCE_UID);
+
+ SparseArray<BinderCallsStats.UidEntry> uidEntries = bcs.getUidEntries();
+ assertEquals(1, uidEntries.size());
+ BinderCallsStats.UidEntry uidEntry = uidEntries.get(WORKSOURCE_UID);
+ Assert.assertNotNull(uidEntry);
+ assertEquals(2, uidEntry.callCount);
+
+ List<BinderCallsStats.CallStat> callStatsList = new ArrayList(uidEntry.getCallStatsList());
+ assertEquals(1, callStatsList.size());
+ BinderCallsStats.CallStat callStats = callStatsList.get(0);
+ assertEquals(-1, callStats.callingUid);
+ assertEquals(2, callStats.callCount);
+ assertEquals(2, callStats.recordedCallCount);
+ }
+
+
class TestBinderCallsStats extends BinderCallsStats {
public int callingUid = CALLING_UID;
public long time = 1234;
@@ -682,6 +743,8 @@
});
setSamplingInterval(1);
setAddDebugEntries(false);
+ setTrackScreenInteractive(true);
+ setTrackDirectCallerUid(true);
if (deviceState != null) {
setDeviceState(deviceState.getReadonlyClient());
}
@@ -701,6 +764,10 @@
protected int getCallingUid() {
return callingUid;
}
+
+ protected void setCallingUid(int uid) {
+ callingUid = uid;
+ }
}
}
diff --git a/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderEndToEndTest.java b/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderEndToEndTest.java
index 64b7c2cc..1c84829 100644
--- a/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderEndToEndTest.java
+++ b/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderEndToEndTest.java
@@ -124,7 +124,7 @@
// Get thread data from KernelCpuThreadReader
final KernelCpuThreadReader kernelCpuThreadReader =
- KernelCpuThreadReader.create(8, uid -> uid == Process.myUid());
+ KernelCpuThreadReader.create(8, uid -> uid == Process.myUid(), 0);
assertNotNull(kernelCpuThreadReader);
final ProcessCpuUsage currentProcessCpuUsage =
kernelCpuThreadReader.getCurrentProcessCpuUsage();
diff --git a/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderTest.java b/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderTest.java
index b9744f5..442ece5 100644
--- a/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderTest.java
+++ b/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderTest.java
@@ -103,6 +103,7 @@
final KernelCpuThreadReader kernelCpuThreadReader = new KernelCpuThreadReader(
8,
uid -> 1000 <= uid && uid < 2000,
+ 0,
mProcDirectory.toPath(),
mProcDirectory.toPath().resolve("self/task/" + THREAD_IDS[0] + "/time_in_state"),
processUtils);
@@ -144,6 +145,7 @@
final KernelCpuThreadReader kernelCpuThreadReader = new KernelCpuThreadReader(
8,
uidPredicate,
+ 0,
mProcDirectory.toPath(),
mProcDirectory.toPath().resolve(uids[0] + "/task/" + uids[0] + "/time_in_state"),
processUtils);
@@ -162,6 +164,60 @@
}
}
+ @Test
+ public void testReader_filtersLowUsage() throws IOException {
+ int[] uids = new int[]{0, 1, 2, 3, 4};
+ int[] cpuUsage = new int[]{10, 0, 2, 100, 3};
+ int[] expectedUids = new int[]{0, 3, 4};
+ Predicate<Integer> uidPredicate = uid -> true;
+ KernelCpuThreadReader.Injector processUtils =
+ new KernelCpuThreadReader.Injector() {
+ @Override
+ public int myPid() {
+ return 0;
+ }
+
+ @Override
+ public int myUid() {
+ return 0;
+ }
+
+ @Override
+ public int getUidForPid(int pid) {
+ return pid;
+ }
+ };
+
+ for (int i = 0; i < uids.length; i++) {
+ int uid = uids[i];
+ setupDirectory(
+ mProcDirectory.toPath().resolve(String.valueOf(uid)),
+ new int[]{uid * 10},
+ "process" + uid,
+ new String[]{"thread" + uid},
+ new int[]{1000},
+ new int[][]{{cpuUsage[i]}});
+ }
+ final KernelCpuThreadReader kernelCpuThreadReader = new KernelCpuThreadReader(
+ 8,
+ uidPredicate,
+ 30,
+ mProcDirectory.toPath(),
+ mProcDirectory.toPath().resolve(uids[0] + "/task/" + uids[0] + "/time_in_state"),
+ processUtils);
+ ArrayList<KernelCpuThreadReader.ProcessCpuUsage> processCpuUsageByUids =
+ kernelCpuThreadReader.getProcessCpuUsageByUids();
+ processCpuUsageByUids.sort(Comparator.comparing(usage -> usage.uid));
+
+ assertEquals(expectedUids.length, processCpuUsageByUids.size());
+ for (int i = 0; i < expectedUids.length; i++) {
+ KernelCpuThreadReader.ProcessCpuUsage processCpuUsage =
+ processCpuUsageByUids.get(i);
+ assertEquals(expectedUids[i], processCpuUsage.uid);
+ }
+
+ }
+
private void setupDirectory(Path processPath, int[] threadIds, String processName,
String[] threadNames, int[] cpuFrequencies, int[][] cpuTimes) throws IOException {
// Make /proc/$PID
@@ -328,7 +384,6 @@
new long[]{1, 1, 1, 1, 1, 1, 1, 1}));
}
-
@Test
public void testGetBigFrequenciesStartIndex_simple() {
assertEquals(
diff --git a/core/tests/coretests/src/com/android/internal/os/LooperStatsTest.java b/core/tests/coretests/src/com/android/internal/os/LooperStatsTest.java
index 79b8477..3edf5f8 100644
--- a/core/tests/coretests/src/com/android/internal/os/LooperStatsTest.java
+++ b/core/tests/coretests/src/com/android/internal/os/LooperStatsTest.java
@@ -476,6 +476,33 @@
assertThat(debugEntry3.totalLatencyMicros).isAtLeast(0L);
}
+ @Test
+ public void testScreenStateTrackingDisabled() {
+ TestableLooperStats looperStats = new TestableLooperStats(1, 100);
+ looperStats.setTrackScreenInteractive(false);
+
+ Message message = mHandlerFirst.obtainMessage(1000);
+ message.workSourceUid = 1000;
+ message.when = looperStats.getSystemUptimeMillis();
+
+ looperStats.tickUptime(30);
+ mDeviceState.setScreenInteractive(false);
+ Object token = looperStats.messageDispatchStarting();
+ looperStats.messageDispatched(token, message);
+
+ looperStats.tickUptime(30);
+ mDeviceState.setScreenInteractive(true);
+ token = looperStats.messageDispatchStarting();
+ looperStats.messageDispatched(token, message);
+
+ List<LooperStats.ExportedEntry> entries = looperStats.getEntries();
+ assertThat(entries).hasSize(1);
+ LooperStats.ExportedEntry entry = entries.get(0);
+ assertThat(entry.isInteractive).isEqualTo(false);
+ assertThat(entry.messageCount).isEqualTo(2);
+ assertThat(entry.recordedMessageCount).isEqualTo(2);
+ }
+
private static void assertThrows(Class<? extends Exception> exceptionClass, Runnable r) {
try {
r.run();
@@ -501,6 +528,7 @@
super(samplingInterval, sizeCap);
mSamplingInterval = samplingInterval;
setAddDebugEntries(false);
+ setTrackScreenInteractive(true);
if (deviceState != null) {
setDeviceState(deviceState.getReadonlyClient());
}
diff --git a/data/etc/privapp-permissions-platform.xml b/data/etc/privapp-permissions-platform.xml
index 6770ae1..915cf95 100644
--- a/data/etc/privapp-permissions-platform.xml
+++ b/data/etc/privapp-permissions-platform.xml
@@ -209,21 +209,14 @@
<privapp-permissions package="com.android.mainline.networkstack">
<permission name="android.permission.ACCESS_NETWORK_CONDITIONS"/>
- <permission name="android.permission.CHANGE_BACKGROUND_DATA_SETTING"/>
<permission name="android.permission.CONNECTIVITY_INTERNAL"/>
<permission name="android.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS"/>
<permission name="android.permission.CONTROL_VPN"/>
+ <permission name="android.permission.INTERACT_ACROSS_USERS"/>
<permission name="android.permission.LOCAL_MAC_ADDRESS"/>
- <permission name="android.permission.MANAGE_IPSEC_TUNNELS"/>
- <permission name="android.permission.MANAGE_NETWORK_POLICY"/>
<permission name="android.permission.MANAGE_SUBSCRIPTION_PLANS"/>
<permission name="android.permission.MANAGE_USB"/>
- <permission name="android.permission.NETWORK_BYPASS_PRIVATE_DNS"/>
- <permission name="android.permission.NETWORK_SETTINGS"/>
- <permission name="android.permission.NETWORK_STACK" />
- <permission name="android.permission.NET_TUNNELING"/>
<permission name="android.permission.PACKET_KEEPALIVE_OFFLOAD"/>
- <permission name="android.permission.PEERS_MAC_ADDRESS"/>
<permission name="android.permission.READ_NETWORK_USAGE_HISTORY"/>
<permission name="android.permission.READ_PRECISE_PHONE_STATE"/>
<permission name="android.permission.READ_PRIVILEGED_PHONE_STATE"/>
@@ -261,6 +254,7 @@
<permission name="android.permission.CHANGE_LOWPAN_STATE"/>
<permission name="android.permission.CHANGE_OVERLAY_PACKAGES"/>
<permission name="android.permission.CLEAR_APP_CACHE"/>
+ <permission name="android.permission.ACCESS_INSTANT_APPS" />
<permission name="android.permission.CONNECTIVITY_INTERNAL"/>
<permission name="android.permission.DELETE_CACHE_FILES"/>
<permission name="android.permission.DELETE_PACKAGES"/>
@@ -334,4 +328,9 @@
<permission name="android.permission.CONTROL_VPN"/>
</privapp-permissions>
+ <privapp-permissions package="com.android.dynandroid">
+ <permission name="android.permission.REBOOT"/>
+ <permission name="android.permission.MANAGE_DYNAMIC_ANDROID"/>
+ </privapp-permissions>
+
</permissions>
diff --git a/graphics/java/android/graphics/Typeface.java b/graphics/java/android/graphics/Typeface.java
index 7c9529b..ef9255f 100644
--- a/graphics/java/android/graphics/Typeface.java
+++ b/graphics/java/android/graphics/Typeface.java
@@ -127,7 +127,10 @@
static Typeface sDefaultTypeface;
// Following two fields are not used but left for hiddenapi private list
- @UnsupportedAppUsage
+ /**
+ * Use {@link SystemFonts#getAvailableFonts()} instead.
+ */
+ @UnsupportedAppUsage(trackingBug = 123769347)
static final Map<String, Typeface> sSystemFontMap;
// We cannot support sSystemFallbackMap since we will migrate to public FontFamily API.
@@ -175,7 +178,12 @@
private int[] mSupportedAxes;
private static final int[] EMPTY_AXES = {};
- @UnsupportedAppUsage
+ /**
+ * Please use font in xml and also your application global theme to change the default Typeface.
+ * android:textViewStyle and its attribute android:textAppearance can be used in order to change
+ * typeface and other text related properties.
+ */
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
private static void setDefault(Typeface t) {
sDefaultTypeface = t;
nativeSetDefault(t.native_instance);
diff --git a/graphics/java/android/graphics/drawable/GradientDrawable.java b/graphics/java/android/graphics/drawable/GradientDrawable.java
index 991847a..6ecb621 100644
--- a/graphics/java/android/graphics/drawable/GradientDrawable.java
+++ b/graphics/java/android/graphics/drawable/GradientDrawable.java
@@ -44,6 +44,7 @@
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.graphics.Xfermode;
+import android.os.Build;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
@@ -156,12 +157,12 @@
private static final float DEFAULT_INNER_RADIUS_RATIO = 3.0f;
private static final float DEFAULT_THICKNESS_RATIO = 9.0f;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124050917)
private GradientState mGradientState;
@UnsupportedAppUsage
private final Paint mFillPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124051827)
private Rect mPadding;
@UnsupportedAppUsage
private Paint mStrokePaint; // optional, set by the caller
@@ -670,7 +671,28 @@
* @see #setColor(int)
*/
public void setColors(@ColorInt int[] colors) {
+ setColors(colors, null);
+ }
+
+ /**
+ * Sets the colors and offsets used to draw the gradient.
+ * <p>
+ * Each color is specified as an ARGB integer and the array must contain at
+ * least 2 colors.
+ * <p>
+ * <strong>Note</strong>: changing colors will affect all instances of a
+ * drawable loaded from a resource. It is recommended to invoke
+ * {@link #mutate()} before changing the colors.
+ *
+ * @param colors an array containing 2 or more ARGB colors
+ * @param offsets optional array of floating point parameters representing the positions
+ * of the colors. Null evenly disperses the colors
+ * @see #mutate()
+ * @see #setColors(int[])
+ */
+ public void setColors(@ColorInt int[] colors, @Nullable float[] offsets) {
mGradientState.setGradientColors(colors);
+ mGradientState.mPositions = offsets;
mGradientIsDirty = true;
invalidateSelf();
}
@@ -849,6 +871,115 @@
}
}
+ /**
+ * Inner radius of the ring expressed as a ratio of the ring's width.
+ *
+ * @see #getInnerRadiusRatio()
+ * @attr ref android.R.styleable#GradientDrawable_innerRadiusRatio
+ */
+ public void setInnerRadiusRatio(float innerRadiusRatio) {
+ mGradientState.mInnerRadiusRatio = innerRadiusRatio;
+ mPathIsDirty = true;
+ invalidateSelf();
+ }
+
+ /**
+ * Return the inner radius of the ring expressed as a ratio of the ring's width.
+ *
+ * @see #setInnerRadiusRatio(float)
+ * @attr ref android.R.styleable#GradientDrawable_innerRadiusRatio
+ */
+ public float getInnerRadiusRatio() {
+ return mGradientState.mInnerRadiusRatio;
+ }
+
+ /**
+ * Configure the inner radius of the ring.
+ *
+ * @see #getInnerRadius()
+ * @attr ref android.R.styleable#GradientDrawable_innerRadius
+ */
+ public void setInnerRadius(int innerRadius) {
+ mGradientState.mInnerRadius = innerRadius;
+ mPathIsDirty = true;
+ invalidateSelf();
+ }
+
+ /**
+ * Retrn the inner radius of the ring
+ *
+ * @see #setInnerRadius(int)
+ * @attr ref android.R.styleable#GradientDrawable_innerRadius
+ */
+ public int getInnerRadius() {
+ return mGradientState.mInnerRadius;
+ }
+
+ /**
+ * Configure the thickness of the ring expressed as a ratio of the ring's width.
+ *
+ * @see #getThicknessRatio()
+ * @attr ref android.R.styleable#GradientDrawable_thicknessRatio
+ */
+ public void setThicknessRatio(float thicknessRatio) {
+ mGradientState.mThicknessRatio = thicknessRatio;
+ mPathIsDirty = true;
+ invalidateSelf();
+ }
+
+ /**
+ * Return the thickness ratio of the ring expressed as a ratio of the ring's width.
+ *
+ * @see #setThicknessRatio(float)
+ * @attr ref android.R.styleable#GradientDrawable_thicknessRatio
+ */
+ public float getThicknessRatio() {
+ return mGradientState.mThicknessRatio;
+ }
+
+ /**
+ * Configure the thickness of the ring.
+ *
+ * @attr ref android.R.styleable#GradientDrawable_thickness
+ */
+ public void setThickness(int thickness) {
+ mGradientState.mThickness = thickness;
+ mPathIsDirty = true;
+ invalidateSelf();
+ }
+
+ /**
+ * Return the thickness of the ring
+ *
+ * @see #setThickness(int)
+ * @attr ref android.R.styleable#GradientDrawable_thickness
+ */
+ public int getThickness() {
+ return mGradientState.mThickness;
+ }
+
+ /**
+ * Configure the padding of the gradient shape
+ * @param left Left padding of the gradient shape
+ * @param top Top padding of the gradient shape
+ * @param right Right padding of the gradient shape
+ * @param bottom Bottom padding of the gradient shape
+ *
+ * @attr ref android.R.styleable#GradientDrawablePadding_left
+ * @attr ref android.R.styleable#GradientDrawablePadding_top
+ * @attr ref android.R.styleable#GradientDrawablePadding_right
+ * @attr ref android.R.styleable#GradientDrawablePadding_bottom
+ */
+ public void setPadding(int left, int top, int right, int bottom) {
+ if (mGradientState.mPadding == null) {
+ mGradientState.mPadding = new Rect();
+ }
+
+ mGradientState.mPadding.set(left, top, right, bottom);
+ mPadding = mGradientState.mPadding;
+ invalidateSelf();
+ }
+
private Path buildRing(GradientState st) {
if (mRingPath != null && (!st.mUseLevelForShape || !mPathIsDirty)) return mRingPath;
mPathIsDirty = false;
@@ -1814,46 +1945,46 @@
final static class GradientState extends ConstantState {
public @Config int mChangingConfigurations;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124050917)
public @Shape int mShape = RECTANGLE;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124050917)
public @GradientType int mGradient = LINEAR_GRADIENT;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124050917)
public int mAngle = 0;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124050917)
public Orientation mOrientation;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124050917)
public ColorStateList mSolidColors;
public ColorStateList mStrokeColors;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124050917)
public @ColorInt int[] mGradientColors;
public @ColorInt int[] mTempColors; // no need to copy
public float[] mTempPositions; // no need to copy
@UnsupportedAppUsage
public float[] mPositions;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124050917)
public int mStrokeWidth = -1; // if >= 0 use stroking.
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124050917)
public float mStrokeDashWidth = 0.0f;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124050917)
public float mStrokeDashGap = 0.0f;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124050917)
public float mRadius = 0.0f; // use this if mRadiusArray is null
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124050917)
public float[] mRadiusArray = null;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124050917)
public Rect mPadding = null;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124050917)
public int mWidth = -1;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124050917)
public int mHeight = -1;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124050917)
public float mInnerRadiusRatio = DEFAULT_INNER_RADIUS_RATIO;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124050218)
public float mThicknessRatio = DEFAULT_THICKNESS_RATIO;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124050917)
public int mInnerRadius = -1;
- @UnsupportedAppUsage
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 124050218)
public int mThickness = -1;
public boolean mDither = false;
public Insets mOpticalInsets = Insets.NONE;
diff --git a/libs/hwui/FrameMetricsObserver.h b/libs/hwui/FrameMetricsObserver.h
index 237fc62..b93f078 100644
--- a/libs/hwui/FrameMetricsObserver.h
+++ b/libs/hwui/FrameMetricsObserver.h
@@ -23,7 +23,7 @@
class FrameMetricsObserver : public VirtualLightRefBase {
public:
- virtual void notify(const int64_t* buffer);
+ virtual void notify(const int64_t* buffer) = 0;
};
} // namespace uirenderer
diff --git a/libs/hwui/Readback.cpp b/libs/hwui/Readback.cpp
index 76c56609..2ffda83 100644
--- a/libs/hwui/Readback.cpp
+++ b/libs/hwui/Readback.cpp
@@ -107,7 +107,7 @@
if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL) {
mRenderThread.requireGlContext();
} else {
- mRenderThread.vulkanManager().initialize();
+ mRenderThread.requireVkContext();
}
if (!image.get()) {
return CopyResult::UnknownError;
diff --git a/libs/hwui/pipeline/skia/SkiaVulkanPipeline.cpp b/libs/hwui/pipeline/skia/SkiaVulkanPipeline.cpp
index 15f53f2..87cffb5 100644
--- a/libs/hwui/pipeline/skia/SkiaVulkanPipeline.cpp
+++ b/libs/hwui/pipeline/skia/SkiaVulkanPipeline.cpp
@@ -120,7 +120,7 @@
}
DeferredLayerUpdater* SkiaVulkanPipeline::createTextureLayer() {
- mVkManager.initialize();
+ mRenderThread.requireVkContext();
return new DeferredLayerUpdater(mRenderThread.renderState());
}
@@ -136,8 +136,9 @@
setSurfaceColorProperties(colorMode);
if (surface) {
+ mRenderThread.requireVkContext();
mVkSurface = mVkManager.createSurface(surface, colorMode, mSurfaceColorSpace,
- mSurfaceColorType);
+ mSurfaceColorType, mRenderThread.getGrContext());
}
return mVkSurface != nullptr;
diff --git a/libs/hwui/renderthread/RenderThread.cpp b/libs/hwui/renderthread/RenderThread.cpp
index 3904ed2..fc63819 100644
--- a/libs/hwui/renderthread/RenderThread.cpp
+++ b/libs/hwui/renderthread/RenderThread.cpp
@@ -173,10 +173,10 @@
initializeDisplayEventReceiver();
mEglManager = new EglManager();
mRenderState = new RenderState(*this);
- mVkManager = new VulkanManager(*this);
+ mVkManager = new VulkanManager();
mCacheManager = new CacheManager(mDisplayInfo);
if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaVulkan) {
- mVkManager->initialize();
+ requireVkContext();
}
}
@@ -195,8 +195,7 @@
LOG_ALWAYS_FATAL_IF(!glInterface.get());
GrContextOptions options;
- options.fPreferExternalImagesOverES3 = true;
- options.fDisableDistanceFieldPaths = true;
+ initGrContextOptions(options);
auto glesVersion = reinterpret_cast<const char*>(glGetString(GL_VERSION));
auto size = glesVersion ? strlen(glesVersion) : -1;
cacheManager().configureContext(&options, glesVersion, size);
@@ -205,6 +204,25 @@
setGrContext(grContext);
}
+void RenderThread::requireVkContext() {
+ if (mVkManager->hasVkContext()) {
+ return;
+ }
+ mVkManager->initialize();
+ GrContextOptions options;
+ initGrContextOptions(options);
+ // TODO: get a string describing the SPIR-V compiler version and use it here
+ cacheManager().configureContext(&options, nullptr, 0);
+ sk_sp<GrContext> grContext = mVkManager->createContext(options);
+ LOG_ALWAYS_FATAL_IF(!grContext.get());
+ setGrContext(grContext);
+}
+
+void RenderThread::initGrContextOptions(GrContextOptions& options) {
+ options.fPreferExternalImagesOverES3 = true;
+ options.fDisableDistanceFieldPaths = true;
+}
+
void RenderThread::destroyRenderingContext() {
mFunctorManager.onContextDestroyed();
if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL) {
diff --git a/libs/hwui/renderthread/RenderThread.h b/libs/hwui/renderthread/RenderThread.h
index b182928..419e7c7 100644
--- a/libs/hwui/renderthread/RenderThread.h
+++ b/libs/hwui/renderthread/RenderThread.h
@@ -112,6 +112,7 @@
void dumpGraphicsMemory(int fd);
void requireGlContext();
+ void requireVkContext();
void destroyRenderingContext();
/**
@@ -122,6 +123,8 @@
*/
static bool isCurrent();
+ static void initGrContextOptions(GrContextOptions& options);
+
protected:
virtual bool threadLoop() override;
diff --git a/libs/hwui/renderthread/VulkanManager.cpp b/libs/hwui/renderthread/VulkanManager.cpp
index 90397fd..1e685ab 100644
--- a/libs/hwui/renderthread/VulkanManager.cpp
+++ b/libs/hwui/renderthread/VulkanManager.cpp
@@ -55,11 +55,7 @@
#define GET_INST_PROC(F) m##F = (PFN_vk##F)vkGetInstanceProcAddr(mInstance, "vk" #F)
#define GET_DEV_PROC(F) m##F = (PFN_vk##F)vkGetDeviceProcAddr(mDevice, "vk" #F)
-VulkanManager::VulkanManager(RenderThread& thread) : mRenderThread(thread) {}
-
void VulkanManager::destroy() {
- mRenderThread.setGrContext(nullptr);
-
// We don't need to explicitly free the command buffer since it automatically gets freed when we
// delete the VkCommandPool below.
mDummyCB = VK_NULL_HANDLE;
@@ -333,29 +329,10 @@
LOG_ALWAYS_FATAL_IF(mEnumerateInstanceVersion(&instanceVersion));
LOG_ALWAYS_FATAL_IF(instanceVersion < VK_MAKE_VERSION(1, 1, 0));
- GrVkExtensions extensions;
- this->setupDevice(extensions, mPhysicalDeviceFeatures2);
+ this->setupDevice(mExtensions, mPhysicalDeviceFeatures2);
mGetDeviceQueue(mDevice, mGraphicsQueueIndex, 0, &mGraphicsQueue);
- auto getProc = [] (const char* proc_name, VkInstance instance, VkDevice device) {
- if (device != VK_NULL_HANDLE) {
- return vkGetDeviceProcAddr(device, proc_name);
- }
- return vkGetInstanceProcAddr(instance, proc_name);
- };
-
- GrVkBackendContext backendContext;
- backendContext.fInstance = mInstance;
- backendContext.fPhysicalDevice = mPhysicalDevice;
- backendContext.fDevice = mDevice;
- backendContext.fQueue = mGraphicsQueue;
- backendContext.fGraphicsQueueIndex = mGraphicsQueueIndex;
- backendContext.fMaxAPIVersion = mAPIVersion;
- backendContext.fVkExtensions = &extensions;
- backendContext.fDeviceFeatures2 = &mPhysicalDeviceFeatures2;
- backendContext.fGetProc = std::move(getProc);
-
// create the command pool for the command buffers
if (VK_NULL_HANDLE == mCommandPool) {
VkCommandPoolCreateInfo commandPoolInfo;
@@ -376,22 +353,35 @@
}
LOG_ALWAYS_FATAL_IF(mDummyCB == VK_NULL_HANDLE);
-
mGetDeviceQueue(mDevice, mPresentQueueIndex, 0, &mPresentQueue);
- GrContextOptions options;
- options.fDisableDistanceFieldPaths = true;
- // TODO: get a string describing the SPIR-V compiler version and use it here
- mRenderThread.cacheManager().configureContext(&options, nullptr, 0);
- sk_sp<GrContext> grContext(GrContext::MakeVulkan(backendContext, options));
- LOG_ALWAYS_FATAL_IF(!grContext.get());
- mRenderThread.setGrContext(grContext);
-
if (Properties::enablePartialUpdates && Properties::useBufferAge) {
mSwapBehavior = SwapBehavior::BufferAge;
}
}
+sk_sp<GrContext> VulkanManager::createContext(GrContextOptions options) {
+ auto getProc = [] (const char* proc_name, VkInstance instance, VkDevice device) {
+ if (device != VK_NULL_HANDLE) {
+ return vkGetDeviceProcAddr(device, proc_name);
+ }
+ return vkGetInstanceProcAddr(instance, proc_name);
+ };
+
+ GrVkBackendContext backendContext;
+ backendContext.fInstance = mInstance;
+ backendContext.fPhysicalDevice = mPhysicalDevice;
+ backendContext.fDevice = mDevice;
+ backendContext.fQueue = mGraphicsQueue;
+ backendContext.fGraphicsQueueIndex = mGraphicsQueueIndex;
+ backendContext.fMaxAPIVersion = mAPIVersion;
+ backendContext.fVkExtensions = &mExtensions;
+ backendContext.fDeviceFeatures2 = &mPhysicalDeviceFeatures2;
+ backendContext.fGetProc = std::move(getProc);
+
+ return GrContext::MakeVulkan(backendContext, options);
+}
+
VkFunctorInitParams VulkanManager::getVkFunctorInitParams() const {
return VkFunctorInitParams{
.instance = mInstance,
@@ -470,8 +460,9 @@
ColorMode colorMode = surface->mColorMode;
sk_sp<SkColorSpace> colorSpace = surface->mColorSpace;
SkColorType colorType = surface->mColorType;
+ GrContext* grContext = surface->mGrContext;
destroySurface(surface);
- *surfaceOut = createSurface(window, colorMode, colorSpace, colorType);
+ *surfaceOut = createSurface(window, colorMode, colorSpace, colorType, grContext);
surface = *surfaceOut;
if (!surface) {
return nullptr;
@@ -650,7 +641,7 @@
VulkanSurface::ImageInfo& imageInfo = surface->mImageInfos[i];
imageInfo.mSurface = SkSurface::MakeFromBackendRenderTarget(
- mRenderThread.getGrContext(), backendRT, kTopLeft_GrSurfaceOrigin,
+ surface->mGrContext, backendRT, kTopLeft_GrSurfaceOrigin,
surface->mColorType, surface->mColorSpace, &props);
}
@@ -880,15 +871,15 @@
VulkanSurface* VulkanManager::createSurface(ANativeWindow* window, ColorMode colorMode,
sk_sp<SkColorSpace> surfaceColorSpace,
- SkColorType surfaceColorType) {
- initialize();
-
+ SkColorType surfaceColorType,
+ GrContext* grContext) {
+ LOG_ALWAYS_FATAL_IF(!hasVkContext(), "Not initialized");
if (!window) {
return nullptr;
}
VulkanSurface* surface = new VulkanSurface(colorMode, window, surfaceColorSpace,
- surfaceColorType);
+ surfaceColorType, grContext);
VkAndroidSurfaceCreateInfoKHR surfaceCreateInfo;
memset(&surfaceCreateInfo, 0, sizeof(VkAndroidSurfaceCreateInfoKHR));
diff --git a/libs/hwui/renderthread/VulkanManager.h b/libs/hwui/renderthread/VulkanManager.h
index 1fe6c65..9763686 100644
--- a/libs/hwui/renderthread/VulkanManager.h
+++ b/libs/hwui/renderthread/VulkanManager.h
@@ -22,6 +22,8 @@
#endif
#include <vulkan/vulkan.h>
+#include <GrContextOptions.h>
+#include <vk/GrVkExtensions.h>
#include <SkSurface.h>
#include <ui/Fence.h>
#include <utils/StrongPointer.h>
@@ -39,9 +41,9 @@
class VulkanSurface {
public:
VulkanSurface(ColorMode colorMode, ANativeWindow* window, sk_sp<SkColorSpace> colorSpace,
- SkColorType colorType)
+ SkColorType colorType, GrContext* grContext)
: mColorMode(colorMode), mNativeWindow(window), mColorSpace(colorSpace),
- mColorType(colorType) {}
+ mColorType(colorType), mGrContext(grContext) {}
sk_sp<SkSurface> getBackBufferSurface() { return mBackbuffer; }
@@ -93,6 +95,7 @@
SkColorType mColorType;
VkSurfaceTransformFlagBitsKHR mTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
SkMatrix mPreTransform;
+ GrContext* mGrContext;
};
// This class contains the shared global Vulkan objects, such as VkInstance, VkDevice and VkQueue,
@@ -100,6 +103,9 @@
// windowing contexts. The VulkanManager must be initialized before use.
class VulkanManager {
public:
+ explicit VulkanManager() {}
+ ~VulkanManager() { destroy(); }
+
// Sets up the vulkan context that is shared amonst all clients of the VulkanManager. This must
// be call once before use of the VulkanManager. Multiple calls after the first will simiply
// return.
@@ -112,7 +118,8 @@
// VulkanSurface object which is returned.
VulkanSurface* createSurface(ANativeWindow* window, ColorMode colorMode,
sk_sp<SkColorSpace> surfaceColorSpace,
- SkColorType surfaceColorType);
+ SkColorType surfaceColorType,
+ GrContext* grContext);
// Destroy the VulkanSurface and all associated vulkan objects.
void destroySurface(VulkanSurface* surface);
@@ -143,12 +150,9 @@
// Returned pointers are owned by VulkanManager.
VkFunctorInitParams getVkFunctorInitParams() const;
+ sk_sp<GrContext> createContext(GrContextOptions options);
+
private:
- friend class RenderThread;
-
- explicit VulkanManager(RenderThread& thread);
- ~VulkanManager() { destroy(); }
-
// Sets up the VkInstance and VkDevice objects. Also fills out the passed in
// VkPhysicalDeviceFeatures struct.
void setupDevice(GrVkExtensions&, VkPhysicalDeviceFeatures2&);
@@ -231,8 +235,6 @@
VkPtr<PFN_vkWaitForFences> mWaitForFences;
VkPtr<PFN_vkResetFences> mResetFences;
- RenderThread& mRenderThread;
-
VkInstance mInstance = VK_NULL_HANDLE;
VkPhysicalDevice mPhysicalDevice = VK_NULL_HANDLE;
VkDevice mDevice = VK_NULL_HANDLE;
@@ -256,6 +258,7 @@
BufferAge,
};
SwapBehavior mSwapBehavior = SwapBehavior::Discard;
+ GrVkExtensions mExtensions;
};
} /* namespace renderthread */
diff --git a/libs/hwui/tests/common/TestUtils.cpp b/libs/hwui/tests/common/TestUtils.cpp
index a9f651d..e8ba15f 100644
--- a/libs/hwui/tests/common/TestUtils.cpp
+++ b/libs/hwui/tests/common/TestUtils.cpp
@@ -100,7 +100,7 @@
// RenderState only valid once RenderThread is running, so queried here
renderthread::RenderThread& renderThread = renderthread::RenderThread::getInstance();
if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaVulkan) {
- renderThread.vulkanManager().initialize();
+ renderThread.requireVkContext();
} else {
renderThread.requireGlContext();
}
diff --git a/libs/input/PointerController.cpp b/libs/input/PointerController.cpp
index d742cc3..733b866 100644
--- a/libs/input/PointerController.cpp
+++ b/libs/input/PointerController.cpp
@@ -115,10 +115,14 @@
mLocked.pointerSprite.clear();
- for (size_t i = 0; i < mLocked.spots.size(); i++) {
- delete mLocked.spots.itemAt(i);
+ for (auto& it : mLocked.spotsByDisplay) {
+ const std::vector<Spot*>& spots = it.second;
+ size_t numSpots = spots.size();
+ for (size_t i = 0; i < numSpots; i++) {
+ delete spots[i];
+ }
}
- mLocked.spots.clear();
+ mLocked.spotsByDisplay.clear();
mLocked.recycledSprites.clear();
}
@@ -271,22 +275,30 @@
}
void PointerController::setSpots(const PointerCoords* spotCoords,
- const uint32_t* spotIdToIndex, BitSet32 spotIdBits) {
+ const uint32_t* spotIdToIndex, BitSet32 spotIdBits, int32_t displayId) {
#if DEBUG_POINTER_UPDATES
ALOGD("setSpots: idBits=%08x", spotIdBits.value);
for (BitSet32 idBits(spotIdBits); !idBits.isEmpty(); ) {
uint32_t id = idBits.firstMarkedBit();
idBits.clearBit(id);
const PointerCoords& c = spotCoords[spotIdToIndex[id]];
- ALOGD(" spot %d: position=(%0.3f, %0.3f), pressure=%0.3f", id,
+ ALOGD(" spot %d: position=(%0.3f, %0.3f), pressure=%0.3f, displayId=%" PRId32 ".", id,
c.getAxisValue(AMOTION_EVENT_AXIS_X),
c.getAxisValue(AMOTION_EVENT_AXIS_Y),
- c.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
+ c.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
+ displayId);
}
#endif
AutoMutex _l(mLock);
+ std::vector<Spot*> newSpots;
+ std::map<int32_t, std::vector<Spot*>>::const_iterator iter =
+ mLocked.spotsByDisplay.find(displayId);
+ if (iter != mLocked.spotsByDisplay.end()) {
+ newSpots = iter->second;
+ }
+
mSpriteController->openTransaction();
// Add or move spots for fingers that are down.
@@ -298,17 +310,17 @@
float x = c.getAxisValue(AMOTION_EVENT_AXIS_X);
float y = c.getAxisValue(AMOTION_EVENT_AXIS_Y);
- Spot* spot = getSpotLocked(id);
+ Spot* spot = getSpot(id, newSpots);
if (!spot) {
- spot = createAndAddSpotLocked(id);
+ spot = createAndAddSpotLocked(id, newSpots);
}
- spot->updateSprite(&icon, x, y);
+ spot->updateSprite(&icon, x, y, displayId);
}
// Remove spots for fingers that went up.
- for (size_t i = 0; i < mLocked.spots.size(); i++) {
- Spot* spot = mLocked.spots.itemAt(i);
+ for (size_t i = 0; i < newSpots.size(); i++) {
+ Spot* spot = newSpots[i];
if (spot->id != Spot::INVALID_ID
&& !spotIdBits.hasBit(spot->id)) {
fadeOutAndReleaseSpotLocked(spot);
@@ -316,6 +328,7 @@
}
mSpriteController->closeTransaction();
+ mLocked.spotsByDisplay[displayId] = newSpots;
}
void PointerController::clearSpots() {
@@ -539,21 +552,33 @@
}
// Animate spots that are fading out and being removed.
- for (size_t i = 0; i < mLocked.spots.size();) {
- Spot* spot = mLocked.spots.itemAt(i);
- if (spot->id == Spot::INVALID_ID) {
- spot->alpha -= float(frameDelay) / SPOT_FADE_DURATION;
- if (spot->alpha <= 0) {
- mLocked.spots.removeAt(i);
- releaseSpotLocked(spot);
- continue;
- } else {
- spot->sprite->setAlpha(spot->alpha);
- keepAnimating = true;
+ for(auto it = mLocked.spotsByDisplay.begin(); it != mLocked.spotsByDisplay.end();) {
+ std::vector<Spot*>& spots = it->second;
+ size_t numSpots = spots.size();
+ for (size_t i = 0; i < numSpots;) {
+ Spot* spot = spots[i];
+ if (spot->id == Spot::INVALID_ID) {
+ spot->alpha -= float(frameDelay) / SPOT_FADE_DURATION;
+ if (spot->alpha <= 0) {
+ spots.erase(spots.begin() + i);
+ releaseSpotLocked(spot);
+ numSpots--;
+ continue;
+ } else {
+ spot->sprite->setAlpha(spot->alpha);
+ keepAnimating = true;
+ }
}
+ ++i;
}
- ++i;
+
+ if (spots.size() == 0) {
+ it = mLocked.spotsByDisplay.erase(it);
+ } else {
+ ++it;
+ }
}
+
return keepAnimating;
}
@@ -655,47 +680,49 @@
mSpriteController->closeTransaction();
}
-PointerController::Spot* PointerController::getSpotLocked(uint32_t id) {
- for (size_t i = 0; i < mLocked.spots.size(); i++) {
- Spot* spot = mLocked.spots.itemAt(i);
+PointerController::Spot* PointerController::getSpot(uint32_t id, const std::vector<Spot*>& spots) {
+ for (size_t i = 0; i < spots.size(); i++) {
+ Spot* spot = spots[i];
if (spot->id == id) {
return spot;
}
}
- return NULL;
+
+ return nullptr;
}
-PointerController::Spot* PointerController::createAndAddSpotLocked(uint32_t id) {
+PointerController::Spot* PointerController::createAndAddSpotLocked(uint32_t id,
+ std::vector<Spot*>& spots) {
// Remove spots until we have fewer than MAX_SPOTS remaining.
- while (mLocked.spots.size() >= MAX_SPOTS) {
- Spot* spot = removeFirstFadingSpotLocked();
+ while (spots.size() >= MAX_SPOTS) {
+ Spot* spot = removeFirstFadingSpotLocked(spots);
if (!spot) {
- spot = mLocked.spots.itemAt(0);
- mLocked.spots.removeAt(0);
+ spot = spots[0];
+ spots.erase(spots.begin());
}
releaseSpotLocked(spot);
}
// Obtain a sprite from the recycled pool.
sp<Sprite> sprite;
- if (! mLocked.recycledSprites.isEmpty()) {
- sprite = mLocked.recycledSprites.top();
- mLocked.recycledSprites.pop();
+ if (! mLocked.recycledSprites.empty()) {
+ sprite = mLocked.recycledSprites.back();
+ mLocked.recycledSprites.pop_back();
} else {
sprite = mSpriteController->createSprite();
}
// Return the new spot.
Spot* spot = new Spot(id, sprite);
- mLocked.spots.push(spot);
+ spots.push_back(spot);
return spot;
}
-PointerController::Spot* PointerController::removeFirstFadingSpotLocked() {
- for (size_t i = 0; i < mLocked.spots.size(); i++) {
- Spot* spot = mLocked.spots.itemAt(i);
+PointerController::Spot* PointerController::removeFirstFadingSpotLocked(std::vector<Spot*>& spots) {
+ for (size_t i = 0; i < spots.size(); i++) {
+ Spot* spot = spots[i];
if (spot->id == Spot::INVALID_ID) {
- mLocked.spots.removeAt(i);
+ spots.erase(spots.begin() + i);
return spot;
}
}
@@ -706,7 +733,7 @@
spot->sprite->clearIcon();
if (mLocked.recycledSprites.size() < MAX_RECYCLED_SPRITES) {
- mLocked.recycledSprites.push(spot->sprite);
+ mLocked.recycledSprites.push_back(spot->sprite);
}
delete spot;
@@ -720,9 +747,13 @@
}
void PointerController::fadeOutAndReleaseAllSpotsLocked() {
- for (size_t i = 0; i < mLocked.spots.size(); i++) {
- Spot* spot = mLocked.spots.itemAt(i);
- fadeOutAndReleaseSpotLocked(spot);
+ for (auto& it : mLocked.spotsByDisplay) {
+ const std::vector<Spot*>& spots = it.second;
+ size_t numSpots = spots.size();
+ for (size_t i = 0; i < numSpots; i++) {
+ Spot* spot = spots[i];
+ fadeOutAndReleaseSpotLocked(spot);
+ }
}
}
@@ -743,12 +774,13 @@
// --- PointerController::Spot ---
-void PointerController::Spot::updateSprite(const SpriteIcon* icon, float x, float y) {
+void PointerController::Spot::updateSprite(const SpriteIcon* icon, float x, float y,
+ int32_t displayId) {
sprite->setLayer(Sprite::BASE_LAYER_SPOT + id);
sprite->setAlpha(alpha);
sprite->setTransformationMatrix(SpriteTransformationMatrix(scale, 0.0f, 0.0f, scale));
sprite->setPosition(x, y);
-
+ sprite->setDisplayId(displayId);
this->x = x;
this->y = y;
diff --git a/libs/input/PointerController.h b/libs/input/PointerController.h
index be05786..52305b8 100644
--- a/libs/input/PointerController.h
+++ b/libs/input/PointerController.h
@@ -103,7 +103,7 @@
virtual void setPresentation(Presentation presentation);
virtual void setSpots(const PointerCoords* spotCoords,
- const uint32_t* spotIdToIndex, BitSet32 spotIdBits);
+ const uint32_t* spotIdToIndex, BitSet32 spotIdBits, int32_t displayId);
virtual void clearSpots();
void updatePointerIcon(int32_t iconId);
@@ -133,7 +133,7 @@
: id(id), sprite(sprite), alpha(1.0f), scale(1.0f),
x(0.0f), y(0.0f), lastIcon(NULL) { }
- void updateSprite(const SpriteIcon* icon, float x, float y);
+ void updateSprite(const SpriteIcon* icon, float x, float y, int32_t displayId);
private:
const SpriteIcon* lastIcon;
@@ -180,8 +180,8 @@
int32_t buttonState;
- Vector<Spot*> spots;
- Vector<sp<Sprite> > recycledSprites;
+ std::map<int32_t /* displayId */, std::vector<Spot*>> spotsByDisplay;
+ std::vector<sp<Sprite> > recycledSprites;
} mLocked GUARDED_BY(mLock);
bool getBoundsLocked(float* outMinX, float* outMinY, float* outMaxX, float* outMaxY) const;
@@ -200,9 +200,9 @@
void removeInactivityTimeoutLocked();
void updatePointerLocked();
- Spot* getSpotLocked(uint32_t id);
- Spot* createAndAddSpotLocked(uint32_t id);
- Spot* removeFirstFadingSpotLocked();
+ Spot* getSpot(uint32_t id, const std::vector<Spot*>& spots);
+ Spot* createAndAddSpotLocked(uint32_t id, std::vector<Spot*>& spots);
+ Spot* removeFirstFadingSpotLocked(std::vector<Spot*>& spots);
void releaseSpotLocked(Spot* spot);
void fadeOutAndReleaseSpotLocked(Spot* spot);
void fadeOutAndReleaseAllSpotsLocked();
diff --git a/location/java/android/location/GnssMeasurement.java b/location/java/android/location/GnssMeasurement.java
index 59eff64..a545f2e 100644
--- a/location/java/android/location/GnssMeasurement.java
+++ b/location/java/android/location/GnssMeasurement.java
@@ -96,7 +96,7 @@
STATE_TOW_DECODED, STATE_MSEC_AMBIGUOUS, STATE_SYMBOL_SYNC, STATE_GLO_STRING_SYNC,
STATE_GLO_TOD_DECODED, STATE_BDS_D2_BIT_SYNC, STATE_BDS_D2_SUBFRAME_SYNC,
STATE_GAL_E1BC_CODE_LOCK, STATE_GAL_E1C_2ND_CODE_LOCK, STATE_GAL_E1B_PAGE_SYNC,
- STATE_SBAS_SYNC, STATE_TOW_KNOWN, STATE_GLO_TOD_KNOWN
+ STATE_SBAS_SYNC, STATE_TOW_KNOWN, STATE_GLO_TOD_KNOWN, STATE_2ND_CODE_LOCK
})
@Retention(RetentionPolicy.SOURCE)
public @interface State {}
@@ -144,6 +144,9 @@
*/
public static final int STATE_GLO_TOD_KNOWN = (1<<15);
+ /** This GNSS measurement's tracking state has secondary code lock. */
+ public static final int STATE_2ND_CODE_LOCK = (1 << 16);
+
/**
* All the GNSS receiver state flags, for bit masking purposes (not a sensible state for any
* individual measurement.)
@@ -517,6 +520,9 @@
if ((mState & STATE_SBAS_SYNC) != 0) {
builder.append("SbasSync|");
}
+ if ((mState & STATE_2ND_CODE_LOCK) != 0) {
+ builder.append("2ndCodeLock|");
+ }
int remainingStates = mState & ~STATE_ALL;
if (remainingStates > 0) {
@@ -531,96 +537,315 @@
/**
* Gets the received GNSS satellite time, at the measurement time, in nanoseconds.
*
- * <p>For GPS & QZSS, this is:
- * <ul>
- * <li>Received GPS Time-of-Week at the measurement time, in nanoseconds.</li>
- * <li>The value is relative to the beginning of the current GPS week.</li>
- * </ul>
+ * <p>The received satellite time is relative to the beginning of the system week for all
+ * constellations except for Glonass where it is relative to the beginning of the Glonass
+ * system day.
*
- * <p>Given the highest sync state that can be achieved, per each satellite, valid range
- * for this field can be:
- * <pre>
- * Searching : [ 0 ] : STATE_UNKNOWN
- * C/A code lock : [ 0 1ms ] : STATE_CODE_LOCK is set
- * Bit sync : [ 0 20ms ] : STATE_BIT_SYNC is set
- * Subframe sync : [ 0 6s ] : STATE_SUBFRAME_SYNC is set
- * TOW decoded : [ 0 1week ] : STATE_TOW_DECODED is set
- * TOW Known : [ 0 1week ] : STATE_TOW_KNOWN set</pre>
+ * <p>The table below indicates the valid range of the received GNSS satellite time. These
+ * ranges depend on the constellation and code being tracked and the state of the tracking
+ * algorithms given by the {@link #getState} method. The minimum value of this field is zero.
+ * The maximum value of this field is determined by looking across all of the state flags
+ * that are set, for the given constellation and code type, and finding the the maximum value
+ * in this table.
*
- * Note: TOW Known refers to the case where TOW is possibly not decoded over the air but has
+ * <p>For example, for GPS L1 C/A, if STATE_TOW_KNOWN is set, this field can be any value from 0
+ * to 1 week (in nanoseconds), and for GAL E1B code, if only STATE_GAL_E1BC_CODE_LOCK is set,
+ * then this field can be any value from 0 to 4 milliseconds (in nanoseconds.)
+ *
+ * <table border="1">
+ * <thead>
+ * <tr>
+ * <td />
+ * <td colspan="3"><strong>GPS/QZSS</strong></td>
+ * <td><strong>GLNS</strong></td>
+ * <td colspan="2"><strong>BDS</strong></td>
+ * <td colspan="3"><strong>GAL</strong></td>
+ * <td><strong>SBAS</strong></td>
+ * </tr>
+ * <tr>
+ * <td><strong>State Flag</strong></td>
+ * <td><strong>L1 C/A</strong></td>
+ * <td><strong>L5I</strong></td>
+ * <td><strong>L5Q</strong></td>
+ * <td><strong>L1OF</strong></td>
+ * <td><strong>B1I (D1)</strong></td>
+ * <td><strong>B1I (D2)</strong></td>
+ * <td><strong>E1B</strong></td>
+ * <td><strong>E1C</strong></td>
+ * <td><strong>E5AQ</strong></td>
+ * <td><strong>L1 C/A</strong></td>
+ * </tr>
+ * </thead>
+ * <tbody>
+ * <tr>
+ * <td>
+ * <strong>STATE_UNKNOWN</strong>
+ * </td>
+ * <td>0</td>
+ * <td>0</td>
+ * <td>0</td>
+ * <td>0</td>
+ * <td>0</td>
+ * <td>0</td>
+ * <td>0</td>
+ * <td>0</td>
+ * <td>0</td>
+ * <td>0</td>
+ * </tr>
+ * <tr>
+ * <td>
+ * <strong>STATE_CODE_LOCK</strong>
+ * </td>
+ * <td>1 ms</td>
+ * <td>1 ms</td>
+ * <td>1 ms</td>
+ * <td>1 ms</td>
+ * <td>1 ms</td>
+ * <td>1 ms</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>1 ms</td>
+ * <td>1 ms</td>
+ * </tr>
+ * <tr>
+ * <td>
+ * <strong>STATE_SYMBOL_SYNC</strong>
+ * </td>
+ * <td>20 ms (optional)</td>
+ * <td>10 ms</td>
+ * <td>1 ms (optional)</td>
+ * <td>10 ms</td>
+ * <td>20 ms (optional)</td>
+ * <td>2 ms</td>
+ * <td>4 ms (optional)</td>
+ * <td>4 ms (optional)</td>
+ * <td>1 ms (optional)</td>
+ * <td>2 ms</td>
+ * </tr>
+ * <tr>
+ * <td>
+ * <strong>STATE_BIT_SYNC</strong>
+ * </td>
+ * <td>20 ms</td>
+ * <td>20 ms</td>
+ * <td>1 ms (optional)</td>
+ * <td>20 ms</td>
+ * <td>20 ms</td>
+ * <td>-</td>
+ * <td>8 ms</td>
+ * <td>-</td>
+ * <td>1 ms (optional)</td>
+ * <td>4 ms</td>
+ * </tr>
+ * <tr>
+ * <td>
+ * <strong>STATE_SUBFRAME_SYNC</strong>
+ * </td>
+ * <td>6s</td>
+ * <td>6s</td>
+ * <td>-</td>
+ * <td>2 s</td>
+ * <td>6 s</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>100 ms</td>
+ * <td>-</td>
+ * </tr>
+ * <tr>
+ * <td>
+ * <strong>STATE_TOW_DECODED</strong>
+ * </td>
+ * <td colspan="2">1 week</td>
+ * <td>-</td>
+ * <td>1 day</td>
+ * <td colspan="2">1 week</td>
+ * <td colspan="2">1 week</td>
+ * <td>-</td>
+ * <td>1 week</td>
+ * </tr>
+ * <tr>
+ * <td>
+ * <strong>STATE_TOW_KNOWN</strong>
+ * </td>
+ * <td colspan="3">1 week</td>
+ * <td>1 day</td>
+ * <td colspan="2">1 week</td>
+ * <td colspan="3">1 week</td>
+ * <td>1 week</td>
+ * </tr>
+ * <tr>
+ * <td>
+ * <strong>STATE_GLO_STRING_SYNC</strong>
+ * </td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>2 s</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * </tr>
+ * <tr>
+ * <td>
+ * <strong>STATE_GLO_TOD_DECODED</strong>
+ * </td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>1 day</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * </tr>
+ * <tr>
+ * <td>
+ * <strong>STATE_GLO_TOD_KNOWN</strong>
+ * </td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>1 day</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * </tr>
+ * <tr>
+ * <td>
+ * <strong>STATE_BDS_D2_BIT_SYNC</strong>
+ * </td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>2 ms</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * </tr>
+ * <tr>
+ * <td>
+ * <strong>STATE_BDS_D2_SUBFRAME_SYNC</strong>
+ * </td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>600 ms</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * </tr>
+ * <tr>
+ * <td>
+ * <strong>STATE_GAL_E1BC_CODE_LOCK</strong>
+ * </td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>4 ms</td>
+ * <td>4 ms</td>
+ * <td>-</td>
+ * <td>-</td>
+ * </tr>
+ * <tr>
+ * <td>
+ * <strong>STATE_GAL_E1C_2ND_CODE_LOCK</strong>
+ * </td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>100 ms</td>
+ * <td>-</td>
+ * <td>-</td>
+ * </tr>
+ * <tr>
+ * <td>
+ * <strong>STATE_2ND_CODE_LOCK</strong>
+ * </td>
+ * <td>-</td>
+ * <td>10 ms (optional)</td>
+ * <td>20 ms</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>100 ms (optional)</td>
+ * <td>100 ms</td>
+ * <td>-</td>
+ * </tr>
+ * <tr>
+ * <td>
+ * <strong>STATE_GAL_E1B_PAGE_SYNC</strong>
+ * </td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>2 s</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * </tr>
+ * <tr>
+ * <td>
+ * <strong>STATE_SBAS_SYNC</strong>
+ * </td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>1 s</td>
+ * </tr>
+ * </tbody>
+ * </table>
+ *
+ * <p>Note: TOW Known refers to the case where TOW is possibly not decoded over the air but has
* been determined from other sources. If TOW decoded is set then TOW Known must also be set.
*
- * <p>Note well: if there is any ambiguity in integer millisecond, {@code STATE_MSEC_AMBIGUOUS}
- * must be set accordingly, in the 'state' field.
+ * <p>Note well: if there is any ambiguity in integer millisecond, STATE_MSEC_AMBIGUOUS must be
+ * set accordingly, in the 'state' field. This value must be populated, unless the 'state' ==
+ * STATE_UNKNOWN.
*
- * <p>This value must be populated if 'state' != {@code STATE_UNKNOWN}.
- *
- * <p>For Glonass, this is:
+ * <p>Note on optional flags:
* <ul>
- * <li>Received Glonass time of day, at the measurement time in nanoseconds.</li>
+ * <li> For L1 C/A and B1I, STATE_SYMBOL_SYNC is optional since the symbol length is the
+ * same as the bit length.
+ * <li> For L5Q and E5aQ, STATE_BIT_SYNC and STATE_SYMBOL_SYNC are optional since they are
+ * implied by STATE_CODE_LOCK.
+ * <li> STATE_2ND_CODE_LOCK for L5I is optional since it is implied by STATE_SYMBOL_SYNC.
+ * <li> STATE_2ND_CODE_LOCK for E1C is optional since it is implied by
+ * STATE_GAL_E1C_2ND_CODE_LOCK.
+ * <li> For E1B and E1C, STATE_SYMBOL_SYNC is optional, because it is implied by
+ * STATE_GAL_E1BC_CODE_LOCK.
* </ul>
- *
- * <p>Given the highest sync state that can be achieved, per each satellite, valid range for
- * this field can be:
- * <pre>
- * Searching : [ 0 ] : STATE_UNKNOWN
- * C/A code lock : [ 0 1ms ] : STATE_CODE_LOCK is set
- * Symbol sync : [ 0 10ms ] : STATE_SYMBOL_SYNC is set
- * Bit sync : [ 0 20ms ] : STATE_BIT_SYNC is set
- * String sync : [ 0 2s ] : STATE_GLO_STRING_SYNC is set
- * Time of day decoded : [ 0 1day ] : STATE_GLO_TOD_DECODED is set
- * Time of day known : [ 0 1day ] : STATE_GLO_TOD_KNOWN set</pre>
- *
- * Note: Time of day known refers to the case where it is possibly not decoded over the air but
- * has been determined from other sources. If Time of day decoded is set then Time of day known
- * must also be set.
- *
- * <p>For Beidou, this is:
- * <ul>
- * <li>Received Beidou time of week, at the measurement time in nanoseconds.</li>
- * </ul>
- *
- * <p>Given the highest sync state that can be achieved, per each satellite, valid range for
- * this field can be:
- * <pre>
- * Searching : [ 0 ] : STATE_UNKNOWN
- * C/A code lock : [ 0 1ms ] : STATE_CODE_LOCK is set
- * Bit sync (D2) : [ 0 2ms ] : STATE_BDS_D2_BIT_SYNC is set
- * Bit sync (D1) : [ 0 20ms ] : STATE_BIT_SYNC is set
- * Subframe (D2) : [ 0 0.6s ] : STATE_BDS_D2_SUBFRAME_SYNC is set
- * Subframe (D1) : [ 0 6s ] : STATE_SUBFRAME_SYNC is set
- * Time of week decoded : [ 0 1week ] : STATE_TOW_DECODED is set
- * Time of week known : [ 0 1week ] : STATE_TOW_KNOWN set</pre>
- *
- * Note: TOW Known refers to the case where TOW is possibly not decoded over the air but has
- * been determined from other sources. If TOW decoded is set then TOW Known must also be set.
- *
- * <p>For Galileo, this is:
- * <ul>
- * <li>Received Galileo time of week, at the measurement time in nanoseconds.</li>
- * </ul>
- * <pre>
- * E1BC code lock : [ 0 4ms ] : STATE_GAL_E1BC_CODE_LOCK is set
- * E1C 2nd code lock : [ 0 100ms ] : STATE_GAL_E1C_2ND_CODE_LOCK is set
- * E1B page : [ 0 2s ] : STATE_GAL_E1B_PAGE_SYNC is set
- * Time of week decoded : [ 0 1week ] : STATE_TOW_DECODED is set
- * Time of week known : [ 0 1week ] : STATE_TOW_KNOWN set</pre>
- *
- * Note: TOW Known refers to the case where TOW is possibly not decoded over the air but has
- * been determined from other sources. If TOW decoded is set then TOW Known must also be set.
- *
- * <p>For SBAS, this is:
- * <ul>
- * <li>Received SBAS time, at the measurement time in nanoseconds.</li>
- * </ul>
- *
- * <p>Given the highest sync state that can be achieved, per each satellite, valid range for
- * this field can be:
- * <pre>
- * Searching : [ 0 ] : STATE_UNKNOWN
- * C/A code lock : [ 0 1ms ] : STATE_CODE_LOCK is set
- * Symbol sync : [ 0 2ms ] : STATE_SYMBOL_SYNC is set
- * Message : [ 0 1s ] : STATE_SBAS_SYNC is set</pre>
*/
public long getReceivedSvTimeNanos() {
return mReceivedSvTimeNanos;
diff --git a/location/java/android/location/LocationRequest.java b/location/java/android/location/LocationRequest.java
index 0caa0c5..b3953fd 100644
--- a/location/java/android/location/LocationRequest.java
+++ b/location/java/android/location/LocationRequest.java
@@ -184,8 +184,7 @@
* @return a new location request
*/
public static LocationRequest create() {
- LocationRequest request = new LocationRequest();
- return request;
+ return new LocationRequest();
}
/** @hide */
@@ -230,12 +229,10 @@
quality = ACCURACY_FINE;
break;
default: {
- switch (criteria.getPowerRequirement()) {
- case Criteria.POWER_HIGH:
- quality = POWER_HIGH;
- break;
- default:
- quality = POWER_LOW;
+ if (criteria.getPowerRequirement() == Criteria.POWER_HIGH) {
+ quality = POWER_HIGH;
+ } else {
+ quality = POWER_LOW;
}
}
}
@@ -288,7 +285,7 @@
*
* @param quality an accuracy or power constant
* @return the same object, so that setters can be chained
- * @throws InvalidArgumentException if the quality constant is not valid
+ * @throws IllegalArgumentException if the quality constant is not valid
*/
public LocationRequest setQuality(int quality) {
checkQuality(quality);
@@ -331,7 +328,7 @@
*
* @param millis desired interval in millisecond, inexact
* @return the same object, so that setters can be chained
- * @throws InvalidArgumentException if the interval is less than zero
+ * @throws IllegalArgumentException if the interval is less than zero
*/
public LocationRequest setInterval(long millis) {
checkInterval(millis);
@@ -433,7 +430,7 @@
*
* @param millis fastest interval for updates in milliseconds, exact
* @return the same object, so that setters can be chained
- * @throws InvalidArgumentException if the interval is less than zero
+ * @throws IllegalArgumentException if the interval is less than zero
*/
public LocationRequest setFastestInterval(long millis) {
checkInterval(millis);
@@ -528,7 +525,7 @@
*
* @param numUpdates the number of location updates requested
* @return the same object, so that setters can be chained
- * @throws InvalidArgumentException if numUpdates is 0 or less
+ * @throws IllegalArgumentException if numUpdates is 0 or less
*/
public LocationRequest setNumUpdates(int numUpdates) {
if (numUpdates <= 0) {
@@ -668,7 +665,7 @@
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
private static void checkProvider(String name) {
if (name == null) {
- throw new IllegalArgumentException("invalid provider: " + name);
+ throw new IllegalArgumentException("invalid provider: null");
}
}
@@ -758,9 +755,11 @@
if (mNumUpdates != Integer.MAX_VALUE) {
s.append(" num=").append(mNumUpdates);
}
- s.append(" lowPowerMode=").append(mLowPowerMode);
+ if (mLowPowerMode) {
+ s.append(" lowPowerMode");
+ }
if (mLocationSettingsIgnored) {
- s.append(" ignoreSettings");
+ s.append(" locationSettingsIgnored");
}
s.append(']');
return s.toString();
diff --git a/location/java/com/android/internal/location/ProviderRequest.java b/location/java/com/android/internal/location/ProviderRequest.java
index a45c20d..af8123a 100644
--- a/location/java/com/android/internal/location/ProviderRequest.java
+++ b/location/java/com/android/internal/location/ProviderRequest.java
@@ -40,7 +40,7 @@
* restrictions or any other restricting factors and always satisfy this request to the best of
* their ability. This flag should only be used in event of an emergency.
*/
- public boolean forceLocation = false;
+ public boolean locationSettingsIgnored = false;
/**
* Whether provider shall make stronger than normal tradeoffs to substantially restrict power
@@ -70,6 +70,7 @@
request.reportLocation = in.readInt() == 1;
request.interval = in.readLong();
request.lowPowerMode = in.readBoolean();
+ request.locationSettingsIgnored = in.readBoolean();
int count = in.readInt();
for (int i = 0; i < count; i++) {
request.locationRequests.add(LocationRequest.CREATOR.createFromParcel(in));
@@ -93,6 +94,7 @@
parcel.writeInt(reportLocation ? 1 : 0);
parcel.writeLong(interval);
parcel.writeBoolean(lowPowerMode);
+ parcel.writeBoolean(locationSettingsIgnored);
parcel.writeInt(locationRequests.size());
for (LocationRequest request : locationRequests) {
request.writeToParcel(parcel, flags);
@@ -107,7 +109,12 @@
s.append("ON");
s.append(" interval=");
TimeUtils.formatDuration(interval, s);
- s.append(" lowPowerMode=" + lowPowerMode);
+ if (lowPowerMode) {
+ s.append(" lowPowerMode");
+ }
+ if (locationSettingsIgnored) {
+ s.append(" locationSettingsIgnored");
+ }
} else {
s.append("OFF");
}
diff --git a/location/lib/api/current.txt b/location/lib/api/current.txt
index 67d6496..dbb581f 100644
--- a/location/lib/api/current.txt
+++ b/location/lib/api/current.txt
@@ -31,6 +31,7 @@
method public long getInterval();
method public int getQuality();
method public float getSmallestDisplacement();
+ method public boolean isLocationSettingsIgnored();
field public static final int ACCURACY_BLOCK = 102; // 0x66
field public static final int ACCURACY_CITY = 104; // 0x68
field public static final int ACCURACY_FINE = 100; // 0x64
@@ -44,10 +45,10 @@
}
public final class ProviderRequestUnbundled {
- method public boolean getForceLocation();
method public long getInterval();
method public java.util.List<com.android.location.provider.LocationRequestUnbundled> getLocationRequests();
method public boolean getReportLocation();
+ method public boolean isLocationSettingsIgnored();
}
}
diff --git a/location/lib/java/com/android/location/provider/LocationRequestUnbundled.java b/location/lib/java/com/android/location/provider/LocationRequestUnbundled.java
index 41fd769..2511c39 100644
--- a/location/lib/java/com/android/location/provider/LocationRequestUnbundled.java
+++ b/location/lib/java/com/android/location/provider/LocationRequestUnbundled.java
@@ -121,6 +121,15 @@
return delegate.getSmallestDisplacement();
}
+ /**
+ * Returns true if location settings will be ignored in order to satisfy this request.
+ *
+ * @return true if location settings will be ignored in order to satisfy this request
+ */
+ public boolean isLocationSettingsIgnored() {
+ return delegate.isLocationSettingsIgnored();
+ }
+
@Override
public String toString() {
return delegate.toString();
diff --git a/location/lib/java/com/android/location/provider/ProviderRequestUnbundled.java b/location/lib/java/com/android/location/provider/ProviderRequestUnbundled.java
index b825b58..febbf1b 100644
--- a/location/lib/java/com/android/location/provider/ProviderRequestUnbundled.java
+++ b/location/lib/java/com/android/location/provider/ProviderRequestUnbundled.java
@@ -46,15 +46,15 @@
return mRequest.interval;
}
- public boolean getForceLocation() {
- return mRequest.forceLocation;
+ public boolean isLocationSettingsIgnored() {
+ return mRequest.locationSettingsIgnored;
}
/**
* Never null.
*/
public List<LocationRequestUnbundled> getLocationRequests() {
- List<LocationRequestUnbundled> result = new ArrayList<LocationRequestUnbundled>(
+ List<LocationRequestUnbundled> result = new ArrayList<>(
mRequest.locationRequests.size());
for (LocationRequest r : mRequest.locationRequests) {
result.add(new LocationRequestUnbundled(r));
diff --git a/media/Android.bp b/media/Android.bp
index 141d415c..86dc509 100644
--- a/media/Android.bp
+++ b/media/Android.bp
@@ -3,7 +3,6 @@
srcs: [
":updatable-media-srcs",
- ":framework-media-annotation-srcs",
],
aidl: {
@@ -28,7 +27,12 @@
installable: true,
// Make sure that the implementaion only relies on SDK or system APIs.
- sdk_version: "system_current",
+ no_framework_libs: true,
+ libs: [
+ // The order matters. android_system_* library should come later.
+ "framework_media_annotation",
+ "android_system_stubs_current",
+ ],
}
filegroup {
@@ -125,3 +129,8 @@
sdk_version: "28",
}
+java_library {
+ name: "framework_media_annotation",
+ srcs: [":framework-media-annotation-srcs"],
+ installable: false,
+}
diff --git a/media/apex/java/android/media/MediaPlayer2.java b/media/apex/java/android/media/MediaPlayer2.java
index c38a831..89a9540 100644
--- a/media/apex/java/android/media/MediaPlayer2.java
+++ b/media/apex/java/android/media/MediaPlayer2.java
@@ -45,8 +45,8 @@
import android.view.Surface;
import android.view.SurfaceHolder;
-import com.android.framework.protobuf.InvalidProtocolBufferException;
import com.android.internal.annotations.GuardedBy;
+import com.android.media.protobuf.InvalidProtocolBufferException;
import java.io.ByteArrayOutputStream;
import java.io.File;
diff --git a/media/java/android/media/IRingtonePlayer.aidl b/media/java/android/media/IRingtonePlayer.aidl
index 5f6686a..c038f36 100644
--- a/media/java/android/media/IRingtonePlayer.aidl
+++ b/media/java/android/media/IRingtonePlayer.aidl
@@ -17,6 +17,7 @@
package android.media;
import android.media.AudioAttributes;
+import android.media.VolumeShaper;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.os.UserHandle;
@@ -27,6 +28,8 @@
interface IRingtonePlayer {
/** Used for Ringtone.java playback */
oneway void play(IBinder token, in Uri uri, in AudioAttributes aa, float volume, boolean looping);
+ oneway void playWithVolumeShaping(IBinder token, in Uri uri, in AudioAttributes aa,
+ float volume, boolean looping, in @nullable VolumeShaper.Configuration volumeShaperConfig);
oneway void stop(IBinder token);
boolean isPlaying(IBinder token);
oneway void setPlaybackProperties(IBinder token, float volume, boolean looping);
diff --git a/media/java/android/media/MediaPlayer.java b/media/java/android/media/MediaPlayer.java
index fb18c3b6..e4d356b 100644
--- a/media/java/android/media/MediaPlayer.java
+++ b/media/java/android/media/MediaPlayer.java
@@ -1180,13 +1180,8 @@
}
final File file = new File(path);
- if (file.exists()) {
- FileInputStream is = new FileInputStream(file);
- FileDescriptor fd = is.getFD();
- setDataSource(fd);
- is.close();
- } else {
- throw new IOException("setDataSource failed.");
+ try (FileInputStream is = new FileInputStream(file)) {
+ setDataSource(is.getFD());
}
}
@@ -2868,15 +2863,9 @@
throw new IllegalArgumentException(msg);
}
- File file = new File(path);
- if (file.exists()) {
- FileInputStream is = new FileInputStream(file);
- FileDescriptor fd = is.getFD();
- addTimedTextSource(fd, mimeType);
- is.close();
- } else {
- // We do not support the case where the path is not a file.
- throw new IOException(path);
+ final File file = new File(path);
+ try (FileInputStream is = new FileInputStream(file)) {
+ addTimedTextSource(is.getFD(), mimeType);
}
}
diff --git a/media/java/android/media/Ringtone.java b/media/java/android/media/Ringtone.java
index 73d3d88..eb680c8 100644
--- a/media/java/android/media/Ringtone.java
+++ b/media/java/android/media/Ringtone.java
@@ -381,7 +381,8 @@
volume = mVolume;
}
try {
- mRemotePlayer.play(mRemoteToken, canonicalUri, mAudioAttributes, volume, looping);
+ mRemotePlayer.playWithVolumeShaping(mRemoteToken, canonicalUri, mAudioAttributes,
+ volume, looping, mVolumeShaperConfig);
} catch (RemoteException e) {
if (!playFallbackRingtone()) {
Log.w(TAG, "Problem playing ringtone: " + e);
diff --git a/media/java/android/media/VolumeShaper.aidl b/media/java/android/media/VolumeShaper.aidl
new file mode 100644
index 0000000..e99c13f
--- /dev/null
+++ b/media/java/android/media/VolumeShaper.aidl
@@ -0,0 +1,19 @@
+/* Copyright 2019, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+** http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+package android.media;
+
+parcelable VolumeShaper;
+parcelable VolumeShaper.Configuration;
diff --git a/media/java/android/media/session/MediaSessionProviderService.java b/media/java/android/media/session/MediaSessionProviderService.java
deleted file mode 100644
index 9a346ff..0000000
--- a/media/java/android/media/session/MediaSessionProviderService.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.media.session;
-
-import android.app.Service;
-import android.content.Intent;
-import android.os.IBinder;
-
-/**
- * Abstract class for mainline module services.
- *
- * @hide // TODO: Make it as a @SystemApi
- */
-public abstract class MediaSessionProviderService extends Service {
-
- @Override
- public IBinder onBind(Intent intent) {
- // TODO: Return IMediaSessionProviderService.Stub()
- return null;
- }
-}
diff --git a/media/jni/soundpool/SoundPool.cpp b/media/jni/soundpool/SoundPool.cpp
index e08dab4..4906695 100644
--- a/media/jni/soundpool/SoundPool.cpp
+++ b/media/jni/soundpool/SoundPool.cpp
@@ -17,8 +17,9 @@
//#define LOG_NDEBUG 0
#define LOG_TAG "SoundPool"
+#include <chrono>
#include <inttypes.h>
-
+#include <thread>
#include <utils/Log.h>
#define USE_SHARED_MEM_BUFFER
@@ -967,6 +968,12 @@
if (mState != IDLE) {
setVolume_l(0, 0);
ALOGV("stop");
+ // Since we're forcibly halting the previously playing content,
+ // we sleep here to ensure the volume is ramped down before we stop the track.
+ // Ideally the sleep time is the mixer period, or an approximation thereof
+ // (Fast vs Normal tracks are different).
+ // TODO: consider pausing instead of stop here.
+ std::this_thread::sleep_for(std::chrono::milliseconds(20));
mAudioTrack->stop();
mPrevSampleID = mSample->sampleID();
mSample.clear();
diff --git a/media/native/midi/Android.bp b/media/native/midi/Android.bp
index d069bd2..58317ed 100644
--- a/media/native/midi/Android.bp
+++ b/media/native/midi/Android.bp
@@ -16,7 +16,7 @@
name: "libamidi",
srcs: [
- "midi.cpp",
+ "amidi.cpp",
":IMidiDeviceServer.aidl",
],
@@ -48,10 +48,10 @@
from: "include",
- to: "amidi",
+ to: "",
- srcs: ["include/midi.h"],
- license: "include/NOTICE",
+ srcs: ["include/amidi/AMidi.h"],
+ license: "include/amidi/NOTICE",
}
ndk_library {
diff --git a/media/native/midi/midi.cpp b/media/native/midi/amidi.cpp
similarity index 99%
rename from media/native/midi/midi.cpp
rename to media/native/midi/amidi.cpp
index a5bdba8..1e9a194 100644
--- a/media/native/midi/midi.cpp
+++ b/media/native/midi/amidi.cpp
@@ -28,8 +28,8 @@
#include "android/media/midi/BpMidiDeviceServer.h"
#include "media/MidiDeviceInfo.h"
-#include "include/midi.h"
-#include "midi_internal.h"
+#include "include/amidi/AMidi.h"
+#include "amidi_internal.h"
using namespace android::media::midi;
diff --git a/media/native/midi/midi_internal.h b/media/native/midi/amidi_internal.h
similarity index 93%
rename from media/native/midi/midi_internal.h
rename to media/native/midi/amidi_internal.h
index cb3ecce..fce8596 100644
--- a/media/native/midi/midi_internal.h
+++ b/media/native/midi/amidi_internal.h
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-#ifndef ANDROID_MEDIA_MIDI_INTERNAL_H_
-#define ANDROID_MEDIA_MIDI_INTERNAL_H_
+#ifndef ANDROID_MEDIA_AMIDI_INTERNAL_H_
+#define ANDROID_MEDIA_AMIDI_INTERNAL_H_
#include <jni.h>
@@ -38,4 +38,4 @@
AMidiDeviceInfo deviceInfo; /* Attributes of the device. */
};
-#endif // ANDROID_MEDIA_MIDI_INTERNAL_H_
+#endif // ANDROID_MEDIA_AMIDI_INTERNAL_H_
diff --git a/media/native/midi/include/midi.h b/media/native/midi/include/amidi/AMidi.h
similarity index 79%
rename from media/native/midi/include/midi.h
rename to media/native/midi/include/amidi/AMidi.h
index 755d09f..0d60b0d 100644
--- a/media/native/midi/include/midi.h
+++ b/media/native/midi/include/amidi/AMidi.h
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-#ifndef ANDROID_MEDIA_MIDI_H_
-#define ANDROID_MEDIA_MIDI_H_
+#ifndef ANDROID_MEDIA_AMIDI_H_
+#define ANDROID_MEDIA_AMIDI_H_
#include <stdarg.h>
#include <stdint.h>
@@ -66,9 +66,9 @@
* @param outDevicePtrPtr Points to the pointer to receive the AMidiDevice
*
* @return AMEDIA_OK on success, or a negative error value:
- * @see AMEDIA_ERROR_INVALID_OBJECT {@link AMEDIA_ERROR_INVALID_OBJECT} - the midiDeviceObj
+ * @see AMEDIA_ERROR_INVALID_OBJECT - the midiDeviceObj
* is null or already connected to a native AMidiDevice
- * @see AMEDIA_ERROR_UNKNOWN {@link AMEDIA_ERROR_UNKNOWN} - an unknown error occurred.
+ * @see AMEDIA_ERROR_UNKNOWN - an unknown error occurred.
*/
media_status_t AMIDI_API AMidiDevice_fromJava(
JNIEnv *env, jobject midiDeviceObj, AMidiDevice **outDevicePtrPtr) __INTRODUCED_IN(29);
@@ -80,13 +80,10 @@
*
* @return AMEDIA_OK on success,
* or a negative error value:
- * @see AMEDIA_ERROR_INVALID_PARAMETER {@link AMEDIA_ERROR_INVALID_PARAMETER}
- * - the device parameter is NULL.
- * @see AMEDIA_ERROR_INVALID_OBJECT {@link AMEDIA_ERROR_INVALID_OBJECT}
- * - the device is not consistent with the associated Java MidiDevice.
- * @see AMEDIA_ERROR_INVALID_OBJECT {@link AMEDIA_ERROR_INVALID_OBJECT}
- * - the JNI interface initialization to the associated java MidiDevice failed.
- * @see AMEDIA_ERROR_UNKNOWN {@link AMEDIA_ERROR_UNKNOWN} - couldn't retrieve the device info.
+ * @see AMEDIA_ERROR_INVALID_PARAMETER - the device parameter is NULL.
+ * @see AMEDIA_ERROR_INVALID_OBJECT - the device is not consistent with the associated Java MidiDevice.
+ * @see AMEDIA_ERROR_INVALID_OBJECT - the JNI interface initialization to the associated java MidiDevice failed.
+ * @see AMEDIA_ERROR_UNKNOWN - couldn't retrieve the device info.
*/
media_status_t AMIDI_API AMidiDevice_release(const AMidiDevice *midiDevice) __INTRODUCED_IN(29);
@@ -100,9 +97,8 @@
* AMIDI_DEVICE_TYPE_VIRTUAL
* AMIDI_DEVICE_TYPE_BLUETOOTH
* or a negative error value:
- * @see AMEDIA_ERROR_INVALID_PARAMETER {@link AMEDIA_ERROR_INVALID_PARAMETER} - the device
- * parameter is NULL.
- * @see AMEDIA_ERROR_UNKNOWN {@link AMEDIA_ERROR_UNKNOWN} - Unknown error.
+ * @see AMEDIA_ERROR_INVALID_PARAMETER - the device parameter is NULL.
+ * @see AMEDIA_ERROR_UNKNOWN - Unknown error.
*/
int32_t AMIDI_API AMidiDevice_getType(const AMidiDevice *device) __INTRODUCED_IN(29);
@@ -113,9 +109,8 @@
*
* @return If successful, returns the number of MIDI input (sending) ports available on the
* device. If an error occurs, returns a negative value indicating the error:
- * @see AMEDIA_ERROR_INVALID_PARAMETER {@link AMEDIA_ERROR_INVALID_PARAMETER} - the device
- * parameter is NULL.
- * @see AMEDIA_ERROR_UNKNOWN {@link AMEDIA_ERROR_UNKNOWN} - couldn't retrieve the device info.
+ * @see AMEDIA_ERROR_INVALID_PARAMETER - the device parameter is NULL.
+ * @see AMEDIA_ERROR_UNKNOWN - couldn't retrieve the device info.
*/
ssize_t AMIDI_API AMidiDevice_getNumInputPorts(const AMidiDevice *device) __INTRODUCED_IN(29);
@@ -126,9 +121,8 @@
*
* @return If successful, returns the number of MIDI output (receiving) ports available on the
* device. If an error occurs, returns a negative value indicating the error:
- * @see AMEDIA_ERROR_INVALID_PARAMETER {@link AMEDIA_ERROR_INVALID_PARAMETER} - the device
- * parameter is NULL.
- * @see AMEDIA_ERROR_UNKNOWN {@link AMEDIA_ERROR_UNKNOWN}- couldn't retrieve the device info.
+ * @see AMEDIA_ERROR_INVALID_PARAMETER - the device parameter is NULL.
+ * @see AMEDIA_ERROR_UNKNOWN - couldn't retrieve the device info.
*/
ssize_t AMIDI_API AMidiDevice_getNumOutputPorts(const AMidiDevice *device) __INTRODUCED_IN(29);
@@ -146,7 +140,7 @@
* @param outOutputPortPtr Receives the native API port identifier of the opened port.
*
* @return AMEDIA_OK, or a negative error code:
- * @see AMEDIA_ERROR_UNKNOWN {@link AMEDIA_ERROR_UNKNOWN} - Unknown Error.
+ * @see AMEDIA_ERROR_UNKNOWN - Unknown Error.
*/
media_status_t AMIDI_API AMidiOutputPort_open(const AMidiDevice *device, int32_t portNumber,
AMidiOutputPort **outOutputPortPtr) __INTRODUCED_IN(29);
@@ -174,7 +168,7 @@
* (the current value of the running Java Virtual Machine's high-resolution time source,
* in nanoseconds)
* @return the number of messages received (either 0 or 1), or a negative error code:
- * @see AMEDIA_ERROR_UNKNOWN {@link AMEDIA_ERROR_UNKNOWN} - Unknown Error.
+ * @see AMEDIA_ERROR_UNKNOWN - Unknown Error.
*/
ssize_t AMIDI_API AMidiOutputPort_receive(const AMidiOutputPort *outputPort, int32_t *opcodePtr,
uint8_t *buffer, size_t maxBytes, size_t* numBytesReceivedPtr, int64_t *outTimestampPtr) __INTRODUCED_IN(29);
@@ -193,7 +187,7 @@
* @param outInputPortPtr Receives the native API port identifier of the opened port.
*
* @return AMEDIA_OK, or a negative error code:
- * @see AMEDIA_ERROR_UNKNOWN {@link AMEDIA_ERROR_UNKNOWN} - Unknown Error.
+ * @see AMEDIA_ERROR_UNKNOWN - Unknown Error.
*/
media_status_t AMIDI_API AMidiInputPort_open(const AMidiDevice *device, int32_t portNumber,
AMidiInputPort **outInputPortPtr) __INTRODUCED_IN(29);
@@ -206,8 +200,7 @@
* @param numBytes Specifies the number of bytes to write.
*
* @return The number of bytes sent, which could be less than specified or a negative error code:
- * @see AMEDIA_ERROR_INVALID_PARAMETER {@link AMEDIA_ERROR_INVALID_PARAMETER} The specified port
- * was NULL, the specified buffer was NULL.
+ * @see AMEDIA_ERROR_INVALID_PARAMETER - The specified port was NULL, the specified buffer was NULL.
*/
ssize_t AMIDI_API AMidiInputPort_send(const AMidiInputPort *inputPort, const uint8_t *buffer,
size_t numBytes) __INTRODUCED_IN(29);
@@ -221,8 +214,7 @@
* @param timestamp The CLOCK_MONOTONIC time in nanoseconds to associate with the sent data.
*
* @return The number of bytes sent, which could be less than specified or a negative error code:
- * @see AMEDIA_ERROR_INVALID_PARAMETER {@link AMEDIA_ERROR_INVALID_PARAMETER} The specified port
- * was NULL, the specified buffer was NULL.
+ * @see AMEDIA_ERROR_INVALID_PARAMETER - The specified port was NULL, the specified buffer was NULL.
*/
ssize_t AMIDI_API AMidiInputPort_sendWithTimestamp(const AMidiInputPort *inputPort,
const uint8_t *buffer, size_t numBytes, int64_t timestamp) __INTRODUCED_IN(29);
@@ -233,10 +225,9 @@
*
* @param inputPort The identifier of the port to send the flush command to.
*
- * @returns @see AMEDIA_OK {@link AMEDIA_OK} if successful, otherwise a negative error code:
- * @see AMEDIA_ERROR_INVALID_PARAMETER {@link AMEDIA_ERROR_INVALID_PARAMETER} The specified port
- * was NULL
- * @see AMEDIA_ERROR_UNSUPPORTED {@link AMEDIA_ERROR_UNSUPPORTED} The FLUSH command couldn't
+ * @returns @see AMEDIA_OK if successful, otherwise a negative error code:
+ * @see AMEDIA_ERROR_INVALID_PARAMETER - The specified port was NULL
+ * @see AMEDIA_ERROR_UNSUPPORTED - The FLUSH command couldn't
* be sent.
*/
media_status_t AMIDI_API AMidiInputPort_sendFlush(const AMidiInputPort *inputPort) __INTRODUCED_IN(29);
@@ -252,4 +243,4 @@
}
#endif
-#endif /* ANDROID_MEDIA_MIDI_H_ */
+#endif /* ANDROID_MEDIA_AMIDI_H_ */
diff --git a/media/native/midi/include/NOTICE b/media/native/midi/include/amidi/NOTICE
similarity index 100%
rename from media/native/midi/include/NOTICE
rename to media/native/midi/include/amidi/NOTICE
diff --git a/media/packages/MediaCore/Android.bp.bak b/media/packages/MediaCore/Android.bp.bak
deleted file mode 100644
index c7fd58b..0000000
--- a/media/packages/MediaCore/Android.bp.bak
+++ /dev/null
@@ -1,21 +0,0 @@
-android_app {
- name: "MediaCore",
-
- srcs: [
- "src/**/*.java",
- ],
-
- static_libs: [
- // TODO: Temporarily statically linked. Should go into "libs"
- "media1",
- ],
-
- // System app
- platform_apis: true,
-
- // Privileged app
- privileged: true,
-
- // Make sure that the implementation only relies on SDK or system APIs.
- sdk_version: "system_current",
-}
diff --git a/media/packages/MediaCore/AndroidManifest.xml b/media/packages/MediaCore/AndroidManifest.xml
deleted file mode 100644
index 4e2b274..0000000
--- a/media/packages/MediaCore/AndroidManifest.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/* //device/apps/common/AndroidManifest.xml
-**
-** Copyright 2019, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-** http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
--->
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.media" coreApp="true" android:sharedUserId="android.uid.system"
- android:sharedUserLabel="@string/android_system_label">
- <application android:process="system"
- android:persistent="true"
- android:directBootAware="true">
- <service android:name="AmlMediaSessionProviderService" android:singleUser="true">
- <intent-filter>
- <action android:name="android.media.session.MediaSessionProviderService"/>
- </intent-filter>
- </service>
- </application>
-</manifest>
diff --git a/media/packages/MediaCore/res/values/strings.xml b/media/packages/MediaCore/res/values/strings.xml
deleted file mode 100644
index 59fd635..0000000
--- a/media/packages/MediaCore/res/values/strings.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright 2019 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-
-<resources>
- <!-- Label for the Android system components when they are shown to the user. -->
- <string name="android_system_label" translatable="false">Android System</string>
-</resources>
-
diff --git a/media/packages/MediaCore/src/com/android/media/AmlMediaSessionProviderService.java b/media/packages/MediaCore/src/com/android/media/AmlMediaSessionProviderService.java
deleted file mode 100644
index 43b95ab..0000000
--- a/media/packages/MediaCore/src/com/android/media/AmlMediaSessionProviderService.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.media;
-
-import android.content.Context;
-import android.media.session.MediaSessionProviderService;
-import android.os.PowerManager;
-import android.util.Log;
-
-/**
- * System implementation of MediaSessionProviderService
- */
-public class AmlMediaSessionProviderService extends MediaSessionProviderService {
- private static final String TAG = "AmlMediaSessionProviderS";
- static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
-
- private Context mContext;
-
- public AmlMediaSessionProviderService(Context context) {
- mContext = context;
- PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
- }
-}
diff --git a/media/proto/jarjar-rules.txt b/media/proto/jarjar-rules.txt
index 7be6e73..bfb0b27 100644
--- a/media/proto/jarjar-rules.txt
+++ b/media/proto/jarjar-rules.txt
@@ -1,2 +1,2 @@
-rule com.google.protobuf.** com.android.framework.protobuf.@1
+rule com.google.protobuf.** com.android.media.protobuf.@1
diff --git a/native/android/libandroid.map.txt b/native/android/libandroid.map.txt
index 51afbc7..a3db2d6 100644
--- a/native/android/libandroid.map.txt
+++ b/native/android/libandroid.map.txt
@@ -146,6 +146,7 @@
AHardwareBuffer_getNativeHandle; # introduced=26
AHardwareBuffer_isSupported; # introduced=29
AHardwareBuffer_lock; # introduced=26
+ AHardwareBuffer_lockPlanes; # introduced=29
AHardwareBuffer_recvHandleFromUnixSocket; # introduced=26
AHardwareBuffer_release; # introduced=26
AHardwareBuffer_sendHandleToUnixSocket; # introduced=26
@@ -230,6 +231,7 @@
ASurfaceTransaction_reparent; # introduced=29
ASurfaceTransaction_setBuffer; # introduced=29
ASurfaceTransaction_setBufferAlpha; # introduced=29
+ ASurfaceTransaction_setBufferDataSpace; # introduced=29
ASurfaceTransaction_setBufferTransparency; # introduced=29
ASurfaceTransaction_setColor; # introduced=29
ASurfaceTransaction_setDamageRegion; # introduced=29
diff --git a/native/android/surface_control.cpp b/native/android/surface_control.cpp
index 7d2934b..d07052b 100644
--- a/native/android/surface_control.cpp
+++ b/native/android/surface_control.cpp
@@ -440,6 +440,20 @@
transaction->setAlpha(surfaceControl, alpha);
}
+void ASurfaceTransaction_setBufferDataSpace(ASurfaceTransaction* aSurfaceTransaction,
+ ASurfaceControl* aSurfaceControl,
+ ADataSpace aDataSpace) {
+ CHECK_NOT_NULL(aSurfaceTransaction);
+ CHECK_NOT_NULL(aSurfaceControl);
+
+ sp<SurfaceControl> surfaceControl = ASurfaceControl_to_SurfaceControl(aSurfaceControl);
+ LOG_ALWAYS_FATAL_IF(!isDataSpaceValid(surfaceControl, aDataSpace), "invalid dataspace");
+
+ Transaction* transaction = ASurfaceTransaction_to_Transaction(aSurfaceTransaction);
+
+ transaction->setDataspace(surfaceControl, static_cast<ui::Dataspace>(aDataSpace));
+}
+
void ASurfaceTransaction_setHdrMetadata_smpte2086(ASurfaceTransaction* aSurfaceTransaction,
ASurfaceControl* aSurfaceControl,
struct AHdrMetadata_smpte2086* metadata) {
diff --git a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
index 2dba1d5b..c5a951c 100644
--- a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
+++ b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
@@ -221,30 +221,6 @@
}
}
- @Override
- public void destroy() {
- mCarBatteryController.stopListening();
- mConnectedDeviceSignalController.stopListening();
- mActivityManagerWrapper.unregisterTaskStackListener(mTaskStackListener);
- mDrivingStateHelper.disconnectFromCarService();
-
- if (mNavigationBarWindow != null) {
- mWindowManager.removeViewImmediate(mNavigationBarWindow);
- mNavigationBarView = null;
- }
-
- if (mLeftNavigationBarWindow != null) {
- mWindowManager.removeViewImmediate(mLeftNavigationBarWindow);
- mLeftNavigationBarView = null;
- }
-
- if (mRightNavigationBarWindow != null) {
- mWindowManager.removeViewImmediate(mRightNavigationBarWindow);
- mRightNavigationBarView = null;
- }
- super.destroy();
- }
-
@Override
protected void makeStatusBarView() {
diff --git a/packages/DynamicAndroidInstallationService/Android.mk b/packages/DynamicAndroidInstallationService/Android.mk
new file mode 100644
index 0000000..13d96ac
--- /dev/null
+++ b/packages/DynamicAndroidInstallationService/Android.mk
@@ -0,0 +1,19 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+LOCAL_RESOURCE_DIR := $(addprefix $(LOCAL_PATH)/, res)
+
+LOCAL_USE_AAPT2 := true
+
+LOCAL_PACKAGE_NAME := DynamicAndroidInstallationService
+LOCAL_CERTIFICATE := platform
+LOCAL_PRIVILEGED_MODULE := true
+LOCAL_PRIVATE_PLATFORM_APIS := true
+
+LOCAL_PROGUARD_ENABLED := disabled
+
+
+include $(BUILD_PACKAGE)
diff --git a/packages/DynamicAndroidInstallationService/AndroidManifest.xml b/packages/DynamicAndroidInstallationService/AndroidManifest.xml
new file mode 100644
index 0000000..1c1c72c
--- /dev/null
+++ b/packages/DynamicAndroidInstallationService/AndroidManifest.xml
@@ -0,0 +1,47 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.android.dynandroid"
+ android:sharedUserId="android.uid.system">
+
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.MANAGE_DYNAMNIC_ANDROID" />
+ <uses-permission android:name="android.permission.REBOOT" />
+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
+
+ <application
+ android:allowBackup="false"
+ android:label="@string/app_name">
+
+ <service
+ android:name=".DynamicAndroidInstallationService"
+ android:enabled="true"
+ android:exported="true"
+ android:permission="android.permission.MANAGE_DYNAMNIC_ANDROID"
+ android:process=":dynandroid">
+ <intent-filter>
+ <action android:name="android.content.action.NOTIFY_IF_IN_USE" />
+ <category android:name="android.intent.category.DEFAULT" />
+ </intent-filter>
+ </service>
+
+ <activity android:name=".VerificationActivity"
+ android:exported="true"
+ android:permission="android.permission.MANAGE_DYNAMNIC_ANDROID"
+ android:theme="@android:style/Theme.Material.Light.Dialog.NoActionBar"
+ android:process=":dynandroid">
+ <intent-filter>
+ <action android:name="android.content.action.START_INSTALL" />
+ <category android:name="android.intent.category.DEFAULT" />
+ </intent-filter>
+ </activity>
+
+ <receiver
+ android:name=".BootCompletedReceiver"
+ android:enabled="true"
+ android:exported="false">
+ <intent-filter>
+ <action android:name="android.intent.action.BOOT_COMPLETED" />
+ </intent-filter>
+ </receiver>
+ </application>
+</manifest>
diff --git a/packages/DynamicAndroidInstallationService/MODULE_LICENSE_APACHE2 b/packages/DynamicAndroidInstallationService/MODULE_LICENSE_APACHE2
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/packages/DynamicAndroidInstallationService/MODULE_LICENSE_APACHE2
diff --git a/packages/DynamicAndroidInstallationService/NOTICE b/packages/DynamicAndroidInstallationService/NOTICE
new file mode 100644
index 0000000..c5b1efa
--- /dev/null
+++ b/packages/DynamicAndroidInstallationService/NOTICE
@@ -0,0 +1,190 @@
+
+ Copyright (c) 2005-2008, The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
diff --git a/packages/DynamicAndroidInstallationService/res/drawable/ic_system_update_googblue_24dp.xml b/packages/DynamicAndroidInstallationService/res/drawable/ic_system_update_googblue_24dp.xml
new file mode 100644
index 0000000..acf1567
--- /dev/null
+++ b/packages/DynamicAndroidInstallationService/res/drawable/ic_system_update_googblue_24dp.xml
@@ -0,0 +1,9 @@
+<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="M17,1.01L7,1c-1.1,0 -2,0.9 -2,2v18c0,1.1 0.9,2 2,2h10c1.1,0 2,-0.9 2,-2L19,3c0,-1.1 -0.9,-1.99 -2,-1.99zM17,19L7,19L7,5h10v14zM16,13h-3L13,8h-2v5L8,13l4,4 4,-4z"
+ android:fillColor="#4285F4"/>
+</vector>
diff --git a/packages/DynamicAndroidInstallationService/res/values/strings.xml b/packages/DynamicAndroidInstallationService/res/values/strings.xml
new file mode 100644
index 0000000..221e1d7
--- /dev/null
+++ b/packages/DynamicAndroidInstallationService/res/values/strings.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <!-- application name [CHAR LIMIT=32] -->
+ <string name="app_name">AndroidOnTap Installer</string>
+
+ <!-- notification channel name [CHAR LIMIT=32] -->
+ <string name="notification_channel_name">AndroidOnTap Installer</string>
+
+ <!-- password page title [CHAR LIMIT=32] -->
+ <string name="keyguard_title">AndroidOnTap Installer</string>
+
+ <!-- password page description [CHAR LIMIT=128] -->
+ <string name="keyguard_description">Please enter your password and continue to AndroidOnTap installation</string>
+
+ <!-- Displayed on notification: DynAndroid installation is completed [CHAR LIMIT=128] -->
+ <string name="notification_install_completed">Installation is completed, you can reboot into the new installed system now.</string>
+ <!-- Displayed on notification: DynAndroid installation is in progress [CHAR LIMIT=128] -->
+ <string name="notification_install_inprogress">Installation is in progress.</string>
+ <!-- Displayed on notification: DynAndroid installation is in progress [CHAR LIMIT=128] -->
+ <string name="notification_install_failed">Installation Failed.</string>
+ <!-- Displayed on notification: We are running in AndroidOnTap [CHAR LIMIT=128] -->
+ <string name="notification_dynandroid_in_use">We are running in AndroidOnTap.</string>
+
+ <!-- Action on notification: Cancel installation [CHAR LIMIT=16] -->
+ <string name="notification_action_cancel">Cancel</string>
+ <!-- Action on notification: Discard installation [CHAR LIMIT=16] -->
+ <string name="notification_action_discard">Discard</string>
+ <!-- Action on notification: Uninstall AndroidOnTap [CHAR LIMIT=16] -->
+ <string name="notification_action_uninstall">Uninstall</string>
+ <!-- Action on notification: Reboot to AndroidOnTap [CHAR LIMIT=16] -->
+ <string name="notification_action_reboot_to_dynandroid">Reboot</string>
+
+</resources>
diff --git a/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/BootCompletedReceiver.java b/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/BootCompletedReceiver.java
new file mode 100644
index 0000000..dd1be89
--- /dev/null
+++ b/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/BootCompletedReceiver.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.dynandroid;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.DynamicAndroidClient;
+import android.content.Intent;
+import android.os.UserHandle;
+import android.util.Log;
+
+
+/**
+ * A BoardcastReceiver waiting for ACTION_BOOT_COMPLETED and ask
+ * the service to display a notification if we are currently running
+ * in DynamicAndroid.
+ */
+public class BootCompletedReceiver extends BroadcastReceiver {
+
+ private static final String TAG = "BootCompletedReceiver";
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ String action = intent.getAction();
+
+ Log.d(TAG, "Broadcast received: " + action);
+
+ if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
+ Intent startServiceIntent = new Intent(
+ context, DynamicAndroidInstallationService.class);
+
+ startServiceIntent.setAction(DynamicAndroidClient.ACTION_NOTIFY_IF_IN_USE);
+ context.startServiceAsUser(startServiceIntent, UserHandle.SYSTEM);
+ }
+ }
+}
diff --git a/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/DynamicAndroidInstallationService.java b/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/DynamicAndroidInstallationService.java
new file mode 100644
index 0000000..7755cbc
--- /dev/null
+++ b/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/DynamicAndroidInstallationService.java
@@ -0,0 +1,483 @@
+/*
+ * 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.dynandroid;
+
+import static android.content.DynamicAndroidClient.ACTION_NOTIFY_IF_IN_USE;
+import static android.content.DynamicAndroidClient.ACTION_START_INSTALL;
+import static android.content.DynamicAndroidClient.CAUSE_ERROR_EXCEPTION;
+import static android.content.DynamicAndroidClient.CAUSE_ERROR_INVALID_URL;
+import static android.content.DynamicAndroidClient.CAUSE_ERROR_IO;
+import static android.content.DynamicAndroidClient.CAUSE_INSTALL_CANCELLED;
+import static android.content.DynamicAndroidClient.CAUSE_INSTALL_COMPLETED;
+import static android.content.DynamicAndroidClient.CAUSE_NOT_SPECIFIED;
+import static android.content.DynamicAndroidClient.STATUS_IN_PROGRESS;
+import static android.content.DynamicAndroidClient.STATUS_IN_USE;
+import static android.content.DynamicAndroidClient.STATUS_NOT_STARTED;
+import static android.content.DynamicAndroidClient.STATUS_READY;
+import static android.os.AsyncTask.Status.FINISHED;
+import static android.os.AsyncTask.Status.PENDING;
+import static android.os.AsyncTask.Status.RUNNING;
+
+import static com.android.dynandroid.InstallationAsyncTask.RESULT_ERROR_EXCEPTION;
+import static com.android.dynandroid.InstallationAsyncTask.RESULT_ERROR_INVALID_URL;
+import static com.android.dynandroid.InstallationAsyncTask.RESULT_ERROR_IO;
+import static com.android.dynandroid.InstallationAsyncTask.RESULT_OK;
+
+import android.app.Notification;
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.app.Service;
+import android.content.Context;
+import android.content.DynamicAndroidClient;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.DynamicAndroidManager;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.Message;
+import android.os.Messenger;
+import android.os.PowerManager;
+import android.os.RemoteException;
+import android.util.Log;
+
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+
+/**
+ * This class is the service in charge of DynamicAndroid installation.
+ * It also posts status to notification bar and wait for user's
+ * cancel and confirm commnands.
+ */
+public class DynamicAndroidInstallationService extends Service
+ implements InstallationAsyncTask.InstallStatusListener {
+
+ private static final String TAG = "DynAndroidInstallationService";
+
+ /*
+ * Intent actions
+ */
+ private static final String ACTION_CANCEL_INSTALL =
+ "com.android.dynandroid.ACTION_CANCEL_INSTALL";
+ private static final String ACTION_REBOOT_TO_DYN_ANDROID =
+ "com.android.dynandroid.ACTION_REBOOT_TO_DYN_ANDROID";
+ private static final String ACTION_REBOOT_TO_NORMAL =
+ "com.android.dynandroid.ACTION_REBOOT_TO_NORMAL";
+
+ /*
+ * For notification
+ */
+ private static final String NOTIFICATION_CHANNEL_ID = "com.android.dynandroid";
+ private static final int NOTIFICATION_ID = 1;
+
+ /*
+ * IPC
+ */
+ /** Keeps track of all current registered clients. */
+ ArrayList<Messenger> mClients = new ArrayList<>();
+
+ /** Handler of incoming messages from clients. */
+ final Messenger mMessenger = new Messenger(new IncomingHandler(this));
+
+ static class IncomingHandler extends Handler {
+ private final WeakReference<DynamicAndroidInstallationService> mWeakService;
+
+ IncomingHandler(DynamicAndroidInstallationService service) {
+ mWeakService = new WeakReference<>(service);
+ }
+
+ @Override
+ public void handleMessage(Message msg) {
+ DynamicAndroidInstallationService service = mWeakService.get();
+
+ if (service != null) {
+ service.handleMessage(msg);
+ }
+ }
+ }
+
+ private DynamicAndroidManager mDynAndroid;
+ private NotificationManager mNM;
+
+ private long mSystemSize;
+ private long mInstalledSize;
+ private boolean mJustCancelledByUser;
+
+ private PendingIntent mPiCancel;
+ private PendingIntent mPiRebootToDynamicAndroid;
+ private PendingIntent mPiUninstallAndReboot;
+
+ private InstallationAsyncTask mInstallTask;
+
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+
+ prepareNotification();
+
+ mDynAndroid = (DynamicAndroidManager) getSystemService(Context.DYNAMIC_ANDROID_SERVICE);
+ }
+
+ @Override
+ public void onDestroy() {
+ // Cancel the persistent notification.
+ mNM.cancel(NOTIFICATION_ID);
+ }
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ return mMessenger.getBinder();
+ }
+
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ String action = intent.getAction();
+
+ Log.d(TAG, "onStartCommand(): action=" + action);
+
+ if (ACTION_START_INSTALL.equals(action)) {
+ executeInstallCommand(intent);
+ } else if (ACTION_CANCEL_INSTALL.equals(action)) {
+ executeCancelCommand();
+ } else if (ACTION_REBOOT_TO_DYN_ANDROID.equals(action)) {
+ executeRebootToDynAndroidCommand();
+ } else if (ACTION_REBOOT_TO_NORMAL.equals(action)) {
+ executeRebootToNormalCommand();
+ } else if (ACTION_NOTIFY_IF_IN_USE.equals(action)) {
+ executeNotifyIfInUseCommand();
+ }
+
+ return Service.START_NOT_STICKY;
+ }
+
+ @Override
+ public void onProgressUpdate(long installedSize) {
+ mInstalledSize = installedSize;
+ postStatus(STATUS_IN_PROGRESS, CAUSE_NOT_SPECIFIED);
+ }
+
+ @Override
+ public void onResult(int result) {
+ if (result == RESULT_OK) {
+ postStatus(STATUS_READY, CAUSE_INSTALL_COMPLETED);
+ return;
+ }
+
+ // if it's not successful, reset the task and stop self.
+ resetTaskAndStop();
+
+ switch (result) {
+ case RESULT_ERROR_IO:
+ postStatus(STATUS_NOT_STARTED, CAUSE_ERROR_IO);
+ break;
+
+ case RESULT_ERROR_INVALID_URL:
+ postStatus(STATUS_NOT_STARTED, CAUSE_ERROR_INVALID_URL);
+ break;
+
+ case RESULT_ERROR_EXCEPTION:
+ postStatus(STATUS_NOT_STARTED, CAUSE_ERROR_EXCEPTION);
+ break;
+ }
+ }
+
+ @Override
+ public void onCancelled() {
+ resetTaskAndStop();
+ postStatus(STATUS_NOT_STARTED, CAUSE_INSTALL_CANCELLED);
+ }
+
+ private void executeInstallCommand(Intent intent) {
+ if (!verifyRequest(intent)) {
+ Log.e(TAG, "Verification failed. Did you use VerificationActivity?");
+ return;
+ }
+
+ if (mInstallTask != null) {
+ Log.e(TAG, "There is already an install task running");
+ return;
+ }
+
+ if (isInDynamicAndroid()) {
+ Log.e(TAG, "We are already running in DynamicAndroid");
+ return;
+ }
+
+ String url = intent.getStringExtra(DynamicAndroidClient.KEY_SYSTEM_URL);
+ mSystemSize = intent.getLongExtra(DynamicAndroidClient.KEY_SYSTEM_SIZE, 0);
+ long userdata = intent.getLongExtra(DynamicAndroidClient.KEY_USERDATA_SIZE, 0);
+
+ mInstallTask = new InstallationAsyncTask(url, mSystemSize, userdata, mDynAndroid, this);
+ mInstallTask.execute();
+
+ // start fore ground
+ startForeground(NOTIFICATION_ID,
+ buildNotification(STATUS_IN_PROGRESS, CAUSE_NOT_SPECIFIED));
+ }
+
+ private void executeCancelCommand() {
+ if (mInstallTask == null || mInstallTask.getStatus() == PENDING) {
+ Log.e(TAG, "Cancel command triggered, but there is no task running");
+ mNM.cancel(NOTIFICATION_ID);
+
+ return;
+ }
+
+ mJustCancelledByUser = true;
+
+ if (mInstallTask.cancel(false)) {
+ // Will cleanup and post status in onCancelled()
+ Log.d(TAG, "Cancel request filed successfully");
+ } else {
+ Log.d(TAG, "Requested cancel, completed task will be discarded");
+
+ resetTaskAndStop();
+ postStatus(STATUS_NOT_STARTED, CAUSE_INSTALL_CANCELLED);
+ }
+
+ }
+
+ private void executeRebootToDynAndroidCommand() {
+ if (mInstallTask == null || mInstallTask.getStatus() != FINISHED) {
+ Log.e(TAG, "Trying to reboot to DynamicAndroid, but there is no complete installation");
+ return;
+ }
+
+ if (!mInstallTask.commit()) {
+ // TODO: b/123673280 better UI response
+ Log.e(TAG, "Failed to commit installation because of native runtime error.");
+ mNM.cancel(NOTIFICATION_ID);
+
+ return;
+ }
+
+ PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
+
+ if (powerManager != null) {
+ powerManager.reboot("dynandroid");
+ }
+ }
+
+ private void executeRebootToNormalCommand() {
+ mDynAndroid.remove();
+
+ PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
+
+ if (powerManager != null) {
+ powerManager.reboot(null);
+ }
+ }
+
+ private void executeNotifyIfInUseCommand() {
+ if (isInDynamicAndroid()) {
+ startForeground(NOTIFICATION_ID,
+ buildNotification(STATUS_IN_USE, CAUSE_NOT_SPECIFIED));
+ }
+ }
+
+ private void resetTaskAndStop() {
+ mInstallTask = null;
+
+ stopForeground(true);
+
+ // stop self, but this service is not destroyed yet if it's still bound
+ stopSelf();
+ }
+
+ private void prepareNotification() {
+ NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
+ getString(R.string.notification_channel_name),
+ NotificationManager.IMPORTANCE_LOW);
+
+ mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
+
+ if (mNM != null) {
+ mNM.createNotificationChannel(chan);
+ }
+
+ Intent intentCancel = new Intent(this, DynamicAndroidInstallationService.class);
+ intentCancel.setAction(ACTION_CANCEL_INSTALL);
+ mPiCancel = PendingIntent.getService(this, 0, intentCancel, 0);
+
+ Intent intentRebootToDyn = new Intent(this, DynamicAndroidInstallationService.class);
+ intentRebootToDyn.setAction(ACTION_REBOOT_TO_DYN_ANDROID);
+ mPiRebootToDynamicAndroid = PendingIntent.getService(this, 0, intentRebootToDyn, 0);
+
+ Intent intentUninstallAndReboot = new Intent(this, DynamicAndroidInstallationService.class);
+ intentUninstallAndReboot.setAction(ACTION_REBOOT_TO_NORMAL);
+ mPiUninstallAndReboot = PendingIntent.getService(this, 0, intentUninstallAndReboot, 0);
+ }
+
+ private Notification buildNotification(int status, int cause) {
+ Notification.Builder builder = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
+ .setSmallIcon(R.drawable.ic_system_update_googblue_24dp)
+ .setProgress(0, 0, false);
+
+ switch (status) {
+ case STATUS_IN_PROGRESS:
+ builder.setContentText(getString(R.string.notification_install_inprogress));
+
+ int max = (int) Math.max(mSystemSize >> 20, 1);
+ int progress = (int) mInstalledSize >> 20;
+
+ builder.setProgress(max, progress, false);
+
+ builder.addAction(new Notification.Action.Builder(
+ null, getString(R.string.notification_action_cancel),
+ mPiCancel).build());
+
+ break;
+
+ case STATUS_READY:
+ builder.setContentText(getString(R.string.notification_install_completed));
+
+ builder.addAction(new Notification.Action.Builder(
+ null, getString(R.string.notification_action_reboot_to_dynandroid),
+ mPiRebootToDynamicAndroid).build());
+
+ builder.addAction(new Notification.Action.Builder(
+ null, getString(R.string.notification_action_cancel),
+ mPiCancel).build());
+
+ break;
+
+ case STATUS_IN_USE:
+ builder.setContentText(getString(R.string.notification_dynandroid_in_use));
+
+ builder.addAction(new Notification.Action.Builder(
+ null, getString(R.string.notification_action_uninstall),
+ mPiUninstallAndReboot).build());
+
+ break;
+
+ case STATUS_NOT_STARTED:
+ if (cause != CAUSE_NOT_SPECIFIED && cause != CAUSE_INSTALL_CANCELLED) {
+ builder.setContentText(getString(R.string.notification_install_failed));
+ } else {
+ // no need to notify the user if the task is not started, or cancelled.
+ }
+ break;
+
+ default:
+ throw new IllegalStateException("status is invalid");
+ }
+
+ return builder.build();
+ }
+
+ private boolean verifyRequest(Intent intent) {
+ String url = intent.getStringExtra(DynamicAndroidClient.KEY_SYSTEM_URL);
+
+ return VerificationActivity.isVerified(url);
+ }
+
+ private void postStatus(int status, int cause) {
+ Log.d(TAG, "postStatus(): statusCode=" + status + ", causeCode=" + cause);
+
+ boolean notifyOnNotificationBar = true;
+
+ if (status == STATUS_NOT_STARTED
+ && cause == CAUSE_INSTALL_CANCELLED
+ && mJustCancelledByUser) {
+ // if task is cancelled by user, do not notify them
+ notifyOnNotificationBar = false;
+ mJustCancelledByUser = false;
+ }
+
+ if (notifyOnNotificationBar) {
+ mNM.notify(NOTIFICATION_ID, buildNotification(status, cause));
+ }
+
+ for (int i = mClients.size() - 1; i >= 0; i--) {
+ try {
+ notifyOneClient(mClients.get(i), status, cause);
+ } catch (RemoteException e) {
+ mClients.remove(i);
+ }
+ }
+ }
+
+ private void notifyOneClient(Messenger client, int status, int cause) throws RemoteException {
+ Bundle bundle = new Bundle();
+
+ bundle.putLong(DynamicAndroidClient.KEY_INSTALLED_SIZE, mInstalledSize);
+
+ client.send(Message.obtain(null,
+ DynamicAndroidClient.MSG_POST_STATUS, status, cause, bundle));
+ }
+
+ private int getStatus() {
+ if (isInDynamicAndroid()) {
+ return STATUS_IN_USE;
+
+ } else if (mInstallTask == null) {
+ return STATUS_NOT_STARTED;
+
+ }
+
+ switch (mInstallTask.getStatus()) {
+ case PENDING:
+ return STATUS_NOT_STARTED;
+
+ case RUNNING:
+ return STATUS_IN_PROGRESS;
+
+ case FINISHED:
+ int result = mInstallTask.getResult();
+
+ if (result == RESULT_OK) {
+ return STATUS_READY;
+ } else {
+ throw new IllegalStateException("A failed InstallationTask is not reset");
+ }
+
+ default:
+ return STATUS_NOT_STARTED;
+ }
+ }
+
+ private boolean isInDynamicAndroid() {
+ return mDynAndroid.isInUse();
+ }
+
+ void handleMessage(Message msg) {
+ switch (msg.what) {
+ case DynamicAndroidClient.MSG_REGISTER_LISTENER:
+ try {
+ Messenger client = msg.replyTo;
+
+ int status = getStatus();
+
+ // tell just registered client my status, but do not specify cause
+ notifyOneClient(client, status, CAUSE_NOT_SPECIFIED);
+
+ mClients.add(client);
+ } catch (RemoteException e) {
+ // do nothing if we cannot send update to the client
+ e.printStackTrace();
+ }
+
+ break;
+ case DynamicAndroidClient.MSG_UNREGISTER_LISTENER:
+ mClients.remove(msg.replyTo);
+ break;
+ default:
+ // do nothing
+ }
+ }
+}
diff --git a/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/InstallationAsyncTask.java b/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/InstallationAsyncTask.java
new file mode 100644
index 0000000..3c759e9
--- /dev/null
+++ b/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/InstallationAsyncTask.java
@@ -0,0 +1,205 @@
+/*
+ * 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.dynandroid;
+
+import android.os.AsyncTask;
+import android.os.DynamicAndroidManager;
+import android.util.Log;
+import android.webkit.URLUtil;
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.Arrays;
+import java.util.Locale;
+import java.util.zip.GZIPInputStream;
+
+
+class InstallationAsyncTask extends AsyncTask<String, Long, Integer> {
+
+ private static final String TAG = "InstallationAsyncTask";
+
+ private static final int READ_BUFFER_SIZE = 1 << 19;
+
+ private class InvalidImageUrlException extends RuntimeException {
+ private InvalidImageUrlException(String message) {
+ super(message);
+ }
+ }
+
+
+ /** Not completed, including being cancelled */
+ static final int NO_RESULT = 0;
+ static final int RESULT_OK = 1;
+ static final int RESULT_ERROR_IO = 2;
+ static final int RESULT_ERROR_INVALID_URL = 3;
+ static final int RESULT_ERROR_EXCEPTION = 6;
+
+ interface InstallStatusListener {
+ void onProgressUpdate(long installedSize);
+ void onResult(int resultCode);
+ void onCancelled();
+ }
+
+ private final String mUrl;
+ private final long mSystemSize;
+ private final long mUserdataSize;
+ private final DynamicAndroidManager mDynamicAndroid;
+ private final InstallStatusListener mListener;
+ private DynamicAndroidManager.Session mInstallationSession;
+
+ private long mInstalledSize;
+ private long mReportedInstalledSize;
+ private int mResult = NO_RESULT;
+
+ private InputStream mStream;
+
+
+ InstallationAsyncTask(String url, long systemSize, long userdataSize,
+ DynamicAndroidManager dynAndroid, InstallStatusListener listener) {
+ mUrl = url;
+ mSystemSize = systemSize;
+ mUserdataSize = userdataSize;
+ mDynamicAndroid = dynAndroid;
+ mListener = listener;
+ }
+
+ @Override
+ protected void onPreExecute() {
+ mListener.onProgressUpdate(0);
+ }
+
+ @Override
+ protected Integer doInBackground(String... voids) {
+ Log.d(TAG, "Start doInBackground(), URL: " + mUrl);
+
+ try {
+ // call start in background
+ mInstallationSession = mDynamicAndroid.startInstallation(mSystemSize, mUserdataSize);
+
+ if (mInstallationSession == null) {
+ Log.e(TAG, "Failed to start installation with requested size: "
+ + (mSystemSize + mUserdataSize));
+
+ return RESULT_ERROR_IO;
+ }
+
+ initInputStream();
+
+ byte[] bytes = new byte[READ_BUFFER_SIZE];
+
+ int numBytesRead;
+ long minStepToReport = mSystemSize / 100;
+
+ Log.d(TAG, "Start installation loop");
+ while ((numBytesRead = mStream.read(bytes, 0, READ_BUFFER_SIZE)) != -1) {
+ if (isCancelled()) {
+ break;
+ }
+
+ byte[] writeBuffer = numBytesRead == READ_BUFFER_SIZE
+ ? bytes : Arrays.copyOf(bytes, numBytesRead);
+
+ if (!mInstallationSession.write(writeBuffer)) {
+ throw new IOException("Failed write() to DynamicAndroid");
+ }
+
+ mInstalledSize += numBytesRead;
+
+ if (mInstalledSize > mReportedInstalledSize + minStepToReport) {
+ publishProgress(mInstalledSize);
+ mReportedInstalledSize = mInstalledSize;
+ }
+ }
+
+ return RESULT_OK;
+
+ } catch (IOException e) {
+ e.printStackTrace();
+ return RESULT_ERROR_IO;
+
+ } catch (InvalidImageUrlException e) {
+ e.printStackTrace();
+ return RESULT_ERROR_INVALID_URL;
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ return RESULT_ERROR_EXCEPTION;
+
+ } finally {
+ close();
+ }
+ }
+
+ @Override
+ protected void onCancelled() {
+ Log.d(TAG, "onCancelled(), URL: " + mUrl);
+
+ close();
+
+ mListener.onCancelled();
+ }
+
+ @Override
+ protected void onPostExecute(Integer result) {
+ Log.d(TAG, "onPostExecute(), URL: " + mUrl + ", result: " + result);
+
+ close();
+
+ mResult = result;
+ mListener.onResult(mResult);
+ }
+
+ @Override
+ protected void onProgressUpdate(Long... values) {
+ long progress = values[0];
+ mListener.onProgressUpdate(progress);
+ }
+
+ private void initInputStream() throws IOException, InvalidImageUrlException {
+ if (URLUtil.isNetworkUrl(mUrl) || URLUtil.isFileUrl(mUrl)) {
+ mStream = new BufferedInputStream(new GZIPInputStream(new URL(mUrl).openStream()));
+ } else {
+ throw new InvalidImageUrlException(
+ String.format(Locale.US, "Unsupported file source: %s", mUrl));
+ }
+ }
+
+ private void close() {
+ try {
+ if (mStream != null) {
+ mStream.close();
+ mStream = null;
+ }
+ } catch (IOException e) {
+ // ignore
+ }
+ }
+
+ int getResult() {
+ return mResult;
+ }
+
+ boolean commit() {
+ if (mInstallationSession == null) {
+ return false;
+ }
+
+ return mInstallationSession.commit();
+ }
+}
diff --git a/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/VerificationActivity.java b/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/VerificationActivity.java
new file mode 100644
index 0000000..c18c4fe
--- /dev/null
+++ b/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/VerificationActivity.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.dynandroid;
+
+import static android.content.DynamicAndroidClient.KEY_SYSTEM_SIZE;
+import static android.content.DynamicAndroidClient.KEY_SYSTEM_URL;
+import static android.content.DynamicAndroidClient.KEY_USERDATA_SIZE;
+
+import android.app.Activity;
+import android.app.KeyguardManager;
+import android.content.Context;
+import android.content.DynamicAndroidClient;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.UserHandle;
+import android.util.Log;
+
+
+/**
+ * This Activity starts KeyguardManager and ask the user to confirm
+ * before any installation request. If the device is not protected by
+ * a password, it approves the request by default.
+ */
+public class VerificationActivity extends Activity {
+
+ private static final String TAG = "VerificationActivity";
+
+ private static final int REQUEST_CODE = 1;
+
+ // For install request verification
+ private static String sVerifiedUrl;
+
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
+
+ if (km != null) {
+ String title = getString(R.string.keyguard_title);
+ String description = getString(R.string.keyguard_description);
+ Intent intent = km.createConfirmDeviceCredentialIntent(title, description);
+
+ if (intent == null) {
+ Log.d(TAG, "This device is not protected by a password/pin");
+ startInstallationService();
+ finish();
+ } else {
+ startActivityForResult(intent, REQUEST_CODE);
+ }
+ } else {
+ finish();
+ }
+ }
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
+ startInstallationService();
+ }
+
+ finish();
+ }
+
+ private void startInstallationService() {
+ // retrieve data from calling intent
+ Intent callingIntent = getIntent();
+
+ String url = callingIntent.getStringExtra(KEY_SYSTEM_URL);
+ long systemSize = callingIntent.getLongExtra(KEY_SYSTEM_SIZE, 0);
+ long userdataSize = callingIntent.getLongExtra(KEY_USERDATA_SIZE, 0);
+
+ sVerifiedUrl = url;
+
+ // start service
+ Intent intent = new Intent(this, DynamicAndroidInstallationService.class);
+ intent.setAction(DynamicAndroidClient.ACTION_START_INSTALL);
+ intent.putExtra(KEY_SYSTEM_URL, url);
+ intent.putExtra(KEY_SYSTEM_SIZE, systemSize);
+ intent.putExtra(KEY_USERDATA_SIZE, userdataSize);
+
+ Log.d(TAG, "Starting Installation Service");
+ startServiceAsUser(intent, UserHandle.SYSTEM);
+ }
+
+ static boolean isVerified(String url) {
+ return sVerifiedUrl != null && sVerifiedUrl.equals(url);
+ }
+}
diff --git a/packages/ExtServices/src/android/ext/services/notification/Assistant.java b/packages/ExtServices/src/android/ext/services/notification/Assistant.java
index b6b229c..c5e598d 100644
--- a/packages/ExtServices/src/android/ext/services/notification/Assistant.java
+++ b/packages/ExtServices/src/android/ext/services/notification/Assistant.java
@@ -230,6 +230,10 @@
NotificationEntry entry =
new NotificationEntry(mPackageManager, sbn, channel, mSmsHelper);
SmartActionsHelper.SmartSuggestions suggestions = mSmartActionsHelper.suggest(entry);
+ if (DEBUG) {
+ Log.d(TAG, String.format("Creating Adjustment for %s, with %d actions, and %d replies.",
+ sbn.getKey(), suggestions.actions.size(), suggestions.replies.size()));
+ }
return createEnqueuedNotificationAdjustment(
entry, suggestions.actions, suggestions.replies);
}
diff --git a/packages/ExtServices/src/android/ext/services/notification/SmartActionsHelper.java b/packages/ExtServices/src/android/ext/services/notification/SmartActionsHelper.java
index 08cc39f..24fa87a 100644
--- a/packages/ExtServices/src/android/ext/services/notification/SmartActionsHelper.java
+++ b/packages/ExtServices/src/android/ext/services/notification/SmartActionsHelper.java
@@ -15,18 +15,20 @@
*/
package android.ext.services.notification;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
import android.app.Notification;
import android.app.Person;
import android.app.RemoteAction;
+import android.app.RemoteInput;
import android.content.Context;
+import android.graphics.drawable.Icon;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.Process;
import android.service.notification.NotificationAssistantService;
import android.text.TextUtils;
+import android.util.ArrayMap;
import android.util.LruCache;
+import android.util.Pair;
import android.view.textclassifier.ConversationAction;
import android.view.textclassifier.ConversationActions;
import android.view.textclassifier.TextClassificationContext;
@@ -34,6 +36,8 @@
import android.view.textclassifier.TextClassifier;
import android.view.textclassifier.TextClassifierEvent;
+import com.android.internal.util.ArrayUtils;
+
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
@@ -42,10 +46,13 @@
import java.util.Collections;
import java.util.Deque;
import java.util.List;
+import java.util.Map;
+import java.util.Objects;
import java.util.stream.Collectors;
public class SmartActionsHelper {
private static final String KEY_ACTION_TYPE = "action_type";
+ private static final String KEY_ACTION_SCORE = "action_score";
// If a notification has any of these flags set, it's inelgibile for actions being added.
private static final int FLAG_MASK_INELGIBILE_FOR_ACTIONS =
Notification.FLAG_ONGOING_EVENT
@@ -56,69 +63,136 @@
private static final List<String> HINTS =
Collections.singletonList(ConversationActions.Request.HINT_FOR_NOTIFICATION);
+ private static final ConversationActions EMPTY_CONVERSATION_ACTIONS =
+ new ConversationActions(Collections.emptyList(), null);
private Context mContext;
- @Nullable
private TextClassifier mTextClassifier;
- @NonNull
private AssistantSettings mSettings;
- private LruCache<String, String> mNotificationKeyToResultIdCache =
- new LruCache<>(MAX_RESULT_ID_TO_CACHE);
+ private LruCache<String, Session> mSessionCache = new LruCache<>(MAX_RESULT_ID_TO_CACHE);
SmartActionsHelper(Context context, AssistantSettings settings) {
mContext = context;
TextClassificationManager textClassificationManager =
mContext.getSystemService(TextClassificationManager.class);
- if (textClassificationManager != null) {
- mTextClassifier = textClassificationManager.getTextClassifier();
- }
+ mTextClassifier = textClassificationManager.getTextClassifier();
mSettings = settings;
}
- SmartSuggestions suggest(@NonNull NotificationEntry entry) {
+ SmartSuggestions suggest(NotificationEntry entry) {
// Whenever suggest() is called on a notification, its previous session is ended.
- mNotificationKeyToResultIdCache.remove(entry.getSbn().getKey());
+ mSessionCache.remove(entry.getSbn().getKey());
boolean eligibleForReplyAdjustment =
mSettings.mGenerateReplies && isEligibleForReplyAdjustment(entry);
boolean eligibleForActionAdjustment =
mSettings.mGenerateActions && isEligibleForActionAdjustment(entry);
- List<ConversationAction> conversationActions =
+ ConversationActions conversationActionsResult =
suggestConversationActions(
entry,
eligibleForReplyAdjustment,
eligibleForActionAdjustment);
- ArrayList<CharSequence> replies = conversationActions.stream()
- .map(ConversationAction::getTextReply)
- .filter(textReply -> !TextUtils.isEmpty(textReply))
- .collect(Collectors.toCollection(ArrayList::new));
+ String resultId = conversationActionsResult.getId();
+ List<ConversationAction> conversationActions =
+ conversationActionsResult.getConversationActions();
+
+ ArrayList<CharSequence> replies = new ArrayList<>();
+ Map<CharSequence, Float> repliesScore = new ArrayMap<>();
+ for (ConversationAction conversationAction : conversationActions) {
+ CharSequence textReply = conversationAction.getTextReply();
+ if (TextUtils.isEmpty(textReply)) {
+ continue;
+ }
+ replies.add(textReply);
+ repliesScore.put(textReply, conversationAction.getConfidenceScore());
+ }
ArrayList<Notification.Action> actions = conversationActions.stream()
.filter(conversationAction -> conversationAction.getAction() != null)
- .map(action -> createNotificationAction(action.getAction(), action.getType()))
+ .map(action -> createNotificationAction(
+ action.getAction(), action.getType(), action.getConfidenceScore()))
.collect(Collectors.toCollection(ArrayList::new));
+
+ // Start a new session for logging if necessary.
+ if (!TextUtils.isEmpty(resultId)
+ && !conversationActions.isEmpty()
+ && suggestionsMightBeUsedInNotification(
+ entry, !actions.isEmpty(), !replies.isEmpty())) {
+ mSessionCache.put(entry.getSbn().getKey(), new Session(resultId, repliesScore));
+ }
+
return new SmartSuggestions(replies, actions);
}
/**
+ * Returns whether the suggestion might be used in the notifications in SysUI.
+ * <p>
+ * Currently, NAS has no idea if suggestions will actually be used in the notification, and thus
+ * this function tries to make a heuristic. This function tries to optimize the precision,
+ * that means when it is unsure, it will return false. The objective is to avoid false positive,
+ * which could pollute the log and CTR as we are logging click rate of suggestions that could
+ * be never visible to users. On the other hand, it is fine to have false negative because
+ * it would be just like sampling.
+ */
+ private boolean suggestionsMightBeUsedInNotification(
+ NotificationEntry notificationEntry, boolean hasSmartAction, boolean hasSmartReply) {
+ Notification notification = notificationEntry.getNotification();
+ boolean hasAppGeneratedContextualActions = !notification.getContextualActions().isEmpty();
+
+ Pair<RemoteInput, Notification.Action> freeformRemoteInputAndAction =
+ notification.findRemoteInputActionPair(/* requiresFreeform */ true);
+ boolean hasAppGeneratedReplies = false;
+ boolean allowGeneratedReplies = false;
+ if (freeformRemoteInputAndAction != null) {
+ RemoteInput freeformRemoteInput = freeformRemoteInputAndAction.first;
+ Notification.Action actionWithFreeformRemoteInput = freeformRemoteInputAndAction.second;
+ hasAppGeneratedReplies = !ArrayUtils.isEmpty(freeformRemoteInput.getChoices());
+ allowGeneratedReplies = actionWithFreeformRemoteInput.getAllowGeneratedReplies();
+ }
+
+ if (hasAppGeneratedReplies || hasAppGeneratedContextualActions) {
+ return false;
+ }
+ return hasSmartAction && notification.getAllowSystemGeneratedContextualActions()
+ || hasSmartReply && allowGeneratedReplies;
+ }
+
+ private void reportActionsGenerated(
+ String resultId, List<ConversationAction> conversationActions) {
+ if (TextUtils.isEmpty(resultId)) {
+ return;
+ }
+ TextClassifierEvent textClassifierEvent =
+ createTextClassifierEventBuilder(
+ TextClassifierEvent.TYPE_ACTIONS_GENERATED, resultId)
+ .setEntityTypes(conversationActions.stream()
+ .map(ConversationAction::getType)
+ .toArray(String[]::new))
+ .build();
+ mTextClassifier.onTextClassifierEvent(textClassifierEvent);
+ }
+
+ /**
* Adds action adjustments based on the notification contents.
*/
- @NonNull
- private List<ConversationAction> suggestConversationActions(
- @NonNull NotificationEntry entry,
+ private ConversationActions suggestConversationActions(
+ NotificationEntry entry,
boolean includeReplies,
boolean includeActions) {
if (!includeReplies && !includeActions) {
- return Collections.emptyList();
- }
- if (mTextClassifier == null) {
- return Collections.emptyList();
+ return EMPTY_CONVERSATION_ACTIONS;
}
List<ConversationActions.Message> messages = extractMessages(entry.getNotification());
if (messages.isEmpty()) {
- return Collections.emptyList();
+ return EMPTY_CONVERSATION_ACTIONS;
+ }
+ // Do not generate smart actions if the last message is from the local user.
+ ConversationActions.Message lastMessage = messages.get(messages.size() - 1);
+ if (arePersonsEqual(
+ ConversationActions.Message.PERSON_USER_SELF, lastMessage.getAuthor())) {
+ return EMPTY_CONVERSATION_ACTIONS;
}
TextClassifier.EntityConfig.Builder typeConfigBuilder =
@@ -138,25 +212,20 @@
.setHints(HINTS)
.setTypeConfig(typeConfigBuilder.build())
.build();
-
- ConversationActions conversationActionsResult =
+ ConversationActions conversationActions =
mTextClassifier.suggestConversationActions(request);
-
- String resultId = conversationActionsResult.getId();
- if (!TextUtils.isEmpty(resultId)
- && !conversationActionsResult.getConversationActions().isEmpty()) {
- mNotificationKeyToResultIdCache.put(entry.getSbn().getKey(), resultId);
- }
- return conversationActionsResult.getConversationActions();
+ reportActionsGenerated(
+ conversationActions.getId(), conversationActions.getConversationActions());
+ return conversationActions;
}
- void onNotificationExpansionChanged(@NonNull NotificationEntry entry, boolean isUserAction,
+ void onNotificationExpansionChanged(NotificationEntry entry, boolean isUserAction,
boolean isExpanded) {
if (!isExpanded) {
return;
}
- String resultId = mNotificationKeyToResultIdCache.get(entry.getSbn().getKey());
- if (resultId == null) {
+ Session session = mSessionCache.get(entry.getSbn().getKey());
+ if (session == null) {
return;
}
// Only report if this is the first time the user sees these suggestions.
@@ -165,56 +234,50 @@
}
entry.setShowActionEventLogged();
TextClassifierEvent textClassifierEvent =
- createTextClassifierEventBuilder(TextClassifierEvent.TYPE_ACTIONS_SHOWN,
- resultId)
+ createTextClassifierEventBuilder(
+ TextClassifierEvent.TYPE_ACTIONS_SHOWN, session.resultId)
.build();
// TODO: If possible, report which replies / actions are actually seen by user.
mTextClassifier.onTextClassifierEvent(textClassifierEvent);
}
- void onNotificationDirectReplied(@NonNull String key) {
- if (mTextClassifier == null) {
- return;
- }
- String resultId = mNotificationKeyToResultIdCache.get(key);
- if (resultId == null) {
+ void onNotificationDirectReplied(String key) {
+ Session session = mSessionCache.get(key);
+ if (session == null) {
return;
}
TextClassifierEvent textClassifierEvent =
- createTextClassifierEventBuilder(TextClassifierEvent.TYPE_MANUAL_REPLY, resultId)
+ createTextClassifierEventBuilder(
+ TextClassifierEvent.TYPE_MANUAL_REPLY, session.resultId)
.build();
mTextClassifier.onTextClassifierEvent(textClassifierEvent);
}
- void onSuggestedReplySent(@NonNull String key, @NonNull CharSequence reply,
+ void onSuggestedReplySent(String key, CharSequence reply,
@NotificationAssistantService.Source int source) {
- if (mTextClassifier == null) {
- return;
- }
if (source != NotificationAssistantService.SOURCE_FROM_ASSISTANT) {
return;
}
- String resultId = mNotificationKeyToResultIdCache.get(key);
- if (resultId == null) {
+ Session session = mSessionCache.get(key);
+ if (session == null) {
return;
}
TextClassifierEvent textClassifierEvent =
- createTextClassifierEventBuilder(TextClassifierEvent.TYPE_SMART_ACTION, resultId)
+ createTextClassifierEventBuilder(
+ TextClassifierEvent.TYPE_SMART_ACTION, session.resultId)
.setEntityTypes(ConversationAction.TYPE_TEXT_REPLY)
+ .setScore(session.repliesScores.getOrDefault(reply, 0f))
.build();
mTextClassifier.onTextClassifierEvent(textClassifierEvent);
}
- void onActionClicked(@NonNull String key, @NonNull Notification.Action action,
+ void onActionClicked(String key, Notification.Action action,
@NotificationAssistantService.Source int source) {
- if (mTextClassifier == null) {
- return;
- }
if (source != NotificationAssistantService.SOURCE_FROM_ASSISTANT) {
return;
}
- String resultId = mNotificationKeyToResultIdCache.get(key);
- if (resultId == null) {
+ Session session = mSessionCache.get(key);
+ if (session == null) {
return;
}
String actionType = action.getExtras().getString(KEY_ACTION_TYPE);
@@ -222,25 +285,32 @@
return;
}
TextClassifierEvent textClassifierEvent =
- createTextClassifierEventBuilder(TextClassifierEvent.TYPE_SMART_ACTION, resultId)
+ createTextClassifierEventBuilder(
+ TextClassifierEvent.TYPE_SMART_ACTION, session.resultId)
.setEntityTypes(actionType)
.build();
mTextClassifier.onTextClassifierEvent(textClassifierEvent);
}
private Notification.Action createNotificationAction(
- RemoteAction remoteAction, String actionType) {
+ RemoteAction remoteAction, String actionType, float score) {
+ Icon icon = remoteAction.shouldShowIcon()
+ ? remoteAction.getIcon()
+ : Icon.createWithResource(mContext, com.android.internal.R.drawable.ic_action_open);
+ Bundle extras = new Bundle();
+ extras.putString(KEY_ACTION_TYPE, actionType);
+ extras.putFloat(KEY_ACTION_SCORE, score);
return new Notification.Action.Builder(
- remoteAction.getIcon(),
+ icon,
remoteAction.getTitle(),
remoteAction.getActionIntent())
.setContextual(true)
- .addExtras(Bundle.forPair(KEY_ACTION_TYPE, actionType))
+ .addExtras(extras)
.build();
}
private TextClassifierEvent.Builder createTextClassifierEventBuilder(
- int eventType, @NonNull String resultId) {
+ int eventType, String resultId) {
return new TextClassifierEvent.Builder(
TextClassifierEvent.CATEGORY_CONVERSATION_ACTIONS, eventType)
.setEventTime(System.currentTimeMillis())
@@ -258,7 +328,7 @@
* to fundamental phone functionality where any error would result in a very negative user
* experience.
*/
- private boolean isEligibleForActionAdjustment(@NonNull NotificationEntry entry) {
+ private boolean isEligibleForActionAdjustment(NotificationEntry entry) {
Notification notification = entry.getNotification();
String pkg = entry.getSbn().getPackageName();
if (!Process.myUserHandle().equals(entry.getSbn().getUser())) {
@@ -274,7 +344,7 @@
return entry.isMessaging();
}
- private boolean isEligibleForReplyAdjustment(@NonNull NotificationEntry entry) {
+ private boolean isEligibleForReplyAdjustment(NotificationEntry entry) {
if (!Process.myUserHandle().equals(entry.getSbn().getUser())) {
return false;
}
@@ -295,8 +365,7 @@
}
/** Returns the text most salient for action extraction in a notification. */
- @Nullable
- private List<ConversationActions.Message> extractMessages(@NonNull Notification notification) {
+ private List<ConversationActions.Message> extractMessages(Notification notification) {
Parcelable[] messages = notification.extras.getParcelableArray(Notification.EXTRA_MESSAGES);
if (messages == null || messages.length == 0) {
return Collections.singletonList(new ConversationActions.Message.Builder(
@@ -312,13 +381,12 @@
if (message == null) {
continue;
}
+ // As per the javadoc of Notification.addMessage, null means local user.
Person senderPerson = message.getSenderPerson();
- // Skip encoding once the sender is missing as it is important to distinguish
- // local user and remote user when generating replies.
if (senderPerson == null) {
- break;
+ senderPerson = localUser;
}
- Person author = localUser != null && localUser.equals(senderPerson)
+ Person author = localUser != null && arePersonsEqual(localUser, senderPerson)
? ConversationActions.Message.PERSON_USER_SELF : senderPerson;
extractMessages.push(new ConversationActions.Message.Builder(author)
.setText(message.getText())
@@ -333,6 +401,12 @@
return new ArrayList<>(extractMessages);
}
+ private static boolean arePersonsEqual(Person left, Person right) {
+ return Objects.equals(left.getKey(), right.getKey())
+ && Objects.equals(left.getName(), right.getName())
+ && Objects.equals(left.getUri(), right.getUri());
+ }
+
static class SmartSuggestions {
public final ArrayList<CharSequence> replies;
public final ArrayList<Notification.Action> actions;
@@ -343,4 +417,14 @@
this.actions = actions;
}
}
+
+ private static class Session {
+ public final String resultId;
+ public final Map<CharSequence, Float> repliesScores;
+
+ Session(String resultId, Map<CharSequence, Float> repliesScores) {
+ this.resultId = resultId;
+ this.repliesScores = repliesScores;
+ }
+ }
}
diff --git a/packages/ExtServices/tests/src/android/ext/services/notification/SmartActionsHelperTest.java b/packages/ExtServices/tests/src/android/ext/services/notification/SmartActionsHelperTest.java
index ebbd961..d0b6d00 100644
--- a/packages/ExtServices/tests/src/android/ext/services/notification/SmartActionsHelperTest.java
+++ b/packages/ExtServices/tests/src/android/ext/services/notification/SmartActionsHelperTest.java
@@ -19,7 +19,9 @@
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -53,8 +55,8 @@
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
+import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
-import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import java.time.Instant;
@@ -71,9 +73,12 @@
public class SmartActionsHelperTest {
private static final String NOTIFICATION_KEY = "key";
private static final String RESULT_ID = "id";
+ private static final float SCORE = 0.7f;
+ private static final CharSequence SMART_REPLY = "Home";
private static final ConversationAction REPLY_ACTION =
new ConversationAction.Builder(ConversationAction.TYPE_TEXT_REPLY)
- .setTextReply("Home")
+ .setTextReply(SMART_REPLY)
+ .setConfidenceScore(SCORE)
.build();
private static final String MESSAGE = "Where are you?";
@@ -197,8 +202,16 @@
List<ConversationActions.Message> messages =
runSuggestAndCaptureRequest().getConversation();
+
assertThat(messages).hasSize(1);
MessageSubject.assertThat(messages.get(0)).hasText(MESSAGE);
+ ArgumentCaptor<TextClassifierEvent> argumentCaptor =
+ ArgumentCaptor.forClass(TextClassifierEvent.class);
+ verify(mTextClassifier).onTextClassifierEvent(argumentCaptor.capture());
+ TextClassifierEvent textClassifierEvent = argumentCaptor.getValue();
+ assertTextClassifierEvent(textClassifierEvent, TextClassifierEvent.TYPE_ACTIONS_GENERATED);
+ assertThat(textClassifierEvent.getEntityTypes()).asList()
+ .containsExactly(ConversationAction.TYPE_TEXT_REPLY);
}
@Test
@@ -222,26 +235,63 @@
List<ConversationActions.Message> messages =
runSuggestAndCaptureRequest().getConversation();
- assertThat(messages).hasSize(3);
+ assertThat(messages).hasSize(4);
- ConversationActions.Message secondMessage = messages.get(0);
+ ConversationActions.Message firstMessage = messages.get(0);
+ MessageSubject.assertThat(firstMessage).hasText("firstMessage");
+ MessageSubject.assertThat(firstMessage)
+ .hasPerson(ConversationActions.Message.PERSON_USER_SELF);
+ MessageSubject.assertThat(firstMessage)
+ .hasReferenceTime(createZonedDateTimeFromMsUtc(1000));
+
+ ConversationActions.Message secondMessage = messages.get(1);
MessageSubject.assertThat(secondMessage).hasText("secondMessage");
MessageSubject.assertThat(secondMessage)
.hasPerson(ConversationActions.Message.PERSON_USER_SELF);
MessageSubject.assertThat(secondMessage)
.hasReferenceTime(createZonedDateTimeFromMsUtc(2000));
- ConversationActions.Message thirdMessage = messages.get(1);
+ ConversationActions.Message thirdMessage = messages.get(2);
MessageSubject.assertThat(thirdMessage).hasText("thirdMessage");
MessageSubject.assertThat(thirdMessage).hasPerson(userA);
MessageSubject.assertThat(thirdMessage)
.hasReferenceTime(createZonedDateTimeFromMsUtc(3000));
- ConversationActions.Message fourthMessage = messages.get(2);
+ ConversationActions.Message fourthMessage = messages.get(3);
MessageSubject.assertThat(fourthMessage).hasText("fourthMessage");
MessageSubject.assertThat(fourthMessage).hasPerson(userB);
MessageSubject.assertThat(fourthMessage)
.hasReferenceTime(createZonedDateTimeFromMsUtc(4000));
+
+ ArgumentCaptor<TextClassifierEvent> argumentCaptor =
+ ArgumentCaptor.forClass(TextClassifierEvent.class);
+ verify(mTextClassifier).onTextClassifierEvent(argumentCaptor.capture());
+ TextClassifierEvent textClassifierEvent = argumentCaptor.getValue();
+ assertTextClassifierEvent(textClassifierEvent, TextClassifierEvent.TYPE_ACTIONS_GENERATED);
+ assertThat(textClassifierEvent.getEntityTypes()).asList()
+ .containsExactly(ConversationAction.TYPE_TEXT_REPLY);
+ }
+
+ @Test
+ public void testSuggest_lastMessageLocalUser() {
+ Person me = new Person.Builder().setName("Me").build();
+ Person userA = new Person.Builder().setName("A").build();
+ Notification.MessagingStyle style =
+ new Notification.MessagingStyle(me)
+ .addMessage("firstMessage", 1000, userA)
+ .addMessage("secondMessage", 2000, me);
+ Notification notification =
+ mNotificationBuilder
+ .setContentText("You have two new messages")
+ .setStyle(style)
+ .setActions(createReplyAction())
+ .build();
+ when(mStatusBarNotification.getNotification()).thenReturn(notification);
+
+ mSmartActionsHelper.suggest(createNotificationEntry());
+
+ verify(mTextClassifier, never())
+ .suggestConversationActions(any(ConversationActions.Request.class));
}
@Test
@@ -270,13 +320,15 @@
mSmartActionsHelper.suggest(createNotificationEntry());
mSmartActionsHelper.onSuggestedReplySent(
- NOTIFICATION_KEY, MESSAGE, NotificationAssistantService.SOURCE_FROM_ASSISTANT);
+ NOTIFICATION_KEY, SMART_REPLY, NotificationAssistantService.SOURCE_FROM_ASSISTANT);
ArgumentCaptor<TextClassifierEvent> argumentCaptor =
ArgumentCaptor.forClass(TextClassifierEvent.class);
- verify(mTextClassifier).onTextClassifierEvent(argumentCaptor.capture());
- TextClassifierEvent textClassifierEvent = argumentCaptor.getValue();
- assertTextClassifierEvent(textClassifierEvent, TextClassifierEvent.TYPE_SMART_ACTION);
+ verify(mTextClassifier, times(2)).onTextClassifierEvent(argumentCaptor.capture());
+ List<TextClassifierEvent> events = argumentCaptor.getAllValues();
+ assertTextClassifierEvent(events.get(0), TextClassifierEvent.TYPE_ACTIONS_GENERATED);
+ assertTextClassifierEvent(events.get(1), TextClassifierEvent.TYPE_SMART_ACTION);
+ assertThat(events.get(1).getScore()).isEqualTo(SCORE);
}
@Test
@@ -288,24 +340,22 @@
mSmartActionsHelper.onSuggestedReplySent(
"something_else", MESSAGE, NotificationAssistantService.SOURCE_FROM_ASSISTANT);
- verify(mTextClassifier, never())
- .onTextClassifierEvent(Mockito.any(TextClassifierEvent.class));
+ verify(mTextClassifier, never()).onTextClassifierEvent(
+ argThat(new TextClassifierEventMatcher(TextClassifierEvent.TYPE_SMART_ACTION)));
}
@Test
public void testOnSuggestedReplySent_missingResultId() {
when(mTextClassifier.suggestConversationActions(any(ConversationActions.Request.class)))
- .thenReturn(new ConversationActions(Collections.emptyList(), null));
-
+ .thenReturn(new ConversationActions(Collections.singletonList(REPLY_ACTION), null));
Notification notification = createMessageNotification();
when(mStatusBarNotification.getNotification()).thenReturn(notification);
mSmartActionsHelper.suggest(createNotificationEntry());
mSmartActionsHelper.onSuggestedReplySent(
- "something_else", MESSAGE, NotificationAssistantService.SOURCE_FROM_ASSISTANT);
+ NOTIFICATION_KEY, SMART_REPLY, NotificationAssistantService.SOURCE_FROM_ASSISTANT);
- verify(mTextClassifier, never())
- .onTextClassifierEvent(Mockito.any(TextClassifierEvent.class));
+ verify(mTextClassifier, never()).onTextClassifierEvent(any(TextClassifierEvent.class));
}
@Test
@@ -318,9 +368,10 @@
ArgumentCaptor<TextClassifierEvent> argumentCaptor =
ArgumentCaptor.forClass(TextClassifierEvent.class);
- verify(mTextClassifier).onTextClassifierEvent(argumentCaptor.capture());
- TextClassifierEvent textClassifierEvent = argumentCaptor.getValue();
- assertTextClassifierEvent(textClassifierEvent, TextClassifierEvent.TYPE_MANUAL_REPLY);
+ verify(mTextClassifier, times(2)).onTextClassifierEvent(argumentCaptor.capture());
+ List<TextClassifierEvent> events = argumentCaptor.getAllValues();
+ assertTextClassifierEvent(events.get(0), TextClassifierEvent.TYPE_ACTIONS_GENERATED);
+ assertTextClassifierEvent(events.get(1), TextClassifierEvent.TYPE_MANUAL_REPLY);
}
@Test
@@ -333,9 +384,10 @@
ArgumentCaptor<TextClassifierEvent> argumentCaptor =
ArgumentCaptor.forClass(TextClassifierEvent.class);
- verify(mTextClassifier).onTextClassifierEvent(argumentCaptor.capture());
- TextClassifierEvent textClassifierEvent = argumentCaptor.getValue();
- assertTextClassifierEvent(textClassifierEvent, TextClassifierEvent.TYPE_ACTIONS_SHOWN);
+ verify(mTextClassifier, times(2)).onTextClassifierEvent(argumentCaptor.capture());
+ List<TextClassifierEvent> events = argumentCaptor.getAllValues();
+ assertTextClassifierEvent(events.get(0), TextClassifierEvent.TYPE_ACTIONS_GENERATED);
+ assertTextClassifierEvent(events.get(1), TextClassifierEvent.TYPE_ACTIONS_SHOWN);
}
@Test
@@ -347,7 +399,7 @@
mSmartActionsHelper.onNotificationExpansionChanged(createNotificationEntry(), false, false);
verify(mTextClassifier, never()).onTextClassifierEvent(
- Mockito.any(TextClassifierEvent.class));
+ argThat(new TextClassifierEventMatcher(TextClassifierEvent.TYPE_ACTIONS_SHOWN)));
}
@Test
@@ -360,9 +412,10 @@
ArgumentCaptor<TextClassifierEvent> argumentCaptor =
ArgumentCaptor.forClass(TextClassifierEvent.class);
- verify(mTextClassifier).onTextClassifierEvent(argumentCaptor.capture());
- TextClassifierEvent textClassifierEvent = argumentCaptor.getValue();
- assertTextClassifierEvent(textClassifierEvent, TextClassifierEvent.TYPE_ACTIONS_SHOWN);
+ verify(mTextClassifier, times(2)).onTextClassifierEvent(argumentCaptor.capture());
+ List<TextClassifierEvent> events = argumentCaptor.getAllValues();
+ assertTextClassifierEvent(events.get(0), TextClassifierEvent.TYPE_ACTIONS_GENERATED);
+ assertTextClassifierEvent(events.get(1), TextClassifierEvent.TYPE_ACTIONS_SHOWN);
}
private ZonedDateTime createZonedDateTimeFromMsUtc(long msUtc) {
@@ -461,4 +514,21 @@
return assertAbout(FACTORY).that(message);
}
}
+
+ private final class TextClassifierEventMatcher implements ArgumentMatcher<TextClassifierEvent> {
+
+ private int mType;
+
+ private TextClassifierEventMatcher(int type) {
+ mType = type;
+ }
+
+ @Override
+ public boolean matches(TextClassifierEvent textClassifierEvent) {
+ if (textClassifierEvent == null) {
+ return false;
+ }
+ return mType == textClassifierEvent.getEventType();
+ }
+ }
}
diff --git a/packages/NetworkStack/AndroidManifest.xml b/packages/NetworkStack/AndroidManifest.xml
index ac55bfa..e4d3591 100644
--- a/packages/NetworkStack/AndroidManifest.xml
+++ b/packages/NetworkStack/AndroidManifest.xml
@@ -27,8 +27,8 @@
<uses-permission android:name="android.permission.NETWORK_SETTINGS" />
<!-- Signature permission defined in NetworkStackStub -->
<uses-permission android:name="android.permission.MAINLINE_NETWORK_STACK" />
- <!-- Launch captive portal app as specific user -->
- <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
+ <!-- Send latency broadcast as current user -->
+ <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS" />
<uses-permission android:name="android.permission.NETWORK_STACK" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
diff --git a/packages/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java b/packages/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java
index 0d6d080..2e72d82 100644
--- a/packages/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java
+++ b/packages/NetworkStack/src/com/android/server/connectivity/NetworkMonitor.java
@@ -500,7 +500,7 @@
private void showProvisioningNotification(String action) {
try {
- mCallback.showProvisioningNotification(action);
+ mCallback.showProvisioningNotification(action, mContext.getPackageName());
} catch (RemoteException e) {
Log.e(TAG, "Error showing provisioning notification", e);
}
diff --git a/packages/NetworkStack/tests/src/com/android/server/connectivity/NetworkMonitorTest.java b/packages/NetworkStack/tests/src/com/android/server/connectivity/NetworkMonitorTest.java
index d11bb64..b98b0f7 100644
--- a/packages/NetworkStack/tests/src/com/android/server/connectivity/NetworkMonitorTest.java
+++ b/packages/NetworkStack/tests/src/com/android/server/connectivity/NetworkMonitorTest.java
@@ -482,7 +482,7 @@
nm.notifyNetworkConnected();
verify(mCallbacks, timeout(HANDLER_TIMEOUT_MS).times(1))
- .showProvisioningNotification(any());
+ .showProvisioningNotification(any(), any());
// Check that startCaptivePortalApp sends the expected intent.
nm.launchCaptivePortalApp();
diff --git a/packages/SettingsLib/Android.bp b/packages/SettingsLib/Android.bp
index 36ee813..caa928f 100644
--- a/packages/SettingsLib/Android.bp
+++ b/packages/SettingsLib/Android.bp
@@ -21,6 +21,7 @@
"SettingsLibActionButtonsPreference",
"SettingsLibEntityHeaderWidgets",
"SettingsLibBarChartPreference",
+ "SettingsLibProgressBar",
],
// ANDROIDMK TRANSLATION ERROR: unsupported assignment to LOCAL_SHARED_JAVA_LIBRARIES
diff --git a/packages/SettingsLib/AppPreference/res/layout/preference_app.xml b/packages/SettingsLib/AppPreference/res/layout/preference_app.xml
index 6d35550..b198f5a 100644
--- a/packages/SettingsLib/AppPreference/res/layout/preference_app.xml
+++ b/packages/SettingsLib/AppPreference/res/layout/preference_app.xml
@@ -52,7 +52,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
- android:textAppearance="@android:style/TextAppearance.Material.Subhead"
+ android:textAppearance="?android:attr/textAppearanceListItem"
android:ellipsize="marquee"
android:fadingEdge="horizontal"/>
@@ -65,7 +65,7 @@
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
- android:textAppearance="@android:style/TextAppearance.Material.Small"
+ android:textAppearance="?android:attr/textAppearanceSmall"
android:textAlignment="viewStart"
android:textColor="?android:attr/textColorSecondary"/>
@@ -73,7 +73,7 @@
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
- android:textAppearance="@android:style/TextAppearance.Material.Small"
+ android:textAppearance="?android:attr/textAppearanceSmall"
android:textAlignment="viewEnd"
android:textColor="?android:attr/textColorSecondary"
android:maxLines="1"
diff --git a/packages/SettingsLib/ProgressBar/Android.bp b/packages/SettingsLib/ProgressBar/Android.bp
new file mode 100644
index 0000000..eae21d8
--- /dev/null
+++ b/packages/SettingsLib/ProgressBar/Android.bp
@@ -0,0 +1,9 @@
+android_library {
+ name: "SettingsLibProgressBar",
+
+ srcs: ["src/**/*.java"],
+ resource_dirs: ["res"],
+
+ sdk_version: "system_current",
+ min_sdk_version: "21",
+}
\ No newline at end of file
diff --git a/packages/SettingsLib/ProgressBar/AndroidManifest.xml b/packages/SettingsLib/ProgressBar/AndroidManifest.xml
new file mode 100644
index 0000000..256b8f3
--- /dev/null
+++ b/packages/SettingsLib/ProgressBar/AndroidManifest.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ Copyright (C) 2019 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.android.settingslib.widget">
+
+ <uses-sdk android:minSdkVersion="21" />
+
+</manifest>
diff --git a/packages/SettingsLib/ProgressBar/res/drawable/progress_indeterminate_horizontal_material_trimmed.xml b/packages/SettingsLib/ProgressBar/res/drawable/progress_indeterminate_horizontal_material_trimmed.xml
new file mode 100644
index 0000000..2b7535a
--- /dev/null
+++ b/packages/SettingsLib/ProgressBar/res/drawable/progress_indeterminate_horizontal_material_trimmed.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<!-- Variant of progress_indeterminate_horizontal_material in frameworks/base/core/res, which
+ draws the whole height of the progress bar instead having blank space above and below the
+ bar. -->
+<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:drawable="@drawable/vector_drawable_progress_indeterminate_horizontal_trimmed" >
+ <target
+ android:name="rect2_grp"
+ android:animation="@*android:anim/progress_indeterminate_horizontal_rect2" />
+ <target
+ android:name="rect1_grp"
+ android:animation="@*android:anim/progress_indeterminate_horizontal_rect1" />
+</animated-vector>
\ No newline at end of file
diff --git a/packages/SettingsLib/ProgressBar/res/drawable/vector_drawable_progress_indeterminate_horizontal_trimmed.xml b/packages/SettingsLib/ProgressBar/res/drawable/vector_drawable_progress_indeterminate_horizontal_trimmed.xml
new file mode 100644
index 0000000..2f604d0
--- /dev/null
+++ b/packages/SettingsLib/ProgressBar/res/drawable/vector_drawable_progress_indeterminate_horizontal_trimmed.xml
@@ -0,0 +1,53 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<!-- Variant of vector_drawable_progress_indeterminate_horizontal in frameworks/base/core/res, which
+ draws the whole height of the progress bar instead having blank space above and below the
+ bar. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:height="10dp"
+ android:width="360dp"
+ android:viewportHeight="10"
+ android:viewportWidth="360" >
+ <group
+ android:name="progress_group"
+ android:translateX="180"
+ android:translateY="5" >
+ <path
+ android:name="background_track"
+ android:pathData="M -180.0,-5.0 l 360.0,0 l 0,10.0 l -360.0,0 Z"
+ android:fillColor="?android:attr/colorControlActivated"
+ android:fillAlpha="?android:attr/disabledAlpha"/>
+ <group
+ android:name="rect2_grp"
+ android:translateX="-197.60001"
+ android:scaleX="0.1" >
+ <path
+ android:name="rect2"
+ android:pathData="M -144.0,-5.0 l 288.0,0 l 0,10.0 l -288.0,0 Z"
+ android:fillColor="?android:attr/colorControlActivated" />
+ </group>
+ <group
+ android:name="rect1_grp"
+ android:translateX="-522.59998"
+ android:scaleX="0.1" >
+ <path
+ android:name="rect1"
+ android:pathData="M -144.0,-5.0 l 288.0,0 l 0,10.0 l -288.0,0 Z"
+ android:fillColor="?android:attr/colorControlActivated" />
+ </group>
+ </group>
+</vector>
\ No newline at end of file
diff --git a/packages/SettingsLib/ProgressBar/res/layout/progress_header.xml b/packages/SettingsLib/ProgressBar/res/layout/progress_header.xml
new file mode 100644
index 0000000..268858b
--- /dev/null
+++ b/packages/SettingsLib/ProgressBar/res/layout/progress_header.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ Copyright (C) 2015 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<FrameLayout
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="3dp">
+ <View
+ android:id="@+id/progress_bar_background"
+ style="@style/TrimmedHorizontalProgressBar"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:background="?android:attr/colorSecondary" />
+ <ProgressBar
+ android:id="@+id/progress_bar_animation"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ style="@style/TrimmedHorizontalProgressBar"
+ android:indeterminate="true" />
+</FrameLayout>
\ No newline at end of file
diff --git a/packages/SettingsLib/ProgressBar/res/values/styles.xml b/packages/SettingsLib/ProgressBar/res/values/styles.xml
new file mode 100644
index 0000000..5f57c1d
--- /dev/null
+++ b/packages/SettingsLib/ProgressBar/res/values/styles.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<resources>
+
+ <style name="TrimmedHorizontalProgressBar"
+ parent="android:Widget.Material.ProgressBar.Horizontal">
+ <item name="android:indeterminateDrawable">
+ @drawable/progress_indeterminate_horizontal_material_trimmed
+ </item>
+ <item name="android:minHeight">3dp</item>
+ <item name="android:maxHeight">3dp</item>
+ </style>
+
+</resources>
\ No newline at end of file
diff --git a/packages/SettingsLib/res/drawable/ic_system_update.xml b/packages/SettingsLib/res/drawable/ic_system_update.xml
new file mode 100644
index 0000000..3325fdd
--- /dev/null
+++ b/packages/SettingsLib/res/drawable/ic_system_update.xml
@@ -0,0 +1,25 @@
+<!--
+ Copyright (C) 2017 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24.0"
+ android:viewportHeight="24.0"
+ android:tint="?android:attr/colorControlNormal">
+ <path
+ android:fillColor="#FFFFFFFF"
+ android:pathData="M17,1.01L7,1C5.9,1 5,1.9 5,3v18c0,1.1 0.9,2 2,2h10c1.1,0 2,-0.9 2,-2V3C19,1.9 18.1,1.01 17,1.01zM17,21H7l0,-1h10V21zM17,18H7V6h10V18zM7,4V3h10v1H7zM16,12.5l-4,4l-4,-4l1.41,-1.41L11,12.67V8.5V8h2v0.5v4.17l1.59,-1.59L16,12.5z"/>
+</vector>
diff --git a/packages/SettingsLib/res/values/strings.xml b/packages/SettingsLib/res/values/strings.xml
index d644833..f5d58d8 100644
--- a/packages/SettingsLib/res/values/strings.xml
+++ b/packages/SettingsLib/res/values/strings.xml
@@ -337,6 +337,9 @@
<string name="data_usage_uninstalled_apps">Removed apps</string>
<!-- Title of data usage item that represents all uninstalled applications or removed users. [CHAR LIMIT=48] -->
<string name="data_usage_uninstalled_apps_users">Removed apps and users</string>
+ <!-- Title of data usage item that represents system updates (OTAs). [CHAR LIMIT=48] -->
+ <string name="data_usage_ota">System updates</string>
+
<!-- Tethering controls, item title to go into the tethering settings -->
<!-- Tethering controls, item title to go into the tethering settings when only USB tethering is available [CHAR LIMIT=25]-->
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java
index e28c894..ab95910 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java
@@ -167,7 +167,7 @@
// This is to ensure all the profiles are disconnected as some CK/Hs do not
// disconnect PBAP connection when HF connection is brought down
PbapServerProfile PbapProfile = mProfileManager.getPbapProfile();
- if (PbapProfile.getConnectionStatus(mDevice) == BluetoothProfile.STATE_CONNECTED)
+ if (PbapProfile != null && isConnectedProfile(PbapProfile))
{
PbapProfile.disconnect(mDevice);
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/HeadsetProfile.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/HeadsetProfile.java
index a1bf936..c1933fd 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/HeadsetProfile.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/HeadsetProfile.java
@@ -73,9 +73,8 @@
BluetoothProfile.STATE_CONNECTED);
device.refresh();
}
-
- mProfileManager.callServiceConnectedListeners();
mIsProfileReady=true;
+ mProfileManager.callServiceConnectedListeners();
}
public void onServiceDisconnected(int profile) {
diff --git a/packages/SettingsLib/src/com/android/settingslib/net/NetworkCycleDataLoader.java b/packages/SettingsLib/src/com/android/settingslib/net/NetworkCycleDataLoader.java
index 305a1ff..dd6d563 100644
--- a/packages/SettingsLib/src/com/android/settingslib/net/NetworkCycleDataLoader.java
+++ b/packages/SettingsLib/src/com/android/settingslib/net/NetworkCycleDataLoader.java
@@ -40,6 +40,7 @@
import com.android.settingslib.NetworkPolicyEditor;
import java.time.ZonedDateTime;
+import java.util.ArrayList;
import java.util.Iterator;
/**
@@ -52,6 +53,7 @@
protected final int mNetworkType;
private final NetworkPolicy mPolicy;
private final NetworkTemplate mNetworkTemplate;
+ private final ArrayList<Long> mCycles;
@VisibleForTesting
final INetworkStatsService mNetworkStatsService;
@@ -60,6 +62,7 @@
mSubId = builder.mSubId;
mNetworkType = builder.mNetworkType;
mNetworkTemplate = builder.mNetworkTemplate;
+ mCycles = builder.mCycles;
mNetworkStatsManager = (NetworkStatsManager)
builder.mContext.getSystemService(Context.NETWORK_STATS_SERVICE);
mNetworkStatsService = INetworkStatsService.Stub.asInterface(
@@ -77,7 +80,9 @@
}
public D loadInBackground() {
- if (mPolicy == null) {
+ if (mCycles != null && mCycles.size() > 1) {
+ loadDataForSpecificCycles();
+ } else if (mPolicy == null) {
loadFourWeeksData();
} else {
loadPolicyData();
@@ -132,6 +137,17 @@
}
@VisibleForTesting
+ void loadDataForSpecificCycles() {
+ long cycleEnd = mCycles.get(0);
+ final int lastCycleIndex = mCycles.size() - 1;
+ for (int i = 1; i <= lastCycleIndex; i++) {
+ final long cycleStart = mCycles.get(i);
+ recordUsage(cycleStart, cycleEnd);
+ cycleEnd = cycleStart;
+ }
+ }
+
+ @VisibleForTesting
abstract void recordUsage(long start, long end);
abstract D getCycleUsage();
@@ -157,11 +173,17 @@
return bytes;
}
+ @VisibleForTesting(otherwise = VisibleForTesting.NONE)
+ public ArrayList<Long> getCycles() {
+ return mCycles;
+ }
+
public static abstract class Builder<T extends NetworkCycleDataLoader> {
private final Context mContext;
private String mSubId;
private int mNetworkType;
private NetworkTemplate mNetworkTemplate;
+ private ArrayList<Long> mCycles;
public Builder (Context context) {
mContext = context;
@@ -178,6 +200,16 @@
return this;
}
+ /**
+ * Sets the network cycles to be used to query the usage data.
+ * @param cycles the time slots for the network cycle to be used to query the network usage.
+ * @return the builder
+ */
+ public Builder<T> setCycles(ArrayList<Long> cycles) {
+ mCycles = cycles;
+ return this;
+ }
+
public abstract T build();
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/net/UidDetailProvider.java b/packages/SettingsLib/src/com/android/settingslib/net/UidDetailProvider.java
index c14f558..e351615 100644
--- a/packages/SettingsLib/src/com/android/settingslib/net/UidDetailProvider.java
+++ b/packages/SettingsLib/src/com/android/settingslib/net/UidDetailProvider.java
@@ -28,6 +28,7 @@
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.TrafficStats;
+import android.os.Process;
import android.os.RemoteException;
import android.os.UserHandle;
import android.os.UserManager;
@@ -111,7 +112,7 @@
// handle special case labels
switch (uid) {
- case android.os.Process.SYSTEM_UID:
+ case Process.SYSTEM_UID:
detail.label = res.getString(R.string.process_kernel_label);
detail.icon = pm.getDefaultActivityIcon();
return detail;
@@ -127,6 +128,10 @@
detail.label = res.getString(Utils.getTetheringLabel(cm));
detail.icon = pm.getDefaultActivityIcon();
return detail;
+ case Process.OTA_UPDATE_UID:
+ detail.label = res.getString(R.string.data_usage_ota);
+ detail.icon = mContext.getDrawable(R.drawable.ic_system_update);
+ return detail;
}
final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
diff --git a/packages/SettingsLib/src/com/android/settingslib/utils/ThreadUtils.java b/packages/SettingsLib/src/com/android/settingslib/utils/ThreadUtils.java
index 88adcdb..5c9a06f9 100644
--- a/packages/SettingsLib/src/com/android/settingslib/utils/ThreadUtils.java
+++ b/packages/SettingsLib/src/com/android/settingslib/utils/ThreadUtils.java
@@ -20,6 +20,7 @@
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
public class ThreadUtils {
@@ -59,12 +60,14 @@
/**
* Posts runnable in background using shared background thread pool.
+ *
+ * @Return A future of the task that can be monitored for updates or cancelled.
*/
- public static void postOnBackgroundThread(Runnable runnable) {
+ public static Future postOnBackgroundThread(Runnable runnable) {
if (sSingleThreadExecutor == null) {
sSingleThreadExecutor = Executors.newSingleThreadExecutor();
}
- sSingleThreadExecutor.execute(runnable);
+ return sSingleThreadExecutor.submit(runnable);
}
/**
diff --git a/packages/SettingsLib/src/com/android/settingslib/wifi/WifiTracker.java b/packages/SettingsLib/src/com/android/settingslib/wifi/WifiTracker.java
index b9a5f23..8ea0f4b 100644
--- a/packages/SettingsLib/src/com/android/settingslib/wifi/WifiTracker.java
+++ b/packages/SettingsLib/src/com/android/settingslib/wifi/WifiTracker.java
@@ -53,6 +53,7 @@
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
+import com.android.internal.util.CollectionUtils;
import com.android.settingslib.R;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.core.lifecycle.LifecycleObserver;
@@ -566,9 +567,6 @@
AccessPoint accessPoint =
getCachedOrCreate(entry.getValue(), cachedAccessPoints);
- if (mLastInfo != null && mLastNetworkInfo != null) {
- accessPoint.update(connectionConfig, mLastInfo, mLastNetworkInfo);
- }
// Update the matching config if there is one, to populate saved network info
accessPoint.update(configsByKey.get(entry.getKey()));
@@ -578,68 +576,20 @@
List<ScanResult> cachedScanResults = new ArrayList<>(mScanResultCache.values());
- // Add a unique Passpoint R1 AccessPoint for each Passpoint profile's FQDN.
- List<Pair<WifiConfiguration, Map<Integer, List<ScanResult>>>> passpointConfigsAndScans =
- mWifiManager.getAllMatchingWifiConfigs(cachedScanResults);
- Set<String> seenFQDNs = new ArraySet<>();
- for (Pair<WifiConfiguration,
- Map<Integer, List<ScanResult>>> pairing : passpointConfigsAndScans) {
- WifiConfiguration config = pairing.first;
+ // Add a unique Passpoint AccessPoint for each Passpoint profile's FQDN.
+ accessPoints.addAll(updatePasspointAccessPoints(
+ mWifiManager.getAllMatchingWifiConfigs(cachedScanResults), cachedAccessPoints));
- List<ScanResult> scanResults = new ArrayList<>();
+ // Add OSU Provider AccessPoints
+ accessPoints.addAll(updateOsuAccessPoints(
+ mWifiManager.getMatchingOsuProviders(cachedScanResults), cachedAccessPoints));
- List<ScanResult> homeScans =
- pairing.second.get(WifiManager.PASSPOINT_HOME_NETWORK);
- List<ScanResult> roamingScans =
- pairing.second.get(WifiManager.PASSPOINT_ROAMING_NETWORK);
-
- if (homeScans == null) {
- homeScans = new ArrayList<>();
- }
- if (roamingScans == null) {
- roamingScans = new ArrayList<>();
- }
-
- // TODO(b/118705403): Differentiate home network vs roaming network for summary info
- if (!homeScans.isEmpty()) {
- scanResults.addAll(homeScans);
- } else {
- scanResults.addAll(roamingScans);
- }
-
- if (seenFQDNs.add(config.FQDN)) {
- int bestRssi = Integer.MIN_VALUE;
- for (ScanResult result : scanResults) {
- if (result.level >= bestRssi) {
- bestRssi = result.level;
- config.SSID = AccessPoint.convertToQuotedString(result.SSID);
- }
- }
-
- AccessPoint accessPoint =
- getCachedOrCreatePasspoint(scanResults, cachedAccessPoints, config);
- accessPoint.update(connectionConfig, mLastInfo, mLastNetworkInfo);
- accessPoints.add(accessPoint);
+ if (mLastInfo != null && mLastNetworkInfo != null) {
+ for (AccessPoint ap : accessPoints) {
+ ap.update(connectionConfig, mLastInfo, mLastNetworkInfo);
}
}
- // Add Passpoint OSU Provider AccessPoints
- Map<OsuProvider, List<ScanResult>> providersAndScans =
- mWifiManager.getMatchingOsuProviders(cachedScanResults);
- Set<OsuProvider> alreadyProvisioned = mWifiManager
- .getMatchingPasspointConfigsForOsuProviders(
- providersAndScans.keySet()).keySet();
- for (OsuProvider provider : providersAndScans.keySet()) {
- if (!alreadyProvisioned.contains(provider)) {
- AccessPoint accessPointOsu =
- getCachedOrCreateOsu(providersAndScans.get(provider),
- cachedAccessPoints, provider);
- accessPointOsu.update(connectionConfig, mLastInfo, mLastNetworkInfo);
- accessPoints.add(accessPointOsu);
- }
- }
-
-
// If there were no scan results, create an AP for the currently connected network (if
// it exists).
if (accessPoints.isEmpty() && connectionConfig != null) {
@@ -686,7 +636,67 @@
}
@VisibleForTesting
- AccessPoint getCachedOrCreate(
+ List<AccessPoint> updatePasspointAccessPoints(
+ List<Pair<WifiConfiguration, Map<Integer, List<ScanResult>>>> passpointConfigsAndScans,
+ List<AccessPoint> accessPointCache) {
+ List<AccessPoint> accessPoints = new ArrayList<>();
+
+ Set<String> seenFQDNs = new ArraySet<>();
+ for (Pair<WifiConfiguration,
+ Map<Integer, List<ScanResult>>> pairing : passpointConfigsAndScans) {
+ WifiConfiguration config = pairing.first;
+ if (seenFQDNs.add(config.FQDN)) {
+ List<ScanResult> apScanResults = new ArrayList<>();
+
+ List<ScanResult> homeScans =
+ pairing.second.get(WifiManager.PASSPOINT_HOME_NETWORK);
+ List<ScanResult> roamingScans =
+ pairing.second.get(WifiManager.PASSPOINT_ROAMING_NETWORK);
+
+ // TODO(b/118705403): Differentiate home network vs roaming network for summary info
+ if (!CollectionUtils.isEmpty(homeScans)) {
+ apScanResults.addAll(homeScans);
+ } else if (!CollectionUtils.isEmpty(roamingScans)) {
+ apScanResults.addAll(roamingScans);
+ }
+
+ int bestRssi = Integer.MIN_VALUE;
+ for (ScanResult result : apScanResults) {
+ if (result.level >= bestRssi) {
+ bestRssi = result.level;
+ config.SSID = AccessPoint.convertToQuotedString(result.SSID);
+ }
+ }
+
+ AccessPoint accessPoint =
+ getCachedOrCreatePasspoint(apScanResults, accessPointCache, config);
+ accessPoints.add(accessPoint);
+ }
+ }
+ return accessPoints;
+ }
+
+ @VisibleForTesting
+ List<AccessPoint> updateOsuAccessPoints(
+ Map<OsuProvider, List<ScanResult>> providersAndScans,
+ List<AccessPoint> accessPointCache) {
+ List<AccessPoint> accessPoints = new ArrayList<>();
+
+ Set<OsuProvider> alreadyProvisioned = mWifiManager
+ .getMatchingPasspointConfigsForOsuProviders(
+ providersAndScans.keySet()).keySet();
+ for (OsuProvider provider : providersAndScans.keySet()) {
+ if (!alreadyProvisioned.contains(provider)) {
+ AccessPoint accessPointOsu =
+ getCachedOrCreateOsu(providersAndScans.get(provider),
+ accessPointCache, provider);
+ accessPoints.add(accessPointOsu);
+ }
+ }
+ return accessPoints;
+ }
+
+ private AccessPoint getCachedOrCreate(
List<ScanResult> scanResults,
List<AccessPoint> cache) {
AccessPoint accessPoint = getCachedByKey(cache, AccessPoint.getKey(scanResults.get(0)));
diff --git a/packages/SettingsLib/tests/integ/src/com/android/settingslib/wifi/WifiTrackerTest.java b/packages/SettingsLib/tests/integ/src/com/android/settingslib/wifi/WifiTrackerTest.java
index 42eb0b9..7d22788 100644
--- a/packages/SettingsLib/tests/integ/src/com/android/settingslib/wifi/WifiTrackerTest.java
+++ b/packages/SettingsLib/tests/integ/src/com/android/settingslib/wifi/WifiTrackerTest.java
@@ -27,6 +27,7 @@
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -48,11 +49,15 @@
import android.net.wifi.WifiManager;
import android.net.wifi.WifiNetworkScoreCache;
import android.net.wifi.WifiSsid;
+import android.net.wifi.hotspot2.OsuProvider;
+import android.net.wifi.hotspot2.PasspointConfiguration;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.SystemClock;
import android.provider.Settings;
+import android.util.ArraySet;
+import android.util.Pair;
import androidx.test.InstrumentationRegistry;
import androidx.test.filters.SmallTest;
@@ -74,7 +79,10 @@
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
+import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -94,6 +102,8 @@
private static final int RSSI_1 = -30;
private static final byte SCORE_1 = 10;
private static final int BADGE_1 = AccessPoint.Speed.MODERATE;
+ private static final String FQDN_1 = "fqdn1";
+ private static final String PROVIDER_FRIENDLY_NAME_1 = "providerFriendlyName1";
private static final String SSID_2 = "ssid2";
private static final String BSSID_2 = "AA:AA:AA:AA:AA:AA";
@@ -102,6 +112,8 @@
private static final int RSSI_2 = -30;
private static final byte SCORE_2 = 15;
private static final int BADGE_2 = AccessPoint.Speed.FAST;
+ private static final String FQDN_2 = "fqdn2";
+ private static final String PROVIDER_FRIENDLY_NAME_2 = "providerFriendlyName2";
private static final String SSID_3 = "ssid3";
private static final String BSSID_3 = "CC:00:00:00:00:00";
@@ -271,6 +283,61 @@
0 /* microsecond timestamp */);
}
+ private static WifiConfiguration buildPasspointConfiguration(String fqdn, String friendlyName) {
+ WifiConfiguration config = spy(new WifiConfiguration());
+ config.FQDN = fqdn;
+ config.providerFriendlyName = friendlyName;
+ when(config.isPasspoint()).thenReturn(true);
+ return config;
+ }
+
+ private List<Pair<WifiConfiguration, Map<Integer, List<ScanResult>>>>
+ createPasspointMatchingWifiConfigsWithDuplicates() {
+ List<Pair<WifiConfiguration, Map<Integer, List<ScanResult>>>> matchingList =
+ new ArrayList<>();
+ Map<Integer, List<ScanResult>> mapping = new HashMap<>();
+
+ mapping.put(WifiManager.PASSPOINT_HOME_NETWORK, Arrays.asList(buildScanResult1()));
+
+ WifiConfiguration passpointConfig1 =
+ buildPasspointConfiguration(FQDN_1, PROVIDER_FRIENDLY_NAME_1);
+ WifiConfiguration passpointConfig2 =
+ buildPasspointConfiguration(FQDN_2, PROVIDER_FRIENDLY_NAME_2);
+
+ matchingList.add(new Pair(passpointConfig1, mapping));
+ matchingList.add(new Pair(passpointConfig1, mapping));
+ matchingList.add(new Pair(passpointConfig2, mapping));
+ matchingList.add(new Pair(passpointConfig2, mapping));
+
+ return matchingList;
+ }
+
+ private List<Pair<WifiConfiguration, Map<Integer, List<ScanResult>>>>
+ createPasspointMatchingWifiConfigWithScanResults(
+ List<ScanResult> homeList, List<ScanResult> roamingList) {
+ List<Pair<WifiConfiguration, Map<Integer, List<ScanResult>>>> matchingList =
+ new ArrayList<>();
+ Map<Integer, List<ScanResult>> mapping = new HashMap<>();
+
+ if (homeList != null) {
+ mapping.put(WifiManager.PASSPOINT_HOME_NETWORK, homeList);
+ }
+ if (roamingList != null) {
+ mapping.put(WifiManager.PASSPOINT_ROAMING_NETWORK, roamingList);
+ }
+
+ matchingList.add(new Pair(buildPasspointConfiguration(FQDN_1, PROVIDER_FRIENDLY_NAME_1),
+ mapping));
+
+ return matchingList;
+ }
+
+ private static OsuProvider buildOsuProvider(String friendlyName) {
+ Map<String, String> friendlyNames = new HashMap<>();
+ friendlyNames.put("en", friendlyName);
+ return new OsuProvider(null, friendlyNames, null, null, null, null, null);
+ }
+
private WifiTracker createTrackerWithImmediateBroadcastsAndInjectInitialScanResults(
Intent ... intents)
throws InterruptedException {
@@ -926,4 +993,172 @@
assertThat(tracker.getAccessPoints().get(0).getBssid()).isEqualTo(BSSID_1);
assertThat(tracker.getAccessPoints().get(1).getBssid()).isEqualTo(BSSID_2);
}
+
+ /**
+ * Verifies that updatePasspointAccessPoints will only return AccessPoints whose
+ * isPasspoint() evaluates as true.
+ */
+ @Test
+ public void updatePasspointAccessPoints_returnedAccessPointsArePasspoint() {
+ WifiTracker tracker = createMockedWifiTracker();
+
+ List<AccessPoint> passpointAccessPoints = tracker.updatePasspointAccessPoints(
+ createPasspointMatchingWifiConfigsWithDuplicates(), new ArrayList<>());
+
+ assertTrue(passpointAccessPoints.size() != 0);
+ for (AccessPoint ap : passpointAccessPoints) {
+ assertTrue(ap.isPasspoint());
+ }
+ }
+
+ /**
+ * Verifies that updatePasspointAccessPoints will return the same amount of AccessPoints as
+ * unique WifiConfigurations, even if duplicate FQDNs exist.
+ */
+ @Test
+ public void updatePasspointAccessPoints_ignoresDuplicateFQDNs() {
+ WifiTracker tracker = createMockedWifiTracker();
+
+ // Process matching list of four configs with two duplicate FQDNs.
+ List<AccessPoint> passpointAccessPoints = tracker.updatePasspointAccessPoints(
+ createPasspointMatchingWifiConfigsWithDuplicates(), new ArrayList<>());
+
+ // Should have 2 APs with unique FQDNs, ignoring the 2 duplicate FQDNs.
+ assertThat(passpointAccessPoints).hasSize(2);
+
+ Set<String> fqdns = new ArraySet<>(Arrays.asList(FQDN_1, FQDN_2));
+
+ assertTrue(fqdns.remove(passpointAccessPoints.get(0).getConfig().FQDN));
+ assertTrue(fqdns.remove(passpointAccessPoints.get(1).getConfig().FQDN));
+ }
+
+ /**
+ * Verifies that updatePasspointAccessPoints will return matching cached APs and update their
+ * scan results instead of creating new APs.
+ */
+ @Test
+ public void updatePasspointAccessPoints_usesCachedAccessPoints() {
+ WifiTracker tracker = createMockedWifiTracker();
+
+ ScanResult result = buildScanResult1();
+
+ List<AccessPoint> passpointAccessPointsFirstUpdate = tracker.updatePasspointAccessPoints(
+ createPasspointMatchingWifiConfigWithScanResults(Arrays.asList(result),
+ null), new ArrayList<>());
+ List<AccessPoint> cachedAccessPoints = new ArrayList<>(passpointAccessPointsFirstUpdate);
+
+ int prevRssi = result.level;
+ int newRssi = prevRssi + 10;
+ result.level = newRssi;
+
+ List<AccessPoint> passpointAccessPointsSecondUpdate = tracker.updatePasspointAccessPoints(
+ createPasspointMatchingWifiConfigWithScanResults(Arrays.asList(result),
+ null), cachedAccessPoints);
+
+ // Verify second update AP is the same object as the first update AP
+ assertThat(passpointAccessPointsFirstUpdate.get(0))
+ .isSameAs(passpointAccessPointsSecondUpdate.get(0));
+ // Verify second update AP has the average of the first and second update RSSIs
+ assertThat(passpointAccessPointsSecondUpdate.get(0).getRssi())
+ .isEqualTo((prevRssi + newRssi) / 2);
+ }
+
+ /**
+ * Verifies that updateOsuAccessPoints will only return AccessPoints whose
+ * isOsuProvider() evaluates as true.
+ */
+ @Test
+ public void updateOsuAccessPoints_returnedAccessPointsAreOsuProviders() {
+ WifiTracker tracker = createMockedWifiTracker();
+
+ Map<OsuProvider, List<ScanResult>> providersAndScans = new HashMap<>();
+ providersAndScans.put(
+ buildOsuProvider(PROVIDER_FRIENDLY_NAME_1), Arrays.asList(buildScanResult1()));
+ providersAndScans.put(
+ buildOsuProvider(PROVIDER_FRIENDLY_NAME_2), Arrays.asList(buildScanResult2()));
+
+ List<AccessPoint> osuAccessPoints = tracker.updateOsuAccessPoints(
+ providersAndScans, new ArrayList<>());
+
+ assertThat(osuAccessPoints).hasSize(2);
+ for (AccessPoint ap: osuAccessPoints) {
+ assertThat(ap.isOsuProvider()).isTrue();
+ }
+ }
+
+ /**
+ * Verifies that updateOsuAccessPoints will not return Osu AccessPoints for already provisioned
+ * networks
+ */
+ @Test
+ public void updateOsuAccessPoints_doesNotReturnAlreadyProvisionedOsuAccessPoints() {
+ WifiTracker tracker = createMockedWifiTracker();
+
+ // Start with two Osu Providers
+ Map<OsuProvider, List<ScanResult>> providersAndScans = new HashMap<>();
+ providersAndScans.put(
+ buildOsuProvider(PROVIDER_FRIENDLY_NAME_1), Arrays.asList(buildScanResult1()));
+ providersAndScans.put(
+ buildOsuProvider(PROVIDER_FRIENDLY_NAME_2), Arrays.asList(buildScanResult2()));
+
+ // First update
+ List<AccessPoint> osuAccessPoints = tracker.updateOsuAccessPoints(
+ providersAndScans, new ArrayList<>());
+
+ // Make sure both Osu Providers' APs are returned
+ assertThat(osuAccessPoints).hasSize(2);
+ List<String> friendlyNames = Arrays.asList(
+ osuAccessPoints.get(0).getTitle(), osuAccessPoints.get(1).getTitle());
+ assertThat(friendlyNames)
+ .containsExactly(PROVIDER_FRIENDLY_NAME_1, PROVIDER_FRIENDLY_NAME_2);
+
+ // Simulate Osu Provider 1 being provisioned
+ Map<OsuProvider, PasspointConfiguration> matchingPasspointConfigForOsuProvider =
+ new HashMap<>();
+ matchingPasspointConfigForOsuProvider.put(buildOsuProvider(PROVIDER_FRIENDLY_NAME_1), null);
+ when(mockWifiManager.getMatchingPasspointConfigsForOsuProviders(any())).thenReturn(
+ matchingPasspointConfigForOsuProvider);
+
+ // Second update
+ osuAccessPoints = tracker.updateOsuAccessPoints(
+ providersAndScans, new ArrayList<>());
+
+ // Returned AP should only be for Osu Provider 2
+ assertThat(osuAccessPoints).hasSize(1);
+ assertThat(osuAccessPoints.get(0).getTitle()).isEqualTo(PROVIDER_FRIENDLY_NAME_2);
+ }
+
+ /**
+ * Verifies that updateOsuAccessPoints will return matching cached APs and update their
+ * scan results instead of creating new APs.
+ */
+ @Test
+ public void updateOsuAccessPoints_usesCachedAccessPoints() {
+ WifiTracker tracker = createMockedWifiTracker();
+
+ ScanResult result = buildScanResult1();
+
+ Map<OsuProvider, List<ScanResult>> providersAndScans = new HashMap<>();
+ providersAndScans.put(
+ buildOsuProvider(PROVIDER_FRIENDLY_NAME_1), Arrays.asList(result));
+
+ List<AccessPoint> osuAccessPointsFirstUpdate = tracker.updateOsuAccessPoints(
+ providersAndScans, new ArrayList<>());
+ List<AccessPoint> cachedAccessPoints = new ArrayList<>(osuAccessPointsFirstUpdate);
+
+ // New RSSI for second update
+ int prevRssi = result.level;
+ int newRssi = prevRssi + 10;
+ result.level = newRssi;
+
+ List<AccessPoint> osuAccessPointsSecondUpdate = tracker.updateOsuAccessPoints(
+ providersAndScans, cachedAccessPoints);
+
+ // Verify second update AP is the same object as the first update AP
+ assertTrue(osuAccessPointsFirstUpdate.get(0)
+ == osuAccessPointsSecondUpdate.get(0));
+ // Verify second update AP has the average of the first and second update RSSIs
+ assertThat(osuAccessPointsSecondUpdate.get(0).getRssi())
+ .isEqualTo((prevRssi + newRssi) / 2);
+ }
}
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/net/NetworkCycleDataLoaderTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/net/NetworkCycleDataLoaderTest.java
index b8a143a..c5f54bb 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/net/NetworkCycleDataLoaderTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/net/NetworkCycleDataLoaderTest.java
@@ -46,6 +46,7 @@
import org.robolectric.util.ReflectionHelpers;
import java.time.ZonedDateTime;
+import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@@ -99,6 +100,20 @@
}
@Test
+ public void loadInBackground_hasCyclePeriod_shouldLoadDataForSpecificCycles() {
+ mLoader = spy(new NetworkCycleDataTestLoader(mContext));
+ doNothing().when(mLoader).loadDataForSpecificCycles();
+ final ArrayList<Long> cycles = new ArrayList<>();
+ cycles.add(67890L);
+ cycles.add(12345L);
+ ReflectionHelpers.setField(mLoader, "mCycles", cycles);
+
+ mLoader.loadInBackground();
+
+ verify(mLoader).loadDataForSpecificCycles();
+ }
+
+ @Test
public void loadPolicyData_shouldRecordUsageFromPolicyCycle() {
final int networkType = ConnectivityManager.TYPE_MOBILE;
final String subId = "TestSubscriber";
@@ -139,6 +154,27 @@
verify(mLoader).recordUsage(fourWeeksAgo, now);
}
+ @Test
+ public void loadDataForSpecificCycles_shouldRecordUsageForSpecifiedTime() {
+ mLoader = spy(new NetworkCycleDataTestLoader(mContext));
+ final long now = System.currentTimeMillis();
+ final long tenDaysAgo = now - (DateUtils.DAY_IN_MILLIS * 10);
+ final long twentyDaysAgo = now - (DateUtils.DAY_IN_MILLIS * 20);
+ final long thirtyDaysAgo = now - (DateUtils.DAY_IN_MILLIS * 30);
+ final ArrayList<Long> cycles = new ArrayList<>();
+ cycles.add(now);
+ cycles.add(tenDaysAgo);
+ cycles.add(twentyDaysAgo);
+ cycles.add(thirtyDaysAgo);
+ ReflectionHelpers.setField(mLoader, "mCycles", cycles);
+
+ mLoader.loadDataForSpecificCycles();
+
+ verify(mLoader).recordUsage(tenDaysAgo, now);
+ verify(mLoader).recordUsage(twentyDaysAgo, tenDaysAgo);
+ verify(mLoader).recordUsage(thirtyDaysAgo, twentyDaysAgo);
+ }
+
public class NetworkCycleDataTestLoader extends NetworkCycleDataLoader<List<NetworkCycleData>> {
private NetworkCycleDataTestLoader(Context context) {
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
index 6152b8c..db4b131 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
@@ -698,6 +698,9 @@
Settings.Global.GLOBAL_SETTINGS_ANGLE_WHITELIST,
GlobalSettingsProto.Gpu.ANGLE_WHITELIST);
dumpSetting(s, p,
+ Settings.Global.GLOBAL_SETTINGS_SHOW_ANGLE_IN_USE_DIALOG_BOX,
+ GlobalSettingsProto.Gpu.SHOW_ANGLE_IN_USE_DIALOG);
+ dumpSetting(s, p,
Settings.Global.GPU_DEBUG_LAYER_APP,
GlobalSettingsProto.Gpu.DEBUG_LAYER_APP);
dumpSetting(s, p,
@@ -718,6 +721,9 @@
dumpSetting(s, p,
Settings.Global.GAME_DRIVER_WHITELIST,
GlobalSettingsProto.Gpu.GAME_DRIVER_WHITELIST);
+ dumpSetting(s, p,
+ Settings.Global.GAME_DRIVER_BLACKLISTS,
+ GlobalSettingsProto.Gpu.GAME_DRIVER_BLACKLISTS);
p.end(gpuToken);
final long hdmiToken = p.start(GlobalSettingsProto.HDMI);
diff --git a/packages/Shell/AndroidManifest.xml b/packages/Shell/AndroidManifest.xml
index e8c728d..0da3b10 100644
--- a/packages/Shell/AndroidManifest.xml
+++ b/packages/Shell/AndroidManifest.xml
@@ -82,6 +82,7 @@
<uses-permission android:name="android.permission.MOVE_PACKAGE" />
<uses-permission android:name="android.permission.CLEAR_APP_USER_DATA" />
<uses-permission android:name="android.permission.CLEAR_APP_CACHE" />
+ <uses-permission android:name="android.permission.ACCESS_INSTANT_APPS" />
<uses-permission android:name="android.permission.DELETE_CACHE_FILES" />
<uses-permission android:name="android.permission.DELETE_PACKAGES" />
<uses-permission android:name="android.permission.MANAGE_ROLLBACKS" />
diff --git a/packages/SystemUI/res-keyguard/layout/bubble_clock.xml b/packages/SystemUI/res-keyguard/layout/bubble_clock.xml
index 6f7f398..c8dc8e4 100644
--- a/packages/SystemUI/res-keyguard/layout/bubble_clock.xml
+++ b/packages/SystemUI/res-keyguard/layout/bubble_clock.xml
@@ -19,9 +19,21 @@
android:layout_width="match_parent"
android:layout_height="match_parent"
>
- <include
+ <TextClock
android:id="@+id/digital_clock"
- layout="@layout/text_clock"
+ android:layout_marginLeft="20dp"
+ android:layout_marginTop="72dp"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_gravity="top|left"
+ android:textSize="44dp"
+ android:letterSpacing="0.05"
+ android:textColor="?attr/wallpaperTextColor"
+ android:singleLine="true"
+ style="@style/widget_big"
+ android:format12Hour="@string/keyguard_widget_12_hours_format"
+ android:format24Hour="@string/keyguard_widget_24_hours_format"
+ android:elegantTextHeight="false"
/>
<com.android.keyguard.clock.ImageClock
android:id="@+id/analog_clock"
diff --git a/packages/SystemUI/res-keyguard/layout/keyguard_status_area.xml b/packages/SystemUI/res-keyguard/layout/keyguard_status_area.xml
index 51f6a4b..dc45b4b 100644
--- a/packages/SystemUI/res-keyguard/layout/keyguard_status_area.xml
+++ b/packages/SystemUI/res-keyguard/layout/keyguard_status_area.xml
@@ -28,11 +28,20 @@
android:clipToPadding="false"
android:orientation="vertical"
android:layout_centerHorizontal="true">
+ <TextView
+ android:id="@+id/title"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:paddingStart="64dp"
+ android:paddingEnd="64dp"
+ android:visibility="gone"
+ android:textColor="?attr/wallpaperTextColor"
+ android:theme="@style/TextAppearance.Keyguard"
+ />
<view class="com.android.keyguard.KeyguardSliceView$Row"
android:id="@+id/row"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:layout_marginTop="@dimen/subtitle_clock_padding"
android:orientation="horizontal"
android:gravity="center"
/>
diff --git a/packages/SystemUI/res-keyguard/layout/stretchanalog_clock.xml b/packages/SystemUI/res-keyguard/layout/stretchanalog_clock.xml
index 64b676f5..116a044 100644
--- a/packages/SystemUI/res-keyguard/layout/stretchanalog_clock.xml
+++ b/packages/SystemUI/res-keyguard/layout/stretchanalog_clock.xml
@@ -19,9 +19,21 @@
android:layout_width="match_parent"
android:layout_height="match_parent"
>
- <include
+ <TextClock
android:id="@+id/digital_clock"
- layout="@layout/text_clock"
+ android:layout_marginLeft="20dp"
+ android:layout_marginTop="72dp"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_gravity="top|left"
+ android:textSize="44dp"
+ android:letterSpacing="0.05"
+ android:textColor="?attr/wallpaperTextColor"
+ android:singleLine="true"
+ style="@style/widget_big"
+ android:format12Hour="@string/keyguard_widget_12_hours_format"
+ android:format24Hour="@string/keyguard_widget_24_hours_format"
+ android:elegantTextHeight="false"
/>
<com.android.keyguard.clock.StretchAnalogClock
android:id="@+id/analog_clock"
diff --git a/packages/SystemUI/res-keyguard/layout/text_clock.xml b/packages/SystemUI/res-keyguard/layout/text_clock.xml
index b61ad9c..9f7ea0d 100644
--- a/packages/SystemUI/res-keyguard/layout/text_clock.xml
+++ b/packages/SystemUI/res-keyguard/layout/text_clock.xml
@@ -16,9 +16,10 @@
-->
<TextClock
xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
+ android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
+ android:gravity="center_horizontal"
android:letterSpacing="0.03"
android:textColor="?attr/wallpaperTextColor"
android:singleLine="true"
diff --git a/packages/SystemUI/res-keyguard/values/dimens.xml b/packages/SystemUI/res-keyguard/values/dimens.xml
index e2ba23e..b6a41c1 100644
--- a/packages/SystemUI/res-keyguard/values/dimens.xml
+++ b/packages/SystemUI/res-keyguard/values/dimens.xml
@@ -42,18 +42,18 @@
<dimen name="eca_overlap">-10dip</dimen>
<!-- Slice header -->
- <dimen name="widget_title_font_size">24dp</dimen>
- <dimen name="widget_title_bottom_margin">14dp</dimen>
- <dimen name="bottom_text_spacing_digital">0dp</dimen>
+ <dimen name="widget_title_font_size">22dp</dimen>
+ <dimen name="header_subtitle_padding">4dp</dimen>
+ <dimen name="header_icon_size">20dp</dimen>
<!-- Slice subtitle -->
<dimen name="widget_label_font_size">16dp</dimen>
<!-- Clock without header -->
<dimen name="widget_big_font_size">64dp</dimen>
+ <dimen name="bottom_text_spacing_digital">0dp</dimen>
<!-- Clock with header -->
- <dimen name="widget_small_clock_padding">-25dp</dimen>
- <dimen name="widget_small_font_size">24dp</dimen>
- <dimen name="widget_small_font_stroke">0.6dp</dimen>
+ <dimen name="widget_small_font_size">22dp</dimen>
<dimen name="widget_vertical_padding">32dp</dimen>
+ <dimen name="widget_vertical_padding_clock">30dp</dimen>
<!-- Subtitle paddings -->
<dimen name="widget_horizontal_padding">8dp</dimen>
<dimen name="widget_icon_size">16dp</dimen>
diff --git a/packages/SystemUI/res-keyguard/values/strings.xml b/packages/SystemUI/res-keyguard/values/strings.xml
index 94481e7..5714556 100644
--- a/packages/SystemUI/res-keyguard/values/strings.xml
+++ b/packages/SystemUI/res-keyguard/values/strings.xml
@@ -64,6 +64,9 @@
charged, say that it is charged. -->
<string name="keyguard_charged">Fully charged</string>
+ <!-- When the lock screen is showing and the phone plugged in, and the battery is not fully charged, say that it's wirelessly charging. [CHAR LIMIT=50] -->
+ <string name="keyguard_plugged_in_wireless"><xliff:g id="percentage" example="20%">%s</xliff:g> • Wirelessly Charging</string>
+
<!-- When the lock screen is showing and the phone plugged in, and the battery
is not fully charged, say that it's charging. -->
<string name="keyguard_plugged_in"><xliff:g id="percentage">%s</xliff:g> • Charging</string>
diff --git a/packages/SystemUI/res/drawable/privacy_chip_bg.xml b/packages/SystemUI/res/drawable/privacy_chip_bg.xml
index 36d0659..f1158ef 100644
--- a/packages/SystemUI/res/drawable/privacy_chip_bg.xml
+++ b/packages/SystemUI/res/drawable/privacy_chip_bg.xml
@@ -17,6 +17,7 @@
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#4a4a4a" />
- <padding android:padding="@dimen/ongoing_appops_chip_bg_padding" />
+ <padding android:paddingTop="@dimen/ongoing_appops_chip_bg_padding"
+ android:paddingBottom="@dimen/ongoing_appops_chip_bg_padding"/>
<corners android:radius="@dimen/ongoing_appops_chip_bg_corner_radius" />
</shape>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/notification_info.xml b/packages/SystemUI/res/layout/notification_info.xml
index d502baa..91353d7 100644
--- a/packages/SystemUI/res/layout/notification_info.xml
+++ b/packages/SystemUI/res/layout/notification_info.xml
@@ -71,18 +71,38 @@
android:maxLines="1"
android:layout_centerVertical="true"
android:layout_toEndOf="@id/pkg_divider" />
- <!-- 24 dp icon with 16 dp padding all around to mirror notification content margins -->
- <ImageButton
- android:id="@+id/info"
- android:layout_width="56dp"
- android:layout_height="56dp"
- android:layout_alignParentEnd="true"
+ <LinearLayout
+ android:id="@+id/info_and_settings"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
android:layout_centerVertical="true"
- android:background="@drawable/ripple_drawable"
- android:contentDescription="@string/notification_more_settings"
- android:padding="16dp"
- android:src="@drawable/ic_info"
- android:tint="?android:attr/colorAccent" />
+ android:layout_alignParentEnd="true"
+ android:paddingHorizontal="16dp"
+ android:orientation="horizontal">
+ <!-- Optional link to app. Only appears if the channel is not disabled and the app
+asked for it -->
+ <ImageButton
+ android:id="@+id/app_settings"
+ android:layout_width="40dp"
+ android:layout_height="56dp"
+ android:layout_centerVertical="true"
+ android:paddingRight="16dp"
+ android:visibility="gone"
+ android:background="@drawable/ripple_drawable"
+ android:contentDescription="@string/notification_app_settings"
+ android:src="@drawable/ic_settings"
+ android:tint="?android:attr/colorAccent" />
+ <!-- 24 dp icon with 16 dp padding all around to mirror notification content margins -->
+ <ImageButton
+ android:id="@+id/info"
+ android:layout_width="24dp"
+ android:layout_height="56dp"
+ android:layout_centerVertical="true"
+ android:background="@drawable/ripple_drawable"
+ android:contentDescription="@string/notification_more_settings"
+ android:src="@drawable/ic_info"
+ android:tint="?android:attr/colorAccent" />
+ </LinearLayout>
</RelativeLayout>
<LinearLayout
@@ -143,50 +163,61 @@
</LinearLayout>
<!-- Settings and Done buttons -->
- <LinearLayout
+ <RelativeLayout
android:id="@+id/block_or_minimize"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/notification_guts_button_spacing"
android:layout_marginStart="@dimen/notification_guts_button_side_margin"
android:layout_marginEnd="@dimen/notification_guts_button_side_margin"
- android:gravity="end"
- android:orientation="horizontal">
-
- <!-- Optional link to app. Only appears if the channel is not disabled and the app
- asked for it -->
+ android:clipChildren="false"
+ android:clipToPadding="false">
<TextView
- android:id="@+id/app_settings"
- android:text="@string/notification_app_settings"
+ android:id="@+id/done"
+ android:text="@string/inline_done_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:visibility="gone"
- android:ellipsize="end"
- android:maxLines="1"
+ android:layout_centerVertical="true"
style="@style/TextAppearance.NotificationInfo.Button"/>
- <TextView
- android:id="@+id/block"
- android:text="@string/inline_stop_button"
+
+ <LinearLayout
+ android:id="@+id/block_buttons"
android:layout_width="wrap_content"
- android:layout_height="match_parent"
- android:layout_marginStart="@dimen/notification_guts_button_horizontal_spacing"
- style="@style/TextAppearance.NotificationInfo.Button"/>
- <TextView
- android:id="@+id/minimize"
- android:text="@string/inline_minimize_button"
- android:layout_width="wrap_content"
- android:layout_height="match_parent"
- android:layout_marginStart="@dimen/notification_guts_button_horizontal_spacing"
- style="@style/TextAppearance.NotificationInfo.Button" />
- <TextView
- android:id="@+id/keep"
- android:minWidth="48dp"
- android:text="@string/inline_keep_button"
- android:layout_width="wrap_content"
- android:layout_height="match_parent"
- android:layout_marginStart="@dimen/notification_guts_button_horizontal_spacing"
- style="@style/TextAppearance.NotificationInfo.Button"/>
- </LinearLayout>
+ android:layout_height="wrap_content"
+ android:layout_centerVertical="true"
+ android:layout_alignParentEnd="true"
+ android:orientation="horizontal">
+ <TextView
+ android:id="@+id/deliver_silently"
+ android:text="@string/inline_deliver_silently_button"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerVertical="true"
+ android:layout_marginStart="@dimen/notification_guts_button_horizontal_spacing"
+ android:paddingRight="24dp"
+ style="@style/TextAppearance.NotificationInfo.Button"/>
+ <TextView
+ android:id="@+id/block"
+ android:text="@string/inline_block_button"
+ android:minWidth="48dp"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerVertical="true"
+ android:layout_marginStart="@dimen/notification_guts_button_horizontal_spacing"
+ style="@style/TextAppearance.NotificationInfo.Button"/>
+ <TextView
+ android:id="@+id/minimize"
+ android:text="@string/inline_minimize_button"
+ android:minWidth="48dp"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerVertical="true"
+ android:layout_marginStart="@dimen/notification_guts_button_horizontal_spacing"
+ style="@style/TextAppearance.NotificationInfo.Button"/>
+ </LinearLayout>
+
+
+ </RelativeLayout>
<LinearLayout
android:id="@+id/interruptiveness_settings"
android:layout_width="match_parent"
diff --git a/packages/SystemUI/res/layout/ongoing_privacy_chip.xml b/packages/SystemUI/res/layout/ongoing_privacy_chip.xml
index cbdd51b..58fe811 100644
--- a/packages/SystemUI/res/layout/ongoing_privacy_chip.xml
+++ b/packages/SystemUI/res/layout/ongoing_privacy_chip.xml
@@ -29,14 +29,25 @@
android:orientation="horizontal"
android:paddingStart="@dimen/ongoing_appops_chip_side_padding"
android:paddingEnd="@dimen/ongoing_appops_chip_side_padding"
- android:background="@drawable/privacy_chip_bg"
android:focusable="true">
+ <TextView
+ android:id="@+id/in_use_text"
+ android:layout_height="match_parent"
+ android:layout_width="wrap_content"
+ android:layout_gravity="center_vertical|start"
+ android:layout_marginEnd="@dimen/ongoing_appops_chip_icon_margin_collapsed"
+ android:gravity="center_vertical"
+ android:textAppearance="@style/TextAppearance.StatusBar.Clock"
+ android:textColor="@color/status_bar_clock_color"
+ android:text="@string/ongoing_privacy_chip_in_use"
+ />
+
<LinearLayout
android:id="@+id/icons_container"
android:layout_height="match_parent"
android:layout_width="wrap_content"
- android:layout_gravity="center_vertical|start"
+ android:layout_gravity="center_vertical"
android:gravity="center_vertical"
/>
@@ -51,7 +62,7 @@
android:gravity="center_vertical"
android:textAppearance="@style/TextAppearance.StatusBar.Clock"
android:textColor="@color/status_bar_clock_color"
- android:layout_marginStart="@dimen/ongoing_appops_chip_icon_margin"
- android:layout_marginEnd="@dimen/ongoing_appops_chip_icon_margin"
+ android:layout_marginStart="@dimen/ongoing_appops_chip_icon_margin_collapsed"
+ android:layout_marginEnd="@dimen/ongoing_appops_chip_icon_margin_collapsed"
/>
</com.android.systemui.privacy.OngoingPrivacyChip>
\ No newline at end of file
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index 0344535..1e1245f 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -967,7 +967,7 @@
<!-- Height and width of App Opp icons in Ongoing App Ops dialog -->
<dimen name="ongoing_appops_dialog_icon_size">24dp</dimen>
<!-- Left margin of App Opp icons in Ongoing App Ops dialog -->
- <dimen name="ongoing_appops_dialog_icon_margin">8dp</dimen>
+ <dimen name="ongoing_appops_dialog_icon_margin">12dp</dimen>
<!-- Height and width of Application icons in Ongoing App Ops dialog -->
<dimen name="ongoing_appops_dialog_app_icon_size">32dp</dimen>
<!-- Height and width of Plus sign in Ongoing App Ops dialog -->
@@ -988,12 +988,14 @@
<dimen name="ongoing_appops_chip_side_padding">6dp</dimen>
<!-- Padding between background of Ongoing App Ops chip and content -->
<dimen name="ongoing_appops_chip_bg_padding">0dp</dimen>
- <!-- Margin between icons of Ongoing App Ops chip -->
- <dimen name="ongoing_appops_chip_icon_margin">4dp</dimen>
+ <!-- Margin between icons of Ongoing App Ops chip when QQS-->
+ <dimen name="ongoing_appops_chip_icon_margin_collapsed">0dp</dimen>
+ <!-- Margin between icons of Ongoing App Ops chip when QS-->
+ <dimen name="ongoing_appops_chip_icon_margin_expanded">8dp</dimen>
<!-- Icon size of Ongoing App Ops chip -->
<dimen name="ongoing_appops_chip_icon_size">18dp</dimen>
<!-- Radius of Ongoing App Ops chip corners -->
- <dimen name="ongoing_appops_chip_bg_corner_radius">12dp</dimen>
+ <dimen name="ongoing_appops_chip_bg_corner_radius">4dp</dimen>
<!-- Text size for Ongoing App Ops dialog title -->
<dimen name="ongoing_appops_dialog_title_size">20sp</dimen>
<!-- Text size for Ongoing App Ops dialog items -->
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index db4a6cc..b4131d7 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -955,6 +955,9 @@
<!-- Interruption level: Alarms only. Optimized for narrow two-line display. [CHAR LIMIT=40] -->
<string name="interruption_level_alarms_twoline">Alarms\nonly</string>
+ <!-- Indication on the keyguard that is shown when the device is wirelessly charging. [CHAR LIMIT=80]-->
+ <string name="keyguard_indication_charging_time_wireless"><xliff:g id="percentage" example="20%">%2$s</xliff:g> • Wirelessly Charging (<xliff:g id="charging_time_left" example="4 hours and 2 minutes">%1$s</xliff:g> until full)</string>
+
<!-- Indication on the keyguard that is shown when the device is charging. [CHAR LIMIT=50]-->
<string name="keyguard_indication_charging_time"><xliff:g id="percentage">%2$s</xliff:g> • Charging (<xliff:g id="charging_time_left" example="4 hours and 2 minutes">%1$s</xliff:g> until full)</string>
@@ -1573,12 +1576,18 @@
<string name="inline_blocking_helper">You usually dismiss these notifications.
\nKeep showing them?</string>
+ <!-- Notification Inline controls: button to dismiss the blocking helper [CHAR_LIMIT=25] -->
+ <string name="inline_done_button">Done</string>
+
<!-- Notification Inline controls: continue receiving notifications prompt, channel level -->
<string name="inline_keep_showing">Keep showing these notifications?</string>
<!-- Notification inline controls: block notifications button -->
<string name="inline_stop_button">Stop notifications</string>
+ <!-- Notification inline controls: button to deliver notifications silently from this channel [CHAR_LIMIT=35] -->
+ <string name="inline_deliver_silently_button">Deliver Silently</string>
+
<!-- Notification inline controls: button to block notifications from this channel [CHAR_LIMIT=35] -->
<string name="inline_block_button">Block</string>
@@ -2301,6 +2310,9 @@
<!-- Content description for ongoing privacy chip. Use with multiple apps [CHAR LIMIT=NONE]-->
<string name="ongoing_privacy_chip_content_multiple_apps">Applications are using your <xliff:g id="types_list" example="camera, location">%s</xliff:g>.</string>
+ <!-- Ongoing Privacy "Chip" in use text [CHAR LIMIT=10]-->
+ <string name="ongoing_privacy_chip_in_use">In use:</string>
+
<!-- Content description for ongoing privacy chip. Use with multiple apps using same app op[CHAR LIMIT=NONE]-->
<plurals name="ongoing_privacy_chip_content_multiple_apps_single_op">
<item quantity="one"><xliff:g id="num_apps" example="1">%1$d</xliff:g> application is using your <xliff:g id="type" example="camera">%2$s</xliff:g>.</item>
@@ -2311,7 +2323,7 @@
<!-- Action for accepting the Ongoing privacy dialog [CHAR LIMIT=10]-->
<string name="ongoing_privacy_dialog_ok">Got it</string>
- <!-- Action on Ongoing Privacy Dialog to open privacy hub [CHAR LIMIT=20]-->
+ <!-- Action on Ongoing Privacy Dialog to open privacy hub [CHAR LIMIT=23]-->
<string name="ongoing_privacy_dialog_open_settings">Privacy settings</string>
<!-- Text for item in Ongoing Privacy Dialog title when only one app is using app ops [CHAR LIMIT=NONE] -->
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/recents/IOverviewProxy.aidl b/packages/SystemUI/shared/src/com/android/systemui/shared/recents/IOverviewProxy.aidl
index 2ff98ba..37abab9 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/recents/IOverviewProxy.aidl
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/recents/IOverviewProxy.aidl
@@ -16,19 +16,32 @@
package com.android.systemui.shared.recents;
+import android.graphics.Region;
+import android.os.Bundle;
import android.view.MotionEvent;
import com.android.systemui.shared.recents.ISystemUiProxy;
oneway interface IOverviewProxy {
- void onBind(in ISystemUiProxy sysUiProxy);
+
+ void onActiveNavBarRegionChanges(in Region activeRegion) = 11;
+
+ void onInitialize(in Bundle params) = 12;
+
+
+ /**
+ * @deprecated
+ */
+ void onBind(in ISystemUiProxy sysUiProxy) = 0;
/**
* Called once immediately prior to the first onMotionEvent() call, providing a hint to the
* target the initial source of the subsequent motion events.
*
* @param downHitTarget is one of the {@link NavigationBarCompat.HitTarget}s
+ *
+ * @deprecated
*/
- void onPreMotionEvent(int downHitTarget);
+ void onPreMotionEvent(int downHitTarget) = 1;
/**
* Proxies motion events from the nav bar in SystemUI to the OverviewProxyService. The sender
@@ -38,40 +51,48 @@
* Quick scrub: DOWN, (MOVE/POINTER_DOWN/POINTER_UP)*, SCRUB_START, SCRUB_PROGRESS*, SCRUB_END
*
* Once quick scrub is sent, then no further motion events will be provided.
+ *
+ * @deprecated
*/
- void onMotionEvent(in MotionEvent event);
+ void onMotionEvent(in MotionEvent event) = 2;
/**
* Sent when the user starts to actively scrub the nav bar to switch tasks. Once this event is
* sent the caller will stop sending any motion events and will no longer preemptively cancel
* any recents animations started as a part of the motion event handling.
+ *
+ * @deprecated
*/
- void onQuickScrubStart();
+ void onQuickScrubStart() = 3;
/**
* Sent when the user stops actively scrubbing the nav bar to switch tasks.
+ *
+ * @deprecated
*/
- void onQuickScrubEnd();
+ void onQuickScrubEnd() = 4;
/**
* Sent for each movement over the nav bar while the user is scrubbing it to switch tasks.
+ *
+ * @deprecated
*/
- void onQuickScrubProgress(float progress);
+ void onQuickScrubProgress(float progress) = 5;
/**
* Sent when overview button is pressed to toggle show/hide of overview.
*/
- void onOverviewToggle();
+ void onOverviewToggle() = 6;
/**
* Sent when overview is to be shown.
*/
- void onOverviewShown(boolean triggeredFromAltTab);
+ void onOverviewShown(boolean triggeredFromAltTab) = 7;
/**
* Sent when overview is to be hidden.
*/
- void onOverviewHidden(boolean triggeredFromAltTab, boolean triggeredFromHomeKey);
+ void onOverviewHidden(boolean triggeredFromAltTab, boolean triggeredFromHomeKey) = 8;
/**
* Sent when a user swipes up over the navigation bar to launch overview. Swipe up is determined
@@ -83,11 +104,13 @@
* visible, this event will still be sent if user swipes up). When this signal is sent,
* navigation bar will not handle any gestures such as quick scrub and the home button will
* cancel (long) press.
+ *
+ * @deprecated
*/
- void onQuickStep(in MotionEvent event);
+ void onQuickStep(in MotionEvent event) = 9;
/**
* Sent when there was an action on one of the onboarding tips view.
*/
- void onTip(int actionType, int viewType);
+ void onTip(int actionType, int viewType) = 10;
}
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/InputChannelCompat.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/InputChannelCompat.java
index f7ccb81..804f4f1 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/InputChannelCompat.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/InputChannelCompat.java
@@ -16,6 +16,7 @@
package com.android.systemui.shared.system;
+import android.os.Bundle;
import android.os.Looper;
import android.util.Pair;
import android.view.BatchedInputEventReceiver;
@@ -53,6 +54,16 @@
}
/**
+ * Creates a dispatcher from the extras received as part on onInitialize
+ */
+ public static InputEventReceiver fromBundle(Bundle params, String key,
+ Looper looper, Choreographer choreographer, InputEventListener listener) {
+
+ InputChannel channel = params.getParcelable(key);
+ return new InputEventReceiver(channel, looper, choreographer, listener);
+ }
+
+ /**
* @see BatchedInputEventReceiver
*/
public static class InputEventReceiver {
@@ -90,7 +101,7 @@
private final InputChannel mInputChannel;
private final InputEventSender mSender;
- private InputEventDispatcher(InputChannel inputChannel, Looper looper) {
+ public InputEventDispatcher(InputChannel inputChannel, Looper looper) {
mInputChannel = inputChannel;
mSender = new InputEventSender(inputChannel, looper) { };
}
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/NavigationBarCompat.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/NavigationBarCompat.java
index 69aea2c..b363b4a 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/NavigationBarCompat.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/NavigationBarCompat.java
@@ -17,31 +17,15 @@
package com.android.systemui.shared.system;
import android.annotation.IntDef;
-import android.content.Context;
-import android.content.res.Resources;
-import android.util.DisplayMetrics;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
-public class NavigationBarCompat {
- /**
- * Touch slopes and thresholds for quick step operations. Drag slop is the point where the
- * home button press/long press over are ignored and will start to drag when exceeded and the
- * touch slop is when the respected operation will occur when exceeded. Touch slop must be
- * larger than the drag slop.
- */
- public static int getQuickStepDragSlopPx() {
- return convertDpToPixel(10);
- }
+/**
+ * TODO: Remove this class
+ */
+public class NavigationBarCompat extends QuickStepContract {
- public static int getQuickStepTouchSlopPx() {
- return convertDpToPixel(24);
- }
-
- public static int getQuickScrubTouchSlopPx() {
- return convertDpToPixel(24);
- }
@Retention(RetentionPolicy.SOURCE)
@IntDef({HIT_TARGET_NONE, HIT_TARGET_BACK, HIT_TARGET_HOME, HIT_TARGET_OVERVIEW})
@@ -75,8 +59,4 @@
* Interaction type: show/hide the overview button while this service is connected to launcher
*/
public static final int FLAG_SHOW_OVERVIEW_BUTTON = 0x4;
-
- private static int convertDpToPixel(float dp){
- return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
- }
}
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/QuickStepContract.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/QuickStepContract.java
new file mode 100644
index 0000000..6d7abd0
--- /dev/null
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/QuickStepContract.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.shared.system;
+
+import android.content.res.Resources;
+
+/**
+ * Various shared constants between Launcher and SysUI as part of quickstep
+ */
+public class QuickStepContract {
+
+ public static final String KEY_EXTRA_SYSUI_PROXY = "extra_sysui_proxy";
+ public static final String KEY_EXTRA_INPUT_CHANNEL = "extra_input_channel";
+ public static final String KEY_EXTRA_WINDOW_CORNER_RADIUS = "extra_window_corner_radius";
+ public static final String KEY_EXTRA_SUPPORTS_WINDOW_CORNERS = "extra_supports_window_corners";
+
+ /**
+ * Touch slopes and thresholds for quick step operations. Drag slop is the point where the
+ * home button press/long press over are ignored and will start to drag when exceeded and the
+ * touch slop is when the respected operation will occur when exceeded. Touch slop must be
+ * larger than the drag slop.
+ */
+ public static int getQuickStepDragSlopPx() {
+ return convertDpToPixel(10);
+ }
+
+ public static int getQuickStepTouchSlopPx() {
+ return convertDpToPixel(24);
+ }
+
+ public static int getQuickScrubTouchSlopPx() {
+ return convertDpToPixel(24);
+ }
+
+ private static int convertDpToPixel(float dp) {
+ return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
+ }
+}
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java b/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java
index fc1843b..8de84bf 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java
@@ -1,10 +1,19 @@
package com.android.keyguard;
+import android.animation.Animator;
+import android.animation.AnimatorSet;
+import android.animation.ValueAnimator;
import android.app.WallpaperManager;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Paint.Style;
+import android.transition.ChangeBounds;
+import android.transition.Transition;
+import android.transition.TransitionManager;
+import android.transition.TransitionValues;
import android.util.AttributeSet;
+import android.util.MathUtils;
+import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
@@ -16,6 +25,7 @@
import com.android.internal.colorextraction.ColorExtractor;
import com.android.keyguard.clock.ClockManager;
import com.android.systemui.Dependency;
+import com.android.systemui.Interpolators;
import com.android.systemui.colorextraction.SysuiColorExtractor;
import com.android.systemui.plugins.ClockPlugin;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
@@ -28,6 +38,7 @@
*/
public class KeyguardClockSwitch extends RelativeLayout {
+ private final Transition mTransition;
/**
* Optional/alternative clock injected via plugin.
*/
@@ -53,6 +64,10 @@
* Maintain state so that a newly connected plugin can be initialized.
*/
private float mDarkAmount;
+ /**
+ * If the Keyguard Slice has a header (big center-aligned text.)
+ */
+ private boolean mShowingHeader;
private boolean mSupportsDarkText;
private int[] mColorPalette;
@@ -98,6 +113,7 @@
public KeyguardClockSwitch(Context context, AttributeSet attrs) {
super(context, attrs);
+ mTransition = new ClockBoundsTransition();
}
/**
@@ -187,7 +203,9 @@
View bigClockView = mClockPlugin.getBigClockView();
if (bigClockView != null) {
container.addView(bigClockView);
- container.setVisibility(View.VISIBLE);
+ if (container.getVisibility() == View.GONE) {
+ container.setVisibility(View.VISIBLE);
+ }
}
}
mBigClockContainer = container;
@@ -284,6 +302,26 @@
}
}
+ /**
+ * Sets if the keyguard slice is showing a center-aligned header. We need a smaller clock
+ * in these cases.
+ */
+ public void setKeyguardShowingHeader(boolean hasHeader) {
+ if (mShowingHeader == hasHeader || hasCustomClock()) {
+ return;
+ }
+ mShowingHeader = hasHeader;
+
+ TransitionManager.beginDelayedTransition((ViewGroup) mClockView.getParent(), mTransition);
+ int fontSize = mContext.getResources().getDimensionPixelSize(mShowingHeader
+ ? R.dimen.widget_small_font_size : R.dimen.widget_big_font_size);
+ int paddingBottom = mContext.getResources().getDimensionPixelSize(mShowingHeader
+ ? R.dimen.widget_vertical_padding_clock : R.dimen.header_subtitle_padding);
+ mClockView.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize);
+ mClockView.setPadding(mClockView.getPaddingLeft(), mClockView.getPaddingTop(),
+ mClockView.getPaddingRight(), paddingBottom);
+ }
+
@VisibleForTesting (otherwise = VisibleForTesting.NONE)
ClockManager.ClockChangedListener getClockChangedListener() {
return mClockChangedListener;
@@ -293,4 +331,54 @@
StatusBarStateController.StateListener getStateListener() {
return mStateListener;
}
+
+ /**
+ * Special layout transition that scales the clock view as its bounds change, to make it look
+ * like the text is shrinking.
+ */
+ private class ClockBoundsTransition extends ChangeBounds {
+
+ ClockBoundsTransition() {
+ setDuration(KeyguardSliceView.DEFAULT_ANIM_DURATION / 2);
+ setInterpolator(Interpolators.LINEAR_OUT_SLOW_IN);
+ }
+
+ @Override
+ public Animator createAnimator(ViewGroup sceneRoot, TransitionValues startValues,
+ TransitionValues endValues) {
+ Animator animator = super.createAnimator(sceneRoot, startValues, endValues);
+ if (animator == null || startValues.view != mClockView) {
+ return animator;
+ }
+
+ ValueAnimator boundsAnimator = null;
+ if (animator instanceof AnimatorSet) {
+ Animator first = ((AnimatorSet) animator).getChildAnimations().get(0);
+ if (first instanceof ValueAnimator) {
+ boundsAnimator = (ValueAnimator) first;
+ }
+ } else if (animator instanceof ValueAnimator) {
+ boundsAnimator = (ValueAnimator) animator;
+ }
+
+ if (boundsAnimator != null) {
+ float bigFontSize = mContext.getResources()
+ .getDimensionPixelSize(R.dimen.widget_big_font_size);
+ float smallFontSize = mContext.getResources()
+ .getDimensionPixelSize(R.dimen.widget_small_font_size);
+ float startScale = mShowingHeader
+ ? bigFontSize / smallFontSize : smallFontSize / bigFontSize;
+ boundsAnimator.addUpdateListener(animation -> {
+ float scale = MathUtils.lerp(startScale, 1f /* stop */,
+ animation.getAnimatedFraction());
+ mClockView.setPivotX(mClockView.getWidth() / 2);
+ mClockView.setPivotY(0);
+ mClockView.setScaleX(scale);
+ mClockView.setScaleY(scale);
+ });
+ }
+
+ return animator;
+ }
+ }
}
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSliceView.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSliceView.java
index bac7844..2040a76 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSliceView.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSliceView.java
@@ -37,10 +37,10 @@
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
-import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.LinearLayout;
+import android.widget.TextView;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
@@ -58,6 +58,7 @@
import com.android.settingslib.Utils;
import com.android.systemui.Dependency;
import com.android.systemui.Interpolators;
+import com.android.systemui.R;
import com.android.systemui.keyguard.KeyguardSliceProvider;
import com.android.systemui.statusbar.policy.ConfigurationController;
import com.android.systemui.tuner.TunerService;
@@ -78,6 +79,8 @@
private final HashMap<View, PendingIntent> mClickActions;
private Uri mKeyguardSliceUri;
+ @VisibleForTesting
+ TextView mTitle;
private Row mRow;
private int mTextColor;
private float mDarkAmount = 0;
@@ -91,6 +94,8 @@
private Runnable mContentChangeListener;
private Slice mSlice;
private boolean mHasHeader;
+ private final int mRowWithHeaderPadding;
+ private final int mRowPadding;
public KeyguardSliceView(Context context) {
this(context, null, 0);
@@ -107,6 +112,9 @@
tunerService.addTunable(this, Settings.Secure.KEYGUARD_SLICE_URI);
mClickActions = new HashMap<>();
+ mRowPadding = context.getResources().getDimensionPixelSize(R.dimen.subtitle_clock_padding);
+ mRowWithHeaderPadding = context.getResources()
+ .getDimensionPixelSize(R.dimen.header_subtitle_padding);
LayoutTransition transition = new LayoutTransition();
transition.setStagger(LayoutTransition.CHANGE_APPEARING, DEFAULT_ANIM_DURATION / 2);
@@ -117,13 +125,13 @@
transition.setInterpolator(LayoutTransition.APPEARING, Interpolators.FAST_OUT_SLOW_IN);
transition.setInterpolator(LayoutTransition.DISAPPEARING, Interpolators.ALPHA_OUT);
transition.setAnimateParentHierarchy(false);
- transition.addTransitionListener(new SliceViewTransitionListener());
setLayoutTransition(transition);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
+ mTitle = findViewById(R.id.title);
mRow = findViewById(R.id.row);
mTextColor = Utils.getColorAttrDefaultColor(mContext, R.attr.wallpaperTextColor);
mIconSize = (int) mContext.getResources().getDimension(R.dimen.widget_icon_size);
@@ -160,6 +168,7 @@
private void showSlice() {
Trace.beginSection("KeyguardSliceView#showSlice");
if (mSlice == null) {
+ mTitle.setVisibility(GONE);
mRow.setVisibility(GONE);
mHasHeader = false;
if (mContentChangeListener != null) {
@@ -170,8 +179,7 @@
ListContent lc = new ListContent(getContext(), mSlice);
SliceContent headerContent = lc.getHeader();
- mHasHeader = headerContent != null
- && !headerContent.getSliceItem().hasHint(HINT_LIST_ITEM);
+ mHasHeader = headerContent != null && !headerContent.getSliceItem().hasHint(HINT_LIST_ITEM);
List<SliceContent> subItems = new ArrayList<>();
for (int i = 0; i < lc.getRowItems().size(); i++) {
SliceContent subItem = lc.getRowItems().get(i);
@@ -181,12 +189,26 @@
subItems.add(subItem);
}
}
+ if (!mHasHeader) {
+ mTitle.setVisibility(GONE);
+ } else {
+ mTitle.setVisibility(VISIBLE);
+
+ RowContent header = lc.getHeader();
+ SliceItem mainTitle = header.getTitleItem();
+ CharSequence title = mainTitle != null ? mainTitle.getText() : null;
+ mTitle.setText(title);
+ }
mClickActions.clear();
final int subItemsCount = subItems.size();
final int blendedColor = getTextColor();
final int startIndex = mHasHeader ? 1 : 0; // First item is header; skip it
mRow.setVisibility(subItemsCount > 0 ? VISIBLE : GONE);
+ LinearLayout.LayoutParams layoutParams = (LayoutParams) mRow.getLayoutParams();
+ layoutParams.topMargin = mHasHeader ? mRowWithHeaderPadding : mRowPadding;
+ mRow.setLayoutParams(layoutParams);
+
for (int i = startIndex; i < subItemsCount; i++) {
RowContent rc = (RowContent) subItems.get(i);
SliceItem item = rc.getSliceItem();
@@ -250,6 +272,7 @@
private void updateTextColors() {
final int blendedColor = getTextColor();
+ mTitle.setTextColor(blendedColor);
int childCount = mRow.getChildCount();
for (int i = 0; i < childCount; i++) {
View v = mRow.getChildAt(i);
@@ -294,7 +317,10 @@
setupUri(newValue);
}
- private void setupUri(String uriString) {
+ /**
+ * Sets the slice provider Uri.
+ */
+ public void setupUri(String uriString) {
if (uriString == null) {
uriString = KeyguardSliceProvider.KEYGUARD_SLICE_URI;
}
@@ -512,29 +538,4 @@
}
}
}
-
- private class SliceViewTransitionListener implements LayoutTransition.TransitionListener {
- @Override
- public void startTransition(LayoutTransition transition, ViewGroup container, View view,
- int transitionType) {
- switch (transitionType) {
- case LayoutTransition.APPEARING:
- int translation = getResources().getDimensionPixelSize(
- R.dimen.pulsing_notification_appear_translation);
- view.setTranslationY(translation);
- view.animate()
- .translationY(0)
- .setDuration(DEFAULT_ANIM_DURATION)
- .setInterpolator(Interpolators.ALPHA_IN)
- .start();
- break;
- }
- }
-
- @Override
- public void endTransition(LayoutTransition transition, ViewGroup container, View view,
- int transitionType) {
-
- }
- }
}
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java b/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java
index bb549ad..b0670fd 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java
@@ -16,14 +16,11 @@
package com.android.keyguard;
-import android.animation.Animator;
-import android.animation.AnimatorListenerAdapter;
import android.app.ActivityManager;
import android.app.IActivityManager;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
-import android.graphics.Paint;
import android.os.Handler;
import android.os.Looper;
import android.os.RemoteException;
@@ -37,15 +34,12 @@
import android.util.TypedValue;
import android.view.View;
import android.widget.GridLayout;
-import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.core.graphics.ColorUtils;
import com.android.internal.widget.LockPatternUtils;
-import com.android.internal.widget.ViewClippingUtil;
import com.android.systemui.Dependency;
-import com.android.systemui.Interpolators;
import com.android.systemui.statusbar.policy.ConfigurationController;
import com.google.android.collect.Sets;
@@ -54,14 +48,13 @@
import java.util.TimeZone;
public class KeyguardStatusView extends GridLayout implements
- ConfigurationController.ConfigurationListener, View.OnLayoutChangeListener {
+ ConfigurationController.ConfigurationListener {
private static final boolean DEBUG = KeyguardConstants.DEBUG;
private static final String TAG = "KeyguardStatusView";
private static final int MARQUEE_DELAY_MS = 2000;
private final LockPatternUtils mLockPatternUtils;
private final IActivityManager mIActivityManager;
- private final float mSmallClockScale;
private TextView mLogoutView;
private KeyguardClockSwitch mClockView;
@@ -74,8 +67,6 @@
private boolean mPulsing;
private float mDarkAmount = 0;
private int mTextColor;
- private int mLastLayoutHeight;
- private int mSmallClockPadding;
private KeyguardUpdateMonitorCallback mInfoCallback = new KeyguardUpdateMonitorCallback() {
@@ -135,8 +126,6 @@
mIActivityManager = ActivityManager.getService();
mLockPatternUtils = new LockPatternUtils(getContext());
mHandler = new Handler(Looper.myLooper());
- mSmallClockScale = getResources().getDimension(R.dimen.widget_small_font_size)
- / getResources().getDimension(R.dimen.widget_big_font_size);
onDensityOrFontScaleChanged();
}
@@ -189,9 +178,6 @@
mVisibleInDoze = Sets.newArraySet(mClockView, mKeyguardSlice);
mTextColor = mClockView.getCurrentTextColor();
- int clockStroke = getResources().getDimensionPixelSize(R.dimen.widget_small_font_stroke);
- mClockView.getPaint().setStrokeWidth(clockStroke);
- mClockView.addOnLayoutChangeListener(this);
mKeyguardSlice.setContentChangeListener(this::onSliceContentChanged);
onSliceContentChanged();
@@ -207,72 +193,20 @@
* Moves clock, adjusting margins when slice content changes.
*/
private void onSliceContentChanged() {
- LinearLayout.LayoutParams layoutParams =
- (LinearLayout.LayoutParams) mClockView.getLayoutParams();
- layoutParams.bottomMargin = mKeyguardSlice.hasHeader() ? mSmallClockPadding : 0;
- mClockView.setLayoutParams(layoutParams);
- }
-
- /**
- * Animate clock when necessary.
- */
- @Override
- public void onLayoutChange(View view, int left, int top, int right, int bottom,
- int oldLeft, int oldTop, int oldRight, int oldBottom) {
- boolean smallClock = mKeyguardSlice.hasHeader();
- int heightOffset = smallClock ? 0 : getHeight() - mLastLayoutHeight;
- long duration = KeyguardSliceView.DEFAULT_ANIM_DURATION;
- long delay = smallClock ? 0 : duration / 4;
-
- boolean shouldAnimate = mKeyguardSlice.getLayoutTransition() != null
- && mKeyguardSlice.getLayoutTransition().isRunning();
- if (view == mClockView) {
- float clockScale = smallClock ? mSmallClockScale : 1;
- Paint.Style style = smallClock ? Paint.Style.FILL_AND_STROKE : Paint.Style.FILL;
- mClockView.animate().cancel();
- if (shouldAnimate) {
- mClockView.setY(oldTop + heightOffset);
- mClockView.animate()
- .setInterpolator(Interpolators.FAST_OUT_SLOW_IN)
- .setDuration(duration)
- .setListener(new ClipChildrenAnimationListener())
- .setStartDelay(delay)
- .y(top)
- .scaleX(clockScale)
- .scaleY(clockScale)
- .withEndAction(() -> {
- mClockView.setStyle(style);
- mClockView.invalidate();
- })
- .start();
- } else {
- mClockView.setY(top);
- mClockView.setScaleX(clockScale);
- mClockView.setScaleY(clockScale);
- mClockView.setStyle(style);
- mClockView.invalidate();
- }
- }
+ mClockView.setKeyguardShowingHeader(mKeyguardSlice.hasHeader());
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
- mClockView.setPivotX(mClockView.getWidth() / 2);
- mClockView.setPivotY(0);
- mLastLayoutHeight = getHeight();
layoutOwnerInfo();
}
@Override
public void onDensityOrFontScaleChanged() {
- mSmallClockPadding = getResources()
- .getDimensionPixelSize(R.dimen.widget_small_clock_padding);
if (mClockView != null) {
mClockView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getResources().getDimensionPixelSize(R.dimen.widget_big_font_size));
- mClockView.getPaint().setStrokeWidth(
- getResources().getDimensionPixelSize(R.dimen.widget_small_font_stroke));
}
if (mOwnerInfo != null) {
mOwnerInfo.setTextSize(TypedValue.COMPLEX_UNIT_PX,
@@ -461,24 +395,4 @@
Log.e(TAG, "Failed to logout user", re);
}
}
-
- private class ClipChildrenAnimationListener extends AnimatorListenerAdapter implements
- ViewClippingUtil.ClippingParameters {
-
- ClipChildrenAnimationListener() {
- ViewClippingUtil.setClippingDeactivated(mClockView, true /* deactivated */,
- this /* clippingParams */);
- }
-
- @Override
- public void onAnimationEnd(Animator animation) {
- ViewClippingUtil.setClippingDeactivated(mClockView, false /* deactivated */,
- this /* clippingParams */);
- }
-
- @Override
- public boolean shouldFinish(View view) {
- return view == getParent();
- }
- }
}
diff --git a/packages/SystemUI/src/com/android/keyguard/clock/ClockLayout.java b/packages/SystemUI/src/com/android/keyguard/clock/ClockLayout.java
index 3591dc8..4d8cf96 100644
--- a/packages/SystemUI/src/com/android/keyguard/clock/ClockLayout.java
+++ b/packages/SystemUI/src/com/android/keyguard/clock/ClockLayout.java
@@ -22,6 +22,7 @@
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
+import android.widget.FrameLayout.LayoutParams;
import com.android.keyguard.R;
@@ -80,8 +81,9 @@
// Put digital clock in two left corner of the screen.
if (mDigitalClock != null) {
- mDigitalClock.setX(0.1f * getWidth() + offsetX);
- mDigitalClock.setY(0.1f * getHeight() + offsetY);
+ LayoutParams params = (LayoutParams) mDigitalClock.getLayoutParams();
+ mDigitalClock.setX(offsetX + params.leftMargin);
+ mDigitalClock.setY(offsetY + params.topMargin);
}
// Put the analog clock in the middle of the screen.
diff --git a/packages/SystemUI/src/com/android/keyguard/clock/ClockManager.java b/packages/SystemUI/src/com/android/keyguard/clock/ClockManager.java
index 9598142..078108d 100644
--- a/packages/SystemUI/src/com/android/keyguard/clock/ClockManager.java
+++ b/packages/SystemUI/src/com/android/keyguard/clock/ClockManager.java
@@ -15,6 +15,7 @@
*/
package com.android.keyguard.clock;
+import android.annotation.Nullable;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
@@ -25,16 +26,18 @@
import android.provider.Settings;
import android.view.LayoutInflater;
+import androidx.annotation.VisibleForTesting;
+
import com.android.keyguard.R;
+import com.android.systemui.dock.DockManager;
+import com.android.systemui.dock.DockManager.DockEventListener;
import com.android.systemui.plugins.ClockPlugin;
import com.android.systemui.statusbar.policy.ExtensionController;
import com.android.systemui.statusbar.policy.ExtensionController.Extension;
import java.util.ArrayList;
import java.util.List;
-import java.util.Objects;
import java.util.function.Consumer;
-import java.util.function.Supplier;
import javax.inject.Inject;
import javax.inject.Singleton;
@@ -45,7 +48,6 @@
@Singleton
public final class ClockManager {
- private final LayoutInflater mLayoutInflater;
private final ContentResolver mContentResolver;
private final List<ClockInfo> mClockInfos = new ArrayList<>();
@@ -62,7 +64,6 @@
}
}
};
-
private final ExtensionController mExtensionController;
/**
* Used to select between plugin or default implementations of ClockPlugin interface.
@@ -72,13 +73,35 @@
* Consumer that accepts the a new ClockPlugin implementation when the Extension reloads.
*/
private final Consumer<ClockPlugin> mClockPluginConsumer = this::setClockPlugin;
+ /**
+ * Supplier of default ClockPlugin implementation.
+ */
+ private final DefaultClockSupplier mDefaultClockSupplier;
+ /**
+ * Observe changes to dock state to know when to switch the clock face.
+ */
+ private final DockEventListener mDockEventListener =
+ new DockEventListener() {
+ @Override
+ public void onEvent(int event) {
+ final boolean isDocked = (event == DockManager.STATE_DOCKED
+ || event == DockManager.STATE_DOCKED_HIDE);
+ mDefaultClockSupplier.setDocked(isDocked);
+ if (mClockExtension != null) {
+ mClockExtension.reload();
+ }
+ }
+ };
+ @Nullable
+ private final DockManager mDockManager;
private final List<ClockChangedListener> mListeners = new ArrayList<>();
@Inject
- public ClockManager(Context context, ExtensionController extensionController) {
+ public ClockManager(Context context, ExtensionController extensionController,
+ @Nullable DockManager dockManager) {
mExtensionController = extensionController;
- mLayoutInflater = LayoutInflater.from(context);
+ mDockManager = dockManager;
mContentResolver = context.getContentResolver();
Resources res = context.getResources();
@@ -110,6 +133,9 @@
.setThumbnail(() -> BitmapFactory.decodeResource(res, R.drawable.type_thumbnail))
.setPreview(() -> BitmapFactory.decodeResource(res, R.drawable.type_preview))
.build());
+
+ mDefaultClockSupplier = new DefaultClockSupplier(new SettingsWrapper(mContentResolver),
+ LayoutInflater.from(context));
}
/**
@@ -154,41 +180,32 @@
mContentResolver.registerContentObserver(
Settings.Secure.getUriFor(Settings.Secure.LOCK_SCREEN_CUSTOM_CLOCK_FACE),
false, mContentObserver);
+ mContentResolver.registerContentObserver(
+ Settings.Secure.getUriFor(Settings.Secure.DOCKED_CLOCK_FACE),
+ false, mContentObserver);
+ if (mDockManager != null) {
+ mDockManager.addListener(mDockEventListener);
+ }
mClockExtension = mExtensionController.newExtension(ClockPlugin.class)
.withPlugin(ClockPlugin.class)
.withCallback(mClockPluginConsumer)
- // Using withDefault even though this isn't the default as a workaround.
- // ExtensionBuilder doesn't provide the ability to supply a ClockPlugin
- // instance based off of the value of a setting. Since multiple "default"
- // can be provided, using a supplier that changes the settings value.
- // A null return will cause Extension#reload to look at the next "default"
- // supplier.
- .withDefault(
- new SettingsGattedSupplier(
- mContentResolver,
- Settings.Secure.LOCK_SCREEN_CUSTOM_CLOCK_FACE,
- BubbleClockController.class.getName(),
- () -> BubbleClockController.build(mLayoutInflater)))
- .withDefault(
- new SettingsGattedSupplier(
- mContentResolver,
- Settings.Secure.LOCK_SCREEN_CUSTOM_CLOCK_FACE,
- StretchAnalogClockController.class.getName(),
- () -> StretchAnalogClockController.build(mLayoutInflater)))
- .withDefault(
- new SettingsGattedSupplier(
- mContentResolver,
- Settings.Secure.LOCK_SCREEN_CUSTOM_CLOCK_FACE,
- TypeClockController.class.getName(),
- () -> TypeClockController.build(mLayoutInflater)))
+ .withDefault(mDefaultClockSupplier)
.build();
}
private void unregister() {
mContentResolver.unregisterContentObserver(mContentObserver);
+ if (mDockManager != null) {
+ mDockManager.removeListener(mDockEventListener);
+ }
mClockExtension.destroy();
}
+ @VisibleForTesting
+ boolean isDocked() {
+ return mDefaultClockSupplier.isDocked();
+ }
+
/**
* Listener for events that should cause the custom clock face to change.
*/
@@ -200,44 +217,4 @@
*/
void onClockChanged(ClockPlugin clock);
}
-
- /**
- * Supplier that only gets an instance when a settings value matches expected value.
- */
- private static class SettingsGattedSupplier implements Supplier<ClockPlugin> {
-
- private final ContentResolver mContentResolver;
- private final String mKey;
- private final String mValue;
- private final Supplier<ClockPlugin> mSupplier;
-
- /**
- * Constructs a supplier that changes secure setting key against value.
- *
- * @param contentResolver Used to look up settings value.
- * @param key Settings key.
- * @param value If the setting matches this values that get supplies a ClockPlugin
- * instance.
- * @param supplier Supplier of ClockPlugin instance, only used if the setting
- * matches value.
- */
- SettingsGattedSupplier(ContentResolver contentResolver, String key, String value,
- Supplier<ClockPlugin> supplier) {
- mContentResolver = contentResolver;
- mKey = key;
- mValue = value;
- mSupplier = supplier;
- }
-
- /**
- * Returns null if the settings value doesn't match the expected value.
- *
- * A null return causes Extension#reload to skip this supplier and move to the next.
- */
- @Override
- public ClockPlugin get() {
- final String currentValue = Settings.Secure.getString(mContentResolver, mKey);
- return Objects.equals(currentValue, mValue) ? mSupplier.get() : null;
- }
- }
}
diff --git a/packages/SystemUI/src/com/android/keyguard/clock/DefaultClockSupplier.java b/packages/SystemUI/src/com/android/keyguard/clock/DefaultClockSupplier.java
new file mode 100644
index 0000000..7fdd235
--- /dev/null
+++ b/packages/SystemUI/src/com/android/keyguard/clock/DefaultClockSupplier.java
@@ -0,0 +1,101 @@
+/*
+ * 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.keyguard.clock;
+
+import android.util.ArrayMap;
+import android.view.LayoutInflater;
+
+import com.android.systemui.plugins.ClockPlugin;
+
+import java.util.Map;
+import java.util.function.Supplier;
+
+/**
+ * Supplier that only gets an instance when a settings value matches expected value.
+ */
+public class DefaultClockSupplier implements Supplier<ClockPlugin> {
+
+ private final SettingsWrapper mSettingsWrapper;
+ /**
+ * Map from expected value stored in settings to supplier of custom clock face.
+ */
+ private final Map<String, Supplier<ClockPlugin>> mClocks = new ArrayMap<>();
+ /**
+ * When docked, the DOCKED_CLOCK_FACE setting will be checked for the custom clock face
+ * to show.
+ */
+ private boolean mIsDocked;
+
+ /**
+ * Constructs a supplier that changes secure setting key against value.
+ *
+ * @param settingsWrapper Wrapper around settings used to look up the custom clock face.
+ * @param layoutInflater Provided to clocks as dependency to inflate clock views.
+ */
+ public DefaultClockSupplier(SettingsWrapper settingsWrapper, LayoutInflater layoutInflater) {
+ mSettingsWrapper = settingsWrapper;
+
+ mClocks.put(BubbleClockController.class.getName(),
+ () -> BubbleClockController.build(layoutInflater));
+ mClocks.put(StretchAnalogClockController.class.getName(),
+ () -> StretchAnalogClockController.build(layoutInflater));
+ mClocks.put(TypeClockController.class.getName(),
+ () -> TypeClockController.build(layoutInflater));
+ }
+
+ /**
+ * Sets the dock state.
+ *
+ * @param isDocked True when docked, false otherwise.
+ */
+ public void setDocked(boolean isDocked) {
+ mIsDocked = isDocked;
+ }
+
+ boolean isDocked() {
+ return mIsDocked;
+ }
+
+ /**
+ * Get the custom clock face based on values in settings.
+ *
+ * @return Custom clock face, null if the settings value doesn't match a custom clock.
+ */
+ @Override
+ public ClockPlugin get() {
+ ClockPlugin plugin = null;
+ if (mIsDocked) {
+ final String name = mSettingsWrapper.getDockedClockFace();
+ if (name != null) {
+ Supplier<ClockPlugin> supplier = mClocks.get(name);
+ if (supplier != null) {
+ plugin = supplier.get();
+ if (plugin != null) {
+ return plugin;
+ }
+ }
+ }
+ }
+ final String name = mSettingsWrapper.getLockScreenCustomClockFace();
+ if (name != null) {
+ Supplier<ClockPlugin> supplier = mClocks.get(name);
+ if (supplier != null) {
+ plugin = supplier.get();
+ }
+ }
+ return plugin;
+ }
+}
diff --git a/packages/SystemUI/src/com/android/keyguard/clock/SettingsWrapper.java b/packages/SystemUI/src/com/android/keyguard/clock/SettingsWrapper.java
new file mode 100644
index 0000000..58e1155
--- /dev/null
+++ b/packages/SystemUI/src/com/android/keyguard/clock/SettingsWrapper.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.keyguard.clock;
+
+import android.content.ContentResolver;
+import android.provider.Settings;
+
+/**
+ * Wrapper around Settings used for testing.
+ */
+public class SettingsWrapper {
+
+ private static final String CUSTOM_CLOCK_FACE = Settings.Secure.LOCK_SCREEN_CUSTOM_CLOCK_FACE;
+ private static final String DOCKED_CLOCK_FACE = Settings.Secure.DOCKED_CLOCK_FACE;
+
+ private ContentResolver mContentResolver;
+
+ public SettingsWrapper(ContentResolver contentResolver) {
+ mContentResolver = contentResolver;
+ }
+
+ /**
+ * Gets the value stored in settings for the custom clock face.
+ */
+ public String getLockScreenCustomClockFace() {
+ return Settings.Secure.getString(mContentResolver, CUSTOM_CLOCK_FACE);
+ }
+
+ /**
+ * Gets the value stored in settings for the clock face to use when docked.
+ */
+ public String getDockedClockFace() {
+ return Settings.Secure.getString(mContentResolver, DOCKED_CLOCK_FACE);
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/SystemUIFactory.java b/packages/SystemUI/src/com/android/systemui/SystemUIFactory.java
index 755d6fc..d27a903 100644
--- a/packages/SystemUI/src/com/android/systemui/SystemUIFactory.java
+++ b/packages/SystemUI/src/com/android/systemui/SystemUIFactory.java
@@ -31,6 +31,7 @@
import com.android.keyguard.ViewMediatorCallback;
import com.android.systemui.assist.AssistManager;
import com.android.systemui.classifier.FalsingManager;
+import com.android.systemui.dock.DockManager;
import com.android.systemui.fragments.FragmentService;
import com.android.systemui.keyguard.DismissCallbackRegistry;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
@@ -228,6 +229,16 @@
return SysUiServiceProvider.getComponent(context, StatusBar.class);
}
+ /**
+ * Provides DockManager.
+ */
+ @Singleton
+ @Provides
+ @Nullable
+ public DockManager providesDockManager(Context context) {
+ return SysUiServiceProvider.getComponent(context, DockManager.class);
+ }
+
@Module
protected static class ContextHolder {
private Context mContext;
diff --git a/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java b/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java
index 4d70890..038f491 100644
--- a/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java
+++ b/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java
@@ -290,10 +290,6 @@
return mAssistUtils.isSessionRunning();
}
- public void destroy() {
- mWindowManager.removeViewImmediate(mView);
- }
-
private void maybeSwapSearchIcon(@NonNull ComponentName assistComponent, boolean isService) {
replaceDrawable(mView.getOrb().getLogo(), assistComponent, ASSIST_ICON_METADATA_NAME,
isService);
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/Bubble.java b/packages/SystemUI/src/com/android/systemui/bubbles/Bubble.java
new file mode 100644
index 0000000..4778434
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/Bubble.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.systemui.bubbles;
+
+
+import android.view.LayoutInflater;
+
+import com.android.systemui.R;
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+
+/**
+ * Encapsulates the data and UI elements of a bubble.
+ */
+class Bubble {
+
+ public BubbleView iconView;
+ public BubbleExpandedView expandedView;
+ public String key;
+ public NotificationEntry entry;
+
+ Bubble(NotificationEntry e, LayoutInflater inflater, BubbleStackView stackView,
+ BubbleExpandedView.OnBubbleBlockedListener listener) {
+ entry = e;
+ key = entry.key;
+
+ iconView = (BubbleView) inflater.inflate(
+ R.layout.bubble_view, stackView, false /* attachToRoot */);
+ iconView.setNotif(entry);
+
+ expandedView = (BubbleExpandedView) inflater.inflate(
+ R.layout.bubble_expanded_view, stackView, false /* attachToRoot */);
+ expandedView.setEntry(entry, stackView);
+
+ expandedView.setOnBlockedListener(listener);
+ }
+
+ public void setEntry(NotificationEntry entry) {
+ key = entry.key;
+ iconView.update(entry);
+ // TODO: should also update the expanded view here (e.g. height change)
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
index 41bc1b2..a67e1b7 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
@@ -16,10 +16,6 @@
package com.android.systemui.bubbles;
-import static android.content.pm.ActivityInfo.DOCUMENT_LAUNCH_ALWAYS;
-import static android.util.StatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__ACTIVITY_INFO_MISSING;
-import static android.util.StatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__ACTIVITY_INFO_NOT_RESIZABLE;
-import static android.util.StatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__DOCUMENT_LAUNCH_NOT_ALWAYS;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
@@ -33,21 +29,14 @@
import android.app.IActivityTaskManager;
import android.app.INotificationManager;
import android.app.Notification;
-import android.app.PendingIntent;
import android.content.Context;
-import android.content.pm.ActivityInfo;
-import android.graphics.Point;
import android.graphics.Rect;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.provider.Settings;
import android.service.notification.StatusBarNotification;
-import android.util.Log;
-import android.util.StatsLog;
import android.view.Display;
-import android.view.LayoutInflater;
import android.view.ViewGroup;
-import android.view.WindowManager;
import android.widget.FrameLayout;
import androidx.annotation.MainThread;
@@ -66,10 +55,7 @@
import com.android.systemui.statusbar.notification.row.NotificationInflater;
import com.android.systemui.statusbar.phone.StatusBarWindowController;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
-import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
@@ -105,11 +91,9 @@
private final BubbleTaskStackListener mTaskStackListener;
private BubbleStateChangeListener mStateChangeListener;
private BubbleExpandListener mExpandListener;
- private LayoutInflater mInflater;
- private final Map<String, BubbleView> mBubbles = new HashMap<>();
+ private BubbleData mBubbleData;
private BubbleStackView mStackView;
- private final Point mDisplaySize;
// Bubbles get added to the status bar view
private final StatusBarWindowController mStatusBarWindowController;
@@ -168,10 +152,6 @@
@Inject
public BubbleController(Context context, StatusBarWindowController statusBarWindowController) {
mContext = context;
- WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
- mDisplaySize = new Point();
- wm.getDefaultDisplay().getSize(mDisplaySize);
- mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mNotificationEntryManager = Dependency.get(NotificationEntryManager.class);
mNotificationEntryManager.addNotificationEntryListener(mEntryListener);
@@ -190,6 +170,8 @@
mActivityTaskManager = ActivityTaskManager.getService();
mTaskStackListener = new BubbleTaskStackListener();
ActivityManagerWrapper.getInstance().registerTaskStackListener(mTaskStackListener);
+
+ mBubbleData = BubbleData.getInstance();
}
/**
@@ -219,8 +201,11 @@
* screen (e.g. if on AOD).
*/
public boolean hasBubbles() {
- for (BubbleView bv : mBubbles.values()) {
- if (!bv.getEntry().isBubbleDismissed()) {
+ if (mStackView == null) {
+ return false;
+ }
+ for (Bubble bubble : mBubbleData.getBubbles()) {
+ if (!bubble.entry.isBubbleDismissed()) {
return true;
}
}
@@ -250,10 +235,6 @@
if (mStackView == null) {
return;
}
- Set<String> keys = mBubbles.keySet();
- for (String key: keys) {
- mBubbles.get(key).getEntry().setBubbleDismissed(true);
- }
mStackView.stackDismissed();
updateVisibility();
@@ -267,10 +248,9 @@
* @param updatePosition whether this update should promote the bubble to the top of the stack.
*/
public void updateBubble(NotificationEntry notif, boolean updatePosition) {
- if (mBubbles.containsKey(notif.key)) {
+ if (mStackView != null && mBubbleData.getBubble(notif.key) != null) {
// It's an update
- BubbleView bubble = mBubbles.get(notif.key);
- mStackView.updateBubble(bubble, notif, updatePosition);
+ mStackView.updateBubble(notif, updatePosition);
} else {
if (mStackView == null) {
mStackView = new BubbleStackView(mContext);
@@ -286,15 +266,7 @@
mStackView.setOnBlockedListener(this);
}
// It's new
- BubbleView bubble = (BubbleView) mInflater.inflate(
- R.layout.bubble_view, mStackView, false /* attachToRoot */);
- bubble.setNotif(notif);
- PendingIntent bubbleIntent = getValidBubbleIntent(notif);
- if (bubbleIntent != null) {
- bubble.setBubbleIntent(bubbleIntent);
- }
- mBubbles.put(bubble.getKey(), bubble);
- mStackView.addBubble(bubble);
+ mStackView.addBubble(notif);
}
updateVisibility();
}
@@ -306,25 +278,18 @@
*/
@MainThread
void removeBubble(String key) {
- BubbleView bv = mBubbles.remove(key);
- if (mStackView != null && bv != null) {
- mStackView.removeBubble(bv);
- bv.destroyActivityView(mStackView);
+ if (mStackView != null) {
+ mStackView.removeBubble(key);
}
-
- NotificationEntry entry = bv != null ? bv.getEntry() : null;
- if (entry != null) {
- entry.setBubbleDismissed(true);
- mNotificationEntryManager.updateNotifications();
- }
+ mNotificationEntryManager.updateNotifications();
updateVisibility();
}
@Override
public void onBubbleBlocked(NotificationEntry entry) {
- Object[] bubbles = mBubbles.values().toArray();
+ Object[] bubbles = mBubbleData.getBubbles().toArray();
for (int i = 0; i < bubbles.length; i++) {
- NotificationEntry e = ((BubbleView) bubbles[i]).getEntry();
+ NotificationEntry e = ((Bubble) bubbles[i]).entry;
boolean samePackage = entry.notification.getPackageName().equals(
e.notification.getPackageName());
if (samePackage) {
@@ -368,10 +333,8 @@
&& alertAgain(entry, entry.notification.getNotification())) {
entry.setShowInShadeWhenBubble(true);
entry.setBubbleDismissed(false); // updates come back as bubbles even if dismissed
- if (mBubbles.containsKey(entry.key)) {
- mBubbles.get(entry.key).updateDotVisibility();
- }
updateBubble(entry, true /* updatePosition */);
+ mStackView.updateDotVisibility(entry.key);
}
}
@@ -383,8 +346,8 @@
return;
}
entry.setShowInShadeWhenBubble(false);
- if (mBubbles.containsKey(entry.key)) {
- mBubbles.get(entry.key).updateDotVisibility();
+ if (mStackView != null) {
+ mStackView.updateDotVisibility(entry.key);
}
if (!removedByUser) {
// This was a cancel so we should remove the bubble
@@ -441,65 +404,6 @@
return mStackView;
}
- @Nullable
- private PendingIntent getValidBubbleIntent(NotificationEntry notif) {
- Notification notification = notif.notification.getNotification();
- String packageName = notif.notification.getPackageName();
- Notification.BubbleMetadata data = notif.getBubbleMetadata();
- if (data != null && canLaunchInActivityView(data.getIntent(),
- true /* enable logging for bubbles */, packageName)) {
- return data.getIntent();
- }
- if (shouldUseContentIntent(mContext)
- && canLaunchInActivityView(notification.contentIntent,
- false /* disable logging for notifications */, packageName)) {
- Log.d(TAG, "[addBubble " + notif.key
- + "]: No appOverlayIntent, using contentIntent.");
- return notification.contentIntent;
- }
- Log.d(TAG, "[addBubble " + notif.key + "]: No supported intent for ActivityView.");
- return null;
- }
-
- /**
- * Whether an intent is properly configured to display in an {@link android.app.ActivityView}.
- *
- * @param intent the pending intent of the bubble.
- * @param enableLogging whether bubble developer error should be logged.
- * @param packageName the notification package name for this bubble.
- * @return
- */
- private boolean canLaunchInActivityView(PendingIntent intent, boolean enableLogging,
- String packageName) {
- if (intent == null) {
- return false;
- }
- ActivityInfo info =
- intent.getIntent().resolveActivityInfo(mContext.getPackageManager(), 0);
- if (info == null) {
- if (enableLogging) {
- StatsLog.write(StatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED, packageName,
- BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__ACTIVITY_INFO_MISSING);
- }
- return false;
- }
- if (!ActivityInfo.isResizeableMode(info.resizeMode)) {
- if (enableLogging) {
- StatsLog.write(StatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED, packageName,
- BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__ACTIVITY_INFO_NOT_RESIZABLE);
- }
- return false;
- }
- if (info.documentLaunchMode != DOCUMENT_LAUNCH_ALWAYS) {
- if (enableLogging) {
- StatsLog.write(StatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED, packageName,
- BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__DOCUMENT_LAUNCH_NOT_ALWAYS);
- }
- return false;
- }
- return (info.flags & ActivityInfo.FLAG_ALLOW_EMBEDDED) != 0;
- }
-
/**
* Whether the notification has been developer configured to bubble and is allowed by the user.
*/
@@ -620,7 +524,7 @@
ENABLE_AUTO_BUBBLE_ALL, 0) != 0;
}
- private static boolean shouldUseContentIntent(Context context) {
+ static boolean shouldUseContentIntent(Context context) {
return Settings.Secure.getInt(context.getContentResolver(),
ENABLE_BUBBLE_CONTENT_INTENT, 0) != 0;
}
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleData.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleData.java
new file mode 100644
index 0000000..89b0de8
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleData.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.systemui.bubbles;
+
+import androidx.annotation.Nullable;
+
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+
+import java.util.Collection;
+import java.util.HashMap;
+
+/**
+ * Keeps track of active bubbles.
+ */
+class BubbleData {
+
+ private HashMap<String, Bubble> mBubbles = new HashMap<>();
+
+ private static BubbleData sBubbleData = null;
+
+ private BubbleData() {}
+
+ public static BubbleData getInstance() {
+ if (sBubbleData == null) {
+ sBubbleData = new BubbleData();
+ }
+ return sBubbleData;
+ }
+
+ /**
+ * The set of bubbles.
+ */
+ public Collection<Bubble> getBubbles() {
+ return mBubbles.values();
+ }
+
+ @Nullable
+ public Bubble getBubble(String key) {
+ return mBubbles.get(key);
+ }
+
+ public void addBubble(Bubble b) {
+ mBubbles.put(b.key, b);
+ }
+
+ @Nullable
+ public Bubble removeBubble(String key) {
+ return mBubbles.remove(key);
+ }
+
+ public void updateBubble(String key, NotificationEntry newEntry) {
+ Bubble oldBubble = mBubbles.get(key);
+ if (oldBubble != null) {
+ oldBubble.setEntry(newEntry);
+ }
+ }
+
+ public void clear() {
+ mBubbles.clear();
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExpandedView.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExpandedView.java
index bf9d7ba..3389c46 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExpandedView.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleExpandedView.java
@@ -16,37 +16,53 @@
package com.android.systemui.bubbles;
+import static android.content.pm.ActivityInfo.DOCUMENT_LAUNCH_ALWAYS;
+import static android.util.StatsLogInternal.BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__ACTIVITY_INFO_MISSING;
+import static android.util.StatsLogInternal.BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__ACTIVITY_INFO_NOT_RESIZABLE;
+import static android.util.StatsLogInternal.BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__DOCUMENT_LAUNCH_NOT_ALWAYS;
+
import android.animation.LayoutTransition;
import android.animation.ObjectAnimator;
import android.annotation.Nullable;
+import android.app.ActivityView;
import android.app.INotificationManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
+import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Color;
+import android.graphics.Insets;
+import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.provider.Settings;
+import android.service.notification.StatusBarNotification;
import android.util.AttributeSet;
import android.util.Log;
+import android.util.StatsLog;
import android.view.View;
+import android.view.ViewGroup;
+import android.view.WindowInsets;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
+import com.android.systemui.Dependency;
import com.android.systemui.Interpolators;
import com.android.systemui.R;
import com.android.systemui.recents.TriangleShape;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
+import com.android.systemui.statusbar.notification.stack.ExpandableViewState;
/**
* Container for the expanded bubble view, handles rendering the caret and header of the view.
@@ -66,8 +82,15 @@
// Permission view
private View mPermissionView;
- // The view that is being displayed for the expanded state
- private View mExpandedView;
+ // Views for expanded state
+ private ExpandableNotificationRow mNotifRow;
+ private ActivityView mActivityView;
+
+ private boolean mActivityViewReady = false;
+ private PendingIntent mBubbleIntent;
+
+ private int mBubbleHeight;
+ private int mDefaultHeight;
private NotificationEntry mEntry;
private PackageManager mPm;
@@ -75,11 +98,38 @@
private Drawable mAppIcon;
private INotificationManager mNotificationManagerService;
+ private BubbleController mBubbleController = Dependency.get(BubbleController.class);
- // Need reference to let it know to collapse when new task is launched
private BubbleStackView mStackView;
- private OnBubbleBlockedListener mOnBubbleBlockedListener;
+ private BubbleExpandedView.OnBubbleBlockedListener mOnBubbleBlockedListener;
+
+ private ActivityView.StateCallback mStateCallback = new ActivityView.StateCallback() {
+ @Override
+ public void onActivityViewReady(ActivityView view) {
+ mActivityViewReady = true;
+ mActivityView.startActivity(mBubbleIntent);
+ }
+
+ @Override
+ public void onActivityViewDestroyed(ActivityView view) {
+ mActivityViewReady = false;
+ }
+
+ /**
+ * This is only called for tasks on this ActivityView, which is also set to
+ * single-task mode -- meaning never more than one task on this display. If a task
+ * is being removed, it's the top Activity finishing and this bubble should
+ * be removed or collapsed.
+ */
+ @Override
+ public void onTaskRemovalStarted(int taskId) {
+ if (mEntry != null) {
+ // Must post because this is called from a binder thread.
+ post(() -> mBubbleController.removeBubble(mEntry.key));
+ }
+ }
+ };
public BubbleExpandedView(Context context) {
this(context, null);
@@ -97,6 +147,8 @@
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
mPm = context.getPackageManager();
+ mDefaultHeight = getResources().getDimensionPixelSize(
+ R.dimen.bubble_expanded_default_height);
try {
mNotificationManagerService = INotificationManager.Stub.asInterface(
ServiceManager.getServiceOrThrow(Context.NOTIFICATION_SERVICE));
@@ -150,6 +202,28 @@
mPermissionView = findViewById(R.id.permission_layout);
findViewById(R.id.no_bubbles_button).setOnClickListener(this);
findViewById(R.id.yes_bubbles_button).setOnClickListener(this);
+
+ mActivityView = new ActivityView(mContext, null /* attrs */, 0 /* defStyle */,
+ true /* singleTaskInstance */);
+ addView(mActivityView);
+
+ mActivityView.setOnApplyWindowInsetsListener((View view, WindowInsets insets) -> {
+ ActivityView activityView = (ActivityView) view;
+ // Here we assume that the position of the ActivityView on the screen
+ // remains regardless of IME status. When we move ActivityView, the
+ // forwardedInsets should be computed not against the current location
+ // and size, but against the post-moved location and size.
+ Point displaySize = new Point();
+ view.getContext().getDisplay().getSize(displaySize);
+ int[] windowLocation = view.getLocationOnScreen();
+ final int windowBottom = windowLocation[1] + view.getHeight();
+ final int keyboardHeight = insets.getSystemWindowInsetBottom()
+ - insets.getStableInsetBottom();
+ final int insetsBottom = Math.max(0,
+ windowBottom + keyboardHeight - displaySize.y);
+ activityView.setForwardedInsets(Insets.of(0, 0, 0, insetsBottom));
+ return view.onApplyWindowInsets(insets);
+ });
}
/**
@@ -187,6 +261,8 @@
}
updateHeaderView();
updatePermissionView();
+ updateExpandedView();
+ mActivityView.setCallback(mStateCallback);
}
private void updateHeaderView() {
@@ -223,6 +299,34 @@
}
}
+ private void updateExpandedView() {
+ mBubbleIntent = getBubbleIntent(mEntry);
+ if (mBubbleIntent != null) {
+ if (mNotifRow != null) {
+ // Clear out the row if we had it previously
+ removeView(mNotifRow);
+ mNotifRow = null;
+ }
+ Notification.BubbleMetadata data = mEntry.getBubbleMetadata();
+ mBubbleHeight = data != null && data.getDesiredHeight() > 0
+ ? data.getDesiredHeight()
+ : mDefaultHeight;
+ // XXX: enforce max / min height
+ LayoutParams lp = (LayoutParams) mActivityView.getLayoutParams();
+ lp.height = mBubbleHeight;
+ mActivityView.setLayoutParams(lp);
+ mActivityView.setVisibility(VISIBLE);
+ } else {
+ // Hide activity view if we had it previously
+ mActivityView.setVisibility(GONE);
+
+ // Use notification view
+ mNotifRow = mEntry.getRow();
+ addView(mNotifRow);
+ }
+ updateView();
+ }
+
@Override
public void onClick(View view) {
if (mEntry == null) {
@@ -234,6 +338,8 @@
mStackView.collapseStack(() -> {
try {
n.contentIntent.send();
+ logBubbleClickEvent(mEntry.notification,
+ StatsLog.BUBBLE_UICHANGED__ACTION__HEADER_GO_TO_APP);
} catch (PendingIntent.CanceledException e) {
Log.w(TAG, "Failed to send intent for bubble with key: "
+ (mEntry != null ? mEntry.key : " null entry"));
@@ -242,7 +348,11 @@
} else if (id == R.id.settings_button) {
Intent intent = getSettingsIntent(mEntry.notification.getPackageName(),
mEntry.notification.getUid());
- mStackView.collapseStack(() -> mContext.startActivity(intent));
+ mStackView.collapseStack(() -> {
+ mContext.startActivity(intent);
+ logBubbleClickEvent(mEntry.notification,
+ StatsLog.BUBBLE_UICHANGED__ACTION__HEADER_GO_TO_SETTINGS);
+ });
} else if (id == R.id.no_bubbles_button) {
setBubblesAllowed(false);
} else if (id == R.id.yes_bubbles_button) {
@@ -262,42 +372,96 @@
} else if (mOnBubbleBlockedListener != null) {
mOnBubbleBlockedListener.onBubbleBlocked(mEntry);
}
+ logBubbleClickEvent(mEntry.notification,
+ allowed ? StatsLog.BUBBLE_UICHANGED__ACTION__PERMISSION_OPT_IN :
+ StatsLog.BUBBLE_UICHANGED__ACTION__PERMISSION_OPT_OUT);
} catch (RemoteException e) {
Log.w(TAG, e);
}
}
/**
+ * Update appearance of the expanded view being displayed.
+ */
+ public void updateView() {
+ if (usingActivityView()
+ && mActivityView.getVisibility() == VISIBLE
+ && mActivityView.isAttachedToWindow()) {
+ mActivityView.onLocationChanged();
+ } else if (mNotifRow != null) {
+ applyRowState(mNotifRow);
+ }
+ }
+
+ /**
* Set the x position that the tip of the triangle should point to.
*/
- public void setPointerPosition(int x) {
+ public void setPointerPosition(float x) {
// Adjust for the pointer size
- x -= (mPointerView.getWidth() / 2);
+ x -= (mPointerView.getWidth() / 2f);
mPointerView.setTranslationX(x);
}
/**
- * Set the view to display for the expanded state. Passing null will clear the view.
+ * Removes and releases an ActivityView if one was previously created for this bubble.
*/
- public void setExpandedView(View view) {
- if (mExpandedView == view) {
+ public void destroyActivityView(ViewGroup tmpParent) {
+ if (mActivityView == null) {
return;
}
- if (mExpandedView != null) {
- removeView(mExpandedView);
+ if (!mActivityViewReady) {
+ // release not needed, never initialized?
+ mActivityView = null;
+ return;
}
- mExpandedView = view;
- if (mExpandedView != null) {
- addView(mExpandedView);
+ // HACK: release() will crash if the view is not attached.
+ if (!isAttachedToWindow()) {
+ mActivityView.setVisibility(View.GONE);
+ tmpParent.addView(this);
}
+
+ mActivityView.release();
+ ((ViewGroup) getParent()).removeView(this);
+ mActivityView = null;
+ mActivityViewReady = false;
}
- /**
- * @return the view containing the expanded content, can be null.
- */
- @Nullable
- public View getExpandedView() {
- return mExpandedView;
+ private boolean usingActivityView() {
+ return mBubbleIntent != null;
+ }
+
+ private void applyRowState(ExpandableNotificationRow view) {
+ view.reset();
+ view.setHeadsUp(false);
+ view.resetTranslation();
+ view.setOnKeyguard(false);
+ view.setOnAmbient(false);
+ view.setClipBottomAmount(0);
+ view.setClipTopAmount(0);
+ view.setContentTransformationAmount(0, false);
+ view.setIconsVisible(true);
+
+ // TODO - Need to reset this (and others) when view goes back in shade, leave for now
+ // view.setTopRoundness(1, false);
+ // view.setBottomRoundness(1, false);
+
+ ExpandableViewState viewState = view.getViewState();
+ viewState = viewState == null ? new ExpandableViewState() : viewState;
+ viewState.height = view.getIntrinsicHeight();
+ viewState.gone = false;
+ viewState.hidden = false;
+ viewState.dimmed = false;
+ viewState.dark = false;
+ viewState.alpha = 1f;
+ viewState.notGoneIndex = -1;
+ viewState.xTranslation = 0;
+ viewState.yTranslation = 0;
+ viewState.zTranslation = 0;
+ viewState.scaleX = 1;
+ viewState.scaleY = 1;
+ viewState.inShelf = true;
+ viewState.headsUpIsVisible = false;
+ viewState.applyToView(view);
}
private Intent getSettingsIntent(String packageName, final int appUid) {
@@ -309,6 +473,61 @@
return intent;
}
+ @Nullable
+ private PendingIntent getBubbleIntent(NotificationEntry entry) {
+ Notification notif = entry.notification.getNotification();
+ String packageName = entry.notification.getPackageName();
+ Notification.BubbleMetadata data = notif.getBubbleMetadata();
+ if (data != null && canLaunchInActivityView(data.getIntent(), true /* enableLogging */,
+ packageName)) {
+ return data.getIntent();
+ } else if (BubbleController.shouldUseContentIntent(mContext)
+ && canLaunchInActivityView(notif.contentIntent, false /* enableLogging */,
+ packageName)) {
+ return notif.contentIntent;
+ }
+ return null;
+ }
+
+ /**
+ * Whether an intent is properly configured to display in an {@link android.app.ActivityView}.
+ *
+ * @param intent the pending intent of the bubble.
+ * @param enableLogging whether bubble developer error should be logged.
+ * @param packageName the notification package name for this bubble.
+ * @return
+ */
+ private boolean canLaunchInActivityView(PendingIntent intent, boolean enableLogging,
+ String packageName) {
+ if (intent == null) {
+ return false;
+ }
+ ActivityInfo info =
+ intent.getIntent().resolveActivityInfo(mContext.getPackageManager(), 0);
+ if (info == null) {
+ if (enableLogging) {
+ StatsLog.write(StatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED, packageName,
+ BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__ACTIVITY_INFO_MISSING);
+ }
+ return false;
+ }
+ if (!ActivityInfo.isResizeableMode(info.resizeMode)) {
+ if (enableLogging) {
+ StatsLog.write(StatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED, packageName,
+ BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__ACTIVITY_INFO_NOT_RESIZABLE);
+ }
+ return false;
+ }
+ if (info.documentLaunchMode != DOCUMENT_LAUNCH_ALWAYS) {
+ if (enableLogging) {
+ StatsLog.write(StatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED, packageName,
+ BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__DOCUMENT_LAUNCH_NOT_ALWAYS);
+ }
+ return false;
+ }
+ return (info.flags & ActivityInfo.FLAG_ALLOW_EMBEDDED) != 0;
+ }
+
/**
* Listener that is notified when a bubble is blocked.
*/
@@ -318,4 +537,22 @@
*/
void onBubbleBlocked(NotificationEntry entry);
}
+
+ /**
+ * Logs bubble UI click event.
+ *
+ * @param notification the bubble notification that user is interacting with.
+ * @param action the user interaction enum.
+ */
+ private void logBubbleClickEvent(StatusBarNotification notification, int action) {
+ StatsLog.write(StatsLog.BUBBLE_UI_CHANGED,
+ notification.getPackageName(),
+ notification.getNotification().getChannelId(),
+ notification.getId(),
+ mStackView.getBubbleIndex(mStackView.getExpandedBubble()),
+ mStackView.getBubbleCount(),
+ action,
+ mStackView.getNormalizedXPosition(),
+ mStackView.getNormalizedYPosition());
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
index f6f3fa6..8bc83d4 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
@@ -19,7 +19,6 @@
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
-import android.app.ActivityView;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Outline;
@@ -33,13 +32,11 @@
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
-import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.ViewTreeObserver;
import android.view.WindowInsets;
import android.view.WindowManager;
import android.widget.FrameLayout;
-import android.widget.LinearLayout;
import androidx.annotation.MainThread;
import androidx.annotation.Nullable;
@@ -54,8 +51,6 @@
import com.android.systemui.bubbles.animation.PhysicsAnimationLayout;
import com.android.systemui.bubbles.animation.StackAnimationController;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
-import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
-import com.android.systemui.statusbar.notification.stack.ExpandableViewState;
import java.math.BigDecimal;
import java.math.RoundingMode;
@@ -95,22 +90,27 @@
private StackAnimationController mStackAnimationController;
private ExpandedAnimationController mExpandedAnimationController;
- private BubbleExpandedView mExpandedViewContainer;
+ private FrameLayout mExpandedViewContainer;
+
+ private BubbleData mBubbleData;
private int mBubbleSize;
private int mBubblePadding;
private int mExpandedAnimateXDistance;
private int mExpandedAnimateYDistance;
+ private Bubble mExpandedBubble;
private boolean mIsExpanded;
- private int mExpandedBubbleHeight;
+
private BubbleTouchHandler mTouchHandler;
- private BubbleView mExpandedBubble;
private BubbleController.BubbleExpandListener mExpandListener;
+ private BubbleExpandedView.OnBubbleBlockedListener mBlockedListener;
private boolean mViewUpdatedRequested = false;
private boolean mIsAnimating = false;
+ private LayoutInflater mInflater;
+
// Used for determining view / touch intersection
int[] mTempLoc = new int[2];
RectF mTempRect = new RectF();
@@ -142,7 +142,9 @@
public BubbleStackView(Context context) {
super(context);
+ mBubbleData = BubbleData.getInstance();
+ mInflater = LayoutInflater.from(context);
mTouchHandler = new BubbleTouchHandler(context);
setOnTouchListener(mTouchHandler);
@@ -154,7 +156,6 @@
mExpandedAnimateYDistance =
res.getDimensionPixelSize(R.dimen.bubble_expanded_animate_y_distance);
- mExpandedBubbleHeight = res.getDimensionPixelSize(R.dimen.bubble_expanded_default_height);
mDisplaySize = new Point();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getSize(mDisplaySize);
@@ -174,9 +175,7 @@
mBubbleContainer.setClipChildren(false);
addView(mBubbleContainer, new FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT));
- mExpandedViewContainer = (BubbleExpandedView)
- LayoutInflater.from(context).inflate(R.layout.bubble_expanded_view,
- this /* parent */, false /* attachToRoot */);
+ mExpandedViewContainer = new FrameLayout(context);
mExpandedViewContainer.setElevation(elevation);
mExpandedViewContainer.setPadding(padding, padding, padding, padding);
mExpandedViewContainer.setClipChildren(false);
@@ -218,6 +217,17 @@
}
/**
+ * Updates the visibility of the 'dot' indicating an update on the bubble.
+ * @param key the {@link NotificationEntry#key} associated with the bubble.
+ */
+ public void updateDotVisibility(String key) {
+ Bubble b = mBubbleData.getBubble(key);
+ if (b != null) {
+ b.iconView.updateDotVisibility();
+ }
+ }
+
+ /**
* Sets the listener to notify when the bubble stack is expanded.
*/
public void setExpandListener(BubbleController.BubbleExpandListener listener) {
@@ -228,7 +238,10 @@
* Sets the listener to notify when a bubble is blocked.
*/
public void setOnBlockedListener(BubbleExpandedView.OnBubbleBlockedListener listener) {
- mExpandedViewContainer.setOnBlockedListener(listener);
+ mBlockedListener = listener;
+ for (Bubble b : mBubbleData.getBubbles()) {
+ b.expandedView.setOnBlockedListener(mBlockedListener);
+ }
}
/**
@@ -241,19 +254,29 @@
/**
* The {@link BubbleView} that is expanded, null if one does not exist.
*/
- public BubbleView getExpandedBubble() {
+ BubbleView getExpandedBubbleView() {
+ return mExpandedBubble != null ? mExpandedBubble.iconView : null;
+ }
+
+ /**
+ * The {@link Bubble} that is expanded, null if one does not exist.
+ */
+ Bubble getExpandedBubble() {
return mExpandedBubble;
}
/**
* Sets the bubble that should be expanded and expands if needed.
+ *
+ * @param key the {@link NotificationEntry#key} associated with the bubble to expand.
*/
- public void setExpandedBubble(BubbleView bubbleToExpand) {
+ void setExpandedBubble(String key) {
+ Bubble bubbleToExpand = mBubbleData.getBubble(key);
if (mIsExpanded && !bubbleToExpand.equals(mExpandedBubble)) {
// Previously expanded, notify that this bubble is no longer expanded
- notifyExpansionChanged(mExpandedBubble, false /* expanded */);
+ notifyExpansionChanged(mExpandedBubble.entry, false /* expanded */);
}
- BubbleView prevBubble = mExpandedBubble;
+ Bubble prevBubble = mExpandedBubble;
mExpandedBubble = bubbleToExpand;
if (!mIsExpanded) {
// If we weren't previously expanded we should animate open.
@@ -268,8 +291,8 @@
logBubbleEvent(prevBubble, StatsLog.BUBBLE_UICHANGED__ACTION__COLLAPSED);
logBubbleEvent(mExpandedBubble, StatsLog.BUBBLE_UICHANGED__ACTION__EXPANDED);
}
- mExpandedBubble.getEntry().setShowInShadeWhenBubble(false);
- notifyExpansionChanged(mExpandedBubble, true /* expanded */);
+ mExpandedBubble.entry.setShowInShadeWhenBubble(false);
+ notifyExpansionChanged(mExpandedBubble.entry, true /* expanded */);
}
/**
@@ -280,7 +303,7 @@
for (int i = 0; i < mBubbleContainer.getChildCount(); i++) {
BubbleView bv = (BubbleView) mBubbleContainer.getChildAt(i);
if (entry.equals(bv.getEntry())) {
- setExpandedBubble(bv);
+ setExpandedBubble(entry.key);
}
}
}
@@ -288,48 +311,67 @@
/**
* Adds a bubble to the top of the stack.
*
- * @param bubbleView the view to add to the stack.
+ * @param entry the notification to add to the stack of bubbles.
*/
- public void addBubble(BubbleView bubbleView) {
- mBubbleContainer.addView(bubbleView, 0,
+ public void addBubble(NotificationEntry entry) {
+ Bubble b = new Bubble(entry, mInflater, this /* stackView */, mBlockedListener);
+ mBubbleData.addBubble(b);
+
+ mBubbleContainer.addView(b.iconView, 0,
new FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
- ViewClippingUtil.setClippingDeactivated(bubbleView, true, mClippingParameters);
+ ViewClippingUtil.setClippingDeactivated(b.iconView, true, mClippingParameters);
+
requestUpdate();
- logBubbleEvent(bubbleView, StatsLog.BUBBLE_UICHANGED__ACTION__POSTED);
+ logBubbleEvent(b, StatsLog.BUBBLE_UICHANGED__ACTION__POSTED);
}
/**
* Remove a bubble from the stack.
*/
- public void removeBubble(BubbleView bubbleView) {
- int removedIndex = mBubbleContainer.indexOfChild(bubbleView);
- mBubbleContainer.removeView(bubbleView);
+ public void removeBubble(String key) {
+ Bubble b = mBubbleData.removeBubble(key);
+ if (b == null) {
+ return;
+ }
+ b.entry.setBubbleDismissed(true);
+
+ // Remove it from the views
+ int removedIndex = mBubbleContainer.indexOfChild(b.iconView);
+ b.expandedView.destroyActivityView(this /* tmpParent */);
+ mBubbleContainer.removeView(b.iconView);
+
int bubbleCount = mBubbleContainer.getChildCount();
if (bubbleCount == 0) {
// If no bubbles remain, collapse the entire stack.
collapseStack();
return;
- } else if (bubbleView.equals(mExpandedBubble)) {
+ } else if (b.equals(mExpandedBubble)) {
// Was the current bubble just removed?
// If we have other bubbles and are expanded go to the next one or previous
// if the bubble removed was last
int nextIndex = bubbleCount > removedIndex ? removedIndex : bubbleCount - 1;
BubbleView expandedBubble = (BubbleView) mBubbleContainer.getChildAt(nextIndex);
if (mIsExpanded) {
- setExpandedBubble(expandedBubble);
+ setExpandedBubble(expandedBubble.getKey());
} else {
mExpandedBubble = null;
}
}
- logBubbleEvent(bubbleView, StatsLog.BUBBLE_UICHANGED__ACTION__DISMISSED);
+ logBubbleEvent(b, StatsLog.BUBBLE_UICHANGED__ACTION__DISMISSED);
}
/**
* Dismiss the stack of bubbles.
*/
public void stackDismissed() {
+ for (Bubble bubble : mBubbleData.getBubbles()) {
+ bubble.entry.setBubbleDismissed(true);
+ bubble.expandedView.destroyActivityView(this /* tmpParent */);
+ }
+ mBubbleData.clear();
collapseStack();
mBubbleContainer.removeAllViews();
+ mExpandedViewContainer.removeAllViews();
logBubbleEvent(null /* no bubble associated with bubble stack dismiss */,
StatsLog.BUBBLE_UICHANGED__ACTION__STACK_DISMISSED);
}
@@ -337,25 +379,26 @@
/**
* Updates a bubble in the stack.
*
- * @param bubbleView the view to update in the stack.
- * @param entry the entry to update it with.
+ * @param entry the entry to update in the stack.
* @param updatePosition whether this bubble should be moved to top of the stack.
*/
- public void updateBubble(BubbleView bubbleView, NotificationEntry entry,
- boolean updatePosition) {
- bubbleView.update(entry);
+ public void updateBubble(NotificationEntry entry, boolean updatePosition) {
+ Bubble b = mBubbleData.getBubble(entry.key);
+ b.iconView.update(entry);
+ // TODO: should also update the expanded view here (e.g. height change)
+
if (updatePosition && !mIsExpanded) {
// If alerting it gets promoted to top of the stack.
- if (mBubbleContainer.indexOfChild(bubbleView) != 0) {
- mBubbleContainer.moveViewTo(bubbleView, 0);
+ if (mBubbleContainer.indexOfChild(b.iconView) != 0) {
+ mBubbleContainer.moveViewTo(b.iconView, 0);
}
requestUpdate();
}
- if (mIsExpanded && bubbleView.equals(mExpandedBubble)) {
+ if (mIsExpanded && entry.equals(mExpandedBubble.entry)) {
entry.setShowInShadeWhenBubble(false);
requestUpdate();
}
- logBubbleEvent(bubbleView, StatsLog.BUBBLE_UICHANGED__ACTION__UPDATED);
+ logBubbleEvent(b, StatsLog.BUBBLE_UICHANGED__ACTION__UPDATED);
}
/**
@@ -393,7 +436,7 @@
if (mIsExpanded) {
// TODO: Save opened bubble & move it to top of stack
animateExpansion(false /* shouldExpand */);
- notifyExpansionChanged(mExpandedBubble, mIsExpanded);
+ notifyExpansionChanged(mExpandedBubble.entry, mIsExpanded);
logBubbleEvent(mExpandedBubble, StatsLog.BUBBLE_UICHANGED__ACTION__COLLAPSED);
}
}
@@ -412,8 +455,8 @@
@MainThread
public void expandStack() {
if (!mIsExpanded) {
- mExpandedBubble = getTopBubble();
- setExpandedBubble(mExpandedBubble);
+ String expandedBubbleKey = getBubbleAt(0).getKey();
+ setExpandedBubble(expandedBubbleKey);
logBubbleEvent(mExpandedBubble, StatsLog.BUBBLE_UICHANGED__ACTION__STACK_EXPANDED);
}
}
@@ -459,7 +502,8 @@
final float yStart = Math.min(
mStackAnimationController.getStackPosition().y,
mExpandedAnimateYDistance);
- final float yDest = getStatusBarHeight() + mExpandedBubble.getHeight() + mBubblePadding;
+ final float yDest = getStatusBarHeight()
+ + mExpandedBubble.iconView.getHeight() + mBubblePadding;
if (shouldExpand) {
mExpandedViewContainer.setTranslationX(xStart);
@@ -484,17 +528,12 @@
+ mBubbleContainer.getPaddingStart();
}
- private void notifyExpansionChanged(BubbleView bubbleView, boolean expanded) {
+ private void notifyExpansionChanged(NotificationEntry entry, boolean expanded) {
if (mExpandListener != null) {
- NotificationEntry entry = bubbleView != null ? bubbleView.getEntry() : null;
mExpandListener.onBubbleExpandChanged(expanded, entry != null ? entry.key : null);
}
}
- private BubbleView getTopBubble() {
- return getBubbleAt(0);
- }
-
/** Return the BubbleView at the given index from the bubble container. */
public BubbleView getBubbleAt(int i) {
return mBubbleContainer.getChildCount() > i
@@ -665,31 +704,10 @@
}
private void updateExpandedBubble() {
- if (mExpandedBubble == null) {
- return;
- }
-
- mExpandedViewContainer.setEntry(mExpandedBubble.getEntry(), this);
- if (mExpandedBubble.hasAppOverlayIntent()) {
- // Bubble with activity view expanded state
- ActivityView expandedView = mExpandedBubble.getActivityView();
- // XXX: gets added to linear layout
- expandedView.setLayoutParams(new LinearLayout.LayoutParams(
- ViewGroup.LayoutParams.MATCH_PARENT, mExpandedBubbleHeight));
-
- mExpandedViewContainer.setExpandedView(expandedView);
- } else {
- // Bubble with notification view expanded state
- ExpandableNotificationRow row = mExpandedBubble.getRowView();
- if (row.getParent() != null) {
- // Row might still be in the shade when we expand
- ((ViewGroup) row.getParent()).removeView(row);
- }
- if (mIsExpanded) {
- mExpandedViewContainer.setExpandedView(row);
- } else {
- mExpandedViewContainer.setExpandedView(null);
- }
+ mExpandedViewContainer.removeAllViews();
+ if (mExpandedBubble != null && mIsExpanded) {
+ mExpandedViewContainer.addView(mExpandedBubble.expandedView);
+ mExpandedViewContainer.setVisibility(mIsExpanded ? VISIBLE : GONE);
}
}
@@ -697,18 +715,10 @@
Log.d(TAG, "applyCurrentState: mIsExpanded=" + mIsExpanded);
mExpandedViewContainer.setVisibility(mIsExpanded ? VISIBLE : GONE);
- if (!mIsExpanded) {
- mExpandedViewContainer.setExpandedView(null);
- } else {
- View expandedView = mExpandedViewContainer.getExpandedView();
- if (expandedView instanceof ActivityView) {
- if (expandedView.isAttachedToWindow()) {
- ((ActivityView) expandedView).onLocationChanged();
- }
- } else {
- applyRowState(mExpandedBubble.getRowView());
- }
+ if (mIsExpanded) {
+ mExpandedBubble.expandedView.updateView();
}
+
int bubbsCount = mBubbleContainer.getChildCount();
for (int i = 0; i < bubbsCount; i++) {
BubbleView bv = (BubbleView) mBubbleContainer.getChildAt(i);
@@ -730,68 +740,34 @@
private void updatePointerPosition() {
if (mExpandedBubble != null) {
- float pointerPosition = mExpandedBubble.getPosition().x
- + (mExpandedBubble.getWidth() / 2f);
- mExpandedViewContainer.setPointerPosition((int) pointerPosition);
+ float pointerPosition = mExpandedBubble.iconView.getPosition().x
+ + (mExpandedBubble.iconView.getWidth() / 2f);
+ mExpandedBubble.expandedView.setPointerPosition(pointerPosition);
}
}
- private void applyRowState(ExpandableNotificationRow view) {
- view.reset();
- view.setHeadsUp(false);
- view.resetTranslation();
- view.setOnKeyguard(false);
- view.setOnAmbient(false);
- view.setClipBottomAmount(0);
- view.setClipTopAmount(0);
- view.setContentTransformationAmount(0, false);
- view.setIconsVisible(true);
-
- // TODO - Need to reset this (and others) when view goes back in shade, leave for now
- // view.setTopRoundness(1, false);
- // view.setBottomRoundness(1, false);
-
- ExpandableViewState viewState = view.getViewState();
- viewState = viewState == null ? new ExpandableViewState() : viewState;
- viewState.height = view.getIntrinsicHeight();
- viewState.gone = false;
- viewState.hidden = false;
- viewState.dimmed = false;
- viewState.dark = false;
- viewState.alpha = 1f;
- viewState.notGoneIndex = -1;
- viewState.xTranslation = 0;
- viewState.yTranslation = 0;
- viewState.zTranslation = 0;
- viewState.scaleX = 1;
- viewState.scaleY = 1;
- viewState.inShelf = true;
- viewState.headsUpIsVisible = false;
- viewState.applyToView(view);
- }
-
/**
* @return the number of bubbles in the stack view.
*/
- private int getBubbleCount() {
+ public int getBubbleCount() {
return mBubbleContainer.getChildCount();
}
/**
* Finds the bubble index within the stack.
*
- * @param bubbleView the view of the bubble.
+ * @param bubble the bubble to look up.
* @return the index of the bubble view within the bubble stack. The range of the position
* is between 0 and the bubble count minus 1.
*/
- private int getBubbleIndex(BubbleView bubbleView) {
- return mBubbleContainer.indexOfChild(bubbleView);
+ int getBubbleIndex(Bubble bubble) {
+ return mBubbleContainer.indexOfChild(bubble.iconView);
}
/**
* @return the normalized x-axis position of the bubble stack rounded to 4 decimal places.
*/
- private float getNormalizedXPosition() {
+ public float getNormalizedXPosition() {
return new BigDecimal(getPosition().x / mDisplaySize.x)
.setScale(4, RoundingMode.CEILING.HALF_UP)
.floatValue();
@@ -800,7 +776,7 @@
/**
* @return the normalized y-axis position of the bubble stack rounded to 4 decimal places.
*/
- private float getNormalizedYPosition() {
+ public float getNormalizedYPosition() {
return new BigDecimal(getPosition().y / mDisplaySize.y)
.setScale(4, RoundingMode.CEILING.HALF_UP)
.floatValue();
@@ -813,7 +789,7 @@
* the user interaction is not specific to one bubble.
* @param action the user interaction enum.
*/
- private void logBubbleEvent(@Nullable BubbleView bubble, int action) {
+ private void logBubbleEvent(@Nullable Bubble bubble, int action) {
if (bubble == null) {
StatsLog.write(StatsLog.BUBBLE_UI_CHANGED,
null /* package name */,
@@ -825,7 +801,7 @@
getNormalizedXPosition(),
getNormalizedYPosition());
} else {
- StatusBarNotification notification = bubble.getEntry().notification;
+ StatusBarNotification notification = bubble.entry.notification;
StatsLog.write(StatsLog.BUBBLE_UI_CHANGED,
notification.getPackageName(),
notification.getNotification().getChannelId(),
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleTouchHandler.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleTouchHandler.java
index 22cd2fc..7d3c0f8 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleTouchHandler.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleTouchHandler.java
@@ -188,7 +188,7 @@
} else {
stack.onBubbleDragFinish(mBubbleDraggingOut, x, y, velX, velY);
}
- } else if (floatingView.equals(stack.getExpandedBubble())) {
+ } else if (floatingView.equals(stack.getExpandedBubbleView())) {
stack.collapseStack();
} else if (isBubbleStack) {
if (stack.isExpanded()) {
@@ -197,7 +197,7 @@
stack.expandStack();
}
} else {
- stack.setExpandedBubble((BubbleView) floatingView);
+ stack.setExpandedBubble(((BubbleView) floatingView).getKey());
}
cleanUpDismissTarget();
mVelocityTracker.recycle();
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleView.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleView.java
index 74ddc8f..1a4b199 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleView.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleView.java
@@ -17,13 +17,9 @@
package com.android.systemui.bubbles;
import android.annotation.Nullable;
-import android.app.ActivityView;
import android.app.Notification;
-import android.app.PendingIntent;
import android.content.Context;
import android.graphics.Color;
-import android.graphics.Insets;
-import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
@@ -31,16 +27,10 @@
import android.graphics.drawable.InsetDrawable;
import android.graphics.drawable.LayerDrawable;
import android.util.AttributeSet;
-import android.util.Log;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.WindowInsets;
import android.widget.FrameLayout;
-import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.internal.graphics.ColorUtils;
-import com.android.systemui.Dependency;
import com.android.systemui.Interpolators;
import com.android.systemui.R;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
@@ -62,11 +52,6 @@
private int mIconInset;
private NotificationEntry mEntry;
- private PendingIntent mAppOverlayIntent;
- private BubbleController mBubbleController;
- private ActivityView mActivityView;
- private boolean mActivityViewReady;
- private boolean mActivityViewStarted;
public BubbleView(Context context) {
this(context, null);
@@ -86,7 +71,6 @@
// XXX: can this padding just be on the view and we look it up?
mPadding = getResources().getDimensionPixelSize(R.dimen.bubble_view_padding);
mIconInset = getResources().getDimensionPixelSize(R.dimen.bubble_icon_inset);
- mBubbleController = Dependency.get(BubbleController.class);
}
@Override
@@ -168,7 +152,6 @@
updateViews();
}
-
/**
* @return the {@link ExpandableNotificationRow} view to display notification content when the
* bubble is expanded.
@@ -235,88 +218,6 @@
return ColorUtils.blendARGB(defaultTint, Color.WHITE, WHITE_SCRIM_ALPHA);
}
- /**
- * @return a view used to display app overlay content when expanded.
- */
- public ActivityView getActivityView() {
- if (mActivityView == null) {
- mActivityView = new ActivityView(mContext, null /* attrs */, 0 /* defStyle */,
- true /* singleTaskInstance */);
- Log.d(TAG, "[getActivityView] created: " + mActivityView);
- mActivityView.setCallback(new ActivityView.StateCallback() {
- @Override
- public void onActivityViewReady(ActivityView view) {
- mActivityViewReady = true;
- mActivityView.startActivity(mAppOverlayIntent);
- }
-
- @Override
- public void onActivityViewDestroyed(ActivityView view) {
- mActivityViewReady = false;
- }
-
- /**
- * This is only called for tasks on this ActivityView, which is also set to
- * single-task mode -- meaning never more than one task on this display. If a task
- * is being removed, it's the top Activity finishing and this bubble should
- * be removed or collapsed.
- */
- @Override
- public void onTaskRemovalStarted(int taskId) {
- if (mEntry != null) {
- // Must post because this is called from a binder thread.
- post(() -> mBubbleController.removeBubble(mEntry.key));
- }
- }
- });
- mActivityView.setOnApplyWindowInsetsListener((View view, WindowInsets insets) -> {
- ActivityView activityView = (ActivityView) view;
- // Here we assume that the position of the ActivityView on the screen
- // remains regardless of IME status. When we move ActivityView, the
- // forwardedInsets should be computed not against the current location
- // and size, but against the post-moved location and size.
- Point displaySize = new Point();
- view.getContext().getDisplay().getSize(displaySize);
- int[] windowLocation = view.getLocationOnScreen();
- final int windowBottom = windowLocation[1] + view.getHeight();
- final int keyboardHeight = insets.getSystemWindowInsetBottom()
- - insets.getStableInsetBottom();
- final int insetsBottom = Math.max(0,
- windowBottom + keyboardHeight - displaySize.y);
- activityView.setForwardedInsets(Insets.of(0, 0, 0, insetsBottom));
- return view.onApplyWindowInsets(insets);
- });
-
- }
- return mActivityView;
- }
-
- /**
- * Removes and releases an ActivityView if one was previously created for this bubble.
- */
- public void destroyActivityView(ViewGroup tmpParent) {
- if (mActivityView == null) {
- return;
- }
- if (!mActivityViewReady) {
- // release not needed, never initialized?
- mActivityView = null;
- return;
- }
- // HACK: release() will crash if the view is not attached.
- if (!mActivityView.isAttachedToWindow()) {
- mActivityView.setVisibility(View.GONE);
- tmpParent.addView(mActivityView, new LinearLayout.LayoutParams(
- ViewGroup.LayoutParams.MATCH_PARENT,
- ViewGroup.LayoutParams.MATCH_PARENT));
- }
-
- mActivityView.release();
-
- ((ViewGroup) mActivityView.getParent()).removeView(mActivityView);
- mActivityView = null;
- }
-
@Override
public void setPosition(float x, float y) {
setPositionX(x);
@@ -337,20 +238,4 @@
public PointF getPosition() {
return new PointF(getTranslationX(), getTranslationY());
}
-
- /**
- * @return whether an ActivityView should be used to display the content of this Bubble
- */
- public boolean hasAppOverlayIntent() {
- return mAppOverlayIntent != null;
- }
-
- public PendingIntent getAppOverlayIntent() {
- return mAppOverlayIntent;
-
- }
-
- public void setBubbleIntent(PendingIntent intent) {
- mAppOverlayIntent = intent;
- }
}
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeReceiver.java b/packages/SystemUI/src/com/android/systemui/doze/DozeReceiver.java
index 4a2e06c..f5cf149 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeReceiver.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeReceiver.java
@@ -25,9 +25,4 @@
* Invoked every time a minute is elapsed in doze mode
*/
void dozeTimeTick();
-
- /**
- * When view is double tapped in doze mode.
- */
- void onDozeDoubleTap();
}
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java b/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java
index 873fbc2..e207cb1 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java
@@ -161,7 +161,8 @@
} else {
mDozeHost.extendPulse();
}
- }, sensorPerformedProxCheck || mDockManager.isDocked(), pulseReason);
+ }, sensorPerformedProxCheck
+ || (mDockManager != null && mDockManager.isDocked()), pulseReason);
}
if (isPickup) {
@@ -224,7 +225,9 @@
case INITIALIZED:
mBroadcastReceiver.register(mContext);
mDozeHost.addCallback(mHostCallback);
- mDockManager.addListener(mDockEventListener);
+ if (mDockManager != null) {
+ mDockManager.addListener(mDockEventListener);
+ }
checkTriggersAtInit();
break;
case DOZE:
@@ -250,7 +253,9 @@
case FINISH:
mBroadcastReceiver.unregister(mContext);
mDozeHost.removeCallback(mHostCallback);
- mDockManager.removeListener(mDockEventListener);
+ if (mDockManager != null) {
+ mDockManager.removeListener(mDockEventListener);
+ }
mDozeSensors.setListening(false);
mDozeSensors.setProxListening(false);
break;
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardSliceProvider.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardSliceProvider.java
index 684175c..85d975f 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardSliceProvider.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardSliceProvider.java
@@ -25,7 +25,9 @@
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
+import android.graphics.Rect;
import android.graphics.Typeface;
+import android.graphics.drawable.Drawable;
import android.graphics.drawable.Icon;
import android.icu.text.DateFormat;
import android.icu.text.DisplayContext;
@@ -35,10 +37,13 @@
import android.os.Trace;
import android.provider.Settings;
import android.service.notification.ZenModeConfig;
-import android.text.Spannable;
import android.text.SpannableStringBuilder;
+import android.text.Spanned;
import android.text.TextUtils;
+import android.text.style.DynamicDrawableSpan;
+import android.text.style.ImageSpan;
import android.text.style.StyleSpan;
+import android.util.MathUtils;
import androidx.core.graphics.drawable.IconCompat;
import androidx.slice.Slice;
@@ -72,6 +77,8 @@
private static final StyleSpan BOLD_STYLE = new StyleSpan(Typeface.BOLD);
public static final String KEYGUARD_SLICE_URI = "content://com.android.systemui.keyguard/main";
+ private static final String KEYGUARD_HEADER_URI =
+ "content://com.android.systemui.keyguard/header";
public static final String KEYGUARD_DATE_URI = "content://com.android.systemui.keyguard/date";
public static final String KEYGUARD_NEXT_ALARM_URI =
"content://com.android.systemui.keyguard/alarm";
@@ -90,6 +97,7 @@
private static KeyguardSliceProvider sInstance;
protected final Uri mSliceUri;
+ protected final Uri mHeaderUri;
protected final Uri mDateUri;
protected final Uri mAlarmUri;
protected final Uri mDndUri;
@@ -163,6 +171,7 @@
KeyguardSliceProvider(Handler handler) {
mHandler = handler;
mSliceUri = Uri.parse(KEYGUARD_SLICE_URI);
+ mHeaderUri = Uri.parse(KEYGUARD_HEADER_URI);
mDateUri = Uri.parse(KEYGUARD_DATE_URI);
mAlarmUri = Uri.parse(KEYGUARD_NEXT_ALARM_URI);
mDndUri = Uri.parse(KEYGUARD_DND_URI);
@@ -213,26 +222,32 @@
protected void addMediaLocked(ListBuilder listBuilder) {
if (mMediaMetaData != null) {
SpannableStringBuilder builder = new SpannableStringBuilder();
+
+ Icon notificationIcon = mMediaManager == null ? null : mMediaManager.getMediaIcon();
+ if (notificationIcon != null) {
+ Drawable drawable = notificationIcon.loadDrawable(getContext());
+ Rect mediaBounds = new Rect(0 /* left */, 0 /* top */,
+ drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
+ int iconHeaderSize = getContext().getResources()
+ .getDimensionPixelSize(R.dimen.header_icon_size);
+ MathUtils.fitRect(mediaBounds, iconHeaderSize);
+ drawable.setBounds(mediaBounds);
+ builder.append("# ");
+ builder.setSpan(new ImageSpan(drawable, DynamicDrawableSpan.ALIGN_CENTER),
+ 0 /* start */, 1 /* end */, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
+ }
+
CharSequence title = mMediaMetaData.getText(MediaMetadata.METADATA_KEY_TITLE);
if (TextUtils.isEmpty(title)) {
title = getContext().getResources().getString(R.string.music_controls_no_title);
}
builder.append(title);
- builder.setSpan(BOLD_STYLE, 0, title.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
+ listBuilder.setHeader(new ListBuilder.HeaderBuilder(mHeaderUri).setTitle(builder));
CharSequence album = mMediaMetaData.getText(MediaMetadata.METADATA_KEY_ARTIST);
if (!TextUtils.isEmpty(album)) {
- builder.append(" ").append(album);
+ listBuilder.addRow(new RowBuilder(mMediaUri).setTitle(album));
}
-
- RowBuilder mediaBuilder = new RowBuilder(mMediaUri).setTitle(builder);
- Icon notificationIcon = mMediaManager == null ? null : mMediaManager.getMediaIcon();
- if (notificationIcon != null) {
- IconCompat icon = IconCompat.createFromIcon(notificationIcon);
- mediaBuilder.addEndItem(icon, ListBuilder.ICON_IMAGE);
- }
-
- listBuilder.addRow(mediaBuilder);
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/media/RingtonePlayer.java b/packages/SystemUI/src/com/android/systemui/media/RingtonePlayer.java
index ddd9cbf..aebadf9 100644
--- a/packages/SystemUI/src/com/android/systemui/media/RingtonePlayer.java
+++ b/packages/SystemUI/src/com/android/systemui/media/RingtonePlayer.java
@@ -16,6 +16,7 @@
package com.android.systemui.media;
+import android.annotation.Nullable;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
@@ -24,6 +25,7 @@
import android.media.IAudioService;
import android.media.IRingtonePlayer;
import android.media.Ringtone;
+import android.media.VolumeShaper;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
@@ -78,11 +80,16 @@
private final Ringtone mRingtone;
public Client(IBinder token, Uri uri, UserHandle user, AudioAttributes aa) {
+ this(token, uri, user, aa, null);
+ }
+
+ Client(IBinder token, Uri uri, UserHandle user, AudioAttributes aa,
+ @Nullable VolumeShaper.Configuration volumeShaperConfig) {
mToken = token;
mRingtone = new Ringtone(getContextForUser(user), false);
mRingtone.setAudioAttributes(aa);
- mRingtone.setUri(uri);
+ mRingtone.setUri(uri, volumeShaperConfig);
}
@Override
@@ -99,6 +106,12 @@
@Override
public void play(IBinder token, Uri uri, AudioAttributes aa, float volume, boolean looping)
throws RemoteException {
+ playWithVolumeShaping(token, uri, aa, volume, looping, null);
+ }
+ @Override
+ public void playWithVolumeShaping(IBinder token, Uri uri, AudioAttributes aa, float volume,
+ boolean looping, @Nullable VolumeShaper.Configuration volumeShaperConfig)
+ throws RemoteException {
if (LOGD) {
Log.d(TAG, "play(token=" + token + ", uri=" + uri + ", uid="
+ Binder.getCallingUid() + ")");
@@ -108,7 +121,7 @@
client = mClients.get(token);
if (client == null) {
final UserHandle user = Binder.getCallingUserHandle();
- client = new Client(token, uri, user, aa);
+ client = new Client(token, uri, user, aa, volumeShaperConfig);
token.linkToDeath(client, 0);
mClients.put(token, client);
}
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipMotionHelper.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipMotionHelper.java
index 82aa473..9c65994 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/phone/PipMotionHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipMotionHelper.java
@@ -79,6 +79,7 @@
private static final int MSG_RESIZE_IMMEDIATE = 1;
private static final int MSG_RESIZE_ANIMATE = 2;
+ private static final int MSG_OFFSET_ANIMATE = 3;
private Context mContext;
private IActivityManager mActivityManager;
@@ -360,9 +361,20 @@
/**
* Animates the PiP to offset it from the IME or shelf.
*/
- void animateToOffset(Rect toBounds) {
+ void animateToOffset(Rect originalBounds, int offset) {
cancelAnimations();
- resizeAndAnimatePipUnchecked(toBounds, SHIFT_DURATION);
+ adjustAndAnimatePipOffset(originalBounds, offset, SHIFT_DURATION);
+ }
+
+ private void adjustAndAnimatePipOffset(Rect originalBounds, int offset, int duration) {
+ if (offset == 0) {
+ return;
+ }
+ SomeArgs args = SomeArgs.obtain();
+ args.arg1 = originalBounds;
+ args.argi1 = offset;
+ args.argi2 = duration;
+ mHandler.sendMessage(mHandler.obtainMessage(MSG_OFFSET_ANIMATE, args));
}
/**
@@ -549,6 +561,31 @@
return true;
}
+ case MSG_OFFSET_ANIMATE: {
+ SomeArgs args = (SomeArgs) msg.obj;
+ Rect originalBounds = (Rect) args.arg1;
+ final int offset = args.argi1;
+ final int duration = args.argi2;
+ try {
+ StackInfo stackInfo = mActivityTaskManager.getStackInfo(
+ WINDOWING_MODE_PINNED, ACTIVITY_TYPE_UNDEFINED);
+ if (stackInfo == null) {
+ // In the case where we've already re-expanded or dismissed the PiP, then
+ // just skip the resize
+ return true;
+ }
+
+ mActivityTaskManager.offsetPinnedStackBounds(stackInfo.stackId, originalBounds,
+ 0/* xOffset */, offset, duration);
+ Rect toBounds = new Rect(originalBounds);
+ toBounds.offset(0, offset);
+ mBounds.set(toBounds);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Could not animate offset pinned stack with offset: " + offset, e);
+ }
+ return true;
+ }
+
default:
return false;
}
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java
index 6a9f24c..cef1b6b 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java
@@ -346,12 +346,11 @@
}
private void animateToOffset(Rect animatingBounds, Rect toAdjustedBounds) {
- final Rect bounds = new Rect(animatingBounds);
- bounds.offset(0, toAdjustedBounds.bottom - bounds.top);
+ int offset = toAdjustedBounds.bottom - animatingBounds.top;
// In landscape mode, PIP window can go offset while launching IME. We want to align the
// the top of the PIP window with the top of the movement bounds in that case.
- bounds.offset(0, Math.max(0, mMovementBounds.top - bounds.top));
- mMotionHelper.animateToOffset(bounds);
+ offset += Math.max(0, mMovementBounds.top - animatingBounds.top);
+ mMotionHelper.animateToOffset(animatingBounds, offset);
}
private void onRegistrationChanged(boolean isRegistered) {
diff --git a/packages/SystemUI/src/com/android/systemui/power/PowerUI.java b/packages/SystemUI/src/com/android/systemui/power/PowerUI.java
index f054345..c43f572 100644
--- a/packages/SystemUI/src/com/android/systemui/power/PowerUI.java
+++ b/packages/SystemUI/src/com/android/systemui/power/PowerUI.java
@@ -54,6 +54,7 @@
import java.io.PrintWriter;
import java.time.Duration;
import java.util.Arrays;
+import java.util.concurrent.Future;
public class PowerUI extends SystemUI {
static final String TAG = "PowerUI";
@@ -80,6 +81,7 @@
private Estimate mLastEstimate;
private boolean mLowWarningShownThisChargeCycle;
private boolean mSevereWarningShownThisChargeCycle;
+ private Future mLastShowWarningTask;
private int mLowBatteryAlertCloseLevel;
private final int[] mLowBatteryReminderLevels = new int[2];
@@ -247,7 +249,10 @@
}
// Show the correct version of low battery warning if needed
- ThreadUtils.postOnBackgroundThread(() -> {
+ if (mLastShowWarningTask != null) {
+ mLastShowWarningTask.cancel(true);
+ }
+ mLastShowWarningTask = ThreadUtils.postOnBackgroundThread(() -> {
maybeShowBatteryWarning(
oldBatteryLevel, plugged, oldPlugged, oldBucket, bucket);
});
@@ -276,7 +281,7 @@
estimate = mEnhancedEstimates.getEstimate();
mLastEstimate = estimate;
}
- // Turbo is not always booted once SysUI is running so we have ot make sure we actually
+ // Turbo is not always booted once SysUI is running so we have to make sure we actually
// get data back
if (estimate != null) {
mTimeRemaining = estimate.estimateMillis;
@@ -355,13 +360,26 @@
// Only show the low warning once per charge cycle & no battery saver
final boolean canShowWarning = !mLowWarningShownThisChargeCycle && !isPowerSaver
&& (timeRemaining < mEnhancedEstimates.getLowWarningThreshold()
- || mBatteryLevel <= warnLevel);
+ || mBatteryLevel <= warnLevel);
// Only show the severe warning once per charge cycle
final boolean canShowSevereWarning = !mSevereWarningShownThisChargeCycle
&& (timeRemaining < mEnhancedEstimates.getSevereWarningThreshold()
- || mBatteryLevel <= critLevel);
+ || mBatteryLevel <= critLevel);
+ final boolean canShow = canShowWarning || canShowSevereWarning;
+ if (DEBUG) {
+ Slog.d(TAG, "Enhanced trigger is: " + canShow + "\nwith values: "
+ + " mLowWarningShownThisChargeCycle: " + mLowWarningShownThisChargeCycle
+ + " mSevereWarningShownThisChargeCycle: " + mSevereWarningShownThisChargeCycle
+ + " mEnhancedEstimates.timeremaining: " + timeRemaining
+ + " mBatteryLevel: " + mBatteryLevel
+ + " canShowWarning: " + canShowWarning
+ + " canShowSevereWarning: " + canShowSevereWarning
+ + " plugged: " + plugged
+ + " batteryStatus: " + batteryStatus
+ + " isPowerSaver: " + isPowerSaver);
+ }
return canShowWarning || canShowSevereWarning;
}
diff --git a/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyChip.kt b/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyChip.kt
index 65ed889..1765dc8 100644
--- a/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyChip.kt
+++ b/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyChip.kt
@@ -16,11 +16,14 @@
import android.content.Context
import android.util.AttributeSet
+import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
+import com.android.systemui.Dependency
import com.android.systemui.R
+import com.android.systemui.statusbar.policy.KeyguardMonitor
class OngoingPrivacyChip @JvmOverloads constructor(
context: Context,
@@ -29,14 +32,27 @@
defStyleRes: Int = 0
) : LinearLayout(context, attrs, defStyleAttrs, defStyleRes) {
- private val iconMargin =
- context.resources.getDimensionPixelSize(R.dimen.ongoing_appops_chip_icon_margin)
+ private val iconMarginExpanded = context.resources.getDimensionPixelSize(
+ R.dimen.ongoing_appops_chip_icon_margin_expanded)
+ private val iconMarginCollapsed = context.resources.getDimensionPixelSize(
+ R.dimen.ongoing_appops_chip_icon_margin_collapsed)
private val iconSize =
context.resources.getDimensionPixelSize(R.dimen.ongoing_appops_chip_icon_size)
- val iconColor = context.resources.getColor(
+ private val iconColor = context.resources.getColor(
R.color.status_bar_clock_color, context.theme)
+ private val backgroundDrawable = context.getDrawable(R.drawable.privacy_chip_bg)
private lateinit var text: TextView
private lateinit var iconsContainer: LinearLayout
+ private lateinit var inUseText: TextView
+ var expanded = false
+ set(value) {
+ if (value != field) {
+ field = value
+ updateView()
+ }
+ }
+ @Suppress("DEPRECATION")
+ private val keyguardMonitor = Dependency.get(KeyguardMonitor::class.java)
var builder = PrivacyDialogBuilder(context, emptyList<PrivacyItem>())
var privacyList = emptyList<PrivacyItem>()
set(value) {
@@ -48,15 +64,18 @@
override fun onFinishInflate() {
super.onFinishInflate()
+ inUseText = findViewById(R.id.in_use_text)
text = findViewById(R.id.text_container)
iconsContainer = findViewById(R.id.icons_container)
}
// Should only be called if the builder icons or app changed
private fun updateView() {
+ inUseText.visibility = if (expanded) View.GONE else View.VISIBLE
+ background = if (expanded) backgroundDrawable else null
fun setIcons(dialogBuilder: PrivacyDialogBuilder, iconsContainer: ViewGroup) {
iconsContainer.removeAllViews()
- dialogBuilder.generateIcons().forEach {
+ dialogBuilder.generateIcons().forEachIndexed { i, it ->
it.mutate()
it.setTint(iconColor)
val image = ImageView(context).apply {
@@ -64,25 +83,18 @@
scaleType = ImageView.ScaleType.CENTER_INSIDE
}
iconsContainer.addView(image, iconSize, iconSize)
- val lp = image.layoutParams as MarginLayoutParams
- lp.marginStart = iconMargin
- image.layoutParams = lp
+ if (i != 0) {
+ val lp = image.layoutParams as MarginLayoutParams
+ lp.marginStart = if (expanded) iconMarginExpanded else iconMarginCollapsed
+ image.layoutParams = lp
+ }
}
}
if (!privacyList.isEmpty()) {
generateContentDescription()
setIcons(builder, iconsContainer)
- text.visibility = if (builder.types.size == 1) VISIBLE else GONE
- if (builder.types.size == 1) {
- if (builder.app != null) {
- text.setText(builder.app?.applicationName)
- } else {
- text.text = context.resources.getQuantityString(
- R.plurals.ongoing_privacy_chip_multiple_apps,
- builder.appsAndTypes.size, builder.appsAndTypes.size)
- }
- }
+ setApplicationText()
} else {
text.visibility = GONE
iconsContainer.removeAllViews()
@@ -90,13 +102,28 @@
requestLayout()
}
+ private fun setApplicationText() {
+ text.visibility = if (builder.types.size == 1 && expanded) VISIBLE else GONE
+ if (builder.types.size == 1 && expanded) {
+ if (builder.app != null && !amISecure()) {
+ text.setText(builder.app?.applicationName)
+ } else {
+ text.text = context.resources.getQuantityString(
+ R.plurals.ongoing_privacy_chip_multiple_apps,
+ builder.appsAndTypes.size, builder.appsAndTypes.size)
+ }
+ }
+ }
+
+ private fun amISecure() = keyguardMonitor.isShowing && keyguardMonitor.isSecure
+
private fun generateContentDescription() {
val typesText = builder.joinTypes()
if (builder.types.size > 1) {
contentDescription = context.getString(
R.string.ongoing_privacy_chip_content_multiple_apps, typesText)
} else {
- if (builder.app != null) {
+ if (builder.app != null && !amISecure()) {
contentDescription =
context.getString(R.string.ongoing_privacy_chip_content_single_app,
builder.app?.applicationName, typesText)
diff --git a/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyDialog.kt b/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyDialog.kt
index cff7fe4..75b8a05 100644
--- a/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyDialog.kt
+++ b/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyDialog.kt
@@ -36,8 +36,8 @@
import java.util.concurrent.TimeUnit
class OngoingPrivacyDialog constructor(
- val context: Context,
- val dialogBuilder: PrivacyDialogBuilder
+ private val context: Context,
+ private val dialogBuilder: PrivacyDialogBuilder
) {
private val iconSize = context.resources.getDimensionPixelSize(
diff --git a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyDialogBuilder.kt b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyDialogBuilder.kt
index 9c1076a..bbea6b2 100644
--- a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyDialogBuilder.kt
+++ b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyDialogBuilder.kt
@@ -18,7 +18,7 @@
import android.graphics.drawable.Drawable
import com.android.systemui.R
-class PrivacyDialogBuilder(val context: Context, itemsList: List<PrivacyItem>) {
+class PrivacyDialogBuilder(private val context: Context, itemsList: List<PrivacyItem>) {
val appsAndTypes: List<Pair<PrivacyApplication, List<PrivacyType>>>
val types: List<PrivacyType>
diff --git a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItemController.kt b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItemController.kt
index f1c3bf2..0f33937 100644
--- a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItemController.kt
+++ b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItemController.kt
@@ -26,16 +26,23 @@
import android.os.UserHandle
import android.os.UserManager
import com.android.internal.annotations.VisibleForTesting
-import com.android.systemui.Dependency
+import com.android.systemui.Dependency.BG_HANDLER_NAME
+import com.android.systemui.Dependency.MAIN_HANDLER_NAME
+import com.android.systemui.R
import com.android.systemui.appops.AppOpItem
import com.android.systemui.appops.AppOpsController
-import com.android.systemui.R
import java.lang.ref.WeakReference
import javax.inject.Inject
+import javax.inject.Named
import javax.inject.Singleton
@Singleton
-class PrivacyItemController @Inject constructor(val context: Context) {
+class PrivacyItemController @Inject constructor(
+ val context: Context,
+ private val appOpsController: AppOpsController,
+ @Named(MAIN_HANDLER_NAME) private val uiHandler: Handler,
+ @Named(BG_HANDLER_NAME) private val bgHandler: Handler
+) {
companion object {
val OPS = intArrayOf(AppOpsManager.OP_CAMERA,
@@ -48,16 +55,10 @@
const val TAG = "PrivacyItemController"
const val SYSTEM_UID = 1000
}
- private var privacyList = emptyList<PrivacyItem>()
- @Suppress("DEPRECATION")
- private val appOpsController = Dependency.get(AppOpsController::class.java)
+ private var privacyList = emptyList<PrivacyItem>()
private val userManager = context.getSystemService(UserManager::class.java)
private var currentUserIds = emptyList<Int>()
- @Suppress("DEPRECATION")
- private val bgHandler = Handler(Dependency.get(Dependency.BG_LOOPER))
- @Suppress("DEPRECATION")
- private val uiHandler = Dependency.get(Dependency.MAIN_HANDLER)
private var listening = false
val systemApp =
PrivacyApplication(context.getString(R.string.device_services), SYSTEM_UID, context)
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java b/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java
index b865ce8..f91c9d9 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java
@@ -189,6 +189,7 @@
addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight,
oldBottom) -> updateAnimator(right - left));
setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
+ updateEverything();
}
private void updateAnimator(int width) {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java b/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java
index 74e82b2..c0f87cb 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java
@@ -48,7 +48,6 @@
import android.view.DisplayCutout;
import android.view.View;
import android.view.WindowInsets;
-import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
@@ -124,6 +123,7 @@
private TintedIconManager mIconManager;
private TouchAnimator mStatusIconsAlphaAnimator;
private TouchAnimator mHeaderTextContainerAlphaAnimator;
+ private TouchAnimator mPrivacyChipAlphaAnimator;
private View mSystemIconsView;
private View mQuickQsStatusIcons;
@@ -212,6 +212,8 @@
mNextAlarmTextView = findViewById(R.id.next_alarm_text);
mRingerModeIcon = findViewById(R.id.ringer_mode_icon);
mRingerModeTextView = findViewById(R.id.ringer_mode_text);
+ mPrivacyChip = findViewById(R.id.privacy_chip);
+ mPrivacyChip.setOnClickListener(this);
updateResources();
@@ -230,8 +232,6 @@
mClockView = findViewById(R.id.clock);
mClockView.setOnClickListener(this);
mDateView = findViewById(R.id.date);
- mPrivacyChip = findViewById(R.id.privacy_chip);
- mPrivacyChip.setOnClickListener(this);
mSpace = findViewById(R.id.space);
// Tint for the battery icons are handled in setupHost()
@@ -383,6 +383,7 @@
updateStatusIconAlphaAnimator();
updateHeaderTextContainerAlphaAnimator();
+ updatePrivacyChipAlphaAnimator();
}
private void updateStatusIconAlphaAnimator() {
@@ -398,6 +399,12 @@
.build();
}
+ private void updatePrivacyChipAlphaAnimator() {
+ mPrivacyChipAlphaAnimator = new TouchAnimator.Builder()
+ .addFloat(mPrivacyChip, "alpha", 1, 0, 1)
+ .build();
+ }
+
public void setExpanded(boolean expanded) {
if (mExpanded == expanded) return;
mExpanded = expanded;
@@ -431,6 +438,10 @@
if (mHeaderTextContainerAlphaAnimator != null) {
mHeaderTextContainerAlphaAnimator.setPosition(keyguardExpansionFraction);
}
+ if (mPrivacyChipAlphaAnimator != null) {
+ mPrivacyChip.setExpanded(expansionFraction > 0.5);
+ mPrivacyChipAlphaAnimator.setPosition(keyguardExpansionFraction);
+ }
// Check the original expansion fraction - we don't want to show the tooltip until the
// panel is pulled all the way out.
@@ -541,12 +552,10 @@
Handler mUiHandler = new Handler(Looper.getMainLooper());
mUiHandler.post(() -> {
Dialog mDialog = new OngoingPrivacyDialog(mContext, builder).createDialog();
- mDialog.getWindow().setType(
- WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
- SystemUIDialog.setShowForAllUsers(mDialog, true);
+ SystemUIDialog.setShowForAllUsers(mDialog, false);
SystemUIDialog.registerDismissListener(mDialog);
SystemUIDialog.setWindowOnTop(mDialog);
- mUiHandler.post(() -> mDialog.show());
+ mActivityStarter.postQSRunnableDismissingKeyguard(() -> mDialog.show());
mHost.collapsePanels();
});
}
diff --git a/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java b/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java
index c474faf..83c4cfc 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java
@@ -24,6 +24,10 @@
import static com.android.systemui.shared.system.NavigationBarCompat.FLAG_DISABLE_SWIPE_UP;
import static com.android.systemui.shared.system.NavigationBarCompat.FLAG_SHOW_OVERVIEW_BUTTON;
import static com.android.systemui.shared.system.NavigationBarCompat.InteractionType;
+import static com.android.systemui.shared.system.QuickStepContract.KEY_EXTRA_INPUT_CHANNEL;
+import static com.android.systemui.shared.system.QuickStepContract.KEY_EXTRA_SUPPORTS_WINDOW_CORNERS;
+import static com.android.systemui.shared.system.QuickStepContract.KEY_EXTRA_SYSUI_PROXY;
+import static com.android.systemui.shared.system.QuickStepContract.KEY_EXTRA_WINDOW_CORNER_RADIUS;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
@@ -32,7 +36,9 @@
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Rect;
+import android.graphics.Region;
import android.os.Binder;
+import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
@@ -41,6 +47,7 @@
import android.os.UserHandle;
import android.provider.Settings;
import android.util.Log;
+import android.view.InputChannel;
import android.view.MotionEvent;
import com.android.internal.policy.ScreenDecorationsUtils;
@@ -51,6 +58,7 @@
import com.android.systemui.shared.recents.IOverviewProxy;
import com.android.systemui.shared.recents.ISystemUiProxy;
import com.android.systemui.shared.system.ActivityManagerWrapper;
+import com.android.systemui.shared.system.InputChannelCompat.InputEventDispatcher;
import com.android.systemui.stackdivider.Divider;
import com.android.systemui.statusbar.phone.StatusBar;
import com.android.systemui.statusbar.policy.CallbackController;
@@ -93,6 +101,8 @@
private final List<OverviewProxyListener> mConnectionCallbacks = new ArrayList<>();
private final Intent mQuickStepIntent;
+ private Region mActiveNavBarRegion;
+
private IOverviewProxy mOverviewProxy;
private int mConnectionBackoffAttempts;
private @InteractionType int mInteractionFlags;
@@ -103,6 +113,8 @@
private float mWindowCornerRadius;
private boolean mSupportsRoundedCornersOnWindows;
+ private InputEventDispatcher mInputEventDispatcher;
+
private ISystemUiProxy mSysUiProxy = new ISystemUiProxy.Stub() {
public void startScreenPinning(int taskId) {
@@ -309,6 +321,20 @@
mCurrentBoundedUserId = -1;
Log.e(TAG_OPS, "Failed to call onBind()", e);
}
+
+ Bundle params = new Bundle();
+ params.putBinder(KEY_EXTRA_SYSUI_PROXY, mSysUiProxy.asBinder());
+ params.putParcelable(KEY_EXTRA_INPUT_CHANNEL, createNewInputDispatcher());
+ params.putFloat(KEY_EXTRA_WINDOW_CORNER_RADIUS, mWindowCornerRadius);
+ params.putBoolean(KEY_EXTRA_SUPPORTS_WINDOW_CORNERS, mSupportsRoundedCornersOnWindows);
+ try {
+ mOverviewProxy.onInitialize(params);
+ } catch (RemoteException e) {
+ // Ignore error until the migration is complete.
+ Log.e(TAG_OPS, "Failed to call onBind()", e);
+ }
+ dispatchNavButtonBounds();
+
notifyConnectionChanged();
}
@@ -317,6 +343,7 @@
Log.w(TAG_OPS, "Null binding of '" + name + "', try reconnecting");
mCurrentBoundedUserId = -1;
retryConnectionWithBackoff();
+ disposeInputDispatcher();
}
@Override
@@ -324,15 +351,32 @@
Log.w(TAG_OPS, "Binding died of '" + name + "', try reconnecting");
mCurrentBoundedUserId = -1;
retryConnectionWithBackoff();
+ disposeInputDispatcher();
}
@Override
public void onServiceDisconnected(ComponentName name) {
// Do nothing
mCurrentBoundedUserId = -1;
+ disposeInputDispatcher();
}
};
+ private void disposeInputDispatcher() {
+ if (mInputEventDispatcher != null) {
+ mInputEventDispatcher.dispose();
+ mInputEventDispatcher = null;
+ }
+ }
+
+ private InputChannel createNewInputDispatcher() {
+ disposeInputDispatcher();
+
+ InputChannel[] channels = InputChannel.openInputChannelPair("overview-proxy-service");
+ mInputEventDispatcher = new InputEventDispatcher(channels[0], Looper.getMainLooper());
+ return channels[1];
+ }
+
private final DeviceProvisionedListener mDeviceProvisionedCallback =
new DeviceProvisionedListener() {
@Override
@@ -382,6 +426,24 @@
}
}
+ /**
+ * Sets the navbar region which can receive touch inputs
+ */
+ public void onActiveNavBarRegionChanges(Region activeRegion) {
+ mActiveNavBarRegion = activeRegion;
+ dispatchNavButtonBounds();
+ }
+
+ private void dispatchNavButtonBounds() {
+ if (mOverviewProxy != null && mActiveNavBarRegion != null) {
+ try {
+ mOverviewProxy.onActiveNavBarRegionChanges(mActiveNavBarRegion);
+ } catch (RemoteException e) {
+ Log.e(TAG_OPS, "Failed to call onActiveNavBarRegionChanges()", e);
+ }
+ }
+ }
+
public float getBackButtonAlpha() {
return mBackButtonAlpha;
}
@@ -477,6 +539,10 @@
return mOverviewProxy;
}
+ public InputEventDispatcher getInputEventDispatcher() {
+ return mInputEventDispatcher;
+ }
+
public int getInteractionFlags() {
return mInteractionFlags;
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java b/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java
index be749ae..164f582 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java
@@ -424,22 +424,28 @@
final boolean hasChargingTime = chargingTimeRemaining > 0;
int chargingId;
- switch (mChargingSpeed) {
- case KeyguardUpdateMonitor.BatteryStatus.CHARGING_FAST:
- chargingId = hasChargingTime
- ? R.string.keyguard_indication_charging_time_fast
- : R.string.keyguard_plugged_in_charging_fast;
- break;
- case KeyguardUpdateMonitor.BatteryStatus.CHARGING_SLOWLY:
- chargingId = hasChargingTime
- ? R.string.keyguard_indication_charging_time_slowly
- : R.string.keyguard_plugged_in_charging_slowly;
- break;
- default:
- chargingId = hasChargingTime
- ? R.string.keyguard_indication_charging_time
- : R.string.keyguard_plugged_in;
- break;
+ if (mPowerPluggedInWired) {
+ switch (mChargingSpeed) {
+ case KeyguardUpdateMonitor.BatteryStatus.CHARGING_FAST:
+ chargingId = hasChargingTime
+ ? R.string.keyguard_indication_charging_time_fast
+ : R.string.keyguard_plugged_in_charging_fast;
+ break;
+ case KeyguardUpdateMonitor.BatteryStatus.CHARGING_SLOWLY:
+ chargingId = hasChargingTime
+ ? R.string.keyguard_indication_charging_time_slowly
+ : R.string.keyguard_plugged_in_charging_slowly;
+ break;
+ default:
+ chargingId = hasChargingTime
+ ? R.string.keyguard_indication_charging_time
+ : R.string.keyguard_plugged_in;
+ break;
+ }
+ } else {
+ chargingId = hasChargingTime
+ ? R.string.keyguard_indication_charging_time_wireless
+ : R.string.keyguard_plugged_in_wireless;
}
String percentage = NumberFormat.getPercentInstance()
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NavigationBarController.java b/packages/SystemUI/src/com/android/systemui/statusbar/NavigationBarController.java
index e11ec2d..2edea78 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NavigationBarController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NavigationBarController.java
@@ -158,18 +158,6 @@
});
}
- /** Removes navigation bars. */
- public void destroy() {
- mDisplayManager.unregisterDisplayListener(this);
- if (mNavigationBars.size() > 0) {
- for (int i = 0; i < mNavigationBars.size(); i++) {
- int displayId = mNavigationBars.keyAt(i);
- removeNavigationBar(displayId);
- }
- mNavigationBars.clear();
- }
- }
-
private void removeNavigationBar(int displayId) {
NavigationBarFragment navBar = mNavigationBars.get(displayId);
if (navBar != null) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManager.java
index c25b7cf..1cc6dc3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManager.java
@@ -42,8 +42,6 @@
/** Adds a listener to be notified when the current user changes. */
void addUserChangedListener(UserChangedListener listener);
- void destroy();
-
SparseArray<UserInfo> getCurrentProfiles();
void setLockscreenPublicMode(boolean isProfilePublic, int userId);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerImpl.java
index 6a49b80..9cb6f11 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerImpl.java
@@ -550,12 +550,6 @@
return mKeyguardMonitor.isSecure() || mLockPatternUtils.isSecure(userId);
}
- public void destroy() {
- mContext.unregisterReceiver(mBaseBroadcastReceiver);
- mContext.unregisterReceiver(mAllUsersReceiver);
- mListeners.clear();
- }
-
@Override
public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
pw.println("NotificationLockscreenUserManager state:");
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
index 01b0bb1..110d515 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
@@ -348,15 +348,13 @@
if (notGoneIndex == 0) {
StatusBarIconView icon = row.getEntry().expandedIcon;
NotificationIconContainer.IconState iconState = getIconState(icon);
+ // The icon state might be null in rare cases where the notification is actually
+ // added to the layout, but not to the shelf. An example are replied messages, since
+ // they don't show up on AOD
if (iconState != null && iconState.clampedAppearAmount == 1.0f) {
// only if the first icon is fully in the shelf we want to clip to it!
backgroundTop = (int) (row.getTranslationY() - getTranslationY());
firstElementRoundness = row.getCurrentTopRoundness();
- } else if (iconState == null) {
- Log.wtf(TAG, "iconState is null. ExpandedIcon: " + row.getEntry().expandedIcon
- + (row.getEntry().expandedIcon != null
- ? "\n icon parent: " + row.getEntry().expandedIcon.getParent() : "")
- + " \n number of notifications: " + mHostLayout.getChildCount() );
}
}
if (row.isFirstInSection() && previousRow != null && previousRow.isLastInSection()) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryListener.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryListener.java
index 839b06c..1ed671f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryListener.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryListener.java
@@ -47,7 +47,11 @@
}
/**
- * Called when a notification is updated, before any filtering of notifications have occurred.
+ * Called when a notification is about to be updated. Notification- and ranking-derived fields
+ * on the entry have already been updated but the following have not yet occurred:
+ * (a) View binding (i.e. the associated view has not yet been updated / inflation has not yet
+ * been kicked off.
+ * (b) Notification filtering
*/
default void onPreEntryUpdated(NotificationEntry entry) {
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
index 81d0e25..56922be 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
@@ -230,7 +230,6 @@
}
}
}
- entry.setLowPriorityStateUpdated(false);
}
@Override
@@ -346,8 +345,7 @@
Dependency.get(LeakDetector.class).trackInstance(entry);
// Construct the expanded view.
- getRowBinder().inflateViews(entry, () -> performRemoveNotification(notification),
- mNotificationData.get(entry.key) != null);
+ getRowBinder().inflateViews(entry, () -> performRemoveNotification(notification));
abortExistingInflation(key);
@@ -384,13 +382,11 @@
mNotificationData.update(entry, ranking, notification);
- getRowBinder().inflateViews(entry, () -> performRemoveNotification(notification),
- mNotificationData.get(entry.key) != null);
-
for (NotificationEntryListener listener : mNotificationEntryListeners) {
listener.onPreEntryUpdated(entry);
}
+ getRowBinder().inflateViews(entry, () -> performRemoveNotification(notification));
updateNotifications();
if (DEBUG) {
@@ -422,6 +418,7 @@
}
}
+ @Override
public void updateNotificationRanking(NotificationListenerService.RankingMap rankingMap) {
List<NotificationEntry> entries = new ArrayList<>();
entries.addAll(mNotificationData.getActiveNotifications());
@@ -447,8 +444,7 @@
entry,
oldImportances.get(entry.key),
oldAdjustments.get(entry.key),
- NotificationUiAdjustment.extractFromNotificationEntry(entry),
- mNotificationData.get(entry.key) != null);
+ NotificationUiAdjustment.extractFromNotificationEntry(entry));
}
updateNotifications();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationListController.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationListController.java
index 88f4ca2..769cbb7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationListController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationListController.java
@@ -61,11 +61,6 @@
mDeviceProvisionedController.addCallback(mDeviceProvisionedListener);
}
- /** Should be called when the list controller is being destroyed. */
- public void destroy() {
- mDeviceProvisionedController.removeCallback(mDeviceProvisionedListener);
- }
-
@SuppressWarnings("FieldCanBeLocal")
private final NotificationEntryListener mEntryListener = new NotificationEntryListener() {
@Override
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationRowBinder.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationRowBinder.java
index 0b8596f..f1bb0d77 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationRowBinder.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationRowBinder.java
@@ -124,8 +124,7 @@
*/
public void inflateViews(
NotificationEntry entry,
- Runnable onDismissRunnable,
- boolean isUpdate)
+ Runnable onDismissRunnable)
throws InflationException {
ViewGroup parent = mListContainer.getViewParentForNotification(entry);
PackageManager pmUser = StatusBar.getPackageManagerForUser(mContext,
@@ -135,13 +134,13 @@
if (entry.rowExists()) {
entry.updateIcons(mContext, sbn);
entry.reset();
- updateNotification(entry, pmUser, sbn, entry.getRow(), isUpdate);
+ updateNotification(entry, pmUser, sbn, entry.getRow());
} else {
entry.createIcons(mContext, sbn);
new RowInflaterTask().inflate(mContext, parent, entry,
row -> {
bindRow(entry, pmUser, sbn, row, onDismissRunnable);
- updateNotification(entry, pmUser, sbn, row, isUpdate);
+ updateNotification(entry, pmUser, sbn, row);
});
}
}
@@ -197,15 +196,14 @@
NotificationEntry entry,
@Nullable Integer oldImportance,
NotificationUiAdjustment oldAdjustment,
- NotificationUiAdjustment newAdjustment,
- boolean isUpdate) {
+ NotificationUiAdjustment newAdjustment) {
if (NotificationUiAdjustment.needReinflate(oldAdjustment, newAdjustment)) {
if (entry.rowExists()) {
entry.reset();
PackageManager pmUser = StatusBar.getPackageManagerForUser(
mContext,
entry.notification.getUser().getIdentifier());
- updateNotification(entry, pmUser, entry.notification, entry.getRow(), isUpdate);
+ updateNotification(entry, pmUser, entry.notification, entry.getRow());
} else {
// Once the RowInflaterTask is done, it will pick up the updated entry, so
// no-op here.
@@ -224,12 +222,8 @@
NotificationEntry entry,
PackageManager pmUser,
StatusBarNotification sbn,
- ExpandableNotificationRow row,
- boolean isUpdate) {
- boolean isLowPriority = entry.ambient;
- boolean wasLowPriority = row.isLowPriority();
- row.setIsLowPriority(isLowPriority);
- row.setLowPriorityStateUpdated(isUpdate && (wasLowPriority != isLowPriority));
+ ExpandableNotificationRow row) {
+ row.setIsLowPriority(entry.ambient);
// bind the click event to the content area
checkNotNull(mNotificationClicker).register(row, sbn);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/VisualStabilityManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/VisualStabilityManager.java
index c886685..396a3a7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/VisualStabilityManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/VisualStabilityManager.java
@@ -45,7 +45,7 @@
private boolean mReorderingAllowed;
private VisibilityLocationProvider mVisibilityLocationProvider;
private ArraySet<View> mAllowedReorderViews = new ArraySet<>();
- private ArraySet<View> mLowPriorityReorderingViews = new ArraySet<>();
+ private ArraySet<NotificationEntry> mLowPriorityReorderingViews = new ArraySet<>();
private ArraySet<View> mAddedChildren = new ArraySet<>();
private boolean mPulsing;
@@ -53,14 +53,21 @@
public VisualStabilityManager(NotificationEntryManager notificationEntryManager) {
notificationEntryManager.addNotificationEntryListener(new NotificationEntryListener() {
@Override
- public void onEntryReinflated(NotificationEntry entry) {
- if (entry.hasLowPriorityStateUpdated()) {
- onLowPriorityUpdated(entry);
- if (mPresenter != null) {
- mPresenter.updateNotificationViews();
- }
+ public void onPreEntryUpdated(NotificationEntry entry) {
+ final boolean mAmbientStateHasChanged =
+ entry.ambient != entry.getRow().isLowPriority();
+ if (mAmbientStateHasChanged) {
+ mLowPriorityReorderingViews.add(entry);
}
}
+
+ @Override
+ public void onPostEntryUpdated(NotificationEntry entry) {
+ // This line is technically not required as we'll get called as the hierarchy
+ // manager will call onReorderingFinished() immediately before this.
+ // TODO: Find a way to make this relationship more explicit
+ mLowPriorityReorderingViews.remove(entry);
+ }
});
}
@@ -142,7 +149,7 @@
if (mAddedChildren.contains(row)) {
return true;
}
- if (mLowPriorityReorderingViews.contains(row)) {
+ if (mLowPriorityReorderingViews.contains(row.getEntry())) {
return true;
}
if (mAllowedReorderViews.contains(row)
@@ -172,10 +179,6 @@
}
}
- private void onLowPriorityUpdated(NotificationEntry entry) {
- mLowPriorityReorderingViews.add(entry.getRow());
- }
-
/**
* Notify the visual stability manager that a new view was added and should be allowed to
* reorder next time.
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java
index f74de5b..f6d4ce22 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java
@@ -622,10 +622,6 @@
return null;
}
- public boolean hasLowPriorityStateUpdated() {
- return row != null && row.hasLowPriorityStateUpdated();
- }
-
public void removeRow() {
if (row != null) row.setRemoved();
}
@@ -650,10 +646,6 @@
return parent == null;
}
- public void setLowPriorityStateUpdated(boolean updated) {
- if (row != null) row.setLowPriorityStateUpdated(updated);
- }
-
/**
* @return Can the underlying notification be cleared? This can be different from whether the
* notification can be dismissed in case notifications are sensitive on the lockscreen.
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationCounters.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationCounters.java
index 43b5503..a1fcbeb 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationCounters.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationCounters.java
@@ -30,6 +30,9 @@
/** Counter tag for when the user hits 'stop notifications' in the blocking helper. */
public static final String BLOCKING_HELPER_STOP_NOTIFICATIONS =
"blocking_helper_stop_notifications";
+ /** Counter tag for when the user hits 'deliver silently' in the blocking helper. */
+ public static final String BLOCKING_HELPER_DELIVER_SILENTLY =
+ "blocking_helper_deliver_silently";
/** Counter tag for when the user hits 'show silently' in the blocking helper. */
public static final String BLOCKING_HELPER_TOGGLE_SILENT =
"blocking_helper_toggle_silent";
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
index b8e33a8..8f7778b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
@@ -124,6 +124,7 @@
public static final float DEFAULT_HEADER_VISIBLE_AMOUNT = 1.0f;
private static final long RECENTLY_ALERTED_THRESHOLD_MS = TimeUnit.SECONDS.toMillis(30);
private boolean mUpdateBackgroundOnUpdate;
+ private boolean mNotificationTranslationFinished = false;
/**
* Listener for when {@link ExpandableNotificationRow} is laid out.
@@ -133,7 +134,6 @@
}
private LayoutListener mLayoutListener;
- private boolean mLowPriorityStateUpdated;
private final NotificationInflater mNotificationInflater;
private int mIconTransformContentShift;
private int mIconTransformContentShiftNoIcon;
@@ -1453,6 +1453,10 @@
return mIsBlockingHelperShowing;
}
+ public boolean isBlockingHelperShowingAndTranslationFinished() {
+ return mIsBlockingHelperShowing && mNotificationTranslationFinished;
+ }
+
public void setOnDismissRunnable(Runnable onDismissRunnable) {
mOnDismissRunnable = onDismissRunnable;
}
@@ -1577,15 +1581,6 @@
}
}
-
- public void setLowPriorityStateUpdated(boolean lowPriorityStateUpdated) {
- mLowPriorityStateUpdated = lowPriorityStateUpdated;
- }
-
- public boolean hasLowPriorityStateUpdated() {
- return mLowPriorityStateUpdated;
- }
-
public boolean isLowPriority() {
return mIsLowPriority;
}
@@ -1851,7 +1846,6 @@
}
void onGutsOpened() {
- resetTranslation();
updateContentAccessibilityImportanceForGuts(false /* isEnabled */);
}
@@ -1905,11 +1899,10 @@
@Override
public void setTranslation(float translationX) {
- if (areGutsExposed()) {
- // Don't translate if guts are showing.
+ if (isBlockingHelperShowingAndTranslationFinished()) {
+ mGuts.setTranslationX(translationX);
return;
- }
- if (!mShouldTranslateContents) {
+ } else if (!mShouldTranslateContents) {
setTranslationX(translationX);
} else if (mTranslateableViews != null) {
// Translate the group of views
@@ -1925,6 +1918,7 @@
// positioning, so we can use the scrollX instead.
getEntry().expandedIcon.setScrollX((int) -translationX);
}
+
if (mMenuRow.getMenuView() != null) {
mMenuRow.onParentTranslationUpdate(translationX);
}
@@ -1936,6 +1930,10 @@
return getTranslationX();
}
+ if (isBlockingHelperShowingAndCanTranslate()) {
+ return mGuts.getTranslationX();
+ }
+
if (mTranslateableViews != null && mTranslateableViews.size() > 0) {
// All of the views in the list should have same translation, just use first one.
return mTranslateableViews.get(0).getTranslationX();
@@ -1944,15 +1942,16 @@
return 0;
}
+ private boolean isBlockingHelperShowingAndCanTranslate() {
+ return areGutsExposed() && mIsBlockingHelperShowing && mNotificationTranslationFinished;
+ }
+
public Animator getTranslateViewAnimator(final float leftTarget,
AnimatorUpdateListener listener) {
if (mTranslateAnim != null) {
mTranslateAnim.cancel();
}
- if (areGutsExposed()) {
- // No translation if guts are exposed.
- return null;
- }
+
final ObjectAnimator translateAnim = ObjectAnimator.ofFloat(this, TRANSLATE_CONTENT,
leftTarget);
if (listener != null) {
@@ -1968,6 +1967,9 @@
@Override
public void onAnimationEnd(Animator anim) {
+ if (mIsBlockingHelperShowing) {
+ mNotificationTranslationFinished = true;
+ }
if (!cancelled && leftTarget == 0) {
mMenuRow.resetMenu();
mTranslateAnim = null;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
index 8095615..1dc48d4 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
@@ -68,6 +68,7 @@
public class NotificationContentView extends FrameLayout {
private static final String TAG = "NotificationContentView";
+ private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
public static final int VISIBLE_TYPE_CONTRACTED = 0;
public static final int VISIBLE_TYPE_EXPANDED = 1;
public static final int VISIBLE_TYPE_HEADSUP = 2;
@@ -1319,6 +1320,14 @@
SmartRepliesAndActions smartRepliesAndActions =
chooseSmartRepliesAndActions(mSmartReplyConstants, entry);
+ if (DEBUG) {
+ Log.d(TAG, String.format("Adding suggestions for %s, %d actions, and %d replies.",
+ entry.notification.getKey(),
+ smartRepliesAndActions.smartActions == null ? 0 :
+ smartRepliesAndActions.smartActions.actions.size(),
+ smartRepliesAndActions.smartReplies == null ? 0 :
+ smartRepliesAndActions.smartReplies.choices.length));
+ }
applyRemoteInput(entry, smartRepliesAndActions.hasFreeformRemoteInput);
applySmartReplyView(smartRepliesAndActions, entry);
@@ -1341,6 +1350,10 @@
notification.findRemoteInputActionPair(true /* freeform */);
if (!smartReplyConstants.isEnabled()) {
+ if (DEBUG) {
+ Log.d(TAG, "Smart suggestions not enabled, not adding suggestions for "
+ + entry.notification.getKey());
+ }
return new SmartRepliesAndActions(null, null, freeformRemoteInputActionPair != null);
}
// Only use smart replies from the app if they target P or above. We have this check because
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationInfo.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationInfo.java
index c7b2fab..3723731 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationInfo.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationInfo.java
@@ -84,6 +84,7 @@
public static final int ACTION_UNDO = 1;
public static final int ACTION_TOGGLE_SILENT = 2;
public static final int ACTION_BLOCK = 3;
+ public static final int ACTION_DELIVER_SILENTLY = 4;
private INotificationManager mINotificationManager;
private PackageManager mPm;
@@ -135,30 +136,26 @@
};
private OnClickListener mOnToggleSilent = v -> {
- Runnable saveImportance = () -> {
- swapContent(ACTION_TOGGLE_SILENT, true /* animate */);
- if (mIsForBlockingHelper) {
- mMetricsLogger.write(getLogMaker()
- .setCategory(MetricsEvent.NOTIFICATION_BLOCKING_HELPER)
- .setType(MetricsEvent.TYPE_ACTION)
- .setSubtype(MetricsEvent.BLOCKING_HELPER_CLICK_ALERT_ME));
- }
- };
- if (mCheckSaveListener != null) {
- mCheckSaveListener.checkSave(saveImportance, mSbn);
- } else {
- saveImportance.run();
- }
+ handleSaveImportance(ACTION_TOGGLE_SILENT, MetricsEvent.BLOCKING_HELPER_CLICK_ALERT_ME);
+ };
+
+ private OnClickListener mOnDeliverSilently = v -> {
+ handleSaveImportance(
+ ACTION_DELIVER_SILENTLY, MetricsEvent.BLOCKING_HELPER_CLICK_STAY_SILENT);
};
private OnClickListener mOnStopOrMinimizeNotifications = v -> {
+ handleSaveImportance(ACTION_BLOCK, MetricsEvent.BLOCKING_HELPER_CLICK_BLOCKED);
+ };
+
+ private void handleSaveImportance(int action, int metricsSubtype) {
Runnable saveImportance = () -> {
- swapContent(ACTION_BLOCK, true /* animate */);
+ swapContent(action, true /* animate */);
if (mIsForBlockingHelper) {
mMetricsLogger.write(getLogMaker()
.setCategory(MetricsEvent.NOTIFICATION_BLOCKING_HELPER)
.setType(MetricsEvent.TYPE_ACTION)
- .setSubtype(MetricsEvent.BLOCKING_HELPER_CLICK_BLOCKED));
+ .setSubtype(metricsSubtype));
}
};
if (mCheckSaveListener != null) {
@@ -166,7 +163,7 @@
} else {
saveImportance.run();
}
- };
+ }
private OnClickListener mOnUndo = v -> {
// Reset exit counter that we'll log and record an undo event separately (not an exit event)
@@ -283,8 +280,6 @@
mMetricsLogger.write(notificationControlsLogMaker());
}
-
-
private void bindHeader() throws RemoteException {
// Package name
Drawable pkgicon = null;
@@ -479,17 +474,21 @@
findViewById(R.id.block_or_minimize).setVisibility(VISIBLE);
findViewById(R.id.interruptiveness_settings).setVisibility(GONE);
View block = findViewById(R.id.block);
- TextView keep = findViewById(R.id.keep);
+ TextView done = findViewById(R.id.done);
View minimize = findViewById(R.id.minimize);
+ View deliverSilently = findViewById(R.id.deliver_silently);
+
block.setOnClickListener(mOnStopOrMinimizeNotifications);
- keep.setOnClickListener(mOnKeepShowing);
+ done.setOnClickListener(mOnKeepShowing);
minimize.setOnClickListener(mOnStopOrMinimizeNotifications);
+ deliverSilently.setOnClickListener(mOnDeliverSilently);
if (mIsNonblockable) {
- keep.setText(android.R.string.ok);
+ done.setText(android.R.string.ok);
block.setVisibility(GONE);
minimize.setVisibility(GONE);
+ deliverSilently.setVisibility(GONE);
} else if (mIsForeground) {
block.setVisibility(GONE);
minimize.setVisibility(VISIBLE);
@@ -499,7 +498,7 @@
}
// Set up app settings link (i.e. Customize)
- TextView settingsLinkView = findViewById(R.id.app_settings);
+ View settingsLinkView = findViewById(R.id.app_settings);
Intent settingsIntent = getAppSettingsIntent(mPm, mPackageName,
mSingleNotificationChannel,
mSbn.getId(), mSbn.getTag());
@@ -507,7 +506,6 @@
&& settingsIntent != null
&& !TextUtils.isEmpty(mSbn.getNotification().getSettingsText())) {
settingsLinkView.setVisibility(VISIBLE);
- settingsLinkView.setText(mContext.getString(R.string.notification_app_settings));
settingsLinkView.setOnClickListener((View view) -> {
mAppSettingsClickListener.onClick(view, settingsIntent);
});
@@ -531,6 +529,11 @@
case ACTION_UNDO:
mChosenImportance = mStartingChannelImportance;
break;
+ case ACTION_DELIVER_SILENTLY:
+ mExitReason = NotificationCounters.BLOCKING_HELPER_DELIVER_SILENTLY;
+ mChosenImportance = IMPORTANCE_LOW;
+ confirmationText.setText(R.string.notification_channel_silenced);
+ break;
case ACTION_TOGGLE_SILENT:
mExitReason = NotificationCounters.BLOCKING_HELPER_TOGGLE_SILENT;
if (mWasShownHighPriority) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java
index 7105876..fbf1e31 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java
@@ -578,6 +578,10 @@
@Override
@ShadeViewRefactor(RefactorComponent.SHADE_VIEW)
public void onDensityOrFontScaleChanged() {
+ reinflateViews();
+ }
+
+ private void reinflateViews() {
inflateFooterView();
inflateEmptyShadeView();
updateFooter();
@@ -608,6 +612,7 @@
mCornerRadius = newRadius;
invalidate();
}
+ reinflateViews();
}
@VisibleForTesting
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java
index 2a88080..7882fd3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java
@@ -195,6 +195,9 @@
return false;
}
ExpandableNotificationRow row = (ExpandableNotificationRow) v;
+ if (row.isBlockingHelperShowingAndTranslationFinished()) {
+ return true;
+ }
if (row.areGutsExposed() || !row.getEntry().hasFinishedInitialization()) {
return false;
}
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 4c1c0a4..de0e194 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhone.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhone.java
@@ -141,10 +141,6 @@
mAnimationStateHandler = handler;
}
- public void destroy() {
- Dependency.get(StatusBarStateController.class).removeCallback(this);
- }
-
private void initResources() {
Resources resources = mContext.getResources();
mStatusBarHeight = resources.getDimensionPixelSize(
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
index 651670c..ebd4204 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
@@ -45,6 +45,8 @@
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
+import android.graphics.Region;
+import android.graphics.Region.Op;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
@@ -128,8 +130,8 @@
private Rect mBackButtonBounds = new Rect();
private Rect mRecentsButtonBounds = new Rect();
private Rect mRotationButtonBounds = new Rect();
+ private final Region mActiveRegion = new Region();
private int[] mTmpPosition = new int[2];
- private Rect mTmpRect = new Rect();
private KeyButtonDrawable mBackIcon;
private KeyButtonDrawable mHomeDefaultIcon;
@@ -954,17 +956,22 @@
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
- updateButtonLocationOnScreen(getBackButton(), mBackButtonBounds);
- updateButtonLocationOnScreen(getHomeButton(), mHomeButtonBounds);
- updateButtonLocationOnScreen(getRecentsButton(), mRecentsButtonBounds);
- updateButtonLocationOnScreen(getRotateSuggestionButton(), mRotationButtonBounds);
+
+ mActiveRegion.setEmpty();
+ updateButtonLocation(getBackButton(), mBackButtonBounds, true);
+ updateButtonLocation(getHomeButton(), mHomeButtonBounds, false);
+ updateButtonLocation(getRecentsButton(), mRecentsButtonBounds, false);
+ updateButtonLocation(getRotateSuggestionButton(), mRotationButtonBounds, true);
+ // TODO: Handle button visibility changes
+ mOverviewProxyService.onActiveNavBarRegionChanges(mActiveRegion);
if (mGestureHelper != null) {
mGestureHelper.onLayout(changed, left, top, right, bottom);
}
mRecentsOnboarding.setNavBarHeight(getMeasuredHeight());
}
- private void updateButtonLocationOnScreen(ButtonDispatcher button, Rect buttonBounds) {
+ private void updateButtonLocation(ButtonDispatcher button, Rect buttonBounds,
+ boolean isActive) {
View view = button.getCurrentView();
if (view == null) {
buttonBounds.setEmpty();
@@ -975,6 +982,14 @@
final float posY = view.getTranslationY();
view.setTranslationX(0);
view.setTranslationY(0);
+
+ if (isActive) {
+ view.getLocationOnScreen(mTmpPosition);
+ buttonBounds.set(mTmpPosition[0], mTmpPosition[1],
+ mTmpPosition[0] + view.getMeasuredWidth(),
+ mTmpPosition[1] + view.getMeasuredHeight());
+ mActiveRegion.op(buttonBounds, Op.UNION);
+ }
view.getLocationInWindow(mTmpPosition);
buttonBounds.set(mTmpPosition[0], mTmpPosition[1],
mTmpPosition[0] + view.getMeasuredWidth(),
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
index 069703e..f4fa1e8 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
@@ -590,11 +590,6 @@
mClockPositionResult.clockX, CLOCK_ANIMATION_PROPERTIES, animateClock);
PropertyAnimator.setProperty(mKeyguardStatusView, AnimatableProperty.Y,
mClockPositionResult.clockY, CLOCK_ANIMATION_PROPERTIES, animateClock);
- // Move big clock up while pulling up the bouncer
- PropertyAnimator.setProperty(mBigClockContainer, AnimatableProperty.Y,
- MathUtils.lerp(-mBigClockContainer.getHeight(), 0,
- Interpolators.FAST_OUT_LINEAR_IN.getInterpolation(getExpandedFraction())),
- CLOCK_ANIMATION_PROPERTIES, animateClock);
updateClock();
stackScrollerPadding = mClockPositionResult.stackScrollerPadding;
}
@@ -1334,8 +1329,7 @@
}
};
- private void setKeyguardBottomAreaVisibility(int statusBarState,
- boolean goingToFullShade) {
+ private void setKeyguardBottomAreaVisibility(int statusBarState, boolean goingToFullShade) {
mKeyguardBottomArea.animate().cancel();
if (goingToFullShade) {
mKeyguardBottomArea.animate()
@@ -1438,6 +1432,7 @@
if (mBarState == StatusBarState.SHADE_LOCKED
|| mBarState == StatusBarState.KEYGUARD) {
updateKeyguardBottomAreaAlpha();
+ updateBigClockAlpha();
}
if (mBarState == StatusBarState.SHADE && mQsExpanded
&& !mStackScrollerOverscrolling && mQsScrimEnabled) {
@@ -1883,6 +1878,19 @@
}
}
+ /**
+ * Custom clock fades away when user drags up to unlock or pulls down quick settings.
+ *
+ * Updates alpha of custom clock to match the alpha of the KeyguardBottomArea. See
+ * {@link updateKeyguardBottomAreaAlpha}.
+ */
+ private void updateBigClockAlpha() {
+ float expansionAlpha = MathUtils.map(isUnlockHintRunning()
+ ? 0 : KeyguardBouncer.ALPHA_EXPANSION_THRESHOLD, 1f, 0f, 1f, getExpandedFraction());
+ float alpha = Math.min(expansionAlpha, 1 - getQsExpansionFraction());
+ mBigClockContainer.setAlpha(alpha);
+ }
+
private float getNotificationsTopY() {
if (mNotificationStackScroller.getNotGoneChildCount() == 0) {
return getExpandedHeight();
@@ -2597,6 +2605,7 @@
}
mNotificationStackScroller.setExpandedHeight(expandedHeight);
updateKeyguardBottomAreaAlpha();
+ updateBigClockAlpha();
updateStatusBarIcons();
}
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 18711c0..2799191 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java
@@ -284,25 +284,6 @@
});
}
- public void destroy() {
- mRotationLockController.removeCallback(this);
- mBluetooth.removeCallback(this);
- mProvisionedController.removeCallback(this);
- mZenController.removeCallback(this);
- mCast.removeCallback(mCastCallback);
- mHotspot.removeCallback(mHotspotCallback);
- mNextAlarmController.removeCallback(mNextAlarmCallback);
- mDataSaver.removeCallback(this);
- mKeyguardMonitor.removeCallback(this);
- mPrivacyItemController.removeCallback(this);
- SysUiServiceProvider.getComponent(mContext, CommandQueue.class).removeCallback(this);
- mContext.unregisterReceiver(mIntentReceiver);
-
- NotificationManager noMan = mContext.getSystemService(NotificationManager.class);
- mCurrentNotifs.forEach(v -> noMan.cancelAsUser(v.first, SystemMessage.NOTE_INSTANT_APPS,
- new UserHandle(v.second)));
- }
-
@Override
public void onZenChanged(int zen) {
updateVolumeZen();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStepController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStepController.java
index 84f1cef..73ab5274 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStepController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStepController.java
@@ -56,6 +56,7 @@
import com.android.systemui.recents.OverviewProxyService;
import com.android.systemui.shared.recents.IOverviewProxy;
import com.android.systemui.shared.recents.utilities.Utilities;
+import com.android.systemui.shared.system.InputChannelCompat.InputEventDispatcher;
import com.android.systemui.shared.system.NavigationBarCompat;
import java.io.PrintWriter;
@@ -676,8 +677,13 @@
}
private boolean proxyMotionEvents(MotionEvent event) {
- final IOverviewProxy overviewProxy = mOverviewEventSender.getProxy();
event.transform(mTransformGlobalMatrix);
+ InputEventDispatcher dispatcher = mOverviewEventSender.getInputEventDispatcher();
+ if (dispatcher != null) {
+ dispatcher.dispatch(event);
+ }
+
+ final IOverviewProxy overviewProxy = mOverviewEventSender.getProxy();
try {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
overviewProxy.onPreMotionEvent(mNavigationBarView.getDownHitTarget());
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
index 9f3bec6..f980d07 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
@@ -1550,12 +1550,12 @@
@Override
public void onHeadsUpStateChanged(NotificationEntry entry, boolean isHeadsUp) {
- mEntryManager.updateNotificationRanking(null /* rankingMap */);
+ mEntryManager.updateNotifications();
}
@Override
public void onAmbientStateChanged(NotificationEntry entry, boolean isAmbient) {
- mEntryManager.updateNotificationRanking(null);
+ mEntryManager.updateNotifications();
if (isAmbient) {
mDozeServiceHost.fireNotificationPulse();
} else if (!mAmbientPulseManager.hasNotifications()) {
@@ -2843,38 +2843,6 @@
startActivityDismissingKeyguard(intent, onlyProvisioned, true /* dismissShade */);
}
- public void destroy() {
- // Begin old BaseStatusBar.destroy().
- mContext.unregisterReceiver(mBannerActionBroadcastReceiver);
- mLockscreenUserManager.destroy();
- try {
- mNotificationListener.unregisterAsSystemService();
- } catch (RemoteException e) {
- // Ignore.
- }
- mNotificationListController.destroy();
- // End old BaseStatusBar.destroy().
- if (mStatusBarWindow != null) {
- mWindowManager.removeViewImmediate(mStatusBarWindow);
- mStatusBarWindow = null;
- }
- mNavigationBarController.destroy();
- mContext.unregisterReceiver(mBroadcastReceiver);
- mContext.unregisterReceiver(mDemoReceiver);
- mAssistManager.destroy();
- mHeadsUpManager.destroy();
- mStatusBarStateController.removeCallback(this);
-
- if (mQSPanel != null && mQSPanel.getHost() != null) {
- mQSPanel.getHost().destroy();
- }
- Dependency.get(ActivityStarterDelegate.class).setActivityStarterImpl(null);
- mDeviceProvisionedController.removeCallback(mUserSetupObserver);
- Dependency.get(ConfigurationController.class).removeCallback(this);
- mZenController.removeCallback(this);
- mAppOpsController.removeCallback(APP_OPS, this);
- }
-
private boolean mDemoModeAllowed;
private boolean mDemoMode;
@@ -4036,8 +4004,7 @@
float viewY = screenY - mTmpInt2[1];
if (0 <= viewX && viewX <= mAmbientIndicationContainer.getWidth()
&& 0 <= viewY && viewY <= mAmbientIndicationContainer.getHeight()) {
- if (mAmbientIndicationContainer instanceof DozeReceiver)
- ((DozeReceiver) mAmbientIndicationContainer).onDozeDoubleTap();
+ dispatchTap(mAmbientIndicationContainer, viewX, viewY);
}
}
}
@@ -4052,6 +4019,12 @@
mScrimController.setAodFrontScrimAlpha(scrimOpacity);
}
+ private void dispatchTap(View view, float x, float y) {
+ long now = SystemClock.elapsedRealtime();
+ dispatchTouchEvent(view, x, y, now, MotionEvent.ACTION_DOWN);
+ dispatchTouchEvent(view, x, y, now, MotionEvent.ACTION_UP);
+ }
+
private void dispatchTouchEvent(View view, float x, float y, long now, int action) {
MotionEvent ev = MotionEvent.obtain(now, now, action, x, y, 0 /* meta */);
view.dispatchTouchEvent(ev);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java
index e9705ff..3ce66c5 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java
@@ -258,6 +258,11 @@
}
}
+ @Override
+ public void onOverlayChanged() {
+ onDensityOrFontScaleChanged();
+ }
+
private void updateNotificationOnUiModeChanged() {
ArrayList<NotificationEntry> userNotifications
= mEntryManager.getNotificationData().getNotificationsForCurrentUser();
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockSwitchTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockSwitchTest.java
index 5d03f19..b0d1106 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockSwitchTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockSwitchTest.java
@@ -35,7 +35,6 @@
import android.text.TextPaint;
import android.view.LayoutInflater;
import android.view.View;
-import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextClock;
@@ -60,6 +59,8 @@
@RunWithLooper(setAsMainLooper = true)
public class KeyguardClockSwitchTest extends SysuiTestCase {
private FrameLayout mClockContainer;
+ private FrameLayout mBigClockContainer;
+ private TextClock mBigClock;
private StatusBarStateController.StateListener mStateListener;
@Mock
@@ -73,6 +74,8 @@
mKeyguardClockSwitch =
(KeyguardClockSwitch) layoutInflater.inflate(R.layout.keyguard_clock_switch, null);
mClockContainer = mKeyguardClockSwitch.findViewById(R.id.clock_view);
+ mBigClockContainer = new FrameLayout(getContext());
+ mBigClock = new TextClock(getContext());
MockitoAnnotations.initMocks(this);
when(mClockView.getPaint()).thenReturn(mock(TextPaint.class));
mStateListener = mKeyguardClockSwitch.getStateListener();
@@ -93,19 +96,17 @@
@Test
public void onPluginConnected_showPluginBigClock() {
// GIVEN that the container for the big clock has visibility GONE
- FrameLayout bigClockContainer = new FrameLayout(getContext());
- bigClockContainer.setVisibility(GONE);
- mKeyguardClockSwitch.setBigClockContainer(bigClockContainer);
+ mBigClockContainer.setVisibility(GONE);
+ mKeyguardClockSwitch.setBigClockContainer(mBigClockContainer);
// AND the plugin returns a view for the big clock
ClockPlugin plugin = mock(ClockPlugin.class);
- TextClock pluginView = new TextClock(getContext());
- when(plugin.getBigClockView()).thenReturn(pluginView);
+ when(plugin.getBigClockView()).thenReturn(mBigClock);
// WHEN the plugin is connected
mKeyguardClockSwitch.getClockChangedListener().onClockChanged(plugin);
// THEN the big clock container is visible and it is the parent of the
// big clock view.
- assertThat(bigClockContainer.getVisibility()).isEqualTo(VISIBLE);
- assertThat(pluginView.getParent()).isEqualTo(bigClockContainer);
+ assertThat(mBigClockContainer.getVisibility()).isEqualTo(View.VISIBLE);
+ assertThat(mBigClock.getParent()).isEqualTo(mBigClockContainer);
}
@Test
@@ -246,24 +247,64 @@
@Test
public void onStateChanged_InvisibleInShade() {
// GIVEN that the big clock container is visible
- ViewGroup container = mock(ViewGroup.class);
- when(container.getVisibility()).thenReturn(View.VISIBLE);
- mKeyguardClockSwitch.setBigClockContainer(container);
+ mBigClockContainer.setVisibility(View.VISIBLE);
+ mKeyguardClockSwitch.setBigClockContainer(mBigClockContainer);
// WHEN transitioned to SHADE state
mStateListener.onStateChanged(StatusBarState.SHADE);
// THEN the container is invisible.
- verify(container).setVisibility(View.INVISIBLE);
+ assertThat(mBigClockContainer.getVisibility()).isEqualTo(View.INVISIBLE);
}
@Test
public void onStateChanged_VisibleInKeyguard() {
// GIVEN that the big clock container is invisible
- ViewGroup container = mock(ViewGroup.class);
- when(container.getVisibility()).thenReturn(View.INVISIBLE);
- mKeyguardClockSwitch.setBigClockContainer(container);
+ mBigClockContainer.setVisibility(View.INVISIBLE);
+ mKeyguardClockSwitch.setBigClockContainer(mBigClockContainer);
// WHEN transitioned to KEYGUARD state
mStateListener.onStateChanged(StatusBarState.KEYGUARD);
// THEN the container is visible.
- verify(container).setVisibility(View.VISIBLE);
+ assertThat(mBigClockContainer.getVisibility()).isEqualTo(View.VISIBLE);
+ }
+
+ @Test
+ public void setBigClockContainer_visible() {
+ // GIVEN that the big clock container is visible
+ mBigClockContainer.setVisibility(View.VISIBLE);
+ // AND GIVEN that a plugin is active.
+ ClockPlugin plugin = mock(ClockPlugin.class);
+ when(plugin.getBigClockView()).thenReturn(mBigClock);
+ mKeyguardClockSwitch.getClockChangedListener().onClockChanged(plugin);
+ // WHEN the container is associated with the clock switch
+ mKeyguardClockSwitch.setBigClockContainer(mBigClockContainer);
+ // THEN the container remains visible.
+ assertThat(mBigClockContainer.getVisibility()).isEqualTo(View.VISIBLE);
+ }
+
+ @Test
+ public void setBigClockContainer_invisible() {
+ // GIVEN that the big clock container is invisible
+ mBigClockContainer.setVisibility(View.INVISIBLE);
+ // AND GIVEN that a plugin is active.
+ ClockPlugin plugin = mock(ClockPlugin.class);
+ when(plugin.getBigClockView()).thenReturn(mBigClock);
+ mKeyguardClockSwitch.getClockChangedListener().onClockChanged(plugin);
+ // WHEN the container is associated with the clock switch
+ mKeyguardClockSwitch.setBigClockContainer(mBigClockContainer);
+ // THEN the container remains invisible.
+ assertThat(mBigClockContainer.getVisibility()).isEqualTo(View.INVISIBLE);
+ }
+
+ @Test
+ public void setBigClockContainer_gone() {
+ // GIVEN that the big clock container is gone
+ mBigClockContainer.setVisibility(View.GONE);
+ // AND GIVEN that a plugin is active.
+ ClockPlugin plugin = mock(ClockPlugin.class);
+ when(plugin.getBigClockView()).thenReturn(mBigClock);
+ mKeyguardClockSwitch.getClockChangedListener().onClockChanged(plugin);
+ // WHEN the container is associated with the clock switch
+ mKeyguardClockSwitch.setBigClockContainer(mBigClockContainer);
+ // THEN the container is made visible.
+ assertThat(mBigClockContainer.getVisibility()).isEqualTo(View.VISIBLE);
}
}
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSliceViewTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSliceViewTest.java
index 77895c9..190ce75 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSliceViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSliceViewTest.java
@@ -75,6 +75,17 @@
}
@Test
+ public void hasHeader_readsSliceData() {
+ ListBuilder builder = new ListBuilder(getContext(), mSliceUri, ListBuilder.INFINITY);
+ mKeyguardSliceView.onChanged(builder.build());
+ Assert.assertFalse("View should not have a header", mKeyguardSliceView.hasHeader());
+
+ builder.setHeader(new ListBuilder.HeaderBuilder().setTitle("header title!"));
+ mKeyguardSliceView.onChanged(builder.build());
+ Assert.assertTrue("View should have a header", mKeyguardSliceView.hasHeader());
+ }
+
+ @Test
public void refresh_replacesSliceContentAndNotifiesListener() {
AtomicBoolean notified = new AtomicBoolean();
mKeyguardSliceView.setContentChangeListener(()-> notified.set(true));
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/clock/ClockManagerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/clock/ClockManagerTest.java
new file mode 100644
index 0000000..f813ac6
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/keyguard/clock/ClockManagerTest.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.keyguard.clock;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.test.suitebuilder.annotation.SmallTest;
+import android.testing.AndroidTestingRunner;
+import android.testing.LeakCheck;
+import android.testing.TestableLooper.RunWithLooper;
+
+import com.android.systemui.SysuiTestCase;
+import com.android.systemui.dock.DockManager;
+import com.android.systemui.dock.DockManagerFake;
+import com.android.systemui.utils.leaks.FakeExtensionController;
+
+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;
+
+@SmallTest
+@RunWith(AndroidTestingRunner.class)
+@RunWithLooper
+public final class ClockManagerTest extends SysuiTestCase {
+
+ private ClockManager mClockManager;
+ private LeakCheck mLeakCheck;
+ private FakeExtensionController mFakeExtensionController;
+ private DockManagerFake mFakeDockManager;
+ @Mock ClockManager.ClockChangedListener mMockListener;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mLeakCheck = new LeakCheck();
+ mFakeExtensionController = new FakeExtensionController(mLeakCheck);
+ mFakeDockManager = new DockManagerFake();
+ mClockManager = new ClockManager(getContext(), mFakeExtensionController,
+ mFakeDockManager);
+ mClockManager.addOnClockChangedListener(mMockListener);
+ }
+
+ @After
+ public void tearDown() {
+ mClockManager.removeOnClockChangedListener(mMockListener);
+ }
+
+ @Test
+ public void dockEvent() {
+ mFakeDockManager.setDockEvent(DockManager.STATE_DOCKED);
+ assertThat(mClockManager.isDocked()).isTrue();
+ }
+
+ @Test
+ public void undockEvent() {
+ mFakeDockManager.setDockEvent(DockManager.STATE_NONE);
+ assertThat(mClockManager.isDocked()).isFalse();
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/clock/DefaultClockSupplierTest.java b/packages/SystemUI/tests/src/com/android/keyguard/clock/DefaultClockSupplierTest.java
new file mode 100644
index 0000000..1a3b198
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/keyguard/clock/DefaultClockSupplierTest.java
@@ -0,0 +1,132 @@
+/*
+ * 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.keyguard.clock;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.when;
+
+import android.test.suitebuilder.annotation.SmallTest;
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper.RunWithLooper;
+import android.view.LayoutInflater;
+
+import com.android.systemui.SysuiTestCase;
+import com.android.systemui.plugins.ClockPlugin;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@SmallTest
+@RunWith(AndroidTestingRunner.class)
+@RunWithLooper
+public final class DefaultClockSupplierTest extends SysuiTestCase {
+
+ private static final String BUBBLE_CLOCK = BubbleClockController.class.getName();
+ private static final Class<?> BUBBLE_CLOCK_CLASS = BubbleClockController.class;
+
+ private DefaultClockSupplier mDefaultClockSupplier;
+ @Mock SettingsWrapper mMockSettingsWrapper;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mDefaultClockSupplier = new DefaultClockSupplier(mMockSettingsWrapper,
+ LayoutInflater.from(getContext()));
+ }
+
+ @Test
+ public void get_default() {
+ // GIVEN that settings doesn't contain any values
+ when(mMockSettingsWrapper.getLockScreenCustomClockFace()).thenReturn(null);
+ when(mMockSettingsWrapper.getDockedClockFace()).thenReturn(null);
+ // WHEN get is called
+ ClockPlugin plugin = mDefaultClockSupplier.get();
+ // THEN the result is null, indicated the default clock face should be used.
+ assertThat(plugin).isNull();
+ }
+
+ @Test
+ public void get_customClock() {
+ // GIVEN that settings is set to the bubble clock face
+ when(mMockSettingsWrapper.getLockScreenCustomClockFace()).thenReturn(BUBBLE_CLOCK);
+ // WHEN get is called
+ ClockPlugin plugin = mDefaultClockSupplier.get();
+ // THEN the plugin is the bubble clock face.
+ assertThat(plugin).isInstanceOf(BUBBLE_CLOCK_CLASS);
+ }
+
+ @Test
+ public void get_badSettingsValue() {
+ // GIVEN that settings contains a value that doesn't correspond to a
+ // custom clock face.
+ when(mMockSettingsWrapper.getLockScreenCustomClockFace()).thenReturn("bad value");
+ // WHEN get is called
+ ClockPlugin plugin = mDefaultClockSupplier.get();
+ // THEN the result is null.
+ assertThat(plugin).isNull();
+ }
+
+ @Test
+ public void get_dockedDefault() {
+ // GIVEN docked
+ mDefaultClockSupplier.setDocked(true);
+ // WHEN get is called
+ ClockPlugin plugin = mDefaultClockSupplier.get();
+ // THEN the result is null, indicating the default clock face.
+ assertThat(plugin).isNull();
+ }
+
+ @Test
+ public void get_dockedCustomClock() {
+ // GIVEN docked and settings is set to the bubble clock face
+ mDefaultClockSupplier.setDocked(true);
+ when(mMockSettingsWrapper.getDockedClockFace()).thenReturn(BUBBLE_CLOCK);
+ // WHEN get is called
+ ClockPlugin plugin = mDefaultClockSupplier.get();
+ // THEN the plugin is the bubble clock face.
+ assertThat(plugin).isInstanceOf(BUBBLE_CLOCK_CLASS);
+ }
+
+ @Test
+ public void get_badDockedSettingsValue() {
+ // GIVEN docked and settings contains a value that doesn't correspond to
+ // an available clock face.
+ mDefaultClockSupplier.setDocked(true);
+ when(mMockSettingsWrapper.getDockedClockFace()).thenReturn("bad value");
+ // WHEN get is called
+ ClockPlugin plugin = mDefaultClockSupplier.get();
+ // THEN the result is null.
+ assertThat(plugin).isNull();
+ }
+
+ @Test
+ public void get_badDockedSettingsFallback() {
+ // GIVEN docked and settings contains a value that doesn't correspond to
+ // an available clock face, but locked screen settings is set to bubble
+ // clock.
+ mDefaultClockSupplier.setDocked(true);
+ when(mMockSettingsWrapper.getDockedClockFace()).thenReturn("bad value");
+ when(mMockSettingsWrapper.getLockScreenCustomClockFace()).thenReturn(BUBBLE_CLOCK);
+ // WHEN get is called
+ ClockPlugin plugin = mDefaultClockSupplier.get();
+ // THEN the plugin is the bubble clock face.
+ assertThat(plugin).isInstanceOf(BUBBLE_CLOCK_CLASS);
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
index 2742577..d9315f9 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
@@ -112,6 +112,9 @@
verify(mNotificationEntryManager, atLeastOnce())
.addNotificationEntryListener(mEntryListenerCaptor.capture());
mEntryListener = mEntryListenerCaptor.getValue();
+
+ // Reset the data
+ BubbleData.getInstance().clear();
}
@Test
@@ -207,12 +210,12 @@
verify(mBubbleExpandListener).onBubbleExpandChanged(true, mRow2.getEntry().key);
// Last added is the one that is expanded
- assertEquals(mRow2.getEntry(), stackView.getExpandedBubble().getEntry());
+ assertEquals(mRow2.getEntry(), stackView.getExpandedBubbleView().getEntry());
assertFalse(mRow2.getEntry().showInShadeWhenBubble());
// Switch which bubble is expanded
stackView.setExpandedBubble(mRow.getEntry());
- assertEquals(mRow.getEntry(), stackView.getExpandedBubble().getEntry());
+ assertEquals(mRow.getEntry(), stackView.getExpandedBubbleView().getEntry());
assertFalse(mRow.getEntry().showInShadeWhenBubble());
// collapse for previous bubble
@@ -262,19 +265,19 @@
verify(mBubbleExpandListener).onBubbleExpandChanged(true, mRow2.getEntry().key);
// Last added is the one that is expanded
- assertEquals(mRow2.getEntry(), stackView.getExpandedBubble().getEntry());
+ assertEquals(mRow2.getEntry(), stackView.getExpandedBubbleView().getEntry());
assertFalse(mRow2.getEntry().showInShadeWhenBubble());
// Dismiss currently expanded
- mBubbleController.removeBubble(stackView.getExpandedBubble().getKey());
+ mBubbleController.removeBubble(stackView.getExpandedBubbleView().getKey());
verify(mBubbleExpandListener).onBubbleExpandChanged(false, mRow2.getEntry().key);
// Make sure next bubble is selected
- assertEquals(mRow.getEntry(), stackView.getExpandedBubble().getEntry());
+ assertEquals(mRow.getEntry(), stackView.getExpandedBubbleView().getEntry());
verify(mBubbleExpandListener).onBubbleExpandChanged(true, mRow.getEntry().key);
// Dismiss that one
- mBubbleController.removeBubble(stackView.getExpandedBubble().getKey());
+ mBubbleController.removeBubble(stackView.getExpandedBubbleView().getKey());
// Make sure state changes and collapse happens
verify(mBubbleExpandListener).onBubbleExpandChanged(false, mRow.getEntry().key);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyItemControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyItemControllerTest.kt
index 98bf3c27..5d3f6ca 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyItemControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyItemControllerTest.kt
@@ -18,6 +18,7 @@
import android.app.ActivityManager
import android.app.AppOpsManager
+import android.content.Context
import android.content.Intent
import android.content.pm.UserInfo
import android.os.Handler
@@ -28,6 +29,8 @@
import android.testing.TestableLooper
import android.testing.TestableLooper.RunWithLooper
import com.android.systemui.Dependency
+import com.android.systemui.Dependency.BG_HANDLER
+import com.android.systemui.Dependency.MAIN_HANDLER
import com.android.systemui.R
import com.android.systemui.SysuiTestCase
import com.android.systemui.appops.AppOpItem
@@ -81,15 +84,20 @@
private lateinit var testableLooper: TestableLooper
private lateinit var privacyItemController: PrivacyItemController
+ private lateinit var handler: Handler
+
+ fun PrivacyItemController(context: Context) =
+ PrivacyItemController(context, appOpsController, handler, handler)
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
testableLooper = TestableLooper.get(this)
+ handler = Handler(testableLooper.looper)
appOpsController = mDependency.injectMockDependency(AppOpsController::class.java)
- mDependency.injectTestDependency(Dependency.BG_LOOPER, testableLooper.looper)
- mDependency.injectTestDependency(Dependency.MAIN_HANDLER, Handler(testableLooper.looper))
+ mDependency.injectTestDependency(Dependency.BG_HANDLER, handler)
+ mDependency.injectTestDependency(Dependency.MAIN_HANDLER, handler)
mContext.addMockSystemService(UserManager::class.java, userManager)
mContext.getOrCreateTestableResources().addOverride(R.string.device_services,
DEVICE_SERVICES_STRING)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java
index cad1a96..79bc0a3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java
@@ -521,6 +521,16 @@
verify(extender2).setShouldManageLifetime(mEntry, false);
}
+ /**
+ * Ensure that calling NotificationEntryManager.performRemoveNotification() doesn't crash when
+ * given a notification that has already been removed from NotificationData.
+ */
+ @Test
+ public void testPerformRemoveNotification_removedEntry() {
+ mEntryManager.getNotificationData().remove(mSbn.getKey(), null /* ranking */);
+ mEntryManager.performRemoveNotification(mSbn);
+ }
+
private Notification.Action createAction() {
return new Notification.Action.Builder(
Icon.createWithResource(getContext(), android.R.drawable.sym_def_app_icon),
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationInfoTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationInfoTest.java
index 105bd9d..19a73f6 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationInfoTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationInfoTest.java
@@ -737,7 +737,7 @@
guts.setGutsContent(mNotificationInfo);
mNotificationInfo.setGutsParent(guts);
- mNotificationInfo.findViewById(R.id.keep).performClick();
+ mNotificationInfo.findViewById(R.id.done).performClick();
verify(mBlockingHelperManager).dismissCurrentBlockingHelper();
mTestableLooper.processAllMessages();
@@ -765,7 +765,7 @@
guts.setGutsContent(mNotificationInfo);
mNotificationInfo.setGutsParent(guts);
- mNotificationInfo.findViewById(R.id.keep).performClick();
+ mNotificationInfo.findViewById(R.id.done).performClick();
verify(mBlockingHelperManager).dismissCurrentBlockingHelper();
mTestableLooper.processAllMessages();
@@ -961,6 +961,41 @@
}
@Test
+ public void testSilentlyChangedCallsUpdateNotificationChannel_blockingHelper()
+ throws Exception {
+ mNotificationChannel.setImportance(IMPORTANCE_LOW);
+ mNotificationInfo.bindNotification(
+ mMockPackageManager,
+ mMockINotificationManager,
+ TEST_PACKAGE_NAME,
+ mNotificationChannel,
+ 1 /* numChannels */,
+ mSbn,
+ null /* checkSaveListener */,
+ null /* onSettingsClick */,
+ null /* onAppSettingsClick */,
+ true /*provisioned */,
+ false /* isNonblockable */,
+ true /* isForBlockingHelper */,
+ true /* isUserSentimentNegative */,
+ IMPORTANCE_DEFAULT,
+ false);
+
+ mNotificationInfo.findViewById(R.id.deliver_silently).performClick();
+ waitForUndoButton();
+ mNotificationInfo.handleCloseControls(true, false);
+
+ mTestableLooper.processAllMessages();
+ ArgumentCaptor<NotificationChannel> updated =
+ ArgumentCaptor.forClass(NotificationChannel.class);
+ verify(mMockINotificationManager, times(1)).updateNotificationChannelForPackage(
+ anyString(), eq(TEST_UID), updated.capture());
+ assertTrue((updated.getValue().getUserLockedFields()
+ & USER_LOCKED_IMPORTANCE) != 0);
+ assertEquals(IMPORTANCE_LOW, updated.getValue().getImportance());
+ }
+
+ @Test
public void testKeepUpdatesNotificationChannel() throws Exception {
mNotificationChannel.setImportance(IMPORTANCE_LOW);
mNotificationInfo.bindNotification(mMockPackageManager, mMockINotificationManager,
diff --git a/proto/src/metrics_constants/metrics_constants.proto b/proto/src/metrics_constants/metrics_constants.proto
index 3c91069..d9adec8 100644
--- a/proto/src/metrics_constants/metrics_constants.proto
+++ b/proto/src/metrics_constants/metrics_constants.proto
@@ -6975,6 +6975,23 @@
// formerly: histogram system_cost_for_smart_sharing
FIELD_TIME_TO_APP_TARGETS = 1653;
+ // Open: Settings > Panel for Internet Connectivity
+ PANEL_INTERNET_CONNECTIVITY = 1654;
+
+ // Open: Settings > Panel for Volume
+ PANEL_VOLUME = 1655;
+
+ // Open: Settings > Panel for NFC
+ PANEL_NFC = 1656;
+
+ // Open: Settings > Panel for Media Output
+ PANEL_MEDIA_OUTPUT = 1657;
+
+ // ACTION: An interaction with a Slice or other component in the Panel.
+ // CATEGORY: SETTINGS
+ // OS: Q
+ ACTION_PANEL_INTERACTION = 1658;
+
// ---- End Q Constants, all Q constants go above this line ----
// Add new aosp constants above this line.
// END OF AOSP CONSTANTS
diff --git a/proto/src/wifi.proto b/proto/src/wifi.proto
index 82359c5..ad0ed8b 100644
--- a/proto/src/wifi.proto
+++ b/proto/src/wifi.proto
@@ -518,6 +518,9 @@
// WifiConfigStore read/write metrics.
optional WifiConfigStoreIO wifi_config_store_io = 137;
+
+ // Total number of saved networks with mac randomization enabled.
+ optional int32 num_saved_networks_with_mac_randomization = 138;
}
// Information that gets logged for every WiFi connection.
diff --git a/sax/tests/saxtests/Android.bp b/sax/tests/saxtests/Android.bp
new file mode 100644
index 0000000..5889f76
--- /dev/null
+++ b/sax/tests/saxtests/Android.bp
@@ -0,0 +1,11 @@
+android_test {
+ name: "FrameworksSaxTests",
+ // Include all test java files.
+ srcs: ["src/**/*.java"],
+ libs: [
+ "android.test.runner",
+ "android.test.base",
+ ],
+ static_libs: ["junit"],
+ platform_apis: true,
+}
diff --git a/sax/tests/saxtests/Android.mk b/sax/tests/saxtests/Android.mk
deleted file mode 100644
index c4517a9..0000000
--- a/sax/tests/saxtests/Android.mk
+++ /dev/null
@@ -1,16 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-# We only want this apk build for tests.
-LOCAL_MODULE_TAGS := tests
-
-# Include all test java files.
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_JAVA_LIBRARIES := android.test.runner android.test.base
-LOCAL_STATIC_JAVA_LIBRARIES := junit
-LOCAL_PACKAGE_NAME := FrameworksSaxTests
-LOCAL_PRIVATE_PLATFORM_APIS := true
-
-include $(BUILD_PACKAGE)
-
diff --git a/services/accessibility/OWNERS b/services/accessibility/OWNERS
new file mode 100644
index 0000000..265674a
--- /dev/null
+++ b/services/accessibility/OWNERS
@@ -0,0 +1,3 @@
+svetoslavganov@google.com
+pweaver@google.com
+rhedjao@google.com
diff --git a/services/autofill/java/com/android/server/autofill/AutofillManagerService.java b/services/autofill/java/com/android/server/autofill/AutofillManagerService.java
index 2e45fa7..4a3f126 100644
--- a/services/autofill/java/com/android/server/autofill/AutofillManagerService.java
+++ b/services/autofill/java/com/android/server/autofill/AutofillManagerService.java
@@ -49,6 +49,7 @@
import android.os.ShellCallback;
import android.os.UserHandle;
import android.os.UserManager;
+import android.provider.DeviceConfig;
import android.provider.Settings;
import android.service.autofill.FillEventHistory;
import android.service.autofill.UserData;
@@ -167,10 +168,14 @@
mUi = new AutoFillUI(ActivityThread.currentActivityThread().getSystemUiContext());
mAm = LocalServices.getService(ActivityManagerInternal.class);
+ DeviceConfig.addOnPropertyChangedListener(DeviceConfig.NAMESPACE_AUTOFILL,
+ ActivityThread.currentApplication().getMainExecutor(),
+ (namespace, name, value) -> setSmartSuggestionModesFromDeviceConfig(value));
+
setLogLevelFromSettings();
setMaxPartitionsFromSettings();
setMaxVisibleDatasetsFromSettings();
- setSmartSuggestionEmulationFromSettings();
+ setSmartSuggestionModesFromDeviceConfig();
final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
@@ -197,9 +202,6 @@
resolver.registerContentObserver(Settings.Global.getUriFor(
Settings.Global.AUTOFILL_MAX_VISIBLE_DATASETS), false, observer,
UserHandle.USER_ALL);
- resolver.registerContentObserver(Settings.Global.getUriFor(
- Settings.Global.AUTOFILL_SMART_SUGGESTION_EMULATION_FLAGS), false, observer,
- UserHandle.USER_ALL);
}
@Override // from AbstractMasterSystemService
@@ -214,9 +216,6 @@
case Settings.Global.AUTOFILL_MAX_VISIBLE_DATASETS:
setMaxVisibleDatasetsFromSettings();
break;
- case Settings.Global.AUTOFILL_SMART_SUGGESTION_EMULATION_FLAGS:
- setSmartSuggestionEmulationFromSettings();
- break;
default:
Slog.w(TAG, "Unexpected property (" + property + "); updating cache instead");
// fall through
@@ -457,14 +456,25 @@
}
}
- private void setSmartSuggestionEmulationFromSettings() {
- final int flags = Settings.Global.getInt(getContext().getContentResolver(),
- Settings.Global.AUTOFILL_SMART_SUGGESTION_EMULATION_FLAGS, 0);
- if (sDebug) {
- Slog.d(TAG, "setSmartSuggestionEmulationFromSettings(): "
- + getSmartSuggestionModeToString(flags));
- }
+ private void setSmartSuggestionModesFromDeviceConfig() {
+ final String value = DeviceConfig.getProperty(DeviceConfig.NAMESPACE_AUTOFILL,
+ AutofillManager.DEVICE_CONFIG_AUTOFILL_SMART_SUGGESTION_SUPPORTED_MODES);
+ setSmartSuggestionModesFromDeviceConfig(value);
+ }
+ private void setSmartSuggestionModesFromDeviceConfig(@Nullable String value) {
+ if (sDebug) Slog.d(TAG, "setSmartSuggestionEmulationFromDeviceConfig(): value=" + value);
+ final int flags;
+ if (value == null) {
+ flags = AutofillManager.FLAG_SMART_SUGGESTION_SYSTEM;
+ } else {
+ try {
+ flags = Integer.parseInt(value);
+ } catch (Exception e) {
+ Slog.w(TAG, "setSmartSuggestionEmulationFromDeviceConfig(): NAN:" + value);
+ return;
+ }
+ }
synchronized (mLock) {
mSupportedSmartSuggestionModes = flags;
}
diff --git a/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java b/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java
index 9b863a9..61f63d3 100644
--- a/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java
+++ b/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java
@@ -47,7 +47,7 @@
private static final String TAG = RemoteAugmentedAutofillService.class.getSimpleName();
- private static final long TIMEOUT_REMOTE_REQUEST_MILLIS = 2 * DateUtils.SECOND_IN_MILLIS;
+ private static final long TIMEOUT_REMOTE_REQUEST_MILLIS = 5 * DateUtils.SECOND_IN_MILLIS;
RemoteAugmentedAutofillService(Context context, ComponentName serviceName,
int userId, RemoteAugmentedAutofillServiceCallbacks callbacks,
@@ -106,6 +106,12 @@
activityComponent, focusedId, focusedValue));
}
+ @Override
+ public String toString() {
+ return "RemoteAugmentedAutofillService["
+ + ComponentName.flattenToShortString(getComponentName()) + "]";
+ }
+
/**
* Called by {@link Session} when it's time to destroy all augmented autofill requests.
*/
@@ -181,11 +187,13 @@
@Override
protected void onTimeout(RemoteAugmentedAutofillService remoteService) {
- Slog.wtf(TAG, "timed out: " + this);
+ // TODO(b/122858578): must update the logged AUTOFILL_AUGMENTED_REQUEST with the
+ // timeout
+ Slog.w(TAG, "PendingAutofillRequest timed out (" + TIMEOUT_REMOTE_REQUEST_MILLIS
+ + "ms) for " + remoteService);
// NOTE: so far we don't need notify RemoteAugmentedAutofillServiceCallbacks
finish();
}
-
}
public interface RemoteAugmentedAutofillServiceCallbacks
diff --git a/services/backup/java/com/android/server/backup/encryption/chunk/ChunkListing.java b/services/backup/java/com/android/server/backup/encryption/chunk/ChunkListingMap.java
similarity index 89%
rename from services/backup/java/com/android/server/backup/encryption/chunk/ChunkListing.java
rename to services/backup/java/com/android/server/backup/encryption/chunk/ChunkListingMap.java
index 2d2e88af..a448901 100644
--- a/services/backup/java/com/android/server/backup/encryption/chunk/ChunkListing.java
+++ b/services/backup/java/com/android/server/backup/encryption/chunk/ChunkListingMap.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2018 The Android Open Source Project
+ * Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -11,13 +11,14 @@
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
- * limitations under the License
+ * limitations under the License.
*/
package com.android.server.backup.encryption.chunk;
import android.annotation.Nullable;
import android.util.proto.ProtoInputStream;
+
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
@@ -30,16 +31,16 @@
* It can then tell the server to use that chunk, through telling it the position and length of the
* chunk in the previous backup's blob.
*/
-public class ChunkListing {
+public class ChunkListingMap {
/**
- * Reads a ChunkListing from a {@link ProtoInputStream}. Expects the message to be of format
+ * Reads a ChunkListingMap from a {@link ProtoInputStream}. Expects the message to be of format
* {@link ChunksMetadataProto.ChunkListing}.
*
* @param inputStream Currently at a {@link ChunksMetadataProto.ChunkListing} message.
* @throws IOException when the message is not structured as expected or a field can not be
* read.
*/
- public static ChunkListing readFromProto(ProtoInputStream inputStream) throws IOException {
+ public static ChunkListingMap readFromProto(ProtoInputStream inputStream) throws IOException {
Map<ChunkHash, Entry> entries = new HashMap();
long start = 0;
@@ -54,12 +55,12 @@
}
}
- return new ChunkListing(entries);
+ return new ChunkListingMap(entries);
}
private final Map<ChunkHash, Entry> mChunksByHash;
- private ChunkListing(Map<ChunkHash, Entry> chunksByHash) {
+ private ChunkListingMap(Map<ChunkHash, Entry> chunksByHash) {
mChunksByHash = Collections.unmodifiableMap(new HashMap<>(chunksByHash));
}
diff --git a/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerServiceShellCommand.java b/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerServiceShellCommand.java
index 39d5c9d..86ad52d 100644
--- a/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerServiceShellCommand.java
+++ b/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerServiceShellCommand.java
@@ -77,15 +77,12 @@
pw.println(" Temporarily (for DURATION ms) changes the service implemtation.");
pw.println(" To reset, call with just the USER_ID argument.");
pw.println("");
- pw.println("");
pw.println(" set default-service-enabled USER_ID [true|false]");
pw.println(" Enable / disable the default service for the user.");
pw.println("");
- pw.println("");
pw.println(" get default-service-enabled USER_ID");
pw.println(" Checks whether the default service is enabled for the user.");
pw.println("");
- pw.println("");
pw.println(" list sessions [--user USER_ID]");
pw.println(" Lists all pending sessions.");
pw.println("");
diff --git a/services/core/java/com/android/server/AlarmManagerInternal.java b/services/core/java/com/android/server/AlarmManagerInternal.java
index 2756610..5b0de5e 100644
--- a/services/core/java/com/android/server/AlarmManagerInternal.java
+++ b/services/core/java/com/android/server/AlarmManagerInternal.java
@@ -26,6 +26,8 @@
void broadcastAlarmComplete(int recipientUid);
}
+ /** Returns true if AlarmManager is delaying alarms due to device idle. */
+ boolean isIdling();
public void removeAlarmsForUid(int uid);
public void registerInFlightListener(InFlightListener callback);
}
diff --git a/services/core/java/com/android/server/AlarmManagerService.java b/services/core/java/com/android/server/AlarmManagerService.java
index 10b5327..a400cc3 100644
--- a/services/core/java/com/android/server/AlarmManagerService.java
+++ b/services/core/java/com/android/server/AlarmManagerService.java
@@ -1991,6 +1991,11 @@
*/
private final class LocalService implements AlarmManagerInternal {
@Override
+ public boolean isIdling() {
+ return isIdlingImpl();
+ }
+
+ @Override
public void removeAlarmsForUid(int uid) {
synchronized (mLock) {
removeLocked(uid);
@@ -2823,6 +2828,12 @@
}
}
+ private boolean isIdlingImpl() {
+ synchronized (mLock) {
+ return mPendingIdleUntil != null;
+ }
+ }
+
AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
synchronized (mLock) {
return mNextAlarmClockForUser.get(userId);
diff --git a/services/core/java/com/android/server/BinderCallsStatsService.java b/services/core/java/com/android/server/BinderCallsStatsService.java
index eafa0e2..e510259 100644
--- a/services/core/java/com/android/server/BinderCallsStatsService.java
+++ b/services/core/java/com/android/server/BinderCallsStatsService.java
@@ -121,6 +121,8 @@
private static final String SETTINGS_DETAILED_TRACKING_KEY = "detailed_tracking";
private static final String SETTINGS_UPLOAD_DATA_KEY = "upload_data";
private static final String SETTINGS_SAMPLING_INTERVAL_KEY = "sampling_interval";
+ private static final String SETTINGS_TRACK_SCREEN_INTERACTIVE_KEY = "track_screen_state";
+ private static final String SETTINGS_TRACK_DIRECT_CALLING_UID_KEY = "track_calling_uid";
private static final String SETTINGS_MAX_CALL_STATS_KEY = "max_call_stats_count";
private boolean mEnabled;
@@ -169,6 +171,12 @@
mBinderCallsStats.setMaxBinderCallStats(mParser.getInt(
SETTINGS_MAX_CALL_STATS_KEY,
BinderCallsStats.MAX_BINDER_CALL_STATS_COUNT_DEFAULT));
+ mBinderCallsStats.setTrackScreenInteractive(
+ mParser.getBoolean(SETTINGS_TRACK_SCREEN_INTERACTIVE_KEY,
+ BinderCallsStats.DEFAULT_TRACK_SCREEN_INTERACTIVE));
+ mBinderCallsStats.setTrackDirectCallerUid(
+ mParser.getBoolean(SETTINGS_TRACK_DIRECT_CALLING_UID_KEY,
+ BinderCallsStats.DEFAULT_TRACK_DIRECT_CALLING_UID));
final boolean enabled =
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index fe4411c..d1cd072 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -38,7 +38,6 @@
import static android.net.NetworkCapabilities.TRANSPORT_VPN;
import static android.net.NetworkPolicyManager.RULE_NONE;
import static android.net.NetworkPolicyManager.uidRulesToString;
-import static android.net.NetworkStack.NETWORKSTACK_PACKAGE_NAME;
import static android.net.shared.NetworkMonitorUtils.isValidationRequired;
import static android.net.shared.NetworkParcelableUtil.toStableParcelable;
import static android.os.Process.INVALID_UID;
@@ -2667,9 +2666,9 @@
}
@Override
- public void showProvisioningNotification(String action) {
+ public void showProvisioningNotification(String action, String packageName) {
final Intent intent = new Intent(action);
- intent.setPackage(NETWORKSTACK_PACKAGE_NAME);
+ intent.setPackage(packageName);
final PendingIntent pendingIntent;
// Only the system server can register notifications with package "android"
diff --git a/services/core/java/com/android/server/DeviceIdleController.java b/services/core/java/com/android/server/DeviceIdleController.java
index 39030aa..6b66394 100644
--- a/services/core/java/com/android/server/DeviceIdleController.java
+++ b/services/core/java/com/android/server/DeviceIdleController.java
@@ -271,6 +271,7 @@
private static final int EVENT_BUFFER_SIZE = 100;
private AlarmManager mAlarmManager;
+ private AlarmManagerInternal mLocalAlarmManager;
private IBatteryStats mBatteryStats;
private ActivityManagerInternal mLocalActivityManager;
private ActivityTaskManagerInternal mLocalActivityTaskManager;
@@ -616,7 +617,8 @@
}
};
- private final AlarmManager.OnAlarmListener mDeepAlarmListener
+ @VisibleForTesting
+ final AlarmManager.OnAlarmListener mDeepAlarmListener
= new AlarmManager.OnAlarmListener() {
@Override
public void onAlarm() {
@@ -1874,6 +1876,7 @@
if (phase == PHASE_SYSTEM_SERVICES_READY) {
synchronized (this) {
mAlarmManager = mInjector.getAlarmManager();
+ mLocalAlarmManager = getLocalService(AlarmManagerInternal.class);
mBatteryStats = BatteryStatsService.getService();
mLocalActivityManager = getLocalService(ActivityManagerInternal.class);
mLocalActivityTaskManager = getLocalService(ActivityTaskManagerInternal.class);
@@ -2605,6 +2608,16 @@
// next natural time to come out of it.
}
+
+ /** Returns true if the screen is locked. */
+ @VisibleForTesting
+ boolean isKeyguardShowing() {
+ synchronized (this) {
+ return mScreenLocked;
+ }
+ }
+
+ @VisibleForTesting
void keyguardShowingLocked(boolean showing) {
if (DEBUG) Slog.i(TAG, "keyguardShowing=" + showing);
if (mScreenLocked != showing) {
@@ -2616,25 +2629,38 @@
}
}
+ @VisibleForTesting
void scheduleReportActiveLocked(String activeReason, int activeUid) {
Message msg = mHandler.obtainMessage(MSG_REPORT_ACTIVE, activeUid, 0, activeReason);
mHandler.sendMessage(msg);
}
void becomeActiveLocked(String activeReason, int activeUid) {
- if (DEBUG) Slog.i(TAG, "becomeActiveLocked, reason = " + activeReason);
+ becomeActiveLocked(activeReason, activeUid, mConstants.INACTIVE_TIMEOUT, true);
+ }
+
+ private void becomeActiveLocked(String activeReason, int activeUid,
+ long newInactiveTimeout, boolean changeLightIdle) {
+ if (DEBUG) {
+ Slog.i(TAG, "becomeActiveLocked, reason=" + activeReason
+ + ", changeLightIdle=" + changeLightIdle);
+ }
if (mState != STATE_ACTIVE || mLightState != STATE_ACTIVE) {
EventLogTags.writeDeviceIdle(STATE_ACTIVE, activeReason);
- EventLogTags.writeDeviceIdleLight(LIGHT_STATE_ACTIVE, activeReason);
- scheduleReportActiveLocked(activeReason, activeUid);
mState = STATE_ACTIVE;
- mLightState = LIGHT_STATE_ACTIVE;
- mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
+ mInactiveTimeout = newInactiveTimeout;
mCurIdleBudget = 0;
mMaintenanceStartTime = 0;
resetIdleManagementLocked();
- resetLightIdleManagementLocked();
- addEvent(EVENT_NORMAL, activeReason);
+
+ if (changeLightIdle) {
+ EventLogTags.writeDeviceIdleLight(LIGHT_STATE_ACTIVE, activeReason);
+ mLightState = LIGHT_STATE_ACTIVE;
+ resetLightIdleManagementLocked();
+ // Only report active if light is also ACTIVE.
+ scheduleReportActiveLocked(activeReason, activeUid);
+ addEvent(EVENT_NORMAL, activeReason);
+ }
}
}
@@ -2654,49 +2680,81 @@
}
}
+ /** Sanity check to make sure DeviceIdleController and AlarmManager are on the same page. */
+ private void verifyAlarmStateLocked() {
+ if (mState == STATE_ACTIVE && mNextAlarmTime != 0) {
+ Slog.wtf(TAG, "mState=ACTIVE but mNextAlarmTime=" + mNextAlarmTime);
+ }
+ if (mState != STATE_IDLE && mLocalAlarmManager.isIdling()) {
+ Slog.wtf(TAG, "mState=" + stateToString(mState) + " but AlarmManager is idling");
+ }
+ if (mState == STATE_IDLE && !mLocalAlarmManager.isIdling()) {
+ Slog.wtf(TAG, "mState=IDLE but AlarmManager is not idling");
+ }
+ if (mLightState == LIGHT_STATE_ACTIVE && mNextLightAlarmTime != 0) {
+ Slog.wtf(TAG, "mLightState=ACTIVE but mNextLightAlarmTime is "
+ + TimeUtils.formatDuration(mNextLightAlarmTime - SystemClock.elapsedRealtime())
+ + " from now");
+ }
+ }
+
void becomeInactiveIfAppropriateLocked() {
- if (DEBUG) Slog.d(TAG, "becomeInactiveIfAppropriateLocked()");
- if ((!mScreenOn && !mCharging) || mForceIdle) {
- // Become inactive and determine if we will ultimately go idle.
- if (mDeepEnabled) {
- if (mQuickDozeActivated) {
- if (mState == STATE_QUICK_DOZE_DELAY || mState == STATE_IDLE
- || mState == STATE_IDLE_MAINTENANCE) {
- // Already "idling". Don't want to restart the process.
- // mLightState can't be LIGHT_STATE_ACTIVE if mState is any of these 3
- // values, so returning here is safe.
- return;
- }
- if (DEBUG) {
- Slog.d(TAG, "Moved from "
- + stateToString(mState) + " to STATE_QUICK_DOZE_DELAY");
- }
- mState = STATE_QUICK_DOZE_DELAY;
- // Make sure any motion sensing or locating is stopped.
- resetIdleManagementLocked();
- // Wait a small amount of time in case something (eg: background service from
- // recently closed app) needs to finish running.
- scheduleAlarmLocked(mConstants.QUICK_DOZE_DELAY_TIMEOUT, false);
- EventLogTags.writeDeviceIdle(mState, "no activity");
- } else if (mState == STATE_ACTIVE) {
- mState = STATE_INACTIVE;
- if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE");
- resetIdleManagementLocked();
- long delay = mInactiveTimeout;
- if (shouldUseIdleTimeoutFactorLocked()) {
- delay = (long) (mPreIdleFactor * delay);
- }
- scheduleAlarmLocked(delay, false);
- EventLogTags.writeDeviceIdle(mState, "no activity");
+ verifyAlarmStateLocked();
+
+ final boolean isScreenBlockingInactive =
+ mScreenOn && (!mConstants.WAIT_FOR_UNLOCK || !mScreenLocked);
+ if (DEBUG) {
+ Slog.d(TAG, "becomeInactiveIfAppropriateLocked():"
+ + " isScreenBlockingInactive=" + isScreenBlockingInactive
+ + " (mScreenOn=" + mScreenOn
+ + ", WAIT_FOR_UNLOCK=" + mConstants.WAIT_FOR_UNLOCK
+ + ", mScreenLocked=" + mScreenLocked + ")"
+ + " mCharging=" + mCharging
+ + " mForceIdle=" + mForceIdle
+ );
+ }
+ if (!mForceIdle && (mCharging || isScreenBlockingInactive)) {
+ return;
+ }
+ // Become inactive and determine if we will ultimately go idle.
+ if (mDeepEnabled) {
+ if (mQuickDozeActivated) {
+ if (mState == STATE_QUICK_DOZE_DELAY || mState == STATE_IDLE
+ || mState == STATE_IDLE_MAINTENANCE) {
+ // Already "idling". Don't want to restart the process.
+ // mLightState can't be LIGHT_STATE_ACTIVE if mState is any of these 3
+ // values, so returning here is safe.
+ return;
}
+ if (DEBUG) {
+ Slog.d(TAG, "Moved from "
+ + stateToString(mState) + " to STATE_QUICK_DOZE_DELAY");
+ }
+ mState = STATE_QUICK_DOZE_DELAY;
+ // Make sure any motion sensing or locating is stopped.
+ resetIdleManagementLocked();
+ // Wait a small amount of time in case something (eg: background service from
+ // recently closed app) needs to finish running.
+ scheduleAlarmLocked(mConstants.QUICK_DOZE_DELAY_TIMEOUT, false);
+ EventLogTags.writeDeviceIdle(mState, "no activity");
+ } else if (mState == STATE_ACTIVE) {
+ mState = STATE_INACTIVE;
+ if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE");
+ resetIdleManagementLocked();
+ long delay = mInactiveTimeout;
+ if (shouldUseIdleTimeoutFactorLocked()) {
+ delay = (long) (mPreIdleFactor * delay);
+ }
+ scheduleAlarmLocked(delay, false);
+ EventLogTags.writeDeviceIdle(mState, "no activity");
}
- if (mLightState == LIGHT_STATE_ACTIVE && mLightEnabled) {
- mLightState = LIGHT_STATE_INACTIVE;
- if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
- resetLightIdleManagementLocked();
- scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
- EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
- }
+ }
+ if (mLightState == LIGHT_STATE_ACTIVE && mLightEnabled) {
+ mLightState = LIGHT_STATE_INACTIVE;
+ if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
+ resetLightIdleManagementLocked();
+ scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
+ EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
}
}
@@ -3216,33 +3274,10 @@
// The device is not yet active, so we want to go back to the pending idle
// state to wait again for no motion. Note that we only monitor for motion
// after moving out of the inactive state, so no need to worry about that.
- boolean becomeInactive = false;
- if (mState != STATE_ACTIVE) {
- // Motion shouldn't affect light state, if it's already in doze-light or maintenance
- boolean lightIdle = mLightState == LIGHT_STATE_IDLE
- || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK
- || mLightState == LIGHT_STATE_IDLE_MAINTENANCE;
- if (!lightIdle) {
- // Only switch to active state if we're not in either idle state
- scheduleReportActiveLocked(type, Process.myUid());
- addEvent(EVENT_NORMAL, type);
- }
- mActiveReason = ACTIVE_REASON_MOTION;
- mState = STATE_ACTIVE;
- mInactiveTimeout = timeout;
- mCurIdleBudget = 0;
- mMaintenanceStartTime = 0;
- EventLogTags.writeDeviceIdle(mState, type);
- becomeInactive = true;
- updateActiveConstraintsLocked();
- }
- if (mLightState == LIGHT_STATE_OVERRIDE) {
- // We went out of light idle mode because we had started deep idle mode... let's
- // now go back and reset things so we resume light idling if appropriate.
- mLightState = LIGHT_STATE_ACTIVE;
- EventLogTags.writeDeviceIdleLight(mLightState, type);
- becomeInactive = true;
- }
+ final boolean becomeInactive = mState != STATE_ACTIVE
+ || mLightState == LIGHT_STATE_OVERRIDE;
+ // We only want to change the IDLE state if it's OVERRIDE.
+ becomeActiveLocked(type, Process.myUid(), timeout, mLightState == LIGHT_STATE_OVERRIDE);
if (becomeInactive) {
becomeInactiveIfAppropriateLocked();
}
diff --git a/services/core/java/com/android/server/ExtconUEventObserver.java b/services/core/java/com/android/server/ExtconUEventObserver.java
index b3084f5..eb59152 100644
--- a/services/core/java/com/android/server/ExtconUEventObserver.java
+++ b/services/core/java/com/android/server/ExtconUEventObserver.java
@@ -22,8 +22,11 @@
import java.io.File;
import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Locale;
import java.util.Map;
+import java.util.regex.Pattern;
/**
* A specialized UEventObserver that receives UEvents from the kernel for devices in the {@code
@@ -40,13 +43,14 @@
* time in that process. Once started the UEvent thread will not stop (although it can stop
* notifying UEventObserver's via stopObserving()).
*
- * <p>
- *
* @hide
*/
public abstract class ExtconUEventObserver extends UEventObserver {
private static final String TAG = "ExtconUEventObserver";
private static final boolean LOG = false;
+ private static final String SELINUX_POLICIES_NEED_TO_BE_CHANGED =
+ "This probably means the selinux policies need to be changed.";
+
private final Map<String, ExtconInfo> mExtconInfos = new ArrayMap<>();
@Override
@@ -70,15 +74,47 @@
/** Starts observing {@link ExtconInfo#getDevicePath()}. */
public void startObserving(ExtconInfo extconInfo) {
- mExtconInfos.put(extconInfo.getDevicePath(), extconInfo);
- if (LOG) Slog.v(TAG, "Observing " + extconInfo.getDevicePath());
- startObserving("DEVPATH=" + extconInfo.getDevicePath());
+ String devicePath = extconInfo.getDevicePath();
+ if (devicePath == null) {
+ Slog.wtf(TAG, "Unable to start observing " + extconInfo.getName()
+ + " because the device path is null. " + SELINUX_POLICIES_NEED_TO_BE_CHANGED);
+ } else {
+ mExtconInfos.put(devicePath, extconInfo);
+ if (LOG) Slog.v(TAG, "Observing " + devicePath);
+ startObserving("DEVPATH=" + devicePath);
+ }
}
/** An External Connection to watch. */
public static final class ExtconInfo {
private static final String TAG = "ExtconInfo";
+ /** Returns a new list of all external connections whose name matches {@code regex}. */
+ public static List<ExtconInfo> getExtconInfos(@Nullable String regex) {
+ Pattern p = regex == null ? null : Pattern.compile(regex);
+ File file = new File("/sys/class/extcon");
+ File[] files = file.listFiles();
+ if (files == null) {
+ Slog.wtf(TAG, file + " exists " + file.exists() + " isDir " + file.isDirectory()
+ + " but listFiles returns null. "
+ + SELINUX_POLICIES_NEED_TO_BE_CHANGED);
+ return new ArrayList<>(0); // Always return a new list.
+ } else {
+ ArrayList list = new ArrayList(files.length);
+ for (File f : files) {
+ String name = f.getName();
+ if (p == null || p.matcher(name).matches()) {
+ ExtconInfo uei = new ExtconInfo(name);
+ list.add(uei);
+ if (LOG) Slog.d(TAG, name + " matches " + regex);
+ } else {
+ if (LOG) Slog.d(TAG, name + " does not match " + regex);
+ }
+ }
+ return list;
+ }
+ }
+
private final String mName;
public ExtconInfo(String name) {
@@ -123,6 +159,15 @@
/** Does the {@link /sys/class/extcon} directory exist */
public static boolean extconExists() {
File extconDir = new File("/sys/class/extcon");
- return extconDir.exists() && extconDir.isDirectory();
+ boolean retVal = extconDir.exists() && extconDir.isDirectory();
+ // TODO(b/124364409): return the correct value after selinux policy is updated.
+ if (retVal) {
+ Slog.w(TAG, extconDir + " exists " + extconDir.exists() + " isDir "
+ + extconDir.isDirectory()
+ + " but reporting it does not exist until selinux policies are updated."
+ + " see b/124364409"
+ );
+ }
+ return false;
}
}
diff --git a/services/core/java/com/android/server/LocationManagerService.java b/services/core/java/com/android/server/LocationManagerService.java
index 4834ce0..0b0934b 100644
--- a/services/core/java/com/android/server/LocationManagerService.java
+++ b/services/core/java/com/android/server/LocationManagerService.java
@@ -67,6 +67,7 @@
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
+import android.os.IInterface;
import android.os.PowerManager;
import android.os.Process;
import android.os.RemoteException;
@@ -109,6 +110,7 @@
import com.android.server.location.LocationRequestStatistics.PackageStatistics;
import com.android.server.location.MockProvider;
import com.android.server.location.PassiveProvider;
+import com.android.server.location.RemoteListenerHelper;
import java.io.FileDescriptor;
import java.io.PrintWriter;
@@ -121,6 +123,8 @@
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
+import java.util.function.Consumer;
+import java.util.function.Function;
/**
* The service class that manages LocationProviders and issues location
@@ -225,11 +229,14 @@
private final ArraySet<String> mIgnoreSettingsPackageWhitelist = new ArraySet<>();
@GuardedBy("mLock")
- private final ArrayMap<IBinder, CallerIdentity> mGnssMeasurementsListeners = new ArrayMap<>();
-
+ private final ArrayMap<IBinder, LinkedListener<IGnssMeasurementsListener>>
+ mGnssMeasurementsListeners = new ArrayMap<>();
@GuardedBy("mLock")
- private final ArrayMap<IBinder, CallerIdentity>
+ private final ArrayMap<IBinder, LinkedListener<IGnssNavigationMessageListener>>
mGnssNavigationMessageListeners = new ArrayMap<>();
+ @GuardedBy("mLock")
+ private final ArrayMap<IBinder, LinkedListener<IGnssStatusListener>>
+ mGnssStatusListeners = new ArrayMap<>();
// current active user on the device - other users are denied location data
private int mCurrentUserId = UserHandle.USER_SYSTEM;
@@ -243,7 +250,7 @@
@GuardedBy("mLock")
private IBatchedLocationCallback mGnssBatchingCallback;
@GuardedBy("mLock")
- private LinkedCallback mGnssBatchingDeathCallback;
+ private LinkedListener<IBatchedLocationCallback> mGnssBatchingDeathCallback;
@GuardedBy("mLock")
private boolean mGnssBatchingInProgress = false;
@@ -485,7 +492,7 @@
&& record.mIsForegroundUid != foreground) {
if (D) {
Log.d(TAG, "request from uid " + uid + " is now "
- + (foreground ? "foreground" : "background)"));
+ + foregroundAsString(foreground));
}
record.updateForeground(foreground);
@@ -499,44 +506,48 @@
applyRequirementsLocked(provider);
}
- for (Entry<IBinder, CallerIdentity> entry : mGnssMeasurementsListeners.entrySet()) {
- CallerIdentity callerIdentity = entry.getValue();
- if (callerIdentity.mUid == uid) {
- if (D) {
- Log.d(TAG, "gnss measurements listener from uid " + uid
- + " is now " + (foreground ? "foreground" : "background)"));
- }
- if (foreground || isThrottlingExemptLocked(entry.getValue())) {
- mGnssMeasurementsProvider.addListener(
- IGnssMeasurementsListener.Stub.asInterface(entry.getKey()),
- callerIdentity);
- } else {
- mGnssMeasurementsProvider.removeListener(
- IGnssMeasurementsListener.Stub.asInterface(entry.getKey()));
- }
- }
- }
+ updateGnssDataProviderOnUidImportanceChangedLocked(mGnssMeasurementsListeners,
+ mGnssMeasurementsProvider, IGnssMeasurementsListener.Stub::asInterface,
+ uid, foreground);
- for (Entry<IBinder, CallerIdentity> entry : mGnssNavigationMessageListeners.entrySet()) {
- CallerIdentity callerIdentity = entry.getValue();
- if (callerIdentity.mUid == uid) {
- if (D) {
- Log.d(TAG, "gnss navigation message listener from uid "
- + uid + " is now "
- + (foreground ? "foreground" : "background)"));
- }
- if (foreground || isThrottlingExemptLocked(entry.getValue())) {
- mGnssNavigationMessageProvider.addListener(
- IGnssNavigationMessageListener.Stub.asInterface(entry.getKey()),
- callerIdentity);
- } else {
- mGnssNavigationMessageProvider.removeListener(
- IGnssNavigationMessageListener.Stub.asInterface(entry.getKey()));
- }
+ updateGnssDataProviderOnUidImportanceChangedLocked(mGnssNavigationMessageListeners,
+ mGnssNavigationMessageProvider, IGnssNavigationMessageListener.Stub::asInterface,
+ uid, foreground);
+
+ updateGnssDataProviderOnUidImportanceChangedLocked(mGnssStatusListeners,
+ mGnssStatusProvider, IGnssStatusListener.Stub::asInterface, uid, foreground);
+ }
+
+ @GuardedBy("mLock")
+ private <TListener extends IInterface> void updateGnssDataProviderOnUidImportanceChangedLocked(
+ ArrayMap<IBinder, ? extends LinkedListenerBase> gnssDataListeners,
+ RemoteListenerHelper<TListener> gnssDataProvider,
+ Function<IBinder, TListener> mapBinderToListener, int uid, boolean foreground) {
+ for (Entry<IBinder, ? extends LinkedListenerBase> entry : gnssDataListeners.entrySet()) {
+ LinkedListenerBase linkedListener = entry.getValue();
+ CallerIdentity callerIdentity = linkedListener.mCallerIdentity;
+ if (callerIdentity.mUid != uid) {
+ continue;
+ }
+
+ if (D) {
+ Log.d(TAG, linkedListener.mListenerName + " from uid "
+ + uid + " is now " + foregroundAsString(foreground));
+ }
+
+ TListener listener = mapBinderToListener.apply(entry.getKey());
+ if (foreground || isThrottlingExemptLocked(callerIdentity)) {
+ gnssDataProvider.addListener(listener, callerIdentity);
+ } else {
+ gnssDataProvider.removeListener(listener);
}
}
}
+ private static String foregroundAsString(boolean foreground) {
+ return foreground ? "foreground" : "background";
+ }
+
private static boolean isImportanceForeground(int importance) {
return importance <= FOREGROUND_IMPORTANCE_CUTOFF;
}
@@ -1218,9 +1229,8 @@
* A wrapper class holding either an ILocationListener or a PendingIntent to receive
* location updates.
*/
- private final class Receiver implements IBinder.DeathRecipient, PendingIntent.OnFinished {
+ private final class Receiver extends LinkedListenerBase implements PendingIntent.OnFinished {
private static final long WAKELOCK_TIMEOUT_MILLIS = 60 * 1000;
- final CallerIdentity mCallerIdentity;
private final int mAllowedResolutionLevel; // resolution level allowed to receiver
private final ILocationListener mListener;
@@ -1240,6 +1250,7 @@
private Receiver(ILocationListener listener, PendingIntent intent, int pid, int uid,
String packageName, WorkSource workSource, boolean hideFromAppOps) {
+ super(new CallerIdentity(uid, pid, packageName), "LocationListener");
mListener = listener;
mPendingIntent = intent;
if (listener != null) {
@@ -1248,7 +1259,6 @@
mKey = intent;
}
mAllowedResolutionLevel = getAllowedResolutionLevel(pid, uid);
- mCallerIdentity = new CallerIdentity(uid, pid, packageName);
if (workSource != null && workSource.isEmpty()) {
workSource = null;
}
@@ -1486,7 +1496,7 @@
@Override
public void binderDied() {
- if (D) Log.d(TAG, "Location listener died");
+ if (D) Log.d(TAG, "Remote " + mListenerName + " died.");
synchronized (mLock) {
removeUpdatesLocked(this);
@@ -1617,53 +1627,59 @@
return false;
}
+ CallerIdentity callerIdentity = new CallerIdentity(Binder.getCallingUid(),
+ Binder.getCallingPid(), packageName);
synchronized (mLock) {
mGnssBatchingCallback = callback;
- mGnssBatchingDeathCallback = new LinkedCallback(callback);
- try {
- callback.asBinder().linkToDeath(mGnssBatchingDeathCallback, 0 /* flags */);
- } catch (RemoteException e) {
- // if the remote process registering the listener is already dead, just swallow the
- // exception and return
- Log.e(TAG, "Remote listener already died.", e);
+ mGnssBatchingDeathCallback = new LinkedListener<>(callback,
+ "BatchedLocationCallback", callerIdentity,
+ (IBatchedLocationCallback listener) -> {
+ stopGnssBatch();
+ removeGnssBatchingCallback();
+ });
+ if (!linkToListenerDeathNotificationLocked(callback.asBinder(),
+ mGnssBatchingDeathCallback)) {
return false;
}
-
return true;
}
}
- private class LinkedCallback implements IBinder.DeathRecipient {
- private final IBatchedLocationCallback mCallback;
+ private abstract static class LinkedListenerBase implements IBinder.DeathRecipient {
+ protected final CallerIdentity mCallerIdentity;
+ protected final String mListenerName;
- private LinkedCallback(@NonNull IBatchedLocationCallback callback) {
- mCallback = callback;
+ private LinkedListenerBase(@NonNull CallerIdentity callerIdentity,
+ @NonNull String listenerName) {
+ mCallerIdentity = callerIdentity;
+ mListenerName = listenerName;
}
+ }
- @NonNull
- public IBatchedLocationCallback getUnderlyingListener() {
- return mCallback;
+ private static class LinkedListener<TListener> extends LinkedListenerBase {
+ private final TListener mListener;
+ private final Consumer<TListener> mBinderDeathCallback;
+
+ private LinkedListener(@NonNull TListener listener, String listenerName,
+ @NonNull CallerIdentity callerIdentity,
+ @NonNull Consumer<TListener> binderDeathCallback) {
+ super(callerIdentity, listenerName);
+ mListener = listener;
+ mBinderDeathCallback = binderDeathCallback;
}
@Override
public void binderDied() {
- Log.d(TAG, "Remote Batching Callback died: " + mCallback);
- stopGnssBatch();
- removeGnssBatchingCallback();
+ if (D) Log.d(TAG, "Remote " + mListenerName + " died.");
+ mBinderDeathCallback.accept(mListener);
}
}
@Override
public void removeGnssBatchingCallback() {
synchronized (mLock) {
- try {
- mGnssBatchingCallback.asBinder().unlinkToDeath(mGnssBatchingDeathCallback,
- 0 /* flags */);
- } catch (NoSuchElementException e) {
- // if the death callback isn't connected (it should be...), log error, swallow the
- // exception and return
- Log.e(TAG, "Couldn't unlink death callback.", e);
- }
+ unlinkFromListenerDeathNotificationLocked(mGnssBatchingCallback.asBinder(),
+ mGnssBatchingDeathCallback);
mGnssBatchingCallback = null;
mGnssBatchingDeathCallback = null;
}
@@ -2053,7 +2069,7 @@
}
if (!provider.isUseableLocked()) {
if (isSettingsExemptLocked(record)) {
- providerRequest.forceLocation = true;
+ providerRequest.locationSettingsIgnored = true;
providerRequest.lowPowerMode = false;
} else {
continue;
@@ -2063,8 +2079,9 @@
LocationRequest locationRequest = record.mRealRequest;
long interval = locationRequest.getInterval();
+
// if we're forcing location, don't apply any throttling
- if (!providerRequest.forceLocation && !isThrottlingExemptLocked(
+ if (!providerRequest.locationSettingsIgnored && !isThrottlingExemptLocked(
record.mReceiver.mCallerIdentity)) {
if (!record.mIsForegroundUid) {
interval = Math.max(interval, backgroundThrottleInterval);
@@ -2264,10 +2281,8 @@
if (receiver == null) {
receiver = new Receiver(listener, null, pid, uid, packageName, workSource,
hideFromAppOps);
- try {
- receiver.getListener().asBinder().linkToDeath(receiver, 0);
- } catch (RemoteException e) {
- Slog.e(TAG, "linkToDeath failed:", e);
+ if (!linkToListenerDeathNotificationLocked(receiver.getListener().asBinder(),
+ receiver)) {
return null;
}
mReceivers.put(binder, receiver);
@@ -2482,7 +2497,8 @@
if (D) Log.i(TAG, "remove " + Integer.toHexString(System.identityHashCode(receiver)));
if (mReceivers.remove(receiver.mKey) != null && receiver.isListener()) {
- receiver.getListener().asBinder().unlinkToDeath(receiver, 0);
+ unlinkFromListenerDeathNotificationLocked(receiver.getListener().asBinder(),
+ receiver);
receiver.clearPendingBroadcastsLocked();
}
@@ -2694,18 +2710,52 @@
}
@Override
- public boolean registerGnssStatusCallback(IGnssStatusListener callback, String packageName) {
+ public boolean registerGnssStatusCallback(IGnssStatusListener listener, String packageName) {
if (!hasGnssPermissions(packageName) || mGnssStatusProvider == null) {
return false;
}
- return mGnssStatusProvider.addListener(callback, new CallerIdentity(Binder.getCallingUid(),
- Binder.getCallingPid(), packageName));
+ CallerIdentity callerIdentity = new CallerIdentity(Binder.getCallingUid(),
+ Binder.getCallingPid(), packageName);
+ LinkedListener<IGnssStatusListener> linkedListener = new LinkedListener<>(listener,
+ "GnssStatusListener", callerIdentity, this::unregisterGnssStatusCallback);
+ IBinder binder = listener.asBinder();
+ synchronized (mLock) {
+ if (!linkToListenerDeathNotificationLocked(binder, linkedListener)) {
+ return false;
+ }
+
+ mGnssStatusListeners.put(binder, linkedListener);
+ long identity = Binder.clearCallingIdentity();
+ try {
+ if (isThrottlingExemptLocked(callerIdentity)
+ || isImportanceForeground(
+ mActivityManager.getPackageImportance(packageName))) {
+ mGnssStatusProvider.addListener(listener, callerIdentity);
+ }
+ return true;
+ } finally {
+ Binder.restoreCallingIdentity(identity);
+ }
+ }
}
@Override
- public void unregisterGnssStatusCallback(IGnssStatusListener callback) {
- mGnssStatusProvider.removeListener(callback);
+ public void unregisterGnssStatusCallback(IGnssStatusListener listener) {
+ if (mGnssStatusProvider == null) {
+ return;
+ }
+
+ IBinder binder = listener.asBinder();
+ synchronized (mLock) {
+ LinkedListener<IGnssStatusListener> linkedListener =
+ mGnssStatusListeners.remove(binder);
+ if (linkedListener == null) {
+ return;
+ }
+ unlinkFromListenerDeathNotificationLocked(binder, linkedListener);
+ mGnssStatusProvider.removeListener(listener);
+ }
}
@Override
@@ -2715,22 +2765,75 @@
return false;
}
+ CallerIdentity callerIdentity = new CallerIdentity(Binder.getCallingUid(),
+ Binder.getCallingPid(), packageName);
+ LinkedListener<IGnssMeasurementsListener> linkedListener = new LinkedListener<>(listener,
+ "GnssMeasurementsListener", callerIdentity, this::removeGnssMeasurementsListener);
+ IBinder binder = listener.asBinder();
synchronized (mLock) {
- CallerIdentity callerIdentity = new CallerIdentity(Binder.getCallingUid(),
- Binder.getCallingPid(), packageName);
- mGnssMeasurementsListeners.put(listener.asBinder(), callerIdentity);
+ if (!linkToListenerDeathNotificationLocked(binder, linkedListener)) {
+ return false;
+ }
+
+ mGnssMeasurementsListeners.put(binder, linkedListener);
long identity = Binder.clearCallingIdentity();
try {
if (isThrottlingExemptLocked(callerIdentity)
|| isImportanceForeground(
mActivityManager.getPackageImportance(packageName))) {
- return mGnssMeasurementsProvider.addListener(listener, callerIdentity);
+ mGnssMeasurementsProvider.addListener(listener, callerIdentity);
}
+ return true;
} finally {
Binder.restoreCallingIdentity(identity);
}
+ }
+ }
+ @Override
+ public void removeGnssMeasurementsListener(IGnssMeasurementsListener listener) {
+ if (mGnssMeasurementsProvider == null) {
+ return;
+ }
+
+ IBinder binder = listener.asBinder();
+ synchronized (mLock) {
+ LinkedListener<IGnssMeasurementsListener> linkedListener =
+ mGnssMeasurementsListeners.remove(binder);
+ if (linkedListener == null) {
+ return;
+ }
+ unlinkFromListenerDeathNotificationLocked(binder, linkedListener);
+ mGnssMeasurementsProvider.removeListener(listener);
+ }
+ }
+
+
+ private boolean linkToListenerDeathNotificationLocked(IBinder binder,
+ LinkedListenerBase linkedListener) {
+ try {
+ binder.linkToDeath(linkedListener, 0 /* flags */);
return true;
+ } catch (RemoteException e) {
+ // if the remote process registering the listener is already dead, just swallow the
+ // exception and return
+ Log.w(TAG, "Could not link " + linkedListener.mListenerName + " death callback.",
+ e);
+ return false;
+ }
+ }
+
+ private boolean unlinkFromListenerDeathNotificationLocked(IBinder binder,
+ LinkedListenerBase linkedListener) {
+ try {
+ binder.unlinkToDeath(linkedListener, 0 /* flags */);
+ return true;
+ } catch (NoSuchElementException e) {
+ // if the death callback isn't connected (it should be...), log error,
+ // swallow the exception and return
+ Log.w(TAG, "Could not unlink " + linkedListener.mListenerName + " death callback.",
+ e);
+ return false;
}
}
@@ -2759,52 +2862,53 @@
}
@Override
- public void removeGnssMeasurementsListener(IGnssMeasurementsListener listener) {
- if (mGnssMeasurementsProvider == null) {
- return;
- }
-
- synchronized (mLock) {
- mGnssMeasurementsListeners.remove(listener.asBinder());
- mGnssMeasurementsProvider.removeListener(listener);
- }
- }
-
- @Override
public boolean addGnssNavigationMessageListener(
- IGnssNavigationMessageListener listener,
- String packageName) {
+ IGnssNavigationMessageListener listener, String packageName) {
if (!hasGnssPermissions(packageName) || mGnssNavigationMessageProvider == null) {
return false;
}
+ CallerIdentity callerIdentity = new CallerIdentity(Binder.getCallingUid(),
+ Binder.getCallingPid(), packageName);
+ LinkedListener<IGnssNavigationMessageListener> linkedListener =
+ new LinkedListener<>(listener, "GnssNavigationMessageListener", callerIdentity,
+ this::removeGnssNavigationMessageListener);
+ IBinder binder = listener.asBinder();
synchronized (mLock) {
- CallerIdentity callerIdentity = new CallerIdentity(Binder.getCallingUid(),
- Binder.getCallingPid(), packageName);
+ if (!linkToListenerDeathNotificationLocked(binder, linkedListener)) {
+ return false;
+ }
- mGnssNavigationMessageListeners.put(listener.asBinder(), callerIdentity);
+ mGnssNavigationMessageListeners.put(binder, linkedListener);
long identity = Binder.clearCallingIdentity();
try {
if (isThrottlingExemptLocked(callerIdentity)
|| isImportanceForeground(
mActivityManager.getPackageImportance(packageName))) {
- return mGnssNavigationMessageProvider.addListener(listener, callerIdentity);
+ mGnssNavigationMessageProvider.addListener(listener, callerIdentity);
}
+ return true;
} finally {
Binder.restoreCallingIdentity(identity);
}
-
- return true;
}
}
@Override
public void removeGnssNavigationMessageListener(IGnssNavigationMessageListener listener) {
- if (mGnssNavigationMessageProvider != null) {
- synchronized (mLock) {
- mGnssNavigationMessageListeners.remove(listener.asBinder());
- mGnssNavigationMessageProvider.removeListener(listener);
+ if (mGnssNavigationMessageProvider == null) {
+ return;
+ }
+
+ IBinder binder = listener.asBinder();
+ synchronized (mLock) {
+ LinkedListener<IGnssNavigationMessageListener> linkedListener =
+ mGnssNavigationMessageListeners.remove(binder);
+ if (linkedListener == null) {
+ return;
}
+ unlinkFromListenerDeathNotificationLocked(binder, linkedListener);
+ mGnssNavigationMessageProvider.removeListener(listener);
}
}
@@ -3368,18 +3472,14 @@
pw.println(" " + record);
}
}
+
pw.println(" Active GnssMeasurement Listeners:");
- for (CallerIdentity callerIdentity : mGnssMeasurementsListeners.values()) {
- pw.println(" " + callerIdentity.mPid + " " + callerIdentity.mUid + " "
- + callerIdentity.mPackageName + ": "
- + isThrottlingExemptLocked(callerIdentity));
- }
+ dumpGnssDataListenersLocked(pw, mGnssMeasurementsListeners);
pw.println(" Active GnssNavigationMessage Listeners:");
- for (CallerIdentity callerIdentity : mGnssNavigationMessageListeners.values()) {
- pw.println(" " + callerIdentity.mPid + " " + callerIdentity.mUid + " "
- + callerIdentity.mPackageName + ": "
- + isThrottlingExemptLocked(callerIdentity));
- }
+ dumpGnssDataListenersLocked(pw, mGnssNavigationMessageListeners);
+ pw.println(" Active GnssStatus Listeners:");
+ dumpGnssDataListenersLocked(pw, mGnssStatusListeners);
+
pw.println(" Historical Records by Provider:");
for (Map.Entry<PackageProviderKey, PackageStatistics> entry
: mRequestStatistics.statistics.entrySet()) {
@@ -3432,4 +3532,15 @@
}
}
}
+
+ @GuardedBy("mLock")
+ private void dumpGnssDataListenersLocked(PrintWriter pw,
+ ArrayMap<IBinder, ? extends LinkedListenerBase> gnssDataListeners) {
+ for (LinkedListenerBase listener : gnssDataListeners.values()) {
+ CallerIdentity callerIdentity = listener.mCallerIdentity;
+ pw.println(" " + callerIdentity.mPid + " " + callerIdentity.mUid + " "
+ + callerIdentity.mPackageName + ": "
+ + isThrottlingExemptLocked(callerIdentity));
+ }
+ }
}
diff --git a/services/core/java/com/android/server/LooperStatsService.java b/services/core/java/com/android/server/LooperStatsService.java
index 9184128..c334540 100644
--- a/services/core/java/com/android/server/LooperStatsService.java
+++ b/services/core/java/com/android/server/LooperStatsService.java
@@ -51,16 +51,19 @@
private static final String LOOPER_STATS_SERVICE_NAME = "looper_stats";
private static final String SETTINGS_ENABLED_KEY = "enabled";
private static final String SETTINGS_SAMPLING_INTERVAL_KEY = "sampling_interval";
+ private static final String SETTINGS_TRACK_SCREEN_INTERACTIVE_KEY = "track_screen_state";
private static final String DEBUG_SYS_LOOPER_STATS_ENABLED =
"debug.sys.looper_stats_enabled";
private static final int DEFAULT_SAMPLING_INTERVAL = 100;
private static final int DEFAULT_ENTRIES_SIZE_CAP = 2000;
private static final boolean DEFAULT_ENABLED = true;
+ private static final boolean DEFAULT_TRACK_SCREEN_INTERACTIVE = false;
private final Context mContext;
private final LooperStats mStats;
// Default should be false so that the first call to #setEnabled installed the looper observer.
private boolean mEnabled = false;
+ private boolean mTrackScreenInteractive = false;
private LooperStatsService(Context context, LooperStats stats) {
this.mContext = context;
@@ -79,6 +82,9 @@
setSamplingInterval(
parser.getInt(SETTINGS_SAMPLING_INTERVAL_KEY, DEFAULT_SAMPLING_INTERVAL));
+ setTrackScreenInteractive(
+ parser.getBoolean(SETTINGS_TRACK_SCREEN_INTERACTIVE_KEY,
+ DEFAULT_TRACK_SCREEN_INTERACTIVE));
// Manually specified value takes precedence over Settings.
setEnabled(SystemProperties.getBoolean(
DEBUG_SYS_LOOPER_STATS_ENABLED,
@@ -155,6 +161,13 @@
}
}
+ private void setTrackScreenInteractive(boolean enabled) {
+ if (mTrackScreenInteractive != enabled) {
+ mTrackScreenInteractive = enabled;
+ mStats.reset();
+ }
+ }
+
private void setSamplingInterval(int samplingInterval) {
if (samplingInterval > 0) {
mStats.setSamplingInterval(samplingInterval);
diff --git a/services/core/java/com/android/server/StorageManagerService.java b/services/core/java/com/android/server/StorageManagerService.java
index e7d7434..5da281a 100644
--- a/services/core/java/com/android/server/StorageManagerService.java
+++ b/services/core/java/com/android/server/StorageManagerService.java
@@ -860,7 +860,7 @@
} else if (remote == 1) {
res = true;
} else {
- res = false;
+ res = true;
}
Slog.d(TAG, "Isolated storage local flag " + local + " and remote flag "
@@ -1533,7 +1533,7 @@
// Snapshot feature flag used for this boot
SystemProperties.set(StorageManager.PROP_ISOLATED_STORAGE_SNAPSHOT, Boolean.toString(
- SystemProperties.getBoolean(StorageManager.PROP_ISOLATED_STORAGE, false)));
+ SystemProperties.getBoolean(StorageManager.PROP_ISOLATED_STORAGE, true)));
mContext = context;
mResolver = mContext.getContentResolver();
diff --git a/services/core/java/com/android/server/TelephonyRegistry.java b/services/core/java/com/android/server/TelephonyRegistry.java
index 2f1510e..8120976 100644
--- a/services/core/java/com/android/server/TelephonyRegistry.java
+++ b/services/core/java/com/android/server/TelephonyRegistry.java
@@ -26,6 +26,7 @@
import android.net.LinkProperties;
import android.net.NetworkCapabilities;
import android.os.Binder;
+import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
@@ -246,7 +247,10 @@
private PreciseDataConnectionState mPreciseDataConnectionState =
new PreciseDataConnectionState();
- static final int ENFORCE_COARSE_LOCATION_PERMISSION_MASK =
+ // Nothing here yet, but putting it here in case we want to add more in the future.
+ static final int ENFORCE_COARSE_LOCATION_PERMISSION_MASK = 0;
+
+ static final int ENFORCE_FINE_LOCATION_PERMISSION_MASK =
PhoneStateListener.LISTEN_CELL_LOCATION
| PhoneStateListener.LISTEN_CELL_INFO;
@@ -637,8 +641,14 @@
if ((events & PhoneStateListener.LISTEN_SERVICE_STATE) != 0) {
try {
if (VDBG) log("listen: call onSSC state=" + mServiceState[phoneId]);
- r.callback.onServiceStateChanged(
- new ServiceState(mServiceState[phoneId]));
+ ServiceState rawSs = new ServiceState(mServiceState[phoneId]);
+ if (checkFineLocationAccess(r, Build.VERSION_CODES.Q)) {
+ r.callback.onServiceStateChanged(rawSs);
+ } else if (checkCoarseLocationAccess(r, Build.VERSION_CODES.Q)) {
+ r.callback.onServiceStateChanged(rawSs.sanitizeLocationInfo(false));
+ } else {
+ r.callback.onServiceStateChanged(rawSs.sanitizeLocationInfo(true));
+ }
} catch (RemoteException ex) {
remove(r.binder);
}
@@ -673,7 +683,7 @@
try {
if (DBG_LOC) log("listen: mCellLocation = "
+ mCellLocation[phoneId]);
- if (checkLocationAccess(r)) {
+ if (checkFineLocationAccess(r, Build.VERSION_CODES.Q)) {
r.callback.onCellLocationChanged(
new Bundle(mCellLocation[phoneId]));
}
@@ -722,7 +732,7 @@
try {
if (DBG_LOC) log("listen: mCellInfo[" + phoneId + "] = "
+ mCellInfo.get(phoneId));
- if (checkLocationAccess(r)) {
+ if (checkFineLocationAccess(r, Build.VERSION_CODES.Q)) {
r.callback.onCellInfoChanged(mCellInfo.get(phoneId));
}
} catch (RemoteException ex) {
@@ -1009,13 +1019,22 @@
}
if (r.matchPhoneStateListenerEvent(PhoneStateListener.LISTEN_SERVICE_STATE) &&
idMatch(r.subId, subId, phoneId)) {
+
try {
+ ServiceState stateToSend;
+ if (checkFineLocationAccess(r, Build.VERSION_CODES.Q)) {
+ stateToSend = new ServiceState(state);
+ } else if (checkCoarseLocationAccess(r, Build.VERSION_CODES.Q)) {
+ stateToSend = state.sanitizeLocationInfo(false);
+ } else {
+ stateToSend = state.sanitizeLocationInfo(true);
+ }
if (DBG) {
log("notifyServiceStateForSubscriber: callback.onSSC r=" + r
+ " subId=" + subId + " phoneId=" + phoneId
+ " state=" + state);
}
- r.callback.onServiceStateChanged(new ServiceState(state));
+ r.callback.onServiceStateChanged(stateToSend);
} catch (RemoteException ex) {
mRemoveList.add(r.binder);
}
@@ -1198,7 +1217,7 @@
for (Record r : mRecords) {
if (validateEventsAndUserLocked(r, PhoneStateListener.LISTEN_CELL_INFO) &&
idMatch(r.subId, subId, phoneId) &&
- checkLocationAccess(r)) {
+ checkFineLocationAccess(r, Build.VERSION_CODES.Q)) {
try {
if (DBG_LOC) {
log("notifyCellInfo: mCellInfo=" + cellInfo + " r=" + r);
@@ -1500,7 +1519,7 @@
for (Record r : mRecords) {
if (validateEventsAndUserLocked(r, PhoneStateListener.LISTEN_CELL_LOCATION) &&
idMatch(r.subId, subId, phoneId) &&
- checkLocationAccess(r)) {
+ checkFineLocationAccess(r, Build.VERSION_CODES.Q)) {
try {
if (DBG_LOC) {
log("notifyCellLocation: cellLocation=" + cellLocation
@@ -2108,12 +2127,35 @@
private boolean checkListenerPermission(
int events, int subId, String callingPackage, String message) {
+ LocationAccessPolicy.LocationPermissionQuery.Builder locationQueryBuilder =
+ new LocationAccessPolicy.LocationPermissionQuery.Builder()
+ .setCallingPackage(callingPackage)
+ .setMethod(message + " events: " + events)
+ .setCallingPid(Binder.getCallingPid())
+ .setCallingUid(Binder.getCallingUid());
+
+ boolean shouldCheckLocationPermissions = false;
if ((events & ENFORCE_COARSE_LOCATION_PERMISSION_MASK) != 0) {
- mContext.enforceCallingOrSelfPermission(
- android.Manifest.permission.ACCESS_COARSE_LOCATION, null);
- if (mAppOps.noteOp(AppOpsManager.OP_COARSE_LOCATION, Binder.getCallingUid(),
- callingPackage) != AppOpsManager.MODE_ALLOWED) {
- return false;
+ locationQueryBuilder.setMinSdkVersionForCoarse(0);
+ shouldCheckLocationPermissions = true;
+ }
+
+ if ((events & ENFORCE_FINE_LOCATION_PERMISSION_MASK) != 0) {
+ // Everything that requires fine location started in Q. So far...
+ locationQueryBuilder.setMinSdkVersionForFine(Build.VERSION_CODES.Q);
+ shouldCheckLocationPermissions = true;
+ }
+
+ if (shouldCheckLocationPermissions) {
+ LocationAccessPolicy.LocationPermissionResult result =
+ LocationAccessPolicy.checkLocationPermission(
+ mContext, locationQueryBuilder.build());
+ switch (result) {
+ case DENIED_HARD:
+ throw new SecurityException("Unable to listen for events " + events + " due to "
+ + "insufficient location permissions.");
+ case DENIED_SOFT:
+ return false;
}
}
@@ -2228,15 +2270,38 @@
}
}
- private boolean checkLocationAccess(Record r) {
- long token = Binder.clearCallingIdentity();
- try {
- return LocationAccessPolicy.canAccessCellLocation(mContext,
- r.callingPackage, r.callerUid, r.callerPid,
- /*throwOnDeniedPermission*/ false);
- } finally {
- Binder.restoreCallingIdentity(token);
- }
+ private boolean checkFineLocationAccess(Record r, int minSdk) {
+ LocationAccessPolicy.LocationPermissionQuery query =
+ new LocationAccessPolicy.LocationPermissionQuery.Builder()
+ .setCallingPackage(r.callingPackage)
+ .setCallingPid(r.callerPid)
+ .setCallingUid(r.callerUid)
+ .setMethod("TelephonyRegistry push")
+ .setMinSdkVersionForFine(minSdk)
+ .build();
+
+ return Binder.withCleanCallingIdentity(() -> {
+ LocationAccessPolicy.LocationPermissionResult locationResult =
+ LocationAccessPolicy.checkLocationPermission(mContext, query);
+ return locationResult == LocationAccessPolicy.LocationPermissionResult.ALLOWED;
+ });
+ }
+
+ private boolean checkCoarseLocationAccess(Record r, int minSdk) {
+ LocationAccessPolicy.LocationPermissionQuery query =
+ new LocationAccessPolicy.LocationPermissionQuery.Builder()
+ .setCallingPackage(r.callingPackage)
+ .setCallingPid(r.callerPid)
+ .setCallingUid(r.callerUid)
+ .setMethod("TelephonyRegistry push")
+ .setMinSdkVersionForCoarse(minSdk)
+ .build();
+
+ return Binder.withCleanCallingIdentity(() -> {
+ LocationAccessPolicy.LocationPermissionResult locationResult =
+ LocationAccessPolicy.checkLocationPermission(mContext, query);
+ return locationResult == LocationAccessPolicy.LocationPermissionResult.ALLOWED;
+ });
}
private void checkPossibleMissNotify(Record r, int phoneId) {
@@ -2286,7 +2351,7 @@
log("checkPossibleMissNotify: onCellInfoChanged[" + phoneId + "] = "
+ mCellInfo.get(phoneId));
}
- if (checkLocationAccess(r)) {
+ if (checkFineLocationAccess(r, Build.VERSION_CODES.Q)) {
r.callback.onCellInfoChanged(mCellInfo.get(phoneId));
}
} catch (RemoteException ex) {
@@ -2336,7 +2401,7 @@
try {
if (DBG_LOC) log("checkPossibleMissNotify: onCellLocationChanged mCellLocation = "
+ mCellLocation[phoneId]);
- if (checkLocationAccess(r)) {
+ if (checkFineLocationAccess(r, Build.VERSION_CODES.Q)) {
r.callback.onCellLocationChanged(new Bundle(mCellLocation[phoneId]));
}
} catch (RemoteException ex) {
diff --git a/services/core/java/com/android/server/WiredAccessoryManager.java b/services/core/java/com/android/server/WiredAccessoryManager.java
index 3939bee..9bbc315 100644
--- a/services/core/java/com/android/server/WiredAccessoryManager.java
+++ b/services/core/java/com/android/server/WiredAccessoryManager.java
@@ -23,6 +23,7 @@
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.UEventObserver;
+import android.util.Pair;
import android.util.Slog;
import android.media.AudioManager;
import android.util.Log;
@@ -31,6 +32,7 @@
import com.android.internal.R;
import com.android.server.input.InputManagerService;
import com.android.server.input.InputManagerService.WiredAccessoryCallbacks;
+
import static com.android.server.input.InputManagerService.SW_HEADPHONE_INSERT;
import static com.android.server.input.InputManagerService.SW_MICROPHONE_INSERT;
import static com.android.server.input.InputManagerService.SW_LINEOUT_INSERT;
@@ -41,6 +43,7 @@
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@@ -52,7 +55,7 @@
*/
final class WiredAccessoryManager implements WiredAccessoryCallbacks {
private static final String TAG = WiredAccessoryManager.class.getSimpleName();
- private static final boolean LOG = true;
+ private static final boolean LOG = false;
private static final int BIT_HEADSET = (1 << 0);
private static final int BIT_HEADSET_NO_MIC = (1 << 1);
@@ -60,9 +63,9 @@
private static final int BIT_USB_HEADSET_DGTL = (1 << 3);
private static final int BIT_HDMI_AUDIO = (1 << 4);
private static final int BIT_LINEOUT = (1 << 5);
- private static final int SUPPORTED_HEADSETS = (BIT_HEADSET|BIT_HEADSET_NO_MIC|
- BIT_USB_HEADSET_ANLG|BIT_USB_HEADSET_DGTL|
- BIT_HDMI_AUDIO|BIT_LINEOUT);
+ private static final int SUPPORTED_HEADSETS = (BIT_HEADSET | BIT_HEADSET_NO_MIC |
+ BIT_USB_HEADSET_ANLG | BIT_USB_HEADSET_DGTL |
+ BIT_HDMI_AUDIO | BIT_LINEOUT);
private static final String NAME_H2W = "h2w";
private static final String NAME_USB_AUDIO = "usb_audio";
@@ -82,30 +85,34 @@
private int mSwitchValues;
private final WiredAccessoryObserver mObserver;
+ private final WiredAccessoryExtconObserver mExtconObserver;
private final InputManagerService mInputManager;
private final boolean mUseDevInputEventForAudioJack;
public WiredAccessoryManager(Context context, InputManagerService inputManager) {
- PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
+ PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "WiredAccessoryManager");
mWakeLock.setReferenceCounted(false);
- mAudioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
+ mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
mInputManager = inputManager;
mUseDevInputEventForAudioJack =
context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);
+ mExtconObserver = new WiredAccessoryExtconObserver();
mObserver = new WiredAccessoryObserver();
}
private void onSystemReady() {
if (mUseDevInputEventForAudioJack) {
int switchValues = 0;
- if (mInputManager.getSwitchState(-1, InputDevice.SOURCE_ANY, SW_HEADPHONE_INSERT) == 1) {
+ if (mInputManager.getSwitchState(-1, InputDevice.SOURCE_ANY, SW_HEADPHONE_INSERT)
+ == 1) {
switchValues |= SW_HEADPHONE_INSERT_BIT;
}
- if (mInputManager.getSwitchState(-1, InputDevice.SOURCE_ANY, SW_MICROPHONE_INSERT) == 1) {
+ if (mInputManager.getSwitchState(-1, InputDevice.SOURCE_ANY, SW_MICROPHONE_INSERT)
+ == 1) {
switchValues |= SW_MICROPHONE_INSERT_BIT;
}
if (mInputManager.getSwitchState(-1, InputDevice.SOURCE_ANY, SW_LINEOUT_INSERT) == 1) {
@@ -115,20 +122,31 @@
SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_LINEOUT_INSERT_BIT);
}
- mObserver.init();
+
+ if (ExtconUEventObserver.extconExists()) {
+ if (mUseDevInputEventForAudioJack) {
+ Log.w(TAG, "Both input event and extcon are used for audio jack,"
+ + " please just choose one.");
+ }
+ mExtconObserver.init();
+ } else {
+ mObserver.init();
+ }
}
@Override
public void notifyWiredAccessoryChanged(long whenNanos, int switchValues, int switchMask) {
- if (LOG) Slog.v(TAG, "notifyWiredAccessoryChanged: when=" + whenNanos
- + " bits=" + switchCodeToString(switchValues, switchMask)
- + " mask=" + Integer.toHexString(switchMask));
+ if (LOG) {
+ Slog.v(TAG, "notifyWiredAccessoryChanged: when=" + whenNanos
+ + " bits=" + switchCodeToString(switchValues, switchMask)
+ + " mask=" + Integer.toHexString(switchMask));
+ }
synchronized (mLock) {
int headset;
mSwitchValues = (mSwitchValues & ~switchMask) | switchValues;
switch (mSwitchValues &
- (SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_LINEOUT_INSERT_BIT)) {
+ (SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_LINEOUT_INSERT_BIT)) {
case 0:
headset = 0;
break;
@@ -155,7 +173,7 @@
}
updateLocked(NAME_H2W,
- (mHeadsetState & ~(BIT_HEADSET | BIT_HEADSET_NO_MIC | BIT_LINEOUT)) | headset);
+ (mHeadsetState & ~(BIT_HEADSET | BIT_HEADSET_NO_MIC | BIT_LINEOUT)) | headset);
}
}
@@ -175,7 +193,7 @@
* results in support for the last one plugged in. Similarly, unplugging either is seen as
* unplugging all.
*
- * @param newName One of the NAME_xxx variables defined above.
+ * @param newName One of the NAME_xxx variables defined above.
* @param newState 0 or one of the BIT_xxx variables defined above.
*/
private void updateLocked(String newName, int newState) {
@@ -186,10 +204,12 @@
int h2w_headset = headsetState & (BIT_HEADSET | BIT_HEADSET_NO_MIC | BIT_LINEOUT);
boolean h2wStateChange = true;
boolean usbStateChange = true;
- if (LOG) Slog.v(TAG, "newName=" + newName
- + " newState=" + newState
- + " headsetState=" + headsetState
- + " prev headsetState=" + mHeadsetState);
+ if (LOG) {
+ Slog.v(TAG, "newName=" + newName
+ + " newState=" + newState
+ + " headsetState=" + headsetState
+ + " prev headsetState=" + mHeadsetState);
+ }
if (mHeadsetState == headsetState) {
Log.e(TAG, "No state change.");
@@ -229,7 +249,7 @@
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_NEW_DEVICE_STATE:
- setDevicesState(msg.arg1, msg.arg2, (String)msg.obj);
+ setDevicesState(msg.arg1, msg.arg2, (String) msg.obj);
mWakeLock.release();
break;
case MSG_SYSTEM_READY:
@@ -269,9 +289,9 @@
if (headset == BIT_HEADSET) {
outDevice = AudioManager.DEVICE_OUT_WIRED_HEADSET;
inDevice = AudioManager.DEVICE_IN_WIRED_HEADSET;
- } else if (headset == BIT_HEADSET_NO_MIC){
+ } else if (headset == BIT_HEADSET_NO_MIC) {
outDevice = AudioManager.DEVICE_OUT_WIRED_HEADPHONE;
- } else if (headset == BIT_LINEOUT){
+ } else if (headset == BIT_LINEOUT) {
outDevice = AudioManager.DEVICE_OUT_LINE;
} else if (headset == BIT_USB_HEADSET_ANLG) {
outDevice = AudioManager.DEVICE_OUT_ANLG_DOCK_HEADSET;
@@ -280,7 +300,7 @@
} else if (headset == BIT_HDMI_AUDIO) {
outDevice = AudioManager.DEVICE_OUT_HDMI;
} else {
- Slog.e(TAG, "setDeviceState() invalid headset type: "+headset);
+ Slog.e(TAG, "setDeviceState() invalid headset type: " + headset);
return;
}
@@ -290,10 +310,10 @@
}
if (outDevice != 0) {
- mAudioManager.setWiredDeviceConnectionState(outDevice, state, "", headsetName);
+ mAudioManager.setWiredDeviceConnectionState(outDevice, state, "", headsetName);
}
if (inDevice != 0) {
- mAudioManager.setWiredDeviceConnectionState(inDevice, state, "", headsetName);
+ mAudioManager.setWiredDeviceConnectionState(inDevice, state, "", headsetName);
}
}
}
@@ -340,7 +360,7 @@
" not found while attempting to determine initial switch state");
} catch (Exception e) {
Slog.e(TAG, "Error while attempting to determine initial switch state for "
- + uei.getDevName() , e);
+ + uei.getDevName(), e);
}
}
}
@@ -350,7 +370,7 @@
// observe three UEVENTs
for (int i = 0; i < mUEventInfo.size(); ++i) {
UEventInfo uei = mUEventInfo.get(i);
- startObserving("DEVPATH="+uei.getDevPath());
+ startObserving("DEVPATH=" + uei.getDevPath());
}
}
@@ -438,7 +458,9 @@
mStateNbits = stateNbits;
}
- public String getDevName() { return mDevName; }
+ public String getDevName() {
+ return mDevName;
+ }
public String getDevPath() {
return String.format(Locale.US, "/devices/virtual/switch/%s", mDevName);
@@ -456,11 +478,84 @@
public int computeNewHeadsetState(int headsetState, int switchState) {
int preserveMask = ~(mState1Bits | mState2Bits | mStateNbits);
int setBits = ((switchState == 1) ? mState1Bits :
- ((switchState == 2) ? mState2Bits :
- ((switchState == mStateNbits) ? mStateNbits : 0)));
+ ((switchState == 2) ? mState2Bits :
+ ((switchState == mStateNbits) ? mStateNbits : 0)));
return ((headsetState & preserveMask) | setBits);
}
}
}
+
+ private class WiredAccessoryExtconObserver extends ExtconStateObserver<Pair<Integer, Integer>> {
+ private final List<ExtconInfo> mExtconInfos;
+
+ WiredAccessoryExtconObserver() {
+ mExtconInfos = ExtconInfo.getExtconInfos(".*audio.*");
+
+ }
+
+ private void init() {
+ for (ExtconInfo extconInfo : mExtconInfos) {
+ Pair<Integer, Integer> state = null;
+ try {
+ state = parseStateFromFile(extconInfo);
+ } catch (FileNotFoundException e) {
+ Slog.w(TAG, extconInfo.getStatePath()
+ + " not found while attempting to determine initial state", e);
+ } catch (IOException e) {
+ Slog.e(
+ TAG,
+ "Error reading " + extconInfo.getStatePath()
+ + " while attempting to determine initial state",
+ e);
+ }
+ if (state != null) {
+ updateState(extconInfo, extconInfo.getName(), state);
+ }
+ if (LOG) Slog.d(TAG, "observing " + extconInfo.getName());
+ startObserving(extconInfo);
+ }
+
+ }
+
+ @Override
+ public Pair<Integer, Integer> parseState(ExtconInfo extconInfo, String status) {
+ if (LOG) Slog.v(TAG, "status " + status);
+ int []maskAndState = {0,0};
+ // extcon event state changes from kernel4.9
+ // new state will be like STATE=MICROPHONE=1\nHEADPHONE=0
+ updateBit(maskAndState, BIT_HEADSET_NO_MIC, status, "HEADPHONE") ;
+ updateBit(maskAndState, BIT_HEADSET, status,"MICROPHONE") ;
+ updateBit(maskAndState, BIT_HDMI_AUDIO, status,"HDMI") ;
+ updateBit(maskAndState, BIT_LINEOUT, status,"LINE-OUT") ;
+ if (LOG) Slog.v(TAG, "mask " + maskAndState[0] + " state " + maskAndState[1]);
+ return Pair.create(maskAndState[0],maskAndState[1]);
+ }
+
+ @Override
+ public void updateState(ExtconInfo extconInfo, String name,
+ Pair<Integer, Integer> maskAndState) {
+ synchronized (mLock) {
+ int mask = maskAndState.first;
+ int state = maskAndState.second;
+ updateLocked(name, mHeadsetState | (mask & state) & ~(mask & ~state));
+ return;
+ }
+ }
+ }
+
+ /**
+ * Updates the mask bit at {@code position} to 1 and the state bit at {@code position} to true
+ * if {@code name=1} or false if {}@code name=0} is contained in {@code state}.
+ */
+ private static void updateBit(int[] maskAndState, int position, String state, String name) {
+ maskAndState[0] |= position;
+ if (state.contains(name + "=1")) {
+ maskAndState[0] |= position;
+ maskAndState[1] |= position;
+ } else if (state.contains(name + "=0")) {
+ maskAndState[0] |= position;
+ maskAndState[1] &= ~position;
+ }
+ }
}
diff --git a/services/core/java/com/android/server/adb/AdbDebuggingManager.java b/services/core/java/com/android/server/adb/AdbDebuggingManager.java
index eaf790b..8ccb6e2 100644
--- a/services/core/java/com/android/server/adb/AdbDebuggingManager.java
+++ b/services/core/java/com/android/server/adb/AdbDebuggingManager.java
@@ -328,6 +328,9 @@
mConnectedKey = key;
mAdbKeyStore.setLastConnectionTime(key, System.currentTimeMillis());
scheduleJobToUpdateAdbKeyStore();
+ // write this key to adb_keys as well so that subsequent connections can
+ // go through the expected SIGNATURE interaction.
+ writeKey(key);
}
logAdbConnectionChanged(key, AdbProtoEnums.USER_ALLOWED, alwaysAllow);
}
@@ -360,20 +363,9 @@
}
break;
}
- // Check if the key should be allowed without user interaction.
- if (mAdbKeyStore.isKeyAuthorized(key)) {
- if (mThread != null) {
- mThread.sendResponse("OK");
- mAdbKeyStore.setLastConnectionTime(key, System.currentTimeMillis());
- logAdbConnectionChanged(key, AdbProtoEnums.AUTOMATICALLY_ALLOWED, true);
- mConnectedKey = key;
- scheduleJobToUpdateAdbKeyStore();
- }
- } else {
- logAdbConnectionChanged(key, AdbProtoEnums.AWAITING_USER_APPROVAL, false);
- mFingerprints = fingerprints;
- startConfirmation(key, mFingerprints);
- }
+ logAdbConnectionChanged(key, AdbProtoEnums.AWAITING_USER_APPROVAL, false);
+ mFingerprints = fingerprints;
+ startConfirmation(key, mFingerprints);
break;
}
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 60a45bf..2f20572 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -6630,8 +6630,7 @@
String msg;
if ((msg = checkContentProviderAssociation(r, callingUid, cpi)) != null) {
- throw new SecurityException("Content provider lookup "
- + cpr.name.flattenToShortString()
+ throw new SecurityException("Content provider lookup " + name
+ " failed: association not allowed with package " + msg);
}
checkTime(startTime, "getContentProviderImpl: before checkContentProviderPermission");
@@ -18101,8 +18100,10 @@
if (!queue.isIdle()) {
final String msg = "Waiting for queue " + queue + " to become idle...";
pw.println(msg);
+ pw.println(queue.describeState());
pw.flush();
Slog.v(TAG, msg);
+ queue.cancelDeferrals();
idle = false;
}
}
diff --git a/services/core/java/com/android/server/am/BroadcastDispatcher.java b/services/core/java/com/android/server/am/BroadcastDispatcher.java
index 6371cd3..0b38ef9 100644
--- a/services/core/java/com/android/server/am/BroadcastDispatcher.java
+++ b/services/core/java/com/android/server/am/BroadcastDispatcher.java
@@ -65,6 +65,14 @@
broadcasts.add(br);
}
+ int size() {
+ return broadcasts.size();
+ }
+
+ boolean isEmpty() {
+ return broadcasts.isEmpty();
+ }
+
void writeToProto(ProtoOutputStream proto, long fieldId) {
for (BroadcastRecord br : broadcasts) {
br.writeToProto(proto, fieldId);
@@ -252,22 +260,48 @@
synchronized (mLock) {
return mCurrentBroadcast == null
&& mOrderedBroadcasts.isEmpty()
- && mDeferredBroadcasts.isEmpty()
- && mAlarmBroadcasts.isEmpty();
+ && isDeferralsListEmpty(mDeferredBroadcasts)
+ && isDeferralsListEmpty(mAlarmBroadcasts);
}
}
- /**
- * Not quite the traditional size() measurement; includes any in-process but
- * not yet retired active outbound broadcast.
- */
- public int totalUndelivered() {
- synchronized (mLock) {
- return mAlarmBroadcasts.size()
- + mDeferredBroadcasts.size()
- + mOrderedBroadcasts.size()
- + (mCurrentBroadcast == null ? 0 : 1);
+ private static int pendingInDeferralsList(ArrayList<Deferrals> list) {
+ int pending = 0;
+ final int numEntries = list.size();
+ for (int i = 0; i < numEntries; i++) {
+ pending += list.get(i).size();
}
+ return pending;
+ }
+
+ private static boolean isDeferralsListEmpty(ArrayList<Deferrals> list) {
+ return pendingInDeferralsList(list) == 0;
+ }
+
+ /**
+ * Strictly for logging, describe the currently pending contents in a human-
+ * readable way
+ */
+ public String describeStateLocked() {
+ final StringBuilder sb = new StringBuilder(128);
+ if (mCurrentBroadcast != null) {
+ sb.append("1 in flight, ");
+ }
+ sb.append(mOrderedBroadcasts.size());
+ sb.append(" ordered");
+ int n = pendingInDeferralsList(mAlarmBroadcasts);
+ if (n > 0) {
+ sb.append(", ");
+ sb.append(n);
+ sb.append(" deferrals in alarm recipients");
+ }
+ n = pendingInDeferralsList(mDeferredBroadcasts);
+ if (n > 0) {
+ sb.append(", ");
+ sb.append(n);
+ sb.append(" deferred");
+ }
+ return sb.toString();
}
// ----------------------------------
@@ -579,6 +613,26 @@
}
}
+ /**
+ * Cancel all current deferrals; that is, make all currently-deferred broadcasts
+ * immediately deliverable. Used by the wait-for-broadcast-idle mechanism.
+ */
+ public void cancelDeferrals() {
+ synchronized (mLock) {
+ zeroDeferralTimes(mAlarmBroadcasts);
+ zeroDeferralTimes(mDeferredBroadcasts);
+ }
+ }
+
+ private static void zeroDeferralTimes(ArrayList<Deferrals> list) {
+ final int num = list.size();
+ for (int i = 0; i < num; i++) {
+ Deferrals d = list.get(i);
+ // Safe to do this in-place because it won't break ordering
+ d.deferUntil = d.deferredBy = 0;
+ }
+ }
+
// ----------------------------------
/**
diff --git a/services/core/java/com/android/server/am/BroadcastQueue.java b/services/core/java/com/android/server/am/BroadcastQueue.java
index f0b137a..d9ea1da 100644
--- a/services/core/java/com/android/server/am/BroadcastQueue.java
+++ b/services/core/java/com/android/server/am/BroadcastQueue.java
@@ -898,6 +898,11 @@
for (int i = perms.length-1; i >= 0; i--) {
try {
PermissionInfo pi = pm.getPermissionInfo(perms[i], "android", 0);
+ if (pi == null) {
+ // a required permission that no package has actually
+ // defined cannot be signature-required.
+ return false;
+ }
if ((pi.protectionLevel & (PermissionInfo.PROTECTION_MASK_BASE
| PermissionInfo.PROTECTION_FLAG_PRIVILEGED))
!= PermissionInfo.PROTECTION_SIGNATURE) {
@@ -923,8 +928,8 @@
if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
+ mQueueName + "]: "
- + mParallelBroadcasts.size() + " parallel broadcasts, "
- + mDispatcher.totalUndelivered() + " ordered broadcasts");
+ + mParallelBroadcasts.size() + " parallel broadcasts; "
+ + mDispatcher.describeStateLocked());
mService.updateCpuStats();
@@ -1822,11 +1827,24 @@
record.intent == null ? "" : record.intent.getAction());
}
- final boolean isIdle() {
+ boolean isIdle() {
return mParallelBroadcasts.isEmpty() && mDispatcher.isEmpty()
&& (mPendingBroadcast == null);
}
+ // Used by wait-for-broadcast-idle : fast-forward all current deferrals to
+ // be immediately deliverable.
+ void cancelDeferrals() {
+ mDispatcher.cancelDeferrals();
+ }
+
+ String describeState() {
+ synchronized (mService) {
+ return mParallelBroadcasts.size() + " parallel; "
+ + mDispatcher.describeStateLocked();
+ }
+ }
+
void writeToProto(ProtoOutputStream proto, long fieldId) {
long token = proto.start(fieldId);
proto.write(BroadcastQueueProto.QUEUE_NAME, mQueueName);
diff --git a/services/core/java/com/android/server/am/CoreSettingsObserver.java b/services/core/java/com/android/server/am/CoreSettingsObserver.java
index 0194624..8ffb67a 100644
--- a/services/core/java/com/android/server/am/CoreSettingsObserver.java
+++ b/services/core/java/com/android/server/am/CoreSettingsObserver.java
@@ -65,6 +65,8 @@
Settings.Global.GLOBAL_SETTINGS_ANGLE_GL_DRIVER_SELECTION_VALUES, String.class);
sGlobalSettingToTypeMap.put(
Settings.Global.GLOBAL_SETTINGS_ANGLE_WHITELIST, String.class);
+ sGlobalSettingToTypeMap.put(
+ Settings.Global.GLOBAL_SETTINGS_SHOW_ANGLE_IN_USE_DIALOG_BOX, String.class);
sGlobalSettingToTypeMap.put(Settings.Global.ENABLE_GPU_DEBUG_LAYERS, int.class);
sGlobalSettingToTypeMap.put(Settings.Global.GPU_DEBUG_APP, String.class);
sGlobalSettingToTypeMap.put(Settings.Global.GPU_DEBUG_LAYERS, String.class);
@@ -76,6 +78,7 @@
sGlobalSettingToTypeMap.put(Settings.Global.GAME_DRIVER_OPT_OUT_APPS, String.class);
sGlobalSettingToTypeMap.put(Settings.Global.GAME_DRIVER_BLACKLIST, String.class);
sGlobalSettingToTypeMap.put(Settings.Global.GAME_DRIVER_WHITELIST, String.class);
+ sGlobalSettingToTypeMap.put(Settings.Global.GAME_DRIVER_BLACKLISTS, String.class);
// add other global settings here...
}
diff --git a/services/core/java/com/android/server/am/ProcessList.java b/services/core/java/com/android/server/am/ProcessList.java
index f01305e..0d49e4c 100644
--- a/services/core/java/com/android/server/am/ProcessList.java
+++ b/services/core/java/com/android/server/am/ProcessList.java
@@ -1681,7 +1681,8 @@
public void killAppZygoteIfNeededLocked(AppZygote appZygote) {
final ApplicationInfo appInfo = appZygote.getAppInfo();
ArrayList<ProcessRecord> zygoteProcesses = mAppZygoteProcesses.get(appZygote);
- if (zygoteProcesses.size() == 0) { // Only remove if no longer in use now
+ if (zygoteProcesses != null && zygoteProcesses.size() == 0) {
+ // Only remove if no longer in use now
mAppZygotes.remove(appInfo.processName, appInfo.uid);
mAppZygoteProcesses.remove(appZygote);
mAppIsolatedUidRangeAllocator.freeUidRangeLocked(appInfo);
@@ -1703,6 +1704,7 @@
ArrayList<ProcessRecord> zygoteProcesses = mAppZygoteProcesses.get(appZygote);
zygoteProcesses.remove(app);
if (zygoteProcesses.size() == 0) {
+ mService.mHandler.removeMessages(KILL_APP_ZYGOTE_MSG);
Message msg = mService.mHandler.obtainMessage(KILL_APP_ZYGOTE_MSG);
msg.obj = appZygote;
mService.mHandler.sendMessageDelayed(msg, KILL_APP_ZYGOTE_DELAY_MS);
diff --git a/services/core/java/com/android/server/am/UserController.java b/services/core/java/com/android/server/am/UserController.java
index c981e68..7f6648a 100644
--- a/services/core/java/com/android/server/am/UserController.java
+++ b/services/core/java/com/android/server/am/UserController.java
@@ -2072,7 +2072,8 @@
new TimingsTraceLog("SystemServerTiming", Trace.TRACE_TAG_SYSTEM_SERVER)
.logDuration("SystemUserUnlock", unlockTime);
} else {
- Slog.d(TAG, "Unlocking user " + id + " took " + unlockTime + " ms");
+ new TimingsTraceLog("SystemServerTiming", Trace.TRACE_TAG_SYSTEM_SERVER)
+ .logDuration("User" + id + "Unlock", unlockTime);
}
}
};
diff --git a/services/core/java/com/android/server/biometrics/face/FaceService.java b/services/core/java/com/android/server/biometrics/face/FaceService.java
index 8995068..eab3820 100644
--- a/services/core/java/com/android/server/biometrics/face/FaceService.java
+++ b/services/core/java/com/android/server/biometrics/face/FaceService.java
@@ -588,6 +588,11 @@
throws RemoteException {
// TODO
}
+
+ @Override
+ public void onLockoutChanged(long duration) {
+
+ }
};
/**
diff --git a/services/core/java/com/android/server/connectivity/Tethering.java b/services/core/java/com/android/server/connectivity/Tethering.java
index a14fd17..19bdc09 100644
--- a/services/core/java/com/android/server/connectivity/Tethering.java
+++ b/services/core/java/com/android/server/connectivity/Tethering.java
@@ -96,6 +96,7 @@
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
import com.android.internal.notification.SystemNotificationChannels;
+import com.android.internal.telephony.TelephonyIntents;
import com.android.internal.util.DumpUtils;
import com.android.internal.util.IndentingPrintWriter;
import com.android.internal.util.MessageUtils;
@@ -180,6 +181,7 @@
// into a single coherent structure.
private final HashSet<IpServer> mForwardedDownstreams;
private final VersionedBroadcastListener mCarrierConfigChange;
+ private final VersionedBroadcastListener mDefaultSubscriptionChange;
private final TetheringDependencies mDeps;
private final EntitlementManager mEntitlementMgr;
@@ -232,6 +234,15 @@
mEntitlementMgr.reevaluateSimCardProvisioning();
});
+ filter = new IntentFilter();
+ filter.addAction(TelephonyIntents.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED);
+ mDefaultSubscriptionChange = new VersionedBroadcastListener(
+ "DefaultSubscriptionChangeListener", mContext, smHandler, filter,
+ (Intent ignored) -> {
+ mLog.log("OBSERVED default data subscription change");
+ updateConfiguration();
+ mEntitlementMgr.reevaluateSimCardProvisioning();
+ });
mStateReceiver = new StateReceiver();
// Load tethering configuration.
@@ -242,6 +253,7 @@
private void startStateMachineUpdaters() {
mCarrierConfigChange.startListening();
+ mDefaultSubscriptionChange.startListening();
final Handler handler = mTetherMasterSM.getHandler();
IntentFilter filter = new IntentFilter();
@@ -270,7 +282,8 @@
// NOTE: This is always invoked on the mLooper thread.
private void updateConfiguration() {
- mConfig = new TetheringConfiguration(mContext, mLog);
+ final int subId = mDeps.getDefaultDataSubscriptionId();
+ mConfig = new TetheringConfiguration(mContext, mLog, subId);
mUpstreamNetworkMonitor.updateMobileRequiresDun(mConfig.isDunRequired);
mEntitlementMgr.updateConfiguration(mConfig);
}
diff --git a/services/core/java/com/android/server/connectivity/tethering/TetheringConfiguration.java b/services/core/java/com/android/server/connectivity/tethering/TetheringConfiguration.java
index 1e6bb04..8a46ff1 100644
--- a/services/core/java/com/android/server/connectivity/tethering/TetheringConfiguration.java
+++ b/services/core/java/com/android/server/connectivity/tethering/TetheringConfiguration.java
@@ -26,8 +26,8 @@
import static com.android.internal.R.array.config_mobile_hotspot_provision_app;
import static com.android.internal.R.array.config_tether_bluetooth_regexs;
import static com.android.internal.R.array.config_tether_dhcp_range;
-import static com.android.internal.R.array.config_tether_usb_regexs;
import static com.android.internal.R.array.config_tether_upstream_types;
+import static com.android.internal.R.array.config_tether_usb_regexs;
import static com.android.internal.R.array.config_tether_wifi_regexs;
import static com.android.internal.R.bool.config_tether_upstream_automatic;
import static com.android.internal.R.string.config_mobile_hotspot_provision_app_no_ui;
@@ -38,6 +38,7 @@
import android.net.ConnectivityManager;
import android.net.util.SharedLog;
import android.provider.Settings;
+import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
@@ -100,29 +101,34 @@
public final String[] provisioningApp;
public final String provisioningAppNoUi;
- public TetheringConfiguration(Context ctx, SharedLog log) {
+ public final int subId;
+
+ public TetheringConfiguration(Context ctx, SharedLog log, int id) {
final SharedLog configLog = log.forSubComponent("config");
- tetherableUsbRegexs = getResourceStringArray(ctx, config_tether_usb_regexs);
+ subId = id;
+ Resources res = getResources(ctx, subId);
+
+ tetherableUsbRegexs = getResourceStringArray(res, config_tether_usb_regexs);
// TODO: Evaluate deleting this altogether now that Wi-Fi always passes
// us an interface name. Careful consideration needs to be given to
// implications for Settings and for provisioning checks.
- tetherableWifiRegexs = getResourceStringArray(ctx, config_tether_wifi_regexs);
- tetherableBluetoothRegexs = getResourceStringArray(ctx, config_tether_bluetooth_regexs);
+ tetherableWifiRegexs = getResourceStringArray(res, config_tether_wifi_regexs);
+ tetherableBluetoothRegexs = getResourceStringArray(res, config_tether_bluetooth_regexs);
dunCheck = checkDunRequired(ctx);
configLog.log("DUN check returned: " + dunCheckString(dunCheck));
- chooseUpstreamAutomatically = getResourceBoolean(ctx, config_tether_upstream_automatic);
- preferredUpstreamIfaceTypes = getUpstreamIfaceTypes(ctx, dunCheck);
+ chooseUpstreamAutomatically = getResourceBoolean(res, config_tether_upstream_automatic);
+ preferredUpstreamIfaceTypes = getUpstreamIfaceTypes(res, dunCheck);
isDunRequired = preferredUpstreamIfaceTypes.contains(TYPE_MOBILE_DUN);
- legacyDhcpRanges = getLegacyDhcpRanges(ctx);
+ legacyDhcpRanges = getLegacyDhcpRanges(res);
defaultIPv4DNS = copy(DEFAULT_IPV4_DNS);
enableLegacyDhcpServer = getEnableLegacyDhcpServer(ctx);
- provisioningApp = getResourceStringArray(ctx, config_mobile_hotspot_provision_app);
- provisioningAppNoUi = getProvisioningAppNoUi(ctx);
+ provisioningApp = getResourceStringArray(res, config_mobile_hotspot_provision_app);
+ provisioningAppNoUi = getProvisioningAppNoUi(res);
configLog.log(toString());
}
@@ -144,6 +150,9 @@
}
public void dump(PrintWriter pw) {
+ pw.print("subId: ");
+ pw.println(subId);
+
dumpStringArray(pw, "tetherableUsbRegexs", tetherableUsbRegexs);
dumpStringArray(pw, "tetherableWifiRegexs", tetherableWifiRegexs);
dumpStringArray(pw, "tetherableBluetoothRegexs", tetherableBluetoothRegexs);
@@ -169,6 +178,7 @@
public String toString() {
final StringJoiner sj = new StringJoiner(" ");
+ sj.add(String.format("subId:%d", subId));
sj.add(String.format("tetherableUsbRegexs:%s", makeString(tetherableUsbRegexs)));
sj.add(String.format("tetherableWifiRegexs:%s", makeString(tetherableWifiRegexs)));
sj.add(String.format("tetherableBluetoothRegexs:%s",
@@ -235,8 +245,8 @@
}
}
- private static Collection<Integer> getUpstreamIfaceTypes(Context ctx, int dunCheck) {
- final int ifaceTypes[] = ctx.getResources().getIntArray(config_tether_upstream_types);
+ private static Collection<Integer> getUpstreamIfaceTypes(Resources res, int dunCheck) {
+ final int[] ifaceTypes = res.getIntArray(config_tether_upstream_types);
final ArrayList<Integer> upstreamIfaceTypes = new ArrayList<>(ifaceTypes.length);
for (int i : ifaceTypes) {
switch (i) {
@@ -286,33 +296,33 @@
return false;
}
- private static String[] getLegacyDhcpRanges(Context ctx) {
- final String[] fromResource = getResourceStringArray(ctx, config_tether_dhcp_range);
+ private static String[] getLegacyDhcpRanges(Resources res) {
+ final String[] fromResource = getResourceStringArray(res, config_tether_dhcp_range);
if ((fromResource.length > 0) && (fromResource.length % 2 == 0)) {
return fromResource;
}
return copy(LEGACY_DHCP_DEFAULT_RANGE);
}
- private static String getProvisioningAppNoUi(Context ctx) {
+ private static String getProvisioningAppNoUi(Resources res) {
try {
- return ctx.getResources().getString(config_mobile_hotspot_provision_app_no_ui);
+ return res.getString(config_mobile_hotspot_provision_app_no_ui);
} catch (Resources.NotFoundException e) {
return "";
}
}
- private static boolean getResourceBoolean(Context ctx, int resId) {
+ private static boolean getResourceBoolean(Resources res, int resId) {
try {
- return ctx.getResources().getBoolean(resId);
+ return res.getBoolean(resId);
} catch (Resources.NotFoundException e404) {
return false;
}
}
- private static String[] getResourceStringArray(Context ctx, int resId) {
+ private static String[] getResourceStringArray(Resources res, int resId) {
try {
- final String[] strArray = ctx.getResources().getStringArray(resId);
+ final String[] strArray = res.getStringArray(resId);
return (strArray != null) ? strArray : EMPTY_STRING_ARRAY;
} catch (Resources.NotFoundException e404) {
return EMPTY_STRING_ARRAY;
@@ -325,6 +335,19 @@
return intVal != 0;
}
+ private Resources getResources(Context ctx, int subId) {
+ if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
+ return getResourcesForSubIdWrapper(ctx, subId);
+ } else {
+ return ctx.getResources();
+ }
+ }
+
+ @VisibleForTesting
+ protected Resources getResourcesForSubIdWrapper(Context ctx, int subId) {
+ return SubscriptionManager.getResourcesForSubId(ctx, subId);
+ }
+
private static String[] copy(String[] strarray) {
return Arrays.copyOf(strarray, strarray.length);
}
diff --git a/services/core/java/com/android/server/connectivity/tethering/TetheringDependencies.java b/services/core/java/com/android/server/connectivity/tethering/TetheringDependencies.java
index 6d6f81e..3fddac1 100644
--- a/services/core/java/com/android/server/connectivity/tethering/TetheringDependencies.java
+++ b/services/core/java/com/android/server/connectivity/tethering/TetheringDependencies.java
@@ -21,6 +21,7 @@
import android.net.ip.IpServer;
import android.net.util.SharedLog;
import android.os.Handler;
+import android.telephony.SubscriptionManager;
import com.android.internal.util.StateMachine;
import com.android.server.connectivity.MockableSystemProperties;
@@ -85,4 +86,11 @@
SharedLog log, MockableSystemProperties systemProperties) {
return new EntitlementManager(ctx, target, log, systemProperties);
}
+
+ /**
+ * Get default data subscription id to build TetheringConfiguration.
+ */
+ public int getDefaultDataSubscriptionId() {
+ return SubscriptionManager.getDefaultDataSubscriptionId();
+ }
}
diff --git a/services/core/java/com/android/server/display/ColorDisplayService.java b/services/core/java/com/android/server/display/ColorDisplayService.java
index 9cb6eee..45f169c 100644
--- a/services/core/java/com/android/server/display/ColorDisplayService.java
+++ b/services/core/java/com/android/server/display/ColorDisplayService.java
@@ -387,8 +387,10 @@
Slog.d(TAG, "Setting saturation level: " + saturationLevel);
if (saturationLevel == 100) {
+ setActivated(false);
Matrix.setIdentityM(mMatrixGlobalSaturation, 0);
} else {
+ setActivated(true);
float saturation = saturationLevel * 0.1f;
float desaturation = 1.0f - saturation;
float[] luminance = {0.231f * desaturation, 0.715f * desaturation,
@@ -556,14 +558,16 @@
if (setting != null) {
switch (setting) {
case Secure.NIGHT_DISPLAY_ACTIVATED:
- final boolean activated = isNightDisplayActivatedSetting();
+ final boolean activated = mNightDisplayTintController
+ .isActivatedSetting();
if (mNightDisplayTintController.isActivatedStateNotSet()
|| mNightDisplayTintController.isActivated() != activated) {
- mNightDisplayTintController.onActivated(activated);
+ mNightDisplayTintController.setActivated(activated);
}
break;
case Secure.NIGHT_DISPLAY_COLOR_TEMPERATURE:
- final int temperature = getNightDisplayColorTemperatureSetting();
+ final int temperature = mNightDisplayTintController
+ .getColorTemperatureSetting();
if (mNightDisplayTintController.getColorTemperature()
!= temperature) {
mNightDisplayTintController
@@ -639,14 +643,16 @@
// Prepare the night display color transformation matrix.
mNightDisplayTintController
.setUp(getContext(), DisplayTransformManager.needsLinearColorMatrix());
- mNightDisplayTintController.setMatrix(getNightDisplayColorTemperatureSetting());
+ mNightDisplayTintController
+ .setMatrix(mNightDisplayTintController.getColorTemperatureSetting());
// Initialize the current auto mode.
onNightDisplayAutoModeChanged(getNightDisplayAutoModeInternal());
// Force the initialization of the current saved activation state.
if (mNightDisplayTintController.isActivatedStateNotSet()) {
- mNightDisplayTintController.onActivated(isNightDisplayActivatedSetting());
+ mNightDisplayTintController
+ .setActivated(mNightDisplayTintController.isActivatedSetting());
}
}
@@ -674,6 +680,10 @@
if (mDisplayWhiteBalanceTintController.isAvailable(getContext())) {
mDisplayWhiteBalanceTintController.endAnimator();
}
+
+ if (mGlobalSaturationTintController.isAvailable(getContext())) {
+ mGlobalSaturationTintController.setActivated(null);
+ }
}
private void onNightDisplayAutoModeChanged(int autoMode) {
@@ -722,7 +732,8 @@
if (mNightDisplayTintController.isAvailable(getContext())) {
mNightDisplayTintController
.setUp(getContext(), DisplayTransformManager.needsLinearColorMatrix(mode));
- mNightDisplayTintController.setMatrix(getNightDisplayColorTemperatureSetting());
+ mNightDisplayTintController
+ .setMatrix(mNightDisplayTintController.getColorTemperatureSetting());
}
updateDisplayWhiteBalanceStatus();
@@ -1040,8 +1051,7 @@
*
* See {@link com.android.server.display.DisplayTransformManager}
*/
- private @ColorMode
- int getCurrentColorModeFromSystemProperties() {
+ private @ColorMode int getCurrentColorModeFromSystemProperties() {
final int displayColorSetting = SystemProperties.getInt("persist.sys.sf.native_mode", 0);
if (displayColorSetting == 0) {
return "1.0".equals(SystemProperties.get("persist.sys.sf.color_saturation"))
@@ -1098,33 +1108,6 @@
pw.println("Color mode: " + getColorModeInternal());
}
- private boolean isNightDisplayActivatedSetting() {
- return Secure.getIntForUser(getContext().getContentResolver(),
- Secure.NIGHT_DISPLAY_ACTIVATED, 0, mCurrentUser) == 1;
- }
-
- private int getNightDisplayColorTemperatureSetting() {
- return clampNightDisplayColorTemperature(Secure.getIntForUser(
- getContext().getContentResolver(), Secure.NIGHT_DISPLAY_COLOR_TEMPERATURE, NOT_SET,
- mCurrentUser));
- }
-
- private int clampNightDisplayColorTemperature(int colorTemperature) {
- if (colorTemperature == NOT_SET) {
- colorTemperature = getContext().getResources().getInteger(
- R.integer.config_nightDisplayColorTemperatureDefault);
- }
- final int minimumTemperature = ColorDisplayManager.getMinimumColorTemperature(getContext());
- final int maximumTemperature = ColorDisplayManager.getMaximumColorTemperature(getContext());
- if (colorTemperature < minimumTemperature) {
- colorTemperature = minimumTemperature;
- } else if (colorTemperature > maximumTemperature) {
- colorTemperature = maximumTemperature;
- }
-
- return colorTemperature;
- }
-
private abstract class NightDisplayAutoMode {
public abstract void onActivated(boolean activated);
@@ -1171,7 +1154,7 @@
// Maintain the existing activated state if within the current period.
if (mLastActivatedTime.isBefore(now) && mLastActivatedTime.isAfter(start)
&& (mLastActivatedTime.isAfter(end) || now.isBefore(end))) {
- activate = isNightDisplayActivatedSetting();
+ activate = mNightDisplayTintController.isActivatedSetting();
}
}
@@ -1267,7 +1250,7 @@
// Maintain the existing activated state if within the current period.
if (mLastActivatedTime.isBefore(now) && (mLastActivatedTime.isBefore(sunrise)
^ mLastActivatedTime.isBefore(sunset))) {
- activate = isNightDisplayActivatedSetting();
+ activate = mNightDisplayTintController.isActivatedSetting();
}
}
@@ -1466,9 +1449,11 @@
if (isActivatedStateNotSet() || activationStateChanged) {
super.setActivated(activated);
- Secure.putIntForUser(getContext().getContentResolver(),
- Secure.NIGHT_DISPLAY_ACTIVATED,
- activated ? 1 : 0, mCurrentUser);
+ if (isActivatedSetting() != activated) {
+ Secure.putIntForUser(getContext().getContentResolver(),
+ Secure.NIGHT_DISPLAY_ACTIVATED,
+ activated ? 1 : 0, mCurrentUser);
+ }
onActivated(activated);
}
}
@@ -1486,7 +1471,7 @@
return mIsAvailable;
}
- void onActivated(boolean activated) {
+ private void onActivated(boolean activated) {
Slog.i(TAG, activated ? "Turning on night display" : "Turning off night display");
if (mNightDisplayAutoMode != null) {
mNightDisplayAutoMode.onActivated(activated);
@@ -1501,7 +1486,7 @@
int getColorTemperature() {
return mColorTemp != null ? clampNightDisplayColorTemperature(mColorTemp)
- : getNightDisplayColorTemperatureSetting();
+ : getColorTemperatureSetting();
}
boolean setColorTemperature(int temperature) {
@@ -1516,6 +1501,36 @@
setMatrix(temperature);
mHandler.sendEmptyMessage(MSG_APPLY_NIGHT_DISPLAY_IMMEDIATE);
}
+
+ boolean isActivatedSetting() {
+ return Secure.getIntForUser(getContext().getContentResolver(),
+ Secure.NIGHT_DISPLAY_ACTIVATED, 0, mCurrentUser) == 1;
+ }
+
+ int getColorTemperatureSetting() {
+ return clampNightDisplayColorTemperature(Secure.getIntForUser(
+ getContext().getContentResolver(), Secure.NIGHT_DISPLAY_COLOR_TEMPERATURE,
+ NOT_SET,
+ mCurrentUser));
+ }
+
+ private int clampNightDisplayColorTemperature(int colorTemperature) {
+ if (colorTemperature == NOT_SET) {
+ colorTemperature = getContext().getResources().getInteger(
+ R.integer.config_nightDisplayColorTemperatureDefault);
+ }
+ final int minimumTemperature = ColorDisplayManager
+ .getMinimumColorTemperature(getContext());
+ final int maximumTemperature = ColorDisplayManager
+ .getMaximumColorTemperature(getContext());
+ if (colorTemperature < minimumTemperature) {
+ colorTemperature = minimumTemperature;
+ } else if (colorTemperature > maximumTemperature) {
+ colorTemperature = maximumTemperature;
+ }
+
+ return colorTemperature;
+ }
}
/**
@@ -1671,6 +1686,20 @@
}
@Override
+ public boolean isSaturationActivated() {
+ getContext().enforceCallingPermission(
+ Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
+ "Permission required to get display saturation level");
+ final long token = Binder.clearCallingIdentity();
+ try {
+ return !mGlobalSaturationTintController.isActivatedStateNotSet()
+ && mGlobalSaturationTintController.isActivated();
+ } finally {
+ Binder.restoreCallingIdentity(token);
+ }
+ }
+
+ @Override
public boolean setAppSaturationLevel(String packageName, int level) {
getContext().enforceCallingPermission(
Manifest.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS,
diff --git a/services/core/java/com/android/server/display/DisplayDevice.java b/services/core/java/com/android/server/display/DisplayDevice.java
index 6ee5665..e9ae516 100644
--- a/services/core/java/com/android/server/display/DisplayDevice.java
+++ b/services/core/java/com/android/server/display/DisplayDevice.java
@@ -19,6 +19,7 @@
import android.graphics.Rect;
import android.hardware.display.DisplayViewport;
import android.os.IBinder;
+import android.view.DisplayAddress;
import android.view.Surface;
import android.view.SurfaceControl;
@@ -225,8 +226,12 @@
viewport.deviceHeight = isRotated ? info.width : info.height;
viewport.uniqueId = info.uniqueId;
- // TODO(b/112898898) Use an actual port here.
- viewport.physicalPort = null;
+
+ if (info.address instanceof DisplayAddress.Physical) {
+ viewport.physicalPort = ((DisplayAddress.Physical) info.address).getPort();
+ } else {
+ viewport.physicalPort = null;
+ }
}
/**
diff --git a/services/core/java/com/android/server/display/DisplayDeviceInfo.java b/services/core/java/com/android/server/display/DisplayDeviceInfo.java
index ab64f61..729ea17 100644
--- a/services/core/java/com/android/server/display/DisplayDeviceInfo.java
+++ b/services/core/java/com/android/server/display/DisplayDeviceInfo.java
@@ -19,6 +19,7 @@
import android.hardware.display.DisplayViewport;
import android.util.DisplayMetrics;
import android.view.Display;
+import android.view.DisplayAddress;
import android.view.DisplayCutout;
import android.view.Surface;
@@ -274,7 +275,7 @@
* Display address, or null if none.
* Interpretation varies by display type.
*/
- public String address;
+ public DisplayAddress address;
/**
* Display state.
diff --git a/services/core/java/com/android/server/display/DisplayManagerService.java b/services/core/java/com/android/server/display/DisplayManagerService.java
index 80ea1da..b99ba7e 100644
--- a/services/core/java/com/android/server/display/DisplayManagerService.java
+++ b/services/core/java/com/android/server/display/DisplayManagerService.java
@@ -1336,7 +1336,7 @@
&& !TextUtils.isEmpty(info.uniqueId)) {
viewportType = VIEWPORT_VIRTUAL;
} else {
- Slog.wtf(TAG, "Unable to populate viewport for display device: " + info);
+ Slog.i(TAG, "Display " + info + " does not support input device matching.");
return;
}
diff --git a/services/core/java/com/android/server/display/LocalDisplayAdapter.java b/services/core/java/com/android/server/display/LocalDisplayAdapter.java
index 28f21f63..4891947 100644
--- a/services/core/java/com/android/server/display/LocalDisplayAdapter.java
+++ b/services/core/java/com/android/server/display/LocalDisplayAdapter.java
@@ -31,6 +31,7 @@
import android.util.Slog;
import android.util.SparseArray;
import android.view.Display;
+import android.view.DisplayAddress;
import android.view.DisplayCutout;
import android.view.DisplayEventReceiver;
import android.view.Surface;
@@ -382,6 +383,7 @@
mInfo.presentationDeadlineNanos = phys.presentationDeadlineNanos;
mInfo.state = mState;
mInfo.uniqueId = getUniqueId();
+ mInfo.address = DisplayAddress.fromPhysicalDisplayId(mPhysicalDisplayId);
// Assume that all built-in displays that have secure output (eg. HDCP) also
// support compositing from gralloc protected buffers.
diff --git a/services/core/java/com/android/server/display/WifiDisplayAdapter.java b/services/core/java/com/android/server/display/WifiDisplayAdapter.java
index e8d6ad4..9e4c1cb 100644
--- a/services/core/java/com/android/server/display/WifiDisplayAdapter.java
+++ b/services/core/java/com/android/server/display/WifiDisplayAdapter.java
@@ -16,9 +16,6 @@
package com.android.server.display;
-import com.android.internal.util.DumpUtils;
-import com.android.internal.util.IndentingPrintWriter;
-
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
@@ -35,9 +32,13 @@
import android.os.UserHandle;
import android.util.Slog;
import android.view.Display;
+import android.view.DisplayAddress;
import android.view.Surface;
import android.view.SurfaceControl;
+import com.android.internal.util.DumpUtils;
+import com.android.internal.util.IndentingPrintWriter;
+
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
@@ -581,7 +582,7 @@
private final int mHeight;
private final float mRefreshRate;
private final int mFlags;
- private final String mAddress;
+ private final DisplayAddress mAddress;
private final Display.Mode mMode;
private Surface mSurface;
@@ -596,7 +597,7 @@
mHeight = height;
mRefreshRate = refreshRate;
mFlags = flags;
- mAddress = address;
+ mAddress = DisplayAddress.fromMacAddress(address);
mSurface = surface;
mMode = createMode(width, height, refreshRate);
}
diff --git a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java
index 7ae00af..b9aa34e8 100644
--- a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java
+++ b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java
@@ -18,6 +18,7 @@
import android.annotation.NonNull;
import android.util.Slog;
+import android.util.Spline;
import com.android.internal.util.Preconditions;
import com.android.server.LocalServices;
@@ -75,6 +76,9 @@
// Override the ambient color temperature for debugging purposes.
private float mAmbientColorTemperatureOverride;
+ // A piecewise linear relationship between ambient and display color temperatures
+ private Spline.LinearSpline mAmbientToDisplayTemperatureSpline;
+
/**
* @param brightnessSensor
* The sensor used to detect changes in the ambient brightness.
@@ -109,7 +113,8 @@
@NonNull AmbientSensor.AmbientColorTemperatureSensor colorTemperatureSensor,
@NonNull AmbientFilter colorTemperatureFilter,
@NonNull DisplayWhiteBalanceThrottler throttler,
- float lowLightAmbientBrightnessThreshold, float lowLightAmbientColorTemperature) {
+ float lowLightAmbientBrightnessThreshold, float lowLightAmbientColorTemperature,
+ float[] ambientTemperatures, float[] displayTemperatures) {
validateArguments(brightnessSensor, brightnessFilter, colorTemperatureSensor,
colorTemperatureFilter, throttler);
mLoggingEnabled = false;
@@ -127,6 +132,14 @@
mLastAmbientColorTemperature = -1.0f;
mAmbientColorTemperatureHistory = new History(HISTORY_SIZE);
mAmbientColorTemperatureOverride = -1.0f;
+
+ try {
+ mAmbientToDisplayTemperatureSpline = new Spline.LinearSpline(ambientTemperatures,
+ displayTemperatures);
+ } catch (Exception e) {
+ mAmbientToDisplayTemperatureSpline = null;
+ }
+
mColorDisplayServiceInternal = LocalServices.getService(ColorDisplayServiceInternal.class);
}
@@ -227,6 +240,9 @@
writer.println(" mLastAmbientColorTemperature=" + mLastAmbientColorTemperature);
writer.println(" mAmbientColorTemperatureHistory=" + mAmbientColorTemperatureHistory);
writer.println(" mAmbientColorTemperatureOverride=" + mAmbientColorTemperatureOverride);
+ writer.println(" mAmbientToDisplayTemperatureSpline="
+ + (mAmbientToDisplayTemperatureSpline == null ? "unused" :
+ mAmbientToDisplayTemperatureSpline));
}
@Override // AmbientSensor.AmbientBrightnessSensor.Callbacks
@@ -250,6 +266,11 @@
final long time = System.currentTimeMillis();
float ambientColorTemperature = mColorTemperatureFilter.getEstimate(time);
+ if (mAmbientToDisplayTemperatureSpline != null) {
+ ambientColorTemperature =
+ mAmbientToDisplayTemperatureSpline.interpolate(ambientColorTemperature);
+ }
+
final float ambientBrightness = mBrightnessFilter.getEstimate(time);
if (ambientBrightness < mLowLightAmbientBrightnessThreshold) {
if (mLoggingEnabled) {
diff --git a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceFactory.java b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceFactory.java
index fd78ddb..56f4ca3 100644
--- a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceFactory.java
+++ b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceFactory.java
@@ -67,9 +67,14 @@
final float lowLightAmbientColorTemperature = getFloat(resources,
com.android.internal.R.dimen
.config_displayWhiteBalanceLowLightAmbientColorTemperature);
+ final float[] ambientTemperatures = getFloatArray(resources,
+ com.android.internal.R.array.config_displayWhiteBalanceAmbientTemperatureValues);
+ final float[] displayTemperatures = getFloatArray(resources,
+ com.android.internal.R.array.config_displayWhiteBalanceDisplayTemperatureValues);
final DisplayWhiteBalanceController controller = new DisplayWhiteBalanceController(
brightnessSensor, brightnessFilter, colorTemperatureSensor, colorTemperatureFilter,
- throttler, lowLightAmbientBrightnessThreshold, lowLightAmbientColorTemperature);
+ throttler, lowLightAmbientBrightnessThreshold, lowLightAmbientColorTemperature,
+ ambientTemperatures, displayTemperatures);
brightnessSensor.setCallbacks(controller);
colorTemperatureSensor.setCallbacks(controller);
return controller;
diff --git a/services/core/java/com/android/server/gpu/GpuService.java b/services/core/java/com/android/server/gpu/GpuService.java
index a68ceed..6899c3f 100644
--- a/services/core/java/com/android/server/gpu/GpuService.java
+++ b/services/core/java/com/android/server/gpu/GpuService.java
@@ -22,24 +22,33 @@
import android.annotation.NonNull;
import android.content.BroadcastReceiver;
+import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
+import android.database.ContentObserver;
+import android.gamedriver.GameDriverProto.Blacklist;
+import android.gamedriver.GameDriverProto.Blacklists;
import android.net.Uri;
import android.os.Build;
+import android.os.Handler;
import android.os.SystemProperties;
import android.os.UserHandle;
import android.provider.Settings;
+import android.util.Base64;
import android.util.Slog;
+import com.android.framework.protobuf.InvalidProtocolBufferException;
+import com.android.internal.annotations.GuardedBy;
import com.android.server.SystemService;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
+import java.util.List;
/**
* Service to manage GPU related features.
@@ -52,17 +61,25 @@
public static final boolean DEBUG = false;
private static final String PROPERTY_GFX_DRIVER = "ro.gfx.driver.0";
- private static final String WHITELIST_FILENAME = "whitelist.txt";
+ private static final String GAME_DRIVER_WHITELIST_FILENAME = "whitelist.txt";
+ private static final int BASE64_FLAGS = Base64.NO_PADDING | Base64.NO_WRAP;
private final Context mContext;
private final String mDriverPackageName;
private final PackageManager mPackageManager;
+ private final Object mLock = new Object();
+ private ContentResolver mContentResolver;
+ private long mGameDriverVersionCode;
+ private SettingsObserver mSettingsObserver;
+ @GuardedBy("mLock")
+ private Blacklists mBlacklists;
public GpuService(Context context) {
super(context);
mContext = context;
mDriverPackageName = SystemProperties.get(PROPERTY_GFX_DRIVER);
+ mGameDriverVersionCode = -1;
mPackageManager = context.getPackageManager();
if (mDriverPackageName != null && !mDriverPackageName.isEmpty()) {
final IntentFilter packageFilter = new IntentFilter();
@@ -82,10 +99,37 @@
@Override
public void onBootPhase(int phase) {
if (phase == PHASE_BOOT_COMPLETED) {
+ mContentResolver = mContext.getContentResolver();
+ mSettingsObserver = new SettingsObserver();
if (mDriverPackageName == null || mDriverPackageName.isEmpty()) {
return;
}
fetchGameDriverPackageProperties();
+ processBlacklists();
+ setBlacklist();
+ }
+ }
+
+ private final class SettingsObserver extends ContentObserver {
+ private final Uri mGameDriverBlackUri =
+ Settings.Global.getUriFor(Settings.Global.GAME_DRIVER_BLACKLISTS);
+
+ SettingsObserver() {
+ super(new Handler());
+ mContentResolver.registerContentObserver(mGameDriverBlackUri, false, this,
+ UserHandle.USER_ALL);
+ }
+
+ @Override
+ public void onChange(boolean selfChange, Uri uri) {
+ if (uri == null) {
+ return;
+ }
+
+ if (mGameDriverBlackUri.equals(uri)) {
+ processBlacklists();
+ setBlacklist();
+ }
}
}
@@ -109,6 +153,7 @@
case ACTION_PACKAGE_CHANGED:
case ACTION_PACKAGE_REMOVED:
fetchGameDriverPackageProperties();
+ setBlacklist();
break;
default:
// do nothing
@@ -138,16 +183,22 @@
return;
}
+ // Reset the whitelist.
+ Settings.Global.putString(mContentResolver,
+ Settings.Global.GAME_DRIVER_WHITELIST, "");
+ mGameDriverVersionCode = driverInfo.longVersionCode;
+
try {
final Context driverContext = mContext.createPackageContext(mDriverPackageName,
Context.CONTEXT_RESTRICTED);
final BufferedReader reader = new BufferedReader(
- new InputStreamReader(driverContext.getAssets().open(WHITELIST_FILENAME)));
+ new InputStreamReader(driverContext.getAssets()
+ .open(GAME_DRIVER_WHITELIST_FILENAME)));
final ArrayList<String> whitelistedPackageNames = new ArrayList<>();
for (String packageName; (packageName = reader.readLine()) != null; ) {
whitelistedPackageNames.add(packageName);
}
- Settings.Global.putString(mContext.getContentResolver(),
+ Settings.Global.putString(mContentResolver,
Settings.Global.GAME_DRIVER_WHITELIST,
String.join(",", whitelistedPackageNames));
} catch (PackageManager.NameNotFoundException e) {
@@ -160,4 +211,48 @@
}
}
}
+
+ private void processBlacklists() {
+ // TODO(b/121350991) Switch to DeviceConfig with property listener.
+ String base64String =
+ Settings.Global.getString(mContentResolver, Settings.Global.GAME_DRIVER_BLACKLISTS);
+ if (base64String == null || base64String.isEmpty()) {
+ return;
+ }
+
+ synchronized (mLock) {
+ // Reset all blacklists
+ mBlacklists = null;
+ try {
+ mBlacklists = Blacklists.parseFrom(Base64.decode(base64String, BASE64_FLAGS));
+ } catch (IllegalArgumentException e) {
+ if (DEBUG) {
+ Slog.w(TAG, "Can't parse blacklist, skip and continue...");
+ }
+ } catch (InvalidProtocolBufferException e) {
+ if (DEBUG) {
+ Slog.w(TAG, "Can't parse blacklist, skip and continue...");
+ }
+ }
+ }
+ }
+
+ private void setBlacklist() {
+ Settings.Global.putString(mContentResolver,
+ Settings.Global.GAME_DRIVER_BLACKLIST, "");
+ synchronized (mLock) {
+ if (mBlacklists == null) {
+ return;
+ }
+ List<Blacklist> blacklists = mBlacklists.getBlacklistsList();
+ for (Blacklist blacklist : blacklists) {
+ if (blacklist.getVersionCode() == mGameDriverVersionCode) {
+ Settings.Global.putString(mContentResolver,
+ Settings.Global.GAME_DRIVER_BLACKLIST,
+ String.join(",", blacklist.getPackageNamesList()));
+ return;
+ }
+ }
+ }
+ }
}
diff --git a/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java b/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java
index 20933db..560f7a0 100644
--- a/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java
+++ b/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java
@@ -342,7 +342,7 @@
super.disableDevice(initiatedByCec, callback);
assertRunOnServiceThread();
- if (!initiatedByCec && mIsActiveSource) {
+ if (!initiatedByCec && mIsActiveSource && mService.isControlEnabled()) {
mService.sendCecCommand(HdmiCecMessageBuilder.buildInactiveSource(
mAddress, mService.getPhysicalAddress()));
}
diff --git a/services/core/java/com/android/server/infra/FrameworkResourcesServiceNameResolver.java b/services/core/java/com/android/server/infra/FrameworkResourcesServiceNameResolver.java
index cf84e22..1b23794 100644
--- a/services/core/java/com/android/server/infra/FrameworkResourcesServiceNameResolver.java
+++ b/services/core/java/com/android/server/infra/FrameworkResourcesServiceNameResolver.java
@@ -187,7 +187,7 @@
@Override
public boolean isDefaultServiceEnabled(int userId) {
synchronized (mLock) {
- return mDefaultServicesDisabled.get(userId);
+ return !mDefaultServicesDisabled.get(userId);
}
}
diff --git a/services/core/java/com/android/server/input/InputManagerService.java b/services/core/java/com/android/server/input/InputManagerService.java
index 5e7ea05..28393a2 100644
--- a/services/core/java/com/android/server/input/InputManagerService.java
+++ b/services/core/java/com/android/server/input/InputManagerService.java
@@ -1805,9 +1805,10 @@
}
// Native callback.
- private int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
+ private int interceptMotionBeforeQueueingNonInteractive(int displayId,
+ long whenNanos, int policyFlags) {
return mWindowManagerCallbacks.interceptMotionBeforeQueueingNonInteractive(
- whenNanos, policyFlags);
+ displayId, whenNanos, policyFlags);
}
// Native callback.
@@ -2021,7 +2022,13 @@
public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags);
- public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags);
+ /**
+ * Provides an opportunity for the window manager policy to intercept early motion event
+ * processing when the device is in a non-interactive state since these events are normally
+ * dropped.
+ */
+ int interceptMotionBeforeQueueingNonInteractive(int displayId, long whenNanos,
+ int policyFlags);
public long interceptKeyBeforeDispatching(IBinder token,
KeyEvent event, int policyFlags);
diff --git a/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java b/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
index 144f2b6..96ba084 100644
--- a/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
+++ b/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
@@ -667,13 +667,19 @@
final int mSequenceNumber;
final long mTimestamp;
final long mWallTime;
+ @UserIdInt
+ final int mImeUserId;
@NonNull
final IBinder mImeToken;
+ final int mImeDisplayId;
@NonNull
final String mImeId;
@StartInputReason
final int mStartInputReason;
final boolean mRestarting;
+ @UserIdInt
+ final int mTargetUserId;
+ final int mTargetDisplayId;
@Nullable
final IBinder mTargetWindow;
@NonNull
@@ -682,17 +688,22 @@
final int mTargetWindowSoftInputMode;
final int mClientBindSequenceNumber;
- StartInputInfo(@NonNull IBinder imeToken, @NonNull String imeId,
- @StartInputReason int startInputReason, boolean restarting,
- @Nullable IBinder targetWindow, @NonNull EditorInfo editorInfo,
- @SoftInputModeFlags int targetWindowSoftInputMode, int clientBindSequenceNumber) {
+ StartInputInfo(@UserIdInt int imeUserId, @NonNull IBinder imeToken, int imeDisplayId,
+ @NonNull String imeId, @StartInputReason int startInputReason, boolean restarting,
+ @UserIdInt int targetUserId, int targetDisplayId, @Nullable IBinder targetWindow,
+ @NonNull EditorInfo editorInfo, @SoftInputModeFlags int targetWindowSoftInputMode,
+ int clientBindSequenceNumber) {
mSequenceNumber = sSequenceNumber.getAndIncrement();
mTimestamp = SystemClock.uptimeMillis();
mWallTime = System.currentTimeMillis();
+ mImeUserId = imeUserId;
mImeToken = imeToken;
+ mImeDisplayId = imeDisplayId;
mImeId = imeId;
mStartInputReason = startInputReason;
mRestarting = restarting;
+ mTargetUserId = targetUserId;
+ mTargetDisplayId = targetDisplayId;
mTargetWindow = targetWindow;
mEditorInfo = editorInfo;
mTargetWindowSoftInputMode = targetWindowSoftInputMode;
@@ -749,13 +760,19 @@
int mSequenceNumber;
long mTimestamp;
long mWallTime;
+ @UserIdInt
+ int mImeUserId;
@NonNull
String mImeTokenString;
+ int mImeDisplayId;
@NonNull
String mImeId;
@StartInputReason
int mStartInputReason;
boolean mRestarting;
+ @UserIdInt
+ int mTargetUserId;
+ int mTargetDisplayId;
@NonNull
String mTargetWindowString;
@NonNull
@@ -772,12 +789,16 @@
mSequenceNumber = original.mSequenceNumber;
mTimestamp = original.mTimestamp;
mWallTime = original.mWallTime;
+ mImeUserId = original.mImeUserId;
// Intentionally convert to String so as not to keep a strong reference to a Binder
// object.
mImeTokenString = String.valueOf(original.mImeToken);
+ mImeDisplayId = original.mImeDisplayId;
mImeId = original.mImeId;
mStartInputReason = original.mStartInputReason;
mRestarting = original.mRestarting;
+ mTargetUserId = original.mTargetUserId;
+ mTargetDisplayId = original.mTargetDisplayId;
// Intentionally convert to String so as not to keep a strong reference to a Binder
// object.
mTargetWindowString = String.valueOf(original.mTargetWindow);
@@ -821,11 +842,15 @@
+ " restarting=" + entry.mRestarting);
pw.print(prefix);
- pw.println(" imeToken=" + entry.mImeTokenString + " [" + entry.mImeId + "]");
+ pw.print(" imeToken=" + entry.mImeTokenString + " [" + entry.mImeId + "]");
+ pw.print(" imeUserId=" + entry.mImeUserId);
+ pw.println(" imeDisplayId=" + entry.mImeDisplayId);
pw.print(prefix);
pw.println(" targetWin=" + entry.mTargetWindowString
+ " [" + entry.mEditorInfo.packageName + "]"
+ + " targetUserId=" + entry.mTargetUserId
+ + " targetDisplayId=" + entry.mTargetDisplayId
+ " clientBindSeq=" + entry.mClientBindSequenceNumber);
pw.print(prefix);
@@ -1904,9 +1929,10 @@
}
final Binder startInputToken = new Binder();
- final StartInputInfo info = new StartInputInfo(mCurToken, mCurId, startInputReason,
- !initial, mCurFocusedWindow, mCurAttribute, mCurFocusedWindowSoftInputMode,
- mCurSeq);
+ final StartInputInfo info = new StartInputInfo(mSettings.getCurrentUserId(), mCurToken,
+ mCurTokenDisplayId, mCurId, startInputReason, !initial,
+ UserHandle.getUserId(mCurClient.uid), mCurClient.selfReportedDisplayId,
+ mCurFocusedWindow, mCurAttribute, mCurFocusedWindowSoftInputMode, mCurSeq);
mImeTargetWindowMap.put(startInputToken, mCurFocusedWindow);
mStartInputHistory.addEntry(info);
diff --git a/services/core/java/com/android/server/location/GnssLocationProvider.java b/services/core/java/com/android/server/location/GnssLocationProvider.java
index 2f0b388..e71b156 100644
--- a/services/core/java/com/android/server/location/GnssLocationProvider.java
+++ b/services/core/java/com/android/server/location/GnssLocationProvider.java
@@ -917,7 +917,7 @@
synchronized (mLock) {
boolean enabled =
((mProviderRequest != null && mProviderRequest.reportLocation
- && mProviderRequest.forceLocation) || (
+ && mProviderRequest.locationSettingsIgnored) || (
mContext.getSystemService(LocationManager.class).isLocationEnabled()
&& !mDisableGps)) && !mShutdown;
if (enabled == mEnabled) {
@@ -976,7 +976,7 @@
}
if (DEBUG) Log.d(TAG, "setRequest " + mProviderRequest);
- if (mProviderRequest.reportLocation && !mDisableGps && isEnabled()) {
+ if (mProviderRequest.reportLocation && isEnabled()) {
// update client uids
updateClientUids(mWorkSource);
diff --git a/services/core/java/com/android/server/location/RemoteListenerHelper.java b/services/core/java/com/android/server/location/RemoteListenerHelper.java
index f03c99b..aa8a25a 100644
--- a/services/core/java/com/android/server/location/RemoteListenerHelper.java
+++ b/services/core/java/com/android/server/location/RemoteListenerHelper.java
@@ -31,9 +31,11 @@
import java.util.Map;
/**
- * A helper class, that handles operations in remote listeners, and tracks for remote process death.
+ * A helper class that handles operations in remote listeners.
+ *
+ * @param <TListener> the type of GNSS data listener.
*/
-abstract class RemoteListenerHelper<TListener extends IInterface> {
+public abstract class RemoteListenerHelper<TListener extends IInterface> {
protected static final int RESULT_SUCCESS = 0;
protected static final int RESULT_NOT_AVAILABLE = 1;
@@ -46,7 +48,7 @@
protected final Handler mHandler;
private final String mTag;
- private final Map<IBinder, LinkedListener> mListenerMap = new HashMap<>();
+ private final Map<IBinder, IdentifiedListener> mListenerMap = new HashMap<>();
protected final Context mContext;
protected final AppOpsManager mAppOps;
@@ -71,24 +73,21 @@
return mIsRegistered;
}
- public boolean addListener(@NonNull TListener listener, CallerIdentity callerIdentity) {
+ /**
+ * Adds GNSS data listener {@code listener} with caller identify {@code callerIdentify}.
+ */
+ public void addListener(@NonNull TListener listener, CallerIdentity callerIdentity) {
Preconditions.checkNotNull(listener, "Attempted to register a 'null' listener.");
IBinder binder = listener.asBinder();
- LinkedListener deathListener = new LinkedListener(listener, callerIdentity);
synchronized (mListenerMap) {
if (mListenerMap.containsKey(binder)) {
// listener already added
- return true;
+ return;
}
- try {
- binder.linkToDeath(deathListener, 0 /* flags */);
- } catch (RemoteException e) {
- // if the remote process registering the listener is already death, just swallow the
- // exception and return
- Log.v(mTag, "Remote listener already died.", e);
- return false;
- }
- mListenerMap.put(binder, deathListener);
+
+ IdentifiedListener identifiedListener = new IdentifiedListener(listener,
+ callerIdentity);
+ mListenerMap.put(binder, identifiedListener);
// update statuses we already know about, starting from the ones that will never change
int result;
@@ -107,26 +106,23 @@
} else {
// at this point if the supported flag is not set, the notification will be sent
// asynchronously in the future
- return true;
+ return;
}
- post(deathListener, getHandlerOperation(result));
+ post(identifiedListener, getHandlerOperation(result));
}
- return true;
}
+ /**
+ * Remove GNSS data listener {@code listener}.
+ */
public void removeListener(@NonNull TListener listener) {
Preconditions.checkNotNull(listener, "Attempted to remove a 'null' listener.");
- IBinder binder = listener.asBinder();
- LinkedListener linkedListener;
synchronized (mListenerMap) {
- linkedListener = mListenerMap.remove(binder);
+ mListenerMap.remove(listener.asBinder());
if (mListenerMap.isEmpty()) {
tryUnregister();
}
}
- if (linkedListener != null) {
- binder.unlinkToDeath(linkedListener, 0 /* flags */);
- }
}
protected abstract boolean isAvailableInPlatform();
@@ -198,14 +194,15 @@
}
private void foreachUnsafe(ListenerOperation<TListener> operation) {
- for (LinkedListener linkedListener : mListenerMap.values()) {
- post(linkedListener, operation);
+ for (IdentifiedListener identifiedListener : mListenerMap.values()) {
+ post(identifiedListener, operation);
}
}
- private void post(LinkedListener linkedListener, ListenerOperation<TListener> operation) {
+ private void post(IdentifiedListener identifiedListener,
+ ListenerOperation<TListener> operation) {
if (operation != null) {
- mHandler.post(new HandlerRunnable(linkedListener, operation));
+ mHandler.post(new HandlerRunnable(identifiedListener, operation));
}
}
@@ -259,35 +256,31 @@
return RESULT_SUCCESS;
}
- private class LinkedListener implements IBinder.DeathRecipient {
+ private class IdentifiedListener {
private final TListener mListener;
private final CallerIdentity mCallerIdentity;
- LinkedListener(@NonNull TListener listener, CallerIdentity callerIdentity) {
+ private IdentifiedListener(@NonNull TListener listener, CallerIdentity callerIdentity) {
mListener = listener;
mCallerIdentity = callerIdentity;
}
-
- @Override
- public void binderDied() {
- Log.d(mTag, "Remote Listener died: " + mListener);
- removeListener(mListener);
- }
}
private class HandlerRunnable implements Runnable {
- private final LinkedListener mLinkedListener;
+ private final IdentifiedListener mIdentifiedListener;
private final ListenerOperation<TListener> mOperation;
- HandlerRunnable(LinkedListener linkedListener, ListenerOperation<TListener> operation) {
- mLinkedListener = linkedListener;
+ private HandlerRunnable(IdentifiedListener identifiedListener,
+ ListenerOperation<TListener> operation) {
+ mIdentifiedListener = identifiedListener;
mOperation = operation;
}
@Override
public void run() {
try {
- mOperation.execute(mLinkedListener.mListener, mLinkedListener.mCallerIdentity);
+ mOperation.execute(mIdentifiedListener.mListener,
+ mIdentifiedListener.mCallerIdentity);
} catch (RemoteException e) {
Log.v(mTag, "Error in monitored listener.", e);
}
diff --git a/services/core/java/com/android/server/locksettings/recoverablekeystore/KeySyncTask.java b/services/core/java/com/android/server/locksettings/recoverablekeystore/KeySyncTask.java
index 1f9b027..e7a71b9 100644
--- a/services/core/java/com/android/server/locksettings/recoverablekeystore/KeySyncTask.java
+++ b/services/core/java/com/android/server/locksettings/recoverablekeystore/KeySyncTask.java
@@ -20,6 +20,7 @@
import android.annotation.Nullable;
import android.content.Context;
+import android.os.RemoteException;
import android.security.Scrypt;
import android.security.keystore.recovery.KeyChainProtectionParams;
import android.security.keystore.recovery.KeyChainSnapshot;
@@ -162,7 +163,7 @@
}
}
- private void syncKeys() {
+ private void syncKeys() throws RemoteException {
if (mCredentialType == LockPatternUtils.CREDENTIAL_TYPE_NONE) {
// Application keys for the user will not be available for sync.
Log.w(TAG, "Credentials are not set for user " + mUserId);
@@ -195,7 +196,7 @@
&& mCredentialType != LockPatternUtils.CREDENTIAL_TYPE_PASSWORD;
}
- private void syncKeysForAgent(int recoveryAgentUid) throws IOException {
+ private void syncKeysForAgent(int recoveryAgentUid) throws IOException, RemoteException {
boolean shouldRecreateCurrentVersion = false;
if (!shouldCreateSnapshot(recoveryAgentUid)) {
shouldRecreateCurrentVersion =
@@ -412,7 +413,7 @@
private Map<String, Pair<SecretKey, byte[]>> getKeysToSync(int recoveryAgentUid)
throws InsecureUserException, KeyStoreException, UnrecoverableKeyException,
NoSuchAlgorithmException, NoSuchPaddingException, BadPlatformKeyException,
- InvalidKeyException, InvalidAlgorithmParameterException, IOException {
+ InvalidKeyException, InvalidAlgorithmParameterException, IOException, RemoteException {
PlatformDecryptionKey decryptKey = mPlatformKeyManager.getDecryptKey(mUserId);;
Map<String, WrappedKey> wrappedKeys = mRecoverableKeyStoreDb.getAllKeys(
mUserId, recoveryAgentUid, decryptKey.getGenerationId());
diff --git a/services/core/java/com/android/server/locksettings/recoverablekeystore/PlatformKeyManager.java b/services/core/java/com/android/server/locksettings/recoverablekeystore/PlatformKeyManager.java
index 9ca052b..1c18771 100644
--- a/services/core/java/com/android/server/locksettings/recoverablekeystore/PlatformKeyManager.java
+++ b/services/core/java/com/android/server/locksettings/recoverablekeystore/PlatformKeyManager.java
@@ -18,15 +18,21 @@
import android.app.KeyguardManager;
import android.content.Context;
+import android.os.RemoteException;
+import android.security.GateKeeper;
import android.security.keystore.AndroidKeyStoreSecretKey;
+import android.security.keystore.KeyPermanentlyInvalidatedException;
import android.security.keystore.KeyProperties;
import android.security.keystore.KeyProtection;
+import android.service.gatekeeper.IGateKeeperService;
import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
import com.android.server.locksettings.recoverablekeystore.storage.RecoverableKeyStoreDb;
import java.io.IOException;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
@@ -34,9 +40,11 @@
import java.security.cert.CertificateException;
import java.util.Locale;
+import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
+import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
-import javax.security.auth.DestroyFailedException;
+import javax.crypto.spec.GCMParameterSpec;
/**
* Manages creating and checking the validity of the platform key.
@@ -67,6 +75,10 @@
private static final String ENCRYPT_KEY_ALIAS_SUFFIX = "encrypt";
private static final String DECRYPT_KEY_ALIAS_SUFFIX = "decrypt";
private static final int USER_AUTHENTICATION_VALIDITY_DURATION_SECONDS = 15;
+ private static final String KEY_WRAP_CIPHER_ALGORITHM = "AES/GCM/NoPadding";
+ private static final int GCM_TAG_LENGTH_BITS = 128;
+ // Only used for checking if a key is usable
+ private static final byte[] GCM_INSECURE_NONCE_BYTES = new byte[12];
private final Context mContext;
private final KeyStoreProxy mKeyStore;
@@ -158,12 +170,14 @@
* @throws KeyStoreException if there is an error in AndroidKeyStore.
* @throws InsecureUserException if the user does not have a lock screen set.
* @throws IOException if there was an issue with local database update.
+ * @throws RemoteException if there was an issue communicating with {@link IGateKeeperService}.
*
* @hide
*/
@VisibleForTesting
void regenerate(int userId)
- throws NoSuchAlgorithmException, KeyStoreException, InsecureUserException, IOException {
+ throws NoSuchAlgorithmException, KeyStoreException, InsecureUserException, IOException,
+ RemoteException {
if (!isAvailable(userId)) {
throw new InsecureUserException(String.format(
Locale.US, "%d does not have a lock screen set.", userId));
@@ -190,11 +204,13 @@
* @throws NoSuchAlgorithmException if AES is unavailable - should never occur.
* @throws InsecureUserException if the user does not have a lock screen set.
* @throws IOException if there was an issue with local database update.
+ * @throws RemoteException if there was an issue communicating with {@link IGateKeeperService}.
*
* @hide
*/
- public PlatformEncryptionKey getEncryptKey(int userId) throws KeyStoreException,
- UnrecoverableKeyException, NoSuchAlgorithmException, InsecureUserException, IOException {
+ public PlatformEncryptionKey getEncryptKey(int userId)
+ throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException,
+ InsecureUserException, IOException, RemoteException {
init(userId);
try {
// Try to see if the decryption key is still accessible before using the encryption key.
@@ -243,14 +259,18 @@
* @throws NoSuchAlgorithmException if AES is unavailable - should never occur.
* @throws InsecureUserException if the user does not have a lock screen set.
* @throws IOException if there was an issue with local database update.
+ * @throws RemoteException if there was an issue communicating with {@link IGateKeeperService}.
*
* @hide
*/
- public PlatformDecryptionKey getDecryptKey(int userId) throws KeyStoreException,
- UnrecoverableKeyException, NoSuchAlgorithmException, InsecureUserException, IOException {
+ public PlatformDecryptionKey getDecryptKey(int userId)
+ throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException,
+ InsecureUserException, IOException, RemoteException {
init(userId);
try {
- return getDecryptKeyInternal(userId);
+ PlatformDecryptionKey decryptionKey = getDecryptKeyInternal(userId);
+ ensureDecryptionKeyIsValid(userId, decryptionKey);
+ return decryptionKey;
} catch (UnrecoverableKeyException e) {
Log.i(TAG, String.format(Locale.US,
"Regenerating permanently invalid Platform key for user %d.",
@@ -284,6 +304,29 @@
}
/**
+ * Tries to use the decryption key to make sure it is not permanently invalidated. The exception
+ * {@code KeyPermanentlyInvalidatedException} is thrown only when the key is in use.
+ *
+ * <p>Note that we ignore all other InvalidKeyException exceptions, because such an exception
+ * may be thrown for auth-bound keys if there's no recent unlock event.
+ */
+ private void ensureDecryptionKeyIsValid(int userId, PlatformDecryptionKey decryptionKey)
+ throws UnrecoverableKeyException {
+ try {
+ Cipher.getInstance(KEY_WRAP_CIPHER_ALGORITHM).init(Cipher.UNWRAP_MODE,
+ decryptionKey.getKey(),
+ new GCMParameterSpec(GCM_TAG_LENGTH_BITS, GCM_INSECURE_NONCE_BYTES));
+ } catch (KeyPermanentlyInvalidatedException e) {
+ Log.e(TAG, String.format(Locale.US, "The platform key for user %d became invalid.",
+ userId));
+ throw new UnrecoverableKeyException(e.getMessage());
+ } catch (NoSuchAlgorithmException | InvalidKeyException
+ | InvalidAlgorithmParameterException | NoSuchPaddingException e) {
+ // Ignore all other exceptions
+ }
+ }
+
+ /**
* Initializes the class. If there is no current platform key, and the user has a lock screen
* set, will create the platform key and set the generation ID.
*
@@ -291,11 +334,13 @@
* @throws KeyStoreException if there was an error in AndroidKeyStore.
* @throws NoSuchAlgorithmException if AES is unavailable - should never happen.
* @throws IOException if there was an issue with local database update.
+ * @throws RemoteException if there was an issue communicating with {@link IGateKeeperService}.
*
* @hide
*/
void init(int userId)
- throws KeyStoreException, NoSuchAlgorithmException, InsecureUserException, IOException {
+ throws KeyStoreException, NoSuchAlgorithmException, InsecureUserException, IOException,
+ RemoteException {
if (!isAvailable(userId)) {
throw new InsecureUserException(String.format(
Locale.US, "%d does not have a lock screen set.", userId));
@@ -372,6 +417,11 @@
&& mKeyStore.containsAlias(getDecryptAlias(userId, generationId));
}
+ @VisibleForTesting
+ IGateKeeperService getGateKeeperService() {
+ return GateKeeper.getService();
+ }
+
/**
* Generates a new 256-bit AES key, and loads it into AndroidKeyStore with the given
* {@code generationId} determining its aliases.
@@ -380,15 +430,23 @@
* available since API version 1.
* @throws KeyStoreException if there was an issue loading the keys into AndroidKeyStore.
* @throws IOException if there was an issue with local database update.
+ * @throws RemoteException if there was an issue communicating with {@link IGateKeeperService}.
*/
private void generateAndLoadKey(int userId, int generationId)
- throws NoSuchAlgorithmException, KeyStoreException, IOException {
+ throws NoSuchAlgorithmException, KeyStoreException, IOException, RemoteException {
String encryptAlias = getEncryptAlias(userId, generationId);
String decryptAlias = getDecryptAlias(userId, generationId);
// SecretKey implementation doesn't provide reliable way to destroy the secret
// so it may live in memory for some time.
SecretKey secretKey = generateAesKey();
+ long secureUserId = getGateKeeperService().getSecureUserId(userId);
+ // TODO(b/124095438): Propagate this failure instead of silently failing.
+ if (secureUserId == GateKeeper.INVALID_SECURE_USER_ID) {
+ Log.e(TAG, "No SID available for user " + userId);
+ return;
+ }
+
// Store decryption key first since it is more likely to fail.
mKeyStore.setEntry(
decryptAlias,
@@ -399,7 +457,7 @@
USER_AUTHENTICATION_VALIDITY_DURATION_SECONDS)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
- .setBoundToSpecificSecureUserId(userId)
+ .setBoundToSpecificSecureUserId(secureUserId)
.build());
mKeyStore.setEntry(
encryptAlias,
diff --git a/services/core/java/com/android/server/pm/ApexManager.java b/services/core/java/com/android/server/pm/ApexManager.java
new file mode 100644
index 0000000..dac4b6f
--- /dev/null
+++ b/services/core/java/com/android/server/pm/ApexManager.java
@@ -0,0 +1,221 @@
+/*
+ * 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.s
+ */
+
+package com.android.server.pm;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.apex.ApexInfo;
+import android.apex.ApexInfoList;
+import android.apex.ApexSessionInfo;
+import android.apex.IApexService;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageParser;
+import android.content.pm.PackageParser.PackageParserException;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.util.Slog;
+
+import com.android.internal.util.IndentingPrintWriter;
+
+import java.io.File;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+/**
+ * ApexManager class handles communications with the apex service to perform operation and queries,
+ * as well as providing caching to avoid unnecessary calls to the service.
+ */
+class ApexManager {
+ static final String TAG = "ApexManager";
+ private final IApexService mApexService;
+ private final Map<String, PackageInfo> mActivePackagesCache;
+
+ ApexManager() {
+ mApexService = IApexService.Stub.asInterface(
+ ServiceManager.getService("apexservice"));
+ mActivePackagesCache = populateActivePackagesCache();
+ }
+
+ @NonNull
+ private Map<String, PackageInfo> populateActivePackagesCache() {
+ try {
+ List<PackageInfo> list = new ArrayList<>();
+ final ApexInfo[] activePkgs = mApexService.getActivePackages();
+ for (ApexInfo ai : activePkgs) {
+ // If the device is using flattened APEX, don't report any APEX
+ // packages since they won't be managed or updated by PackageManager.
+ if ((new File(ai.packagePath)).isDirectory()) {
+ break;
+ }
+ try {
+ list.add(PackageParser.generatePackageInfoFromApex(
+ new File(ai.packagePath), true /* collect certs */));
+ } catch (PackageParserException pe) {
+ throw new IllegalStateException("Unable to parse: " + ai, pe);
+ }
+ }
+ return list.stream().collect(Collectors.toMap(p -> p.packageName, Function.identity()));
+ } catch (RemoteException re) {
+ Slog.e(TAG, "Unable to retrieve packages from apexservice: " + re.toString());
+ throw new RuntimeException(re);
+ }
+ }
+
+ /**
+ * Retrieves information about an active APEX package.
+ *
+ * @param packageName the package name to look for. Note that this is the package name reported
+ * in the APK container manifest (i.e. AndroidManifest.xml), which might
+ * differ from the one reported in the APEX manifest (i.e.
+ * apex_manifest.json).
+ * @return a PackageInfo object with the information about the package, or null if the package
+ * is not found.
+ */
+ @Nullable PackageInfo getActivePackage(String packageName) {
+ return mActivePackagesCache.get(packageName);
+ }
+
+ /**
+ * Retrieves information about all active APEX packages.
+ *
+ * @return a Collection of PackageInfo object, each one containing information about a different
+ * active package.
+ */
+ Collection<PackageInfo> getActivePackages() {
+ return mActivePackagesCache.values();
+ }
+
+ /**
+ * Retrieves information about an apexd staged session i.e. the internal state used by apexd to
+ * track the different states of a session.
+ *
+ * @param sessionId the identifier of the session.
+ * @return an ApexSessionInfo object, or null if the session is not known.
+ */
+ @Nullable ApexSessionInfo getStagedSessionInfo(int sessionId) {
+ try {
+ ApexSessionInfo apexSessionInfo = mApexService.getStagedSessionInfo(sessionId);
+ if (apexSessionInfo.isUnknown) {
+ return null;
+ }
+ return apexSessionInfo;
+ } catch (RemoteException re) {
+ Slog.e(TAG, "Unable to contact apexservice", re);
+ throw new RuntimeException(re);
+ }
+ }
+
+ /**
+ * Submit a staged session to apex service. This causes the apex service to perform some initial
+ * verification and accept or reject the session. Submitting a session successfully is not
+ * enough for it to be activated at the next boot, the caller needs to call
+ * {@link #markStagedSessionReady(int)}.
+ *
+ * @param sessionId the identifier of the {@link PackageInstallerSession} being submitted.
+ * @param childSessionIds if {@code sessionId} is a multi-package session, this should contain
+ * an array of identifiers of all the child sessions. Otherwise it should
+ * be an empty array.
+ * @param apexInfoList this is an output parameter, which needs to be initialized by tha caller
+ * and will be filled with a list of {@link ApexInfo} objects, each of which
+ * contains metadata about one of the packages being submitted as part of
+ * the session.
+ * @return whether the submission of the session was successful.
+ */
+ boolean submitStagedSession(
+ int sessionId, @NonNull int[] childSessionIds, @NonNull ApexInfoList apexInfoList) {
+ try {
+ return mApexService.submitStagedSession(sessionId, childSessionIds, apexInfoList);
+ } catch (RemoteException re) {
+ Slog.e(TAG, "Unable to contact apexservice", re);
+ throw new RuntimeException(re);
+ }
+ }
+
+ /**
+ * Mark a staged session previously submitted using {@cde submitStagedSession} as ready to be
+ * applied at next reboot.
+ *
+ * @param sessionId the identifier of the {@link PackageInstallerSession} being marked as ready.
+ * @return true upon success, false if the session is unknown.
+ */
+ boolean markStagedSessionReady(int sessionId) {
+ try {
+ return mApexService.markStagedSessionReady(sessionId);
+ } catch (RemoteException re) {
+ Slog.e(TAG, "Unable to contact apexservice", re);
+ throw new RuntimeException(re);
+ }
+ }
+
+ /**
+ * Dumps various state information to the provided {@link PrintWriter} object.
+ *
+ * @param pw the {@link PrintWriter} object to send information to.
+ * @param packageName a {@link String} containing a package name, or {@code null}. If set, only
+ * information about that specific package will be dumped.
+ */
+ void dump(PrintWriter pw, @Nullable String packageName) {
+ final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
+ ipw.println();
+ ipw.println("Active APEX packages:");
+ ipw.increaseIndent();
+ try {
+ populateActivePackagesCache();
+ for (PackageInfo pi : mActivePackagesCache.values()) {
+ if (packageName != null && !packageName.equals(pi.packageName)) {
+ continue;
+ }
+ ipw.println(pi.packageName);
+ ipw.increaseIndent();
+ ipw.println("Version: " + pi.versionCode);
+ ipw.println("Path: " + pi.applicationInfo.sourceDir);
+ ipw.decreaseIndent();
+ }
+ ipw.decreaseIndent();
+ ipw.println();
+ ipw.println("APEX session state:");
+ ipw.increaseIndent();
+ final ApexSessionInfo[] sessions = mApexService.getSessions();
+ for (ApexSessionInfo si : sessions) {
+ ipw.println("Session ID: " + Integer.toString(si.sessionId));
+ ipw.increaseIndent();
+ if (si.isUnknown) {
+ ipw.println("State: UNKNOWN");
+ } else if (si.isVerified) {
+ ipw.println("State: VERIFIED");
+ } else if (si.isStaged) {
+ ipw.println("State: STAGED");
+ } else if (si.isActivated) {
+ ipw.println("State: ACTIVATED");
+ } else if (si.isActivationPendingRetry) {
+ ipw.println("State: ACTIVATION PENDING RETRY");
+ } else if (si.isActivationFailed) {
+ ipw.println("State: ACTIVATION FAILED");
+ }
+ ipw.decreaseIndent();
+ }
+ ipw.decreaseIndent();
+ } catch (RemoteException e) {
+ ipw.println("Couldn't communicate with apexd.");
+ }
+ }
+}
diff --git a/services/core/java/com/android/server/pm/PackageInstallerService.java b/services/core/java/com/android/server/pm/PackageInstallerService.java
index 21965e4..8608349 100644
--- a/services/core/java/com/android/server/pm/PackageInstallerService.java
+++ b/services/core/java/com/android/server/pm/PackageInstallerService.java
@@ -186,7 +186,7 @@
}
};
- public PackageInstallerService(Context context, PackageManagerService pm) {
+ public PackageInstallerService(Context context, PackageManagerService pm, ApexManager am) {
mContext = context;
mPm = pm;
mPermissionManager = LocalServices.getService(PermissionManagerInternal.class);
@@ -204,7 +204,7 @@
mSessionsDir = new File(Environment.getDataSystemDirectory(), "install_sessions");
mSessionsDir.mkdirs();
- mStagingManager = new StagingManager(pm, this);
+ mStagingManager = new StagingManager(pm, this, am);
}
private void setBootCompleted() {
@@ -481,6 +481,10 @@
}
}
+ if (params.isStaged) {
+ mContext.enforceCallingOrSelfPermission(Manifest.permission.INSTALL_PACKAGES, TAG);
+ }
+
if (!params.isMultiPackage) {
// Only system components can circumvent runtime permissions when installing.
if ((params.installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 874d1a7..941de89 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -119,13 +119,11 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.UserIdInt;
-import android.apex.ApexInfo;
-import android.apex.ApexSessionInfo;
-import android.apex.IApexService;
import android.app.ActivityManager;
import android.app.ActivityManagerInternal;
import android.app.AppDetailsActivity;
import android.app.AppOpsManager;
+import android.app.BroadcastOptions;
import android.app.IActivityManager;
import android.app.ResourcesManager;
import android.app.admin.IDevicePolicyManager;
@@ -241,6 +239,7 @@
import android.os.storage.VolumeInfo;
import android.os.storage.VolumeRecord;
import android.permission.PermissionControllerManager;
+import android.provider.DeviceConfig;
import android.provider.MediaStore;
import android.provider.Settings.Global;
import android.provider.Settings.Secure;
@@ -733,10 +732,10 @@
@GuardedBy("mPackages")
final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
- private PackageManager mPackageManager;
-
private final ModuleInfoProvider mModuleInfoProvider;
+ private final ApexManager mApexManager;
+
class PackageParserCallback implements PackageParser.Callback {
@Override public final boolean hasFeature(String feature) {
return PackageManagerService.this.hasSystemFeature(feature, 0);
@@ -1046,12 +1045,17 @@
verificationIntent.setComponent(mIntentFilterVerifierComponent);
verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
+ final long whitelistTimeout = getVerificationTimeout();
+ final BroadcastOptions options = BroadcastOptions.makeBasic();
+ options.setTemporaryAppWhitelistDuration(whitelistTimeout);
+
DeviceIdleController.LocalService idleController = getDeviceIdleController();
idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
- mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
+ mIntentFilterVerifierComponent.getPackageName(), whitelistTimeout,
UserHandle.USER_SYSTEM, true, "intent filter verifier");
- mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
+ mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM,
+ null, options.toBundle());
if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
"Sending IntentFilter verification broadcast");
}
@@ -3074,7 +3078,8 @@
}
}
- mInstallerService = new PackageInstallerService(context, this);
+ mApexManager = new ApexManager();
+ mInstallerService = new PackageInstallerService(context, this, mApexManager);
final Pair<ComponentName, String> instantAppResolverComponent =
getInstantAppResolverLPr();
if (instantAppResolverComponent != null) {
@@ -3301,7 +3306,8 @@
// feature flags should cause us to invalidate any caches.
final String cacheName = SystemProperties.digestOf(
"ro.build.fingerprint",
- "persist.sys.isolated_storage");
+ StorageManager.PROP_ISOLATED_STORAGE,
+ StorageManager.PROP_ISOLATED_STORAGE_SNAPSHOT);
// Reconcile cache directories, keeping only what we'd actually use.
for (File cacheDir : FileUtils.listFilesOrEmpty(cacheBaseDir)) {
@@ -3934,27 +3940,7 @@
}
//
if (!matchFactoryOnly && (flags & MATCH_APEX) != 0) {
- //TODO(b/123052859) Don't do file operations every time there is a query.
- final IApexService apex = IApexService.Stub.asInterface(
- ServiceManager.getService("apexservice"));
- if (apex != null) {
- try {
- final ApexInfo activePkg = apex.getActivePackage(packageName);
- if (activePkg != null && !TextUtils.isEmpty(activePkg.packagePath)) {
- try {
- return PackageParser.generatePackageInfoFromApex(
- new File(activePkg.packagePath), true /* collect certs */);
- } catch (PackageParserException pe) {
- Log.e(TAG, "Unable to parse package at "
- + activePkg.packagePath, pe);
- }
- }
- } catch (RemoteException e) {
- Log.e(TAG, "Unable to retrieve packages from apexservice: " + e.toString());
- }
- } else {
- Log.e(TAG, "Unable to connect to apexservice for querying packages.");
- }
+ return mApexManager.getActivePackage(packageName);
}
}
return null;
@@ -7851,25 +7837,7 @@
if (listApex) {
// TODO(b/119767311): include uninstalled/inactive APEX if
// MATCH_UNINSTALLED_PACKAGES is set.
- final IApexService apex = IApexService.Stub.asInterface(
- ServiceManager.getService("apexservice"));
- if (apex != null) {
- try {
- final ApexInfo[] activePkgs = apex.getActivePackages();
- for (ApexInfo ai : activePkgs) {
- try {
- list.add(PackageParser.generatePackageInfoFromApex(
- new File(ai.packagePath), true /* collect certs */));
- } catch (PackageParserException pe) {
- throw new IllegalStateException("Unable to parse: " + ai, pe);
- }
- }
- } catch (RemoteException e) {
- Log.e(TAG, "Unable to retrieve packages from apexservice: " + e.toString());
- }
- } else {
- Log.e(TAG, "Unable to connect to apexservice for querying packages.");
- }
+ list.addAll(mApexManager.getActivePackages());
}
return new ParceledListSlice<>(list);
}
@@ -12836,7 +12804,7 @@
public String[] setDistractingPackageRestrictionsAsUser(String[] packageNames,
int restrictionFlags, int userId) {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS,
- "setPackagesSuspendedAsUser");
+ "setDistractingPackageRestrictionsAsUser");
final int callingUid = Binder.getCallingUid();
if (callingUid != Process.ROOT_UID && callingUid != Process.SYSTEM_UID
@@ -14604,14 +14572,19 @@
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
- // TODO(ruhler) b/112431924 Have a configurable setting to
- // allow changing the timeout and fall back to the default
- // if no such specified.
+ // the duration to wait for rollback to be enabled, in millis
+ long rollbackTimeout = DEFAULT_ENABLE_ROLLBACK_TIMEOUT;
+ try {
+ rollbackTimeout = Long.valueOf(
+ DeviceConfig.getProperty(
+ DeviceConfig.Rollback.NAMESPACE,
+ DeviceConfig.Rollback.ENABLE_ROLLBACK_TIMEOUT));
+ } catch (NumberFormatException ignore) {
+ }
final Message msg = mHandler.obtainMessage(
ENABLE_ROLLBACK_TIMEOUT);
msg.arg1 = enableRollbackToken;
- mHandler.sendMessageDelayed(msg,
- DEFAULT_ENABLE_ROLLBACK_TIMEOUT);
+ mHandler.sendMessageDelayed(msg, rollbackTimeout);
}
}, null, 0, null, null);
@@ -21319,51 +21292,7 @@
}
if (!checkin && dumpState.isDumping(DumpState.DUMP_APEX)) {
- final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
- ipw.println();
- ipw.println("Active APEX packages:");
- ipw.increaseIndent();
- final IApexService apex = IApexService.Stub.asInterface(
- ServiceManager.getService("apexservice"));
- try {
- final ApexInfo[] activeApexes = apex.getActivePackages();
- for (ApexInfo ai : activeApexes) {
- if (packageName != null && !packageName.equals(ai.packageName)) {
- continue;
- }
- ipw.println(ai.packageName);
- ipw.increaseIndent();
- ipw.println("Version: " + Long.toString(ai.versionCode));
- ipw.println("Path: " + ai.packagePath);
- ipw.decreaseIndent();
- }
- ipw.decreaseIndent();
- ipw.println();
- ipw.println("APEX session state:");
- ipw.increaseIndent();
- final ApexSessionInfo[] sessions = apex.getSessions();
- for (ApexSessionInfo si : sessions) {
- ipw.println("Session ID: " + Integer.toString(si.sessionId));
- ipw.increaseIndent();
- if (si.isUnknown) {
- ipw.println("State: UNKNOWN");
- } else if (si.isVerified) {
- ipw.println("State: VERIFIED");
- } else if (si.isStaged) {
- ipw.println("State: STAGED");
- } else if (si.isActivated) {
- ipw.println("State: ACTIVATED");
- } else if (si.isActivationPendingRetry) {
- ipw.println("State: ACTIVATION PENDING RETRY");
- } else if (si.isActivationFailed) {
- ipw.println("State: ACTIVATION FAILED");
- }
- ipw.decreaseIndent();
- }
- ipw.decreaseIndent();
- } catch (RemoteException e) {
- ipw.println("Couldn't communicate with apexd.");
- }
+ mApexManager.dump(pw, packageName);
}
}
diff --git a/services/core/java/com/android/server/pm/ShortcutPackage.java b/services/core/java/com/android/server/pm/ShortcutPackage.java
index 84c8b60..d9a5eb9 100644
--- a/services/core/java/com/android/server/pm/ShortcutPackage.java
+++ b/services/core/java/com/android/server/pm/ShortcutPackage.java
@@ -18,6 +18,7 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.UserIdInt;
+import android.app.Person;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
@@ -33,6 +34,7 @@
import android.util.Slog;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.util.ArrayUtils;
import com.android.internal.util.Preconditions;
import com.android.internal.util.XmlUtils;
import com.android.server.pm.ShortcutService.DumpFilter;
@@ -71,6 +73,7 @@
private static final String TAG_EXTRAS = "extras";
private static final String TAG_SHORTCUT = "shortcut";
private static final String TAG_CATEGORIES = "categories";
+ private static final String TAG_PERSON = "person";
private static final String ATTR_NAME = "name";
private static final String ATTR_CALL_COUNT = "call-count";
@@ -96,6 +99,12 @@
private static final String ATTR_ICON_RES_NAME = "icon-resname";
private static final String ATTR_BITMAP_PATH = "bitmap-path";
+ private static final String ATTR_PERSON_NAME = "name";
+ private static final String ATTR_PERSON_URI = "uri";
+ private static final String ATTR_PERSON_KEY = "key";
+ private static final String ATTR_PERSON_IS_BOT = "is-bot";
+ private static final String ATTR_PERSON_IS_IMPORTANT = "is-important";
+
private static final String NAME_CATEGORIES = "categories";
private static final String TAG_STRING_ARRAY_XMLUTILS = "string-array";
@@ -1499,6 +1508,22 @@
out.endTag(null, TAG_CATEGORIES);
}
}
+ if (!forBackup) { // Don't backup the persons field.
+ final Person[] persons = si.getPersons();
+ if (!ArrayUtils.isEmpty(persons)) {
+ for (int i = 0; i < persons.length; i++) {
+ final Person p = persons[i];
+
+ out.startTag(null, TAG_PERSON);
+ ShortcutService.writeAttr(out, ATTR_PERSON_NAME, p.getName());
+ ShortcutService.writeAttr(out, ATTR_PERSON_URI, p.getUri());
+ ShortcutService.writeAttr(out, ATTR_PERSON_KEY, p.getKey());
+ ShortcutService.writeAttr(out, ATTR_PERSON_IS_BOT, p.isBot());
+ ShortcutService.writeAttr(out, ATTR_PERSON_IS_IMPORTANT, p.isImportant());
+ out.endTag(null, TAG_PERSON);
+ }
+ }
+ }
final Intent[] intentsNoExtras = si.getIntentsNoExtras();
final PersistableBundle[] intentsExtras = si.getIntentPersistableExtrases();
final int numIntents = intentsNoExtras.length;
@@ -1588,6 +1613,7 @@
String bitmapPath;
int backupVersionCode;
ArraySet<String> categories = null;
+ ArrayList<Person> persons = new ArrayList<>();
id = ShortcutService.parseStringAttribute(parser, ATTR_ID);
activityComponent = ShortcutService.parseComponentNameAttribute(parser,
@@ -1638,6 +1664,9 @@
case TAG_CATEGORIES:
// This just contains string-array.
continue;
+ case TAG_PERSON:
+ persons.add(parsePerson(parser));
+ continue;
case TAG_STRING_ARRAY_XMLUTILS:
if (NAME_CATEGORIES.equals(ShortcutService.parseStringAttribute(parser,
ATTR_NAME_XMLUTILS))) {
@@ -1680,7 +1709,8 @@
categories,
intents.toArray(new Intent[intents.size()]),
rank, extras, lastChangedTimestamp, flags,
- iconResId, iconResName, bitmapPath, disabledReason);
+ iconResId, iconResName, bitmapPath, disabledReason,
+ persons.toArray(new Person[persons.size()]));
}
private static Intent parseIntent(XmlPullParser parser)
@@ -1713,6 +1743,20 @@
return intent;
}
+ private static Person parsePerson(XmlPullParser parser)
+ throws IOException, XmlPullParserException {
+ CharSequence name = ShortcutService.parseStringAttribute(parser, ATTR_PERSON_NAME);
+ String uri = ShortcutService.parseStringAttribute(parser, ATTR_PERSON_URI);
+ String key = ShortcutService.parseStringAttribute(parser, ATTR_PERSON_KEY);
+ boolean isBot = ShortcutService.parseBooleanAttribute(parser, ATTR_PERSON_IS_BOT);
+ boolean isImportant = ShortcutService.parseBooleanAttribute(parser,
+ ATTR_PERSON_IS_IMPORTANT);
+
+ Person.Builder builder = new Person.Builder();
+ builder.setName(name).setUri(uri).setKey(key).setBot(isBot).setImportant(isImportant);
+ return builder.build();
+ }
+
@VisibleForTesting
List<ShortcutInfo> getAllShortcutsForTest() {
return new ArrayList<>(mShortcuts.values());
diff --git a/services/core/java/com/android/server/pm/ShortcutParser.java b/services/core/java/com/android/server/pm/ShortcutParser.java
index 90f08c3..668fc88 100644
--- a/services/core/java/com/android/server/pm/ShortcutParser.java
+++ b/services/core/java/com/android/server/pm/ShortcutParser.java
@@ -449,7 +449,8 @@
iconResId,
null, // icon res name
null, // bitmap path
- disabledReason);
+ disabledReason,
+ null /* persons */);
}
private static String parseCategory(ShortcutService service, AttributeSet attrs) {
diff --git a/services/core/java/com/android/server/pm/StagingManager.java b/services/core/java/com/android/server/pm/StagingManager.java
index fa8360b..30c2281 100644
--- a/services/core/java/com/android/server/pm/StagingManager.java
+++ b/services/core/java/com/android/server/pm/StagingManager.java
@@ -20,12 +20,12 @@
import android.apex.ApexInfo;
import android.apex.ApexInfoList;
import android.apex.ApexSessionInfo;
-import android.apex.IApexService;
import android.content.Context;
import android.content.IIntentReceiver;
import android.content.IIntentSender;
import android.content.Intent;
import android.content.IntentSender;
+import android.content.pm.PackageInfo;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageInstaller.SessionInfo;
import android.content.pm.PackageManager;
@@ -41,7 +41,6 @@
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.os.ServiceManager;
-import android.text.TextUtils;
import android.util.Slog;
import android.util.SparseArray;
import android.util.apk.ApkSignatureVerifier;
@@ -68,14 +67,16 @@
private final PackageInstallerService mPi;
private final PackageManagerService mPm;
+ private final ApexManager mApexManager;
private final Handler mBgHandler;
@GuardedBy("mStagedSessions")
private final SparseArray<PackageInstallerSession> mStagedSessions = new SparseArray<>();
- StagingManager(PackageManagerService pm, PackageInstallerService pi) {
+ StagingManager(PackageManagerService pm, PackageInstallerService pi, ApexManager am) {
mPm = pm;
mPi = pi;
+ mApexManager = am;
mBgHandler = BackgroundThread.getHandler();
}
@@ -100,7 +101,7 @@
return new ParceledListSlice<>(result);
}
- private static boolean validateApexSignature(String apexPath, String packageName) {
+ private boolean validateApexSignature(String apexPath, String packageName) {
final SigningDetails signingDetails;
try {
signingDetails = ApkSignatureVerifier.verify(apexPath, SignatureSchemeVersion.JAR);
@@ -109,17 +110,9 @@
return false;
}
- final IApexService apex = IApexService.Stub.asInterface(
- ServiceManager.getService("apexservice"));
- final ApexInfo apexInfo;
- try {
- apexInfo = apex.getActivePackage(packageName);
- } catch (RemoteException re) {
- Slog.e(TAG, "Unable to contact APEXD", re);
- return false;
- }
+ final PackageInfo packageInfo = mApexManager.getActivePackage(packageName);
- if (apexInfo == null || TextUtils.isEmpty(apexInfo.packageName)) {
+ if (packageInfo == null) {
// TODO: What is the right thing to do here ? This implies there's no active package
// with the given name. This should never be the case in production (where we only
// accept updates to existing APEXes) but may be required for testing.
@@ -129,9 +122,10 @@
final SigningDetails existingSigningDetails;
try {
existingSigningDetails = ApkSignatureVerifier.verify(
- apexInfo.packagePath, SignatureSchemeVersion.JAR);
+ packageInfo.applicationInfo.sourceDir, SignatureSchemeVersion.JAR);
} catch (PackageParserException e) {
- Slog.e(TAG, "Unable to parse APEX package: " + apexInfo.packagePath, e);
+ Slog.e(TAG, "Unable to parse APEX package: "
+ + packageInfo.applicationInfo.sourceDir, e);
return false;
}
@@ -143,10 +137,10 @@
return false;
}
- private static boolean submitSessionToApexService(@NonNull PackageInstallerSession session,
- List<PackageInstallerSession> childSessions,
- ApexInfoList apexInfoList) {
- return sendSubmitStagedSessionRequest(
+ private boolean submitSessionToApexService(@NonNull PackageInstallerSession session,
+ List<PackageInstallerSession> childSessions,
+ ApexInfoList apexInfoList) {
+ return mApexManager.submitStagedSession(
session.sessionId,
childSessions != null
? childSessions.stream().mapToInt(s -> s.sessionId).toArray() :
@@ -154,33 +148,6 @@
apexInfoList);
}
- private static boolean sendSubmitStagedSessionRequest(
- int sessionId, int[] childSessionIds, ApexInfoList apexInfoList) {
- final IApexService apex = IApexService.Stub.asInterface(
- ServiceManager.getService("apexservice"));
- boolean success;
- try {
- success = apex.submitStagedSession(sessionId, childSessionIds, apexInfoList);
- } catch (RemoteException re) {
- Slog.e(TAG, "Unable to contact apexservice", re);
- return false;
- }
- return success;
- }
-
- private static boolean sendMarkStagedSessionReadyRequest(int sessionId) {
- final IApexService apex = IApexService.Stub.asInterface(
- ServiceManager.getService("apexservice"));
- boolean success;
- try {
- success = apex.markStagedSessionReady(sessionId);
- } catch (RemoteException re) {
- Slog.e(TAG, "Unable to contact apexservice", re);
- return false;
- }
- return success;
- }
-
private static boolean isApexSession(@NonNull PackageInstallerSession session) {
return (session.params.installFlags & PackageManager.INSTALL_APEX) != 0;
}
@@ -260,7 +227,7 @@
}
session.setStagedSessionReady();
- if (!sendMarkStagedSessionReadyRequest(session.sessionId)) {
+ if (!mApexManager.markStagedSessionReady(session.sessionId)) {
session.setStagedSessionFailed(SessionInfo.STAGED_SESSION_VERIFICATION_FAILED,
"APEX staging failed, check logcat messages from apexd for more "
+ "details.");
@@ -284,16 +251,12 @@
private void resumeSession(@NonNull PackageInstallerSession session) {
if (sessionContainsApex(session)) {
- // Check with apexservice whether the apex
- // packages have been activated.
- final IApexService apex = IApexService.Stub.asInterface(
- ServiceManager.getService("apexservice"));
- ApexSessionInfo apexSessionInfo;
- try {
- apexSessionInfo = apex.getStagedSessionInfo(session.sessionId);
- } catch (RemoteException re) {
- Slog.e(TAG, "Unable to contact apexservice", re);
- // TODO should we retry here? Mark the session as failed?
+ // Check with apexservice whether the apex packages have been activated.
+ ApexSessionInfo apexSessionInfo = mApexManager.getStagedSessionInfo(session.sessionId);
+ if (apexSessionInfo == null) {
+ session.setStagedSessionFailed(SessionInfo.STAGED_SESSION_ACTIVATION_FAILED,
+ "apexd did not know anything about a staged session supposed to be"
+ + "activated");
return;
}
if (apexSessionInfo.isActivationFailed || apexSessionInfo.isUnknown) {
@@ -323,8 +286,8 @@
// The APEX part of the session is activated, proceed with the installation of APKs.
if (!installApksInSession(session)) {
session.setStagedSessionFailed(SessionInfo.STAGED_SESSION_ACTIVATION_FAILED,
- "APEX activation failed. Check logcat messages from apexd for "
- + "more information.");
+ "Staged installation of APKs failed. Check logcat messages for"
+ + "more information.");
return;
}
session.setStagedSessionApplied();
diff --git a/services/core/java/com/android/server/pm/UserRestrictionsUtils.java b/services/core/java/com/android/server/pm/UserRestrictionsUtils.java
index 18e292f..7e4365d 100644
--- a/services/core/java/com/android/server/pm/UserRestrictionsUtils.java
+++ b/services/core/java/com/android/server/pm/UserRestrictionsUtils.java
@@ -119,6 +119,7 @@
UserManager.DISALLOW_OEM_UNLOCK,
UserManager.DISALLOW_UNMUTE_DEVICE,
UserManager.DISALLOW_AUTOFILL,
+ UserManager.DISALLOW_CONTENT_CAPTURE,
UserManager.DISALLOW_USER_SWITCH,
UserManager.DISALLOW_UNIFIED_PASSWORD,
UserManager.DISALLOW_CONFIG_LOCATION,
diff --git a/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java b/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
index bfa539c..bd577598 100644
--- a/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
+++ b/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
@@ -645,7 +645,7 @@
grantPermissionsToSystemPackage(packageName, userId,
CONTACTS_PERMISSIONS, CALENDAR_PERMISSIONS, MICROPHONE_PERMISSIONS,
PHONE_PERMISSIONS, SMS_PERMISSIONS, CAMERA_PERMISSIONS,
- SENSORS_PERMISSIONS, STORAGE_PERMISSIONS);
+ SENSORS_PERMISSIONS, STORAGE_PERMISSIONS, MEDIA_AURAL_PERMISSIONS);
grantSystemFixedPermissionsToSystemPackage(packageName, userId,
LOCATION_PERMISSIONS, ACTIVITY_RECOGNITION_PERMISSIONS);
}
@@ -721,7 +721,7 @@
grantSystemFixedPermissionsToSystemPackage(
getDefaultSystemHandlerActivityPackage(
RingtoneManager.ACTION_RINGTONE_PICKER, userId),
- userId, STORAGE_PERMISSIONS);
+ userId, STORAGE_PERMISSIONS, MEDIA_AURAL_PERMISSIONS);
// TextClassifier Service
String textClassifierPackageName =
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index b00193f..2e3e3e4 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -22,7 +22,6 @@
import static android.app.AppOpsManager.OP_TOAST_WINDOW;
import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
import static android.content.Context.CONTEXT_RESTRICTED;
-import static android.content.Context.DISPLAY_SERVICE;
import static android.content.Context.WINDOW_SERVICE;
import static android.content.pm.PackageManager.FEATURE_HDMI_CEC;
import static android.content.pm.PackageManager.FEATURE_LEANBACK;
@@ -36,6 +35,7 @@
import static android.view.Display.DEFAULT_DISPLAY;
import static android.view.Display.INVALID_DISPLAY;
import static android.view.Display.STATE_OFF;
+import static android.view.KeyEvent.KEYCODE_UNKNOWN;
import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW;
import static android.view.WindowManager.LayoutParams.FIRST_SUB_WINDOW;
import static android.view.WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW;
@@ -84,10 +84,8 @@
import static android.view.WindowManagerGlobal.ADD_PERMISSION_DENIED;
import static com.android.server.policy.WindowManagerPolicy.WindowManagerFuncs.CAMERA_LENS_COVERED;
-import static com.android.server.policy.WindowManagerPolicy.WindowManagerFuncs
- .CAMERA_LENS_COVER_ABSENT;
-import static com.android.server.policy.WindowManagerPolicy.WindowManagerFuncs
- .CAMERA_LENS_UNCOVERED;
+import static com.android.server.policy.WindowManagerPolicy.WindowManagerFuncs.CAMERA_LENS_COVER_ABSENT;
+import static com.android.server.policy.WindowManagerPolicy.WindowManagerFuncs.CAMERA_LENS_UNCOVERED;
import static com.android.server.policy.WindowManagerPolicy.WindowManagerFuncs.LID_CLOSED;
import static com.android.server.policy.WindowManagerPolicy.WindowManagerFuncs.LID_OPEN;
import static com.android.server.wm.WindowManagerPolicyProto.KEYGUARD_DELEGATE;
@@ -371,6 +369,7 @@
IStatusBarService mStatusBarService;
StatusBarManagerInternal mStatusBarManagerInternal;
AudioManagerInternal mAudioManagerInternal;
+ DisplayManager mDisplayManager;
boolean mPreloadedRecentApps;
final Object mServiceAquireLock = new Object();
Vibrator mVibrator; // Vibrator for giving feedback of orientation changes
@@ -1717,7 +1716,8 @@
mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
mDreamManagerInternal = LocalServices.getService(DreamManagerInternal.class);
mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
- mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
+ mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
+ mDisplayManager = mContext.getSystemService(DisplayManager.class);
mHasFeatureWatch = mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH);
mHasFeatureLeanback = mContext.getPackageManager().hasSystemFeature(FEATURE_LEANBACK);
mHasFeatureHdmiCec = mContext.getPackageManager().hasSystemFeature(FEATURE_HDMI_CEC);
@@ -2508,8 +2508,7 @@
return context;
}
- final DisplayManager dm = (DisplayManager) context.getSystemService(DISPLAY_SERVICE);
- final Display targetDisplay = dm.getDisplay(displayId);
+ final Display targetDisplay = mDisplayManager.getDisplay(displayId);
if (targetDisplay == null) {
// Failed to obtain the non-default display where splash screen should be shown,
// lets not show at all.
@@ -3655,7 +3654,7 @@
// Reset the pending key
mPendingWakeKey = PENDING_KEY_NULL;
}
- } else if (!interactive && shouldDispatchInputWhenNonInteractive(event)) {
+ } else if (!interactive && shouldDispatchInputWhenNonInteractive(displayId, keyCode)) {
// If we're currently dozing with the screen on and the keyguard showing, pass the key
// to the application but preserve its wake key status to make sure we still move
// from dozing to fully interactive if we would normally go from off to fully
@@ -4126,7 +4125,8 @@
// TODO(b/117479243): handle it in InputPolicy
/** {@inheritDoc} */
@Override
- public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
+ public int interceptMotionBeforeQueueingNonInteractive(int displayId, long whenNanos,
+ int policyFlags) {
if ((policyFlags & FLAG_WAKE) != 0) {
if (wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromMotion,
PowerManager.WAKE_REASON_WAKE_MOTION, "android.policy:MOTION")) {
@@ -4134,7 +4134,7 @@
}
}
- if (shouldDispatchInputWhenNonInteractive(null)) {
+ if (shouldDispatchInputWhenNonInteractive(displayId, KEYCODE_UNKNOWN)) {
return ACTION_PASS_TO_USER;
}
@@ -4149,9 +4149,15 @@
return 0;
}
- private boolean shouldDispatchInputWhenNonInteractive(KeyEvent event) {
- final boolean displayOff = (mDefaultDisplay == null
- || mDefaultDisplay.getState() == STATE_OFF);
+ private boolean shouldDispatchInputWhenNonInteractive(int displayId, int keyCode) {
+ // Apply the default display policy to unknown displays as well.
+ final boolean isDefaultDisplay = displayId == DEFAULT_DISPLAY
+ || displayId == INVALID_DISPLAY;
+ final Display display = isDefaultDisplay
+ ? mDefaultDisplay
+ : mDisplayManager.getDisplay(displayId);
+ final boolean displayOff = (display == null
+ || display.getState() == STATE_OFF);
if (displayOff && !mHasFeatureWatch) {
return false;
@@ -4163,25 +4169,25 @@
}
// Watches handle BACK specially
- if (mHasFeatureWatch
- && event != null
- && (event.getKeyCode() == KeyEvent.KEYCODE_BACK
- || event.getKeyCode() == KeyEvent.KEYCODE_STEM_PRIMARY)) {
+ if (mHasFeatureWatch && (keyCode == KeyEvent.KEYCODE_BACK
+ || keyCode == KeyEvent.KEYCODE_STEM_PRIMARY)) {
return false;
}
- // Send events to a dozing dream even if the screen is off since the dream
- // is in control of the state of the screen.
- IDreamManager dreamManager = getDreamManager();
+ // TODO(b/123372519): Refine when dream can support multi display.
+ if (isDefaultDisplay) {
+ // Send events to a dozing dream even if the screen is off since the dream
+ // is in control of the state of the screen.
+ IDreamManager dreamManager = getDreamManager();
- try {
- if (dreamManager != null && dreamManager.isDreaming()) {
- return true;
+ try {
+ if (dreamManager != null && dreamManager.isDreaming()) {
+ return true;
+ }
+ } catch (RemoteException e) {
+ Slog.e(TAG, "RemoteException when checking if dreaming", e);
}
- } catch (RemoteException e) {
- Slog.e(TAG, "RemoteException when checking if dreaming", e);
}
-
// Otherwise, consume events since the user can't see what is being
// interacted with.
return false;
diff --git a/services/core/java/com/android/server/policy/WindowManagerPolicy.java b/services/core/java/com/android/server/policy/WindowManagerPolicy.java
index d1bd102..870d61b 100644
--- a/services/core/java/com/android/server/policy/WindowManagerPolicy.java
+++ b/services/core/java/com/android/server/policy/WindowManagerPolicy.java
@@ -1003,11 +1003,13 @@
* affect the power state of the device, for example, waking on motions.
* Generally, it's best to keep as little as possible in the queue thread
* because it's the most fragile.
+ * @param displayId The display ID of the motion event.
* @param policyFlags The policy flags associated with the motion.
*
* @return Actions flags: may be {@link #ACTION_PASS_TO_USER}.
*/
- public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags);
+ int interceptMotionBeforeQueueingNonInteractive(int displayId, long whenNanos,
+ int policyFlags);
/**
* Called from the input dispatcher thread before a key is dispatched to a window.
diff --git a/services/core/java/com/android/server/stats/StatsCompanionService.java b/services/core/java/com/android/server/stats/StatsCompanionService.java
index dd2cda2..f3393e2 100644
--- a/services/core/java/com/android/server/stats/StatsCompanionService.java
+++ b/services/core/java/com/android/server/stats/StatsCompanionService.java
@@ -167,6 +167,7 @@
public static final int CODE_DATA_BROADCAST = 1;
public static final int CODE_SUBSCRIBER_BROADCAST = 1;
+ public static final int CODE_ACTIVE_CONFIGS_BROADCAST = 1;
/**
* The last report time is provided with each intent registered to
* StatsManager#setFetchReportsOperation. This allows easy de-duping in the receiver if
@@ -356,6 +357,22 @@
}
@Override
+ public void sendActiveConfigsChangedBroadcast(IBinder intentSenderBinder, long[] configIds) {
+ enforceCallingPermission();
+ IntentSender intentSender = new IntentSender(intentSenderBinder);
+ Intent intent = new Intent();
+ intent.putExtra(StatsManager.EXTRA_STATS_ACTIVE_CONFIG_KEYS, configIds);
+ try {
+ intentSender.sendIntent(mContext, CODE_ACTIVE_CONFIGS_BROADCAST, intent, null, null);
+ if (DEBUG) {
+ Slog.d(TAG, "Sent broadcast with config ids " + Arrays.toString(configIds));
+ }
+ } catch (IntentSender.SendIntentException e) {
+ Slog.w(TAG, "Unable to send active configs changed broadcast using IntentSender");
+ }
+ }
+
+ @Override
public void sendSubscriberBroadcast(IBinder intentSenderBinder, long configUid, long configKey,
long subscriptionId, long subscriptionRuleId, String[] cookies,
StatsDimensionsValue dimensionsValue) {
@@ -1169,7 +1186,7 @@
BinderCallsStatsService.Internal binderStats =
LocalServices.getService(BinderCallsStatsService.Internal.class);
if (binderStats == null) {
- return;
+ throw new IllegalStateException("binderStats is null");
}
List<ExportedCallStat> callStats = binderStats.getExportedCallStats();
@@ -1200,7 +1217,7 @@
BinderCallsStatsService.Internal binderStats =
LocalServices.getService(BinderCallsStatsService.Internal.class);
if (binderStats == null) {
- return;
+ throw new IllegalStateException("binderStats is null");
}
ArrayMap<String, Integer> exceptionStats = binderStats.getExportedExceptionStats();
@@ -1218,7 +1235,7 @@
List<StatsLogEventWrapper> pulledData) {
LooperStats looperStats = LocalServices.getService(LooperStats.class);
if (looperStats == null) {
- return;
+ throw new IllegalStateException("looperStats null");
}
List<LooperStats.ExportedEntry> entries = looperStats.getEntries();
@@ -1689,18 +1706,19 @@
private void pullCpuTimePerThreadFreq(int tagId, long elapsedNanos, long wallClockNanos,
List<StatsLogEventWrapper> pulledData) {
if (this.mKernelCpuThreadReader == null) {
- return;
+ throw new IllegalStateException("mKernelCpuThreadReader is null");
}
ArrayList<KernelCpuThreadReader.ProcessCpuUsage> processCpuUsages =
this.mKernelCpuThreadReader.getProcessCpuUsageByUids();
if (processCpuUsages == null) {
- return;
+ throw new IllegalStateException("processCpuUsages is null");
}
int[] cpuFrequencies = mKernelCpuThreadReader.getCpuFrequenciesKhz();
if (cpuFrequencies.length > CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES) {
- Slog.w(TAG, "Expected maximum " + CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES
- + " frequencies, but got " + cpuFrequencies.length);
- return;
+ String message = "Expected maximum " + CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES
+ + " frequencies, but got " + cpuFrequencies.length;
+ Slog.w(TAG, message);
+ throw new IllegalStateException(message);
}
for (int i = 0; i < processCpuUsages.size(); i++) {
KernelCpuThreadReader.ProcessCpuUsage processCpuUsage = processCpuUsages.get(i);
@@ -1709,10 +1727,11 @@
for (int j = 0; j < threadCpuUsages.size(); j++) {
KernelCpuThreadReader.ThreadCpuUsage threadCpuUsage = threadCpuUsages.get(j);
if (threadCpuUsage.usageTimesMillis.length != cpuFrequencies.length) {
- Slog.w(TAG, "Unexpected number of usage times,"
+ String message = "Unexpected number of usage times,"
+ " expected " + cpuFrequencies.length
- + " but got " + threadCpuUsage.usageTimesMillis.length);
- continue;
+ + " but got " + threadCpuUsage.usageTimesMillis.length;
+ Slog.w(TAG, message);
+ throw new IllegalStateException(message);
}
StatsLogEventWrapper e =
diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java
index 4faf910..0251efb 100644
--- a/services/core/java/com/android/server/wm/ActivityRecord.java
+++ b/services/core/java/com/android/server/wm/ActivityRecord.java
@@ -75,12 +75,12 @@
import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE;
import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION;
import static android.content.pm.ActivityInfo.RESIZE_MODE_UNRESIZEABLE;
-import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
import static android.content.pm.ActivityInfo.isFixedOrientationLandscape;
import static android.content.pm.ActivityInfo.isFixedOrientationPortrait;
import static android.content.res.Configuration.EMPTY;
import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
+import static android.content.res.Configuration.ORIENTATION_UNDEFINED;
import static android.content.res.Configuration.UI_MODE_TYPE_MASK;
import static android.content.res.Configuration.UI_MODE_TYPE_VR_HEADSET;
import static android.os.Build.VERSION_CODES.HONEYCOMB;
@@ -2610,10 +2610,6 @@
}
}
- int getRequestedOrientation() {
- return getOrientation();
- }
-
void setRequestedOrientation(int requestedOrientation) {
setOrientation(requestedOrientation, mayFreezeScreenLocked(app));
mAtmService.getTaskChangeNotificationController().notifyActivityRequestedOrientationChanged(
@@ -2641,7 +2637,7 @@
int getOrientation() {
if (mAppWindowToken == null) {
- return SCREEN_ORIENTATION_UNSPECIFIED;
+ return info.screenOrientation;
}
return mAppWindowToken.getOrientationIgnoreVisibility();
@@ -2677,25 +2673,92 @@
mLastReportedConfiguration.setConfiguration(global, override);
}
+ /**
+ * Get the configuration orientation by the requested screen orientation
+ * ({@link ActivityInfo.ScreenOrientation}) of this activity.
+ *
+ * @return orientation in ({@link #ORIENTATION_LANDSCAPE}, {@link #ORIENTATION_PORTRAIT},
+ * {@link #ORIENTATION_UNDEFINED}).
+ */
+ int getRequestedConfigurationOrientation() {
+ final int screenOrientation = getOrientation();
+ if (screenOrientation == ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
+ // NOSENSOR means the display's "natural" orientation, so return that.
+ final ActivityDisplay display = getDisplay();
+ if (display != null && display.mDisplayContent != null) {
+ return display.mDisplayContent.getNaturalOrientation();
+ }
+ } else if (screenOrientation == ActivityInfo.SCREEN_ORIENTATION_LOCKED) {
+ // LOCKED means the activity's orientation remains unchanged, so return existing value.
+ return getConfiguration().orientation;
+ } else if (isFixedOrientationLandscape(screenOrientation)) {
+ return ORIENTATION_LANDSCAPE;
+ } else if (isFixedOrientationPortrait(screenOrientation)) {
+ return ORIENTATION_PORTRAIT;
+ }
+ return ORIENTATION_UNDEFINED;
+ }
+
+ /**
+ * Indicates the activity will keep the bounds and screen configuration when it was first
+ * launched, no matter how its parent changes.
+ *
+ * @return {@code true} if this activity is declared as non-resizable and fixed orientation or
+ * aspect ratio.
+ */
+ private boolean inSizeCompatMode() {
+ return !isResizeable() && (info.isFixedOrientation() || info.hasFixedAspectRatio())
+ // The configuration of non-standard type should be enforced by system.
+ && isActivityTypeStandard()
+ && !mAtmService.mForceResizableActivities;
+ }
+
// TODO(b/36505427): Consider moving this method and similar ones to ConfigurationContainer.
private void updateOverrideConfiguration() {
+ final boolean inSizeCompatMode = inSizeCompatMode();
+ if (inSizeCompatMode) {
+ if (!matchParentBounds()) {
+ // The override configuration is set only once in size compatible mode.
+ return;
+ }
+ if (!hasProcess() && !isConfigurationCompatible(task.getConfiguration())) {
+ // Don't compute when launching in fullscreen and the fixed orientation is not the
+ // current orientation. It is more accurately to compute the override bounds from
+ // the updated configuration after the fixed orientation is applied.
+ return;
+ }
+ }
+
computeBounds(mTmpBounds);
+ if (inSizeCompatMode && mTmpBounds.isEmpty()) {
+ mTmpBounds.set(task.getWindowConfiguration().getBounds());
+ }
if (mTmpBounds.equals(getRequestedOverrideBounds())) {
+ // The bounds is not changed or the activity is resizable (both the 2 bounds are empty).
return;
}
- setBounds(mTmpBounds);
-
- // Bounds changed...update configuration to match.
- if (!matchParentBounds()) {
- mTmpConfig.setTo(getRequestedOverrideConfiguration());
- task.computeConfigResourceOverrides(mTmpConfig, task.getParent().getConfiguration());
- } else {
- mTmpConfig.unset();
+ final Configuration overrideConfig = mTmpConfig;
+ overrideConfig.unset();
+ if (!mTmpBounds.isEmpty()) {
+ overrideConfig.windowConfiguration.setBounds(mTmpBounds);
+ if (inSizeCompatMode) {
+ // Ensure the screen related fields are set. It is used to prevent activity relaunch
+ // when moving between displays. For screenWidthDp and screenWidthDp, because they
+ // are relative to bounds and density, they will be calculated in
+ // {@link TaskRecord#computeConfigResourceOverrides} and the result will also be
+ // relatively fixed.
+ final Configuration srcConfig = task.getConfiguration();
+ overrideConfig.colorMode = srcConfig.colorMode;
+ overrideConfig.densityDpi = srcConfig.densityDpi;
+ overrideConfig.screenLayout = srcConfig.screenLayout;
+ // The smallest screen width is the short side of screen bounds. Because the bounds
+ // and density won't be changed, smallestScreenWidthDp is also fixed.
+ overrideConfig.smallestScreenWidthDp = srcConfig.smallestScreenWidthDp;
+ }
}
-
- onRequestedOverrideConfigurationChanged(mTmpConfig);
+ onRequestedOverrideConfigurationChanged(overrideConfig);
}
@Override
@@ -2707,6 +2770,86 @@
// layout traversals.
mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
getResolvedOverrideConfiguration().seq = mConfigurationSeq;
+
+ if (matchParentBounds()) {
+ return;
+ }
+
+ final Configuration resolvedConfig = getResolvedOverrideConfiguration();
+ if (!inSizeCompatMode()) {
+ computeConfigResourceOverrides(resolvedConfig, newParentConfiguration,
+ ORIENTATION_UNDEFINED, true /* insideParentBounds */);
+ return;
+ }
+
+ final Configuration displayConfig = getDisplay().getConfiguration();
+ int orientation = getConfiguration().orientation;
+ if (orientation != displayConfig.orientation && isConfigurationCompatible(displayConfig)) {
+ // The activity is compatible to apply the orientation change or it requests different
+ // fixed orientation.
+ orientation = displayConfig.orientation;
+ } else {
+ if (resolvedConfig.windowConfiguration.getAppBounds() != null) {
+ // Keep the computed resolved override configuration.
+ return;
+ }
+ final int requestedOrientation = getRequestedConfigurationOrientation();
+ if (requestedOrientation != ORIENTATION_UNDEFINED) {
+ orientation = requestedOrientation;
+ }
+ }
+
+ // Adjust the bounds to match the current orientation.
+ if (orientation != ORIENTATION_UNDEFINED) {
+ final Rect resolvedBounds = resolvedConfig.windowConfiguration.getBounds();
+ final int longSide = Math.max(resolvedBounds.height(), resolvedBounds.width());
+ final int shortSide = Math.min(resolvedBounds.height(), resolvedBounds.width());
+ final boolean toBeLandscape = orientation == ORIENTATION_LANDSCAPE;
+ final int width = toBeLandscape ? longSide : shortSide;
+ final int height = toBeLandscape ? shortSide : longSide;
+ // Assume the bounds is always started from zero because the size may be bigger than its
+ // parent (task ~ display). The actual letterboxing will be done by surface offset.
+ resolvedBounds.set(0, 0, width, height);
+ }
+
+ // In size compatible mode, activity is allowed to have larger bounds than its parent.
+ computeConfigResourceOverrides(resolvedConfig, newParentConfiguration, orientation,
+ false /* insideParentBounds */);
+ }
+
+ private void computeConfigResourceOverrides(Configuration inOutConfig,
+ Configuration parentConfig, int orientation, boolean insideParentBounds) {
+ // Set the real orientation or undefined value to ensure the output orientation won't be the
+ // old value. Also reset app bounds so it will be updated according to bounds.
+ inOutConfig.orientation = orientation;
+ final Rect outAppBounds = inOutConfig.windowConfiguration.getAppBounds();
+ if (outAppBounds != null) {
+ outAppBounds.setEmpty();
+ }
+
+ // TODO(b/112288258): Remove below calculation because the position information in bounds
+ // will be replaced by the offset of surface.
+ final Rect appBounds = parentConfig.windowConfiguration.getAppBounds();
+ if (appBounds != null) {
+ final Rect outBounds = inOutConfig.windowConfiguration.getBounds();
+ final int activityWidth = outBounds.width();
+ final int navBarPosition = mAtmService.mWindowManager.getNavBarPosition(getDisplayId());
+ if (navBarPosition == NAV_BAR_LEFT) {
+ // Position the activity frame on the opposite side of the nav bar.
+ outBounds.left = appBounds.right - activityWidth;
+ outBounds.right = appBounds.right;
+ } else if (navBarPosition == NAV_BAR_RIGHT) {
+ // Position the activity frame on the opposite side of the nav bar.
+ outBounds.left = 0;
+ outBounds.right = activityWidth + appBounds.left;
+ } else if (appBounds.width() > activityWidth) {
+ // Horizontally center the frame.
+ outBounds.left = appBounds.left + (appBounds.width() - activityWidth) / 2;
+ outBounds.right = outBounds.left + activityWidth;
+ }
+ }
+
+ task.computeConfigResourceOverrides(inOutConfig, parentConfig, insideParentBounds);
}
@Override
@@ -2739,8 +2882,7 @@
/** Returns true if the configuration is compatible with this activity. */
boolean isConfigurationCompatible(Configuration config) {
- final int orientation = mAppWindowToken != null
- ? getOrientation() : info.screenOrientation;
+ final int orientation = getOrientation();
if (isFixedOrientationPortrait(orientation)
&& config.orientation != ORIENTATION_PORTRAIT) {
return false;
@@ -2822,21 +2964,6 @@
// away later in StackWindowController.adjustConfigurationForBounds(). Otherwise, the app
// bounds would end up too small.
outBounds.set(0, 0, activityWidth + appBounds.left, activityHeight + appBounds.top);
-
- final int navBarPosition = mAtmService.mWindowManager.getNavBarPosition(getDisplayId());
- if (navBarPosition == NAV_BAR_LEFT) {
- // Position the activity frame on the opposite side of the nav bar.
- outBounds.left = appBounds.right - activityWidth;
- outBounds.right = appBounds.right;
- } else if (navBarPosition == NAV_BAR_RIGHT) {
- // Position the activity frame on the opposite side of the nav bar.
- outBounds.left = 0;
- outBounds.right = activityWidth + appBounds.left;
- } else {
- // Horizontally center the frame.
- outBounds.left = appBounds.left + (containingAppWidth - activityWidth) / 2;
- outBounds.right = outBounds.left + activityWidth;
- }
}
/**
diff --git a/services/core/java/com/android/server/wm/ActivityStack.java b/services/core/java/com/android/server/wm/ActivityStack.java
index cc78588..932cfd3 100644
--- a/services/core/java/com/android/server/wm/ActivityStack.java
+++ b/services/core/java/com/android/server/wm/ActivityStack.java
@@ -5631,6 +5631,19 @@
}
}
+ /**
+ * Get current bounds of this stack, return empty when it is unavailable.
+ * @see TaskStack#getAnimationOrCurrentBounds(Rect)
+ */
+ void getAnimationOrCurrentBounds(Rect outBounds) {
+ final TaskStack stack = getTaskStack();
+ if (stack == null) {
+ outBounds.setEmpty();
+ return;
+ }
+ stack.getAnimationOrCurrentBounds(outBounds);
+ }
+
private boolean skipResizeAnimation(boolean toFullscreen) {
if (!toFullscreen) {
return false;
diff --git a/services/core/java/com/android/server/wm/ActivityStarter.java b/services/core/java/com/android/server/wm/ActivityStarter.java
index 678a896..c33a2c1 100644
--- a/services/core/java/com/android/server/wm/ActivityStarter.java
+++ b/services/core/java/com/android/server/wm/ActivityStarter.java
@@ -989,8 +989,8 @@
if (mSupervisor.mRecentTasks.isCallerRecents(callingUid)) {
return false;
}
- // don't abort if the callingPackage is a device owner
- if (mService.getDevicePolicyManager().isDeviceOwnerApp(callingPackage)) {
+ // don't abort if the callingPackage is the device owner
+ if (mService.isDeviceOwner(callingPackage)) {
return false;
}
// anything that has fallen through would currently be aborted
diff --git a/services/core/java/com/android/server/wm/ActivityTaskManagerInternal.java b/services/core/java/com/android/server/wm/ActivityTaskManagerInternal.java
index 1a5e6a1..5a20959 100644
--- a/services/core/java/com/android/server/wm/ActivityTaskManagerInternal.java
+++ b/services/core/java/com/android/server/wm/ActivityTaskManagerInternal.java
@@ -492,4 +492,9 @@
/** Returns true if uid has a visible window or its process is in a top state. */
public abstract boolean isUidForeground(int uid);
+
+ /**
+ * Called by DevicePolicyManagerService to set the package name of the device owner.
+ */
+ public abstract void setDeviceOwnerPackageName(String deviceOwnerPkg);
}
diff --git a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
index 875fc4e..258819f 100644
--- a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
+++ b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
@@ -151,7 +151,6 @@
import android.app.WaitResult;
import android.app.WindowConfiguration;
import android.app.admin.DevicePolicyCache;
-import android.app.admin.DevicePolicyManager;
import android.app.assist.AssistContent;
import android.app.assist.AssistStructure;
import android.app.usage.UsageStatsManagerInternal;
@@ -363,7 +362,6 @@
WindowManagerService mWindowManager;
private UserManagerService mUserManager;
private AppOpsService mAppOpsService;
- private DevicePolicyManager mDpm;
/** All active uids in the system. */
private final SparseArray<Integer> mActiveUids = new SparseArray<>();
private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
@@ -623,6 +621,8 @@
private FontScaleSettingObserver mFontScaleSettingObserver;
+ private String mDeviceOwnerPackageName;
+
private final class FontScaleSettingObserver extends ContentObserver {
private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
@@ -838,13 +838,6 @@
return mAppOpsService;
}
- DevicePolicyManager getDevicePolicyManager() {
- if (mDpm == null) {
- mDpm = mContext.getSystemService(DevicePolicyManager.class);
- }
- return mDpm;
- }
-
boolean hasUserRestriction(String restriction, int userId) {
return getUserManager().hasUserRestriction(restriction, userId);
}
@@ -1720,7 +1713,7 @@
if (r == null) {
return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
}
- return r.getRequestedOrientation();
+ return r.getOrientation();
}
}
@@ -2452,6 +2445,40 @@
}
}
+ @Override
+ public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
+ int animationDuration) {
+ enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
+
+ final long ident = Binder.clearCallingIdentity();
+ try {
+ synchronized (mGlobalLock) {
+ if (xOffset == 0 && yOffset == 0) {
+ return;
+ }
+ final ActivityStack stack = mRootActivityContainer.getStack(stackId);
+ if (stack == null) {
+ Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
+ return;
+ }
+ if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
+ throw new IllegalArgumentException("Stack: " + stackId
+ + " doesn't support animated resize.");
+ }
+ final Rect destBounds = new Rect();
+ stack.getAnimationOrCurrentBounds(destBounds);
+ if (!destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
+ Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
+ return;
+ }
+ destBounds.offset(xOffset, yOffset);
+ stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
+ animationDuration, false /* fromFullscreen */);
+ }
+ } finally {
+ Binder.restoreCallingIdentity(ident);
+ }
+ }
/**
* Moves the specified task to the primary-split-screen stack.
*
@@ -5691,6 +5718,17 @@
|| mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
}
+ boolean isDeviceOwner(String packageName) {
+ if (packageName == null) {
+ return false;
+ }
+ return packageName.equals(mDeviceOwnerPackageName);
+ }
+
+ void setDeviceOwnerPackageName(String deviceOwnerPkg) {
+ mDeviceOwnerPackageName = deviceOwnerPkg;
+ }
+
/**
* @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
* the whitelist
@@ -7108,5 +7146,12 @@
return ActivityTaskManagerService.this.isUidForeground(uid);
}
}
+
+ @Override
+ public void setDeviceOwnerPackageName(String deviceOwnerPkg) {
+ synchronized (mGlobalLock) {
+ ActivityTaskManagerService.this.setDeviceOwnerPackageName(deviceOwnerPkg);
+ }
+ }
}
}
diff --git a/services/core/java/com/android/server/wm/AppWindowToken.java b/services/core/java/com/android/server/wm/AppWindowToken.java
index bcf6aba..88c8b95 100644
--- a/services/core/java/com/android/server/wm/AppWindowToken.java
+++ b/services/core/java/com/android/server/wm/AppWindowToken.java
@@ -239,6 +239,17 @@
ArrayDeque<Rect> mFrozenBounds = new ArrayDeque<>();
ArrayDeque<Configuration> mFrozenMergedConfig = new ArrayDeque<>();
+ /**
+ * The scale to fit at least one side of the activity to its parent. If the activity uses
+ * 1920x1080, and the actually size on the screen is 960x540, then the scale is 0.5.
+ */
+ private float mSizeCompatScale = 1f;
+ /**
+ * The bounds in global coordinates for activity in size compatibility mode.
+ * @see ActivityRecord#inSizeCompatMode
+ */
+ private Rect mSizeCompatBounds;
+
private boolean mDisablePreviewScreenshots;
private Task mLastParent;
@@ -884,6 +895,10 @@
dc.setFocusedApp(null);
mWmService.updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL, true /*updateInputWindows*/);
}
+ if (mLetterbox != null) {
+ mLetterbox.destroy();
+ mLetterbox = null;
+ }
if (!delayed) {
updateReportedVisibilityLocked();
@@ -1297,6 +1312,10 @@
}
}
}
+
+ if (prevDc != mDisplayContent && mLetterbox != null) {
+ mLetterbox.onMovedToDisplay(mDisplayContent.getDisplayId());
+ }
}
/**
@@ -1555,11 +1574,52 @@
return mOrientation;
}
+ /** @return {@code true} if the compatibility bounds is taking effect. */
+ boolean inSizeCompatMode() {
+ return mSizeCompatBounds != null;
+ }
+
+ @Override
+ float getSizeCompatScale() {
+ return inSizeCompatMode() ? mSizeCompatScale : super.getSizeCompatScale();
+ }
+
+ /**
+ * @return Non-empty bounds if the activity has override bounds.
+ * @see ActivityRecord#resolveOverrideConfiguration(Configuration)
+ */
+ Rect getResolvedOverrideBounds() {
+ // Get bounds from resolved override configuration because it is computed with orientation.
+ return getResolvedOverrideConfiguration().windowConfiguration.getBounds();
+ }
+
@Override
public void onConfigurationChanged(Configuration newParentConfig) {
final int prevWinMode = getWindowingMode();
mTmpPrevBounds.set(getBounds());
super.onConfigurationChanged(newParentConfig);
+
+ final Task task = getTask();
+ final Rect overrideBounds = getResolvedOverrideBounds();
+ if (task != null && !overrideBounds.isEmpty()
+ // If the changes come from change-listener, the incoming parent configuration is
+ // still the old one. Make sure their orientations are the same to reduce computing
+ // the compatibility bounds for the intermediate state.
+ && getResolvedOverrideConfiguration().orientation == newParentConfig.orientation) {
+ final Rect taskBounds = task.getBounds();
+ // Since we only center the activity horizontally, if only the fixed height is smaller
+ // than its container, the override bounds don't need to take effect.
+ if ((overrideBounds.width() != taskBounds.width()
+ || overrideBounds.height() > taskBounds.height())) {
+ calculateCompatBoundsTransformation(newParentConfig);
+ updateSurfacePosition();
+ } else if (mSizeCompatBounds != null) {
+ mSizeCompatBounds = null;
+ mSizeCompatScale = 1f;
+ updateSurfacePosition();
+ }
+ }
+
final int winMode = getWindowingMode();
if (prevWinMode == winMode) {
@@ -1657,8 +1717,10 @@
final ActivityManager.TaskSnapshot snapshot = snapshotCtrl.getSnapshot(
getTask().mTaskId, getTask().mUserId, false /* restoreFromDisk */,
false /* reducedResolution */);
- mThumbnail = new AppWindowThumbnail(t, this, snapshot.getSnapshot(),
- true /* relative */);
+ if (snapshot != null) {
+ mThumbnail = new AppWindowThumbnail(t, this, snapshot.getSnapshot(),
+ true /* relative */);
+ }
}
}
@@ -1671,6 +1733,54 @@
return mThumbnail;
}
+ /**
+ * Calculates the scale and offset to horizontal center the size compatibility bounds into the
+ * region which is available to application.
+ */
+ private void calculateCompatBoundsTransformation(Configuration newParentConfig) {
+ final Rect parentAppBounds = newParentConfig.windowConfiguration.getAppBounds();
+ final Rect viewportBounds = parentAppBounds != null
+ ? parentAppBounds : newParentConfig.windowConfiguration.getBounds();
+ final Rect contentBounds = getResolvedOverrideBounds();
+ final float contentW = contentBounds.width();
+ final float contentH = contentBounds.height();
+ final float viewportW = viewportBounds.width();
+ final float viewportH = viewportBounds.height();
+ // Only allow to scale down.
+ mSizeCompatScale = (contentW <= viewportW && contentH <= viewportH)
+ ? 1 : Math.min(viewportW / contentW, viewportH / contentH);
+ final int offsetX = (int) ((viewportW - contentW * mSizeCompatScale + 1) * 0.5f)
+ + viewportBounds.left;
+
+ if (mSizeCompatBounds == null) {
+ mSizeCompatBounds = new Rect();
+ }
+ mSizeCompatBounds.set(contentBounds);
+ mSizeCompatBounds.offsetTo(0, 0);
+ mSizeCompatBounds.scale(mSizeCompatScale);
+ mSizeCompatBounds.left += offsetX;
+ mSizeCompatBounds.right += offsetX;
+ }
+
+ @Override
+ public Rect getBounds() {
+ if (mSizeCompatBounds != null) {
+ return mSizeCompatBounds;
+ }
+ return super.getBounds();
+ }
+
+ @Override
+ public boolean matchParentBounds() {
+ if (super.matchParentBounds()) {
+ return true;
+ }
+ // An activity in size compatibility mode may have override bounds which equals to its
+ // parent bounds, so the exact bounds should also be checked.
+ final WindowContainer parent = getParent();
+ return parent == null || parent.getBounds().equals(getResolvedOverrideBounds());
+ }
+
@Override
void checkAppWindowsReadyToShow() {
if (allDrawn == mLastAllDrawn) {
@@ -1844,6 +1954,7 @@
if (needsLetterbox) {
if (mLetterbox == null) {
mLetterbox = new Letterbox(() -> makeChildSurface(null));
+ mLetterbox.attachInput(w);
}
getPosition(mTmpPoint);
mLetterbox.layout(getParent().getBounds(), w.getFrameLw(), mTmpPoint);
@@ -2864,6 +2975,10 @@
if (mPendingRelaunchCount != 0) {
pw.print(prefix); pw.print("mPendingRelaunchCount="); pw.println(mPendingRelaunchCount);
}
+ if (mSizeCompatScale != 1f || mSizeCompatBounds != null) {
+ pw.println(prefix + "mSizeCompatScale=" + mSizeCompatScale + " mSizeCompatBounds="
+ + mSizeCompatBounds);
+ }
if (mRemovingFromDisplay) {
pw.println(prefix + "mRemovingFromDisplay=" + mRemovingFromDisplay);
}
diff --git a/services/core/java/com/android/server/wm/InputManagerCallback.java b/services/core/java/com/android/server/wm/InputManagerCallback.java
index f9c9d33..f46835e 100644
--- a/services/core/java/com/android/server/wm/InputManagerCallback.java
+++ b/services/core/java/com/android/server/wm/InputManagerCallback.java
@@ -163,15 +163,12 @@
return mService.mPolicy.interceptKeyBeforeQueueing(event, policyFlags);
}
- /**
- * Provides an opportunity for the window manager policy to intercept early motion event
- * processing when the device is in a non-interactive state since these events are normally
- * dropped.
- */
+ /** {@inheritDoc} */
@Override
- public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
+ public int interceptMotionBeforeQueueingNonInteractive(int displayId, long whenNanos,
+ int policyFlags) {
return mService.mPolicy.interceptMotionBeforeQueueingNonInteractive(
- whenNanos, policyFlags);
+ displayId, whenNanos, policyFlags);
}
/**
diff --git a/services/core/java/com/android/server/wm/Letterbox.java b/services/core/java/com/android/server/wm/Letterbox.java
index 9874920..d67193e 100644
--- a/services/core/java/com/android/server/wm/Letterbox.java
+++ b/services/core/java/com/android/server/wm/Letterbox.java
@@ -20,7 +20,15 @@
import android.graphics.Point;
import android.graphics.Rect;
+import android.os.Binder;
+import android.os.Process;
+import android.view.InputChannel;
+import android.view.InputEventReceiver;
+import android.view.InputWindowHandle;
import android.view.SurfaceControl;
+import android.view.WindowManager;
+
+import com.android.server.UiThread;
import java.util.function.Supplier;
@@ -40,6 +48,7 @@
private final LetterboxSurface mLeft = new LetterboxSurface("left");
private final LetterboxSurface mBottom = new LetterboxSurface("bottom");
private final LetterboxSurface mRight = new LetterboxSurface("right");
+ private final LetterboxSurface[] mSurfaces = { mLeft, mTop, mRight, mBottom };
/**
* Constructs a Letterbox.
@@ -87,8 +96,12 @@
* Returns true if any part of the letterbox overlaps with the given {@code rect}.
*/
public boolean isOverlappingWith(Rect rect) {
- return mTop.isOverlappingWith(rect) || mLeft.isOverlappingWith(rect)
- || mBottom.isOverlappingWith(rect) || mRight.isOverlappingWith(rect);
+ for (LetterboxSurface surface : mSurfaces) {
+ if (surface.isOverlappingWith(rect)) {
+ return true;
+ }
+ }
+ return false;
}
/**
@@ -107,25 +120,94 @@
mOuter.setEmpty();
mInner.setEmpty();
- mTop.remove();
- mLeft.remove();
- mBottom.remove();
- mRight.remove();
+ for (LetterboxSurface surface : mSurfaces) {
+ surface.remove();
+ }
}
/** Returns whether a call to {@link #applySurfaceChanges} would change the surface. */
public boolean needsApplySurfaceChanges() {
- return mTop.needsApplySurfaceChanges()
- || mLeft.needsApplySurfaceChanges()
- || mBottom.needsApplySurfaceChanges()
- || mRight.needsApplySurfaceChanges();
+ for (LetterboxSurface surface : mSurfaces) {
+ if (surface.needsApplySurfaceChanges()) {
+ return true;
+ }
+ }
+ return false;
}
public void applySurfaceChanges(SurfaceControl.Transaction t) {
- mTop.applySurfaceChanges(t);
- mLeft.applySurfaceChanges(t);
- mBottom.applySurfaceChanges(t);
- mRight.applySurfaceChanges(t);
+ for (LetterboxSurface surface : mSurfaces) {
+ surface.applySurfaceChanges(t);
+ }
+ }
+
+ /** Enables touches to slide into other neighboring surfaces. */
+ void attachInput(WindowState win) {
+ for (LetterboxSurface surface : mSurfaces) {
+ surface.attachInput(win);
+ }
+ }
+
+ void onMovedToDisplay(int displayId) {
+ for (LetterboxSurface surface : mSurfaces) {
+ if (surface.mInputInterceptor != null) {
+ surface.mInputInterceptor.mWindowHandle.displayId = displayId;
+ }
+ }
+ }
+
+ private static class InputInterceptor {
+ final InputChannel mServerChannel;
+ final InputChannel mClientChannel;
+ final InputWindowHandle mWindowHandle;
+ final InputEventReceiver mInputEventReceiver;
+ final WindowManagerService mWmService;
+
+ InputInterceptor(String namePrefix, WindowState win) {
+ mWmService = win.mWmService;
+ final String name = namePrefix + (win.mAppToken != null ? win.mAppToken : win);
+ final InputChannel[] channels = InputChannel.openInputChannelPair(name);
+ mServerChannel = channels[0];
+ mClientChannel = channels[1];
+ mInputEventReceiver = new SimpleInputReceiver(mClientChannel);
+
+ final Binder token = new Binder();
+ mWmService.mInputManager.registerInputChannel(mServerChannel, token);
+
+ mWindowHandle = new InputWindowHandle(null /* inputApplicationHandle */,
+ null /* clientWindow */, win.getDisplayId());
+ mWindowHandle.name = name;
+ mWindowHandle.token = token;
+ mWindowHandle.layoutParamsFlags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
+ | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
+ | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH
+ | WindowManager.LayoutParams.FLAG_SLIPPERY;
+ mWindowHandle.layoutParamsType = WindowManager.LayoutParams.TYPE_INPUT_CONSUMER;
+ mWindowHandle.dispatchingTimeoutNanos =
+ WindowManagerService.DEFAULT_INPUT_DISPATCHING_TIMEOUT_NANOS;
+ mWindowHandle.visible = true;
+ mWindowHandle.ownerPid = Process.myPid();
+ mWindowHandle.ownerUid = Process.myUid();
+ mWindowHandle.scaleFactor = 1.0f;
+ }
+
+ void updateTouchableRegion(Rect frame) {
+ mWindowHandle.touchableRegion.set(frame);
+ mWindowHandle.touchableRegion.translate(-frame.left, -frame.top);
+ }
+
+ void dispose() {
+ mWmService.mInputManager.unregisterInputChannel(mServerChannel);
+ mInputEventReceiver.dispose();
+ mServerChannel.dispose();
+ mClientChannel.dispose();
+ }
+
+ private static class SimpleInputReceiver extends InputEventReceiver {
+ SimpleInputReceiver(InputChannel inputChannel) {
+ super(inputChannel, UiThread.getHandler().getLooper());
+ }
+ }
}
private class LetterboxSurface {
@@ -137,6 +219,8 @@
private final Rect mLayoutFrameGlobal = new Rect();
private final Rect mLayoutFrameRelative = new Rect();
+ private InputInterceptor mInputInterceptor;
+
public LetterboxSurface(String type) {
mType = type;
}
@@ -154,11 +238,22 @@
mSurface.setColor(new float[]{0, 0, 0});
}
+ void attachInput(WindowState win) {
+ if (mInputInterceptor != null) {
+ mInputInterceptor.dispose();
+ }
+ mInputInterceptor = new InputInterceptor("Letterbox_" + mType + "_", win);
+ }
+
public void remove() {
if (mSurface != null) {
mSurface.remove();
mSurface = null;
}
+ if (mInputInterceptor != null) {
+ mInputInterceptor.dispose();
+ mInputInterceptor = null;
+ }
}
public int getWidth() {
@@ -193,6 +288,10 @@
t.setPosition(mSurface, mSurfaceFrameRelative.left, mSurfaceFrameRelative.top);
t.setWindowCrop(mSurface, mSurfaceFrameRelative.width(),
mSurfaceFrameRelative.height());
+ if (mInputInterceptor != null) {
+ mInputInterceptor.updateTouchableRegion(mSurfaceFrameRelative);
+ t.setInputWindowInfo(mSurface, mInputInterceptor.mWindowHandle);
+ }
t.show(mSurface);
} else if (mSurface != null) {
t.hide(mSurface);
diff --git a/services/core/java/com/android/server/wm/RootActivityContainer.java b/services/core/java/com/android/server/wm/RootActivityContainer.java
index fb5b1d8..5c91d9e 100644
--- a/services/core/java/com/android/server/wm/RootActivityContainer.java
+++ b/services/core/java/com/android/server/wm/RootActivityContainer.java
@@ -300,7 +300,7 @@
* corresponding record in display manager.
*/
// TODO: Look into consolidating with getActivityDisplay()
- ActivityDisplay getActivityDisplayOrCreate(int displayId) {
+ @Nullable ActivityDisplay getActivityDisplayOrCreate(int displayId) {
ActivityDisplay activityDisplay = getActivityDisplay(displayId);
if (activityDisplay != null) {
return activityDisplay;
@@ -1317,6 +1317,9 @@
if (DEBUG_STACK) Slog.v(TAG, "Display added displayId=" + displayId);
synchronized (mService.mGlobalLock) {
final ActivityDisplay display = getActivityDisplayOrCreate(displayId);
+ if (display == null) {
+ return;
+ }
// Do not start home before booting, or it may accidentally finish booting before it
// starts. Instead, we expect home activities to be launched when the system is ready
// (ActivityManagerService#systemReady).
diff --git a/services/core/java/com/android/server/wm/SurfaceAnimator.java b/services/core/java/com/android/server/wm/SurfaceAnimator.java
index 5ea2451..35b8641 100644
--- a/services/core/java/com/android/server/wm/SurfaceAnimator.java
+++ b/services/core/java/com/android/server/wm/SurfaceAnimator.java
@@ -251,7 +251,7 @@
if (DEBUG_ANIM) Slog.i(TAG, "Cancelling animation restarting=" + restarting);
final SurfaceControl leash = mLeash;
final AnimationAdapter animation = mAnimation;
- reset(t, forwardCancel);
+ reset(t, false);
if (animation != null) {
if (!mAnimationStartDelayed && forwardCancel) {
animation.onAnimationCancelled(leash);
@@ -260,6 +260,12 @@
mAnimationFinishedCallback.run();
}
}
+
+ if (forwardCancel && leash != null) {
+ t.remove(leash);
+ mService.scheduleAnimationLocked();
+ }
+
if (!restarting) {
mAnimationStartDelayed = false;
}
diff --git a/services/core/java/com/android/server/wm/TaskRecord.java b/services/core/java/com/android/server/wm/TaskRecord.java
index 69f0012..59d7560 100644
--- a/services/core/java/com/android/server/wm/TaskRecord.java
+++ b/services/core/java/com/android/server/wm/TaskRecord.java
@@ -119,6 +119,7 @@
import android.util.EventLog;
import android.util.Slog;
import android.util.proto.ProtoOutputStream;
+import android.view.Display;
import android.view.DisplayInfo;
import com.android.internal.annotations.VisibleForTesting;
@@ -1288,22 +1289,7 @@
|| top == null) {
return getRequestedOverrideConfiguration().orientation;
}
- int screenOrientation = top.getOrientation();
- if (screenOrientation == ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
- // NOSENSOR means the display's "natural" orientation, so return that.
- ActivityDisplay display = mStack != null ? mStack.getDisplay() : null;
- if (display != null && display.mDisplayContent != null) {
- return mStack.getDisplay().mDisplayContent.getNaturalOrientation();
- }
- } else if (screenOrientation == ActivityInfo.SCREEN_ORIENTATION_LOCKED) {
- // LOCKED means the activity's orientation remains unchanged, so return existing value.
- return top.getConfiguration().orientation;
- } else if (ActivityInfo.isFixedOrientationLandscape(screenOrientation)) {
- return ORIENTATION_LANDSCAPE;
- } else if (ActivityInfo.isFixedOrientationPortrait(screenOrientation)) {
- return ORIENTATION_PORTRAIT;
- }
- return ORIENTATION_UNDEFINED;
+ return top.getRequestedConfigurationOrientation();
}
/**
@@ -2084,6 +2070,11 @@
return Configuration.SMALLEST_SCREEN_WIDTH_DP_UNDEFINED;
}
+ void computeConfigResourceOverrides(@NonNull Configuration inOutConfig,
+ @NonNull Configuration parentConfig) {
+ computeConfigResourceOverrides(inOutConfig, parentConfig, true /* insideParentBounds */);
+ }
+
/**
* Calculates configuration values used by the client to get resources. This should be run
* using app-facing bounds (bounds unmodified by animations or transient interactions).
@@ -2093,7 +2084,7 @@
* just be inherited from the parent configuration.
**/
void computeConfigResourceOverrides(@NonNull Configuration inOutConfig,
- @NonNull Configuration parentConfig) {
+ @NonNull Configuration parentConfig, boolean insideParentBounds) {
int windowingMode = inOutConfig.windowConfiguration.getWindowingMode();
if (windowingMode == WINDOWING_MODE_UNDEFINED) {
windowingMode = parentConfig.windowConfiguration.getWindowingMode();
@@ -2111,7 +2102,7 @@
inOutConfig.windowConfiguration.setAppBounds(bounds);
outAppBounds = inOutConfig.windowConfiguration.getAppBounds();
}
- if (windowingMode != WINDOWING_MODE_FREEFORM) {
+ if (insideParentBounds && windowingMode != WINDOWING_MODE_FREEFORM) {
final Rect parentAppBounds = parentConfig.windowConfiguration.getAppBounds();
if (parentAppBounds != null && !parentAppBounds.isEmpty()) {
outAppBounds.intersect(parentAppBounds);
@@ -2120,7 +2111,7 @@
if (inOutConfig.screenWidthDp == Configuration.SCREEN_WIDTH_DP_UNDEFINED
|| inOutConfig.screenHeightDp == Configuration.SCREEN_HEIGHT_DP_UNDEFINED) {
- if (mStack != null) {
+ if (insideParentBounds && mStack != null) {
final DisplayInfo di = new DisplayInfo();
mStack.getDisplay().mDisplay.getDisplayInfo(di);
@@ -2135,12 +2126,16 @@
}
if (inOutConfig.screenWidthDp == Configuration.SCREEN_WIDTH_DP_UNDEFINED) {
- inOutConfig.screenWidthDp = Math.min((int) (mTmpStableBounds.width() / density),
- parentConfig.screenWidthDp);
+ final int overrideScreenWidthDp = (int) (mTmpStableBounds.width() / density);
+ inOutConfig.screenWidthDp = insideParentBounds
+ ? Math.min(overrideScreenWidthDp, parentConfig.screenWidthDp)
+ : overrideScreenWidthDp;
}
if (inOutConfig.screenHeightDp == Configuration.SCREEN_HEIGHT_DP_UNDEFINED) {
- inOutConfig.screenHeightDp = Math.min((int) (mTmpStableBounds.height() / density),
- parentConfig.screenHeightDp);
+ final int overrideScreenHeightDp = (int) (mTmpStableBounds.height() / density);
+ inOutConfig.screenHeightDp = insideParentBounds
+ ? Math.min(overrideScreenHeightDp, parentConfig.screenWidthDp)
+ : overrideScreenHeightDp;
}
if (inOutConfig.smallestScreenWidthDp
@@ -2162,7 +2157,7 @@
if (inOutConfig.orientation == ORIENTATION_UNDEFINED) {
inOutConfig.orientation = (inOutConfig.screenWidthDp <= inOutConfig.screenHeightDp)
- ? Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
+ ? ORIENTATION_PORTRAIT : ORIENTATION_LANDSCAPE;
}
if (inOutConfig.screenLayout == Configuration.SCREENLAYOUT_UNDEFINED) {
// For calculating screen layout, we need to use the non-decor inset screen area for the
@@ -2332,6 +2327,7 @@
info.userId = userId;
info.stackId = getStackId();
info.taskId = taskId;
+ info.displayId = mStack == null ? Display.INVALID_DISPLAY : mStack.mDisplayId;
info.isRunning = getTopActivity() != null;
info.baseIntent = new Intent(getBaseIntent());
info.baseActivity = reuseActivitiesReport.base != null
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 6c3e1f4..c747c6d 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -47,7 +47,6 @@
import static android.view.WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL;
import static android.view.WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
import static android.view.WindowManager.LayoutParams.LAST_SUB_WINDOW;
-import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_IS_ROUNDED_CORNERS_OVERLAY;
import static android.view.WindowManager.LayoutParams.SYSTEM_FLAG_HIDE_NON_SYSTEM_OVERLAY_WINDOWS;
import static android.view.WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY;
@@ -188,6 +187,7 @@
import android.util.TimeUtils;
import android.util.TypedValue;
import android.util.proto.ProtoOutputStream;
+import android.view.Choreographer;
import android.view.Display;
import android.view.DisplayCutout;
import android.view.DisplayInfo;
@@ -843,7 +843,7 @@
Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "closeSurfaceTransaction");
synchronized (mGlobalLock) {
SurfaceControl.closeTransaction();
- traceStateLocked(where);
+ mWindowTracing.logState(where);
}
} finally {
Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
@@ -967,7 +967,8 @@
mWindowPlacerLocked = new WindowSurfacePlacer(this);
mTaskSnapshotController = new TaskSnapshotController(this);
- mWindowTracing = WindowTracing.createDefaultAndStartLooper(context);
+ mWindowTracing = WindowTracing.createDefaultAndStartLooper(this,
+ Choreographer.getInstance());
LocalServices.addService(WindowManagerPolicy.class, mPolicy);
@@ -1837,6 +1838,9 @@
return;
}
outDisplayFrame.set(win.getDisplayFrameLw());
+ if (win.inSizeCompatMode()) {
+ outDisplayFrame.scale(win.mInvGlobalScale);
+ }
}
}
@@ -1961,8 +1965,6 @@
if (DEBUG_LAYOUT) Slog.v(TAG_WM, "Relayout " + win + ": viewVisibility=" + viewVisibility
+ " req=" + requestedWidth + "x" + requestedHeight + " " + win.mAttrs);
winAnimator.mSurfaceDestroyDeferred = (flags & RELAYOUT_DEFER_SURFACE_DESTROY) != 0;
- win.mEnforceSizeCompat =
- (win.mAttrs.privateFlags & PRIVATE_FLAG_COMPATIBLE_WINDOW) != 0;
if ((attrChanges & WindowManager.LayoutParams.ALPHA_CHANGED) != 0) {
winAnimator.mAlpha = attrs.alpha;
}
@@ -5765,17 +5767,6 @@
proto.write(LAST_ORIENTATION, defaultDisplayContent.getLastOrientation());
}
- void traceStateLocked(String where) {
- Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "traceStateLocked");
- try {
- mWindowTracing.traceStateLocked(where, this);
- } catch (Exception e) {
- Log.wtf(TAG, "Exception while tracing state", e);
- } finally {
- Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
- }
- }
-
private void dumpWindowsLocked(PrintWriter pw, boolean dumpAll,
ArrayList<WindowState> windows) {
pw.println("WINDOW MANAGER WINDOWS (dumpsys window windows)");
diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java
index 85b251a..3430987 100644
--- a/services/core/java/com/android/server/wm/WindowState.java
+++ b/services/core/java/com/android/server/wm/WindowState.java
@@ -246,7 +246,6 @@
final boolean mIsWallpaper;
private final boolean mIsFloatingLayer;
int mSeq;
- boolean mEnforceSizeCompat;
int mViewVisibility;
int mSystemUiVisibility;
/**
@@ -505,7 +504,8 @@
*/
private PowerManager.WakeLock mDrawLock;
- final private Rect mTmpRect = new Rect();
+ private final Rect mTmpRect = new Rect();
+ private final Point mTmpPoint = new Point();
/**
* Whether the window was resized by us while it was gone for layout.
@@ -655,7 +655,6 @@
mContext = mWmService.mContext;
DeathRecipient deathRecipient = new DeathRecipient();
mSeq = seq;
- mEnforceSizeCompat = (mAttrs.privateFlags & PRIVATE_FLAG_COMPATIBLE_WINDOW) != 0;
mPowerManagerWrapper = powerManagerWrapper;
mForceSeamlesslyRotate = token.mRoundedCornerOverlay;
if (localLOGV) Slog.v(
@@ -733,6 +732,18 @@
}
/**
+ * @return {@code true} if the application runs in size compatibility mode.
+ * @see android.content.res.CompatibilityInfo#supportsScreen
+ * @see ActivityRecord#inSizeCompatMode
+ */
+ boolean inSizeCompatMode() {
+ return (mAttrs.privateFlags & PRIVATE_FLAG_COMPATIBLE_WINDOW) != 0
+ || (mAppToken != null && mAppToken.inSizeCompatMode()
+ // Exclude starting window because it is not displayed by the application.
+ && mAttrs.type != TYPE_APPLICATION_STARTING);
+ }
+
+ /**
* Returns whether this {@link WindowState} has been considered for drawing by its parent.
*/
boolean getDrawnStateEvaluated() {
@@ -995,7 +1006,7 @@
mWindowFrames.offsetFrames(-layoutXDiff, -layoutYDiff);
mWindowFrames.mCompatFrame.set(mWindowFrames.mFrame);
- if (mEnforceSizeCompat) {
+ if (inSizeCompatMode()) {
// If there is a size compatibility scale being applied to the
// window, we need to apply this to its insets so that they are
// reported to the app in its coordinate space.
@@ -1354,8 +1365,8 @@
}
void prelayout() {
- if (mEnforceSizeCompat) {
- mGlobalScale = getDisplayContent().mCompatibleScreenScale;
+ if (inSizeCompatMode()) {
+ mGlobalScale = mToken.getSizeCompatScale();
mInvGlobalScale = 1 / mGlobalScale;
} else {
mGlobalScale = mInvGlobalScale = 1;
@@ -2145,6 +2156,30 @@
int getSurfaceTouchableRegion(Region region, int flags) {
final boolean modal = (flags & (FLAG_NOT_TOUCH_MODAL | FLAG_NOT_FOCUSABLE)) == 0;
+ if (mAppToken != null && !mAppToken.getResolvedOverrideBounds().isEmpty()) {
+ // There may have touchable letterboxes around the activity, so in order to let the
+ // letterboxes are able to receive touch event and slip to activity, the activity with
+ // compatibility bounds cannot occupy full screen touchable region.
+ if (modal) {
+ // A modal window uses the whole compatibility bounds.
+ flags |= FLAG_NOT_TOUCH_MODAL;
+ mTmpRect.set(mAppToken.getResolvedOverrideBounds());
+ // TODO(b/112288258): Remove the forced offset when the override bounds always
+ // starts from zero (See {@link ActivityRecord#resolveOverrideConfiguration}).
+ mTmpRect.offsetTo(0, 0);
+ } else {
+ // Non-modal uses the application based frame.
+ mTmpRect.set(mWindowFrames.mCompatFrame);
+ }
+ // The offset of compatibility bounds is applied to surface of {@link #AppWindowToken}
+ // and frame, so it is unnecessary to translate twice in surface based coordinates.
+ final int surfaceOffsetX = mAppToken.inSizeCompatMode()
+ ? mAppToken.getBounds().left : 0;
+ mTmpRect.offset(surfaceOffsetX - mWindowFrames.mFrame.left, -mWindowFrames.mFrame.top);
+ region.set(mTmpRect);
+ return flags;
+ }
+
if (modal && mAppToken != null) {
// Limit the outer touch to the activity stack region.
flags |= FLAG_NOT_TOUCH_MODAL;
@@ -2431,7 +2466,7 @@
/** @return false if this window desires touch events. */
boolean cantReceiveTouchInput() {
return mAppToken != null && mAppToken.getTask() != null
- && mAppToken.getTask().mStack.shouldIgnoreInput();
+ && (mAppToken.getTask().mStack.shouldIgnoreInput() || mAppToken.hiddenRequested);
}
@Override
@@ -2943,7 +2978,7 @@
if (DEBUG_ORIENTATION && mWinAnimator.mDrawState == DRAW_PENDING)
Slog.i(TAG, "Resizing " + this + " WITH DRAW PENDING");
- final Rect frame = mWindowFrames.mFrame;
+ final Rect frame = mWindowFrames.mCompatFrame;
final Rect overscanInsets = mWindowFrames.mLastOverscanInsets;
final Rect contentInsets = mWindowFrames.mLastContentInsets;
final Rect visibleInsets = mWindowFrames.mLastVisibleInsets;
@@ -3353,7 +3388,7 @@
pw.println(prefix + "mHasSurface=" + mHasSurface
+ " isReadyForDisplay()=" + isReadyForDisplay()
+ " mWindowRemovalAllowed=" + mWindowRemovalAllowed);
- if (mEnforceSizeCompat) {
+ if (inSizeCompatMode()) {
pw.println(prefix + "mCompatFrame=" + mWindowFrames.mCompatFrame.toShortString(sTmpSB));
}
if (dumpAll) {
@@ -3477,17 +3512,18 @@
float x, y;
int w,h;
+ final boolean inSizeCompatMode = inSizeCompatMode();
if ((mAttrs.flags & FLAG_SCALED) != 0) {
if (mAttrs.width < 0) {
w = pw;
- } else if (mEnforceSizeCompat) {
+ } else if (inSizeCompatMode) {
w = (int)(mAttrs.width * mGlobalScale + .5f);
} else {
w = mAttrs.width;
}
if (mAttrs.height < 0) {
h = ph;
- } else if (mEnforceSizeCompat) {
+ } else if (inSizeCompatMode) {
h = (int)(mAttrs.height * mGlobalScale + .5f);
} else {
h = mAttrs.height;
@@ -3495,21 +3531,21 @@
} else {
if (mAttrs.width == MATCH_PARENT) {
w = pw;
- } else if (mEnforceSizeCompat) {
+ } else if (inSizeCompatMode) {
w = (int)(mRequestedWidth * mGlobalScale + .5f);
} else {
w = mRequestedWidth;
}
if (mAttrs.height == MATCH_PARENT) {
h = ph;
- } else if (mEnforceSizeCompat) {
+ } else if (inSizeCompatMode) {
h = (int)(mRequestedHeight * mGlobalScale + .5f);
} else {
h = mRequestedHeight;
}
}
- if (mEnforceSizeCompat) {
+ if (inSizeCompatMode) {
x = mAttrs.x * mGlobalScale;
y = mAttrs.y * mGlobalScale;
} else {
@@ -3537,7 +3573,7 @@
// We need to make sure we update the CompatFrame as it is used for
// cropping decisions, etc, on systems where we lack a decor layer.
mWindowFrames.mCompatFrame.set(mWindowFrames.mFrame);
- if (mEnforceSizeCompat) {
+ if (inSizeCompatMode) {
// See comparable block in computeFrameLw.
mWindowFrames.mCompatFrame.scale(mInvGlobalScale);
}
@@ -3650,7 +3686,7 @@
float translateToWindowX(float x) {
float winX = x - mWindowFrames.mFrame.left;
- if (mEnforceSizeCompat) {
+ if (inSizeCompatMode()) {
winX *= mGlobalScale;
}
return winX;
@@ -3658,7 +3694,7 @@
float translateToWindowY(float y) {
float winY = y - mWindowFrames.mFrame.top;
- if (mEnforceSizeCompat) {
+ if (inSizeCompatMode()) {
winY *= mGlobalScale;
}
return winY;
@@ -4233,12 +4269,11 @@
*/
void calculatePolicyCrop(Rect policyCrop) {
final DisplayContent displayContent = getDisplayContent();
- final DisplayInfo displayInfo = displayContent.getDisplayInfo();
- if (!isDefaultDisplay()) {
+ if (!displayContent.isDefaultDisplay && !displayContent.supportsSystemDecorations()) {
// On a different display there is no system decor. Crop the window
// by the screen boundaries.
- // TODO(multi-display)
+ final DisplayInfo displayInfo = displayContent.getDisplayInfo();
policyCrop.set(0, 0, mWindowFrames.mCompatFrame.width(),
mWindowFrames.mCompatFrame.height());
policyCrop.intersect(-mWindowFrames.mCompatFrame.left, -mWindowFrames.mCompatFrame.top,
@@ -4304,7 +4339,7 @@
// scale function because we want to round things to make the crop
// always round to a larger rect to ensure we don't crop too
// much and hide part of the window that should be seen.
- if (mEnforceSizeCompat && mInvGlobalScale != 1.0f) {
+ if (inSizeCompatMode() && mInvGlobalScale != 1.0f) {
final float scale = mInvGlobalScale;
systemDecorRect.left = (int) (systemDecorRect.left * scale - 0.5f);
systemDecorRect.top = (int) (systemDecorRect.top * scale - 0.5f);
@@ -4664,8 +4699,9 @@
// Since the parent was outset by its surface insets, we need to undo the outsetting
// with insetting by the same amount.
final WindowState parent = getParentWindow();
- outPoint.offset(-parent.mWindowFrames.mFrame.left + parent.mAttrs.surfaceInsets.left,
- -parent.mWindowFrames.mFrame.top + parent.mAttrs.surfaceInsets.top);
+ transformSurfaceInsetsPosition(mTmpPoint, parent.mAttrs.surfaceInsets);
+ outPoint.offset(-parent.mWindowFrames.mFrame.left + mTmpPoint.x,
+ -parent.mWindowFrames.mFrame.top + mTmpPoint.y);
} else if (parentWindowContainer != null) {
final Rect parentBounds = parentWindowContainer.getDisplayedBounds();
outPoint.offset(-parentBounds.left, -parentBounds.top);
@@ -4683,7 +4719,22 @@
}
// Expand for surface insets. See WindowState.expandForSurfaceInsets.
- outPoint.offset(-mAttrs.surfaceInsets.left, -mAttrs.surfaceInsets.top);
+ transformSurfaceInsetsPosition(mTmpPoint, mAttrs.surfaceInsets);
+ outPoint.offset(-mTmpPoint.x, -mTmpPoint.y);
+ }
+
+ /**
+ * The surface insets from layout parameter are in application coordinate. If the window is
+ * scaled, the insets also need to be scaled for surface position in global coordinate.
+ */
+ private void transformSurfaceInsetsPosition(Point outPos, Rect surfaceInsets) {
+ if (!inSizeCompatMode()) {
+ outPos.x = surfaceInsets.left;
+ outPos.y = surfaceInsets.top;
+ return;
+ }
+ outPos.x = (int) (surfaceInsets.left * mGlobalScale + 0.5f);
+ outPos.y = (int) (surfaceInsets.top * mGlobalScale + 0.5f);
}
boolean needsRelativeLayeringToIme() {
diff --git a/services/core/java/com/android/server/wm/WindowToken.java b/services/core/java/com/android/server/wm/WindowToken.java
index 3b9b8ba..f0b9c62 100644
--- a/services/core/java/com/android/server/wm/WindowToken.java
+++ b/services/core/java/com/android/server/wm/WindowToken.java
@@ -182,6 +182,14 @@
}
/**
+ * @return The scale for applications running in compatibility mode. Multiply the size in the
+ * application by this scale will be the size in the screen.
+ */
+ float getSizeCompatScale() {
+ return mDisplayContent.mCompatibleScreenScale;
+ }
+
+ /**
* Returns true if the new window is considered greater than the existing window in terms of
* z-order.
*/
diff --git a/services/core/java/com/android/server/wm/WindowTracing.java b/services/core/java/com/android/server/wm/WindowTracing.java
index 8b1ffa8..abc474d 100644
--- a/services/core/java/com/android/server/wm/WindowTracing.java
+++ b/services/core/java/com/android/server/wm/WindowTracing.java
@@ -24,12 +24,14 @@
import static com.android.server.wm.WindowManagerTraceProto.WINDOW_MANAGER_SERVICE;
import android.annotation.Nullable;
-import android.content.Context;
import android.os.ShellCommand;
import android.os.SystemClock;
import android.os.Trace;
import android.util.Log;
import android.util.proto.ProtoOutputStream;
+import android.view.Choreographer;
+
+import com.android.internal.annotations.VisibleForTesting;
import java.io.File;
import java.io.IOException;
@@ -48,6 +50,10 @@
private static final int WINDOW_TRACE_BUFFER_SIZE = 512 * 1024;
private static final String TAG = "WindowTracing";
+ private final WindowManagerService mService;
+ private final Choreographer mChoreographer;
+ private final WindowManagerGlobalLock mGlobalLock;
+
private final Object mLock = new Object();
private final WindowTraceBuffer.Builder mBufferBuilder;
@@ -57,11 +63,24 @@
private boolean mContinuousMode;
private boolean mEnabled;
private volatile boolean mEnabledLockFree;
+ private boolean mScheduled;
+ private Choreographer.FrameCallback mFrameCallback = (frameTimeNanos) ->
+ log("onFrame" /* where */);
- WindowTracing(File file) {
+ private WindowTracing(File file, WindowManagerService service, Choreographer choreographer) {
+ this(file, service, choreographer, service.mGlobalLock);
+ }
+
+ @VisibleForTesting
+ WindowTracing(File file, WindowManagerService service, Choreographer choreographer,
+ WindowManagerGlobalLock globalLock) {
mBufferBuilder = new WindowTraceBuffer.Builder()
.setTraceFile(file)
.setBufferCapacity(WINDOW_TRACE_BUFFER_SIZE);
+
+ mChoreographer = choreographer;
+ mService = service;
+ mGlobalLock = globalLock;
}
void startTrace(@Nullable PrintWriter pw) throws IOException {
@@ -111,7 +130,8 @@
}
}
- private void setContinuousMode(boolean continuous, PrintWriter pw) {
+ @VisibleForTesting
+ void setContinuousMode(boolean continuous, PrintWriter pw) {
logAndPrintln(pw, "Setting window tracing continuous mode to " + continuous);
if (mEnabled) {
@@ -123,21 +143,14 @@
WindowTraceLogLevel.TRIM;
}
- private void appendTraceEntry(ProtoOutputStream proto) {
- if (!mEnabledLockFree) {
- return;
- }
-
- mTraceBuffer.add(proto);
- }
-
boolean isEnabled() {
return mEnabledLockFree;
}
- static WindowTracing createDefaultAndStartLooper(Context context) {
+ static WindowTracing createDefaultAndStartLooper(WindowManagerService service,
+ Choreographer choreographer) {
File file = new File("/data/misc/wmtrace/wm_trace.pb");
- return new WindowTracing(file);
+ return new WindowTracing(file, service, choreographer);
}
int onShellCommand(ShellCommand shell) {
@@ -164,28 +177,65 @@
}
}
- void traceStateLocked(String where, WindowManagerService service) {
+ /**
+ * If tracing is enabled, log the current state or schedule the next frame to be logged,
+ * according to {@link #mContinuousMode}.
+ *
+ * @param where Logging point descriptor
+ */
+ void logState(String where) {
if (!isEnabled()) {
return;
}
- Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "writeToBufferLocked");
- try {
- ProtoOutputStream os = new ProtoOutputStream();
- long tokenOuter = os.start(ENTRY);
- os.write(ELAPSED_REALTIME_NANOS, SystemClock.elapsedRealtimeNanos());
- os.write(WHERE, where);
+ if (mContinuousMode) {
+ schedule();
+ } else {
+ log(where);
+ }
+ }
- Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "writeToProtoLocked");
- try {
- long tokenInner = os.start(WINDOW_MANAGER_SERVICE);
- service.writeToProtoLocked(os, mWindowTraceLogLevel);
- os.end(tokenInner);
- } finally {
- Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
+ /**
+ * Schedule the log to trace the next frame
+ */
+ private void schedule() {
+ if (mScheduled) {
+ return;
+ }
+
+ mScheduled = true;
+ mChoreographer.postFrameCallback(mFrameCallback);
+ }
+
+ /**
+ * Write the current frame to the buffer
+ *
+ * @param where Logging point descriptor
+ */
+ private void log(String where) {
+ Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "traceStateLocked");
+ try {
+ synchronized (mGlobalLock) {
+ ProtoOutputStream os = new ProtoOutputStream();
+ long tokenOuter = os.start(ENTRY);
+ os.write(ELAPSED_REALTIME_NANOS, SystemClock.elapsedRealtimeNanos());
+ os.write(WHERE, where);
+
+ Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "writeToProtoLocked");
+ try {
+ long tokenInner = os.start(WINDOW_MANAGER_SERVICE);
+ mService.writeToProtoLocked(os, mWindowTraceLogLevel);
+ os.end(tokenInner);
+ } finally {
+ Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
+ }
+ os.end(tokenOuter);
+ mTraceBuffer.add(os);
+
+ mScheduled = false;
}
- os.end(tokenOuter);
- appendTraceEntry(os);
+ } catch (Exception e) {
+ Log.wtf(TAG, "Exception while tracing state", e);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
}
diff --git a/services/core/jni/com_android_server_input_InputManagerService.cpp b/services/core/jni/com_android_server_input_InputManagerService.cpp
index c18e98b..57377c6 100644
--- a/services/core/jni/com_android_server_input_InputManagerService.cpp
+++ b/services/core/jni/com_android_server_input_InputManagerService.cpp
@@ -249,7 +249,8 @@
virtual bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags);
virtual void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig);
virtual void interceptKeyBeforeQueueing(const KeyEvent* keyEvent, uint32_t& policyFlags);
- virtual void interceptMotionBeforeQueueing(nsecs_t when, uint32_t& policyFlags);
+ virtual void interceptMotionBeforeQueueing(const int32_t displayId, nsecs_t when,
+ uint32_t& policyFlags);
virtual nsecs_t interceptKeyBeforeDispatching(
const sp<IBinder>& token,
const KeyEvent* keyEvent, uint32_t policyFlags);
@@ -1066,7 +1067,8 @@
}
}
-void NativeInputManager::interceptMotionBeforeQueueing(nsecs_t when, uint32_t& policyFlags) {
+void NativeInputManager::interceptMotionBeforeQueueing(const int32_t displayId, nsecs_t when,
+ uint32_t& policyFlags) {
ATRACE_CALL();
// Policy:
// - Ignore untrusted events and pass them along.
@@ -1084,7 +1086,7 @@
JNIEnv* env = jniEnv();
jint wmActions = env->CallIntMethod(mServiceObj,
gServiceClassInfo.interceptMotionBeforeQueueingNonInteractive,
- when, policyFlags);
+ displayId, when, policyFlags);
if (checkAndClearExceptionFromCallback(env,
"interceptMotionBeforeQueueingNonInteractive")) {
wmActions = 0;
@@ -1794,7 +1796,7 @@
"interceptKeyBeforeQueueing", "(Landroid/view/KeyEvent;I)I");
GET_METHOD_ID(gServiceClassInfo.interceptMotionBeforeQueueingNonInteractive, clazz,
- "interceptMotionBeforeQueueingNonInteractive", "(JI)I");
+ "interceptMotionBeforeQueueingNonInteractive", "(IJI)I");
GET_METHOD_ID(gServiceClassInfo.interceptKeyBeforeDispatching, clazz,
"interceptKeyBeforeDispatching",
diff --git a/services/core/jni/com_android_server_location_GnssLocationProvider.cpp b/services/core/jni/com_android_server_location_GnssLocationProvider.cpp
index cbc3791..d178c3a 100644
--- a/services/core/jni/com_android_server_location_GnssLocationProvider.cpp
+++ b/services/core/jni/com_android_server_location_GnssLocationProvider.cpp
@@ -973,7 +973,10 @@
JavaObject& object) {
translateSingleGnssMeasurement(&(measurement_V2_0->v1_1), object);
- SET(CodeType, (static_cast<int32_t>(measurement_V2_0->codeType)));
+ SET(CodeType, static_cast<int32_t>(measurement_V2_0->codeType));
+
+ // Overwrite with v2_0.state since v2_0->v1_1->v1_0.state is deprecated.
+ SET(State, static_cast<int32_t>(measurement_V2_0->state));
}
jobject GnssMeasurementCallback::translateGnssClock(
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/AbUpdateInstaller.java b/services/devicepolicy/java/com/android/server/devicepolicy/AbUpdateInstaller.java
index de5dd17..d5cfab9 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/AbUpdateInstaller.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/AbUpdateInstaller.java
@@ -16,7 +16,7 @@
package com.android.server.devicepolicy;
-import android.app.admin.DevicePolicyManager.InstallUpdateCallback;
+import android.app.admin.DevicePolicyManager.InstallSystemUpdateCallback;
import android.app.admin.StartInstallingUpdateCallback;
import android.content.Context;
import android.os.ParcelFileDescriptor;
@@ -62,41 +62,43 @@
private static Map<Integer, Integer> buildErrorCodesMap() {
Map<Integer, Integer> map = new HashMap<>();
- map.put(UpdateEngine.ErrorCodeConstants.ERROR, InstallUpdateCallback.UPDATE_ERROR_UNKNOWN);
+ map.put(
+ UpdateEngine.ErrorCodeConstants.ERROR,
+ InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN);
map.put(
DOWNLOAD_STATE_INITIALIZATION_ERROR,
- InstallUpdateCallback.UPDATE_ERROR_INCORRECT_OS_VERSION);
+ InstallSystemUpdateCallback.UPDATE_ERROR_INCORRECT_OS_VERSION);
map.put(
UpdateEngine.ErrorCodeConstants.PAYLOAD_TIMESTAMP_ERROR,
- InstallUpdateCallback.UPDATE_ERROR_INCORRECT_OS_VERSION);
+ InstallSystemUpdateCallback.UPDATE_ERROR_INCORRECT_OS_VERSION);
// Error constants corresponding to errors related to bad update file.
map.put(
UpdateEngine.ErrorCodeConstants.DOWNLOAD_PAYLOAD_VERIFICATION_ERROR,
- InstallUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID);
+ InstallSystemUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID);
map.put(
UpdateEngine.ErrorCodeConstants.PAYLOAD_SIZE_MISMATCH_ERROR,
- InstallUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID);
+ InstallSystemUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID);
map.put(
UpdateEngine.ErrorCodeConstants.PAYLOAD_MISMATCHED_TYPE_ERROR,
- InstallUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID);
+ InstallSystemUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID);
map.put(
UpdateEngine.ErrorCodeConstants.PAYLOAD_HASH_MISMATCH_ERROR,
- InstallUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID);
+ InstallSystemUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID);
// Error constants corresponding to errors related to devices bad state.
map.put(
UpdateEngine.ErrorCodeConstants.POST_INSTALL_RUNNER_ERROR,
- InstallUpdateCallback.UPDATE_ERROR_UNKNOWN);
+ InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN);
map.put(
UpdateEngine.ErrorCodeConstants.INSTALL_DEVICE_OPEN_ERROR,
- InstallUpdateCallback.UPDATE_ERROR_UNKNOWN);
+ InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN);
map.put(
UpdateEngine.ErrorCodeConstants.DOWNLOAD_TRANSFER_ERROR,
- InstallUpdateCallback.UPDATE_ERROR_UNKNOWN);
+ InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN);
map.put(
UpdateEngine.ErrorCodeConstants.UPDATED_BUT_NOT_ACTIVE,
- InstallUpdateCallback.UPDATE_ERROR_UNKNOWN);
+ InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN);
return map;
}
@@ -153,12 +155,13 @@
} catch (ZipException e) {
Log.w(UpdateInstaller.TAG, e);
notifyCallbackOnError(
- InstallUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID,
+ InstallSystemUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID,
Log.getStackTraceString(e));
} catch (IOException e) {
Log.w(UpdateInstaller.TAG, e);
notifyCallbackOnError(
- InstallUpdateCallback.UPDATE_ERROR_UNKNOWN, Log.getStackTraceString(e));
+ InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN,
+ Log.getStackTraceString(e));
}
}
@@ -185,7 +188,7 @@
if (mSizeForUpdate == -1) {
Log.w(UpdateInstaller.TAG, "Failed to find payload entry in the given package.");
notifyCallbackOnError(
- InstallUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID,
+ InstallSystemUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID,
"Failed to find payload entry in the given package.");
return;
}
@@ -210,7 +213,7 @@
if (entry.getMethod() != ZipEntry.STORED) {
Log.w(UpdateInstaller.TAG, "Invalid compression method.");
notifyCallbackOnError(
- InstallUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID,
+ InstallSystemUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID,
"Invalid compression method.");
return false;
}
@@ -263,7 +266,7 @@
} else {
mUpdateInstaller.notifyCallbackOnError(
errorCodesMap.getOrDefault(
- errorCode, InstallUpdateCallback.UPDATE_ERROR_UNKNOWN),
+ errorCode, InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN),
errorStringsMap.getOrDefault(errorCode, UNKNOWN_ERROR + errorCode));
}
}
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index e30acf7..9523202 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -17,8 +17,8 @@
package com.android.server.devicepolicy;
import static android.Manifest.permission.BIND_DEVICE_ADMIN;
-import static android.Manifest.permission.GET_AND_REQUEST_SCREEN_LOCK_COMPLEXITY;
import static android.Manifest.permission.MANAGE_CA_CERTIFICATES;
+import static android.Manifest.permission.REQUEST_SCREEN_LOCK_COMPLEXITY;
import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
import static android.app.admin.DeviceAdminReceiver.EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE;
import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_USER;
@@ -247,6 +247,7 @@
import com.android.server.pm.UserRestrictionsUtils;
import com.android.server.storage.DeviceStorageMonitorInternal;
import com.android.server.uri.UriGrantsManagerInternal;
+import com.android.server.wm.ActivityTaskManagerInternal;
import com.google.android.collect.Sets;
@@ -1870,7 +1871,7 @@
Owners newOwners() {
return new Owners(getUserManager(), getUserManagerInternal(),
- getPackageManagerInternal());
+ getPackageManagerInternal(), getActivityTaskManagerInternal());
}
UserManager getUserManager() {
@@ -1885,6 +1886,10 @@
return LocalServices.getService(PackageManagerInternal.class);
}
+ ActivityTaskManagerInternal getActivityTaskManagerInternal() {
+ return LocalServices.getService(ActivityTaskManagerInternal.class);
+ }
+
UsageStatsManagerInternal getUsageStatsManagerInternal() {
return LocalServices.getService(UsageStatsManagerInternal.class);
}
@@ -4773,8 +4778,8 @@
final int callingUserId = mInjector.userHandleGetCallingUserId();
enforceUserUnlocked(callingUserId);
mContext.enforceCallingOrSelfPermission(
- GET_AND_REQUEST_SCREEN_LOCK_COMPLEXITY,
- "Must have " + GET_AND_REQUEST_SCREEN_LOCK_COMPLEXITY + " permission.");
+ REQUEST_SCREEN_LOCK_COMPLEXITY,
+ "Must have " + REQUEST_SCREEN_LOCK_COMPLEXITY + " permission.");
synchronized (getLockObject()) {
int targetUserId = getCredentialOwner(callingUserId, /* parent= */ false);
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/NonAbUpdateInstaller.java b/services/devicepolicy/java/com/android/server/devicepolicy/NonAbUpdateInstaller.java
index 5f1e926..582306c 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/NonAbUpdateInstaller.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/NonAbUpdateInstaller.java
@@ -16,7 +16,7 @@
package com.android.server.devicepolicy;
-import android.app.admin.DevicePolicyManager;
+import android.app.admin.DevicePolicyManager.InstallSystemUpdateCallback;
import android.app.admin.StartInstallingUpdateCallback;
import android.content.Context;
import android.os.ParcelFileDescriptor;
@@ -45,7 +45,7 @@
} catch (IOException e) {
Log.w(TAG, "IO error while trying to install non AB update.", e);
notifyCallbackOnError(
- DevicePolicyManager.InstallUpdateCallback.UPDATE_ERROR_UNKNOWN,
+ InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN,
Log.getStackTraceString(e));
}
}
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/Owners.java b/services/devicepolicy/java/com/android/server/devicepolicy/Owners.java
index ee1c1df3..27cd70c 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/Owners.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/Owners.java
@@ -41,6 +41,7 @@
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.FastXmlSerializer;
import com.android.server.LocalServices;
+import com.android.server.wm.ActivityTaskManagerInternal;
import libcore.io.IoUtils;
@@ -104,6 +105,7 @@
private final UserManager mUserManager;
private final UserManagerInternal mUserManagerInternal;
private final PackageManagerInternal mPackageManagerInternal;
+ private final ActivityTaskManagerInternal mActivityTaskManagerInternal;
private boolean mSystemReady;
@@ -129,18 +131,22 @@
public Owners(UserManager userManager,
UserManagerInternal userManagerInternal,
- PackageManagerInternal packageManagerInternal) {
- this(userManager, userManagerInternal, packageManagerInternal, new Injector());
+ PackageManagerInternal packageManagerInternal,
+ ActivityTaskManagerInternal activityTaskManagerInternal) {
+ this(userManager, userManagerInternal, packageManagerInternal,
+ activityTaskManagerInternal, new Injector());
}
@VisibleForTesting
Owners(UserManager userManager,
UserManagerInternal userManagerInternal,
PackageManagerInternal packageManagerInternal,
+ ActivityTaskManagerInternal activityTaskManagerInternal,
Injector injector) {
mUserManager = userManager;
mUserManagerInternal = userManagerInternal;
mPackageManagerInternal = packageManagerInternal;
+ mActivityTaskManagerInternal = activityTaskManagerInternal;
mInjector = injector;
}
@@ -187,6 +193,7 @@
getDeviceOwnerUserId()));
}
pushToPackageManagerLocked();
+ pushToActivityTaskManagerLocked();
pushToAppOpsLocked();
}
}
@@ -201,6 +208,11 @@
po);
}
+ private void pushToActivityTaskManagerLocked() {
+ mActivityTaskManagerInternal.setDeviceOwnerPackageName(mDeviceOwner != null
+ ? mDeviceOwner.packageName : null);
+ }
+
String getDeviceOwnerPackageName() {
synchronized (mLock) {
return mDeviceOwner != null ? mDeviceOwner.packageName : null;
@@ -275,6 +287,7 @@
mUserManagerInternal.setDeviceManaged(true);
pushToPackageManagerLocked();
+ pushToActivityTaskManagerLocked();
pushToAppOpsLocked();
}
}
@@ -286,6 +299,7 @@
mUserManagerInternal.setDeviceManaged(false);
pushToPackageManagerLocked();
+ pushToActivityTaskManagerLocked();
pushToAppOpsLocked();
}
}
@@ -333,6 +347,7 @@
mDeviceOwner.remoteBugreportHash, /* canAccessDeviceIds =*/
mDeviceOwner.canAccessDeviceIds);
pushToPackageManagerLocked();
+ pushToActivityTaskManagerLocked();
pushToAppOpsLocked();
}
}
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/UpdateInstaller.java b/services/devicepolicy/java/com/android/server/devicepolicy/UpdateInstaller.java
index cf68ccf..7148ed4 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/UpdateInstaller.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/UpdateInstaller.java
@@ -18,7 +18,7 @@
import android.annotation.Nullable;
import android.app.admin.DevicePolicyEventLogger;
-import android.app.admin.DevicePolicyManager;
+import android.app.admin.DevicePolicyManager.InstallSystemUpdateCallback;
import android.app.admin.StartInstallingUpdateCallback;
import android.content.Context;
import android.content.Intent;
@@ -66,7 +66,7 @@
mCopiedUpdateFile = null;
if (!isBatteryLevelSufficient()) {
notifyCallbackOnError(
- DevicePolicyManager.InstallUpdateCallback.UPDATE_ERROR_BATTERY_LOW,
+ InstallSystemUpdateCallback.UPDATE_ERROR_BATTERY_LOW,
"The battery level must be above "
+ mConstants.BATTERY_THRESHOLD_NOT_CHARGING + " while not charging or"
+ "above " + mConstants.BATTERY_THRESHOLD_CHARGING + " while charging");
@@ -76,7 +76,7 @@
mCopiedUpdateFile = copyUpdateFileToDataOtaPackageDir();
if (mCopiedUpdateFile == null) {
notifyCallbackOnError(
- DevicePolicyManager.InstallUpdateCallback.UPDATE_ERROR_UNKNOWN,
+ InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN,
"Error while copying file.");
return;
}
@@ -111,7 +111,7 @@
} catch (IOException e) {
Log.w(TAG, "Failed to copy update file to OTA directory", e);
notifyCallbackOnError(
- DevicePolicyManager.InstallUpdateCallback.UPDATE_ERROR_UNKNOWN,
+ InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN,
Log.getStackTraceString(e));
return null;
}
diff --git a/services/robotests/backup/src/com/android/server/backup/encryption/chunk/ChunkListingTest.java b/services/robotests/backup/src/com/android/server/backup/encryption/chunk/ChunkListingMapTest.java
similarity index 76%
rename from services/robotests/backup/src/com/android/server/backup/encryption/chunk/ChunkListingTest.java
rename to services/robotests/backup/src/com/android/server/backup/encryption/chunk/ChunkListingMapTest.java
index 4354db7..24e5573 100644
--- a/services/robotests/backup/src/com/android/server/backup/encryption/chunk/ChunkListingTest.java
+++ b/services/robotests/backup/src/com/android/server/backup/encryption/chunk/ChunkListingMapTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2018 The Android Open Source Project
+ * Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -11,7 +11,7 @@
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
- * limitations under the License
+ * limitations under the License.
*/
package com.android.server.backup.encryption.chunk;
@@ -36,7 +36,7 @@
@RunWith(RobolectricTestRunner.class)
@Presubmit
-public class ChunkListingTest {
+public class ChunkListingMapTest {
private static final String CHUNK_A = "CHUNK_A";
private static final String CHUNK_B = "CHUNK_B";
private static final String CHUNK_C = "CHUNK_C";
@@ -62,13 +62,13 @@
createChunkListingProto(
new ChunkHash[] {mChunkHashA, mChunkHashB, mChunkHashC},
new int[] {CHUNK_A_LENGTH, CHUNK_B_LENGTH, CHUNK_C_LENGTH});
- ChunkListing chunkListing =
- ChunkListing.readFromProto(
+ ChunkListingMap chunkListingMap =
+ ChunkListingMap.readFromProto(
new ProtoInputStream(new ByteArrayInputStream(chunkListingProto)));
- boolean chunkAInList = chunkListing.hasChunk(mChunkHashA);
- boolean chunkBInList = chunkListing.hasChunk(mChunkHashB);
- boolean chunkCInList = chunkListing.hasChunk(mChunkHashC);
+ boolean chunkAInList = chunkListingMap.hasChunk(mChunkHashA);
+ boolean chunkBInList = chunkListingMap.hasChunk(mChunkHashB);
+ boolean chunkCInList = chunkListingMap.hasChunk(mChunkHashC);
assertThat(chunkAInList).isTrue();
assertThat(chunkBInList).isTrue();
@@ -81,13 +81,13 @@
createChunkListingProto(
new ChunkHash[] {mChunkHashA, mChunkHashB},
new int[] {CHUNK_A_LENGTH, CHUNK_B_LENGTH});
- ChunkListing chunkListing =
- ChunkListing.readFromProto(
+ ChunkListingMap chunkListingMap =
+ ChunkListingMap.readFromProto(
new ProtoInputStream(new ByteArrayInputStream(chunkListingProto)));
ChunkHash chunkHashEmpty = getHash("");
- boolean chunkCInList = chunkListing.hasChunk(mChunkHashC);
- boolean emptyChunkInList = chunkListing.hasChunk(chunkHashEmpty);
+ boolean chunkCInList = chunkListingMap.hasChunk(mChunkHashC);
+ boolean emptyChunkInList = chunkListingMap.hasChunk(chunkHashEmpty);
assertThat(chunkCInList).isFalse();
assertThat(emptyChunkInList).isFalse();
@@ -99,13 +99,13 @@
createChunkListingProto(
new ChunkHash[] {mChunkHashA, mChunkHashB, mChunkHashC},
new int[] {CHUNK_A_LENGTH, CHUNK_B_LENGTH, CHUNK_C_LENGTH});
- ChunkListing chunkListing =
- ChunkListing.readFromProto(
+ ChunkListingMap chunkListingMap =
+ ChunkListingMap.readFromProto(
new ProtoInputStream(new ByteArrayInputStream(chunkListingProto)));
- ChunkListing.Entry entryA = chunkListing.getChunkEntry(mChunkHashA);
- ChunkListing.Entry entryB = chunkListing.getChunkEntry(mChunkHashB);
- ChunkListing.Entry entryC = chunkListing.getChunkEntry(mChunkHashC);
+ ChunkListingMap.Entry entryA = chunkListingMap.getChunkEntry(mChunkHashA);
+ ChunkListingMap.Entry entryB = chunkListingMap.getChunkEntry(mChunkHashB);
+ ChunkListingMap.Entry entryC = chunkListingMap.getChunkEntry(mChunkHashC);
assertThat(entryA.getLength()).isEqualTo(CHUNK_A_LENGTH);
assertThat(entryB.getLength()).isEqualTo(CHUNK_B_LENGTH);
@@ -118,13 +118,13 @@
createChunkListingProto(
new ChunkHash[] {mChunkHashA, mChunkHashB, mChunkHashC},
new int[] {CHUNK_A_LENGTH, CHUNK_B_LENGTH, CHUNK_C_LENGTH});
- ChunkListing chunkListing =
- ChunkListing.readFromProto(
+ ChunkListingMap chunkListingMap =
+ ChunkListingMap.readFromProto(
new ProtoInputStream(new ByteArrayInputStream(chunkListingProto)));
- ChunkListing.Entry entryA = chunkListing.getChunkEntry(mChunkHashA);
- ChunkListing.Entry entryB = chunkListing.getChunkEntry(mChunkHashB);
- ChunkListing.Entry entryC = chunkListing.getChunkEntry(mChunkHashC);
+ ChunkListingMap.Entry entryA = chunkListingMap.getChunkEntry(mChunkHashA);
+ ChunkListingMap.Entry entryB = chunkListingMap.getChunkEntry(mChunkHashB);
+ ChunkListingMap.Entry entryC = chunkListingMap.getChunkEntry(mChunkHashC);
assertThat(entryA.getStart()).isEqualTo(0);
assertThat(entryB.getStart()).isEqualTo(CHUNK_A_LENGTH);
@@ -137,22 +137,24 @@
createChunkListingProto(
new ChunkHash[] {mChunkHashA, mChunkHashB},
new int[] {CHUNK_A_LENGTH, CHUNK_B_LENGTH});
- ChunkListing chunkListing =
- ChunkListing.readFromProto(
+ ChunkListingMap chunkListingMap =
+ ChunkListingMap.readFromProto(
new ProtoInputStream(new ByteArrayInputStream(chunkListingProto)));
- ChunkListing.Entry chunkEntryNonexistentChunk = chunkListing.getChunkEntry(mChunkHashC);
+ ChunkListingMap.Entry chunkEntryNonexistentChunk =
+ chunkListingMap.getChunkEntry(mChunkHashC);
assertThat(chunkEntryNonexistentChunk).isNull();
}
@Test
- public void testReadFromProto_whenEmptyProto_returnsChunkListingWith0Chunks() throws Exception {
+ public void testReadFromProto_whenEmptyProto_returnsChunkListingMapWith0Chunks()
+ throws Exception {
ProtoInputStream emptyProto = new ProtoInputStream(new ByteArrayInputStream(new byte[] {}));
- ChunkListing chunkListing = ChunkListing.readFromProto(emptyProto);
+ ChunkListingMap chunkListingMap = ChunkListingMap.readFromProto(emptyProto);
- assertThat(chunkListing.getChunkCount()).isEqualTo(0);
+ assertThat(chunkListingMap.getChunkCount()).isEqualTo(0);
}
@Test
@@ -162,11 +164,11 @@
new ChunkHash[] {mChunkHashA, mChunkHashB, mChunkHashC},
new int[] {CHUNK_A_LENGTH, CHUNK_B_LENGTH, CHUNK_C_LENGTH});
- ChunkListing chunkListing =
- ChunkListing.readFromProto(
+ ChunkListingMap chunkListingMap =
+ ChunkListingMap.readFromProto(
new ProtoInputStream(new ByteArrayInputStream(chunkListingProto)));
- assertThat(chunkListing.getChunkCount()).isEqualTo(3);
+ assertThat(chunkListingMap.getChunkCount()).isEqualTo(3);
}
private byte[] createChunkListingProto(ChunkHash[] hashes, int[] lengths) {
diff --git a/services/robotests/src/com/android/server/backup/encryption/chunking/ByteRangeTest.java b/services/robotests/backup/src/com/android/server/backup/encryption/chunking/ByteRangeTest.java
similarity index 100%
rename from services/robotests/src/com/android/server/backup/encryption/chunking/ByteRangeTest.java
rename to services/robotests/backup/src/com/android/server/backup/encryption/chunking/ByteRangeTest.java
diff --git a/services/robotests/src/com/android/server/backup/encryption/chunking/DiffScriptBackupWriterTest.java b/services/robotests/backup/src/com/android/server/backup/encryption/chunking/DiffScriptBackupWriterTest.java
similarity index 100%
rename from services/robotests/src/com/android/server/backup/encryption/chunking/DiffScriptBackupWriterTest.java
rename to services/robotests/backup/src/com/android/server/backup/encryption/chunking/DiffScriptBackupWriterTest.java
diff --git a/services/robotests/src/com/android/server/backup/encryption/chunking/SingleStreamDiffScriptWriterTest.java b/services/robotests/backup/src/com/android/server/backup/encryption/chunking/SingleStreamDiffScriptWriterTest.java
similarity index 100%
rename from services/robotests/src/com/android/server/backup/encryption/chunking/SingleStreamDiffScriptWriterTest.java
rename to services/robotests/backup/src/com/android/server/backup/encryption/chunking/SingleStreamDiffScriptWriterTest.java
diff --git a/services/tests/mockingservicestests/src/com/android/server/DeviceIdleControllerTest.java b/services/tests/mockingservicestests/src/com/android/server/DeviceIdleControllerTest.java
index 53d72bb..e51ee94 100644
--- a/services/tests/mockingservicestests/src/com/android/server/DeviceIdleControllerTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/DeviceIdleControllerTest.java
@@ -19,6 +19,7 @@
import static com.android.dx.mockito.inline.extended.ExtendedMockito.doNothing;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.inOrder;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
@@ -51,6 +52,9 @@
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
import android.app.ActivityManagerInternal;
import android.app.AlarmManager;
@@ -82,6 +86,7 @@
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
+import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.MockitoSession;
import org.mockito.quality.Strictness;
@@ -105,6 +110,8 @@
@Mock
private ContentResolver mContentResolver;
@Mock
+ private DeviceIdleController.MyHandler mHandler;
+ @Mock
private IActivityManager mIActivityManager;
@Mock
private LocationManager mLocationManager;
@@ -154,7 +161,7 @@
@Override
DeviceIdleController.MyHandler getHandler(DeviceIdleController controller) {
- return mock(DeviceIdleController.MyHandler.class, Answers.RETURNS_DEEP_STUBS);
+ return mHandler;
}
@Override
@@ -232,10 +239,12 @@
.when(() -> LocalServices.getService(ActivityManagerInternal.class));
doReturn(mock(ActivityTaskManagerInternal.class))
.when(() -> LocalServices.getService(ActivityTaskManagerInternal.class));
+ doReturn(mock(AlarmManagerInternal.class))
+ .when(() -> LocalServices.getService(AlarmManagerInternal.class));
doReturn(mPowerManagerInternal)
.when(() -> LocalServices.getService(PowerManagerInternal.class));
- when(mPowerManagerInternal.getLowPowerState(anyInt())).thenReturn(
- mock(PowerSaveState.class));
+ when(mPowerManagerInternal.getLowPowerState(anyInt()))
+ .thenReturn(mock(PowerSaveState.class));
doReturn(mock(NetworkPolicyManagerInternal.class))
.when(() -> LocalServices.getService(NetworkPolicyManagerInternal.class));
when(mPowerManager.newWakeLock(anyInt(), anyString())).thenReturn(mWakeLock);
@@ -246,8 +255,11 @@
doReturn(true).when(mSensorManager).registerListener(any(), any(), anyInt());
mAppStateTracker = new AppStateTrackerForTest(getContext(), Looper.getMainLooper());
mAnyMotionDetector = new AnyMotionDetectorForTest();
+ mHandler = mock(DeviceIdleController.MyHandler.class, Answers.RETURNS_DEEP_STUBS);
+ doNothing().when(mHandler).handleMessage(any());
mInjector = new InjectorForTest(getContext());
doNothing().when(mContentResolver).registerContentObserver(any(), anyBoolean(), any());
+
mDeviceIdleController = new DeviceIdleController(getContext(), mInjector);
spyOn(mDeviceIdleController);
doNothing().when(mDeviceIdleController).publishBinderService(any(), any());
@@ -423,6 +435,29 @@
mDeviceIdleController.becomeInactiveIfAppropriateLocked();
verifyStateConditions(STATE_ACTIVE);
+
+ mConstants.WAIT_FOR_UNLOCK = false;
+ setScreenLocked(true);
+ setScreenOn(true);
+ setChargingOn(false);
+
+ mDeviceIdleController.becomeInactiveIfAppropriateLocked();
+ verifyStateConditions(STATE_ACTIVE);
+
+ setScreenLocked(false);
+ setScreenOn(true);
+ setChargingOn(false);
+
+ mDeviceIdleController.becomeInactiveIfAppropriateLocked();
+ verifyStateConditions(STATE_ACTIVE);
+
+ mConstants.WAIT_FOR_UNLOCK = true;
+ setScreenLocked(false);
+ setScreenOn(true);
+ setChargingOn(false);
+
+ mDeviceIdleController.becomeInactiveIfAppropriateLocked();
+ verifyStateConditions(STATE_ACTIVE);
}
@Test
@@ -1307,7 +1342,7 @@
}
@Test
- public void testbecomeActiveLocked_deep() {
+ public void testBecomeActiveLocked_deep() {
// becomeActiveLocked should put everything into ACTIVE.
enterDeepState(STATE_ACTIVE);
@@ -1344,7 +1379,7 @@
}
@Test
- public void testbecomeActiveLocked_light() {
+ public void testBecomeActiveLocked_light() {
// becomeActiveLocked should put everything into ACTIVE.
enterLightState(LIGHT_STATE_ACTIVE);
@@ -1376,6 +1411,163 @@
verifyLightStateConditions(LIGHT_STATE_ACTIVE);
}
+ /** Test based on b/119058625. */
+ @Test
+ public void testExitNotifiesDependencies_WaitForUnlockOn_KeyguardOn_ScreenThenMotion() {
+ mConstants.WAIT_FOR_UNLOCK = true;
+ enterDeepState(STATE_IDLE);
+ reset(mAlarmManager);
+ spyOn(mDeviceIdleController);
+
+ mDeviceIdleController.keyguardShowingLocked(true);
+ setScreenOn(true);
+ // With WAIT_FOR_UNLOCK = true and the screen locked, turning the screen on by itself
+ // shouldn't bring the device out of deep IDLE.
+ verifyStateConditions(STATE_IDLE);
+ mDeviceIdleController.handleMotionDetectedLocked(1000, "test");
+ // Motion should bring the device out of Doze. Since the screen is still locked (albeit
+ // on), the states should go back into INACTIVE.
+ verifyStateConditions(STATE_INACTIVE);
+ verifyLightStateConditions(LIGHT_STATE_INACTIVE);
+ verify(mAlarmManager).cancel(eq(mDeviceIdleController.mDeepAlarmListener));
+ verify(mDeviceIdleController).scheduleReportActiveLocked(anyString(), anyInt());
+ }
+
+ /** Test based on b/119058625. */
+ @Test
+ public void testExitNotifiesDependencies_WaitForUnlockOn_KeyguardOff_ScreenThenMotion() {
+ mConstants.WAIT_FOR_UNLOCK = true;
+ enterDeepState(STATE_IDLE);
+ reset(mAlarmManager);
+ spyOn(mDeviceIdleController);
+
+ mDeviceIdleController.keyguardShowingLocked(false);
+ setScreenOn(true);
+ // With WAIT_FOR_UNLOCK = true and the screen unlocked, turning the screen on by itself
+ // should bring the device out of deep IDLE.
+ verifyStateConditions(STATE_ACTIVE);
+ verifyLightStateConditions(LIGHT_STATE_ACTIVE);
+ verify(mAlarmManager).cancel(eq(mDeviceIdleController.mDeepAlarmListener));
+ verify(mDeviceIdleController).scheduleReportActiveLocked(anyString(), anyInt());
+ }
+
+ /** Test based on b/119058625. */
+ @Test
+ public void testExitNotifiesDependencies_WaitForUnlockOn_KeyguardOn_MotionThenScreen() {
+ mConstants.WAIT_FOR_UNLOCK = true;
+ enterDeepState(STATE_IDLE);
+ reset(mAlarmManager);
+ spyOn(mDeviceIdleController);
+
+ InOrder alarmManagerInOrder = inOrder(mAlarmManager);
+ InOrder controllerInOrder = inOrder(mDeviceIdleController);
+
+ mDeviceIdleController.keyguardShowingLocked(true);
+ mDeviceIdleController.handleMotionDetectedLocked(1000, "test");
+ // The screen is still off, so motion should result in the INACTIVE state.
+ verifyStateConditions(STATE_INACTIVE);
+ verifyLightStateConditions(LIGHT_STATE_INACTIVE);
+ alarmManagerInOrder.verify(mAlarmManager)
+ .cancel(eq(mDeviceIdleController.mDeepAlarmListener));
+ controllerInOrder.verify(mDeviceIdleController)
+ .scheduleReportActiveLocked(anyString(), anyInt());
+
+ setScreenOn(true);
+ // With WAIT_FOR_UNLOCK = true and the screen locked, turning the screen on by itself
+ // shouldn't bring the device all the way to ACTIVE.
+ verifyStateConditions(STATE_INACTIVE);
+ verifyLightStateConditions(LIGHT_STATE_INACTIVE);
+ alarmManagerInOrder.verify(mAlarmManager, never()).cancel(
+ eq(mDeviceIdleController.mDeepAlarmListener));
+
+ // User finally unlocks the device. Device should be fully active.
+ mDeviceIdleController.keyguardShowingLocked(false);
+ verifyStateConditions(STATE_ACTIVE);
+ verifyLightStateConditions(LIGHT_STATE_ACTIVE);
+ alarmManagerInOrder.verify(mAlarmManager)
+ .cancel(eq(mDeviceIdleController.mDeepAlarmListener));
+ controllerInOrder.verify(mDeviceIdleController)
+ .scheduleReportActiveLocked(anyString(), anyInt());
+ }
+
+ /** Test based on b/119058625. */
+ @Test
+ public void testExitNotifiesDependencies_WaitForUnlockOn_KeyguardOff_MotionThenScreen() {
+ mConstants.WAIT_FOR_UNLOCK = true;
+ enterDeepState(STATE_IDLE);
+ reset(mAlarmManager);
+ spyOn(mDeviceIdleController);
+
+ InOrder alarmManagerInOrder = inOrder(mAlarmManager);
+ InOrder controllerInOrder = inOrder(mDeviceIdleController);
+
+ mDeviceIdleController.keyguardShowingLocked(false);
+ mDeviceIdleController.handleMotionDetectedLocked(1000, "test");
+ // The screen is still off, so motion should result in the INACTIVE state.
+ verifyStateConditions(STATE_INACTIVE);
+ verifyLightStateConditions(LIGHT_STATE_INACTIVE);
+ alarmManagerInOrder.verify(mAlarmManager)
+ .cancel(eq(mDeviceIdleController.mDeepAlarmListener));
+ controllerInOrder.verify(mDeviceIdleController)
+ .scheduleReportActiveLocked(anyString(), anyInt());
+
+ setScreenOn(true);
+ // With WAIT_FOR_UNLOCK = true and the screen unlocked, turning the screen on by itself
+ // should bring the device out of deep IDLE.
+ verifyStateConditions(STATE_ACTIVE);
+ verifyLightStateConditions(LIGHT_STATE_ACTIVE);
+ alarmManagerInOrder.verify(mAlarmManager)
+ .cancel(eq(mDeviceIdleController.mDeepAlarmListener));
+ controllerInOrder.verify(mDeviceIdleController)
+ .scheduleReportActiveLocked(anyString(), anyInt());
+ }
+
+ @Test
+ public void testExitNotifiesDependencies_WaitForUnlockOff_Screen() {
+ mConstants.WAIT_FOR_UNLOCK = false;
+ enterDeepState(STATE_IDLE);
+ reset(mAlarmManager);
+ spyOn(mDeviceIdleController);
+
+ setScreenOn(true);
+ // With WAIT_FOR_UNLOCK = false and the screen locked, turning the screen on by itself
+ // should bring the device out of deep IDLE.
+ verifyStateConditions(STATE_ACTIVE);
+ verifyLightStateConditions(LIGHT_STATE_ACTIVE);
+ verify(mAlarmManager).cancel(eq(mDeviceIdleController.mDeepAlarmListener));
+ verify(mDeviceIdleController).scheduleReportActiveLocked(anyString(), anyInt());
+ }
+
+ @Test
+ public void testExitNotifiesDependencies_WaitForUnlockOff_MotionThenScreen() {
+ mConstants.WAIT_FOR_UNLOCK = false;
+ enterDeepState(STATE_IDLE);
+ reset(mAlarmManager);
+ spyOn(mDeviceIdleController);
+
+ InOrder alarmManagerInOrder = inOrder(mAlarmManager);
+ InOrder controllerInOrder = inOrder(mDeviceIdleController);
+
+ mDeviceIdleController.handleMotionDetectedLocked(1000, "test");
+ // The screen is still off, so motion should result in the INACTIVE state.
+ verifyStateConditions(STATE_INACTIVE);
+ verifyLightStateConditions(LIGHT_STATE_INACTIVE);
+ alarmManagerInOrder.verify(mAlarmManager)
+ .cancel(eq(mDeviceIdleController.mDeepAlarmListener));
+ controllerInOrder.verify(mDeviceIdleController)
+ .scheduleReportActiveLocked(anyString(), anyInt());
+
+ setScreenOn(true);
+ // With WAIT_FOR_UNLOCK = false and the screen locked, turning the screen on by itself
+ // should bring the device out of deep IDLE.
+ verifyStateConditions(STATE_ACTIVE);
+ verifyLightStateConditions(LIGHT_STATE_ACTIVE);
+ alarmManagerInOrder.verify(mAlarmManager)
+ .cancel(eq(mDeviceIdleController.mDeepAlarmListener));
+ controllerInOrder.verify(mDeviceIdleController)
+ .scheduleReportActiveLocked(anyString(), anyInt());
+ }
+
@Test
public void testStepToIdleMode() {
float delta = mDeviceIdleController.MIN_PRE_IDLE_FACTOR_CHANGE;
@@ -1508,6 +1700,10 @@
mDeviceIdleController.updateChargingLocked(on);
}
+ private void setScreenLocked(boolean locked) {
+ mDeviceIdleController.keyguardShowingLocked(locked);
+ }
+
private void setScreenOn(boolean on) {
doReturn(on).when(mPowerManager).isInteractive();
mDeviceIdleController.updateInteractivityLocked();
@@ -1549,7 +1745,8 @@
assertFalse(mDeviceIdleController.mMotionListener.isActive());
assertFalse(mAnyMotionDetector.isMonitoring);
assertFalse(mDeviceIdleController.isCharging());
- assertFalse(mDeviceIdleController.isScreenOn());
+ assertFalse(mDeviceIdleController.isScreenOn()
+ && !mDeviceIdleController.isKeyguardShowing());
break;
case STATE_IDLE_PENDING:
assertEquals(
@@ -1557,7 +1754,8 @@
mDeviceIdleController.mMotionListener.isActive());
assertFalse(mAnyMotionDetector.isMonitoring);
assertFalse(mDeviceIdleController.isCharging());
- assertFalse(mDeviceIdleController.isScreenOn());
+ assertFalse(mDeviceIdleController.isScreenOn()
+ && !mDeviceIdleController.isKeyguardShowing());
break;
case STATE_SENSING:
assertEquals(
@@ -1567,14 +1765,16 @@
mDeviceIdleController.hasMotionSensor(),
mAnyMotionDetector.isMonitoring);
assertFalse(mDeviceIdleController.isCharging());
- assertFalse(mDeviceIdleController.isScreenOn());
+ assertFalse(mDeviceIdleController.isScreenOn()
+ && !mDeviceIdleController.isKeyguardShowing());
break;
case STATE_LOCATING:
assertEquals(
mDeviceIdleController.hasMotionSensor(),
mDeviceIdleController.mMotionListener.isActive());
assertFalse(mDeviceIdleController.isCharging());
- assertFalse(mDeviceIdleController.isScreenOn());
+ assertFalse(mDeviceIdleController.isScreenOn()
+ && !mDeviceIdleController.isKeyguardShowing());
break;
case STATE_IDLE:
if (mDeviceIdleController.hasMotionSensor()) {
@@ -1584,7 +1784,8 @@
}
assertFalse(mAnyMotionDetector.isMonitoring);
assertFalse(mDeviceIdleController.isCharging());
- assertFalse(mDeviceIdleController.isScreenOn());
+ assertFalse(mDeviceIdleController.isScreenOn()
+ && !mDeviceIdleController.isKeyguardShowing());
// Light state should be OVERRIDE at this point.
verifyLightStateConditions(LIGHT_STATE_OVERRIDE);
break;
@@ -1596,14 +1797,16 @@
}
assertFalse(mAnyMotionDetector.isMonitoring);
assertFalse(mDeviceIdleController.isCharging());
- assertFalse(mDeviceIdleController.isScreenOn());
+ assertFalse(mDeviceIdleController.isScreenOn()
+ && !mDeviceIdleController.isKeyguardShowing());
break;
case STATE_QUICK_DOZE_DELAY:
// If quick doze is enabled, the motion listener should NOT be active.
assertFalse(mDeviceIdleController.mMotionListener.isActive());
assertFalse(mAnyMotionDetector.isMonitoring);
assertFalse(mDeviceIdleController.isCharging());
- assertFalse(mDeviceIdleController.isScreenOn());
+ assertFalse(mDeviceIdleController.isScreenOn()
+ && !mDeviceIdleController.isKeyguardShowing());
break;
default:
fail("Conditions for " + stateToString(expectedState) + " unknown.");
@@ -1632,7 +1835,8 @@
case LIGHT_STATE_IDLE_MAINTENANCE:
case LIGHT_STATE_OVERRIDE:
assertFalse(mDeviceIdleController.isCharging());
- assertFalse(mDeviceIdleController.isScreenOn());
+ assertFalse(mDeviceIdleController.isScreenOn()
+ && !mDeviceIdleController.isKeyguardShowing());
break;
default:
fail("Conditions for " + lightStateToString(expectedLightState) + " unknown.");
diff --git a/services/tests/servicestests/AndroidManifest.xml b/services/tests/servicestests/AndroidManifest.xml
index dc31c0f..fce7599 100644
--- a/services/tests/servicestests/AndroidManifest.xml
+++ b/services/tests/servicestests/AndroidManifest.xml
@@ -66,6 +66,8 @@
<uses-permission android:name="android.permission.CONTROL_KEYGUARD"/>
<uses-permission android:name="android.permission.MANAGE_BIND_INSTANT_SERVICE"/>
<uses-permission android:name="android.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS" />
+ <uses-permission android:name="android.permission.READ_DEVICE_CONFIG" />
+ <uses-permission android:name="android.permission.WRITE_DEVICE_CONFIG" />
<!-- Uses API introduced in O (26) -->
<uses-sdk android:minSdkVersion="1"
diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceTestable.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceTestable.java
index a847b6a..2ce4c54 100644
--- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceTestable.java
+++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceTestable.java
@@ -65,7 +65,8 @@
public OwnersTestable(MockSystemServices services) {
super(services.userManager, services.userManagerInternal,
- services.packageManagerInternal, new MockInjector(services));
+ services.packageManagerInternal, services.activityTaskManagerInternal,
+ new MockInjector(services));
}
static class MockInjector extends Injector {
diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
index 9ac91dd..de782a5 100644
--- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
@@ -5199,7 +5199,7 @@
public void testGetPasswordComplexity_currentUserNoPassword() {
when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
.thenReturn(true);
- mServiceContext.permissions.add(permission.GET_AND_REQUEST_SCREEN_LOCK_COMPLEXITY);
+ mServiceContext.permissions.add(permission.REQUEST_SCREEN_LOCK_COMPLEXITY);
when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
.thenReturn(DpmMockContext.CALLER_USER_HANDLE);
@@ -5209,7 +5209,7 @@
public void testGetPasswordComplexity_currentUserHasPassword() {
when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
.thenReturn(true);
- mServiceContext.permissions.add(permission.GET_AND_REQUEST_SCREEN_LOCK_COMPLEXITY);
+ mServiceContext.permissions.add(permission.REQUEST_SCREEN_LOCK_COMPLEXITY);
when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
.thenReturn(DpmMockContext.CALLER_USER_HANDLE);
dpms.mUserPasswordMetrics.put(
@@ -5222,7 +5222,7 @@
public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() {
when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
.thenReturn(true);
- mServiceContext.permissions.add(permission.GET_AND_REQUEST_SCREEN_LOCK_COMPLEXITY);
+ mServiceContext.permissions.add(permission.REQUEST_SCREEN_LOCK_COMPLEXITY);
UserInfo parentUser = new UserInfo();
parentUser.id = DpmMockContext.CALLER_USER_HANDLE + 10;
diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java b/services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java
index 4724f1c..8f0aeea 100644
--- a/services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java
+++ b/services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java
@@ -64,6 +64,7 @@
import com.android.internal.util.test.FakeSettingsProvider;
import com.android.internal.widget.LockPatternUtils;
import com.android.server.net.NetworkPolicyManagerInternal;
+import com.android.server.wm.ActivityTaskManagerInternal;
import java.io.File;
import java.io.IOException;
@@ -94,6 +95,7 @@
public final IActivityManager iactivityManager;
public final IActivityTaskManager iactivityTaskManager;
public ActivityManagerInternal activityManagerInternal;
+ public ActivityTaskManagerInternal activityTaskManagerInternal;
public final IPackageManager ipackageManager;
public final IBackupManager ibackupManager;
public final IAudioService iaudioService;
@@ -133,6 +135,7 @@
iactivityManager = mock(IActivityManager.class);
iactivityTaskManager = mock(IActivityTaskManager.class);
activityManagerInternal = mock(ActivityManagerInternal.class);
+ activityTaskManagerInternal = mock(ActivityTaskManagerInternal.class);
ipackageManager = mock(IPackageManager.class);
ibackupManager = mock(IBackupManager.class);
iaudioService = mock(IAudioService.class);
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/PlatformKeyManagerTest.java b/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/PlatformKeyManagerTest.java
index 13436e7..821d97a 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/PlatformKeyManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/PlatformKeyManagerTest.java
@@ -24,14 +24,21 @@
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import static org.testng.Assert.expectThrows;
import android.app.KeyguardManager;
import android.content.Context;
+import android.os.RemoteException;
+import android.security.GateKeeper;
+import android.security.keystore.AndroidKeyStoreSecretKey;
+import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.security.keystore.KeyProtection;
+import android.service.gatekeeper.IGateKeeperService;
import androidx.test.InstrumentationRegistry;
import androidx.test.filters.SmallTest;
@@ -53,6 +60,8 @@
import java.security.UnrecoverableKeyException;
import java.util.List;
+import javax.crypto.KeyGenerator;
+
@SmallTest
@RunWith(AndroidJUnit4.class)
public class PlatformKeyManagerTest {
@@ -60,10 +69,15 @@
private static final String DATABASE_FILE_NAME = "recoverablekeystore.db";
private static final int USER_AUTHENTICATION_VALIDITY_DURATION_SECONDS = 15;
private static final int USER_ID_FIXTURE = 42;
+ private static final long USER_SID = 4200L;
+ private static final String KEY_ALGORITHM = "AES";
+ private static final String ANDROID_KEY_STORE_PROVIDER = "AndroidKeyStore";
+ private static final String TESTING_KEYSTORE_KEY_ALIAS = "testing-key-store-key-alias";
@Mock private Context mContext;
@Mock private KeyStoreProxy mKeyStoreProxy;
@Mock private KeyguardManager mKeyguardManager;
+ @Mock private IGateKeeperService mGateKeeperService;
@Captor private ArgumentCaptor<KeyStore.ProtectionParameter> mProtectionParameterCaptor;
@Captor private ArgumentCaptor<KeyStore.Entry> mEntryArgumentCaptor;
@@ -74,18 +88,19 @@
private PlatformKeyManager mPlatformKeyManager;
@Before
- public void setUp() {
+ public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
Context context = InstrumentationRegistry.getTargetContext();
mDatabaseFile = context.getDatabasePath(DATABASE_FILE_NAME);
mRecoverableKeyStoreDb = RecoverableKeyStoreDb.newInstance(context);
- mPlatformKeyManager = new PlatformKeyManager(
- mContext, mKeyStoreProxy, mRecoverableKeyStoreDb);
+ mPlatformKeyManager = new PlatformKeyManagerTestable(
+ mContext, mKeyStoreProxy, mRecoverableKeyStoreDb, mGateKeeperService);
when(mContext.getSystemService(anyString())).thenReturn(mKeyguardManager);
when(mContext.getSystemServiceName(any())).thenReturn("test");
when(mKeyguardManager.isDeviceSecure(USER_ID_FIXTURE)).thenReturn(true);
+ when(mGateKeeperService.getSecureUserId(USER_ID_FIXTURE)).thenReturn(USER_SID);
}
@After
@@ -192,11 +207,36 @@
mPlatformKeyManager.init(USER_ID_FIXTURE);
assertEquals(
- USER_ID_FIXTURE,
+ USER_SID,
getDecryptKeyProtection().getBoundToSpecificSecureUserId());
}
@Test
+ public void init_doesNotCreateDecryptKeyIfNoSid() throws Exception {
+ when(mGateKeeperService.getSecureUserId(USER_ID_FIXTURE))
+ .thenReturn(GateKeeper.INVALID_SECURE_USER_ID);
+
+ mPlatformKeyManager.init(USER_ID_FIXTURE);
+
+ verify(mKeyStoreProxy, never()).setEntry(
+ eq("com.android.server.locksettings.recoverablekeystore/platform/42/1/decrypt"),
+ any(),
+ any());
+ }
+
+ @Test
+ public void init_doesNotCreateDecryptKeyOnGateKeeperException() throws Exception {
+ when(mGateKeeperService.getSecureUserId(USER_ID_FIXTURE)).thenThrow(new RemoteException());
+
+ expectThrows(RemoteException.class, () -> mPlatformKeyManager.init(USER_ID_FIXTURE));
+
+ verify(mKeyStoreProxy, never()).setEntry(
+ eq("com.android.server.locksettings.recoverablekeystore/platform/42/1/decrypt"),
+ any(),
+ any());
+ }
+
+ @Test
public void init_createsBothKeysWithSameMaterial() throws Exception {
mPlatformKeyManager.init(USER_ID_FIXTURE);
@@ -259,6 +299,9 @@
when(mKeyStoreProxy
.containsAlias("com.android.server.locksettings.recoverablekeystore/"
+ "platform/42/1/encrypt")).thenReturn(true);
+ when(mKeyStoreProxy.getKey(
+ eq("com.android.server.locksettings.recoverablekeystore/platform/42/1/decrypt"),
+ any())).thenReturn(generateAndroidKeyStoreKey());
mPlatformKeyManager.getDecryptKey(USER_ID_FIXTURE);
@@ -281,6 +324,9 @@
when(mKeyStoreProxy
.containsAlias("com.android.server.locksettings.recoverablekeystore/"
+ "platform/42/2/decrypt")).thenReturn(true);
+ when(mKeyStoreProxy.getKey(
+ eq("com.android.server.locksettings.recoverablekeystore/platform/42/2/decrypt"),
+ any())).thenReturn(generateAndroidKeyStoreKey());
mPlatformKeyManager.getDecryptKey(USER_ID_FIXTURE);
@@ -352,6 +398,9 @@
doThrow(new UnrecoverableKeyException()).when(mKeyStoreProxy).getKey(
eq("com.android.server.locksettings.recoverablekeystore/platform/42/1/decrypt"),
any());
+ when(mKeyStoreProxy.getKey(
+ eq("com.android.server.locksettings.recoverablekeystore/platform/42/2/decrypt"),
+ any())).thenReturn(generateAndroidKeyStoreKey());
when(mKeyStoreProxy
.containsAlias("com.android.server.locksettings.recoverablekeystore/"
@@ -536,4 +585,34 @@
mProtectionParameterCaptor.capture());
return (KeyProtection) mProtectionParameterCaptor.getValue();
}
+
+ private AndroidKeyStoreSecretKey generateAndroidKeyStoreKey() throws Exception {
+ KeyGenerator keyGenerator = KeyGenerator.getInstance(
+ KEY_ALGORITHM,
+ ANDROID_KEY_STORE_PROVIDER);
+ keyGenerator.init(new KeyGenParameterSpec.Builder(TESTING_KEYSTORE_KEY_ALIAS,
+ KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
+ .build());
+ return (AndroidKeyStoreSecretKey) keyGenerator.generateKey();
+ }
+
+ class PlatformKeyManagerTestable extends PlatformKeyManager {
+ private IGateKeeperService mGateKeeperService;
+
+ PlatformKeyManagerTestable(
+ Context context,
+ KeyStoreProxy keyStoreProxy,
+ RecoverableKeyStoreDb database,
+ IGateKeeperService gateKeeperService) {
+ super(context, keyStoreProxy, database);
+ mGateKeeperService = gateKeeperService;
+ }
+
+ @Override
+ IGateKeeperService getGateKeeperService() {
+ return mGateKeeperService;
+ }
+ }
}
diff --git a/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest2.java b/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest2.java
index 8d0365b..9504381 100644
--- a/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest2.java
+++ b/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest2.java
@@ -32,6 +32,7 @@
import android.Manifest.permission;
import android.app.ActivityManager;
+import android.app.Person;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ShortcutInfo;
@@ -890,6 +891,7 @@
.setText("text")
.setDisabledMessage("dismes")
.setCategories(set(ShortcutInfo.SHORTCUT_CATEGORY_CONVERSATION, "xyz"))
+ .setPerson(makePerson("person", "personKey", "personUri"))
.setIntent(makeIntent("action", ShortcutActivity.class, "key", "val"))
.setRank(123)
.setExtras(pb)
@@ -901,6 +903,8 @@
.setTitle("x")
.setActivity(new ComponentName(mClientContext, ShortcutActivity2.class))
.setIntent(makeIntent("action", ShortcutActivity.class, "key", "val"))
+ .setPersons(list(makePerson("person1", "personKey1", "personUri1"),
+ makePerson("person2", "personKey2", "personUri2")).toArray(new Person[2]))
.setRank(456)
.build();
sorig2.setTimestamp(mInjectedCurrentTimeMillis);
@@ -936,6 +940,10 @@
assertEquals(set(ShortcutInfo.SHORTCUT_CATEGORY_CONVERSATION, "xyz"), si.getCategories());
assertEquals("action", si.getIntent().getAction());
assertEquals("val", si.getIntent().getStringExtra("key"));
+ assertEquals(1, si.getPersons().length);
+ assertEquals("person", si.getPersons()[0].getName());
+ assertEquals("personKey", si.getPersons()[0].getKey());
+ assertEquals("personUri", si.getPersons()[0].getUri());
assertEquals(0, si.getRank());
assertEquals(1, si.getExtras().getInt("k"));
@@ -949,6 +957,8 @@
// to test it.
si = mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "id2", USER_10);
assertEquals(1, si.getRank());
+ assertEquals(2, si.getPersons().length);
+ assertEquals("personUri2", si.getPersons()[1].getUri());
dumpUserFile(USER_10);
}
@@ -1114,6 +1124,7 @@
.setDisabledMessage("dismes")
.setCategories(set(ShortcutInfo.SHORTCUT_CATEGORY_CONVERSATION, "xyz"))
.setIntent(makeIntent("action", ShortcutActivity.class, "key", "val"))
+ .setPerson(makePerson("person", "personKey", "personUri"))
.setRank(123)
.setExtras(pb)
.build();
@@ -1150,6 +1161,7 @@
assertEquals(set(ShortcutInfo.SHORTCUT_CATEGORY_CONVERSATION, "xyz"), si.getCategories());
assertEquals("action", si.getIntent().getAction());
assertEquals("val", si.getIntent().getStringExtra("key"));
+ assertEquals(0, si.getPersons().length); // Don't backup the persons field
assertEquals(0, si.getRank());
assertEquals(1, si.getExtras().getInt("k"));
diff --git a/services/tests/servicestests/src/com/android/server/usage/AppTimeLimitControllerTests.java b/services/tests/servicestests/src/com/android/server/usage/AppTimeLimitControllerTests.java
index 4e43d00..8caa39d 100644
--- a/services/tests/servicestests/src/com/android/server/usage/AppTimeLimitControllerTests.java
+++ b/services/tests/servicestests/src/com/android/server/usage/AppTimeLimitControllerTests.java
@@ -1035,6 +1035,15 @@
0L, group.getUsageRemaining());
}
+ /** Verify that a limit of 0 is allowed for the special case of re-registering an observer. */
+ @Test
+ public void testAppUsageLimitObserver_ZeroTimeLimitIsAllowed() {
+ addAppUsageLimitObserver(OBS_ID1, GROUP1, 0);
+ AppTimeLimitController.AppUsageLimitGroup group = getAppUsageLimitObserver(UID, OBS_ID1);
+ assertNotNull("Observer wasn't added", group);
+ assertEquals("Usage remaining was not 0.", 0, group.getUsageRemaining());
+ }
+
private void startUsage(String packageName) {
mController.noteUsageStart(packageName, USER_ID);
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityMetricsLaunchObserverTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityMetricsLaunchObserverTests.java
index 2de4ae0..23bae88 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityMetricsLaunchObserverTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityMetricsLaunchObserverTests.java
@@ -24,6 +24,7 @@
import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.verifyNoMoreInteractions;
+
import static com.google.common.truth.Truth.assertWithMessage;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -35,9 +36,7 @@
import android.os.SystemClock;
import android.platform.test.annotations.Presubmit;
import android.util.SparseIntArray;
-import android.util.proto.ProtoOutputStream;
-import androidx.test.filters.FlakyTest;
import androidx.test.filters.SmallTest;
import com.android.server.wm.ActivityMetricsLaunchObserver.ActivityRecordProto;
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
index 4073ff1..8c36905 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
@@ -183,11 +183,14 @@
.thenReturn(navBarPosition);
mTask.getConfiguration().windowConfiguration.setAppBounds(taskBounds);
mActivity.info.maxAspectRatio = aspectRatio;
- mActivity.ensureActivityConfiguration(
- 0 /* globalChanges */, false /* preserveWindow */);
+ ensureActivityConfiguration();
assertEquals(expectedActivityBounds, mActivity.getBounds());
}
+ private void ensureActivityConfiguration() {
+ mActivity.ensureActivityConfiguration(0 /* globalChanges */, false /* preserveWindow */);
+ }
+
@Test
public void testCanBeLaunchedOnDisplay() {
mService.mSupportsMultiWindow = true;
@@ -281,7 +284,7 @@
mActivity.mRelaunchReason = ActivityTaskManagerService.RELAUNCH_REASON_NONE;
- mActivity.ensureActivityConfiguration(0, false, false);
+ ensureActivityConfiguration();
assertEquals(ActivityTaskManagerService.RELAUNCH_REASON_WINDOWING_MODE_RESIZE,
mActivity.mRelaunchReason);
@@ -305,7 +308,7 @@
mActivity.mRelaunchReason = ActivityTaskManagerService.RELAUNCH_REASON_NONE;
- mActivity.ensureActivityConfiguration(0, false, false);
+ ensureActivityConfiguration();
assertEquals(ActivityTaskManagerService.RELAUNCH_REASON_FREE_RESIZE,
mActivity.mRelaunchReason);
@@ -327,7 +330,7 @@
mActivity.mRelaunchReason =
ActivityTaskManagerService.RELAUNCH_REASON_WINDOWING_MODE_RESIZE;
- mActivity.ensureActivityConfiguration(0, false, false);
+ ensureActivityConfiguration();
assertEquals(ActivityTaskManagerService.RELAUNCH_REASON_NONE,
mActivity.mRelaunchReason);
@@ -433,4 +436,46 @@
stack.getDisplay().removeChild(stack);
}
}
+
+ @Test
+ public void testFixedScreenConfigurationWhenMovingToDisplay() {
+ // Initialize different bounds on a new display.
+ final ActivityDisplay newDisplay = addNewActivityDisplayAt(ActivityDisplay.POSITION_TOP);
+ newDisplay.setBounds(0, 0, 1000, 2000);
+ newDisplay.getConfiguration().densityDpi = 300;
+
+ mTask.getWindowConfiguration().setAppBounds(mStack.getDisplay().getBounds());
+ mTask.getConfiguration().densityDpi = 200;
+ when(mActivity.mAppWindowToken.getOrientationIgnoreVisibility()).thenReturn(
+ ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
+ mActivity.info.resizeMode = ActivityInfo.RESIZE_MODE_UNRESIZEABLE;
+ mActivity.info.maxAspectRatio = 1.5f;
+ ensureActivityConfiguration();
+ final Rect originalBounds = new Rect(mActivity.getBounds());
+ final int originalDpi = mActivity.getConfiguration().densityDpi;
+
+ // Move the non-resizable activity to the new display.
+ mStack.reparent(newDisplay, true /* onTop */, false /* displayRemoved */);
+ ensureActivityConfiguration();
+
+ assertEquals(originalBounds, mActivity.getBounds());
+ assertEquals(originalDpi, mActivity.getConfiguration().densityDpi);
+ }
+
+ @Test
+ public void testFixedScreenBoundsWhenDisplaySizeChanged() {
+ when(mActivity.mAppWindowToken.getOrientationIgnoreVisibility()).thenReturn(
+ ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
+ mTask.getWindowConfiguration().setAppBounds(mStack.getDisplay().getBounds());
+ mActivity.info.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
+ mActivity.info.resizeMode = ActivityInfo.RESIZE_MODE_UNRESIZEABLE;
+ ensureActivityConfiguration();
+ final Rect originalBounds = new Rect(mActivity.getBounds());
+
+ // Change the size of current display.
+ mStack.getDisplay().setBounds(0, 0, 1000, 2000);
+ ensureActivityConfiguration();
+
+ assertEquals(originalBounds, mActivity.getBounds());
+ }
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
index 60f1ae26..392b010 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
@@ -61,7 +61,6 @@
import android.app.ActivityOptions;
import android.app.IApplicationThread;
-import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ActivityInfo;
@@ -643,7 +642,7 @@
UNIMPORTANT_UID2, false, PROCESS_STATE_TOP + 1,
false, false, false, true, false);
runAndVerifyBackgroundActivityStartsSubtest(
- "disallowed_callingPackageIsDeviceOwner_notAborted", false,
+ "disallowed_callingPackageNameIsDeviceOwner_notAborted", false,
UNIMPORTANT_UID, false, PROCESS_STATE_TOP + 1,
UNIMPORTANT_UID2, false, PROCESS_STATE_TOP + 1,
false, false, false, false, true);
@@ -655,7 +654,7 @@
boolean hasForegroundActivities, boolean callerIsRecents,
boolean callerIsTempWhitelisted,
boolean callerIsInstrumentingWithBackgroundActivityStartPrivileges,
- boolean isCallingPackageDeviceOwner) {
+ boolean isCallingPackageNameDeviceOwner) {
// window visibility
doReturn(callingUidHasVisibleWindow).when(mService.mWindowManager.mRoot)
.isAnyNonToastWindowVisibleForUid(callingUid);
@@ -681,9 +680,8 @@
// caller is instrumenting with background activity starts privileges
callerApp.setInstrumenting(callerIsInstrumentingWithBackgroundActivityStartPrivileges,
callerIsInstrumentingWithBackgroundActivityStartPrivileges);
- // caller is device owner
- DevicePolicyManager dpmMock = mService.getDevicePolicyManager();
- doReturn(isCallingPackageDeviceOwner).when(dpmMock).isDeviceOwnerApp(any());
+ // calling package name is whitelisted
+ doReturn(isCallingPackageNameDeviceOwner).when(mService).isDeviceOwner(any());
final ActivityOptions options = spy(ActivityOptions.makeBasic());
ActivityStarter starter = prepareStarter(FLAG_ACTIVITY_NEW_TASK)
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java b/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java
index e27dd94..abc0bd6 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java
@@ -42,7 +42,6 @@
import android.app.ActivityManagerInternal;
import android.app.ActivityOptions;
import android.app.IApplicationThread;
-import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
@@ -72,8 +71,10 @@
import com.android.server.appop.AppOpsService;
import com.android.server.firewall.IntentFirewall;
import com.android.server.uri.UriGrantsManagerInternal;
+import com.android.server.wm.utils.MockTracker;
import org.junit.After;
+import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
@@ -88,6 +89,8 @@
class ActivityTestsBase {
private static int sNextDisplayId = DEFAULT_DISPLAY + 1;
+ private static MockTracker sMockTracker;
+
@Rule
public final DexmakerShareClassLoaderRule mDexmakerShareClassLoaderRule =
new DexmakerShareClassLoaderRule();
@@ -107,9 +110,17 @@
@BeforeClass
public static void setUpOnceBase() {
+ sMockTracker = new MockTracker();
+
AttributeCache.init(getInstrumentation().getTargetContext());
}
+ @AfterClass
+ public static void tearDownOnceBase() {
+ sMockTracker.close();
+ sMockTracker = null;
+ }
+
@Before
public void setUpBase() {
mTestInjector.setUp();
@@ -425,7 +436,6 @@
spyOn(getLifecycleManager());
spyOn(getLockTaskController());
doReturn(mock(IPackageManager.class)).when(this).getPackageManager();
- doReturn(mock(DevicePolicyManager.class)).when(this).getDevicePolicyManager();
// allow background activity starts by default
doReturn(true).when(this).isBackgroundActivityStartsEnabled();
doNothing().when(this).updateCpuStats();
@@ -657,12 +667,11 @@
private static WindowManagerService sMockWindowManagerService;
private static WindowManagerService prepareMockWindowManager() {
- if (sMockWindowManagerService != null) {
- return sMockWindowManagerService;
+ if (sMockWindowManagerService == null) {
+ sMockWindowManagerService = mock(WindowManagerService.class);
}
- final WindowManagerService service = mock(WindowManagerService.class);
- service.mRoot = mock(RootWindowContainer.class);
+ sMockWindowManagerService.mRoot = mock(RootWindowContainer.class);
doAnswer((InvocationOnMock invocationOnMock) -> {
final Runnable runnable = invocationOnMock.<Runnable>getArgument(0);
@@ -670,10 +679,9 @@
runnable.run();
}
return null;
- }).when(service).inSurfaceTransaction(any());
+ }).when(sMockWindowManagerService).inSurfaceTransaction(any());
- sMockWindowManagerService = service;
- return service;
+ return sMockWindowManagerService;
}
/**
diff --git a/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java b/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java
index bc62de1..cd13209 100644
--- a/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java
@@ -44,6 +44,7 @@
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyInt;
+import android.content.res.Configuration;
import android.graphics.Point;
import android.graphics.Rect;
import android.platform.test.annotations.Presubmit;
@@ -62,7 +63,6 @@
* Build/Install/Run:
* atest FrameworksServicesTests:AppWindowTokenTests
*/
-@FlakyTest(bugId = 68267650)
@SmallTest
@Presubmit
public class AppWindowTokenTests extends WindowTestsBase {
@@ -79,6 +79,7 @@
mTask = createTaskInStack(mStack, 0 /* userId */);
mToken = WindowTestUtils.createTestAppWindowToken(mDisplayContent);
+ mToken.mSkipOnParentChanged = false;
mTask.addChild(mToken, 0);
}
@@ -141,6 +142,7 @@
mToken.removeImmediately();
}
+ @FlakyTest(detail = "Promote to presubmit when shown to be stable.")
@Test
public void testLandscapeSeascapeRotationByApp() {
// Some plumbing to get the service ready for rotation updates.
@@ -166,6 +168,8 @@
mDisplayContent.updateOrientationFromAppTokens(
mDisplayContent.getRequestedOverrideConfiguration(),
null /* freezeThisOneIfNeeded */, false /* forceUpdate */);
+ // In this test, DC will not get config update. Set the waiting flag to false.
+ mDisplayContent.mWaitingForConfig = false;
mWm.mRoot.performSurfacePlacement(false /* recoveringMemory */);
assertEquals(SCREEN_ORIENTATION_REVERSE_LANDSCAPE, mDisplayContent.getLastOrientation());
assertTrue(appWindow.mResizeReported);
@@ -211,6 +215,48 @@
}
@Test
+ public void testSizeCompatBounds() {
+ // The real surface transaction is unnecessary.
+ mToken.setSkipPrepareSurfaces(true);
+
+ final Rect fixedBounds = mToken.getRequestedOverrideConfiguration().windowConfiguration
+ .getBounds();
+ fixedBounds.set(0, 0, 1200, 1600);
+ final Configuration newParentConfig = mTask.getConfiguration();
+
+ // Change the size of the container to two times smaller with insets.
+ newParentConfig.windowConfiguration.setAppBounds(200, 0, 800, 800);
+ final Rect containerAppBounds = newParentConfig.windowConfiguration.getAppBounds();
+ final Rect containerBounds = newParentConfig.windowConfiguration.getBounds();
+ containerBounds.set(0, 0, 600, 800);
+ mToken.onConfigurationChanged(newParentConfig);
+
+ assertTrue(mToken.inSizeCompatMode());
+ assertEquals(containerAppBounds, mToken.getBounds());
+ assertEquals((float) containerAppBounds.width() / fixedBounds.width(),
+ mToken.getSizeCompatScale(), 0.0001f /* delta */);
+
+ // Change the width of the container to two times bigger.
+ containerAppBounds.set(0, 0, 2400, 1600);
+ containerBounds.set(containerAppBounds);
+ mToken.onConfigurationChanged(newParentConfig);
+
+ assertTrue(mToken.inSizeCompatMode());
+ // Don't scale up, so the bounds keep the same as the fixed width.
+ assertEquals(fixedBounds.width(), mToken.getBounds().width());
+ // Assert the position is horizontal center.
+ assertEquals((containerAppBounds.width() - fixedBounds.width()) / 2,
+ mToken.getBounds().left);
+ assertEquals(1f, mToken.getSizeCompatScale(), 0.0001f /* delta */);
+
+ // Change the width of the container to fit the fixed bounds.
+ containerBounds.set(0, 0, 1200, 2000);
+ mToken.onConfigurationChanged(newParentConfig);
+ // Assert don't use fixed bounds because the region is enough.
+ assertFalse(mToken.inSizeCompatMode());
+ }
+
+ @Test
@Presubmit
public void testGetOrientation() {
mToken.setOrientation(SCREEN_ORIENTATION_LANDSCAPE);
@@ -300,6 +346,7 @@
assertNoStartingWindow(mToken);
}
+ @FlakyTest(detail = "Promote to presubmit when shown to be stable.")
@Test
public void testAddRemoveRace() {
// There was once a race condition between adding and removing starting windows
@@ -384,6 +431,7 @@
// bottom one.
tokenTop.setVisibility(false, false);
tokenBottom.transferStartingWindowFromHiddenAboveTokenIfNeeded();
+ waitUntilHandlersIdle();
// Assert that the bottom window now has the starting window.
assertNoStartingWindow(tokenTop);
diff --git a/services/tests/wmtests/src/com/android/server/wm/AssistDataRequesterTest.java b/services/tests/wmtests/src/com/android/server/wm/AssistDataRequesterTest.java
index 2f90baa..3f83cae 100644
--- a/services/tests/wmtests/src/com/android/server/wm/AssistDataRequesterTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/AssistDataRequesterTest.java
@@ -71,7 +71,6 @@
* atest WmTests:AssistDataRequesterTest
*/
@MediumTest
-@FlakyTest(bugId = 113616538)
public class AssistDataRequesterTest extends ActivityTestsBase {
private static final String TAG = AssistDataRequesterTest.class.getSimpleName();
@@ -154,6 +153,7 @@
.checkOpNoThrow(eq(OP_ASSIST_SCREENSHOT), anyInt(), anyString());
}
+ @FlakyTest(bugId = 124088319)
@Test
public void testRequestData() throws Exception {
setupMocks(CURRENT_ACTIVITY_ASSIST_ALLOWED, CALLER_ASSIST_STRUCTURE_ALLOWED,
@@ -174,6 +174,7 @@
assertReceivedDataCount(0, 0, 0, 0);
}
+ @FlakyTest(bugId = 124088319)
@Test
public void testCurrentAppDisallow_expectNullCallbacks() throws Exception {
setupMocks(!CURRENT_ACTIVITY_ASSIST_ALLOWED, CALLER_ASSIST_STRUCTURE_ALLOWED,
@@ -184,6 +185,7 @@
assertReceivedDataCount(0, 1, 0, 1);
}
+ @FlakyTest(bugId = 124088319)
@Test
public void testProcessPendingData() throws Exception {
setupMocks(CURRENT_ACTIVITY_ASSIST_ALLOWED, CALLER_ASSIST_STRUCTURE_ALLOWED,
@@ -241,6 +243,7 @@
assertReceivedDataCount(0, 1, 0, 1);
}
+ @FlakyTest(bugId = 124088319)
@Test
public void testDisallowAssistContextExtras_expectNullDataCallbacks() throws Exception {
setupMocks(CURRENT_ACTIVITY_ASSIST_ALLOWED, CALLER_ASSIST_STRUCTURE_ALLOWED,
@@ -254,6 +257,7 @@
assertReceivedDataCount(0, 1, 0, 1);
}
+ @FlakyTest(bugId = 124088319)
@Test
public void testNoFetchScreenshots_expectNoScreenshotCallbacks() throws Exception {
setupMocks(CURRENT_ACTIVITY_ASSIST_ALLOWED, CALLER_ASSIST_STRUCTURE_ALLOWED,
@@ -264,6 +268,7 @@
assertReceivedDataCount(5, 5, 0, 0);
}
+ @FlakyTest(bugId = 124088319)
@Test
public void testDisallowAssistScreenshot_expectNullScreenshotCallback() throws Exception {
setupMocks(CURRENT_ACTIVITY_ASSIST_ALLOWED, CALLER_ASSIST_STRUCTURE_ALLOWED,
diff --git a/services/tests/wmtests/src/com/android/server/wm/InsetsSourceProviderTest.java b/services/tests/wmtests/src/com/android/server/wm/InsetsSourceProviderTest.java
index 0c363de..a0546d7 100644
--- a/services/tests/wmtests/src/com/android/server/wm/InsetsSourceProviderTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/InsetsSourceProviderTest.java
@@ -19,11 +19,11 @@
import static android.view.InsetsState.TYPE_TOP_BAR;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION;
-import static junit.framework.Assert.assertFalse;
-import static junit.framework.Assert.assertNull;
-import static junit.framework.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import android.graphics.Insets;
import android.graphics.Rect;
@@ -31,8 +31,6 @@
import android.view.InsetsSource;
import android.view.InsetsState;
-import org.junit.Before;
-import androidx.test.filters.FlakyTest;
import androidx.test.filters.SmallTest;
import org.junit.Before;
diff --git a/services/tests/wmtests/src/com/android/server/wm/InsetsStateControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/InsetsStateControllerTest.java
index 11526a8..bc62e8c 100644
--- a/services/tests/wmtests/src/com/android/server/wm/InsetsStateControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/InsetsStateControllerTest.java
@@ -35,7 +35,6 @@
import org.junit.Test;
@SmallTest
-@FlakyTest(detail = "Promote once confirmed non-flaky")
@Presubmit
public class InsetsStateControllerTest extends WindowTestsBase {
@@ -48,6 +47,7 @@
assertNotNull(getController().getInsetsForDispatch(app).getSource(TYPE_TOP_BAR));
}
+ @FlakyTest(bugId = 69229402)
@Test
public void testStripForDispatch_own() {
final WindowState topBar = createWindow(null, TYPE_APPLICATION, "parentWindow");
@@ -57,6 +57,7 @@
assertEquals(new InsetsState(), getController().getInsetsForDispatch(topBar));
}
+ @FlakyTest(bugId = 124088319)
@Test
public void testStripForDispatch_navBar() {
final WindowState navBar = createWindow(null, TYPE_APPLICATION, "parentWindow");
@@ -68,6 +69,7 @@
assertEquals(new InsetsState(), getController().getInsetsForDispatch(navBar));
}
+ @FlakyTest(bugId = 124088319)
@Test
public void testBarControllingWinChanged() {
final WindowState navBar = createWindow(null, TYPE_APPLICATION, "parentWindow");
@@ -80,6 +82,7 @@
assertEquals(2, controls.length);
}
+ @FlakyTest(bugId = 124088319)
@Test
public void testControlRevoked() {
final WindowState topBar = createWindow(null, TYPE_APPLICATION, "parentWindow");
@@ -91,6 +94,7 @@
assertNull(getController().getControlsForDispatch(app));
}
+ @FlakyTest(bugId = 124088319)
@Test
public void testControlRevoked_animation() {
final WindowState topBar = createWindow(null, TYPE_APPLICATION, "parentWindow");
diff --git a/services/tests/wmtests/src/com/android/server/wm/PendingRemoteAnimationRegistryTest.java b/services/tests/wmtests/src/com/android/server/wm/PendingRemoteAnimationRegistryTest.java
index 86bf3db..b769fce 100644
--- a/services/tests/wmtests/src/com/android/server/wm/PendingRemoteAnimationRegistryTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/PendingRemoteAnimationRegistryTest.java
@@ -24,7 +24,6 @@
import android.platform.test.annotations.Presubmit;
import android.view.RemoteAnimationAdapter;
-import androidx.test.filters.FlakyTest;
import androidx.test.filters.SmallTest;
import com.android.server.testutils.OffsettableClock;
diff --git a/services/tests/wmtests/src/com/android/server/wm/PersisterQueueTests.java b/services/tests/wmtests/src/com/android/server/wm/PersisterQueueTests.java
index c3d2f33..8327440 100644
--- a/services/tests/wmtests/src/com/android/server/wm/PersisterQueueTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/PersisterQueueTests.java
@@ -28,7 +28,6 @@
import android.os.SystemClock;
import android.platform.test.annotations.Presubmit;
-import androidx.test.filters.FlakyTest;
import androidx.test.filters.MediumTest;
import org.junit.After;
diff --git a/services/tests/wmtests/src/com/android/server/wm/RootActivityContainerTests.java b/services/tests/wmtests/src/com/android/server/wm/RootActivityContainerTests.java
index 67ee4ad..94def2b 100644
--- a/services/tests/wmtests/src/com/android/server/wm/RootActivityContainerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RootActivityContainerTests.java
@@ -67,6 +67,7 @@
import org.junit.Test;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
/**
@@ -142,7 +143,8 @@
private static void ensureStackPlacement(ActivityStack stack, TaskRecord... tasks) {
final ArrayList<TaskRecord> stackTasks = stack.getAllTasks();
- assertEquals(stackTasks.size(), tasks != null ? tasks.length : 0);
+ assertEquals("Expecting " + Arrays.deepToString(tasks) + " got " + stackTasks,
+ stackTasks.size(), tasks != null ? tasks.length : 0);
if (tasks == null) {
return;
diff --git a/services/tests/wmtests/src/com/android/server/wm/SafeActivityOptionsTest.java b/services/tests/wmtests/src/com/android/server/wm/SafeActivityOptionsTest.java
index dad6c95..7111852 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SafeActivityOptionsTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SafeActivityOptionsTest.java
@@ -21,7 +21,6 @@
import android.app.ActivityOptions;
import android.platform.test.annotations.Presubmit;
-import androidx.test.filters.FlakyTest;
import androidx.test.filters.MediumTest;
import org.junit.Test;
diff --git a/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimationRunnerTest.java b/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimationRunnerTest.java
index dfdbf32..6cce9f0 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimationRunnerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimationRunnerTest.java
@@ -167,7 +167,6 @@
verify(mMockAnimationSpec, atLeastOnce()).apply(any(), any(), eq(0L));
}
- @FlakyTest(bugId = 74780584)
@Test
public void testDeferStartingAnimations() throws Exception {
mSurfaceAnimationRunner.deferStartingAnimations();
diff --git a/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimatorTest.java b/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimatorTest.java
index 8c32e8c..88ac96d 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimatorTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SurfaceAnimatorTest.java
@@ -34,7 +34,6 @@
import android.view.SurfaceControl.Transaction;
import android.view.SurfaceSession;
-import androidx.test.filters.FlakyTest;
import androidx.test.filters.SmallTest;
import com.android.server.wm.SurfaceAnimator.Animatable;
@@ -51,7 +50,7 @@
* Test class for {@link SurfaceAnimatorTest}.
*
* Build/Install/Run:
- * atest FrameworksServicesTests:SurfaceAnimatorTest
+ * atest WmTests:SurfaceAnimatorTest
*/
@SmallTest
@Presubmit
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskPersisterTest.java b/services/tests/wmtests/src/com/android/server/wm/TaskPersisterTest.java
index 12ed3c2..9dfeadf 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskPersisterTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskPersisterTest.java
@@ -29,8 +29,6 @@
import android.platform.test.annotations.Presubmit;
import android.util.SparseBooleanArray;
-import androidx.test.filters.FlakyTest;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskPositioningControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskPositioningControllerTests.java
index 8c6ac23..1e58e41 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskPositioningControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskPositioningControllerTests.java
@@ -43,7 +43,6 @@
* Build/Install/Run:
* atest FrameworksServicesTests:TaskPositioningControllerTests
*/
-@FlakyTest(bugId = 117924387)
@SmallTest
@Presubmit
public class TaskPositioningControllerTests extends WindowTestsBase {
@@ -90,6 +89,7 @@
assertNull(mTarget.getDragWindowHandleLocked());
}
+ @FlakyTest(bugId = 69229402)
@Test
public void testHandleTapOutsideTask() {
synchronized (mWm.mGlobalLock) {
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskStackChangedListenerTest.java b/services/tests/wmtests/src/com/android/server/wm/TaskStackChangedListenerTest.java
index 4a734e5..dcca316 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskStackChangedListenerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskStackChangedListenerTest.java
@@ -35,9 +35,11 @@
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.RemoteException;
+import android.platform.test.annotations.Presubmit;
import android.support.test.uiautomator.UiDevice;
import android.text.TextUtils;
+import androidx.test.filters.FlakyTest;
import androidx.test.filters.MediumTest;
import com.android.internal.annotations.GuardedBy;
@@ -76,6 +78,7 @@
}
@Test
+ @Presubmit
public void testTaskStackChanged_afterFinish() throws Exception {
registerTaskStackChangedListener(new TaskStackListener() {
@Override
@@ -87,7 +90,8 @@
});
Context context = getInstrumentation().getContext();
- context.startActivity(new Intent(context, ActivityA.class));
+ context.startActivity(
+ new Intent(context, ActivityA.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
UiDevice.getInstance(getInstrumentation()).waitForIdle();
synchronized (sLock) {
assertTrue(sTaskStackChangedCalled);
@@ -96,6 +100,7 @@
}
@Test
+ @FlakyTest(bugId = 119893767)
public void testTaskDescriptionChanged() throws Exception {
final Object[] params = new Object[2];
final CountDownLatch latch = new CountDownLatch(1);
@@ -124,6 +129,7 @@
}
@Test
+ @FlakyTest(bugId = 119893767)
public void testActivityRequestedOrientationChanged() throws Exception {
final int[] params = new int[2];
final CountDownLatch latch = new CountDownLatch(1);
@@ -146,6 +152,7 @@
* Tests for onTaskCreated, onTaskMovedToFront, onTaskRemoved and onTaskRemovalStarted.
*/
@Test
+ @FlakyTest(bugId = 119893767)
public void testTaskChangeCallBacks() throws Exception {
final Object[] params = new Object[2];
final CountDownLatch taskCreatedLaunchLatch = new CountDownLatch(1);
@@ -221,7 +228,8 @@
final ActivityMonitor monitor = new ActivityMonitor(activityClass.getName(), null, false);
getInstrumentation().addMonitor(monitor);
final Context context = getInstrumentation().getContext();
- context.startActivity(new Intent(context, activityClass));
+ context.startActivity(
+ new Intent(context, activityClass).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
final TestActivity activity = (TestActivity) monitor.waitForActivityWithTimeout(1000);
if (activity == null) {
throw new RuntimeException("Timed out waiting for Activity");
diff --git a/services/tests/wmtests/src/com/android/server/wm/TestSystemServices.java b/services/tests/wmtests/src/com/android/server/wm/TestSystemServices.java
index b151fb7..e540b3a 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TestSystemServices.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TestSystemServices.java
@@ -61,7 +61,7 @@
import org.mockito.invocation.InvocationOnMock;
import org.mockito.quality.Strictness;
-import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.atomic.AtomicBoolean;
/**
* A Test utility class to create a mock {@link WindowManagerService} instance for tests.
@@ -71,6 +71,8 @@
private static WindowManagerService sService;
private static TestWindowManagerPolicy sPolicy;
+ static AtomicBoolean sCurrentMessagesProcessed = new AtomicBoolean(false);
+
static void setUpWindowManagerService() {
sMockitoSession = mockitoSession()
.spyStatic(LockGuard.class)
@@ -88,6 +90,7 @@
sPolicy = null;
sMockitoSession.finishMocking();
+ sMockitoSession = null;
}
private static void setUpTestWindowService() {
@@ -194,21 +197,23 @@
}
private static void waitHandlerIdle(Handler handler) {
- if (!handler.hasMessagesOrCallbacks()) {
- return;
- }
- final CountDownLatch latch = new CountDownLatch(1);
- // Wait for delayed messages are processed.
- handler.getLooper().getQueue().addIdleHandler(() -> {
- if (handler.hasMessagesOrCallbacks()) {
- return true; // keep idle handler.
+ synchronized (sCurrentMessagesProcessed) {
+ // Add a message to the handler queue and make sure it is fully processed before we move
+ // on. This makes sure all previous messages in the handler are fully processed vs. just
+ // popping them from the message queue.
+ sCurrentMessagesProcessed.set(false);
+ handler.post(() -> {
+ synchronized (sCurrentMessagesProcessed) {
+ sCurrentMessagesProcessed.set(true);
+ sCurrentMessagesProcessed.notifyAll();
+ }
+ });
+ while (!sCurrentMessagesProcessed.get()) {
+ try {
+ sCurrentMessagesProcessed.wait();
+ } catch (InterruptedException e) {
+ }
}
- latch.countDown();
- return false; // remove idle handler.
- });
- try {
- latch.await();
- } catch (InterruptedException e) {
}
}
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/TestWindowManagerPolicy.java b/services/tests/wmtests/src/com/android/server/wm/TestWindowManagerPolicy.java
index bfb9193..849772a 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TestWindowManagerPolicy.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TestWindowManagerPolicy.java
@@ -156,7 +156,8 @@
}
@Override
- public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
+ public int interceptMotionBeforeQueueingNonInteractive(int displayId, long whenNanos,
+ int policyFlags) {
return 0;
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowConfigurationTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowConfigurationTests.java
index 64ceb1b..d6608f1 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowConfigurationTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowConfigurationTests.java
@@ -49,7 +49,7 @@
* Test class to for {@link android.app.WindowConfiguration}.
*
* Build/Install/Run:
- * atest FrameworksServicesTests:WindowConfigurationTests
+ * atest WmTests:WindowConfigurationTests
*/
@SmallTest
@Presubmit
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowContainerControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowContainerControllerTests.java
index af8ccc9..fc78635 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowContainerControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowContainerControllerTests.java
@@ -26,7 +26,6 @@
import android.content.res.Configuration;
import android.platform.test.annotations.Presubmit;
-import androidx.test.filters.FlakyTest;
import androidx.test.filters.SmallTest;
import org.junit.Test;
@@ -35,7 +34,7 @@
* Test class for {@link WindowContainerController}.
*
* Build/Install/Run:
- * atest FrameworksServicesTests:WindowContainerControllerTests
+ * atest WmTests:WindowContainerControllerTests
*/
@SmallTest
@Presubmit
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java
index a9a76c2..b93c994 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java
@@ -47,7 +47,6 @@
import android.view.SurfaceControl;
import android.view.SurfaceSession;
-import androidx.test.filters.FlakyTest;
import androidx.test.filters.SmallTest;
import org.junit.Test;
@@ -59,11 +58,10 @@
* Test class for {@link WindowContainer}.
*
* Build/Install/Run:
- * atest FrameworksServicesTests:WindowContainerTests
+ * atest WmTests:WindowContainerTests
*/
@SmallTest
@Presubmit
-@FlakyTest(bugId = 74078662)
public class WindowContainerTests extends WindowTestsBase {
@Test
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowFrameTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowFrameTests.java
index 0a4a8a4..fb30f8b 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowFrameTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowFrameTests.java
@@ -449,8 +449,7 @@
// Now simulate switch to fullscreen for letterboxed app.
final int xInset = logicalWidth / 10;
- final int yInset = logicalWidth / 10;
- final Rect cf = new Rect(xInset, yInset, logicalWidth - xInset, logicalHeight - yInset);
+ final Rect cf = new Rect(xInset, 0, logicalWidth - xInset, logicalHeight);
Configuration config = new Configuration(w.mAppToken.getRequestedOverrideConfiguration());
config.windowConfiguration.setBounds(cf);
w.mAppToken.onRequestedOverrideConfigurationChanged(config);
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java b/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java
index a494889..114eac9 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java
@@ -151,6 +151,7 @@
/** Used so we can gain access to some protected members of the {@link AppWindowToken} class. */
public static class TestAppWindowToken extends AppWindowToken {
boolean mOnTop = false;
+ private boolean mSkipPrepareSurfaces;
private Transaction mPendingTransactionOverride;
boolean mSkipOnParentChanged = true;
@@ -213,6 +214,17 @@
return mOnTop;
}
+ @Override
+ void prepareSurfaces() {
+ if (!mSkipPrepareSurfaces) {
+ super.prepareSurfaces();
+ }
+ }
+
+ void setSkipPrepareSurfaces(boolean ignore) {
+ mSkipPrepareSurfaces = ignore;
+ }
+
void setPendingTransaction(Transaction transaction) {
mPendingTransactionOverride = transaction;
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
index 3cb2814..a83bf2a 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
@@ -50,6 +50,7 @@
import android.view.WindowManager;
import com.android.server.AttributeCache;
+import com.android.server.wm.utils.MockTracker;
import org.junit.After;
import org.junit.AfterClass;
@@ -77,6 +78,8 @@
private static int sNextDisplayId = DEFAULT_DISPLAY + 1;
static int sNextStackId = 1000;
+ private static MockTracker sMockTracker;
+
/** Non-default display. */
DisplayContent mDisplayContent;
DisplayInfo mDisplayInfo = new DisplayInfo();
@@ -109,11 +112,18 @@
TestSystemServices.setUpWindowManagerService();
+ // MockTracker needs to be initialized after TestSystemServices because we don't want to
+ // track static mocks.
+ sMockTracker = new MockTracker();
+
sPowerManagerWrapper = mock(WindowState.PowerManagerWrapper.class);
}
@AfterClass
- public static void tearDonwOnceBase() {
+ public static void tearDownOnceBase() {
+ sMockTracker.close();
+ sMockTracker = null;
+
TestSystemServices.tearDownWindowManagerService();
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTokenTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowTokenTests.java
index d556886..4cdbea0 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowTokenTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowTokenTests.java
@@ -28,7 +28,6 @@
import android.platform.test.annotations.Presubmit;
-import androidx.test.filters.FlakyTest;
import androidx.test.filters.SmallTest;
import org.junit.Test;
@@ -37,7 +36,7 @@
* Tests for the {@link WindowToken} class.
*
* Build/Install/Run:
- * atest FrameworksServicesTests:WindowTokenTests
+ * atest WmTests:WindowTokenTests
*/
@SmallTest
@Presubmit
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTracingTest.java b/services/tests/wmtests/src/com/android/server/wm/WindowTracingTest.java
index b6b9a86..3c6e240 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowTracingTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowTracingTest.java
@@ -34,8 +34,8 @@
import android.platform.test.annotations.Presubmit;
import android.testing.DexmakerShareClassLoaderRule;
import android.util.proto.ProtoOutputStream;
+import android.view.Choreographer;
-import androidx.test.filters.FlakyTest;
import androidx.test.filters.SmallTest;
import com.android.internal.util.Preconditions;
@@ -58,7 +58,7 @@
* Test class for {@link WindowTracing}.
*
* Build/Install/Run:
- * atest FrameworksServicesTests:WindowTracingTest
+ * atest WmTests:WindowTracingTest
*/
@SmallTest
@Presubmit
@@ -74,6 +74,8 @@
@Mock
private WindowManagerService mWmMock;
+ @Mock
+ private Choreographer mChoreographer;
private WindowTracing mWindowTracing;
private File mFile;
@@ -85,7 +87,9 @@
mFile = testContext.getFileStreamPath("tracing_test.dat");
mFile.delete();
- mWindowTracing = new WindowTracing(mFile);
+ mWindowTracing = new WindowTracing(mFile, mWmMock, mChoreographer,
+ new WindowManagerGlobalLock());
+ mWindowTracing.setContinuousMode(false /* continuous */, null /* pw */);
}
@After
@@ -113,15 +117,14 @@
@Test
public void trace_discared_whenNotTracing() {
- mWindowTracing.traceStateLocked("where", mWmMock);
+ mWindowTracing.logState("where");
verifyZeroInteractions(mWmMock);
}
@Test
public void trace_dumpsWindowManagerState_whenTracing() throws Exception {
mWindowTracing.startTrace(mock(PrintWriter.class));
- mWindowTracing.traceStateLocked("where", mWmMock);
-
+ mWindowTracing.logState("where");
verify(mWmMock).writeToProtoLocked(any(), eq(WindowTraceLogLevel.TRIM));
}
@@ -147,7 +150,7 @@
WindowManagerTraceProto.WHERE, "TEST_WM_PROTO");
return null;
}).when(mWmMock).writeToProtoLocked(any(), any());
- mWindowTracing.traceStateLocked("TEST_WHERE", mWmMock);
+ mWindowTracing.logState("TEST_WHERE");
mWindowTracing.stopTrace(mock(PrintWriter.class));
diff --git a/services/tests/wmtests/src/com/android/server/wm/ZOrderingTests.java b/services/tests/wmtests/src/com/android/server/wm/ZOrderingTests.java
index 3dcea75..f3b8a62 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ZOrderingTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ZOrderingTests.java
@@ -51,9 +51,8 @@
* Tests for the {@link DisplayContent#assignChildLayers(SurfaceControl.Transaction)} method.
*
* Build/Install/Run:
- * atest FrameworksServicesTests:ZOrderingTests
+ * atest WmTests:ZOrderingTests
*/
-@FlakyTest(bugId = 74078662)
@SmallTest
@Presubmit
public class ZOrderingTests extends WindowTestsBase {
@@ -207,6 +206,7 @@
return createWindow(null, TYPE_BASE_APPLICATION, mDisplayContent, name);
}
+ @FlakyTest(bugId = 124088319)
@Test
public void testAssignWindowLayers_ForImeWithNoTarget() {
mDisplayContent.mInputMethodTarget = null;
@@ -224,6 +224,7 @@
assertWindowHigher(mImeDialogWindow, mImeWindow);
}
+ @FlakyTest(bugId = 124088319)
@Test
public void testAssignWindowLayers_ForImeWithAppTarget() {
final WindowState imeAppTarget = createWindow("imeAppTarget");
@@ -243,6 +244,7 @@
assertWindowHigher(mImeDialogWindow, mImeWindow);
}
+ @FlakyTest(bugId = 124088319)
@Test
public void testAssignWindowLayers_ForImeWithAppTargetWithChildWindows() {
final WindowState imeAppTarget = createWindow("imeAppTarget");
@@ -269,6 +271,7 @@
assertWindowHigher(mImeDialogWindow, mImeWindow);
}
+ @FlakyTest(bugId = 124088319)
@Test
public void testAssignWindowLayers_ForImeWithAppTargetAndAppAbove() {
final WindowState appBelowImeTarget = createWindow("appBelowImeTarget");
@@ -292,6 +295,7 @@
assertWindowHigher(mImeDialogWindow, mImeWindow);
}
+ @FlakyTest(bugId = 124088319)
@Test
public void testAssignWindowLayers_ForImeNonAppImeTarget() {
final WindowState imeSystemOverlayTarget = createWindow(null, TYPE_SYSTEM_OVERLAY,
@@ -319,6 +323,7 @@
assertWindowHigher(mImeDialogWindow, mImeWindow);
}
+ @FlakyTest(bugId = 124088319)
@Test
public void testAssignWindowLayers_ForStatusBarImeTarget() {
mDisplayContent.mInputMethodTarget = mStatusBarWindow;
@@ -333,6 +338,7 @@
assertWindowHigher(mImeDialogWindow, mImeWindow);
}
+ @FlakyTest(bugId = 124088319)
@Test
public void testStackLayers() {
final WindowState anyWindow1 = createWindow("anyWindow");
@@ -398,6 +404,7 @@
assertWindowHigher(mediaOverlayChild, child);
}
+ @FlakyTest(bugId = 124088319)
@Test
public void testDockedDividerPosition() {
final WindowState pinnedStackWindow = createWindowOnStack(null, WINDOWING_MODE_PINNED,
diff --git a/services/tests/wmtests/src/com/android/server/wm/utils/MockTracker.java b/services/tests/wmtests/src/com/android/server/wm/utils/MockTracker.java
new file mode 100644
index 0000000..1ce463b
--- /dev/null
+++ b/services/tests/wmtests/src/com/android/server/wm/utils/MockTracker.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.wm.utils;
+
+import android.util.Log;
+
+import org.mockito.Mockito;
+import org.mockito.MockitoFramework;
+import org.mockito.internal.creation.settings.CreationSettings;
+import org.mockito.listeners.MockCreationListener;
+import org.mockito.mock.MockCreationSettings;
+
+import java.lang.reflect.Field;
+import java.util.IdentityHashMap;
+
+/**
+ * An util class used to track mock creation, and reset them when closing. Note only one instance is
+ * allowed at anytime, as Mockito framework throws exception if there is already a listener of the
+ * same type registered.
+ */
+public class MockTracker implements MockCreationListener, AutoCloseable {
+ private static final String TAG = "MockTracker";
+
+ private static final Field SPIED_INSTANCE_FIELD;
+
+ static {
+ try {
+ SPIED_INSTANCE_FIELD = CreationSettings.class.getDeclaredField("spiedInstance");
+ SPIED_INSTANCE_FIELD.setAccessible(true);
+ } catch (NoSuchFieldException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private final MockitoFramework mMockitoFramework = Mockito.framework();
+
+ private final IdentityHashMap<Object, Void> mMocks = new IdentityHashMap<>();
+
+ public MockTracker() {
+ mMockitoFramework.addListener(this);
+ }
+
+ @Override
+ public void onMockCreated(Object mock, MockCreationSettings settings) {
+ mMocks.put(mock, null);
+ clearSpiedInstanceIfNeeded(mock, settings);
+ }
+
+ // HACK: Changing Mockito core implementation details.
+ // TODO(b/123984854): Remove this once there is a real fix.
+ private void clearSpiedInstanceIfNeeded(Object mock, MockCreationSettings settings) {
+ if (mock != settings.getSpiedInstance()) {
+ // Not a spyOn instance.
+ return;
+ }
+ if (!(settings instanceof CreationSettings)) {
+ throw new IllegalStateException("Unexpected type of settings: " + settings.getClass());
+ }
+ try {
+ SPIED_INSTANCE_FIELD.set(settings, null);
+ Log.d(TAG, "Setting spiedInstance for " + mock + " to null.");
+ } catch (IllegalAccessException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public void close() {
+ mMockitoFramework.removeListener(this);
+
+ for (final Object mock : mMocks.keySet()) {
+ try {
+ Mockito.reset(mock);
+ } catch (Exception e) {
+ Log.e(TAG, "Failed to reset " + mock, e);
+ }
+ }
+ mMocks.clear();
+ }
+}
diff --git a/services/usage/java/com/android/server/usage/AppTimeLimitController.java b/services/usage/java/com/android/server/usage/AppTimeLimitController.java
index 873ada0..731cbf4 100644
--- a/services/usage/java/com/android/server/usage/AppTimeLimitController.java
+++ b/services/usage/java/com/android/server/usage/AppTimeLimitController.java
@@ -840,7 +840,8 @@
*/
public void addAppUsageLimitObserver(int requestingUid, int observerId, String[] observed,
long timeLimit, PendingIntent callbackIntent, @UserIdInt int userId) {
- if (timeLimit < getMinTimeLimit()) {
+ // Allow the special case of the limit being 0, but with no callback.
+ if (timeLimit != 0L && timeLimit < getMinTimeLimit()) {
throw new IllegalArgumentException("Time limit must be >= " + getMinTimeLimit());
}
synchronized (mLock) {
@@ -858,7 +859,7 @@
"Too many app usage observers added by uid " + requestingUid);
}
group = new AppUsageLimitGroup(user, observerApp, observerId, observed, timeLimit,
- callbackIntent);
+ timeLimit == 0L ? null : callbackIntent);
observerApp.appUsageLimitGroups.append(observerId, group);
if (DEBUG) {
diff --git a/services/usage/java/com/android/server/usage/UsageStatsService.java b/services/usage/java/com/android/server/usage/UsageStatsService.java
index df2f455..af5278f 100644
--- a/services/usage/java/com/android/server/usage/UsageStatsService.java
+++ b/services/usage/java/com/android/server/usage/UsageStatsService.java
@@ -1377,7 +1377,7 @@
if (packages == null || packages.length == 0) {
throw new IllegalArgumentException("Must specify at least one package");
}
- if (callbackIntent == null) {
+ if (callbackIntent == null && timeLimitMs != 0L) {
throw new NullPointerException("callbackIntent can't be null");
}
final int callingUid = Binder.getCallingUid();
diff --git a/telecomm/java/android/telecom/DefaultDialerManager.java b/telecomm/java/android/telecom/DefaultDialerManager.java
index aac0956d..e43b2b7 100644
--- a/telecomm/java/android/telecom/DefaultDialerManager.java
+++ b/telecomm/java/android/telecom/DefaultDialerManager.java
@@ -22,7 +22,6 @@
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
-import android.content.pm.ServiceInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Binder;
@@ -163,9 +162,7 @@
final Intent dialIntentWithTelScheme = new Intent(Intent.ACTION_DIAL);
dialIntentWithTelScheme.setData(Uri.fromParts(PhoneAccount.SCHEME_TEL, "", null));
- packageNames = filterByIntent(context, packageNames, dialIntentWithTelScheme, userId);
- packageNames = requireInCallService(packageNames, userId, context);
- return packageNames;
+ return filterByIntent(context, packageNames, dialIntentWithTelScheme, userId);
}
public static List<String> getInstalledDialerApplications(Context context) {
@@ -223,35 +220,6 @@
return result;
}
- private static List<String> requireInCallService(List<String> packageNames, int userId,
- Context context) {
- if (packageNames == null || packageNames.isEmpty()) {
- return new ArrayList<>();
- }
-
- final Intent intent = new Intent(InCallService.SERVICE_INTERFACE);
- final List<ResolveInfo> resolveInfoList = context.getPackageManager()
- .queryIntentServicesAsUser(intent, PackageManager.GET_META_DATA, userId);
- final List<String> result = new ArrayList<>();
- final int length = resolveInfoList.size();
- for (int i = 0; i < length; i++) {
- final ServiceInfo info = resolveInfoList.get(i).serviceInfo;
- if (info == null || info.metaData == null) {
- continue;
- }
- if (!info.metaData.getBoolean(TelecomManager.METADATA_IN_CALL_SERVICE_UI)) {
- continue;
- }
- if (info.metaData.getBoolean(TelecomManager.METADATA_IN_CALL_SERVICE_CAR_MODE_UI)) {
- continue;
- }
- if (packageNames.contains(info.packageName) && !result.contains(info.packageName)) {
- result.add(info.packageName);
- }
- }
-
- return result;
- }
private static TelecomManager getTelecomManager(Context context) {
return (TelecomManager) context.getSystemService(Context.TELECOM_SERVICE);
diff --git a/telecomm/java/android/telecom/TelecomManager.java b/telecomm/java/android/telecom/TelecomManager.java
index e99a289..d509168 100644
--- a/telecomm/java/android/telecom/TelecomManager.java
+++ b/telecomm/java/android/telecom/TelecomManager.java
@@ -291,6 +291,19 @@
"android.telecom.extra.OUTGOING_CALL_EXTRAS";
/**
+ * An optional boolean extra on {@link android.content.Intent#ACTION_CALL_EMERGENCY} to tell
+ * whether the user's dial intent is emergency; this is required to specify when the dialed
+ * number is ambiguous, identified as both emergency number and any other non-emergency number;
+ * e.g. in some situation, 611 could be both an emergency number in a country and a
+ * non-emergency number of a carrier's customer service hotline.
+ *
+ * @hide
+ */
+ @SystemApi
+ public static final String EXTRA_IS_USER_INTENT_EMERGENCY_CALL =
+ "android.telecom.extra.IS_USER_INTENT_EMERGENCY_CALL";
+
+ /**
* @hide
*/
public static final String EXTRA_UNKNOWN_CALL_HANDLE =
diff --git a/telephony/java/android/provider/Telephony.java b/telephony/java/android/provider/Telephony.java
index 4539ab3..a1c32b5 100644
--- a/telephony/java/android/provider/Telephony.java
+++ b/telephony/java/android/provider/Telephony.java
@@ -2717,6 +2717,41 @@
Uri RCS_EVENT_QUERY_URI = Uri.withAppendedPath(CONTENT_AND_AUTHORITY,
RCS_EVENT_QUERY_URI_PATH);
}
+
+ /**
+ * Allows RCS specific canonical address handling.
+ */
+ interface RcsCanonicalAddressHelper {
+ /**
+ * Returns the canonical address ID for a canonical address, if now row exists, this
+ * will add a row and return its ID. This helper works against the same table used by
+ * the SMS and MMS threads, but is accessible only by the phone process for use by RCS
+ * message storage.
+ *
+ * @throws IllegalArgumentException if unable to retrieve or create the canonical
+ * address entry.
+ */
+ static long getOrCreateCanonicalAddressId(
+ ContentResolver contentResolver, String canonicalAddress) {
+
+ Uri.Builder uriBuilder = CONTENT_AND_AUTHORITY.buildUpon();
+ uriBuilder.appendPath("canonical-address");
+ uriBuilder.appendQueryParameter("address", canonicalAddress);
+ Uri uri = uriBuilder.build();
+
+ try (Cursor cursor = contentResolver.query(uri, null, null, null)) {
+ if (cursor != null && cursor.moveToFirst()) {
+ return cursor.getLong(cursor.getColumnIndex(CanonicalAddressesColumns._ID));
+ } else {
+ Rlog.e(TAG, "getOrCreateCanonicalAddressId returned no rows");
+ }
+ }
+
+ Rlog.e(TAG, "getOrCreateCanonicalAddressId failed");
+ throw new IllegalArgumentException(
+ "Unable to find or allocate a canonical address ID");
+ }
+ }
}
/**
diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java
index 068b68e..1b7228a 100644
--- a/telephony/java/android/telephony/CarrierConfigManager.java
+++ b/telephony/java/android/telephony/CarrierConfigManager.java
@@ -2424,6 +2424,14 @@
"5g_icon_configuration_string";
/**
+ * Support ASCII 7-BIT encoding for long SMS. This carrier config is used to enable
+ * this feature.
+ * @hide
+ */
+ public static final String KEY_ASCII_7_BIT_SUPPORT_FOR_LONG_MESSAGE_BOOL =
+ "ascii_7_bit_support_for_long_message_bool";
+
+ /**
* Controls RSRP threshold at which OpportunisticNetworkService will decide whether
* the opportunistic network is good enough for internet data.
*/
@@ -2589,6 +2597,16 @@
}
}
+ /**
+ * An int array containing CDMA enhanced roaming indicator values for Home (non-roaming) network.
+ * The default values come from 3GPP2 C.R1001 table 8.1-1.
+ * Enhanced Roaming Indicator Number Assignments
+ *
+ * @hide
+ */
+ public static final String KEY_CDMA_ENHANCED_ROAMING_INDICATOR_FOR_HOME_NETWORK_INT_ARRAY =
+ "cdma_enhanced_roaming_indicator_for_home_network_int_array";
+
/** The default value for every variable. */
private final static PersistableBundle sDefaults;
@@ -2951,6 +2969,7 @@
sDefaults.putInt(KEY_CALL_WAITING_SERVICE_CLASS_INT, 1 /* SERVICE_CLASS_VOICE */);
sDefaults.putString(KEY_5G_ICON_CONFIGURATION_STRING,
"connected_mmwave:None,connected:5G,not_restricted:None,restricted:None");
+ sDefaults.putBoolean(KEY_ASCII_7_BIT_SUPPORT_FOR_LONG_MESSAGE_BOOL, false);
/* Default value is minimum RSRP level needed for SIGNAL_STRENGTH_GOOD */
sDefaults.putInt(KEY_OPPORTUNISTIC_NETWORK_ENTRY_THRESHOLD_RSRP_INT, -108);
/* Default value is minimum RSRP level needed for SIGNAL_STRENGTH_MODERATE */
@@ -2966,6 +2985,10 @@
/* Default value is 10 seconds. */
sDefaults.putInt(KEY_OPPORTUNISTIC_NETWORK_DATA_SWITCH_HYSTERESIS_TIME_LONG, 10000);
sDefaults.putAll(Gps.getDefaults());
+ sDefaults.putIntArray(KEY_CDMA_ENHANCED_ROAMING_INDICATOR_FOR_HOME_NETWORK_INT_ARRAY,
+ new int[] {
+ 1 /* Roaming Indicator Off */
+ });
}
/**
diff --git a/telephony/java/android/telephony/CarrierRestrictionRules.java b/telephony/java/android/telephony/CarrierRestrictionRules.java
index 37847ae..d47b55c 100644
--- a/telephony/java/android/telephony/CarrierRestrictionRules.java
+++ b/telephony/java/android/telephony/CarrierRestrictionRules.java
@@ -27,6 +27,7 @@
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
+import java.util.Objects;
/**
* Contains the list of carrier restrictions.
@@ -93,6 +94,9 @@
value = {CARRIER_RESTRICTION_DEFAULT_NOT_ALLOWED, CARRIER_RESTRICTION_DEFAULT_ALLOWED})
public @interface CarrierRestrictionDefault {}
+ /* Wild character for comparison */
+ private static final char WILD_CHARACTER = '?';
+
private List<CarrierIdentifier> mAllowedCarriers;
private List<CarrierIdentifier> mExcludedCarriers;
@CarrierRestrictionDefault
@@ -166,6 +170,124 @@
}
/**
+ * Tests an array of carriers with the carrier restriction configuration. The list of carrier
+ * ids passed as argument does not need to be the same as currently present in the device.
+ *
+ * @param carrierIds list of {@link CarrierIdentifier}, one for each SIM slot on the device
+ * @return a list of boolean with the same size as input, indicating if each
+ * {@link CarrierIdentifier} is allowed or not.
+ */
+ public List<Boolean> isCarrierIdentifiersAllowed(@NonNull List<CarrierIdentifier> carrierIds) {
+ ArrayList<Boolean> result = new ArrayList<>(carrierIds.size());
+
+ // First calculate the result for each slot independently
+ for (int i = 0; i < carrierIds.size(); i++) {
+ boolean inAllowedList = isCarrierIdInList(carrierIds.get(i), mAllowedCarriers);
+ boolean inExcludedList = isCarrierIdInList(carrierIds.get(i), mExcludedCarriers);
+ if (mCarrierRestrictionDefault == CARRIER_RESTRICTION_DEFAULT_NOT_ALLOWED) {
+ result.add((inAllowedList && !inExcludedList) ? true : false);
+ } else {
+ result.add((inExcludedList && !inAllowedList) ? false : true);
+ }
+ }
+ // Apply the multi-slot policy, if needed.
+ if (mMultiSimPolicy == MULTISIM_POLICY_ONE_VALID_SIM_MUST_BE_PRESENT) {
+ for (boolean b : result) {
+ if (b) {
+ result.replaceAll(x -> true);
+ break;
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Indicates if a certain carrier {@code id} is present inside a {@code list}
+ *
+ * @return true if the carrier {@code id} is present, false otherwise
+ */
+ private static boolean isCarrierIdInList(CarrierIdentifier id, List<CarrierIdentifier> list) {
+ for (CarrierIdentifier listItem : list) {
+ // Compare MCC and MNC
+ if (!patternMatch(id.getMcc(), listItem.getMcc())
+ || !patternMatch(id.getMnc(), listItem.getMnc())) {
+ continue;
+ }
+
+ // Compare SPN. Comparison is on the complete strings, case insensitive and with wild
+ // characters.
+ String listItemValue = convertNullToEmpty(listItem.getSpn());
+ String idValue = convertNullToEmpty(id.getSpn());
+ if (!listItemValue.isEmpty()) {
+ if (!patternMatch(idValue, listItemValue)) {
+ continue;
+ }
+ }
+
+ // The IMSI of the configuration can be shorter than actual IMSI in the SIM card.
+ listItemValue = convertNullToEmpty(listItem.getImsi());
+ idValue = convertNullToEmpty(id.getImsi());
+ if (!patternMatch(
+ idValue.substring(0, Math.min(idValue.length(), listItemValue.length())),
+ listItemValue)) {
+ continue;
+ }
+
+ // The GID1 of the configuration can be shorter than actual GID1 in the SIM card.
+ listItemValue = convertNullToEmpty(listItem.getGid1());
+ idValue = convertNullToEmpty(id.getGid1());
+ if (!patternMatch(
+ idValue.substring(0, Math.min(idValue.length(), listItemValue.length())),
+ listItemValue)) {
+ continue;
+ }
+
+ // The GID2 of the configuration can be shorter than actual GID2 in the SIM card.
+ listItemValue = convertNullToEmpty(listItem.getGid2());
+ idValue = convertNullToEmpty(id.getGid2());
+ if (!patternMatch(
+ idValue.substring(0, Math.min(idValue.length(), listItemValue.length())),
+ listItemValue)) {
+ continue;
+ }
+
+ // Valid match was found in the list
+ return true;
+ }
+ return false;
+ }
+
+ private static String convertNullToEmpty(String value) {
+ return Objects.toString(value, "");
+ }
+
+ /**
+ * Performs a case insensitive string comparison against a given pattern. The character '?'
+ * is used in the pattern as wild character in the comparison. The string must have the same
+ * length as the pattern.
+ *
+ * @param str string to match
+ * @param pattern string containing the pattern
+ * @return true in case of match, false otherwise
+ */
+ private static boolean patternMatch(String str, String pattern) {
+ if (str.length() != pattern.length()) {
+ return false;
+ }
+ String lowerCaseStr = str.toLowerCase();
+ String lowerCasePattern = pattern.toLowerCase();
+
+ for (int i = 0; i < lowerCasePattern.length(); i++) {
+ if (lowerCasePattern.charAt(i) != lowerCaseStr.charAt(i)
+ && lowerCasePattern.charAt(i) != WILD_CHARACTER) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
* {@link Parcelable#writeToParcel}
*/
@Override
diff --git a/telephony/java/android/telephony/CellIdentityNr.java b/telephony/java/android/telephony/CellIdentityNr.java
index 6b1b84c..856f081 100644
--- a/telephony/java/android/telephony/CellIdentityNr.java
+++ b/telephony/java/android/telephony/CellIdentityNr.java
@@ -30,6 +30,7 @@
private final int mNrArfcn;
private final int mPci;
private final int mTac;
+ private final long mNci;
/**
*
@@ -44,11 +45,12 @@
* @hide
*/
public CellIdentityNr(int pci, int tac, int nrArfcn, String mccStr, String mncStr,
- String alphal, String alphas) {
+ long nci, String alphal, String alphas) {
super(TAG, CellInfo.TYPE_NR, mccStr, mncStr, alphal, alphas);
mPci = pci;
mTac = tac;
mNrArfcn = nrArfcn;
+ mNci = nci;
}
/**
@@ -62,7 +64,7 @@
@Override
public int hashCode() {
- return Objects.hash(super.hashCode(), mPci, mTac, mNrArfcn);
+ return Objects.hash(super.hashCode(), mPci, mTac, mNrArfcn, mNci);
}
@Override
@@ -72,7 +74,17 @@
}
CellIdentityNr o = (CellIdentityNr) other;
- return super.equals(o) && mPci == o.mPci && mTac == o.mTac && mNrArfcn == o.mNrArfcn;
+ return super.equals(o) && mPci == o.mPci && mTac == o.mTac && mNrArfcn == o.mNrArfcn
+ && mNci == o.mNci;
+ }
+
+ /**
+ * Get the NR Cell Identity.
+ *
+ * @return The NR Cell Identity in range [0, 68719476735] or Long.MAX_VALUE if unknown.
+ */
+ public long getNci() {
+ return mNci;
}
/**
@@ -122,6 +134,7 @@
.append(" mNrArfcn = ").append(mNrArfcn)
.append(" mMcc = ").append(mMccStr)
.append(" mMnc = ").append(mMncStr)
+ .append(" mNci = ").append(mNci)
.append(" mAlphaLong = ").append(mAlphaLong)
.append(" mAlphaShort = ").append(mAlphaShort)
.append(" }")
@@ -134,6 +147,7 @@
dest.writeInt(mPci);
dest.writeInt(mTac);
dest.writeInt(mNrArfcn);
+ dest.writeLong(mNci);
}
/** Construct from Parcel, type has already been processed */
@@ -142,6 +156,7 @@
mPci = in.readInt();
mTac = in.readInt();
mNrArfcn = in.readInt();
+ mNci = in.readLong();
}
/** Implement the Parcelable interface */
diff --git a/telephony/java/android/telephony/CellIdentityTdscdma.java b/telephony/java/android/telephony/CellIdentityTdscdma.java
index 3814333..dba437a 100644
--- a/telephony/java/android/telephony/CellIdentityTdscdma.java
+++ b/telephony/java/android/telephony/CellIdentityTdscdma.java
@@ -141,6 +141,14 @@
return mCpid;
}
+ /**
+ * @return 16-bit UMTS Absolute RF Channel Number,
+ * {@link android.telephony.CellInfo#UNAVAILABLE UNAVAILABLE} if unavailable.
+ */
+ public int getUarfcn() {
+ return mUarfcn;
+ }
+
/** @hide */
@Override
public int getChannelNumber() {
diff --git a/telephony/java/android/telephony/LocationAccessPolicy.java b/telephony/java/android/telephony/LocationAccessPolicy.java
index 53d69f4..24db438 100644
--- a/telephony/java/android/telephony/LocationAccessPolicy.java
+++ b/telephony/java/android/telephony/LocationAccessPolicy.java
@@ -26,11 +26,12 @@
import android.content.pm.UserInfo;
import android.location.LocationManager;
import android.os.Binder;
+import android.os.Build;
import android.os.Process;
-import android.os.Trace;
import android.os.UserHandle;
import android.os.UserManager;
import android.util.Log;
+import android.widget.Toast;
import java.util.List;
@@ -41,59 +42,234 @@
public final class LocationAccessPolicy {
private static final String TAG = "LocationAccessPolicy";
private static final boolean DBG = false;
+ public static final int MAX_SDK_FOR_ANY_ENFORCEMENT = Build.VERSION_CODES.P;
- /**
- * API to determine if the caller has permissions to get cell location.
- *
- * @param pkgName Package name of the application requesting access
- * @param uid The uid of the package
- * @param pid The pid of the package
- * @param throwOnDeniedPermission Whether to throw if the location permission is denied.
- * @return boolean true or false if permissions is granted
- */
- public static boolean canAccessCellLocation(@NonNull Context context, @NonNull String pkgName,
- int uid, int pid, boolean throwOnDeniedPermission) throws SecurityException {
- Trace.beginSection("TelephonyLocationCheck");
- try {
- // Always allow the phone process and system server to access location. This avoid
- // breaking legacy code that rely on public-facing APIs to access cell location, and
- // it doesn't create an info leak risk because the cell location is stored in the phone
- // process anyway, and the system server already has location access.
- if (uid == Process.PHONE_UID || uid == Process.SYSTEM_UID || uid == Process.ROOT_UID) {
- return true;
- }
+ public enum LocationPermissionResult {
+ ALLOWED,
+ /**
+ * Indicates that the denial is due to a transient device state
+ * (e.g. app-ops, location master switch)
+ */
+ DENIED_SOFT,
+ /**
+ * Indicates that the denial is due to a misconfigured app (e.g. missing entry in manifest)
+ */
+ DENIED_HARD,
+ }
- // We always require the location permission and also require the
- // location mode to be on for non-legacy apps. Legacy apps are
- // required to be in the foreground to at least mitigate the case
- // where a legacy app the user is not using tracks their location.
- // Granting ACCESS_FINE_LOCATION to an app automatically grants it
- // ACCESS_COARSE_LOCATION.
- if (throwOnDeniedPermission) {
- context.enforcePermission(Manifest.permission.ACCESS_COARSE_LOCATION,
- pid, uid, "canAccessCellLocation");
- } else if (context.checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION,
- pid, uid) == PackageManager.PERMISSION_DENIED) {
- if (DBG) Log.w(TAG, "Permission checked failed (" + pid + "," + uid + ")");
- return false;
- }
- final int opCode = AppOpsManager.permissionToOpCode(
- Manifest.permission.ACCESS_COARSE_LOCATION);
- if (opCode != AppOpsManager.OP_NONE && context.getSystemService(AppOpsManager.class)
- .noteOpNoThrow(opCode, uid, pkgName) != AppOpsManager.MODE_ALLOWED) {
- if (DBG) Log.w(TAG, "AppOp check failed (" + uid + "," + pkgName + ")");
- return false;
- }
- if (!isLocationModeEnabled(context, UserHandle.getUserId(uid))) {
- if (DBG) Log.w(TAG, "Location disabled, failed, (" + uid + ")");
- return false;
- }
- // If the user or profile is current, permission is granted.
- // Otherwise, uid must have INTERACT_ACROSS_USERS_FULL permission.
- return isCurrentProfile(context, uid) || checkInteractAcrossUsersFull(context);
- } finally {
- Trace.endSection();
+ public static class LocationPermissionQuery {
+ public final String callingPackage;
+ public final int callingUid;
+ public final int callingPid;
+ public final int minSdkVersionForCoarse;
+ public final int minSdkVersionForFine;
+ public final String method;
+
+ private LocationPermissionQuery(String callingPackage, int callingUid, int callingPid,
+ int minSdkVersionForCoarse, int minSdkVersionForFine, String method) {
+ this.callingPackage = callingPackage;
+ this.callingUid = callingUid;
+ this.callingPid = callingPid;
+ this.minSdkVersionForCoarse = minSdkVersionForCoarse;
+ this.minSdkVersionForFine = minSdkVersionForFine;
+ this.method = method;
}
+
+ public static class Builder {
+ private String mCallingPackage;
+ private int mCallingUid;
+ private int mCallingPid;
+ private int mMinSdkVersionForCoarse = Integer.MAX_VALUE;
+ private int mMinSdkVersionForFine = Integer.MAX_VALUE;
+ private String mMethod;
+
+ /**
+ * Mandatory parameter, used for performing permission checks.
+ */
+ public Builder setCallingPackage(String callingPackage) {
+ mCallingPackage = callingPackage;
+ return this;
+ }
+
+ /**
+ * Mandatory parameter, used for performing permission checks.
+ */
+ public Builder setCallingUid(int callingUid) {
+ mCallingUid = callingUid;
+ return this;
+ }
+
+ /**
+ * Mandatory parameter, used for performing permission checks.
+ */
+ public Builder setCallingPid(int callingPid) {
+ mCallingPid = callingPid;
+ return this;
+ }
+
+ /**
+ * Apps that target at least this sdk version will be checked for coarse location
+ * permission. Defaults to INT_MAX (which means don't check)
+ */
+ public Builder setMinSdkVersionForCoarse(
+ int minSdkVersionForCoarse) {
+ mMinSdkVersionForCoarse = minSdkVersionForCoarse;
+ return this;
+ }
+
+ /**
+ * Apps that target at least this sdk version will be checked for fine location
+ * permission. Defaults to INT_MAX (which means don't check)
+ */
+ public Builder setMinSdkVersionForFine(
+ int minSdkVersionForFine) {
+ mMinSdkVersionForFine = minSdkVersionForFine;
+ return this;
+ }
+
+ /**
+ * Optional, for logging purposes only.
+ */
+ public Builder setMethod(String method) {
+ mMethod = method;
+ return this;
+ }
+
+ public LocationPermissionQuery build() {
+ return new LocationPermissionQuery(mCallingPackage, mCallingUid,
+ mCallingPid, mMinSdkVersionForCoarse, mMinSdkVersionForFine, mMethod);
+ }
+ }
+ }
+
+ private static void logError(Context context, String errorMsg) {
+ Log.e(TAG, errorMsg);
+ try {
+ if (Build.IS_DEBUGGABLE) {
+ Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
+ }
+ } catch (Throwable t) {
+ // whatever, not important
+ }
+ }
+
+ private static LocationPermissionResult appOpsModeToPermissionResult(int appOpsMode) {
+ switch (appOpsMode) {
+ case AppOpsManager.MODE_ALLOWED:
+ return LocationPermissionResult.ALLOWED;
+ case AppOpsManager.MODE_ERRORED:
+ return LocationPermissionResult.DENIED_HARD;
+ default:
+ return LocationPermissionResult.DENIED_SOFT;
+ }
+ }
+
+ private static LocationPermissionResult checkAppLocationPermissionHelper(Context context,
+ LocationPermissionQuery query, String permissionToCheck) {
+ String locationTypeForLog =
+ Manifest.permission.ACCESS_FINE_LOCATION.equals(permissionToCheck)
+ ? "fine" : "coarse";
+
+ // Do the app-ops and the manifest check without any of the allow-overrides first.
+ boolean hasManifestPermission = checkManifestPermission(context, query.callingPid,
+ query.callingUid, permissionToCheck);
+
+ int appOpMode = context.getSystemService(AppOpsManager.class)
+ .noteOpNoThrow(AppOpsManager.permissionToOpCode(permissionToCheck),
+ query.callingUid, query.callingPackage);
+
+ if (hasManifestPermission && appOpMode == AppOpsManager.MODE_ALLOWED) {
+ // If the app did everything right, return without logging.
+ return LocationPermissionResult.ALLOWED;
+ }
+
+ // If the app has the manifest permission but not the app-op permission, it means that
+ // it's aware of the requirement and the user denied permission explicitly. If we see
+ // this, don't let any of the overrides happen.
+ if (hasManifestPermission) {
+ Log.i(TAG, query.callingPackage + " is aware of " + locationTypeForLog + " but the"
+ + " app-ops permission is specifically denied.");
+ return appOpsModeToPermissionResult(appOpMode);
+ }
+
+ int minSdkVersion = Manifest.permission.ACCESS_FINE_LOCATION.equals(permissionToCheck)
+ ? query.minSdkVersionForFine : query.minSdkVersionForCoarse;
+
+ // If the app fails for some reason, see if it should be allowed to proceed.
+ if (minSdkVersion > MAX_SDK_FOR_ANY_ENFORCEMENT) {
+ String errorMsg = "Allowing " + query.callingPackage + " " + locationTypeForLog
+ + " because we're not enforcing API " + query.minSdkVersionForFine + " yet."
+ + " Please fix this app because it will break in the future. Called from "
+ + query.method;
+ logError(context, errorMsg);
+ return null;
+ } else if (!isAppAtLeastSdkVersion(context, query.callingPackage, minSdkVersion)) {
+ String errorMsg = "Allowing " + query.callingPackage + " " + locationTypeForLog
+ + " because it doesn't target API " + query.minSdkVersionForFine + " yet."
+ + " Please fix this app. Called from " + query.method;
+ logError(context, errorMsg);
+ return null;
+ } else {
+ // If we're not allowing it due to the above two conditions, this means that the app
+ // did not declare the permission in their manifest.
+ return LocationPermissionResult.DENIED_HARD;
+ }
+ }
+
+ public static LocationPermissionResult checkLocationPermission(
+ Context context, LocationPermissionQuery query) {
+ // Always allow the phone process and system server to access location. This avoid
+ // breaking legacy code that rely on public-facing APIs to access cell location, and
+ // it doesn't create an info leak risk because the cell location is stored in the phone
+ // process anyway, and the system server already has location access.
+ if (query.callingUid == Process.PHONE_UID || query.callingUid == Process.SYSTEM_UID
+ || query.callingUid == Process.ROOT_UID) {
+ return LocationPermissionResult.ALLOWED;
+ }
+
+ // Check the system-wide requirements. If the location master switch is off or
+ // the app's profile isn't in foreground, return a soft denial.
+ if (!checkSystemLocationAccess(context, query.callingUid, query.callingPid)) {
+ return LocationPermissionResult.DENIED_SOFT;
+ }
+
+ // Do the check for fine, then for coarse.
+ if (query.minSdkVersionForFine < Integer.MAX_VALUE) {
+ LocationPermissionResult resultForFine = checkAppLocationPermissionHelper(
+ context, query, Manifest.permission.ACCESS_FINE_LOCATION);
+ if (resultForFine != null) {
+ return resultForFine;
+ }
+ }
+
+ if (query.minSdkVersionForCoarse < Integer.MAX_VALUE) {
+ LocationPermissionResult resultForCoarse = checkAppLocationPermissionHelper(
+ context, query, Manifest.permission.ACCESS_COARSE_LOCATION);
+ if (resultForCoarse != null) {
+ return resultForCoarse;
+ }
+ }
+
+ // At this point, we're out of location checks to do. If the app bypassed all the previous
+ // ones due to the SDK grandfathering schemes, allow it access.
+ return LocationPermissionResult.ALLOWED;
+ }
+
+
+ private static boolean checkManifestPermission(Context context, int pid, int uid,
+ String permissionToCheck) {
+ return context.checkPermission(permissionToCheck, pid, uid)
+ == PackageManager.PERMISSION_GRANTED;
+ }
+
+ private static boolean checkSystemLocationAccess(@NonNull Context context, int uid, int pid) {
+ if (!isLocationModeEnabled(context, UserHandle.getUserId(uid))) {
+ if (DBG) Log.w(TAG, "Location disabled, failed, (" + uid + ")");
+ return false;
+ }
+ // If the user or profile is current, permission is granted.
+ // Otherwise, uid must have INTERACT_ACROSS_USERS_FULL permission.
+ return isCurrentProfile(context, uid) || checkInteractAcrossUsersFull(context, uid, pid);
}
private static boolean isLocationModeEnabled(@NonNull Context context, @UserIdInt int userId) {
@@ -105,10 +281,10 @@
return locationManager.isLocationEnabledForUser(UserHandle.of(userId));
}
- private static boolean checkInteractAcrossUsersFull(@NonNull Context context) {
- return context.checkCallingOrSelfPermission(
- android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
- == PackageManager.PERMISSION_GRANTED;
+ private static boolean checkInteractAcrossUsersFull(
+ @NonNull Context context, int pid, int uid) {
+ return checkManifestPermission(context, pid, uid,
+ Manifest.permission.INTERACT_ACROSS_USERS_FULL);
}
private static boolean isCurrentProfile(@NonNull Context context, int uid) {
@@ -132,4 +308,18 @@
Binder.restoreCallingIdentity(token);
}
}
-}
+
+ private static boolean isAppAtLeastSdkVersion(Context context, String pkgName, int sdkVersion) {
+ try {
+ if (context.getPackageManager().getApplicationInfo(pkgName, 0).targetSdkVersion
+ >= sdkVersion) {
+ return true;
+ }
+ } catch (PackageManager.NameNotFoundException e) {
+ // In case of exception, assume known app (more strict checking)
+ // Note: This case will never happen since checkPackage is
+ // called to verify validity before checking app's version.
+ }
+ return false;
+ }
+}
\ No newline at end of file
diff --git a/telephony/java/android/telephony/NetworkRegistrationState.java b/telephony/java/android/telephony/NetworkRegistrationState.java
index ceb76b5..6e6d59e 100644
--- a/telephony/java/android/telephony/NetworkRegistrationState.java
+++ b/telephony/java/android/telephony/NetworkRegistrationState.java
@@ -27,6 +27,7 @@
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
import java.util.Objects;
+import java.util.stream.Collectors;
/**
* Description of a mobile network registration state
@@ -151,7 +152,7 @@
private final int[] mAvailableServices;
@Nullable
- private final CellIdentity mCellIdentity;
+ private CellIdentity mCellIdentity;
@Nullable
private VoiceSpecificRegistrationStates mVoiceSpecificStates;
@@ -360,7 +361,34 @@
return 0;
}
- private static String regStateToString(int regState) {
+ /**
+ * Convert service type to string
+ *
+ * @hide
+ *
+ * @param serviceType The service type
+ * @return The service type in string format
+ */
+ public static String serviceTypeToString(@ServiceType int serviceType) {
+ switch (serviceType) {
+ case SERVICE_TYPE_VOICE: return "VOICE";
+ case SERVICE_TYPE_DATA: return "DATA";
+ case SERVICE_TYPE_SMS: return "SMS";
+ case SERVICE_TYPE_VIDEO: return "VIDEO";
+ case SERVICE_TYPE_EMERGENCY: return "EMERGENCY";
+ }
+ return "Unknown service type " + serviceType;
+ }
+
+ /**
+ * Convert registration state to string
+ *
+ * @hide
+ *
+ * @param regState The registration state
+ * @return The reg state in string
+ */
+ public static String regStateToString(@RegState int regState) {
switch (regState) {
case REG_STATE_NOT_REG_NOT_SEARCHING: return "NOT_REG_NOT_SEARCHING";
case REG_STATE_HOME: return "HOME";
@@ -389,14 +417,17 @@
public String toString() {
return new StringBuilder("NetworkRegistrationState{")
.append(" domain=").append((mDomain == DOMAIN_CS) ? "CS" : "PS")
- .append("transportType=").append(mTransportType)
+ .append(" transportType=").append(TransportType.toString(mTransportType))
.append(" regState=").append(regStateToString(mRegState))
- .append(" roamingType=").append(mRoamingType)
+ .append(" roamingType=").append(ServiceState.roamingTypeToString(mRoamingType))
.append(" accessNetworkTechnology=")
.append(TelephonyManager.getNetworkTypeName(mAccessNetworkTechnology))
.append(" rejectCause=").append(mRejectCause)
.append(" emergencyEnabled=").append(mEmergencyOnly)
- .append(" supportedServices=").append(mAvailableServices)
+ .append(" availableServices=").append("[" + (mAvailableServices != null
+ ? Arrays.stream(mAvailableServices)
+ .mapToObj(type -> serviceTypeToString(type))
+ .collect(Collectors.joining(",")) : null) + "]")
.append(" cellIdentity=").append(mCellIdentity)
.append(" voiceSpecificStates=").append(mVoiceSpecificStates)
.append(" dataSpecificStates=").append(mDataSpecificStates)
@@ -490,4 +521,22 @@
return new NetworkRegistrationState[size];
}
};
+
+ /**
+ * @hide
+ */
+ public NetworkRegistrationState sanitizeLocationInfo() {
+ NetworkRegistrationState result = copy();
+ result.mCellIdentity = null;
+ return result;
+ }
+
+ private NetworkRegistrationState copy() {
+ Parcel p = Parcel.obtain();
+ this.writeToParcel(p, 0);
+ p.setDataPosition(0);
+ NetworkRegistrationState result = new NetworkRegistrationState(p);
+ p.recycle();
+ return result;
+ }
}
diff --git a/telephony/java/android/telephony/PhoneStateListener.java b/telephony/java/android/telephony/PhoneStateListener.java
index fea1b7b..3ce646c 100644
--- a/telephony/java/android/telephony/PhoneStateListener.java
+++ b/telephony/java/android/telephony/PhoneStateListener.java
@@ -45,7 +45,8 @@
* <p>
* Override the methods for the state that you wish to receive updates for, and
* pass your PhoneStateListener object, along with bitwise-or of the LISTEN_
- * flags to {@link TelephonyManager#listen TelephonyManager.listen()}.
+ * flags to {@link TelephonyManager#listen TelephonyManager.listen()}. Methods are
+ * called when the state changes, as well as once on initial registration.
* <p>
* Note that access to some telephony information is
* permission-protected. Your application won't receive updates for protected
diff --git a/telephony/java/android/telephony/ServiceState.java b/telephony/java/android/telephony/ServiceState.java
index 3317876..a1aee6d 100644
--- a/telephony/java/android/telephony/ServiceState.java
+++ b/telephony/java/android/telephony/ServiceState.java
@@ -36,6 +36,7 @@
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
+import java.util.stream.Collectors;
/**
* Contains phone state and service related information.
@@ -887,6 +888,24 @@
}
/**
+ * Convert roaming type to string
+ *
+ * @param roamingType roaming type
+ * @return The roaming type in string format
+ *
+ * @hide
+ */
+ public static String roamingTypeToString(@RoamingType int roamingType) {
+ switch (roamingType) {
+ case ROAMING_TYPE_NOT_ROAMING: return "NOT_ROAMING";
+ case ROAMING_TYPE_UNKNOWN: return "UNKNOWN";
+ case ROAMING_TYPE_DOMESTIC: return "DOMESTIC";
+ case ROAMING_TYPE_INTERNATIONAL: return "INTERNATIONAL";
+ }
+ return "Unknown roaming type " + roamingType;
+ }
+
+ /**
* Convert radio technology to String
*
* @param rt radioTechnology
@@ -1867,4 +1886,29 @@
? range1
: range2;
}
+
+ /**
+ * Returns a copy of self with location-identifying information removed.
+ * Always clears the NetworkRegistrationState's CellIdentity fields, but if removeCoarseLocation
+ * is true, clears other info as well.
+ * @hide
+ */
+ public ServiceState sanitizeLocationInfo(boolean removeCoarseLocation) {
+ ServiceState state = new ServiceState(this);
+ if (state.mNetworkRegistrationStates != null) {
+ state.mNetworkRegistrationStates = state.mNetworkRegistrationStates.stream()
+ .map(NetworkRegistrationState::sanitizeLocationInfo)
+ .collect(Collectors.toList());
+ }
+ if (!removeCoarseLocation) return state;
+
+ state.mDataOperatorAlphaLong = null;
+ state.mDataOperatorAlphaShort = null;
+ state.mDataOperatorNumeric = null;
+ state.mVoiceOperatorAlphaLong = null;
+ state.mVoiceOperatorAlphaShort = null;
+ state.mVoiceOperatorNumeric = null;
+
+ return state;
+ }
}
diff --git a/telephony/java/android/telephony/SubscriptionManager.java b/telephony/java/android/telephony/SubscriptionManager.java
index 313146d..836a50b 100644
--- a/telephony/java/android/telephony/SubscriptionManager.java
+++ b/telephony/java/android/telephony/SubscriptionManager.java
@@ -59,6 +59,7 @@
import android.util.Log;
import com.android.internal.telephony.IOnSubscriptionsChangedListener;
+import com.android.internal.telephony.ISetOpportunisticDataCallback;
import com.android.internal.telephony.ISub;
import com.android.internal.telephony.ITelephonyRegistry;
import com.android.internal.telephony.PhoneConstants;
@@ -72,6 +73,7 @@
import java.util.Locale;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
@@ -864,7 +866,8 @@
}
/**
- * Callback invoked when there is any change to any SubscriptionInfo. Typically
+ * Callback invoked when there is any change to any SubscriptionInfo, as well as once on
+ * registering for changes with {@link #addOnSubscriptionsChangedListener}. Typically
* this method would invoke {@link #getActiveSubscriptionInfoList}
*/
public void onSubscriptionsChanged() {
@@ -916,7 +919,9 @@
/**
* Register for changes to the list of active {@link SubscriptionInfo} records or to the
* individual records themselves. When a change occurs the onSubscriptionsChanged method of
- * the listener will be invoked immediately if there has been a notification.
+ * the listener will be invoked immediately if there has been a notification. The
+ * onSubscriptionChanged method will also be triggered once initially when calling this
+ * function.
*
* @param listener an instance of {@link OnSubscriptionsChangedListener} with
* onSubscriptionsChanged overridden.
@@ -1859,7 +1864,7 @@
iSub.setDefaultSmsSubId(subscriptionId);
}
} catch (RemoteException ex) {
- // ignore it
+ ex.rethrowFromSystemServer();
}
}
@@ -2573,17 +2578,35 @@
* {@link SubscriptionManager#DEFAULT_SUBSCRIPTION_ID}, it means
* it's unset and {@link SubscriptionManager#getDefaultDataSubscriptionId()}
* is used to determine which modem is preferred.
+ * @param needValidation whether validation is needed before switch happens.
+ * @param executor The executor of where the callback will execute.
+ * @param callback Callback will be triggered once it succeeds or failed.
+ * See {@link TelephonyManager.SetOpportunisticSubscriptionResult}
+ * for more details. Pass null if don't care about the result.
+ *
* @hide
*
*/
+ @SystemApi
@RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
- public void setPreferredDataSubscriptionId(int subId) {
+ public void setPreferredDataSubscriptionId(int subId, boolean needValidation,
+ @NonNull @CallbackExecutor Executor executor, Consumer<Integer> callback) {
if (VDBG) logd("[setPreferredDataSubscriptionId]+ subId:" + subId);
try {
ISub iSub = ISub.Stub.asInterface(ServiceManager.getService("isub"));
- if (iSub != null) {
- iSub.setPreferredDataSubscriptionId(subId);
- }
+ if (iSub == null) return;
+
+ ISetOpportunisticDataCallback callbackStub = new ISetOpportunisticDataCallback.Stub() {
+ @Override
+ public void onComplete(int result) {
+ Binder.withCleanCallingIdentity(() -> executor.execute(() -> {
+ if (callback != null) {
+ callback.accept(result);
+ }
+ }));
+ }
+ };
+ iSub.setPreferredDataSubscriptionId(subId, needValidation, callbackStub);
} catch (RemoteException ex) {
// ignore it
}
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index f5d452e..ced4f4a 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -229,10 +229,19 @@
public static final int SRVCC_STATE_HANDOVER_CANCELED = 3;
/**
- * An invalid UICC card identifier. See {@link #getCardIdForDefaultEuicc()} and
- * {@link UiccCardInfo#getCardId()}.
+ * A UICC card identifier used if the device does not support the operation.
+ * For example, {@link #getCardIdForDefaultEuicc()} returns this value if the device has no
+ * eUICC, or the eUICC cannot be read.
*/
- public static final int INVALID_CARD_ID = -1;
+ public static final int UNSUPPORTED_CARD_ID = -1;
+
+ /**
+ * A UICC card identifier used before the UICC card is loaded. See
+ * {@link #getCardIdForDefaultEuicc()} and {@link UiccCardInfo#getCardId()}.
+ * <p>
+ * Note that once the UICC card is loaded, the card ID may become {@link #UNSUPPORTED_CARD_ID}.
+ */
+ public static final int UNINITIALIZED_CARD_ID = -2;
/** @hide */
@Retention(RetentionPolicy.SOURCE)
@@ -1689,10 +1698,7 @@
* @deprecated use {@link #getAllCellInfo} instead, which returns a superset of this API.
*/
@Deprecated
- @RequiresPermission(anyOf = {
- android.Manifest.permission.ACCESS_COARSE_LOCATION,
- android.Manifest.permission.ACCESS_FINE_LOCATION
- })
+ @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
public CellLocation getCellLocation() {
try {
ITelephony telephony = getITelephony();
@@ -3178,24 +3184,25 @@
}
/**
- * Get the card ID of the default eUICC card. If there is no eUICC, returns
- * {@link #INVALID_CARD_ID}.
+ * Get the card ID of the default eUICC card. If the eUICCs have not yet been loaded, returns
+ * {@link #UNINITIALIZED_CARD_ID}. If there is no eUICC or the device does not support card IDs
+ * for eUICCs, returns {@link #UNSUPPORTED_CARD_ID}.
*
* <p>The card ID is a unique identifier associated with a UICC or eUICC card. Card IDs are
* unique to a device, and always refer to the same UICC or eUICC card unless the device goes
* through a factory reset.
*
- * @return card ID of the default eUICC card.
+ * @return card ID of the default eUICC card, if loaded.
*/
public int getCardIdForDefaultEuicc() {
try {
ITelephony telephony = getITelephony();
if (telephony == null) {
- return INVALID_CARD_ID;
+ return UNINITIALIZED_CARD_ID;
}
return telephony.getCardIdForDefaultEuicc(mSubId, mContext.getOpPackageName());
} catch (RemoteException e) {
- return INVALID_CARD_ID;
+ return UNINITIALIZED_CARD_ID;
}
}
@@ -4941,7 +4948,7 @@
* @return List of {@link android.telephony.CellInfo}; null if cell
* information is unavailable.
*/
- @RequiresPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION)
+ @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
public List<CellInfo> getAllCellInfo() {
try {
ITelephony telephony = getITelephony();
@@ -5018,7 +5025,7 @@
* @param executor the executor on which callback will be invoked.
* @param callback a callback to receive CellInfo.
*/
- @RequiresPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION)
+ @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
public void requestCellInfoUpdate(
@NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback) {
try {
@@ -5057,7 +5064,7 @@
* @hide
*/
@SystemApi
- @RequiresPermission(allOf = {android.Manifest.permission.ACCESS_COARSE_LOCATION,
+ @RequiresPermission(allOf = {android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.MODIFY_PHONE_STATE})
public void requestCellInfoUpdate(@NonNull WorkSource workSource,
@NonNull @CallbackExecutor Executor executor, @NonNull CellInfoCallback callback) {
@@ -6647,9 +6654,10 @@
*
* <p> Note that this scan can take a long time (sometimes minutes) to happen.
*
- * <p>Requires Permission:
+ * <p>Requires Permissions:
* {@link android.Manifest.permission#MODIFY_PHONE_STATE} or that the calling app has carrier
* privileges (see {@link #hasCarrierPrivileges})
+ * and {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
*
* @return {@link CellNetworkScanResult} with the status
* {@link CellNetworkScanResult#STATUS_SUCCESS} and a list of
@@ -6658,12 +6666,15 @@
*
* @hide
*/
- @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
+ @RequiresPermission(allOf = {
+ android.Manifest.permission.MODIFY_PHONE_STATE,
+ Manifest.permission.ACCESS_COARSE_LOCATION
+ })
public CellNetworkScanResult getAvailableNetworks() {
try {
ITelephony telephony = getITelephony();
if (telephony != null) {
- return telephony.getCellNetworkScanResults(getSubId());
+ return telephony.getCellNetworkScanResults(getSubId(), getOpPackageName());
}
} catch (RemoteException ex) {
Rlog.e(TAG, "getAvailableNetworks RemoteException", ex);
@@ -6682,7 +6693,8 @@
*
* <p>Requires Permission:
* {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} or that the calling
- * app has carrier privileges (see {@link #hasCarrierPrivileges}).
+ * app has carrier privileges (see {@link #hasCarrierPrivileges})
+ * and {@link android.Manifest.permission#ACCESS_FINE_LOCATION}.
*
* @param request Contains all the RAT with bands/channels that need to be scanned.
* @param executor The executor through which the callback should be invoked. Since the scan
@@ -6693,7 +6705,10 @@
* @return A NetworkScan obj which contains a callback which can be used to stop the scan.
*/
@SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
- @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
+ @RequiresPermission(allOf = {
+ android.Manifest.permission.MODIFY_PHONE_STATE,
+ Manifest.permission.ACCESS_FINE_LOCATION
+ })
public NetworkScan requestNetworkScan(
NetworkScanRequest request, Executor executor,
TelephonyScanManager.NetworkScanCallback callback) {
@@ -6702,7 +6717,8 @@
mTelephonyScanManager = new TelephonyScanManager();
}
}
- return mTelephonyScanManager.requestNetworkScan(getSubId(), request, executor, callback);
+ return mTelephonyScanManager.requestNetworkScan(getSubId(), request, executor, callback,
+ getOpPackageName());
}
/**
@@ -6712,7 +6728,10 @@
* @removed
*/
@Deprecated
- @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
+ @RequiresPermission(allOf = {
+ android.Manifest.permission.MODIFY_PHONE_STATE,
+ Manifest.permission.ACCESS_FINE_LOCATION
+ })
public NetworkScan requestNetworkScan(
NetworkScanRequest request, TelephonyScanManager.NetworkScanCallback callback) {
return requestNetworkScan(request, AsyncTask.SERIAL_EXECUTOR, callback);
@@ -8713,10 +8732,14 @@
* given subId. Otherwise, applies to {@link SubscriptionManager#getDefaultSubscriptionId()}
*
* <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
- * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
+ * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges})
+ * and {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
*/
@SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
- @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
+ @RequiresPermission(allOf = {
+ Manifest.permission.READ_PHONE_STATE,
+ Manifest.permission.ACCESS_COARSE_LOCATION
+ })
public ServiceState getServiceState() {
return getServiceStateForSubscriber(getSubId());
}
@@ -10094,6 +10117,29 @@
return false;
}
+ /** @hide */
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(prefix = {"SET_OPPORTUNISTIC_SUB"}, value = {
+ SET_OPPORTUNISTIC_SUB_SUCCESS,
+ SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED,
+ SET_OPPORTUNISTIC_SUB_INVALID_PARAMETER})
+ public @interface SetOpportunisticSubscriptionResult {}
+
+ /**
+ * No error. Operation succeeded.
+ */
+ public static final int SET_OPPORTUNISTIC_SUB_SUCCESS = 0;
+
+ /**
+ * Validation failed when trying to switch to preferred subscription.
+ */
+ public static final int SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED = 1;
+
+ /**
+ * The parameter passed in is invalid.
+ */
+ public static final int SET_OPPORTUNISTIC_SUB_INVALID_PARAMETER = 2;
+
/**
* Set preferred opportunistic data subscription id.
*
@@ -10309,11 +10355,14 @@
/**
* Get whether reboot is required or not after making changes to modem configurations.
- * @Return {@code True} if reboot is required after making changes to modem configurations,
- * otherwise return {@code False}.
+ * The modem configuration change refers to switching from single SIM configuration to DSDS
+ * or the other way around.
+ * @Return {@code true} if reboot is required after making changes to modem configurations,
+ * otherwise return {@code false}.
*
* @hide
*/
+ @SystemApi
@RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
public boolean isRebootRequiredForModemConfigChange() {
try {
diff --git a/telephony/java/android/telephony/TelephonyScanManager.java b/telephony/java/android/telephony/TelephonyScanManager.java
index 96ff332..91f74b8 100644
--- a/telephony/java/android/telephony/TelephonyScanManager.java
+++ b/telephony/java/android/telephony/TelephonyScanManager.java
@@ -29,14 +29,14 @@
import android.os.Parcelable;
import android.os.RemoteException;
import android.os.ServiceManager;
-import android.util.Log;
import android.util.SparseArray;
+
+import com.android.internal.telephony.ITelephony;
+
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executor;
-import com.android.internal.telephony.ITelephony;
-
/**
* Manages the radio access network scan requests and callbacks.
*/
@@ -183,6 +183,7 @@
*
* <p>
* Requires Permission:
+ * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION} and
* {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}
* Or the calling app has carrier privileges. @see #hasCarrierPrivileges
*
@@ -192,11 +193,13 @@
* @hide
*/
public NetworkScan requestNetworkScan(int subId,
- NetworkScanRequest request, Executor executor, NetworkScanCallback callback) {
+ NetworkScanRequest request, Executor executor, NetworkScanCallback callback,
+ String callingPackage) {
try {
ITelephony telephony = getITelephony();
if (telephony != null) {
- int scanId = telephony.requestNetworkScan(subId, request, mMessenger, new Binder());
+ int scanId = telephony.requestNetworkScan(
+ subId, request, mMessenger, new Binder(), callingPackage);
saveScanInfo(scanId, request, executor, callback);
return new NetworkScan(scanId, subId);
}
diff --git a/telephony/java/android/telephony/euicc/EuiccManager.java b/telephony/java/android/telephony/euicc/EuiccManager.java
index 1bbf9f4..ad34349 100644
--- a/telephony/java/android/telephony/euicc/EuiccManager.java
+++ b/telephony/java/android/telephony/euicc/EuiccManager.java
@@ -460,7 +460,7 @@
*/
@Nullable
public String getEid() {
- if (!refreshCardIdIfInvalid()) {
+ if (!refreshCardIdIfUninitialized()) {
return null;
}
try {
@@ -483,7 +483,7 @@
@SystemApi
@RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
public int getOtaStatus() {
- if (!refreshCardIdIfInvalid()) {
+ if (!refreshCardIdIfUninitialized()) {
return EUICC_OTA_STATUS_UNAVAILABLE;
}
try {
@@ -518,7 +518,7 @@
@RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
public void downloadSubscription(DownloadableSubscription subscription,
boolean switchAfterDownload, PendingIntent callbackIntent) {
- if (!refreshCardIdIfInvalid()) {
+ if (!refreshCardIdIfUninitialized()) {
sendUnavailableError(callbackIntent);
return;
}
@@ -580,7 +580,7 @@
@SystemApi
@RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
public void continueOperation(Intent resolutionIntent, Bundle resolutionExtras) {
- if (!refreshCardIdIfInvalid()) {
+ if (!refreshCardIdIfUninitialized()) {
PendingIntent callbackIntent =
resolutionIntent.getParcelableExtra(
EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_RESOLUTION_CALLBACK_INTENT);
@@ -617,7 +617,7 @@
@RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
public void getDownloadableSubscriptionMetadata(
DownloadableSubscription subscription, PendingIntent callbackIntent) {
- if (!refreshCardIdIfInvalid()) {
+ if (!refreshCardIdIfUninitialized()) {
sendUnavailableError(callbackIntent);
return;
}
@@ -647,7 +647,7 @@
@SystemApi
@RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
public void getDefaultDownloadableSubscriptionList(PendingIntent callbackIntent) {
- if (!refreshCardIdIfInvalid()) {
+ if (!refreshCardIdIfUninitialized()) {
sendUnavailableError(callbackIntent);
return;
}
@@ -666,7 +666,7 @@
*/
@Nullable
public EuiccInfo getEuiccInfo() {
- if (!refreshCardIdIfInvalid()) {
+ if (!refreshCardIdIfUninitialized()) {
return null;
}
try {
@@ -691,7 +691,7 @@
*/
@RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
public void deleteSubscription(int subscriptionId, PendingIntent callbackIntent) {
- if (!refreshCardIdIfInvalid()) {
+ if (!refreshCardIdIfUninitialized()) {
sendUnavailableError(callbackIntent);
return;
}
@@ -731,7 +731,7 @@
*/
@RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
public void switchToSubscription(int subscriptionId, PendingIntent callbackIntent) {
- if (!refreshCardIdIfInvalid()) {
+ if (!refreshCardIdIfUninitialized()) {
sendUnavailableError(callbackIntent);
return;
}
@@ -757,7 +757,7 @@
@RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
public void updateSubscriptionNickname(
int subscriptionId, String nickname, PendingIntent callbackIntent) {
- if (!refreshCardIdIfInvalid()) {
+ if (!refreshCardIdIfUninitialized()) {
sendUnavailableError(callbackIntent);
return;
}
@@ -781,7 +781,7 @@
@SystemApi
@RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
public void eraseSubscriptions(PendingIntent callbackIntent) {
- if (!refreshCardIdIfInvalid()) {
+ if (!refreshCardIdIfUninitialized()) {
sendUnavailableError(callbackIntent);
return;
}
@@ -811,7 +811,7 @@
* @hide
*/
public void retainSubscriptionsForFactoryReset(PendingIntent callbackIntent) {
- if (!refreshCardIdIfInvalid()) {
+ if (!refreshCardIdIfUninitialized()) {
sendUnavailableError(callbackIntent);
return;
}
@@ -822,16 +822,24 @@
}
}
- private boolean refreshCardIdIfInvalid() {
- if (!isEnabled()) {
- return false;
- }
- // Refresh mCardId if it's invalid.
- if (mCardId == TelephonyManager.INVALID_CARD_ID) {
+ /**
+ * Refreshes the cardId if its uninitialized, and returns whether we should continue the
+ * operation.
+ * <p>
+ * Note that after a successful refresh, the mCardId may be TelephonyManager.UNSUPPORTED_CARD_ID
+ * on older HALs. For backwards compatability, we continue to the LPA and let it decide which
+ * card to use.
+ */
+ private boolean refreshCardIdIfUninitialized() {
+ // Refresh mCardId if its UNINITIALIZED_CARD_ID
+ if (mCardId == TelephonyManager.UNINITIALIZED_CARD_ID) {
TelephonyManager tm = (TelephonyManager)
mContext.getSystemService(Context.TELEPHONY_SERVICE);
mCardId = tm.getCardIdForDefaultEuicc();
}
+ if (mCardId == TelephonyManager.UNINITIALIZED_CARD_ID) {
+ return false;
+ }
return true;
}
diff --git a/telephony/java/android/telephony/ims/ImsCallProfile.java b/telephony/java/android/telephony/ims/ImsCallProfile.java
index 59167b7..73f0556 100644
--- a/telephony/java/android/telephony/ims/ImsCallProfile.java
+++ b/telephony/java/android/telephony/ims/ImsCallProfile.java
@@ -350,6 +350,9 @@
/** Indicates if the call is for testing purpose */
private boolean mEmergencyCallTesting = false;
+ /** Indicates if we have known the intent of the user for the call is emergency */
+ private boolean mHasKnownUserIntentEmergency = false;
+
/**
* Extras associated with this {@link ImsCallProfile}.
* <p>
@@ -789,12 +792,13 @@
*
* @hide
*/
- public void setEmergencyCallInfo(EmergencyNumber num) {
+ public void setEmergencyCallInfo(EmergencyNumber num, boolean hasKnownUserIntentEmergency) {
setEmergencyServiceCategories(num.getEmergencyServiceCategoryBitmaskInternalDial());
setEmergencyUrns(num.getEmergencyUrns());
setEmergencyCallRouting(num.getEmergencyCallRouting());
setEmergencyCallTesting(num.getEmergencyNumberSourceBitmask()
== EmergencyNumber.EMERGENCY_NUMBER_SOURCE_TEST);
+ setHasKnownUserIntentEmergency(hasKnownUserIntentEmergency);
}
/**
@@ -860,6 +864,19 @@
}
/**
+ * Set if we have known the user intent of the call is emergency.
+ *
+ * This is only used to specify when the dialed number is ambiguous when it can be identified
+ * as both emergency number and any other non-emergency number; e.g. in some situation, 611
+ * could be both an emergency number in a country and a non-emergency number of a carrier's
+ * customer service hotline.
+ */
+ @VisibleForTesting
+ public void setHasKnownUserIntentEmergency(boolean hasKnownUserIntentEmergency) {
+ mHasKnownUserIntentEmergency = hasKnownUserIntentEmergency;
+ }
+
+ /**
* Get the emergency service categories, only valid if {@link #getServiceType} returns
* {@link #SERVICE_TYPE_EMERGENCY}
*
@@ -916,4 +933,16 @@
public boolean isEmergencyCallTesting() {
return mEmergencyCallTesting;
}
+
+ /**
+ * Checks if we have known the user intent of the call is emergency.
+ *
+ * This is only used to specify when the dialed number is ambiguous when it can be identified
+ * as both emergency number and any other non-emergency number; e.g. in some situation, 611
+ * could be both an emergency number in a country and a non-emergency number of a carrier's
+ * customer service hotline.
+ */
+ public boolean hasKnownUserIntentEmergency() {
+ return mHasKnownUserIntentEmergency;
+ }
}
diff --git a/telephony/java/android/telephony/ims/Rcs1To1Thread.java b/telephony/java/android/telephony/ims/Rcs1To1Thread.java
index 3255f8d..d4a78ff 100644
--- a/telephony/java/android/telephony/ims/Rcs1To1Thread.java
+++ b/telephony/java/android/telephony/ims/Rcs1To1Thread.java
@@ -22,8 +22,6 @@
* Rcs1To1Thread represents a single RCS conversation thread with a total of two
* {@link RcsParticipant}s. Please see Section 5 (1-to-1 Messaging) - GSMA RCC.71 (RCS Universal
* Profile Service Definition Document)
- *
- * @hide - TODO: make public
*/
public class Rcs1To1Thread extends RcsThread {
private int mThreadId;
diff --git a/telephony/java/android/telephony/ims/RcsEvent.java b/telephony/java/android/telephony/ims/RcsEvent.java
index ef359a1..df62277 100644
--- a/telephony/java/android/telephony/ims/RcsEvent.java
+++ b/telephony/java/android/telephony/ims/RcsEvent.java
@@ -19,8 +19,6 @@
/**
* The base class for events that can happen on {@link RcsParticipant}s and {@link RcsThread}s.
- *
- * @hide - TODO: make public
*/
public abstract class RcsEvent {
/**
diff --git a/telephony/java/android/telephony/ims/RcsEventQueryParams.java b/telephony/java/android/telephony/ims/RcsEventQueryParams.java
index 5249bec..9dbfe43 100644
--- a/telephony/java/android/telephony/ims/RcsEventQueryParams.java
+++ b/telephony/java/android/telephony/ims/RcsEventQueryParams.java
@@ -37,8 +37,6 @@
* The parameters to pass into
* {@link RcsMessageStore#getRcsEvents(RcsEventQueryParams)} in order to select a
* subset of {@link RcsEvent}s present in the message store.
- *
- * @hide - TODO: make public
*/
public final class RcsEventQueryParams implements Parcelable {
/**
@@ -152,8 +150,8 @@
}
/**
- * @return Returns the type of {@link RcsEvent}s that this {@link RcsEventQueryParams} is
- * set to query for.
+ * @return Returns the number of {@link RcsEvent}s to be returned from the query. A value of
+ * 0 means there is no set limit.
*/
public int getLimit() {
return mLimit;
diff --git a/telephony/java/android/telephony/ims/RcsEventQueryResult.java b/telephony/java/android/telephony/ims/RcsEventQueryResult.java
index f8d57fa..c30e4cc 100644
--- a/telephony/java/android/telephony/ims/RcsEventQueryResult.java
+++ b/telephony/java/android/telephony/ims/RcsEventQueryResult.java
@@ -25,8 +25,6 @@
* The result of a {@link RcsMessageStore#getRcsEvents(RcsEventQueryParams)}
* call. This class allows getting the token for querying the next batch of events in order to
* prevent handling large amounts of data at once.
- *
- * @hide - TODO: make public
*/
public final class RcsEventQueryResult implements Parcelable {
private RcsQueryContinuationToken mContinuationToken;
diff --git a/telephony/java/android/telephony/ims/RcsFileTransferCreationParams.java b/telephony/java/android/telephony/ims/RcsFileTransferCreationParams.java
index 663def5..14af8ea 100644
--- a/telephony/java/android/telephony/ims/RcsFileTransferCreationParams.java
+++ b/telephony/java/android/telephony/ims/RcsFileTransferCreationParams.java
@@ -24,8 +24,6 @@
* Pass an instance of this class to
* {@link RcsMessage#insertFileTransfer(RcsFileTransferCreationParams)} create an
* {@link RcsFileTransferPart} and save it into storage.
- *
- * @hide - TODO: make public
*/
public final class RcsFileTransferCreationParams implements Parcelable {
private String mRcsFileTransferSessionId;
diff --git a/telephony/java/android/telephony/ims/RcsFileTransferPart.java b/telephony/java/android/telephony/ims/RcsFileTransferPart.java
index 1ce7999..9531c2e 100644
--- a/telephony/java/android/telephony/ims/RcsFileTransferPart.java
+++ b/telephony/java/android/telephony/ims/RcsFileTransferPart.java
@@ -26,8 +26,6 @@
/**
* A part of a composite {@link RcsMessage} that holds a file transfer. Please see Section 7
* (File Transfer) - GSMA RCC.71 (RCS Universal Profile Service Definition Document)
- *
- * @hide - TODO: make public
*/
public class RcsFileTransferPart {
/**
diff --git a/telephony/java/android/telephony/ims/RcsGroupThread.java b/telephony/java/android/telephony/ims/RcsGroupThread.java
index 2c42494..6e17bc2 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThread.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThread.java
@@ -29,8 +29,6 @@
* RcsGroupThread represents a single RCS conversation thread where {@link RcsParticipant}s can join
* or leave. Please see Section 6 (Group Chat) - GSMA RCC.71 (RCS Universal Profile Service
* Definition Document)
- *
- * @hide - TODO: make public
*/
public class RcsGroupThread extends RcsThread {
/**
diff --git a/telephony/java/android/telephony/ims/RcsGroupThreadEvent.java b/telephony/java/android/telephony/ims/RcsGroupThreadEvent.java
index bc61877..609b174 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThreadEvent.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThreadEvent.java
@@ -20,8 +20,6 @@
/**
* An event that happened on an {@link RcsGroupThread}.
- *
- * @hide - TODO: make public
*/
public abstract class RcsGroupThreadEvent extends RcsEvent {
private final int mRcsGroupThreadId;
diff --git a/telephony/java/android/telephony/ims/RcsGroupThreadIconChangedEvent.java b/telephony/java/android/telephony/ims/RcsGroupThreadIconChangedEvent.java
index 74af973..e768439 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThreadIconChangedEvent.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThreadIconChangedEvent.java
@@ -24,8 +24,6 @@
/**
* An event that indicates an {@link RcsGroupThread}'s icon was changed. Please see R6-2-5 - GSMA
* RCC.71 (RCS Universal Profile Service Definition Document)
- *
- * @hide - TODO: make public
*/
public final class RcsGroupThreadIconChangedEvent extends RcsGroupThreadEvent implements
Parcelable {
diff --git a/telephony/java/android/telephony/ims/RcsGroupThreadNameChangedEvent.java b/telephony/java/android/telephony/ims/RcsGroupThreadNameChangedEvent.java
index 06f4d5b..02030bc 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThreadNameChangedEvent.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThreadNameChangedEvent.java
@@ -23,8 +23,6 @@
/**
* An event that indicates an {@link RcsGroupThread}'s name was changed. Please see R6-2-5 - GSMA
* RCC.71 (RCS Universal Profile Service Definition Document)
- *
- * @hide - TODO: make public
*/
public final class RcsGroupThreadNameChangedEvent extends RcsGroupThreadEvent implements
Parcelable {
diff --git a/telephony/java/android/telephony/ims/RcsGroupThreadParticipantJoinedEvent.java b/telephony/java/android/telephony/ims/RcsGroupThreadParticipantJoinedEvent.java
index 4932707..0d1a573 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThreadParticipantJoinedEvent.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThreadParticipantJoinedEvent.java
@@ -22,8 +22,6 @@
/**
* An event that indicates an RCS participant has joined an {@link RcsThread}. Please see US6-3 -
* GSMA RCC.71 (RCS Universal Profile Service Definition Document)
- *
- * @hide - TODO: make public
*/
public final class RcsGroupThreadParticipantJoinedEvent extends RcsGroupThreadEvent implements
Parcelable {
diff --git a/telephony/java/android/telephony/ims/RcsGroupThreadParticipantLeftEvent.java b/telephony/java/android/telephony/ims/RcsGroupThreadParticipantLeftEvent.java
index 970a046..cd52508 100644
--- a/telephony/java/android/telephony/ims/RcsGroupThreadParticipantLeftEvent.java
+++ b/telephony/java/android/telephony/ims/RcsGroupThreadParticipantLeftEvent.java
@@ -22,8 +22,6 @@
/**
* An event that indicates an RCS participant has left an {@link RcsThread}. Please see US6-23 -
* GSMA RCC.71 (RCS Universal Profile Service Definition Document)
- *
- * @hide - TODO: make public
*/
public final class RcsGroupThreadParticipantLeftEvent extends RcsGroupThreadEvent implements
Parcelable {
diff --git a/telephony/java/android/telephony/ims/RcsIncomingMessage.java b/telephony/java/android/telephony/ims/RcsIncomingMessage.java
index f3b7815..61911ab 100644
--- a/telephony/java/android/telephony/ims/RcsIncomingMessage.java
+++ b/telephony/java/android/telephony/ims/RcsIncomingMessage.java
@@ -19,8 +19,6 @@
/**
* This is a single instance of a message received over RCS.
- *
- * @hide - TODO: make public
*/
public class RcsIncomingMessage extends RcsMessage {
/**
diff --git a/telephony/java/android/telephony/ims/RcsIncomingMessageCreationParams.java b/telephony/java/android/telephony/ims/RcsIncomingMessageCreationParams.java
index 64b2339..61dedbc 100644
--- a/telephony/java/android/telephony/ims/RcsIncomingMessageCreationParams.java
+++ b/telephony/java/android/telephony/ims/RcsIncomingMessageCreationParams.java
@@ -24,8 +24,6 @@
* {@link RcsIncomingMessageCreationParams} is a collection of parameters that should be passed
* into {@link RcsThread#addIncomingMessage(RcsIncomingMessageCreationParams)} to generate an
* {@link RcsIncomingMessage} on that {@link RcsThread}
- *
- * @hide - TODO: make public
*/
public final class RcsIncomingMessageCreationParams extends RcsMessageCreationParams implements
Parcelable {
diff --git a/telephony/java/android/telephony/ims/RcsManager.java b/telephony/java/android/telephony/ims/RcsManager.java
index 90bd044..22e4b22 100644
--- a/telephony/java/android/telephony/ims/RcsManager.java
+++ b/telephony/java/android/telephony/ims/RcsManager.java
@@ -20,8 +20,6 @@
/**
* The manager class for RCS related utilities.
- *
- * @hide - TODO: make public
*/
@SystemService(Context.TELEPHONY_RCS_SERVICE)
public class RcsManager {
diff --git a/telephony/java/android/telephony/ims/RcsMessage.java b/telephony/java/android/telephony/ims/RcsMessage.java
index 1700941..3227413 100644
--- a/telephony/java/android/telephony/ims/RcsMessage.java
+++ b/telephony/java/android/telephony/ims/RcsMessage.java
@@ -27,8 +27,6 @@
/**
* This is a single instance of a message sent or received over RCS.
- *
- * @hide - TODO: make public
*/
public abstract class RcsMessage {
/**
diff --git a/telephony/java/android/telephony/ims/RcsMessageCreationParams.java b/telephony/java/android/telephony/ims/RcsMessageCreationParams.java
index 9ac4dcd..c46c605 100644
--- a/telephony/java/android/telephony/ims/RcsMessageCreationParams.java
+++ b/telephony/java/android/telephony/ims/RcsMessageCreationParams.java
@@ -27,8 +27,6 @@
* {@link RcsThread#addIncomingMessage(RcsIncomingMessageCreationParams)} and
* {@link RcsThread#addOutgoingMessage(RcsOutgoingMessageCreationParams)} to create and persist
* {@link RcsMessage}s on an {@link RcsThread}
- *
- * @hide - TODO: make public
*/
public class RcsMessageCreationParams {
// The globally unique id of the RcsMessage to be created.
diff --git a/telephony/java/android/telephony/ims/RcsMessageQueryParams.java b/telephony/java/android/telephony/ims/RcsMessageQueryParams.java
index fae0d97..535a597 100644
--- a/telephony/java/android/telephony/ims/RcsMessageQueryParams.java
+++ b/telephony/java/android/telephony/ims/RcsMessageQueryParams.java
@@ -31,8 +31,6 @@
* The parameters to pass into
* {@link RcsMessageStore#getRcsMessages(RcsMessageQueryParams)} in order to select a
* subset of {@link RcsMessage}s present in the message store.
- *
- * @hide - TODO: make public
*/
public final class RcsMessageQueryParams implements Parcelable {
/**
diff --git a/telephony/java/android/telephony/ims/RcsMessageQueryResult.java b/telephony/java/android/telephony/ims/RcsMessageQueryResult.java
index 5adab76..3514b48e 100644
--- a/telephony/java/android/telephony/ims/RcsMessageQueryResult.java
+++ b/telephony/java/android/telephony/ims/RcsMessageQueryResult.java
@@ -32,8 +32,6 @@
* The result of a {@link RcsMessageStore#getRcsMessages(RcsMessageQueryParams)}
* call. This class allows getting the token for querying the next batch of messages in order to
* prevent handling large amounts of data at once.
- *
- * @hide - TODO: make public
*/
public final class RcsMessageQueryResult implements Parcelable {
// The token to continue the query to get the next batch of results
diff --git a/telephony/java/android/telephony/ims/RcsMessageSnippet.java b/telephony/java/android/telephony/ims/RcsMessageSnippet.java
index 565bb99..b0b930c 100644
--- a/telephony/java/android/telephony/ims/RcsMessageSnippet.java
+++ b/telephony/java/android/telephony/ims/RcsMessageSnippet.java
@@ -23,8 +23,6 @@
/**
* An immutable summary of the latest {@link RcsMessage} on an {@link RcsThread}
- *
- * @hide - TODO: make public
*/
public final class RcsMessageSnippet implements Parcelable {
private final String mText;
diff --git a/telephony/java/android/telephony/ims/RcsMessageStore.java b/telephony/java/android/telephony/ims/RcsMessageStore.java
index eca5ed5..d811c6e 100644
--- a/telephony/java/android/telephony/ims/RcsMessageStore.java
+++ b/telephony/java/android/telephony/ims/RcsMessageStore.java
@@ -26,8 +26,6 @@
/**
* RcsMessageStore is the application interface to RcsProvider and provides access methods to
* RCS related database tables.
- *
- * @hide - TODO: make public
*/
public class RcsMessageStore {
/**
diff --git a/telephony/java/android/telephony/ims/RcsMessageStoreException.java b/telephony/java/android/telephony/ims/RcsMessageStoreException.java
index 7c00749..f25bb17 100644
--- a/telephony/java/android/telephony/ims/RcsMessageStoreException.java
+++ b/telephony/java/android/telephony/ims/RcsMessageStoreException.java
@@ -19,8 +19,6 @@
/**
* An exception that happened on {@link RcsMessageStore} or one of the derived storage classes in
* {@link android.telephony.ims}
- *
- * @hide - TODO: make public
*/
public class RcsMessageStoreException extends Exception {
diff --git a/telephony/java/android/telephony/ims/RcsOutgoingMessage.java b/telephony/java/android/telephony/ims/RcsOutgoingMessage.java
index dfcdee4..06fb832 100644
--- a/telephony/java/android/telephony/ims/RcsOutgoingMessage.java
+++ b/telephony/java/android/telephony/ims/RcsOutgoingMessage.java
@@ -23,8 +23,6 @@
/**
* This is a single instance of a message sent over RCS.
- *
- * @hide - TODO: make public
*/
public class RcsOutgoingMessage extends RcsMessage {
RcsOutgoingMessage(int id) {
diff --git a/telephony/java/android/telephony/ims/RcsOutgoingMessageCreationParams.java b/telephony/java/android/telephony/ims/RcsOutgoingMessageCreationParams.java
index ca466e8..979634a 100644
--- a/telephony/java/android/telephony/ims/RcsOutgoingMessageCreationParams.java
+++ b/telephony/java/android/telephony/ims/RcsOutgoingMessageCreationParams.java
@@ -23,8 +23,6 @@
* {@link RcsOutgoingMessageCreationParams} is a collection of parameters that should be passed
* into {@link RcsThread#addOutgoingMessage(RcsOutgoingMessageCreationParams)} to generate an
* {@link RcsOutgoingMessage} on that {@link RcsThread}
- *
- * @hide - TODO: make public
*/
public final class RcsOutgoingMessageCreationParams extends RcsMessageCreationParams
implements Parcelable {
diff --git a/telephony/java/android/telephony/ims/RcsOutgoingMessageDelivery.java b/telephony/java/android/telephony/ims/RcsOutgoingMessageDelivery.java
index 5a3062a..1c87b13 100644
--- a/telephony/java/android/telephony/ims/RcsOutgoingMessageDelivery.java
+++ b/telephony/java/android/telephony/ims/RcsOutgoingMessageDelivery.java
@@ -21,8 +21,6 @@
/**
* This class holds the delivery information of an {@link RcsOutgoingMessage} for each
* {@link RcsParticipant} that the message was intended for.
- *
- * @hide - TODO: make public
*/
public class RcsOutgoingMessageDelivery {
// The participant that this delivery is intended for
diff --git a/telephony/java/android/telephony/ims/RcsParticipant.java b/telephony/java/android/telephony/ims/RcsParticipant.java
index 37b827b..7ba5d8e 100644
--- a/telephony/java/android/telephony/ims/RcsParticipant.java
+++ b/telephony/java/android/telephony/ims/RcsParticipant.java
@@ -20,8 +20,6 @@
/**
* RcsParticipant is an RCS capable contact that can participate in {@link RcsThread}s.
- *
- * @hide - TODO: make public
*/
public class RcsParticipant {
// The row ID of this participant in the database
diff --git a/telephony/java/android/telephony/ims/RcsParticipantAliasChangedEvent.java b/telephony/java/android/telephony/ims/RcsParticipantAliasChangedEvent.java
index aa278b3..c9a2b0d 100644
--- a/telephony/java/android/telephony/ims/RcsParticipantAliasChangedEvent.java
+++ b/telephony/java/android/telephony/ims/RcsParticipantAliasChangedEvent.java
@@ -23,8 +23,6 @@
/**
* An event that indicates an {@link RcsParticipant}'s alias was changed. Please see US18-2 - GSMA
* RCC.71 (RCS Universal Profile Service Definition Document)
- *
- * @hide - TODO: make public
*/
public final class RcsParticipantAliasChangedEvent extends RcsEvent implements Parcelable {
// The ID of the participant that changed their alias
diff --git a/telephony/java/android/telephony/ims/RcsParticipantQueryParams.java b/telephony/java/android/telephony/ims/RcsParticipantQueryParams.java
index 57c67fa..d24d079 100644
--- a/telephony/java/android/telephony/ims/RcsParticipantQueryParams.java
+++ b/telephony/java/android/telephony/ims/RcsParticipantQueryParams.java
@@ -30,8 +30,6 @@
* The parameters to pass into
* {@link RcsMessageStore#getRcsParticipants(RcsParticipantQueryParams)} in order to select a
* subset of {@link RcsThread}s present in the message store.
- *
- * @hide - TODO: make public
*/
public final class RcsParticipantQueryParams implements Parcelable {
/**
diff --git a/telephony/java/android/telephony/ims/RcsParticipantQueryResult.java b/telephony/java/android/telephony/ims/RcsParticipantQueryResult.java
index 4eae39d..505f1a5 100644
--- a/telephony/java/android/telephony/ims/RcsParticipantQueryResult.java
+++ b/telephony/java/android/telephony/ims/RcsParticipantQueryResult.java
@@ -28,8 +28,6 @@
* The result of a {@link RcsMessageStore#getRcsParticipants(RcsParticipantQueryParams)}
* call. This class allows getting the token for querying the next batch of participants in order to
* prevent handling large amounts of data at once.
- *
- * @hide - TODO: make public
*/
public final class RcsParticipantQueryResult implements Parcelable {
// A token for the caller to continue their query for the next batch of results
diff --git a/telephony/java/android/telephony/ims/RcsQueryContinuationToken.java b/telephony/java/android/telephony/ims/RcsQueryContinuationToken.java
index c1ff396..08643de 100644
--- a/telephony/java/android/telephony/ims/RcsQueryContinuationToken.java
+++ b/telephony/java/android/telephony/ims/RcsQueryContinuationToken.java
@@ -31,8 +31,6 @@
* @see RcsMessageQueryResult#getContinuationToken()
* @see RcsParticipantQueryResult#getContinuationToken()
* @see RcsThreadQueryResult#getContinuationToken()
- *
- * @hide - TODO: make public
*/
public final class RcsQueryContinuationToken implements Parcelable {
/**
diff --git a/telephony/java/android/telephony/ims/RcsThread.java b/telephony/java/android/telephony/ims/RcsThread.java
index 8865586..e015dd3 100644
--- a/telephony/java/android/telephony/ims/RcsThread.java
+++ b/telephony/java/android/telephony/ims/RcsThread.java
@@ -27,8 +27,6 @@
/**
* RcsThread represents a single RCS conversation thread. It holds messages that were sent and
* received and events that occurred on that thread.
- *
- * @hide - TODO: make public
*/
public abstract class RcsThread {
/**
diff --git a/telephony/java/android/telephony/ims/RcsThreadQueryParams.java b/telephony/java/android/telephony/ims/RcsThreadQueryParams.java
index ba32e32..05a5a39 100644
--- a/telephony/java/android/telephony/ims/RcsThreadQueryParams.java
+++ b/telephony/java/android/telephony/ims/RcsThreadQueryParams.java
@@ -35,8 +35,6 @@
/**
* The parameters to pass into {@link RcsMessageStore#getRcsThreads(RcsThreadQueryParams)} in
* order to select a subset of {@link RcsThread}s present in the message store.
- *
- * @hide - TODO: make public
*/
public final class RcsThreadQueryParams implements Parcelable {
/**
diff --git a/telephony/java/android/telephony/ims/RcsThreadQueryResult.java b/telephony/java/android/telephony/ims/RcsThreadQueryResult.java
index a91126b..1cac61d 100644
--- a/telephony/java/android/telephony/ims/RcsThreadQueryResult.java
+++ b/telephony/java/android/telephony/ims/RcsThreadQueryResult.java
@@ -32,8 +32,6 @@
* The result of a {@link RcsMessageStore#getRcsThreads(RcsThreadQueryParams)}
* call. This class allows getting the token for querying the next batch of threads in order to
* prevent handling large amounts of data at once.
- *
- * @hide - TODO: make public
*/
public final class RcsThreadQueryResult implements Parcelable {
// A token for the caller to continue their query for the next batch of results
diff --git a/telephony/java/com/android/internal/telephony/ISetOpportunisticDataCallback.aidl b/telephony/java/com/android/internal/telephony/ISetOpportunisticDataCallback.aidl
new file mode 100644
index 0000000..7a78f34
--- /dev/null
+++ b/telephony/java/com/android/internal/telephony/ISetOpportunisticDataCallback.aidl
@@ -0,0 +1,25 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.telephony;
+
+/**
+ * Callback to provide asynchronous result of setPreferredOpportunisticData.
+ * @hide
+ */
+oneway interface ISetOpportunisticDataCallback {
+ void onComplete(int result);
+}
diff --git a/telephony/java/com/android/internal/telephony/ISub.aidl b/telephony/java/com/android/internal/telephony/ISub.aidl
index 6ce9de4..75a4d82 100755
--- a/telephony/java/com/android/internal/telephony/ISub.aidl
+++ b/telephony/java/com/android/internal/telephony/ISub.aidl
@@ -17,6 +17,7 @@
package com.android.internal.telephony;
import android.telephony.SubscriptionInfo;
+import com.android.internal.telephony.ISetOpportunisticDataCallback;
interface ISub {
/**
@@ -217,10 +218,14 @@
* designed to overwrite default data subscription temporarily.
*
* @param subId which subscription is preferred to for cellular data.
+ * @param needValidation whether validation is needed before switching.
+ * @param callback callback upon request completion.
+ *
* @hide
*
*/
- void setPreferredDataSubscriptionId(int subId);
+ void setPreferredDataSubscriptionId(int subId, boolean needValidation,
+ ISetOpportunisticDataCallback callback);
/**
* Get which subscription is preferred for cellular data.
diff --git a/telephony/java/com/android/internal/telephony/ITelephony.aidl b/telephony/java/com/android/internal/telephony/ITelephony.aidl
index bc43fea..7089ee5 100644
--- a/telephony/java/com/android/internal/telephony/ITelephony.aidl
+++ b/telephony/java/com/android/internal/telephony/ITelephony.aidl
@@ -765,7 +765,7 @@
* @param subId the id of the subscription.
* @return CellNetworkScanResult containing status of scan and networks.
*/
- CellNetworkScanResult getCellNetworkScanResults(int subId);
+ CellNetworkScanResult getCellNetworkScanResults(int subId, String callingPackage);
/**
* Perform a radio network scan and return the id of this scan.
@@ -774,10 +774,11 @@
* @param request Defines all the configs for network scan.
* @param messenger Callback messages will be sent using this messenger.
* @param binder the binder object instantiated in TelephonyManager.
+ * @param callingPackage the calling package
* @return An id for this scan.
*/
int requestNetworkScan(int subId, in NetworkScanRequest request, in Messenger messenger,
- in IBinder binder);
+ in IBinder binder, in String callingPackage);
/**
* Stop an existing radio network scan.
@@ -1837,7 +1838,7 @@
* @hide
*/
boolean isMultisimCarrierRestricted();
-
+
/**
* Switch configs to enable multi-sim or switch back to single-sim
* @hide
@@ -1846,6 +1847,7 @@
/**
* Get if reboot is required upon altering modems configurations
+ * @hide
*/
boolean isRebootRequiredForModemConfigChange();
diff --git a/telephony/java/com/android/internal/telephony/TelephonyPermissions.java b/telephony/java/com/android/internal/telephony/TelephonyPermissions.java
index b9ec7bf..9d78bf4 100644
--- a/telephony/java/com/android/internal/telephony/TelephonyPermissions.java
+++ b/telephony/java/com/android/internal/telephony/TelephonyPermissions.java
@@ -334,8 +334,7 @@
// settings to individually disable the new restrictions for privileged, preloaded
// non-privileged, and non-preinstalled apps.
if (!isIdentifierCheckDisabled() && (
- (isPrivApp && !relaxPrivDeviceIdentifierCheck)
- || (!isPreinstalled && !relax3PDeviceIdentifierCheck)
+ (!isPreinstalled && !relax3PDeviceIdentifierCheck)
|| (isPreinstalled && !isPrivApp && !relaxNonPrivDeviceIdentifierCheck))) {
// The current package should only be reported in StatsLog if it has not previously been
// reported for the currently invoked device identifier method.
diff --git a/telephony/java/com/android/internal/telephony/cdma/BearerData.java b/telephony/java/com/android/internal/telephony/cdma/BearerData.java
index a4cd56b..694cc69 100644
--- a/telephony/java/com/android/internal/telephony/cdma/BearerData.java
+++ b/telephony/java/com/android/internal/telephony/cdma/BearerData.java
@@ -596,6 +596,45 @@
System.arraycopy(payload, 0, uData.payload, udhBytes, payload.length);
}
+ private static void encode7bitAsciiEms(UserData uData, byte[] udhData, boolean force)
+ throws CodingException
+ {
+ try {
+ Rlog.d(LOG_TAG, "encode7bitAsciiEms");
+ int udhBytes = udhData.length + 1; // Add length octet.
+ int udhSeptets = ((udhBytes * 8) + 6) / 7;
+ int paddingBits = (udhSeptets * 7) - (udhBytes * 8);
+ String msg = uData.payloadStr;
+ byte[] payload ;
+ int msgLen = msg.length();
+ BitwiseOutputStream outStream = new BitwiseOutputStream(msgLen +
+ (paddingBits > 0 ? 1 : 0));
+ outStream.write(paddingBits, 0);
+ for (int i = 0; i < msgLen; i++) {
+ int charCode = UserData.charToAscii.get(msg.charAt(i), -1);
+ if (charCode == -1) {
+ if (force) {
+ outStream.write(7, UserData.UNENCODABLE_7_BIT_CHAR);
+ } else {
+ throw new CodingException("cannot ASCII encode (" + msg.charAt(i) + ")");
+ }
+ } else {
+ outStream.write(7, charCode);
+ }
+ }
+ payload = outStream.toByteArray();
+ uData.msgEncoding = UserData.ENCODING_7BIT_ASCII;
+ uData.msgEncodingSet = true;
+ uData.numFields = udhSeptets + uData.payloadStr.length();
+ uData.payload = new byte[udhBytes + payload.length];
+ uData.payload[0] = (byte)udhData.length;
+ System.arraycopy(udhData, 0, uData.payload, 1, udhData.length);
+ System.arraycopy(payload, 0, uData.payload, udhBytes, payload.length);
+ } catch (BitwiseOutputStream.AccessException ex) {
+ throw new CodingException("7bit ASCII encode failed: " + ex);
+ }
+ }
+
private static void encodeEmsUserDataPayload(UserData uData)
throws CodingException
{
@@ -605,6 +644,8 @@
encode7bitEms(uData, headerData, true);
} else if (uData.msgEncoding == UserData.ENCODING_UNICODE_16) {
encode16bitEms(uData, headerData);
+ } else if (uData.msgEncoding == UserData.ENCODING_7BIT_ASCII) {
+ encode7bitAsciiEms(uData, headerData, true);
} else {
throw new CodingException("unsupported EMS user data encoding (" +
uData.msgEncoding + ")");
@@ -1056,15 +1097,18 @@
throws CodingException
{
try {
- offset *= 8;
+ int offsetBits = offset * 8;
+ int offsetSeptets = (offsetBits + 6) / 7;
+ numFields -= offsetSeptets;
+
StringBuffer strBuf = new StringBuffer(numFields);
BitwiseInputStream inStream = new BitwiseInputStream(data);
- int wantedBits = (offset * 8) + (numFields * 7);
+ int wantedBits = (offsetSeptets * 7) + (numFields * 7);
if (inStream.available() < wantedBits) {
throw new CodingException("insufficient data (wanted " + wantedBits +
" bits, but only have " + inStream.available() + ")");
}
- inStream.skip(offset);
+ inStream.skip(offsetSeptets * 7);
for (int i = 0; i < numFields; i++) {
int charCode = inStream.read(7);
if ((charCode >= UserData.ASCII_MAP_BASE_INDEX) &&
diff --git a/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java b/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java
index 9080e23..1da5eac 100644
--- a/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java
+++ b/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java
@@ -864,8 +864,9 @@
Rlog.d(LOG_TAG, "MO raw BearerData = '" + HexDump.toHexString(encodedBearerData) + "'");
}
- int teleservice = bearerData.hasUserDataHeader ?
- SmsEnvelope.TELESERVICE_WEMT : SmsEnvelope.TELESERVICE_WMT;
+ int teleservice = (bearerData.hasUserDataHeader
+ && userData.msgEncoding != UserData.ENCODING_7BIT_ASCII)
+ ? SmsEnvelope.TELESERVICE_WEMT : SmsEnvelope.TELESERVICE_WMT;
SmsEnvelope envelope = new SmsEnvelope();
envelope.messageType = SmsEnvelope.MESSAGE_TYPE_POINT_TO_POINT;
diff --git a/test-runner/Android.mk b/test-runner/Android.mk
deleted file mode 100644
index 18bde85..0000000
--- a/test-runner/Android.mk
+++ /dev/null
@@ -1,20 +0,0 @@
-#
-# Copyright (C) 2008 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# 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.
-#
-
-LOCAL_PATH:= $(call my-dir)
-
-# additionally, build unit tests in a separate .apk
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/test-runner/tests/Android.bp b/test-runner/tests/Android.bp
new file mode 100644
index 0000000..03c7398
--- /dev/null
+++ b/test-runner/tests/Android.bp
@@ -0,0 +1,40 @@
+// Copyright 2010, The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+android_test {
+ name: "FrameworkTestRunnerTests",
+
+ // We only want this apk build for tests.
+ //
+ // Run the tests using the following commands:
+ // adb install -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworkTestRunnerTests/FrameworkTestRunnerTests.apk
+ // adb shell am instrument \
+ // -e notAnnotation android.test.suitebuilder.examples.error.RunAsPartOfSeparateTest \
+ // -w com.android.frameworks.testrunner.tests/android.test.InstrumentationTestRunner \
+ //
+
+ libs: [
+ "android.test.runner",
+ "android.test.base",
+ "android.test.mock",
+ ],
+ static_libs: ["junit"],
+
+ // Include all test java files.
+ srcs: ["src/**/*.java"],
+
+ // Because of android.test.mock.
+ platform_apis: true,
+
+}
diff --git a/test-runner/tests/Android.mk b/test-runner/tests/Android.mk
deleted file mode 100644
index f97d1c9..0000000
--- a/test-runner/tests/Android.mk
+++ /dev/null
@@ -1,39 +0,0 @@
-# Copyright 2010, 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.
-
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-# We only want this apk build for tests.
-#
-# Run the tests using the following commands:
-# adb install -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworkTestRunnerTests/FrameworkTestRunnerTests.apk
-# adb shell am instrument \
- -e notAnnotation android.test.suitebuilder.examples.error.RunAsPartOfSeparateTest \
- -w com.android.frameworks.testrunner.tests/android.test.InstrumentationTestRunner
-#
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_JAVA_LIBRARIES := android.test.runner android.test.base android.test.mock
-LOCAL_STATIC_JAVA_LIBRARIES := junit
-
-# Include all test java files.
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_PACKAGE_NAME := FrameworkTestRunnerTests
-# Because of android.test.mock.
-LOCAL_PRIVATE_PLATFORM_APIS := true
-
-include $(BUILD_PACKAGE)
-
diff --git a/tests/ActivityTests/src/com/google/android/test/activity/ActivityTestMain.java b/tests/ActivityTests/src/com/google/android/test/activity/ActivityTestMain.java
index d5549cc..07b3a97 100644
--- a/tests/ActivityTests/src/com/google/android/test/activity/ActivityTestMain.java
+++ b/tests/ActivityTests/src/com/google/android/test/activity/ActivityTestMain.java
@@ -439,6 +439,14 @@
return true;
}
});
+ menu.add("Require unknown permission").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
+ @Override public boolean onMenuItemClick(MenuItem item) {
+ final Intent intent = new Intent(SLOW_RECEIVER_ACTION);
+ intent.putExtra(SLOW_RECEIVER_EXTRA, 5038);
+ sendOrderedBroadcast(intent, "com.google.android.test.activity.permission.UNDEFINED");
+ return true;
+ }
+ });
menu.add("Stack Doc").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override public boolean onMenuItemClick(MenuItem item) {
ActivityManager.AppTask task = findDocTask();
diff --git a/tests/net/java/com/android/server/ConnectivityServiceTest.java b/tests/net/java/com/android/server/ConnectivityServiceTest.java
index e2d59d6..a7c95c7 100644
--- a/tests/net/java/com/android/server/ConnectivityServiceTest.java
+++ b/tests/net/java/com/android/server/ConnectivityServiceTest.java
@@ -554,7 +554,7 @@
if (mNmValidationRedirectUrl != null) {
mNmCallbacks.showProvisioningNotification(
- "test_provisioning_notif_action");
+ "test_provisioning_notif_action", "com.android.test.package");
mNmProvNotificationRequested = true;
}
} catch (RemoteException e) {
diff --git a/tests/net/java/com/android/server/connectivity/TetheringTest.java b/tests/net/java/com/android/server/connectivity/TetheringTest.java
index b635607..a4a735d 100644
--- a/tests/net/java/com/android/server/connectivity/TetheringTest.java
+++ b/tests/net/java/com/android/server/connectivity/TetheringTest.java
@@ -35,6 +35,7 @@
import static android.net.wifi.WifiManager.IFACE_IP_MODE_TETHERED;
import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLED;
import static android.provider.Settings.Global.TETHER_ENABLE_LEGACY_DHCP_SERVER;
+import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -274,6 +275,11 @@
isTetheringSupportedCalls++;
return true;
}
+
+ @Override
+ public int getDefaultDataSubscriptionId() {
+ return INVALID_SUBSCRIPTION_ID;
+ }
}
private static NetworkState buildMobileUpstreamState(boolean withIPv4, boolean withIPv6,
diff --git a/tests/net/java/com/android/server/connectivity/tethering/EntitlementManagerTest.java b/tests/net/java/com/android/server/connectivity/tethering/EntitlementManagerTest.java
index ec286759..193f380 100644
--- a/tests/net/java/com/android/server/connectivity/tethering/EntitlementManagerTest.java
+++ b/tests/net/java/com/android/server/connectivity/tethering/EntitlementManagerTest.java
@@ -21,6 +21,7 @@
import static android.net.ConnectivityManager.TETHER_ERROR_ENTITLEMENT_UNKONWN;
import static android.net.ConnectivityManager.TETHER_ERROR_NO_ERROR;
import static android.net.ConnectivityManager.TETHER_ERROR_PROVISION_FAILED;
+import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -140,7 +141,8 @@
mMockContext = new MockContext(mContext);
mSM = new TestStateMachine();
mEnMgr = new WrappedEntitlementManager(mMockContext, mSM, mLog, mSystemProperties);
- mEnMgr.updateConfiguration(new TetheringConfiguration(mMockContext, mLog));
+ mEnMgr.updateConfiguration(
+ new TetheringConfiguration(mMockContext, mLog, INVALID_SUBSCRIPTION_ID));
}
@After
@@ -168,7 +170,8 @@
@Test
public void canRequireProvisioning() {
setupForRequiredProvisioning();
- mEnMgr.updateConfiguration(new TetheringConfiguration(mMockContext, mLog));
+ mEnMgr.updateConfiguration(
+ new TetheringConfiguration(mMockContext, mLog, INVALID_SUBSCRIPTION_ID));
assertTrue(mEnMgr.isTetherProvisioningRequired());
}
@@ -177,7 +180,8 @@
setupForRequiredProvisioning();
when(mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE))
.thenReturn(null);
- mEnMgr.updateConfiguration(new TetheringConfiguration(mMockContext, mLog));
+ mEnMgr.updateConfiguration(
+ new TetheringConfiguration(mMockContext, mLog, INVALID_SUBSCRIPTION_ID));
// Couldn't get the CarrierConfigManager, but still had a declared provisioning app.
// Therefore provisioning still be required.
assertTrue(mEnMgr.isTetherProvisioningRequired());
@@ -187,7 +191,8 @@
public void toleratesCarrierConfigMissing() {
setupForRequiredProvisioning();
when(mCarrierConfigManager.getConfig()).thenReturn(null);
- mEnMgr.updateConfiguration(new TetheringConfiguration(mMockContext, mLog));
+ mEnMgr.updateConfiguration(
+ new TetheringConfiguration(mMockContext, mLog, INVALID_SUBSCRIPTION_ID));
// We still have a provisioning app configured, so still require provisioning.
assertTrue(mEnMgr.isTetherProvisioningRequired());
}
@@ -197,11 +202,13 @@
setupForRequiredProvisioning();
when(mResources.getStringArray(R.array.config_mobile_hotspot_provision_app))
.thenReturn(null);
- mEnMgr.updateConfiguration(new TetheringConfiguration(mMockContext, mLog));
+ mEnMgr.updateConfiguration(
+ new TetheringConfiguration(mMockContext, mLog, INVALID_SUBSCRIPTION_ID));
assertFalse(mEnMgr.isTetherProvisioningRequired());
when(mResources.getStringArray(R.array.config_mobile_hotspot_provision_app))
.thenReturn(new String[] {"malformedApp"});
- mEnMgr.updateConfiguration(new TetheringConfiguration(mMockContext, mLog));
+ mEnMgr.updateConfiguration(
+ new TetheringConfiguration(mMockContext, mLog, INVALID_SUBSCRIPTION_ID));
assertFalse(mEnMgr.isTetherProvisioningRequired());
}
@@ -223,7 +230,8 @@
assertFalse(mEnMgr.everRunUiEntitlement);
setupForRequiredProvisioning();
- mEnMgr.updateConfiguration(new TetheringConfiguration(mMockContext, mLog));
+ mEnMgr.updateConfiguration(new TetheringConfiguration(mMockContext, mLog,
+ INVALID_SUBSCRIPTION_ID));
// 2. No cache value and don't need to run entitlement check.
mEnMgr.everRunUiEntitlement = false;
receiver = new ResultReceiver(null) {
diff --git a/tests/net/java/com/android/server/connectivity/tethering/TetheringConfigurationTest.java b/tests/net/java/com/android/server/connectivity/tethering/TetheringConfigurationTest.java
index 5217784..01b904d8 100644
--- a/tests/net/java/com/android/server/connectivity/tethering/TetheringConfigurationTest.java
+++ b/tests/net/java/com/android/server/connectivity/tethering/TetheringConfigurationTest.java
@@ -22,10 +22,12 @@
import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
import static android.net.ConnectivityManager.TYPE_WIFI;
import static android.provider.Settings.Global.TETHER_ENABLE_LEGACY_DHCP_SERVER;
+import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
import static com.android.server.connectivity.tethering.TetheringConfiguration.DUN_NOT_REQUIRED;
import static com.android.server.connectivity.tethering.TetheringConfiguration.DUN_REQUIRED;
import static com.android.server.connectivity.tethering.TetheringConfiguration.DUN_UNSPECIFIED;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -44,26 +46,39 @@
import com.android.internal.util.test.BroadcastInterceptingContext;
import com.android.internal.util.test.FakeSettingsProvider;
-import java.util.Iterator;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import java.util.Iterator;
@RunWith(AndroidJUnit4.class)
@SmallTest
public class TetheringConfigurationTest {
private final SharedLog mLog = new SharedLog("TetheringConfigurationTest");
+
+ private static final String[] PROVISIONING_APP_NAME = {"some", "app"};
@Mock private Context mContext;
@Mock private TelephonyManager mTelephonyManager;
@Mock private Resources mResources;
+ @Mock private Resources mResourcesForSubId;
private MockContentResolver mContentResolver;
private Context mMockContext;
private boolean mHasTelephonyManager;
+ private class MockTetheringConfiguration extends TetheringConfiguration {
+ MockTetheringConfiguration(Context ctx, SharedLog log, int id) {
+ super(ctx, log, id);
+ }
+
+ @Override
+ protected Resources getResourcesForSubIdWrapper(Context ctx, int subId) {
+ return mResourcesForSubId;
+ }
+ }
+
private class MockContext extends BroadcastInterceptingContext {
MockContext(Context base) {
super(base);
@@ -99,6 +114,9 @@
.thenReturn(new String[0]);
when(mResources.getIntArray(com.android.internal.R.array.config_tether_upstream_types))
.thenReturn(new int[0]);
+ when(mResources.getStringArray(
+ com.android.internal.R.array.config_mobile_hotspot_provision_app))
+ .thenReturn(new String[0]);
mContentResolver = new MockContentResolver();
mContentResolver.addProvider(Settings.AUTHORITY, new FakeSettingsProvider());
mMockContext = new MockContext(mContext);
@@ -111,7 +129,8 @@
mHasTelephonyManager = true;
when(mTelephonyManager.getTetherApnRequired()).thenReturn(DUN_REQUIRED);
- final TetheringConfiguration cfg = new TetheringConfiguration(mMockContext, mLog);
+ final TetheringConfiguration cfg = new TetheringConfiguration(
+ mMockContext, mLog, INVALID_SUBSCRIPTION_ID);
assertTrue(cfg.isDunRequired);
assertTrue(cfg.preferredUpstreamIfaceTypes.contains(TYPE_MOBILE_DUN));
assertFalse(cfg.preferredUpstreamIfaceTypes.contains(TYPE_MOBILE));
@@ -127,7 +146,8 @@
mHasTelephonyManager = true;
when(mTelephonyManager.getTetherApnRequired()).thenReturn(DUN_NOT_REQUIRED);
- final TetheringConfiguration cfg = new TetheringConfiguration(mMockContext, mLog);
+ final TetheringConfiguration cfg = new TetheringConfiguration(
+ mMockContext, mLog, INVALID_SUBSCRIPTION_ID);
assertFalse(cfg.isDunRequired);
assertFalse(cfg.preferredUpstreamIfaceTypes.contains(TYPE_MOBILE_DUN));
assertTrue(cfg.preferredUpstreamIfaceTypes.contains(TYPE_MOBILE));
@@ -143,7 +163,8 @@
mHasTelephonyManager = false;
when(mTelephonyManager.getTetherApnRequired()).thenReturn(DUN_UNSPECIFIED);
- final TetheringConfiguration cfg = new TetheringConfiguration(mMockContext, mLog);
+ final TetheringConfiguration cfg = new TetheringConfiguration(
+ mMockContext, mLog, INVALID_SUBSCRIPTION_ID);
assertTrue(cfg.isDunRequired);
assertTrue(cfg.preferredUpstreamIfaceTypes.contains(TYPE_MOBILE_DUN));
// Just to prove we haven't clobbered Wi-Fi:
@@ -160,7 +181,8 @@
mHasTelephonyManager = false;
when(mTelephonyManager.getTetherApnRequired()).thenReturn(DUN_UNSPECIFIED);
- final TetheringConfiguration cfg = new TetheringConfiguration(mMockContext, mLog);
+ final TetheringConfiguration cfg = new TetheringConfiguration(
+ mMockContext, mLog, INVALID_SUBSCRIPTION_ID);
final Iterator<Integer> upstreamIterator = cfg.preferredUpstreamIfaceTypes.iterator();
assertTrue(upstreamIterator.hasNext());
assertEquals(TYPE_ETHERNET, upstreamIterator.next().intValue());
@@ -181,7 +203,8 @@
mHasTelephonyManager = false;
when(mTelephonyManager.getTetherApnRequired()).thenReturn(DUN_UNSPECIFIED);
- final TetheringConfiguration cfg = new TetheringConfiguration(mMockContext, mLog);
+ final TetheringConfiguration cfg = new TetheringConfiguration(
+ mMockContext, mLog, INVALID_SUBSCRIPTION_ID);
final Iterator<Integer> upstreamIterator = cfg.preferredUpstreamIfaceTypes.iterator();
assertTrue(upstreamIterator.hasNext());
assertEquals(TYPE_ETHERNET, upstreamIterator.next().intValue());
@@ -199,7 +222,8 @@
mHasTelephonyManager = false;
when(mTelephonyManager.getTetherApnRequired()).thenReturn(DUN_UNSPECIFIED);
- final TetheringConfiguration cfg = new TetheringConfiguration(mMockContext, mLog);
+ final TetheringConfiguration cfg = new TetheringConfiguration(
+ mMockContext, mLog, INVALID_SUBSCRIPTION_ID);
final Iterator<Integer> upstreamIterator = cfg.preferredUpstreamIfaceTypes.iterator();
assertTrue(upstreamIterator.hasNext());
assertEquals(TYPE_WIFI, upstreamIterator.next().intValue());
@@ -214,7 +238,8 @@
public void testNewDhcpServerDisabled() {
Settings.Global.putInt(mContentResolver, TETHER_ENABLE_LEGACY_DHCP_SERVER, 1);
- final TetheringConfiguration cfg = new TetheringConfiguration(mMockContext, mLog);
+ final TetheringConfiguration cfg = new TetheringConfiguration(
+ mMockContext, mLog, INVALID_SUBSCRIPTION_ID);
assertTrue(cfg.enableLegacyDhcpServer);
}
@@ -222,7 +247,41 @@
public void testNewDhcpServerEnabled() {
Settings.Global.putInt(mContentResolver, TETHER_ENABLE_LEGACY_DHCP_SERVER, 0);
- final TetheringConfiguration cfg = new TetheringConfiguration(mMockContext, mLog);
+ final TetheringConfiguration cfg = new TetheringConfiguration(
+ mMockContext, mLog, INVALID_SUBSCRIPTION_ID);
assertFalse(cfg.enableLegacyDhcpServer);
}
+
+ @Test
+ public void testGetResourcesBySubId() {
+ setUpResourceForSubId();
+ final TetheringConfiguration cfg = new TetheringConfiguration(
+ mMockContext, mLog, INVALID_SUBSCRIPTION_ID);
+ assertTrue(cfg.provisioningApp.length == 0);
+ final int anyValidSubId = 1;
+ final MockTetheringConfiguration mockCfg =
+ new MockTetheringConfiguration(mMockContext, mLog, anyValidSubId);
+ assertEquals(mockCfg.provisioningApp[0], PROVISIONING_APP_NAME[0]);
+ assertEquals(mockCfg.provisioningApp[1], PROVISIONING_APP_NAME[1]);
+ }
+
+ private void setUpResourceForSubId() {
+ when(mResourcesForSubId.getStringArray(
+ com.android.internal.R.array.config_tether_dhcp_range)).thenReturn(new String[0]);
+ when(mResourcesForSubId.getStringArray(
+ com.android.internal.R.array.config_tether_usb_regexs)).thenReturn(new String[0]);
+ when(mResourcesForSubId.getStringArray(
+ com.android.internal.R.array.config_tether_wifi_regexs))
+ .thenReturn(new String[]{ "test_wlan\\d" });
+ when(mResourcesForSubId.getStringArray(
+ com.android.internal.R.array.config_tether_bluetooth_regexs))
+ .thenReturn(new String[0]);
+ when(mResourcesForSubId.getIntArray(
+ com.android.internal.R.array.config_tether_upstream_types))
+ .thenReturn(new int[0]);
+ when(mResourcesForSubId.getStringArray(
+ com.android.internal.R.array.config_mobile_hotspot_provision_app))
+ .thenReturn(PROVISIONING_APP_NAME);
+ }
+
}
diff --git a/tools/aapt2/Resources.proto b/tools/aapt2/Resources.proto
index 73b568e..9a1d942 100644
--- a/tools/aapt2/Resources.proto
+++ b/tools/aapt2/Resources.proto
@@ -151,10 +151,12 @@
// Represents an overlayable <item> declaration within an <overlayable> tag.
message OverlayableItem {
enum Policy {
- PUBLIC = 0;
- SYSTEM = 1;
- VENDOR = 2;
- PRODUCT = 3;
+ NONE = 0;
+ PUBLIC = 1;
+ SYSTEM = 2;
+ VENDOR = 3;
+ PRODUCT = 4;
+ SIGNATURE = 5;
}
// The location of the <item> declaration in source.
diff --git a/tools/aapt2/link/ManifestFixer.cpp b/tools/aapt2/link/ManifestFixer.cpp
index 85bf6f2..582a5b8 100644
--- a/tools/aapt2/link/ManifestFixer.cpp
+++ b/tools/aapt2/link/ManifestFixer.cpp
@@ -294,22 +294,6 @@
}
}
- if (el->FindAttribute("", "platformBuildVersionCode") == nullptr) {
- auto versionCode = el->FindAttribute(xml::kSchemaAndroid, "versionCode");
- if (versionCode != nullptr) {
- el->attributes.push_back(xml::Attribute{"", "platformBuildVersionCode",
- versionCode->value});
- }
- }
-
- if (el->FindAttribute("", "platformBuildVersionName") == nullptr) {
- auto versionName = el->FindAttribute(xml::kSchemaAndroid, "versionName");
- if (versionName != nullptr) {
- el->attributes.push_back(xml::Attribute{"", "platformBuildVersionName",
- versionName->value});
- }
- }
-
return true;
});
@@ -489,8 +473,14 @@
// Make sure we un-compile the value if it was set to something else.
attr->compiled_value = {};
-
attr->value = options_.compile_sdk_version.value();
+
+ attr = root->FindOrCreateAttribute("", "platformBuildVersionCode");
+
+ // Make sure we un-compile the value if it was set to something else.
+ attr->compiled_value = {};
+ attr->value = options_.compile_sdk_version.value();
+
}
if (options_.compile_sdk_version_codename) {
@@ -499,7 +489,12 @@
// Make sure we un-compile the value if it was set to something else.
attr->compiled_value = {};
+ attr->value = options_.compile_sdk_version_codename.value();
+ attr = root->FindOrCreateAttribute("", "platformBuildVersionName");
+
+ // Make sure we un-compile the value if it was set to something else.
+ attr->compiled_value = {};
attr->value = options_.compile_sdk_version_codename.value();
}
diff --git a/tools/aapt2/link/ManifestFixer_test.cpp b/tools/aapt2/link/ManifestFixer_test.cpp
index adea627..4842f62 100644
--- a/tools/aapt2/link/ManifestFixer_test.cpp
+++ b/tools/aapt2/link/ManifestFixer_test.cpp
@@ -725,6 +725,43 @@
attr = manifest->root->FindAttribute(xml::kSchemaAndroid, "compileSdkVersionCodename");
ASSERT_THAT(attr, NotNull());
EXPECT_THAT(attr->value, StrEq("P"));
+
+ attr = manifest->root->FindAttribute("", "platformBuildVersionCode");
+ ASSERT_THAT(attr, NotNull());
+ EXPECT_THAT(attr->value, StrEq("28"));
+
+ attr = manifest->root->FindAttribute("", "platformBuildVersionName");
+ ASSERT_THAT(attr, NotNull());
+ EXPECT_THAT(attr->value, StrEq("P"));
+}
+
+TEST_F(ManifestFixerTest, OverrideCompileSdkVersions) {
+ std::string input = R"(
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="android"
+ compileSdkVersion="27" compileSdkVersionCodename="O"
+ platformBuildVersionCode="27" platformBuildVersionName="O"/>)";
+ ManifestFixerOptions options;
+ options.compile_sdk_version = {"28"};
+ options.compile_sdk_version_codename = {"P"};
+
+ std::unique_ptr<xml::XmlResource> manifest = VerifyWithOptions(input, options);
+ ASSERT_THAT(manifest, NotNull());
+
+ xml::Attribute* attr = manifest->root->FindAttribute(xml::kSchemaAndroid, "compileSdkVersion");
+ ASSERT_THAT(attr, NotNull());
+ EXPECT_THAT(attr->value, StrEq("28"));
+
+ attr = manifest->root->FindAttribute(xml::kSchemaAndroid, "compileSdkVersionCodename");
+ ASSERT_THAT(attr, NotNull());
+ EXPECT_THAT(attr->value, StrEq("P"));
+
+ attr = manifest->root->FindAttribute("", "platformBuildVersionCode");
+ ASSERT_THAT(attr, NotNull());
+ EXPECT_THAT(attr->value, StrEq("28"));
+
+ attr = manifest->root->FindAttribute("", "platformBuildVersionName");
+ ASSERT_THAT(attr, NotNull());
+ EXPECT_THAT(attr->value, StrEq("P"));
}
TEST_F(ManifestFixerTest, UnexpectedElementsInManifest) {
@@ -750,59 +787,6 @@
ASSERT_THAT(manifest, IsNull());
}
-TEST_F(ManifestFixerTest, InsertPlatformBuildVersions) {
- // Test for insertion when versionCode and versionName are included in the manifest
- {
- std::string input = R"(
- <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="android"
- android:versionCode="27" android:versionName="O"/>)";
- std::unique_ptr<xml::XmlResource> manifest = Verify(input);
- ASSERT_THAT(manifest, NotNull());
-
- xml::Attribute* attr = manifest->root->FindAttribute("", "platformBuildVersionCode");
- ASSERT_THAT(attr, NotNull());
- EXPECT_THAT(attr->value, StrEq("27"));
- attr = manifest->root->FindAttribute("", "platformBuildVersionName");
- ASSERT_THAT(attr, NotNull());
- EXPECT_THAT(attr->value, StrEq("O"));
- }
-
- // Test for insertion when versionCode and versionName defaults are specified
- {
- std::string input = R"(
- <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="android"/>)";
- ManifestFixerOptions options;
- options.version_code_default = {"27"};
- options.version_name_default = {"O"};
- std::unique_ptr<xml::XmlResource> manifest = VerifyWithOptions(input, options);
- ASSERT_THAT(manifest, NotNull());
-
- xml::Attribute* attr = manifest->root->FindAttribute("", "platformBuildVersionCode");
- ASSERT_THAT(attr, NotNull());
- EXPECT_THAT(attr->value, StrEq("27"));
- attr = manifest->root->FindAttribute("", "platformBuildVersionName");
- ASSERT_THAT(attr, NotNull());
- EXPECT_THAT(attr->value, StrEq("O"));
- }
-
- // Test that the platform build version attributes are not changed if they are currently present
- {
- std::string input = R"(
- <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="android"
- android:versionCode="28" android:versionName="P"
- platformBuildVersionCode="27" platformBuildVersionName="O"/>)";
- std::unique_ptr<xml::XmlResource> manifest = Verify(input);
- ASSERT_THAT(manifest, NotNull());
-
- xml::Attribute* attr = manifest->root->FindAttribute("", "platformBuildVersionCode");
- ASSERT_THAT(attr, NotNull());
- EXPECT_THAT(attr->value, StrEq("27"));
- attr = manifest->root->FindAttribute("", "platformBuildVersionName");
- ASSERT_THAT(attr, NotNull());
- EXPECT_THAT(attr->value, StrEq("O"));
- }
-}
-
TEST_F(ManifestFixerTest, UsesLibraryMustHaveNonEmptyName) {
std::string input = R"(
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
diff --git a/tools/preload/Android.bp b/tools/preload/Android.bp
new file mode 100644
index 0000000..809ee47
--- /dev/null
+++ b/tools/preload/Android.bp
@@ -0,0 +1,17 @@
+java_library_host {
+ name: "preload",
+ srcs: [
+ "Compile.java",
+ "LoadedClass.java",
+ "MemoryUsage.java",
+ "Operation.java",
+ "Policy.java",
+ "PrintCsv.java",
+ "PrintHtmlDiff.java",
+ "PrintPsTree.java",
+ "Proc.java",
+ "Record.java",
+ "Root.java",
+ "WritePreloadedClassFile.java",
+ ],
+}
diff --git a/tools/preload/Android.mk b/tools/preload/Android.mk
deleted file mode 100644
index 14a4547..0000000
--- a/tools/preload/Android.mk
+++ /dev/null
@@ -1,23 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := \
- Compile.java \
- LoadedClass.java \
- MemoryUsage.java \
- Operation.java \
- Policy.java \
- PrintCsv.java \
- PrintHtmlDiff.java \
- PrintPsTree.java \
- Proc.java \
- Record.java \
- Root.java \
- WritePreloadedClassFile.java
-
-LOCAL_MODULE:= preload
-
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tools/preload/loadclass/Android.bp b/tools/preload/loadclass/Android.bp
new file mode 100644
index 0000000..6f12015
--- /dev/null
+++ b/tools/preload/loadclass/Android.bp
@@ -0,0 +1,4 @@
+java_test {
+ name: "loadclass",
+ srcs: ["**/*.java"],
+}
diff --git a/tools/preload/loadclass/Android.mk b/tools/preload/loadclass/Android.mk
deleted file mode 100644
index 65828be..0000000
--- a/tools/preload/loadclass/Android.mk
+++ /dev/null
@@ -1,9 +0,0 @@
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_MODULE := loadclass
-
-include $(BUILD_JAVA_LIBRARY)
diff --git a/wifi/java/android/net/wifi/WifiManager.java b/wifi/java/android/net/wifi/WifiManager.java
index 2cc1d83..5e5a595 100644
--- a/wifi/java/android/net/wifi/WifiManager.java
+++ b/wifi/java/android/net/wifi/WifiManager.java
@@ -1149,9 +1149,6 @@
* Return a list of all the networks configured for the current foreground
* user.
*
- * Requires the same permissions as {@link #getScanResults}.
- * If such access is not allowed, this API will always return an empty list.
- *
* Not all fields of WifiConfiguration are returned. Only the following
* fields are filled in:
* <ul>
@@ -1176,8 +1173,12 @@
* when auto-connecting to wifi.
* <b>Compatibility Note:</b> For applications targeting
* {@link android.os.Build.VERSION_CODES#Q} or above, this API will return an empty list,
- * except to callers with Carrier privilege which will receive a restricted list only
- * containing configurations which they created.
+ * except for:
+ * <ul>
+ * <li>Device Owner (DO) & Profile Owner (PO) apps will have access to the full list.
+ * <li>Callers with Carrier privilege will receive a restricted list only containing
+ * configurations which they created.
+ * </ul>
*/
@Deprecated
@RequiresPermission(allOf = {ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE})
@@ -4721,7 +4722,6 @@
*
* @hide
*/
- @SystemApi
private static class EasyConnectCallbackProxy extends IDppCallback.Stub {
private final Executor mExecutor;
private final EasyConnectStatusCallback mEasyConnectStatusCallback;
diff --git a/wifi/java/android/net/wifi/aware/ParcelablePeerHandle.java b/wifi/java/android/net/wifi/aware/ParcelablePeerHandle.java
new file mode 100644
index 0000000..4ddf872
--- /dev/null
+++ b/wifi/java/android/net/wifi/aware/ParcelablePeerHandle.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net.wifi.aware;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+/**
+ * A Parcelable {@link PeerHandle}. Can be constructed from a {@code PeerHandle} and then passed
+ * to any of the APIs which take a {@code PeerHandle} as inputs.
+ */
+public final class ParcelablePeerHandle extends PeerHandle implements Parcelable {
+ /**
+ * Construct a parcelable version of {@link PeerHandle}.
+ *
+ * @param peerHandle The {@link PeerHandle} to be made parcelable.
+ */
+ public ParcelablePeerHandle(PeerHandle peerHandle) {
+ super(peerHandle.peerId);
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(Parcel dest, int flags) {
+ dest.writeInt(peerId);
+ }
+
+ public static final Creator<ParcelablePeerHandle> CREATOR =
+ new Creator<ParcelablePeerHandle>() {
+ @Override
+ public ParcelablePeerHandle[] newArray(int size) {
+ return new ParcelablePeerHandle[size];
+ }
+
+ @Override
+ public ParcelablePeerHandle createFromParcel(Parcel in) {
+ int peerHandle = in.readInt();
+ return new ParcelablePeerHandle(new PeerHandle(peerHandle));
+ }
+ };
+}
diff --git a/wifi/java/android/net/wifi/aware/PeerHandle.java b/wifi/java/android/net/wifi/aware/PeerHandle.java
index 1603d00..422e177 100644
--- a/wifi/java/android/net/wifi/aware/PeerHandle.java
+++ b/wifi/java/android/net/wifi/aware/PeerHandle.java
@@ -16,9 +16,6 @@
package android.net.wifi.aware;
-import android.os.Parcel;
-import android.os.Parcelable;
-
/**
* Opaque object used to represent a Wi-Fi Aware peer. Obtained from discovery sessions in
* {@link DiscoverySessionCallback#onServiceDiscovered(PeerHandle, byte[], java.util.List)} or
@@ -35,8 +32,9 @@
* configuration's service-specific information field,
* {@link PublishConfig.Builder#setServiceSpecificInfo(byte[])}, or match filter,
* {@link PublishConfig.Builder#setMatchFilter(java.util.List)}.
+ * <p>A parcelable handle object is available with {@link ParcelablePeerHandle}.
*/
-public final class PeerHandle implements Parcelable {
+public class PeerHandle {
/** @hide */
public PeerHandle(int peerId) {
this.peerId = peerId;
@@ -62,29 +60,4 @@
public int hashCode() {
return peerId;
}
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(peerId);
- }
-
- public static final Creator<PeerHandle> CREATOR = new Creator<PeerHandle>() {
- @Override
- public PeerHandle[] newArray(int size) {
- return new PeerHandle[size];
- }
-
- @Override
- public PeerHandle createFromParcel(Parcel in) {
- int peerHandle = in.readInt();
-
- return new PeerHandle(peerHandle);
- }
- };
-
}
diff --git a/wifi/java/android/net/wifi/aware/TlvBufferUtils.java b/wifi/java/android/net/wifi/aware/TlvBufferUtils.java
index 29f10e9..b3b5b29 100644
--- a/wifi/java/android/net/wifi/aware/TlvBufferUtils.java
+++ b/wifi/java/android/net/wifi/aware/TlvBufferUtils.java
@@ -61,6 +61,7 @@
public static class TlvConstructor {
private int mTypeSize;
private int mLengthSize;
+ private ByteOrder mByteOrder = ByteOrder.BIG_ENDIAN;
private byte[] mArray;
private int mArrayLength;
@@ -84,6 +85,20 @@
}
mTypeSize = typeSize;
mLengthSize = lengthSize;
+ mPosition = 0;
+ }
+
+ /**
+ * Configure the TLV constructor to use a particular byte order. Should be
+ * {@link ByteOrder#BIG_ENDIAN} (the default at construction) or
+ * {@link ByteOrder#LITTLE_ENDIAN}.
+ *
+ * @return The constructor to facilitate chaining
+ * {@code ctr.putXXX(..).putXXX(..)}.
+ */
+ public TlvConstructor setByteOrder(ByteOrder byteOrder) {
+ mByteOrder = byteOrder;
+ return this;
}
/**
@@ -96,6 +111,7 @@
public TlvConstructor wrap(@Nullable byte[] array) {
mArray = array;
mArrayLength = (array == null) ? 0 : array.length;
+ mPosition = 0;
return this;
}
@@ -109,6 +125,7 @@
public TlvConstructor allocate(int capacity) {
mArray = new byte[capacity];
mArrayLength = capacity;
+ mPosition = 0;
return this;
}
@@ -155,6 +172,18 @@
}
/**
+ * Copies a raw byte into the TLV buffer - without a type or a length.
+ *
+ * @param b The byte to be inserted into the structure.
+ * @return The constructor to facilitate chaining {@code cts.putXXX(..).putXXX(..)}.
+ */
+ public TlvConstructor putRawByte(byte b) {
+ checkRawLength(1);
+ mArray[mPosition++] = b;
+ return this;
+ }
+
+ /**
* Copies a byte array into the TLV with the indicated type. For an LV
* formatted structure (i.e. typeLength=0 in {@link TlvConstructor
* TlvConstructor(int, int)} ) the type field is ignored.
@@ -193,6 +222,22 @@
}
/**
+ * Copies a byte array into the TLV - without a type or a length.
+ *
+ * @param array The array to be copied (in full) into the TLV structure.
+ * @return The constructor to facilitate chaining
+ * {@code ctr.putXXX(..).putXXX(..)}.
+ */
+ public TlvConstructor putRawByteArray(@Nullable byte[] array) {
+ if (array == null) return this;
+
+ checkRawLength(array.length);
+ System.arraycopy(array, 0, mArray, mPosition, array.length);
+ mPosition += array.length;
+ return this;
+ }
+
+ /**
* Places a zero length element (i.e. Length field = 0) into the TLV.
* For an LV formatted structure (i.e. typeLength=0 in
* {@link TlvConstructor TlvConstructor(int, int)} ) the type field is
@@ -221,7 +266,7 @@
public TlvConstructor putShort(int type, short data) {
checkLength(2);
addHeader(type, 2);
- Memory.pokeShort(mArray, mPosition, data, ByteOrder.BIG_ENDIAN);
+ Memory.pokeShort(mArray, mPosition, data, mByteOrder);
mPosition += 2;
return this;
}
@@ -239,7 +284,7 @@
public TlvConstructor putInt(int type, int data) {
checkLength(4);
addHeader(type, 4);
- Memory.pokeInt(mArray, mPosition, data, ByteOrder.BIG_ENDIAN);
+ Memory.pokeInt(mArray, mPosition, data, mByteOrder);
mPosition += 4;
return this;
}
@@ -294,18 +339,24 @@
}
}
+ private void checkRawLength(int dataLength) {
+ if (mPosition + dataLength > mArrayLength) {
+ throw new BufferOverflowException();
+ }
+ }
+
private void addHeader(int type, int length) {
if (mTypeSize == 1) {
mArray[mPosition] = (byte) type;
} else if (mTypeSize == 2) {
- Memory.pokeShort(mArray, mPosition, (short) type, ByteOrder.BIG_ENDIAN);
+ Memory.pokeShort(mArray, mPosition, (short) type, mByteOrder);
}
mPosition += mTypeSize;
if (mLengthSize == 1) {
mArray[mPosition] = (byte) length;
} else if (mLengthSize == 2) {
- Memory.pokeShort(mArray, mPosition, (short) length, ByteOrder.BIG_ENDIAN);
+ Memory.pokeShort(mArray, mPosition, (short) length, mByteOrder);
}
mPosition += mLengthSize;
}
@@ -330,13 +381,19 @@
public int length;
/**
+ * Control of the endianess of the TLV element - true for big-endian, false for little-
+ * endian.
+ */
+ public ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
+
+ /**
* The Value (V) field - a raw byte array representing the current TLV
* element where the entry starts at {@link TlvElement#offset}.
*/
- public byte[] refArray;
+ private byte[] mRefArray;
/**
- * The offset to be used into {@link TlvElement#refArray} to access the
+ * The offset to be used into {@link TlvElement#mRefArray} to access the
* raw data representing the current TLV element.
*/
public int offset;
@@ -344,7 +401,7 @@
private TlvElement(int type, int length, @Nullable byte[] refArray, int offset) {
this.type = type;
this.length = length;
- this.refArray = refArray;
+ mRefArray = refArray;
this.offset = offset;
if (offset + length > refArray.length) {
@@ -353,6 +410,15 @@
}
/**
+ * Return the raw byte array of the Value (V) field.
+ *
+ * @return The Value (V) field as a byte array.
+ */
+ public byte[] getRawData() {
+ return Arrays.copyOfRange(mRefArray, offset, offset + length);
+ }
+
+ /**
* Utility function to return a byte representation of a TLV element of
* length 1. Note: an attempt to call this function on a TLV item whose
* {@link TlvElement#length} is != 1 will result in an exception.
@@ -364,7 +430,7 @@
throw new IllegalArgumentException(
"Accesing a byte from a TLV element of length " + length);
}
- return refArray[offset];
+ return mRefArray[offset];
}
/**
@@ -379,7 +445,7 @@
throw new IllegalArgumentException(
"Accesing a short from a TLV element of length " + length);
}
- return Memory.peekShort(refArray, offset, ByteOrder.BIG_ENDIAN);
+ return Memory.peekShort(mRefArray, offset, byteOrder);
}
/**
@@ -394,7 +460,7 @@
throw new IllegalArgumentException(
"Accesing an int from a TLV element of length " + length);
}
- return Memory.peekInt(refArray, offset, ByteOrder.BIG_ENDIAN);
+ return Memory.peekInt(mRefArray, offset, byteOrder);
}
/**
@@ -403,7 +469,7 @@
* @return String repersentation of the current TLV element.
*/
public String getString() {
- return new String(refArray, offset, length);
+ return new String(mRefArray, offset, length);
}
}
@@ -413,6 +479,7 @@
public static class TlvIterable implements Iterable<TlvElement> {
private int mTypeSize;
private int mLengthSize;
+ private ByteOrder mByteOrder = ByteOrder.BIG_ENDIAN;
private byte[] mArray;
private int mArrayLength;
@@ -440,6 +507,13 @@
}
/**
+ * Configure the TLV iterator to use little-endian byte ordering.
+ */
+ public void setByteOrder(ByteOrder byteOrder) {
+ mByteOrder = byteOrder;
+ }
+
+ /**
* Prints out a parsed representation of the TLV-formatted byte array.
* Whenever possible bytes, shorts, and integer are printed out (for
* fields whose length is 1, 2, or 4 respectively).
@@ -486,7 +560,7 @@
public List<byte[]> toList() {
List<byte[]> list = new ArrayList<>();
for (TlvElement tlv : this) {
- list.add(Arrays.copyOfRange(tlv.refArray, tlv.offset, tlv.offset + tlv.length));
+ list.add(Arrays.copyOfRange(tlv.mRefArray, tlv.offset, tlv.offset + tlv.length));
}
return list;
@@ -516,7 +590,7 @@
if (mTypeSize == 1) {
type = mArray[mOffset];
} else if (mTypeSize == 2) {
- type = Memory.peekShort(mArray, mOffset, ByteOrder.BIG_ENDIAN);
+ type = Memory.peekShort(mArray, mOffset, mByteOrder);
}
mOffset += mTypeSize;
@@ -524,11 +598,12 @@
if (mLengthSize == 1) {
length = mArray[mOffset];
} else if (mLengthSize == 2) {
- length = Memory.peekShort(mArray, mOffset, ByteOrder.BIG_ENDIAN);
+ length = Memory.peekShort(mArray, mOffset, mByteOrder);
}
mOffset += mLengthSize;
TlvElement tlv = new TlvElement(type, length, mArray, mOffset);
+ tlv.byteOrder = mByteOrder;
mOffset += length;
return tlv;
}
@@ -543,7 +618,8 @@
/**
* Validates that a (T)LV array is constructed correctly. I.e. that its specified Length
- * fields correctly fill the specified length (and do not overshoot).
+ * fields correctly fill the specified length (and do not overshoot). Uses big-endian
+ * byte ordering.
*
* @param array The (T)LV array to verify.
* @param typeSize The size (in bytes) of the type field. Valid values are 0, 1, or 2.
@@ -551,6 +627,22 @@
* @return A boolean indicating whether the array is valid (true) or invalid (false).
*/
public static boolean isValid(@Nullable byte[] array, int typeSize, int lengthSize) {
+ return isValidEndian(array, typeSize, lengthSize, ByteOrder.BIG_ENDIAN);
+ }
+
+ /**
+ * Validates that a (T)LV array is constructed correctly. I.e. that its specified Length
+ * fields correctly fill the specified length (and do not overshoot).
+ *
+ * @param array The (T)LV array to verify.
+ * @param typeSize The size (in bytes) of the type field. Valid values are 0, 1, or 2.
+ * @param lengthSize The size (in bytes) of the length field. Valid values are 1 or 2.
+ * @param byteOrder The endianness of the byte array: {@link ByteOrder#BIG_ENDIAN} or
+ * {@link ByteOrder#LITTLE_ENDIAN}.
+ * @return A boolean indicating whether the array is valid (true) or invalid (false).
+ */
+ public static boolean isValidEndian(@Nullable byte[] array, int typeSize, int lengthSize,
+ ByteOrder byteOrder) {
if (typeSize < 0 || typeSize > 2) {
throw new IllegalArgumentException(
"Invalid arguments - typeSize must be 0, 1, or 2: typeSize=" + typeSize);
@@ -569,8 +661,7 @@
if (lengthSize == 1) {
nextTlvIndex += lengthSize + array[nextTlvIndex];
} else {
- nextTlvIndex += lengthSize + Memory.peekShort(array, nextTlvIndex,
- ByteOrder.BIG_ENDIAN);
+ nextTlvIndex += lengthSize + Memory.peekShort(array, nextTlvIndex, byteOrder);
}
}
diff --git a/wifi/tests/src/android/net/wifi/aware/TlvBufferUtilsTest.java b/wifi/tests/src/android/net/wifi/aware/TlvBufferUtilsTest.java
index 83affed..971aa8e 100644
--- a/wifi/tests/src/android/net/wifi/aware/TlvBufferUtilsTest.java
+++ b/wifi/tests/src/android/net/wifi/aware/TlvBufferUtilsTest.java
@@ -28,6 +28,7 @@
import java.util.ArrayList;
import java.util.List;
+
/**
* Unit test harness for TlvBufferUtils class.
*/
@@ -69,6 +70,24 @@
}
/**
+ * Validate that re-using a TLV by any of the reallocation method resets it completely.
+ */
+ @Test
+ public void testTlvReuse() {
+ TlvBufferUtils.TlvConstructor tlv = new TlvBufferUtils.TlvConstructor(1, 1);
+
+ tlv.allocate(10);
+ tlv.putByte(0, (byte) 2);
+ tlv.putByte(1, (byte) 104);
+
+ collector.checkThat("initial", tlv.getArray(), equalTo(new byte[]{0, 1, 2, 1, 1, 104}));
+
+ tlv.allocate(8);
+ tlv.putByte(5, (byte) 7);
+ collector.checkThat("re-alloc", tlv.getArray(), equalTo(new byte[]{5, 1, 7}));
+ }
+
+ /**
* Verify that can build a valid TLV from a List of byte[].
*/
@Test
@@ -121,6 +140,23 @@
List<byte[]> data = new TlvBufferUtils.TlvIterable(0, 1, invalidTlv01).toList();
}
+ /**
+ * Validate the API which places raw bytes into the TLV (without a TL structure).
+ */
+ @Test
+ public void testRawPuts() {
+ TlvBufferUtils.TlvConstructor tlv = new TlvBufferUtils.TlvConstructor(1, 1);
+
+ tlv.allocate(10);
+ tlv.putByte(0, (byte) 2);
+ tlv.putRawByte((byte) 55);
+ tlv.putByte(1, (byte) 104);
+ tlv.putRawByteArray(new byte[]{66, 77});
+
+ collector.checkThat("data", tlv.getArray(),
+ equalTo(new byte[]{0, 1, 2, 55, 1, 1, 104, 66, 77}));
+ }
+
@Test
public void testTlvIterate() {
final String ascii = "ABC";
@@ -163,6 +199,7 @@
tlv02.putByte(0, (byte) 2);
tlv02.putString(0, ascii);
tlv02.putString(0, nonAscii);
+ tlv02.putByteArray(0, new byte[]{5, 4, 3, 2, 1});
TlvBufferUtils.TlvIterable tlv02It = new TlvBufferUtils.TlvIterable(0, 2, tlv02.getArray());
count = 0;
@@ -181,6 +218,11 @@
equalTo(nonAscii.getBytes().length));
collector.checkThat("tlv02-correct-iteration-DATA",
tlv.getString().equals(nonAscii), equalTo(true));
+ } else if (count == 3) {
+ collector.checkThat("tlv02-correct-iteration-mLength", tlv.length,
+ equalTo(5));
+ collector.checkThat("tlv02-correct-iteration-DATA", tlv.getRawData(),
+ equalTo(new byte[]{5, 4, 3, 2, 1}));
} else {
collector.checkThat("Invalid number of iterations in loop - tlv02", true,
equalTo(false));
@@ -188,7 +230,7 @@
++count;
}
collector.checkThat("Invalid number of iterations outside loop - tlv02", count,
- equalTo(3));
+ equalTo(4));
collector.checkThat("tlv22-valid",
TlvBufferUtils.isValid(tlv22.getArray(), 2, 2),
diff --git a/wifi/tests/src/android/net/wifi/aware/WifiAwareManagerTest.java b/wifi/tests/src/android/net/wifi/aware/WifiAwareManagerTest.java
index 6da6d4a..3cc96bf 100644
--- a/wifi/tests/src/android/net/wifi/aware/WifiAwareManagerTest.java
+++ b/wifi/tests/src/android/net/wifi/aware/WifiAwareManagerTest.java
@@ -1614,23 +1614,31 @@
assertEquals(cap.hashCode(), rereadCap.hashCode());
}
- // PeerHandle tests
+ // ParcelablePeerHandle tests
+ /**
+ * Verify parceling of ParcelablePeerHandle and interoperability with PeerHandle.
+ */
@Test
- public void testPeerHandleParcel() {
+ public void testParcelablePeerHandleParcel() {
final PeerHandle peerHandle = new PeerHandle(5);
+ final ParcelablePeerHandle parcelablePeerHandle = new ParcelablePeerHandle(peerHandle);
Parcel parcelW = Parcel.obtain();
- peerHandle.writeToParcel(parcelW, 0);
+ parcelablePeerHandle.writeToParcel(parcelW, 0);
byte[] bytes = parcelW.marshall();
parcelW.recycle();
Parcel parcelR = Parcel.obtain();
parcelR.unmarshall(bytes, 0, bytes.length);
parcelR.setDataPosition(0);
- PeerHandle rereadPeerHandle = PeerHandle.CREATOR.createFromParcel(parcelR);
+ ParcelablePeerHandle rereadParcelablePeerHandle =
+ ParcelablePeerHandle.CREATOR.createFromParcel(parcelR);
- assertEquals(peerHandle, rereadPeerHandle);
- assertEquals(peerHandle.hashCode(), rereadPeerHandle.hashCode());
+ assertEquals(peerHandle, rereadParcelablePeerHandle);
+ assertEquals(peerHandle.hashCode(), rereadParcelablePeerHandle.hashCode());
+ assertEquals(parcelablePeerHandle, rereadParcelablePeerHandle);
+ assertEquals(parcelablePeerHandle.hashCode(), rereadParcelablePeerHandle.hashCode());
+
}
}