Merge "Handle atomic formula max value size"
diff --git a/api/current.txt b/api/current.txt
index cba0a3c..c734db5 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -23803,9 +23803,9 @@
method public void loadSoundEffects();
method public void playSoundEffect(int);
method public void playSoundEffect(int, float);
- method public void registerAudioDeviceCallback(android.media.AudioDeviceCallback, android.os.Handler);
- method public void registerAudioPlaybackCallback(@NonNull android.media.AudioManager.AudioPlaybackCallback, android.os.Handler);
- method public void registerAudioRecordingCallback(@NonNull android.media.AudioManager.AudioRecordingCallback, android.os.Handler);
+ method public void registerAudioDeviceCallback(android.media.AudioDeviceCallback, @Nullable android.os.Handler);
+ method public void registerAudioPlaybackCallback(@NonNull android.media.AudioManager.AudioPlaybackCallback, @Nullable android.os.Handler);
+ method public void registerAudioRecordingCallback(@NonNull android.media.AudioManager.AudioRecordingCallback, @Nullable android.os.Handler);
method @Deprecated public void registerMediaButtonEventReceiver(android.content.ComponentName);
method @Deprecated public void registerMediaButtonEventReceiver(android.app.PendingIntent);
method @Deprecated public void registerRemoteControlClient(android.media.RemoteControlClient);
@@ -46004,6 +46004,7 @@
method public int getSimState();
method public int getSimState(int);
method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public String getSubscriberId();
+ method public int getSubscriptionId();
method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public int getSubscriptionId(@NonNull android.telecom.PhoneAccountHandle);
method public int getSupportedModemCount();
method @Nullable public String getTypeAllocationCode();
diff --git a/api/system-current.txt b/api/system-current.txt
index e056419..b79289f 100755
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -2414,9 +2414,13 @@
method @Nullable public android.hardware.display.BrightnessCorrection getCorrectionByCategory(int);
method @Nullable public android.hardware.display.BrightnessCorrection getCorrectionByPackageName(@NonNull String);
method public android.util.Pair<float[],float[]> getCurve();
+ method public float getShortTermModelLowerLuxMultiplier();
+ method public long getShortTermModelTimeout();
+ method public float getShortTermModelUpperLuxMultiplier();
method public boolean shouldCollectColorSamples();
method public void writeToParcel(android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.hardware.display.BrightnessConfiguration> CREATOR;
+ field public static final long SHORT_TERM_TIMEOUT_UNSET = -1L; // 0xffffffffffffffffL
}
public static class BrightnessConfiguration.Builder {
@@ -2427,6 +2431,9 @@
method public int getMaxCorrectionsByCategory();
method public int getMaxCorrectionsByPackageName();
method @NonNull public android.hardware.display.BrightnessConfiguration.Builder setDescription(@Nullable String);
+ method @NonNull public android.hardware.display.BrightnessConfiguration.Builder setShortTermModelLowerLuxMultiplier(@FloatRange(from=0.0f) float);
+ method @NonNull public android.hardware.display.BrightnessConfiguration.Builder setShortTermModelTimeout(long);
+ method @NonNull public android.hardware.display.BrightnessConfiguration.Builder setShortTermModelUpperLuxMultiplier(@FloatRange(from=0.0f) float);
method @NonNull public android.hardware.display.BrightnessConfiguration.Builder setShouldCollectColorSamples(boolean);
}
@@ -4864,6 +4871,14 @@
method @NonNull public android.net.StaticIpConfiguration.Builder setIpAddress(@Nullable android.net.LinkAddress);
}
+ public final class StringNetworkSpecifier extends android.net.NetworkSpecifier implements android.os.Parcelable {
+ ctor public StringNetworkSpecifier(@NonNull String);
+ method public int describeContents();
+ method public void writeToParcel(@NonNull android.os.Parcel, int);
+ field @NonNull public static final android.os.Parcelable.Creator<android.net.StringNetworkSpecifier> CREATOR;
+ field @NonNull public final String specifier;
+ }
+
public class TrafficStats {
method public static void setThreadStatsTagApp();
method public static void setThreadStatsTagBackup();
@@ -9903,6 +9918,7 @@
public class SubscriptionManager {
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean canDisablePhysicalSubscription();
+ method public boolean canManageSubscription(@Nullable android.telephony.SubscriptionInfo, @Nullable String);
method public java.util.List<android.telephony.SubscriptionInfo> getAvailableSubscriptionInfoList();
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public int getEnabledSubscriptionId(int);
method @NonNull public static android.content.res.Resources getResourcesForSubId(@NonNull android.content.Context, int);
diff --git a/api/test-current.txt b/api/test-current.txt
index a7cecf8..498dd2f 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -1058,9 +1058,13 @@
method @Nullable public android.hardware.display.BrightnessCorrection getCorrectionByCategory(int);
method @Nullable public android.hardware.display.BrightnessCorrection getCorrectionByPackageName(@NonNull String);
method public android.util.Pair<float[],float[]> getCurve();
+ method public float getShortTermModelLowerLuxMultiplier();
+ method public long getShortTermModelTimeout();
+ method public float getShortTermModelUpperLuxMultiplier();
method public boolean shouldCollectColorSamples();
method public void writeToParcel(android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.hardware.display.BrightnessConfiguration> CREATOR;
+ field public static final long SHORT_TERM_TIMEOUT_UNSET = -1L; // 0xffffffffffffffffL
}
public static class BrightnessConfiguration.Builder {
@@ -1071,6 +1075,9 @@
method public int getMaxCorrectionsByCategory();
method public int getMaxCorrectionsByPackageName();
method @NonNull public android.hardware.display.BrightnessConfiguration.Builder setDescription(@Nullable String);
+ method @NonNull public android.hardware.display.BrightnessConfiguration.Builder setShortTermModelLowerLuxMultiplier(@FloatRange(from=0.0f) float);
+ method @NonNull public android.hardware.display.BrightnessConfiguration.Builder setShortTermModelTimeout(long);
+ method @NonNull public android.hardware.display.BrightnessConfiguration.Builder setShortTermModelUpperLuxMultiplier(@FloatRange(from=0.0f) float);
method @NonNull public android.hardware.display.BrightnessConfiguration.Builder setShouldCollectColorSamples(boolean);
}
diff --git a/core/java/android/app/StatsManager.java b/core/java/android/app/StatsManager.java
index 2d851e0..b9893aa 100644
--- a/core/java/android/app/StatsManager.java
+++ b/core/java/android/app/StatsManager.java
@@ -38,6 +38,7 @@
import android.util.StatsEventParcel;
import com.android.internal.annotations.GuardedBy;
+import com.android.internal.annotations.VisibleForTesting;
import java.util.ArrayList;
import java.util.List;
@@ -121,8 +122,17 @@
**/
public static final int PULL_SKIP = 1;
- private static final long DEFAULT_COOL_DOWN_NS = 1_000_000_000L; // 1 second.
- private static final long DEFAULT_TIMEOUT_NS = 10_000_000_000L; // 10 seconds.
+ /**
+ * @hide
+ **/
+ @VisibleForTesting
+ public static final long DEFAULT_COOL_DOWN_NS = 1_000_000_000L; // 1 second.
+
+ /**
+ * @hide
+ **/
+ @VisibleForTesting
+ public static final long DEFAULT_TIMEOUT_NS = 10_000_000_000L; // 10 seconds.
/**
* Constructor for StatsManagerClient.
@@ -677,6 +687,30 @@
return new PullAtomMetadata(mCoolDownNs, mTimeoutNs, mAdditiveFields);
}
}
+
+ /**
+ * @hide
+ */
+ @VisibleForTesting
+ public long getCoolDownNs() {
+ return mCoolDownNs;
+ }
+
+ /**
+ * @hide
+ */
+ @VisibleForTesting
+ public long getTimeoutNs() {
+ return mTimeoutNs;
+ }
+
+ /**
+ * @hide
+ */
+ @VisibleForTesting
+ public int[] getAdditiveFields() {
+ return mAdditiveFields;
+ }
}
/**
diff --git a/core/java/android/companion/BluetoothLeDeviceFilter.java b/core/java/android/companion/BluetoothLeDeviceFilter.java
index 730bc60..dccfb03 100644
--- a/core/java/android/companion/BluetoothLeDeviceFilter.java
+++ b/core/java/android/companion/BluetoothLeDeviceFilter.java
@@ -340,7 +340,7 @@
public Builder setRawDataFilter(@NonNull byte[] rawDataFilter,
@Nullable byte[] rawDataFilterMask) {
checkNotUsed();
- Preconditions.checkNotNull(rawDataFilter);
+ Objects.requireNonNull(rawDataFilter);
checkArgument(rawDataFilterMask == null ||
rawDataFilter.length == rawDataFilterMask.length,
"Mask and filter should be the same length");
diff --git a/core/java/android/companion/CompanionDeviceManager.java b/core/java/android/companion/CompanionDeviceManager.java
index 28cc1f8..3107c63 100644
--- a/core/java/android/companion/CompanionDeviceManager.java
+++ b/core/java/android/companion/CompanionDeviceManager.java
@@ -16,9 +16,6 @@
package android.companion;
-
-import static com.android.internal.util.Preconditions.checkNotNull;
-
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.RequiresPermission;
@@ -42,6 +39,7 @@
import java.util.Collections;
import java.util.List;
+import java.util.Objects;
import java.util.function.BiConsumer;
/**
@@ -150,8 +148,8 @@
if (!checkFeaturePresent()) {
return;
}
- checkNotNull(request, "Request cannot be null");
- checkNotNull(callback, "Callback cannot be null");
+ Objects.requireNonNull(request, "Request cannot be null");
+ Objects.requireNonNull(callback, "Callback cannot be null");
try {
mService.associate(
request,
@@ -278,9 +276,9 @@
if (!checkFeaturePresent()) {
return false;
}
- checkNotNull(packageName, "package name cannot be null");
- checkNotNull(macAddress, "mac address cannot be null");
- checkNotNull(user, "user cannot be null");
+ Objects.requireNonNull(packageName, "package name cannot be null");
+ Objects.requireNonNull(macAddress, "mac address cannot be null");
+ Objects.requireNonNull(user, "user cannot be null");
try {
return mService.isDeviceAssociated(
packageName, macAddress.toString(), user.getIdentifier());
diff --git a/core/java/android/content/ClipboardManager.java b/core/java/android/content/ClipboardManager.java
index dec9589..7f73238 100644
--- a/core/java/android/content/ClipboardManager.java
+++ b/core/java/android/content/ClipboardManager.java
@@ -25,9 +25,8 @@
import android.os.ServiceManager;
import android.os.ServiceManager.ServiceNotFoundException;
-import com.android.internal.util.Preconditions;
-
import java.util.ArrayList;
+import java.util.Objects;
/**
* Interface to the clipboard service, for placing and retrieving text in
@@ -101,7 +100,7 @@
*/
public void setPrimaryClip(@NonNull ClipData clip) {
try {
- Preconditions.checkNotNull(clip);
+ Objects.requireNonNull(clip);
clip.prepareToLeaveProcess(true);
mService.setPrimaryClip(clip, mContext.getOpPackageName(), mContext.getUserId());
} catch (RemoteException e) {
diff --git a/core/java/android/content/ContentProviderClient.java b/core/java/android/content/ContentProviderClient.java
index 4008f2b..a9b7862 100644
--- a/core/java/android/content/ContentProviderClient.java
+++ b/core/java/android/content/ContentProviderClient.java
@@ -41,7 +41,6 @@
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.util.Preconditions;
import dalvik.system.CloseGuard;
@@ -49,6 +48,7 @@
import java.io.FileNotFoundException;
import java.util.ArrayList;
+import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
/**
@@ -184,7 +184,7 @@
public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
Bundle queryArgs, @Nullable CancellationSignal cancellationSignal)
throws RemoteException {
- Preconditions.checkNotNull(uri, "url");
+ Objects.requireNonNull(uri, "url");
beforeRemote();
try {
@@ -213,7 +213,7 @@
/** See {@link ContentProvider#getType ContentProvider.getType} */
@Override
public @Nullable String getType(@NonNull Uri url) throws RemoteException {
- Preconditions.checkNotNull(url, "url");
+ Objects.requireNonNull(url, "url");
beforeRemote();
try {
@@ -232,8 +232,8 @@
@Override
public @Nullable String[] getStreamTypes(@NonNull Uri url, @NonNull String mimeTypeFilter)
throws RemoteException {
- Preconditions.checkNotNull(url, "url");
- Preconditions.checkNotNull(mimeTypeFilter, "mimeTypeFilter");
+ Objects.requireNonNull(url, "url");
+ Objects.requireNonNull(mimeTypeFilter, "mimeTypeFilter");
beforeRemote();
try {
@@ -251,7 +251,7 @@
/** See {@link ContentProvider#canonicalize} */
@Override
public final @Nullable Uri canonicalize(@NonNull Uri url) throws RemoteException {
- Preconditions.checkNotNull(url, "url");
+ Objects.requireNonNull(url, "url");
beforeRemote();
try {
@@ -269,7 +269,7 @@
/** See {@link ContentProvider#uncanonicalize} */
@Override
public final @Nullable Uri uncanonicalize(@NonNull Uri url) throws RemoteException {
- Preconditions.checkNotNull(url, "url");
+ Objects.requireNonNull(url, "url");
beforeRemote();
try {
@@ -288,7 +288,7 @@
@Override
public boolean refresh(Uri url, @Nullable Bundle extras,
@Nullable CancellationSignal cancellationSignal) throws RemoteException {
- Preconditions.checkNotNull(url, "url");
+ Objects.requireNonNull(url, "url");
beforeRemote();
try {
@@ -314,7 +314,7 @@
@Override
public int checkUriPermission(@NonNull Uri uri, int uid, @Intent.AccessUriMode int modeFlags)
throws RemoteException {
- Preconditions.checkNotNull(uri, "uri");
+ Objects.requireNonNull(uri, "uri");
beforeRemote();
try {
@@ -340,7 +340,7 @@
@Override
public @Nullable Uri insert(@NonNull Uri url, @Nullable ContentValues initialValues,
@Nullable Bundle extras) throws RemoteException {
- Preconditions.checkNotNull(url, "url");
+ Objects.requireNonNull(url, "url");
beforeRemote();
try {
@@ -359,8 +359,8 @@
@Override
public int bulkInsert(@NonNull Uri url, @NonNull ContentValues[] initialValues)
throws RemoteException {
- Preconditions.checkNotNull(url, "url");
- Preconditions.checkNotNull(initialValues, "initialValues");
+ Objects.requireNonNull(url, "url");
+ Objects.requireNonNull(initialValues, "initialValues");
beforeRemote();
try {
@@ -384,7 +384,7 @@
/** See {@link ContentProvider#delete ContentProvider.delete} */
@Override
public int delete(@NonNull Uri url, @Nullable Bundle extras) throws RemoteException {
- Preconditions.checkNotNull(url, "url");
+ Objects.requireNonNull(url, "url");
beforeRemote();
try {
@@ -409,7 +409,7 @@
@Override
public int update(@NonNull Uri url, @Nullable ContentValues values, @Nullable Bundle extras)
throws RemoteException {
- Preconditions.checkNotNull(url, "url");
+ Objects.requireNonNull(url, "url");
beforeRemote();
try {
@@ -446,8 +446,8 @@
@Override
public @Nullable ParcelFileDescriptor openFile(@NonNull Uri url, @NonNull String mode,
@Nullable CancellationSignal signal) throws RemoteException, FileNotFoundException {
- Preconditions.checkNotNull(url, "url");
- Preconditions.checkNotNull(mode, "mode");
+ Objects.requireNonNull(url, "url");
+ Objects.requireNonNull(mode, "mode");
beforeRemote();
try {
@@ -491,8 +491,8 @@
@Override
public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri url, @NonNull String mode,
@Nullable CancellationSignal signal) throws RemoteException, FileNotFoundException {
- Preconditions.checkNotNull(url, "url");
- Preconditions.checkNotNull(mode, "mode");
+ Objects.requireNonNull(url, "url");
+ Objects.requireNonNull(mode, "mode");
beforeRemote();
try {
@@ -532,8 +532,8 @@
public final @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
@NonNull String mimeTypeFilter, @Nullable Bundle opts,
@Nullable CancellationSignal signal) throws RemoteException, FileNotFoundException {
- Preconditions.checkNotNull(uri, "uri");
- Preconditions.checkNotNull(mimeTypeFilter, "mimeTypeFilter");
+ Objects.requireNonNull(uri, "uri");
+ Objects.requireNonNull(mimeTypeFilter, "mimeTypeFilter");
beforeRemote();
try {
@@ -567,7 +567,7 @@
public @NonNull ContentProviderResult[] applyBatch(@NonNull String authority,
@NonNull ArrayList<ContentProviderOperation> operations)
throws RemoteException, OperationApplicationException {
- Preconditions.checkNotNull(operations, "operations");
+ Objects.requireNonNull(operations, "operations");
beforeRemote();
try {
@@ -592,8 +592,8 @@
@Override
public @Nullable Bundle call(@NonNull String authority, @NonNull String method,
@Nullable String arg, @Nullable Bundle extras) throws RemoteException {
- Preconditions.checkNotNull(authority, "authority");
- Preconditions.checkNotNull(method, "method");
+ Objects.requireNonNull(authority, "authority");
+ Objects.requireNonNull(method, "method");
beforeRemote();
try {
diff --git a/core/java/android/content/ContentResolver.java b/core/java/android/content/ContentResolver.java
index ede668a..1d3c650 100644
--- a/core/java/android/content/ContentResolver.java
+++ b/core/java/android/content/ContentResolver.java
@@ -68,7 +68,6 @@
import android.util.SparseArray;
import com.android.internal.util.MimeIconUtils;
-import com.android.internal.util.Preconditions;
import dalvik.system.CloseGuard;
@@ -711,7 +710,7 @@
/** {@hide} */
public static @NonNull ContentResolver wrap(@NonNull ContentInterface wrapped) {
- Preconditions.checkNotNull(wrapped);
+ Objects.requireNonNull(wrapped);
return new ContentResolver(null, wrapped) {
@Override
@@ -796,7 +795,7 @@
*/
@Override
public final @Nullable String getType(@NonNull Uri url) {
- Preconditions.checkNotNull(url, "url");
+ Objects.requireNonNull(url, "url");
try {
if (mWrapped != null) return mWrapped.getType(url);
@@ -856,8 +855,8 @@
*/
@Override
public @Nullable String[] getStreamTypes(@NonNull Uri url, @NonNull String mimeTypeFilter) {
- Preconditions.checkNotNull(url, "url");
- Preconditions.checkNotNull(mimeTypeFilter, "mimeTypeFilter");
+ Objects.requireNonNull(url, "url");
+ Objects.requireNonNull(mimeTypeFilter, "mimeTypeFilter");
try {
if (mWrapped != null) return mWrapped.getStreamTypes(url, mimeTypeFilter);
@@ -998,7 +997,7 @@
public final @Nullable Cursor query(final @RequiresPermission.Read @NonNull Uri uri,
@Nullable String[] projection, @Nullable Bundle queryArgs,
@Nullable CancellationSignal cancellationSignal) {
- Preconditions.checkNotNull(uri, "uri");
+ Objects.requireNonNull(uri, "uri");
try {
if (mWrapped != null) {
@@ -1112,7 +1111,7 @@
*/
@Override
public final @Nullable Uri canonicalize(@NonNull Uri url) {
- Preconditions.checkNotNull(url, "url");
+ Objects.requireNonNull(url, "url");
try {
if (mWrapped != null) return mWrapped.canonicalize(url);
@@ -1156,7 +1155,7 @@
*/
@Override
public final @Nullable Uri uncanonicalize(@NonNull Uri url) {
- Preconditions.checkNotNull(url, "url");
+ Objects.requireNonNull(url, "url");
try {
if (mWrapped != null) return mWrapped.uncanonicalize(url);
@@ -1202,7 +1201,7 @@
@Override
public final boolean refresh(@NonNull Uri url, @Nullable Bundle extras,
@Nullable CancellationSignal cancellationSignal) {
- Preconditions.checkNotNull(url, "url");
+ Objects.requireNonNull(url, "url");
try {
if (mWrapped != null) return mWrapped.refresh(url, extras, cancellationSignal);
@@ -1236,7 +1235,7 @@
/** {@hide} */
@Override
public int checkUriPermission(@NonNull Uri uri, int uid, @Intent.AccessUriMode int modeFlags) {
- Preconditions.checkNotNull(uri, "uri");
+ Objects.requireNonNull(uri, "uri");
try {
if (mWrapped != null) return mWrapped.checkUriPermission(uri, uid, modeFlags);
@@ -1272,7 +1271,7 @@
*/
public final @Nullable InputStream openInputStream(@NonNull Uri uri)
throws FileNotFoundException {
- Preconditions.checkNotNull(uri, "uri");
+ Objects.requireNonNull(uri, "uri");
String scheme = uri.getScheme();
if (SCHEME_ANDROID_RESOURCE.equals(scheme)) {
// Note: left here to avoid breaking compatibility. May be removed
@@ -1579,8 +1578,8 @@
public final @Nullable AssetFileDescriptor openAssetFileDescriptor(@NonNull Uri uri,
@NonNull String mode, @Nullable CancellationSignal cancellationSignal)
throws FileNotFoundException {
- Preconditions.checkNotNull(uri, "uri");
- Preconditions.checkNotNull(mode, "mode");
+ Objects.requireNonNull(uri, "uri");
+ Objects.requireNonNull(mode, "mode");
try {
if (mWrapped != null) return mWrapped.openAssetFile(uri, mode, cancellationSignal);
@@ -1764,8 +1763,8 @@
public final @Nullable AssetFileDescriptor openTypedAssetFileDescriptor(@NonNull Uri uri,
@NonNull String mimeType, @Nullable Bundle opts,
@Nullable CancellationSignal cancellationSignal) throws FileNotFoundException {
- Preconditions.checkNotNull(uri, "uri");
- Preconditions.checkNotNull(mimeType, "mimeType");
+ Objects.requireNonNull(uri, "uri");
+ Objects.requireNonNull(mimeType, "mimeType");
try {
if (mWrapped != null) return mWrapped.openTypedAssetFile(uri, mimeType, opts, cancellationSignal);
@@ -1933,7 +1932,7 @@
@Override
public final @Nullable Uri insert(@RequiresPermission.Write @NonNull Uri url,
@Nullable ContentValues values, @Nullable Bundle extras) {
- Preconditions.checkNotNull(url, "url");
+ Objects.requireNonNull(url, "url");
try {
if (mWrapped != null) return mWrapped.insert(url, values, extras);
@@ -1980,8 +1979,8 @@
public @NonNull ContentProviderResult[] applyBatch(@NonNull String authority,
@NonNull ArrayList<ContentProviderOperation> operations)
throws RemoteException, OperationApplicationException {
- Preconditions.checkNotNull(authority, "authority");
- Preconditions.checkNotNull(operations, "operations");
+ Objects.requireNonNull(authority, "authority");
+ Objects.requireNonNull(operations, "operations");
try {
if (mWrapped != null) return mWrapped.applyBatch(authority, operations);
@@ -2013,8 +2012,8 @@
@Override
public final int bulkInsert(@RequiresPermission.Write @NonNull Uri url,
@NonNull ContentValues[] values) {
- Preconditions.checkNotNull(url, "url");
- Preconditions.checkNotNull(values, "values");
+ Objects.requireNonNull(url, "url");
+ Objects.requireNonNull(values, "values");
try {
if (mWrapped != null) return mWrapped.bulkInsert(url, values);
@@ -2068,7 +2067,7 @@
*/
@Override
public final int delete(@RequiresPermission.Write @NonNull Uri url, @Nullable Bundle extras) {
- Preconditions.checkNotNull(url, "url");
+ Objects.requireNonNull(url, "url");
try {
if (mWrapped != null) return mWrapped.delete(url, extras);
@@ -2130,7 +2129,7 @@
@Override
public final int update(@RequiresPermission.Write @NonNull Uri uri,
@Nullable ContentValues values, @Nullable Bundle extras) {
- Preconditions.checkNotNull(uri, "uri");
+ Objects.requireNonNull(uri, "uri");
try {
if (mWrapped != null) return mWrapped.update(uri, values, extras);
@@ -2179,8 +2178,8 @@
@Override
public final @Nullable Bundle call(@NonNull String authority, @NonNull String method,
@Nullable String arg, @Nullable Bundle extras) {
- Preconditions.checkNotNull(authority, "authority");
- Preconditions.checkNotNull(method, "method");
+ Objects.requireNonNull(authority, "authority");
+ Objects.requireNonNull(method, "method");
try {
if (mWrapped != null) return mWrapped.call(authority, method, arg, extras);
@@ -2297,7 +2296,7 @@
* that services the content at uri or null if there isn't one.
*/
public final @Nullable ContentProviderClient acquireContentProviderClient(@NonNull Uri uri) {
- Preconditions.checkNotNull(uri, "uri");
+ Objects.requireNonNull(uri, "uri");
IContentProvider provider = acquireProvider(uri);
if (provider != null) {
return new ContentProviderClient(this, provider, uri.getAuthority(), true);
@@ -2318,7 +2317,7 @@
*/
public final @Nullable ContentProviderClient acquireContentProviderClient(
@NonNull String name) {
- Preconditions.checkNotNull(name, "name");
+ Objects.requireNonNull(name, "name");
IContentProvider provider = acquireProvider(name);
if (provider != null) {
return new ContentProviderClient(this, provider, name, true);
@@ -2345,7 +2344,7 @@
*/
public final @Nullable ContentProviderClient acquireUnstableContentProviderClient(
@NonNull Uri uri) {
- Preconditions.checkNotNull(uri, "uri");
+ Objects.requireNonNull(uri, "uri");
IContentProvider provider = acquireUnstableProvider(uri);
if (provider != null) {
return new ContentProviderClient(this, provider, uri.getAuthority(), false);
@@ -2372,7 +2371,7 @@
*/
public final @Nullable ContentProviderClient acquireUnstableContentProviderClient(
@NonNull String name) {
- Preconditions.checkNotNull(name, "name");
+ Objects.requireNonNull(name, "name");
IContentProvider provider = acquireUnstableProvider(name);
if (provider != null) {
return new ContentProviderClient(this, provider, name, false);
@@ -2401,8 +2400,8 @@
*/
public final void registerContentObserver(@NonNull Uri uri, boolean notifyForDescendants,
@NonNull ContentObserver observer) {
- Preconditions.checkNotNull(uri, "uri");
- Preconditions.checkNotNull(observer, "observer");
+ Objects.requireNonNull(uri, "uri");
+ Objects.requireNonNull(observer, "observer");
registerContentObserver(
ContentProvider.getUriWithoutUserId(uri),
notifyForDescendants,
@@ -2429,7 +2428,7 @@
* @see #registerContentObserver
*/
public final void unregisterContentObserver(@NonNull ContentObserver observer) {
- Preconditions.checkNotNull(observer, "observer");
+ Objects.requireNonNull(observer, "observer");
try {
IContentObserver contentObserver = observer.releaseContentObserver();
if (contentObserver != null) {
@@ -2523,7 +2522,7 @@
*/
public void notifyChange(@NonNull Uri uri, @Nullable ContentObserver observer,
@NotifyFlags int flags) {
- Preconditions.checkNotNull(uri, "uri");
+ Objects.requireNonNull(uri, "uri");
notifyChange(
ContentProvider.getUriWithoutUserId(uri),
observer,
@@ -2557,7 +2556,7 @@
*/
public void notifyChange(@NonNull Iterable<Uri> uris, @Nullable ContentObserver observer,
@NotifyFlags int flags) {
- Preconditions.checkNotNull(uris, "uris");
+ Objects.requireNonNull(uris, "uris");
// Cluster based on user ID
final SparseArray<ArrayList<Uri>> clusteredByUser = new SparseArray<>();
@@ -2628,7 +2627,7 @@
*/
public void takePersistableUriPermission(@NonNull Uri uri,
@Intent.AccessUriMode int modeFlags) {
- Preconditions.checkNotNull(uri, "uri");
+ Objects.requireNonNull(uri, "uri");
try {
UriGrantsManager.getService().takePersistableUriPermission(
ContentProvider.getUriWithoutUserId(uri), modeFlags, /* toPackage= */ null,
@@ -2644,8 +2643,8 @@
@UnsupportedAppUsage
public void takePersistableUriPermission(@NonNull String toPackage, @NonNull Uri uri,
@Intent.AccessUriMode int modeFlags) {
- Preconditions.checkNotNull(toPackage, "toPackage");
- Preconditions.checkNotNull(uri, "uri");
+ Objects.requireNonNull(toPackage, "toPackage");
+ Objects.requireNonNull(uri, "uri");
try {
UriGrantsManager.getService().takePersistableUriPermission(
ContentProvider.getUriWithoutUserId(uri), modeFlags, toPackage,
@@ -2665,7 +2664,7 @@
*/
public void releasePersistableUriPermission(@NonNull Uri uri,
@Intent.AccessUriMode int modeFlags) {
- Preconditions.checkNotNull(uri, "uri");
+ Objects.requireNonNull(uri, "uri");
try {
UriGrantsManager.getService().releasePersistableUriPermission(
ContentProvider.getUriWithoutUserId(uri), modeFlags, /* toPackage= */ null,
diff --git a/core/java/android/content/integrity/AppInstallMetadata.java b/core/java/android/content/integrity/AppInstallMetadata.java
index 70776c7..85af881 100644
--- a/core/java/android/content/integrity/AppInstallMetadata.java
+++ b/core/java/android/content/integrity/AppInstallMetadata.java
@@ -16,15 +16,14 @@
package android.content.integrity;
-import static com.android.internal.util.Preconditions.checkArgument;
-import static com.android.internal.util.Preconditions.checkNotNull;
-
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import com.android.internal.annotations.VisibleForTesting;
+import java.util.Objects;
+
/**
* The app install metadata.
*
@@ -115,7 +114,7 @@
*/
@NonNull
public Builder setPackageName(@NonNull String packageName) {
- this.mPackageName = checkNotNull(packageName);
+ this.mPackageName = Objects.requireNonNull(packageName);
return this;
}
@@ -129,7 +128,7 @@
*/
@NonNull
public Builder setAppCertificate(@NonNull String appCertificate) {
- this.mAppCertificate = checkNotNull(appCertificate);
+ this.mAppCertificate = Objects.requireNonNull(appCertificate);
return this;
}
@@ -140,7 +139,7 @@
*/
@NonNull
public Builder setInstallerName(@NonNull String installerName) {
- this.mInstallerName = checkNotNull(installerName);
+ this.mInstallerName = Objects.requireNonNull(installerName);
return this;
}
@@ -154,7 +153,7 @@
*/
@NonNull
public Builder setInstallerCertificate(@NonNull String installerCertificate) {
- this.mInstallerCertificate = checkNotNull(installerCertificate);
+ this.mInstallerCertificate = Objects.requireNonNull(installerCertificate);
return this;
}
@@ -187,8 +186,8 @@
*/
@NonNull
public AppInstallMetadata build() {
- checkArgument(mPackageName != null);
- checkArgument(mAppCertificate != null);
+ Objects.requireNonNull(mPackageName);
+ Objects.requireNonNull(mAppCertificate);
return new AppInstallMetadata(this);
}
}
diff --git a/core/java/android/content/integrity/Rule.java b/core/java/android/content/integrity/Rule.java
index 39a0909..7758785 100644
--- a/core/java/android/content/integrity/Rule.java
+++ b/core/java/android/content/integrity/Rule.java
@@ -17,7 +17,6 @@
package android.content.integrity;
import static com.android.internal.util.Preconditions.checkArgument;
-import static com.android.internal.util.Preconditions.checkNotNull;
import android.annotation.IntDef;
import android.annotation.NonNull;
@@ -65,7 +64,7 @@
public Rule(@NonNull Formula formula, @Effect int effect) {
checkArgument(isValidEffect(effect), String.format("Unknown effect: %d", effect));
- this.mFormula = checkNotNull(formula);
+ this.mFormula = Objects.requireNonNull(formula);
this.mEffect = effect;
}
diff --git a/core/java/android/content/integrity/RuleSet.java b/core/java/android/content/integrity/RuleSet.java
index a78f8c9..b423b54 100644
--- a/core/java/android/content/integrity/RuleSet.java
+++ b/core/java/android/content/integrity/RuleSet.java
@@ -16,14 +16,13 @@
package android.content.integrity;
-import static com.android.internal.util.Preconditions.checkNotNull;
-
import android.annotation.NonNull;
import android.annotation.SystemApi;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import java.util.Objects;
/**
* Immutable data class encapsulating all parameters of a rule set.
@@ -85,7 +84,7 @@
*/
@NonNull
public RuleSet build() {
- checkNotNull(mVersion);
+ Objects.requireNonNull(mVersion);
return new RuleSet(mVersion, mRules);
}
}
diff --git a/core/java/android/content/pm/LauncherApps.java b/core/java/android/content/pm/LauncherApps.java
index 94a5375..ed958b1 100644
--- a/core/java/android/content/pm/LauncherApps.java
+++ b/core/java/android/content/pm/LauncherApps.java
@@ -62,8 +62,6 @@
import android.util.DisplayMetrics;
import android.util.Log;
-import com.android.internal.util.Preconditions;
-
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -72,6 +70,7 @@
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
+import java.util.Objects;
import java.util.concurrent.Executor;
/**
@@ -766,8 +765,8 @@
*/
public boolean shouldHideFromSuggestions(@NonNull String packageName,
@NonNull UserHandle user) {
- Preconditions.checkNotNull(packageName, "packageName");
- Preconditions.checkNotNull(user, "user");
+ Objects.requireNonNull(packageName, "packageName");
+ Objects.requireNonNull(user, "user");
try {
return mService.shouldHideFromSuggestions(packageName, user);
} catch (RemoteException re) {
@@ -789,8 +788,8 @@
public ApplicationInfo getApplicationInfo(@NonNull String packageName,
@ApplicationInfoFlags int flags, @NonNull UserHandle user)
throws PackageManager.NameNotFoundException {
- Preconditions.checkNotNull(packageName, "packageName");
- Preconditions.checkNotNull(user, "user");
+ Objects.requireNonNull(packageName, "packageName");
+ Objects.requireNonNull(user, "user");
logErrorForInvalidProfileAccess(user);
try {
final ApplicationInfo ai = mService
diff --git a/core/java/android/content/pm/PackageInstaller.java b/core/java/android/content/pm/PackageInstaller.java
index e4a0bc0..7a28022 100644
--- a/core/java/android/content/pm/PackageInstaller.java
+++ b/core/java/android/content/pm/PackageInstaller.java
@@ -56,7 +56,6 @@
import android.util.ExceptionUtils;
import com.android.internal.util.IndentingPrintWriter;
-import com.android.internal.util.Preconditions;
import com.android.internal.util.function.pooled.PooledLambda;
import java.io.Closeable;
@@ -70,6 +69,7 @@
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
+import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
@@ -634,7 +634,7 @@
Manifest.permission.REQUEST_DELETE_PACKAGES})
public void uninstall(@NonNull VersionedPackage versionedPackage, @DeleteFlags int flags,
@NonNull IntentSender statusReceiver) {
- Preconditions.checkNotNull(versionedPackage, "versionedPackage cannot be null");
+ Objects.requireNonNull(versionedPackage, "versionedPackage cannot be null");
try {
mInstaller.uninstall(versionedPackage, mInstallerPackageName,
flags, statusReceiver, mUserId);
@@ -661,7 +661,7 @@
public void installExistingPackage(@NonNull String packageName,
@InstallReason int installReason,
@Nullable IntentSender statusReceiver) {
- Preconditions.checkNotNull(packageName, "packageName cannot be null");
+ Objects.requireNonNull(packageName, "packageName cannot be null");
try {
mInstaller.installExistingPackage(packageName,
PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, installReason,
@@ -1202,8 +1202,8 @@
*/
public void transfer(@NonNull String packageName, @NonNull IntentSender statusReceiver)
throws PackageManager.NameNotFoundException {
- Preconditions.checkNotNull(statusReceiver);
- Preconditions.checkNotNull(packageName);
+ Objects.requireNonNull(statusReceiver);
+ Objects.requireNonNull(packageName);
try {
mSession.transfer(packageName, statusReceiver);
@@ -1231,7 +1231,7 @@
*/
public void transfer(@NonNull String packageName)
throws PackageManager.NameNotFoundException {
- Preconditions.checkNotNull(packageName);
+ Objects.requireNonNull(packageName);
CompletableFuture<Intent> intentFuture = new CompletableFuture<Intent>();
try {
diff --git a/core/java/android/content/pm/PackageItemInfo.java b/core/java/android/content/pm/PackageItemInfo.java
index 50a2f00..7fd5531 100644
--- a/core/java/android/content/pm/PackageItemInfo.java
+++ b/core/java/android/content/pm/PackageItemInfo.java
@@ -33,10 +33,10 @@
import android.util.Printer;
import android.util.proto.ProtoOutputStream;
-import com.android.internal.util.Preconditions;
import java.text.Collator;
import java.util.Comparator;
+import java.util.Objects;
/**
* Base class containing information common to all package items held by
@@ -240,7 +240,7 @@
@SystemApi
public @NonNull CharSequence loadSafeLabel(@NonNull PackageManager pm,
@FloatRange(from = 0) float ellipsizeDip, @TextUtils.SafeStringFlags int flags) {
- Preconditions.checkNotNull(pm);
+ Objects.requireNonNull(pm);
return makeSafeForPresentation(loadUnsafeLabel(pm).toString(), MAX_SAFE_LABEL_LENGTH,
ellipsizeDip, flags);
diff --git a/core/java/android/content/pm/ShortcutInfo.java b/core/java/android/content/pm/ShortcutInfo.java
index 2c4ccbf..d5fb848 100644
--- a/core/java/android/content/pm/ShortcutInfo.java
+++ b/core/java/android/content/pm/ShortcutInfo.java
@@ -51,6 +51,7 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;
+import java.util.Objects;
import java.util.Set;
/**
@@ -519,12 +520,12 @@
public void enforceMandatoryFields(boolean forPinned) {
Preconditions.checkStringNotEmpty(mId, "Shortcut ID must be provided");
if (!forPinned) {
- Preconditions.checkNotNull(mActivity, "Activity must be provided");
+ Objects.requireNonNull(mActivity, "Activity must be provided");
}
if (mTitle == null && mTitleResId == 0) {
throw new IllegalArgumentException("Short label must be provided");
}
- Preconditions.checkNotNull(mIntents, "Shortcut Intent must be provided");
+ Objects.requireNonNull(mIntents, "Shortcut Intent must be provided");
Preconditions.checkArgument(mIntents.length > 0, "Shortcut Intent must be provided");
}
@@ -1008,7 +1009,7 @@
*/
@NonNull
public Builder setLocusId(@NonNull LocusId locusId) {
- mLocusId = Preconditions.checkNotNull(locusId, "locusId cannot be null");
+ mLocusId = Objects.requireNonNull(locusId, "locusId cannot be null");
return this;
}
@@ -1039,7 +1040,7 @@
*/
@NonNull
public Builder setActivity(@NonNull ComponentName activity) {
- mActivity = Preconditions.checkNotNull(activity, "activity cannot be null");
+ mActivity = Objects.requireNonNull(activity, "activity cannot be null");
return this;
}
@@ -1229,11 +1230,11 @@
*/
@NonNull
public Builder setIntents(@NonNull Intent[] intents) {
- Preconditions.checkNotNull(intents, "intents cannot be null");
- Preconditions.checkNotNull(intents.length, "intents cannot be empty");
+ Objects.requireNonNull(intents, "intents cannot be null");
+ Objects.requireNonNull(intents.length, "intents cannot be empty");
for (Intent intent : intents) {
- Preconditions.checkNotNull(intent, "intents cannot contain null");
- Preconditions.checkNotNull(intent.getAction(), "intent's action must be set");
+ Objects.requireNonNull(intent, "intents cannot contain null");
+ Objects.requireNonNull(intent.getAction(), "intent's action must be set");
}
// Make sure always clone incoming intents.
mIntents = cloneIntents(intents);
@@ -1267,10 +1268,10 @@
*/
@NonNull
public Builder setPersons(@NonNull Person[] persons) {
- Preconditions.checkNotNull(persons, "persons cannot be null");
- Preconditions.checkNotNull(persons.length, "persons cannot be empty");
+ Objects.requireNonNull(persons, "persons cannot be null");
+ Objects.requireNonNull(persons.length, "persons cannot be empty");
for (Person person : persons) {
- Preconditions.checkNotNull(person, "persons cannot contain null");
+ Objects.requireNonNull(person, "persons cannot contain null");
}
mPersons = clonePersons(persons);
return this;
@@ -1979,7 +1980,7 @@
* @hide
*/
public void setIntents(Intent[] intents) throws IllegalArgumentException {
- Preconditions.checkNotNull(intents);
+ Objects.requireNonNull(intents);
Preconditions.checkArgument(intents.length > 0);
mIntents = cloneIntents(intents);
diff --git a/core/java/android/content/res/ApkAssets.java b/core/java/android/content/res/ApkAssets.java
index 0e4a8e6..8db2785 100644
--- a/core/java/android/content/res/ApkAssets.java
+++ b/core/java/android/content/res/ApkAssets.java
@@ -23,10 +23,10 @@
import android.text.TextUtils;
import com.android.internal.annotations.GuardedBy;
-import com.android.internal.util.Preconditions;
import java.io.FileDescriptor;
import java.io.IOException;
+import java.util.Objects;
/**
* The loaded, immutable, in-memory representation of an APK.
@@ -193,7 +193,7 @@
private ApkAssets(@NonNull String path, boolean system, boolean forceSharedLib, boolean overlay,
boolean arscOnly, boolean forLoader) throws IOException {
mForLoader = forLoader;
- Preconditions.checkNotNull(path, "path");
+ Objects.requireNonNull(path, "path");
mNativePtr = arscOnly ? nativeLoadArsc(path, forLoader)
: nativeLoad(path, system, forceSharedLib, overlay, forLoader);
mStringBlock = new StringBlock(nativeGetStringBlock(mNativePtr), true /*useSparse*/);
@@ -202,8 +202,8 @@
private ApkAssets(@NonNull FileDescriptor fd, @NonNull String friendlyName, boolean system,
boolean forceSharedLib, boolean arscOnly, boolean forLoader) throws IOException {
mForLoader = forLoader;
- Preconditions.checkNotNull(fd, "fd");
- Preconditions.checkNotNull(friendlyName, "friendlyName");
+ Objects.requireNonNull(fd, "fd");
+ Objects.requireNonNull(friendlyName, "friendlyName");
mNativePtr = arscOnly ? nativeLoadArscFromFd(fd, friendlyName, forLoader)
: nativeLoadFromFd(fd, friendlyName, system, forceSharedLib, forLoader);
mStringBlock = new StringBlock(nativeGetStringBlock(mNativePtr), true /*useSparse*/);
@@ -240,7 +240,7 @@
* @throws IOException if the file was not found or an error occurred retrieving it.
*/
public @NonNull XmlResourceParser openXml(@NonNull String fileName) throws IOException {
- Preconditions.checkNotNull(fileName, "fileName");
+ Objects.requireNonNull(fileName, "fileName");
synchronized (this) {
long nativeXmlPtr = nativeOpenXml(mNativePtr, fileName);
try (XmlBlock block = new XmlBlock(null, nativeXmlPtr)) {
diff --git a/core/java/android/content/res/AssetManager.java b/core/java/android/content/res/AssetManager.java
index d20dca1..96fbe91 100644
--- a/core/java/android/content/res/AssetManager.java
+++ b/core/java/android/content/res/AssetManager.java
@@ -39,7 +39,6 @@
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.util.Preconditions;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
@@ -52,6 +51,7 @@
import java.util.List;
import java.util.Locale;
import java.util.Map;
+import java.util.Objects;
/**
* Provides access to an application's raw asset files; see {@link Resources}
@@ -273,7 +273,7 @@
* @hide
*/
public void setApkAssets(@NonNull ApkAssets[] apkAssets, boolean invalidateCaches) {
- Preconditions.checkNotNull(apkAssets, "apkAssets");
+ Objects.requireNonNull(apkAssets, "apkAssets");
ApkAssets[] newApkAssets = new ApkAssets[sSystemApkAssets.length + apkAssets.length];
@@ -352,7 +352,7 @@
* @hide
*/
public int findCookieForPath(@NonNull String path) {
- Preconditions.checkNotNull(path, "path");
+ Objects.requireNonNull(path, "path");
synchronized (this) {
ensureValidLocked();
final int count = mApkAssets.length;
@@ -396,7 +396,7 @@
}
private int addAssetPathInternal(String path, boolean overlay, boolean appAsLib) {
- Preconditions.checkNotNull(path, "path");
+ Objects.requireNonNull(path, "path");
synchronized (this) {
ensureOpenLocked();
final int count = mApkAssets.length;
@@ -471,7 +471,7 @@
@UnsupportedAppUsage
boolean getResourceValue(@AnyRes int resId, int densityDpi, @NonNull TypedValue outValue,
boolean resolveRefs) {
- Preconditions.checkNotNull(outValue, "outValue");
+ Objects.requireNonNull(outValue, "outValue");
synchronized (this) {
ensureValidLocked();
final int cookie = nativeGetResourceValue(
@@ -568,7 +568,7 @@
* @see TypedArray#STYLE_DENSITY
*/
int getResourceArray(@ArrayRes int resId, @NonNull int[] outData) {
- Preconditions.checkNotNull(outData, "outData");
+ Objects.requireNonNull(outData, "outData");
synchronized (this) {
ensureValidLocked();
return nativeGetResourceArray(mObject, resId, outData);
@@ -652,7 +652,7 @@
*/
boolean getThemeValue(long theme, @AnyRes int resId, @NonNull TypedValue outValue,
boolean resolveRefs) {
- Preconditions.checkNotNull(outValue, "outValue");
+ Objects.requireNonNull(outValue, "outValue");
synchronized (this) {
ensureValidLocked();
final int cookie = nativeThemeGetAttributeValue(mObject, theme, resId, outValue,
@@ -791,7 +791,7 @@
* @see #list
*/
public @NonNull InputStream open(@NonNull String fileName, int accessMode) throws IOException {
- Preconditions.checkNotNull(fileName, "fileName");
+ Objects.requireNonNull(fileName, "fileName");
synchronized (this) {
ensureOpenLocked();
@@ -822,7 +822,7 @@
* @return An open AssetFileDescriptor.
*/
public @NonNull AssetFileDescriptor openFd(@NonNull String fileName) throws IOException {
- Preconditions.checkNotNull(fileName, "fileName");
+ Objects.requireNonNull(fileName, "fileName");
synchronized (this) {
ensureOpenLocked();
@@ -853,7 +853,7 @@
* @see #open
*/
public @Nullable String[] list(@NonNull String path) throws IOException {
- Preconditions.checkNotNull(path, "path");
+ Objects.requireNonNull(path, "path");
synchronized (this) {
ensureValidLocked();
return nativeList(mObject, path);
@@ -922,7 +922,7 @@
@UnsupportedAppUsage
public @NonNull InputStream openNonAsset(int cookie, @NonNull String fileName, int accessMode)
throws IOException {
- Preconditions.checkNotNull(fileName, "fileName");
+ Objects.requireNonNull(fileName, "fileName");
synchronized (this) {
ensureOpenLocked();
@@ -967,7 +967,7 @@
*/
public @NonNull AssetFileDescriptor openNonAssetFd(int cookie, @NonNull String fileName)
throws IOException {
- Preconditions.checkNotNull(fileName, "fileName");
+ Objects.requireNonNull(fileName, "fileName");
synchronized (this) {
ensureOpenLocked();
@@ -1034,7 +1034,7 @@
* @hide
*/
@NonNull XmlBlock openXmlBlockAsset(int cookie, @NonNull String fileName) throws IOException {
- Preconditions.checkNotNull(fileName, "fileName");
+ Objects.requireNonNull(fileName, "fileName");
synchronized (this) {
ensureOpenLocked();
@@ -1145,7 +1145,7 @@
void applyStyle(long themePtr, @AttrRes int defStyleAttr, @StyleRes int defStyleRes,
@Nullable XmlBlock.Parser parser, @NonNull int[] inAttrs, long outValuesAddress,
long outIndicesAddress) {
- Preconditions.checkNotNull(inAttrs, "inAttrs");
+ Objects.requireNonNull(inAttrs, "inAttrs");
synchronized (this) {
// Need to synchronize on AssetManager because we will be accessing
// the native implementation of AssetManager.
@@ -1168,9 +1168,9 @@
boolean resolveAttrs(long themePtr, @AttrRes int defStyleAttr, @StyleRes int defStyleRes,
@Nullable int[] inValues, @NonNull int[] inAttrs, @NonNull int[] outValues,
@NonNull int[] outIndices) {
- Preconditions.checkNotNull(inAttrs, "inAttrs");
- Preconditions.checkNotNull(outValues, "outValues");
- Preconditions.checkNotNull(outIndices, "outIndices");
+ Objects.requireNonNull(inAttrs, "inAttrs");
+ Objects.requireNonNull(outValues, "outValues");
+ Objects.requireNonNull(outIndices, "outIndices");
synchronized (this) {
// Need to synchronize on AssetManager because we will be accessing
// the native implementation of AssetManager.
@@ -1183,10 +1183,10 @@
@UnsupportedAppUsage
boolean retrieveAttributes(@NonNull XmlBlock.Parser parser, @NonNull int[] inAttrs,
@NonNull int[] outValues, @NonNull int[] outIndices) {
- Preconditions.checkNotNull(parser, "parser");
- Preconditions.checkNotNull(inAttrs, "inAttrs");
- Preconditions.checkNotNull(outValues, "outValues");
- Preconditions.checkNotNull(outIndices, "outIndices");
+ Objects.requireNonNull(parser, "parser");
+ Objects.requireNonNull(inAttrs, "inAttrs");
+ Objects.requireNonNull(outValues, "outValues");
+ Objects.requireNonNull(outIndices, "outIndices");
synchronized (this) {
// Need to synchronize on AssetManager because we will be accessing
// the native implementation of AssetManager.
@@ -1290,14 +1290,14 @@
@Override
public final int read(@NonNull byte[] b) throws IOException {
ensureOpen();
- Preconditions.checkNotNull(b, "b");
+ Objects.requireNonNull(b, "b");
return nativeAssetRead(mAssetNativePtr, b, 0, b.length);
}
@Override
public final int read(@NonNull byte[] b, int off, int len) throws IOException {
ensureOpen();
- Preconditions.checkNotNull(b, "b");
+ Objects.requireNonNull(b, "b");
return nativeAssetRead(mAssetNativePtr, b, off, len);
}
diff --git a/core/java/android/hardware/camera2/CameraManager.java b/core/java/android/hardware/camera2/CameraManager.java
index b61b1ef..9b58578 100644
--- a/core/java/android/hardware/camera2/CameraManager.java
+++ b/core/java/android/hardware/camera2/CameraManager.java
@@ -1076,6 +1076,10 @@
}
public String[] getCameraIdListNoLazy() {
+ if (sCameraServiceDisabled) {
+ return new String[] {};
+ }
+
CameraStatus[] cameraStatuses;
ICameraServiceListener.Stub testListener = new ICameraServiceListener.Stub() {
@Override
diff --git a/core/java/android/hardware/display/BrightnessConfiguration.java b/core/java/android/hardware/display/BrightnessConfiguration.java
index 139be8e..0a38538 100644
--- a/core/java/android/hardware/display/BrightnessConfiguration.java
+++ b/core/java/android/hardware/display/BrightnessConfiguration.java
@@ -16,6 +16,7 @@
package android.hardware.display;
+import android.annotation.FloatRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
@@ -56,6 +57,16 @@
private static final String ATTR_PACKAGE_NAME = "package-name";
private static final String ATTR_CATEGORY = "category";
private static final String ATTR_COLLECT_COLOR = "collect-color";
+ private static final String ATTR_MODEL_TIMEOUT = "model-timeout";
+ private static final String ATTR_MODEL_LOWER_BOUND = "model-lower-bound";
+ private static final String ATTR_MODEL_UPPER_BOUND = "model-upper-bound";
+ /**
+ * Returned from {@link #getShortTermModelTimeout()} if no timeout has been set.
+ * In this case the device will use the default timeout available in the
+ * {@link BrightnessConfiguration} returned from
+ * {@link DisplayManager#getDefaultBrightnessConfiguration()}.
+ */
+ public static final long SHORT_TERM_TIMEOUT_UNSET = -1;
private final float[] mLux;
private final float[] mNits;
@@ -63,17 +74,26 @@
private final Map<Integer, BrightnessCorrection> mCorrectionsByCategory;
private final String mDescription;
private final boolean mShouldCollectColorSamples;
+ private final long mShortTermModelTimeout;
+ private final float mShortTermModelLowerLuxMultiplier;
+ private final float mShortTermModelUpperLuxMultiplier;
private BrightnessConfiguration(float[] lux, float[] nits,
Map<String, BrightnessCorrection> correctionsByPackageName,
Map<Integer, BrightnessCorrection> correctionsByCategory, String description,
- boolean shouldCollectColorSamples) {
+ boolean shouldCollectColorSamples,
+ long shortTermModelTimeout,
+ float shortTermModelLowerLuxMultiplier,
+ float shortTermModelUpperLuxMultiplier) {
mLux = lux;
mNits = nits;
mCorrectionsByPackageName = correctionsByPackageName;
mCorrectionsByCategory = correctionsByCategory;
mDescription = description;
mShouldCollectColorSamples = shouldCollectColorSamples;
+ mShortTermModelTimeout = shortTermModelTimeout;
+ mShortTermModelLowerLuxMultiplier = shortTermModelLowerLuxMultiplier;
+ mShortTermModelUpperLuxMultiplier = shortTermModelUpperLuxMultiplier;
}
/**
@@ -132,6 +152,42 @@
return mShouldCollectColorSamples;
}
+ /**
+ * Returns the timeout for the short term model in milliseconds.
+ *
+ * If the screen is inactive for this timeout then the short term model
+ * will check the lux range defined by {@link #getShortTermModelLowerLuxMultiplier()} and
+ * {@link #getShortTermModelUpperLuxMultiplier()} to decide whether to keep any adjustment
+ * the user has made to adaptive brightness.
+ */
+ public long getShortTermModelTimeout() {
+ return mShortTermModelTimeout;
+ }
+
+ /**
+ * Returns the multiplier used to calculate the upper bound for which
+ * a users adaptive brightness is considered valid.
+ *
+ * For example if a user changes the brightness when the ambient light level
+ * is 100 lux, the adjustment will be kept if the current ambient light level
+ * is {@code <= 100 + (100 * getShortTermModelUpperLuxMultiplier())}.
+ */
+ public float getShortTermModelUpperLuxMultiplier() {
+ return mShortTermModelUpperLuxMultiplier;
+ }
+
+ /**
+ * Returns the multiplier used to calculate the lower bound for which
+ * a users adaptive brightness is considered valid.
+ *
+ * For example if a user changes the brightness when the ambient light level
+ * is 100 lux, the adjustment will be kept if the current ambient light level
+ * is {@code >= 100 - (100 * getShortTermModelLowerLuxMultiplier())}.
+ */
+ public float getShortTermModelLowerLuxMultiplier() {
+ return mShortTermModelLowerLuxMultiplier;
+ }
+
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeFloatArray(mLux);
@@ -152,6 +208,9 @@
}
dest.writeString(mDescription);
dest.writeBoolean(mShouldCollectColorSamples);
+ dest.writeLong(mShortTermModelTimeout);
+ dest.writeFloat(mShortTermModelLowerLuxMultiplier);
+ dest.writeFloat(mShortTermModelUpperLuxMultiplier);
}
@Override
@@ -182,6 +241,15 @@
sb.append(mDescription);
}
sb.append(", shouldCollectColorSamples = " + mShouldCollectColorSamples);
+ if (mShortTermModelTimeout >= 0) {
+ sb.append(", shortTermModelTimeout = " + mShortTermModelTimeout);
+ }
+ if (!Float.isNaN(mShortTermModelLowerLuxMultiplier)) {
+ sb.append(", shortTermModelLowerLuxMultiplier = " + mShortTermModelLowerLuxMultiplier);
+ }
+ if (!Float.isNaN(mShortTermModelLowerLuxMultiplier)) {
+ sb.append(", shortTermModelUpperLuxMultiplier = " + mShortTermModelUpperLuxMultiplier);
+ }
sb.append("'}");
return sb.toString();
}
@@ -197,6 +265,9 @@
result = result * 31 + mDescription.hashCode();
}
result = result * 31 + Boolean.hashCode(mShouldCollectColorSamples);
+ result = result * 31 + Long.hashCode(mShortTermModelTimeout);
+ result = result * 31 + Float.hashCode(mShortTermModelLowerLuxMultiplier);
+ result = result * 31 + Float.hashCode(mShortTermModelUpperLuxMultiplier);
return result;
}
@@ -213,7 +284,19 @@
&& mCorrectionsByPackageName.equals(other.mCorrectionsByPackageName)
&& mCorrectionsByCategory.equals(other.mCorrectionsByCategory)
&& Objects.equals(mDescription, other.mDescription)
- && mShouldCollectColorSamples == other.mShouldCollectColorSamples;
+ && mShouldCollectColorSamples == other.mShouldCollectColorSamples
+ && mShortTermModelTimeout == other.mShortTermModelTimeout
+ && checkFloatEquals(mShortTermModelLowerLuxMultiplier,
+ other.mShortTermModelLowerLuxMultiplier)
+ && checkFloatEquals(mShortTermModelUpperLuxMultiplier,
+ other.mShortTermModelUpperLuxMultiplier);
+ }
+
+ private boolean checkFloatEquals(float one, float two) {
+ if (Float.isNaN(one) && Float.isNaN(two)) {
+ return true;
+ }
+ return one == two;
}
public static final @android.annotation.NonNull Creator<BrightnessConfiguration> CREATOR =
@@ -243,6 +326,9 @@
builder.setDescription(description);
final boolean shouldCollectColorSamples = in.readBoolean();
builder.setShouldCollectColorSamples(shouldCollectColorSamples);
+ builder.setShortTermModelTimeout(in.readLong());
+ builder.setShortTermModelLowerLuxMultiplier(in.readFloat());
+ builder.setShortTermModelUpperLuxMultiplier(in.readFloat());
return builder.build();
}
@@ -296,6 +382,18 @@
if (mShouldCollectColorSamples) {
serializer.attribute(null, ATTR_COLLECT_COLOR, Boolean.toString(true));
}
+ if (mShortTermModelTimeout >= 0) {
+ serializer.attribute(null, ATTR_MODEL_TIMEOUT,
+ Long.toString(mShortTermModelTimeout));
+ }
+ if (!Float.isNaN(mShortTermModelLowerLuxMultiplier)) {
+ serializer.attribute(null, ATTR_MODEL_LOWER_BOUND,
+ Float.toString(mShortTermModelLowerLuxMultiplier));
+ }
+ if (!Float.isNaN(mShortTermModelUpperLuxMultiplier)) {
+ serializer.attribute(null, ATTR_MODEL_UPPER_BOUND,
+ Float.toString(mShortTermModelUpperLuxMultiplier));
+ }
serializer.endTag(null, TAG_BRIGHTNESS_PARAMS);
}
@@ -320,6 +418,9 @@
Map<String, BrightnessCorrection> correctionsByPackageName = new HashMap<>();
Map<Integer, BrightnessCorrection> correctionsByCategory = new HashMap<>();
boolean shouldCollectColorSamples = false;
+ long shortTermModelTimeout = SHORT_TERM_TIMEOUT_UNSET;
+ float shortTermModelLowerLuxMultiplier = Float.NaN;
+ float shortTermModelUpperLuxMultiplier = Float.NaN;
final int configDepth = parser.getDepth();
while (XmlUtils.nextElementWithin(parser, configDepth)) {
if (TAG_BRIGHTNESS_CURVE.equals(parser.getName())) {
@@ -357,6 +458,12 @@
} else if (TAG_BRIGHTNESS_PARAMS.equals(parser.getName())) {
shouldCollectColorSamples =
Boolean.parseBoolean(parser.getAttributeValue(null, ATTR_COLLECT_COLOR));
+ Long timeout = loadLongFromXml(parser, ATTR_MODEL_TIMEOUT);
+ if (timeout != null) {
+ shortTermModelTimeout = timeout;
+ }
+ shortTermModelLowerLuxMultiplier = loadFloatFromXml(parser, ATTR_MODEL_LOWER_BOUND);
+ shortTermModelUpperLuxMultiplier = loadFloatFromXml(parser, ATTR_MODEL_UPPER_BOUND);
}
}
final int n = luxList.size();
@@ -380,6 +487,9 @@
builder.addCorrectionByCategory(category, correction);
}
builder.setShouldCollectColorSamples(shouldCollectColorSamples);
+ builder.setShortTermModelTimeout(shortTermModelTimeout);
+ builder.setShortTermModelLowerLuxMultiplier(shortTermModelLowerLuxMultiplier);
+ builder.setShortTermModelUpperLuxMultiplier(shortTermModelUpperLuxMultiplier);
return builder.build();
}
@@ -392,6 +502,16 @@
}
}
+ private static Long loadLongFromXml(XmlPullParser parser, String attribute) {
+ final String string = parser.getAttributeValue(null, attribute);
+ try {
+ return Long.parseLong(string);
+ } catch (NullPointerException | NumberFormatException e) {
+ // Ignoring
+ }
+ return null;
+ }
+
/**
* A builder class for {@link BrightnessConfiguration}s.
*/
@@ -405,6 +525,9 @@
private Map<Integer, BrightnessCorrection> mCorrectionsByCategory;
private String mDescription;
private boolean mShouldCollectColorSamples;
+ private long mShortTermModelTimeout = SHORT_TERM_TIMEOUT_UNSET;
+ private float mShortTermModelLowerLuxMultiplier = Float.NaN;
+ private float mShortTermModelUpperLuxMultiplier = Float.NaN;
/**
* Constructs the builder with the control points for the brightness curve.
@@ -542,6 +665,60 @@
}
/**
+ * Sets the timeout for the short term model in milliseconds.
+ *
+ * If the screen is inactive for this timeout then the short term model
+ * will check the lux range defined by {@link #setShortTermModelLowerLuxMultiplier(float))}
+ * and {@link #setShortTermModelUpperLuxMultiplier(float)} to decide whether to keep any
+ * adjustment the user has made to adaptive brightness.
+ */
+ @NonNull
+ public Builder setShortTermModelTimeout(long shortTermModelTimeout) {
+ mShortTermModelTimeout = shortTermModelTimeout;
+ return this;
+ }
+
+ /**
+ * Sets the multiplier used to calculate the upper bound for which
+ * a users adaptive brightness is considered valid.
+ *
+ * For example if a user changes the brightness when the ambient light level
+ * is 100 lux, the adjustment will be kept if the current ambient light level
+ * is {@code <= 100 + (100 * shortTermModelUpperLuxMultiplier)}.
+ *
+ * @throws IllegalArgumentException if shortTermModelUpperLuxMultiplier is negative.
+ */
+ @NonNull
+ public Builder setShortTermModelUpperLuxMultiplier(
+ @FloatRange(from = 0.0f) float shortTermModelUpperLuxMultiplier) {
+ if (shortTermModelUpperLuxMultiplier < 0.0f) {
+ throw new IllegalArgumentException("Negative lux multiplier");
+ }
+ mShortTermModelUpperLuxMultiplier = shortTermModelUpperLuxMultiplier;
+ return this;
+ }
+
+ /**
+ * Returns the multiplier used to calculate the lower bound for which
+ * a users adaptive brightness is considered valid.
+ *
+ * For example if a user changes the brightness when the ambient light level
+ * is 100 lux, the adjustment will be kept if the current ambient light level
+ * is {@code >= 100 - (100 * shortTermModelLowerLuxMultiplier)}.
+ *
+ * @throws IllegalArgumentException if shortTermModelUpperLuxMultiplier is negative.
+ */
+ @NonNull
+ public Builder setShortTermModelLowerLuxMultiplier(
+ @FloatRange(from = 0.0f) float shortTermModelLowerLuxMultiplier) {
+ if (shortTermModelLowerLuxMultiplier < 0.0f) {
+ throw new IllegalArgumentException("Negative lux multiplier");
+ }
+ mShortTermModelLowerLuxMultiplier = shortTermModelLowerLuxMultiplier;
+ return this;
+ }
+
+ /**
* Builds the {@link BrightnessConfiguration}.
*/
@NonNull
@@ -550,7 +727,9 @@
throw new IllegalStateException("A curve must be set!");
}
return new BrightnessConfiguration(mCurveLux, mCurveNits, mCorrectionsByPackageName,
- mCorrectionsByCategory, mDescription, mShouldCollectColorSamples);
+ mCorrectionsByCategory, mDescription, mShouldCollectColorSamples,
+ mShortTermModelTimeout, mShortTermModelLowerLuxMultiplier,
+ mShortTermModelUpperLuxMultiplier);
}
private static void checkMonotonic(float[] vals, boolean strictlyIncreasing, String name) {
diff --git a/core/java/android/hardware/hdmi/HdmiControlManager.java b/core/java/android/hardware/hdmi/HdmiControlManager.java
index 2295d2b..65a8e15 100644
--- a/core/java/android/hardware/hdmi/HdmiControlManager.java
+++ b/core/java/android/hardware/hdmi/HdmiControlManager.java
@@ -36,10 +36,10 @@
import android.util.Log;
import com.android.internal.annotations.GuardedBy;
-import com.android.internal.util.Preconditions;
import java.util.ArrayList;
import java.util.List;
+import java.util.Objects;
/**
* The {@link HdmiControlManager} class is used to send HDMI control messages
@@ -532,7 +532,7 @@
*/
@SystemApi
public void powerOffDevice(@NonNull HdmiDeviceInfo deviceInfo) {
- Preconditions.checkNotNull(deviceInfo);
+ Objects.requireNonNull(deviceInfo);
try {
mService.powerOffRemoteDevice(
deviceInfo.getLogicalAddress(), deviceInfo.getDevicePowerStatus());
@@ -549,7 +549,7 @@
@Deprecated
@SystemApi
public void powerOffRemoteDevice(@NonNull HdmiDeviceInfo deviceInfo) {
- Preconditions.checkNotNull(deviceInfo);
+ Objects.requireNonNull(deviceInfo);
try {
mService.powerOffRemoteDevice(
deviceInfo.getLogicalAddress(), deviceInfo.getDevicePowerStatus());
@@ -569,7 +569,7 @@
* @hide
*/
public void powerOnDevice(HdmiDeviceInfo deviceInfo) {
- Preconditions.checkNotNull(deviceInfo);
+ Objects.requireNonNull(deviceInfo);
try {
mService.powerOnRemoteDevice(
deviceInfo.getLogicalAddress(), deviceInfo.getDevicePowerStatus());
@@ -586,7 +586,7 @@
@Deprecated
@SystemApi
public void powerOnRemoteDevice(HdmiDeviceInfo deviceInfo) {
- Preconditions.checkNotNull(deviceInfo);
+ Objects.requireNonNull(deviceInfo);
try {
mService.powerOnRemoteDevice(
deviceInfo.getLogicalAddress(), deviceInfo.getDevicePowerStatus());
@@ -610,7 +610,7 @@
*/
@SystemApi
public void setActiveSource(@NonNull HdmiDeviceInfo deviceInfo) {
- Preconditions.checkNotNull(deviceInfo);
+ Objects.requireNonNull(deviceInfo);
try {
mService.askRemoteDeviceToBecomeActiveSource(deviceInfo.getPhysicalAddress());
} catch (RemoteException e) {
@@ -626,7 +626,7 @@
@Deprecated
@SystemApi
public void requestRemoteDeviceToBecomeActiveSource(@NonNull HdmiDeviceInfo deviceInfo) {
- Preconditions.checkNotNull(deviceInfo);
+ Objects.requireNonNull(deviceInfo);
try {
mService.askRemoteDeviceToBecomeActiveSource(deviceInfo.getPhysicalAddress());
} catch (RemoteException e) {
@@ -689,7 +689,7 @@
*/
@SystemApi
public boolean isDeviceConnected(@NonNull HdmiDeviceInfo targetDevice) {
- Preconditions.checkNotNull(targetDevice);
+ Objects.requireNonNull(targetDevice);
int physicalAddress = getLocalPhysicalAddress();
if (physicalAddress == INVALID_PHYSICAL_ADDRESS) {
return false;
@@ -710,7 +710,7 @@
@Deprecated
@SystemApi
public boolean isRemoteDeviceConnected(@NonNull HdmiDeviceInfo targetDevice) {
- Preconditions.checkNotNull(targetDevice);
+ Objects.requireNonNull(targetDevice);
int physicalAddress = getLocalPhysicalAddress();
if (physicalAddress == INVALID_PHYSICAL_ADDRESS) {
return false;
diff --git a/core/java/android/hardware/hdmi/HdmiSwitchClient.java b/core/java/android/hardware/hdmi/HdmiSwitchClient.java
index 6a72a4a..7833653 100644
--- a/core/java/android/hardware/hdmi/HdmiSwitchClient.java
+++ b/core/java/android/hardware/hdmi/HdmiSwitchClient.java
@@ -23,10 +23,9 @@
import android.os.RemoteException;
import android.util.Log;
-import com.android.internal.util.Preconditions;
-
import java.util.Collections;
import java.util.List;
+import java.util.Objects;
import java.util.concurrent.Executor;
/**
@@ -70,7 +69,7 @@
* @hide
*/
public void selectDevice(int logicalAddress, @NonNull OnSelectListener listener) {
- Preconditions.checkNotNull(listener);
+ Objects.requireNonNull(listener);
try {
mService.deviceSelect(logicalAddress, getCallbackWrapper(listener));
} catch (RemoteException e) {
@@ -91,7 +90,7 @@
*/
@SystemApi
public void selectPort(int portId, @NonNull OnSelectListener listener) {
- Preconditions.checkNotNull(listener);
+ Objects.requireNonNull(listener);
try {
mService.portSelect(portId, getCallbackWrapper(listener));
} catch (RemoteException e) {
@@ -114,7 +113,7 @@
int logicalAddress,
@NonNull @CallbackExecutor Executor executor,
@NonNull OnSelectListener listener) {
- Preconditions.checkNotNull(listener);
+ Objects.requireNonNull(listener);
try {
mService.deviceSelect(logicalAddress,
new IHdmiControlCallback.Stub() {
@@ -146,7 +145,7 @@
int portId,
@NonNull @CallbackExecutor Executor executor,
@NonNull OnSelectListener listener) {
- Preconditions.checkNotNull(listener);
+ Objects.requireNonNull(listener);
try {
mService.portSelect(portId,
new IHdmiControlCallback.Stub() {
diff --git a/core/java/android/hardware/location/ContextHubClient.java b/core/java/android/hardware/location/ContextHubClient.java
index 3adc101..c6a5dd0 100644
--- a/core/java/android/hardware/location/ContextHubClient.java
+++ b/core/java/android/hardware/location/ContextHubClient.java
@@ -22,11 +22,10 @@
import android.os.RemoteException;
import android.util.Log;
-import com.android.internal.util.Preconditions;
-
import dalvik.system.CloseGuard;
import java.io.Closeable;
+import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
/**
@@ -80,7 +79,7 @@
* @param clientProxy the proxy of the client at the service
*/
/* package */ void setClientProxy(IContextHubClient clientProxy) {
- Preconditions.checkNotNull(clientProxy, "IContextHubClient cannot be null");
+ Objects.requireNonNull(clientProxy, "IContextHubClient cannot be null");
if (mClientProxy != null) {
throw new IllegalStateException("Cannot change client proxy multiple times");
}
@@ -140,7 +139,7 @@
@RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
@ContextHubTransaction.Result
public int sendMessageToNanoApp(@NonNull NanoAppMessage message) {
- Preconditions.checkNotNull(message, "NanoAppMessage cannot be null");
+ Objects.requireNonNull(message, "NanoAppMessage cannot be null");
int maxPayloadBytes = mAttachedHub.getMaxPacketLengthBytes();
byte[] payload = message.getMessageBody();
diff --git a/core/java/android/hardware/location/ContextHubIntentEvent.java b/core/java/android/hardware/location/ContextHubIntentEvent.java
index 754327a..917f62b 100644
--- a/core/java/android/hardware/location/ContextHubIntentEvent.java
+++ b/core/java/android/hardware/location/ContextHubIntentEvent.java
@@ -21,7 +21,7 @@
import android.app.PendingIntent;
import android.content.Intent;
-import com.android.internal.util.Preconditions;
+import java.util.Objects;
/**
* A helper class to retrieve information about a Intent event received for a PendingIntent
@@ -89,7 +89,7 @@
*/
@NonNull
public static ContextHubIntentEvent fromIntent(@NonNull Intent intent) {
- Preconditions.checkNotNull(intent, "Intent cannot be null");
+ Objects.requireNonNull(intent, "Intent cannot be null");
hasExtraOrThrow(intent, ContextHubManager.EXTRA_CONTEXT_HUB_INFO);
ContextHubInfo info = intent.getParcelableExtra(ContextHubManager.EXTRA_CONTEXT_HUB_INFO);
diff --git a/core/java/android/hardware/location/ContextHubManager.java b/core/java/android/hardware/location/ContextHubManager.java
index 7639302..a51d2c9 100644
--- a/core/java/android/hardware/location/ContextHubManager.java
+++ b/core/java/android/hardware/location/ContextHubManager.java
@@ -34,11 +34,10 @@
import android.os.ServiceManager.ServiceNotFoundException;
import android.util.Log;
-import com.android.internal.util.Preconditions;
-
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;
+import java.util.Objects;
import java.util.concurrent.Executor;
/**
@@ -470,8 +469,8 @@
@RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
@NonNull public ContextHubTransaction<Void> loadNanoApp(
@NonNull ContextHubInfo hubInfo, @NonNull NanoAppBinary appBinary) {
- Preconditions.checkNotNull(hubInfo, "ContextHubInfo cannot be null");
- Preconditions.checkNotNull(appBinary, "NanoAppBinary cannot be null");
+ Objects.requireNonNull(hubInfo, "ContextHubInfo cannot be null");
+ Objects.requireNonNull(appBinary, "NanoAppBinary cannot be null");
ContextHubTransaction<Void> transaction =
new ContextHubTransaction<>(ContextHubTransaction.TYPE_LOAD_NANOAPP);
@@ -499,7 +498,7 @@
@RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
@NonNull public ContextHubTransaction<Void> unloadNanoApp(
@NonNull ContextHubInfo hubInfo, long nanoAppId) {
- Preconditions.checkNotNull(hubInfo, "ContextHubInfo cannot be null");
+ Objects.requireNonNull(hubInfo, "ContextHubInfo cannot be null");
ContextHubTransaction<Void> transaction =
new ContextHubTransaction<>(ContextHubTransaction.TYPE_UNLOAD_NANOAPP);
@@ -527,7 +526,7 @@
@RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
@NonNull public ContextHubTransaction<Void> enableNanoApp(
@NonNull ContextHubInfo hubInfo, long nanoAppId) {
- Preconditions.checkNotNull(hubInfo, "ContextHubInfo cannot be null");
+ Objects.requireNonNull(hubInfo, "ContextHubInfo cannot be null");
ContextHubTransaction<Void> transaction =
new ContextHubTransaction<>(ContextHubTransaction.TYPE_ENABLE_NANOAPP);
@@ -555,7 +554,7 @@
@RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
@NonNull public ContextHubTransaction<Void> disableNanoApp(
@NonNull ContextHubInfo hubInfo, long nanoAppId) {
- Preconditions.checkNotNull(hubInfo, "ContextHubInfo cannot be null");
+ Objects.requireNonNull(hubInfo, "ContextHubInfo cannot be null");
ContextHubTransaction<Void> transaction =
new ContextHubTransaction<>(ContextHubTransaction.TYPE_DISABLE_NANOAPP);
@@ -582,7 +581,7 @@
@RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
@NonNull public ContextHubTransaction<List<NanoAppState>> queryNanoApps(
@NonNull ContextHubInfo hubInfo) {
- Preconditions.checkNotNull(hubInfo, "ContextHubInfo cannot be null");
+ Objects.requireNonNull(hubInfo, "ContextHubInfo cannot be null");
ContextHubTransaction<List<NanoAppState>> transaction =
new ContextHubTransaction<>(ContextHubTransaction.TYPE_QUERY_NANOAPPS);
@@ -729,9 +728,9 @@
@NonNull public ContextHubClient createClient(
@NonNull ContextHubInfo hubInfo, @NonNull ContextHubClientCallback callback,
@NonNull @CallbackExecutor Executor executor) {
- Preconditions.checkNotNull(callback, "Callback cannot be null");
- Preconditions.checkNotNull(hubInfo, "ContextHubInfo cannot be null");
- Preconditions.checkNotNull(executor, "Executor cannot be null");
+ Objects.requireNonNull(callback, "Callback cannot be null");
+ Objects.requireNonNull(hubInfo, "ContextHubInfo cannot be null");
+ Objects.requireNonNull(executor, "Executor cannot be null");
ContextHubClient client = new ContextHubClient(hubInfo, false /* persistent */);
IContextHubClientCallback clientInterface = createClientCallback(
@@ -808,8 +807,8 @@
@RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
@NonNull public ContextHubClient createClient(
@NonNull ContextHubInfo hubInfo, @NonNull PendingIntent pendingIntent, long nanoAppId) {
- Preconditions.checkNotNull(pendingIntent);
- Preconditions.checkNotNull(hubInfo);
+ Objects.requireNonNull(pendingIntent);
+ Objects.requireNonNull(hubInfo);
ContextHubClient client = new ContextHubClient(hubInfo, true /* persistent */);
diff --git a/core/java/android/hardware/location/ContextHubTransaction.java b/core/java/android/hardware/location/ContextHubTransaction.java
index bc7efef..d11e0a9 100644
--- a/core/java/android/hardware/location/ContextHubTransaction.java
+++ b/core/java/android/hardware/location/ContextHubTransaction.java
@@ -22,10 +22,9 @@
import android.os.Handler;
import android.os.HandlerExecutor;
-import com.android.internal.util.Preconditions;
-
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
+import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
@@ -291,8 +290,8 @@
@NonNull ContextHubTransaction.OnCompleteListener<T> listener,
@NonNull @CallbackExecutor Executor executor) {
synchronized (this) {
- Preconditions.checkNotNull(listener, "OnCompleteListener cannot be null");
- Preconditions.checkNotNull(executor, "Executor cannot be null");
+ Objects.requireNonNull(listener, "OnCompleteListener cannot be null");
+ Objects.requireNonNull(executor, "Executor cannot be null");
if (mListener != null) {
throw new IllegalStateException(
"Cannot set ContextHubTransaction listener multiple times");
@@ -340,7 +339,7 @@
*/
/* package */ void setResponse(ContextHubTransaction.Response<T> response) {
synchronized (this) {
- Preconditions.checkNotNull(response, "Response cannot be null");
+ Objects.requireNonNull(response, "Response cannot be null");
if (mIsResponseSet) {
throw new IllegalStateException(
"Cannot set response of ContextHubTransaction multiple times");
diff --git a/core/java/android/hardware/location/NanoApp.java b/core/java/android/hardware/location/NanoApp.java
index 6a734f3..242c9e2 100644
--- a/core/java/android/hardware/location/NanoApp.java
+++ b/core/java/android/hardware/location/NanoApp.java
@@ -21,7 +21,7 @@
import android.os.Parcelable;
import android.util.Log;
-import com.android.internal.util.Preconditions;
+import java.util.Objects;
/** A class describing nano apps.
* A nano app is a piece of executable code that can be
@@ -198,12 +198,12 @@
* needed Sensors
*/
public void setNeededSensors(int[] neededSensors) {
- Preconditions.checkNotNull(neededSensors, "neededSensors must not be null");
+ Objects.requireNonNull(neededSensors, "neededSensors must not be null");
mNeededSensors = neededSensors;
}
public void setOutputEvents(int[] outputEvents) {
- Preconditions.checkNotNull(outputEvents, "outputEvents must not be null");
+ Objects.requireNonNull(outputEvents, "outputEvents must not be null");
mOutputEvents = outputEvents;
}
@@ -213,7 +213,7 @@
* @param appBinary generated events
*/
public void setAppBinary(byte[] appBinary) {
- Preconditions.checkNotNull(appBinary, "appBinary must not be null");
+ Objects.requireNonNull(appBinary, "appBinary must not be null");
mAppBinary = appBinary;
}
diff --git a/core/java/android/hardware/usb/UsbAccessory.java b/core/java/android/hardware/usb/UsbAccessory.java
index a76e4ad..a725205 100644
--- a/core/java/android/hardware/usb/UsbAccessory.java
+++ b/core/java/android/hardware/usb/UsbAccessory.java
@@ -24,6 +24,7 @@
import android.os.RemoteException;
import com.android.internal.util.Preconditions;
+import java.util.Objects;
/**
* A class representing a USB accessory, which is an external hardware component
@@ -79,8 +80,8 @@
public UsbAccessory(@NonNull String manufacturer, @NonNull String model,
@Nullable String description, @Nullable String version, @Nullable String uri,
@NonNull IUsbSerialReader serialNumberReader) {
- mManufacturer = Preconditions.checkNotNull(manufacturer);
- mModel = Preconditions.checkNotNull(model);
+ mManufacturer = Objects.requireNonNull(manufacturer);
+ mModel = Objects.requireNonNull(model);
mDescription = description;
mVersion = version;
mUri = uri;
diff --git a/core/java/android/hardware/usb/UsbDevice.java b/core/java/android/hardware/usb/UsbDevice.java
index ee2e262..67e05c8 100644
--- a/core/java/android/hardware/usb/UsbDevice.java
+++ b/core/java/android/hardware/usb/UsbDevice.java
@@ -25,6 +25,7 @@
import android.os.RemoteException;
import com.android.internal.util.Preconditions;
+import java.util.Objects;
/**
* This class represents a USB device attached to the android device with the android device
@@ -81,7 +82,7 @@
@NonNull IUsbSerialReader serialNumberReader,
boolean hasAudioPlayback, boolean hasAudioCapture, boolean hasMidi,
boolean hasVideoPlayback, boolean hasVideoCapture) {
- mName = Preconditions.checkNotNull(name);
+ mName = Objects.requireNonNull(name);
mVendorId = vendorId;
mProductId = productId;
mClass = Class;
@@ -91,7 +92,7 @@
mProductName = productName;
mVersion = Preconditions.checkStringNotEmpty(version);
mConfigurations = Preconditions.checkArrayElementsNotNull(configurations, "configurations");
- mSerialNumberReader = Preconditions.checkNotNull(serialNumberReader);
+ mSerialNumberReader = Objects.requireNonNull(serialNumberReader);
mHasAudioPlayback = hasAudioPlayback;
mHasAudioCapture = hasAudioCapture;
mHasMidi = hasMidi;
@@ -441,7 +442,7 @@
@Nullable String serialNumber,
boolean hasAudioPlayback, boolean hasAudioCapture, boolean hasMidi,
boolean hasVideoPlayback, boolean hasVideoCapture) {
- mName = Preconditions.checkNotNull(name);
+ mName = Objects.requireNonNull(name);
mVendorId = vendorId;
mProductId = productId;
mClass = Class;
diff --git a/core/java/android/hardware/usb/UsbPort.java b/core/java/android/hardware/usb/UsbPort.java
index 506230e..274e23f 100644
--- a/core/java/android/hardware/usb/UsbPort.java
+++ b/core/java/android/hardware/usb/UsbPort.java
@@ -42,6 +42,8 @@
import com.android.internal.util.Preconditions;
+import java.util.Objects;
+
/**
* Represents a physical USB port and describes its characteristics.
*
@@ -67,7 +69,7 @@
int supportedContaminantProtectionModes,
boolean supportsEnableContaminantPresenceProtection,
boolean supportsEnableContaminantPresenceDetection) {
- Preconditions.checkNotNull(id);
+ Objects.requireNonNull(id);
Preconditions.checkFlagsArgument(supportedModes,
MODE_DFP | MODE_UFP | MODE_AUDIO_ACCESSORY | MODE_DEBUG_ACCESSORY);
diff --git a/core/java/android/hardware/usb/UsbRequest.java b/core/java/android/hardware/usb/UsbRequest.java
index cc4ba08..d464ab5 100644
--- a/core/java/android/hardware/usb/UsbRequest.java
+++ b/core/java/android/hardware/usb/UsbRequest.java
@@ -27,6 +27,7 @@
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
+import java.util.Objects;
/**
* A class representing USB request packet.
@@ -96,7 +97,7 @@
*/
public boolean initialize(UsbDeviceConnection connection, UsbEndpoint endpoint) {
mEndpoint = endpoint;
- mConnection = Preconditions.checkNotNull(connection, "connection");
+ mConnection = Objects.requireNonNull(connection, "connection");
boolean wasInitialized = native_init(connection, endpoint.getAddress(),
endpoint.getAttributes(), endpoint.getMaxPacketSize(), endpoint.getInterval());
diff --git a/core/java/android/net/StringNetworkSpecifier.java b/core/java/android/net/StringNetworkSpecifier.java
index 21dee55..83dbc63 100644
--- a/core/java/android/net/StringNetworkSpecifier.java
+++ b/core/java/android/net/StringNetworkSpecifier.java
@@ -16,7 +16,8 @@
package android.net;
-import android.annotation.UnsupportedAppUsage;
+import android.annotation.NonNull;
+import android.annotation.SystemApi;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
@@ -26,18 +27,20 @@
import java.util.Objects;
/** @hide */
+@SystemApi
public final class StringNetworkSpecifier extends NetworkSpecifier implements Parcelable {
/**
* Arbitrary string used to pass (additional) information to the network factory.
*/
- @UnsupportedAppUsage
+ @NonNull
public final String specifier;
- public StringNetworkSpecifier(String specifier) {
+ public StringNetworkSpecifier(@NonNull String specifier) {
Preconditions.checkStringNotEmpty(specifier);
this.specifier = specifier;
}
+ /** @hide */
@Override
public boolean satisfiedBy(NetworkSpecifier other) {
return equals(other);
@@ -65,11 +68,11 @@
}
@Override
- public void writeToParcel(Parcel dest, int flags) {
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
dest.writeString(specifier);
}
- public static final @android.annotation.NonNull Parcelable.Creator<StringNetworkSpecifier> CREATOR =
+ public static final @NonNull Parcelable.Creator<StringNetworkSpecifier> CREATOR =
new Parcelable.Creator<StringNetworkSpecifier>() {
public StringNetworkSpecifier createFromParcel(Parcel in) {
return new StringNetworkSpecifier(in.readString());
diff --git a/core/tests/coretests/src/android/app/PullAtomMetadataTest.java b/core/tests/coretests/src/android/app/PullAtomMetadataTest.java
new file mode 100644
index 0000000..2e3f892
--- /dev/null
+++ b/core/tests/coretests/src/android/app/PullAtomMetadataTest.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.app;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.app.StatsManager.PullAtomMetadata;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public final class PullAtomMetadataTest {
+
+ @Test
+ public void testEmpty() {
+ PullAtomMetadata metadata = PullAtomMetadata.newBuilder().build();
+ assertThat(metadata.getTimeoutNs()).isEqualTo(StatsManager.DEFAULT_TIMEOUT_NS);
+ assertThat(metadata.getCoolDownNs()).isEqualTo(StatsManager.DEFAULT_COOL_DOWN_NS);
+ assertThat(metadata.getAdditiveFields()).isNull();
+ }
+
+ @Test
+ public void testSetTimeoutNs() {
+ long timeoutNs = 500_000_000L;
+ PullAtomMetadata metadata =
+ PullAtomMetadata.newBuilder().setTimeoutNs(timeoutNs).build();
+ assertThat(metadata.getTimeoutNs()).isEqualTo(timeoutNs);
+ assertThat(metadata.getCoolDownNs()).isEqualTo(StatsManager.DEFAULT_COOL_DOWN_NS);
+ assertThat(metadata.getAdditiveFields()).isNull();
+ }
+
+ @Test
+ public void testSetCoolDownNs() {
+ long coolDownNs = 10_000_000_000L;
+ PullAtomMetadata metadata =
+ PullAtomMetadata.newBuilder().setCoolDownNs(coolDownNs).build();
+ assertThat(metadata.getTimeoutNs()).isEqualTo(StatsManager.DEFAULT_TIMEOUT_NS);
+ assertThat(metadata.getCoolDownNs()).isEqualTo(coolDownNs);
+ assertThat(metadata.getAdditiveFields()).isNull();
+ }
+
+ @Test
+ public void testSetAdditiveFields() {
+ int[] fields = {2, 4, 6};
+ PullAtomMetadata metadata =
+ PullAtomMetadata.newBuilder().setAdditiveFields(fields).build();
+ assertThat(metadata.getTimeoutNs()).isEqualTo(StatsManager.DEFAULT_TIMEOUT_NS);
+ assertThat(metadata.getCoolDownNs()).isEqualTo(StatsManager.DEFAULT_COOL_DOWN_NS);
+ assertThat(metadata.getAdditiveFields()).isEqualTo(fields);
+ }
+
+ @Test
+ public void testSetAllElements() {
+ long timeoutNs = 300L;
+ long coolDownNs = 9572L;
+ int[] fields = {3, 2};
+ PullAtomMetadata metadata = PullAtomMetadata.newBuilder()
+ .setTimeoutNs(timeoutNs)
+ .setCoolDownNs(coolDownNs)
+ .setAdditiveFields(fields)
+ .build();
+ assertThat(metadata.getTimeoutNs()).isEqualTo(timeoutNs);
+ assertThat(metadata.getCoolDownNs()).isEqualTo(coolDownNs);
+ assertThat(metadata.getAdditiveFields()).isEqualTo(fields);
+ }
+}
diff --git a/core/tests/coretests/src/android/hardware/display/BrightnessConfigurationTest.java b/core/tests/coretests/src/android/hardware/display/BrightnessConfigurationTest.java
index 85aa118..895b22c 100644
--- a/core/tests/coretests/src/android/hardware/display/BrightnessConfigurationTest.java
+++ b/core/tests/coretests/src/android/hardware/display/BrightnessConfigurationTest.java
@@ -115,10 +115,26 @@
}
@Test
+ public void testLuxMultipliersMustBePositive() {
+ BrightnessConfiguration.Builder config = new BrightnessConfiguration.Builder(
+ LUX_LEVELS, NITS_LEVELS);
+ assertThrows(IllegalArgumentException.class, () -> {
+ config.setShortTermModelUpperLuxMultiplier(-1f);
+ });
+
+ assertThrows(IllegalArgumentException.class, () -> {
+ config.setShortTermModelLowerLuxMultiplier(-1f);
+ });
+ }
+
+ @Test
public void testParceledConfigIsEquivalent() {
BrightnessConfiguration.Builder builder =
new BrightnessConfiguration.Builder(LUX_LEVELS, NITS_LEVELS);
builder.setShouldCollectColorSamples(true);
+ builder.setShortTermModelTimeout(1234L);
+ builder.setShortTermModelLowerLuxMultiplier(0.9f);
+ builder.setShortTermModelUpperLuxMultiplier(0.2f);
builder.addCorrectionByCategory(3,
BrightnessCorrection.createScaleAndTranslateLog(1.0f, 2.0f));
builder.addCorrectionByPackageName("a.package.name",
@@ -137,6 +153,9 @@
BrightnessConfiguration.Builder builder =
new BrightnessConfiguration.Builder(LUX_LEVELS, NITS_LEVELS);
builder.setShouldCollectColorSamples(true);
+ builder.setShortTermModelTimeout(123L);
+ builder.setShortTermModelLowerLuxMultiplier(0.4f);
+ builder.setShortTermModelUpperLuxMultiplier(0.8f);
builder.addCorrectionByCategory(3,
BrightnessCorrection.createScaleAndTranslateLog(1.0f, 2.0f));
builder.addCorrectionByPackageName("a.package.name",
@@ -208,13 +227,28 @@
BrightnessCorrection.createScaleAndTranslateLog(1.0f, 2.0f));
builder.addCorrectionByPackageName("a.package.name",
BrightnessCorrection.createScaleAndTranslateLog(1.0f, 2.0f));
+ BrightnessConfiguration correctionsDiffer = builder.build();
+ assertNotEquals(baseConfig, correctionsDiffer);
+
+ builder = new BrightnessConfiguration.Builder(LUX_LEVELS, NITS_LEVELS);
+ builder.setShouldCollectColorSamples(true);
BrightnessConfiguration colorCollectionDiffers = builder.build();
assertNotEquals(baseConfig, colorCollectionDiffers);
builder = new BrightnessConfiguration.Builder(LUX_LEVELS, NITS_LEVELS);
- builder.setShouldCollectColorSamples(true);
- BrightnessConfiguration correctionsDiffer = builder.build();
- assertNotEquals(baseConfig, correctionsDiffer);
+ builder.setShortTermModelTimeout(300L);
+ BrightnessConfiguration timeoutDiffers = builder.build();
+ assertNotEquals(baseConfig, timeoutDiffers);
+
+ builder = new BrightnessConfiguration.Builder(LUX_LEVELS, NITS_LEVELS);
+ builder.setShortTermModelLowerLuxMultiplier(0.7f);
+ BrightnessConfiguration lowerLuxDiffers = builder.build();
+ assertNotEquals(baseConfig, lowerLuxDiffers);
+
+ builder = new BrightnessConfiguration.Builder(LUX_LEVELS, NITS_LEVELS);
+ builder.setShortTermModelUpperLuxMultiplier(0.6f);
+ BrightnessConfiguration upperLuxDiffers = builder.build();
+ assertNotEquals(baseConfig, upperLuxDiffers);
}
private static void assertArrayEquals(float[] expected, float[] actual, String name) {
diff --git a/core/tests/coretests/src/android/view/textclassifier/ActionsSuggestionsHelperTest.java b/core/tests/coretests/src/android/view/textclassifier/ActionsSuggestionsHelperTest.java
index 80bce26..ec7e83f 100644
--- a/core/tests/coretests/src/android/view/textclassifier/ActionsSuggestionsHelperTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/ActionsSuggestionsHelperTest.java
@@ -238,6 +238,7 @@
assertThat(conversationActions).isEmpty();
}
+ @Test
public void createLabeledIntentResult_null() {
ActionsSuggestionsModel.ActionSuggestion nativeSuggestion =
new ActionsSuggestionsModel.ActionSuggestion(
diff --git a/core/tests/systemproperties/src/android/os/SystemPropertiesTest.java b/core/tests/systemproperties/src/android/os/SystemPropertiesTest.java
index 9f70538..67783bf 100644
--- a/core/tests/systemproperties/src/android/os/SystemPropertiesTest.java
+++ b/core/tests/systemproperties/src/android/os/SystemPropertiesTest.java
@@ -94,7 +94,7 @@
}
@SmallTest
- private static void testHandle() throws Exception {
+ public void testHandle() throws Exception {
String value;
SystemProperties.Handle handle = SystemProperties.find("doesnotexist_2341431");
assertNull(handle);
diff --git a/media/java/android/media/AudioManager.java b/media/java/android/media/AudioManager.java
index 34ed5b3..e410882 100644
--- a/media/java/android/media/AudioManager.java
+++ b/media/java/android/media/AudioManager.java
@@ -3645,7 +3645,8 @@
* the callback. If <code>null</code>, the {@link Handler} associated with the main
* {@link Looper} will be used.
*/
- public void registerAudioPlaybackCallback(@NonNull AudioPlaybackCallback cb, Handler handler)
+ public void registerAudioPlaybackCallback(@NonNull AudioPlaybackCallback cb,
+ @Nullable Handler handler)
{
if (cb == null) {
throw new IllegalArgumentException("Illegal null AudioPlaybackCallback argument");
@@ -3834,7 +3835,8 @@
* the callback. If <code>null</code>, the {@link Handler} associated with the main
* {@link Looper} will be used.
*/
- public void registerAudioRecordingCallback(@NonNull AudioRecordingCallback cb, Handler handler)
+ public void registerAudioRecordingCallback(@NonNull AudioRecordingCallback cb,
+ @Nullable Handler handler)
{
if (cb == null) {
throw new IllegalArgumentException("Illegal null AudioRecordingCallback argument");
@@ -5172,7 +5174,7 @@
* {@link Looper} will be used.
*/
public void registerAudioDeviceCallback(AudioDeviceCallback callback,
- android.os.Handler handler) {
+ @Nullable Handler handler) {
synchronized (mDeviceCallbacks) {
if (callback != null && !mDeviceCallbacks.containsKey(callback)) {
if (mDeviceCallbacks.size() == 0) {
diff --git a/media/java/android/media/IMediaRoute2Provider.aidl b/media/java/android/media/IMediaRoute2Provider.aidl
index eb34a01..cfe9b39 100644
--- a/media/java/android/media/IMediaRoute2Provider.aidl
+++ b/media/java/android/media/IMediaRoute2Provider.aidl
@@ -25,7 +25,7 @@
oneway interface IMediaRoute2Provider {
void setClient(IMediaRoute2ProviderClient client);
void requestCreateSession(String packageName, String routeId,
- String controlCategory, int requestId);
+ String controlCategory, long requestId);
void releaseSession(int sessionId);
void selectRoute(int sessionId, String routeId);
diff --git a/media/java/android/media/IMediaRoute2ProviderClient.aidl b/media/java/android/media/IMediaRoute2ProviderClient.aidl
index ce5fa8c..6a763c5 100644
--- a/media/java/android/media/IMediaRoute2ProviderClient.aidl
+++ b/media/java/android/media/IMediaRoute2ProviderClient.aidl
@@ -26,5 +26,5 @@
*/
oneway interface IMediaRoute2ProviderClient {
void updateProviderInfo(in MediaRoute2ProviderInfo info);
- void notifySessionCreated(in @nullable RouteSessionInfo sessionInfo, int requestId);
+ void notifySessionCreated(in @nullable RouteSessionInfo sessionInfo, long requestId);
}
diff --git a/media/java/android/media/MediaRoute2ProviderService.java b/media/java/android/media/MediaRoute2ProviderService.java
index 9d5b071..d3f47e9 100644
--- a/media/java/android/media/MediaRoute2ProviderService.java
+++ b/media/java/android/media/MediaRoute2ProviderService.java
@@ -128,7 +128,7 @@
* session info changes.
*
* @param sessionInfo new session information
- * @see #notifySessionCreated(RouteSessionInfo, int)
+ * @see #notifySessionCreated(RouteSessionInfo, long)
*/
public final void updateSessionInfo(@NonNull RouteSessionInfo sessionInfo) {
Objects.requireNonNull(sessionInfo, "sessionInfo must not be null");
@@ -159,7 +159,7 @@
* @param requestId id of the previous request to create this session
*/
//TODO: fail reason?
- public final void notifySessionCreated(@Nullable RouteSessionInfo sessionInfo, int requestId) {
+ public final void notifySessionCreated(@Nullable RouteSessionInfo sessionInfo, long requestId) {
if (sessionInfo != null) {
int sessionId = sessionInfo.getSessionId();
synchronized (mSessionLock) {
@@ -203,10 +203,10 @@
/**
* Called when a session should be created.
* You should create and maintain your own session and notifies the client of
- * session info. Call {@link #notifySessionCreated(RouteSessionInfo, int)}
+ * session info. Call {@link #notifySessionCreated(RouteSessionInfo, long)}
* with the given {@code requestId} to notify the information of a new session.
* If you can't create the session or want to reject the request, pass {@code null}
- * as session info in {@link #notifySessionCreated(RouteSessionInfo, int)}
+ * as session info in {@link #notifySessionCreated(RouteSessionInfo, long)}
* with the given {@code requestId}.
*
* @param packageName the package name of the application that selected the route
@@ -215,7 +215,7 @@
* @param requestId the id of this session creation request
*/
public abstract void onCreateSession(@NonNull String packageName, @NonNull String routeId,
- @NonNull String controlCategory, int requestId);
+ @NonNull String controlCategory, long requestId);
/**
* Called when a session is about to be destroyed.
@@ -308,7 +308,7 @@
@Override
public void requestCreateSession(String packageName, String routeId,
- String controlCategory, int requestId) {
+ String controlCategory, long requestId) {
if (!checkCallerisSystem()) {
return;
}
diff --git a/media/java/android/media/MediaRouter2.java b/media/java/android/media/MediaRouter2.java
index 660d3d1..046a8bb 100644
--- a/media/java/android/media/MediaRouter2.java
+++ b/media/java/android/media/MediaRouter2.java
@@ -29,7 +29,6 @@
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
-import android.os.Process;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.text.TextUtils;
@@ -344,9 +343,7 @@
// TODO: Check the route supports the given controlCategory
final int requestId;
- // TODO: This does not ensure the uniqueness of the request ID.
- // Find the way to ensure it. (e.g. have mapping inside MediaRouterService)
- requestId = Process.myPid() * 10000 + mSessionCreationRequestCnt.getAndIncrement();
+ requestId = mSessionCreationRequestCnt.getAndIncrement();
SessionCreationRequest request = new SessionCreationRequest(
requestId, route, controlCategory);
diff --git a/media/java/android/media/MediaRouter2Manager.java b/media/java/android/media/MediaRouter2Manager.java
index f677336..4213dd3 100644
--- a/media/java/android/media/MediaRouter2Manager.java
+++ b/media/java/android/media/MediaRouter2Manager.java
@@ -23,7 +23,6 @@
import android.annotation.Nullable;
import android.content.Context;
import android.os.Handler;
-import android.os.Process;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.text.TextUtils;
@@ -176,6 +175,11 @@
return routes;
}
+ @NonNull
+ public List<RouteSessionInfo> getRouteSessions() {
+ return Collections.emptyList();
+ }
+
/**
* Gets the list of routes that are actively used by {@link MediaRouter2}.
*/
@@ -220,8 +224,7 @@
}
if (client != null) {
try {
- //TODO: make request id globally unique
- int requestId = Process.myPid() * 10000 + mNextRequestId.getAndIncrement();
+ int requestId = mNextRequestId.getAndIncrement();
mMediaRouterService.requestCreateClientSession(
client, packageName, route, requestId);
} catch (RemoteException ex) {
diff --git a/media/tests/MediaRouteProvider/src/com/android/mediarouteprovider/example/SampleMediaRoute2ProviderService.java b/media/tests/MediaRouteProvider/src/com/android/mediarouteprovider/example/SampleMediaRoute2ProviderService.java
index ca209bc..afca6cf 100644
--- a/media/tests/MediaRouteProvider/src/com/android/mediarouteprovider/example/SampleMediaRoute2ProviderService.java
+++ b/media/tests/MediaRouteProvider/src/com/android/mediarouteprovider/example/SampleMediaRoute2ProviderService.java
@@ -153,7 +153,7 @@
@Override
public void onCreateSession(String packageName, String routeId, String controlCategory,
- int requestId) {
+ long requestId) {
MediaRoute2Info route = mRoutes.get(routeId);
if (route == null || TextUtils.equals(ROUTE_ID3_SESSION_CREATION_FAILED, routeId)) {
// Tell the router that session cannot be created by passing null as sessionInfo.
diff --git a/packages/SystemUI/res/values-television/config.xml b/packages/SystemUI/res/values-television/config.xml
index 27db294..4cc5a67 100644
--- a/packages/SystemUI/res/values-television/config.xml
+++ b/packages/SystemUI/res/values-television/config.xml
@@ -22,6 +22,7 @@
<resources>
<!-- SystemUI Services: The classes of the stuff to start. -->
<string-array name="config_systemUIServiceComponents" translatable="false">
+ <item>com.android.systemui.util.NotificationChannels</item>
<item>com.android.systemui.volume.VolumeUI</item>
<item>com.android.systemui.stackdivider.Divider</item>
<item>com.android.systemui.statusbar.tv.TvStatusBar</item>
diff --git a/services/backup/java/com/android/server/backup/UserBackupManagerService.java b/services/backup/java/com/android/server/backup/UserBackupManagerService.java
index b36f46c..2799f12 100644
--- a/services/backup/java/com/android/server/backup/UserBackupManagerService.java
+++ b/services/backup/java/com/android/server/backup/UserBackupManagerService.java
@@ -2431,7 +2431,6 @@
mContext.enforceCallingPermission(android.Manifest.permission.BACKUP,
"setAncestralSerialNumber");
Slog.v(TAG, "Setting ancestral work profile id to " + ancestralSerialNumber);
- // TODO (b/124359804)
try (RandomAccessFile af = getAncestralSerialNumberFile()) {
af.writeLong(ancestralSerialNumber);
} catch (IOException e) {
@@ -2444,7 +2443,6 @@
* {@link #setAncestralSerialNumber(long)}. Will return {@code -1} if not set.
*/
public long getAncestralSerialNumber() {
- // TODO (b/124359804)
try (RandomAccessFile af = getAncestralSerialNumberFile()) {
return af.readLong();
} catch (IOException e) {
@@ -2570,7 +2568,6 @@
mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "adbBackup");
final int callingUserHandle = UserHandle.getCallingUserId();
- // TODO: http://b/22388012
if (callingUserHandle != UserHandle.USER_SYSTEM) {
throw new IllegalStateException("Backup supported only for the device owner");
}
@@ -2708,7 +2705,6 @@
mContext.enforceCallingPermission(android.Manifest.permission.BACKUP, "adbRestore");
final int callingUserHandle = UserHandle.getCallingUserId();
- // TODO: http://b/22388012
if (callingUserHandle != UserHandle.USER_SYSTEM) {
throw new IllegalStateException("Restore supported only for the device owner");
}
diff --git a/services/backup/java/com/android/server/backup/utils/TarBackupReader.java b/services/backup/java/com/android/server/backup/utils/TarBackupReader.java
index f3b8098..d2d382d 100644
--- a/services/backup/java/com/android/server/backup/utils/TarBackupReader.java
+++ b/services/backup/java/com/android/server/backup/utils/TarBackupReader.java
@@ -775,17 +775,17 @@
private static void hexLog(byte[] block) {
int offset = 0;
- int todo = block.length;
+ int remaining = block.length;
StringBuilder buf = new StringBuilder(64);
- while (todo > 0) {
+ while (remaining > 0) {
buf.append(String.format("%04x ", offset));
- int numThisLine = (todo > 16) ? 16 : todo;
+ int numThisLine = (remaining > 16) ? 16 : remaining;
for (int i = 0; i < numThisLine; i++) {
buf.append(String.format("%02x ", block[offset + i]));
}
Slog.i("hexdump", buf.toString());
buf.setLength(0);
- todo -= numThisLine;
+ remaining -= numThisLine;
offset += numThisLine;
}
}
diff --git a/services/core/java/com/android/server/DynamicSystemService.java b/services/core/java/com/android/server/DynamicSystemService.java
index 7b02b6e..7909e30 100644
--- a/services/core/java/com/android/server/DynamicSystemService.java
+++ b/services/core/java/com/android/server/DynamicSystemService.java
@@ -179,18 +179,7 @@
@Override
public boolean isInUse() throws RemoteException {
- boolean gsidWasRunning = "running".equals(SystemProperties.get("init.svc.gsid"));
- boolean isInUse = false;
-
- try {
- isInUse = getGsiService().isGsiRunning();
- } finally {
- if (!gsidWasRunning && !isInUse) {
- mGsiService = null;
- }
- }
-
- return isInUse;
+ return SystemProperties.getBoolean("ro.gsid.image_running", false);
}
@Override
diff --git a/services/core/java/com/android/server/display/AutomaticBrightnessController.java b/services/core/java/com/android/server/display/AutomaticBrightnessController.java
index 177e2d8..c99774a 100644
--- a/services/core/java/com/android/server/display/AutomaticBrightnessController.java
+++ b/services/core/java/com/android/server/display/AutomaticBrightnessController.java
@@ -52,9 +52,6 @@
private static final boolean DEBUG_PRETEND_LIGHT_SENSOR_ABSENT = false;
- // If true, enables the use of the screen auto-brightness adjustment setting.
- private static final boolean USE_SCREEN_AUTO_BRIGHTNESS_ADJUSTMENT = true;
-
// How long the current sensor reading is assumed to be valid beyond the current time.
// This provides a bit of prediction, as well as ensures that the weight for the last sample is
// non-zero, which in turn ensures that the total weight is non-zero.
@@ -131,13 +128,6 @@
private boolean mLoggingEnabled;
- // Timeout after which we remove the effects any user interactions might've had on the
- // brightness mapping. This timeout doesn't start until we transition to a non-interactive
- // display policy so that we don't reset while users are using their devices, but also so that
- // we don't erroneously keep the short-term model if the device is dozing but the display is
- // fully on.
- private long mShortTermModelTimeout;
-
// Amount of time to delay auto-brightness after screen on while waiting for
// the light sensor to warm-up in milliseconds.
// May be 0 if no warm-up is required.
@@ -202,7 +192,6 @@
// we use a relative threshold to determine when to revert to the OEM curve.
private boolean mShortTermModelValid;
private float mShortTermModelAnchor;
- private float SHORT_TERM_MODEL_THRESHOLD_RATIO = 0.6f;
// Context-sensitive brightness configurations require keeping track of the foreground app's
// package name and category, which is done by registering a TaskStackListener to call back to
@@ -224,14 +213,13 @@
int lightSensorRate, int initialLightSensorRate, long brighteningLightDebounceConfig,
long darkeningLightDebounceConfig, boolean resetAmbientLuxAfterWarmUpConfig,
HysteresisLevels ambientBrightnessThresholds,
- HysteresisLevels screenBrightnessThresholds, long shortTermModelTimeout,
+ HysteresisLevels screenBrightnessThresholds,
PackageManager packageManager) {
this(new Injector(), callbacks, looper, sensorManager, lightSensor, mapper,
lightSensorWarmUpTime, brightnessMin, brightnessMax, dozeScaleFactor,
lightSensorRate, initialLightSensorRate, brighteningLightDebounceConfig,
darkeningLightDebounceConfig, resetAmbientLuxAfterWarmUpConfig,
- ambientBrightnessThresholds, screenBrightnessThresholds, shortTermModelTimeout,
- packageManager);
+ ambientBrightnessThresholds, screenBrightnessThresholds, packageManager);
}
@VisibleForTesting
@@ -241,7 +229,7 @@
int lightSensorRate, int initialLightSensorRate, long brighteningLightDebounceConfig,
long darkeningLightDebounceConfig, boolean resetAmbientLuxAfterWarmUpConfig,
HysteresisLevels ambientBrightnessThresholds,
- HysteresisLevels screenBrightnessThresholds, long shortTermModelTimeout,
+ HysteresisLevels screenBrightnessThresholds,
PackageManager packageManager) {
mInjector = injector;
mCallbacks = callbacks;
@@ -261,7 +249,6 @@
mWeightingIntercept = AMBIENT_LIGHT_LONG_HORIZON_MILLIS;
mAmbientBrightnessThresholds = ambientBrightnessThresholds;
mScreenBrightnessThresholds = screenBrightnessThresholds;
- mShortTermModelTimeout = shortTermModelTimeout;
mShortTermModelValid = true;
mShortTermModelAnchor = -1;
@@ -370,7 +357,7 @@
}
if (!isInteractivePolicy(policy) && isInteractivePolicy(oldPolicy)) {
mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_SHORT_TERM_MODEL,
- mShortTermModelTimeout);
+ mBrightnessMapper.getShortTermModelTimeout());
} else if (isInteractivePolicy(policy) && !isInteractivePolicy(oldPolicy)) {
mHandler.removeMessages(MSG_INVALIDATE_SHORT_TERM_MODEL);
}
@@ -452,7 +439,7 @@
pw.println(" mAmbientLightRingBuffer=" + mAmbientLightRingBuffer);
pw.println(" mScreenAutoBrightness=" + mScreenAutoBrightness);
pw.println(" mDisplayPolicy=" + DisplayPowerRequest.policyToString(mDisplayPolicy));
- pw.println(" mShortTermModelTimeout=" + mShortTermModelTimeout);
+ pw.println(" mShortTermModelTimeout=" + mBrightnessMapper.getShortTermModelTimeout());
pw.println(" mShortTermModelAnchor=" + mShortTermModelAnchor);
pw.println(" mShortTermModelValid=" + mShortTermModelValid);
pw.println(" mBrightnessAdjustmentSamplePending=" + mBrightnessAdjustmentSamplePending);
@@ -552,20 +539,10 @@
// If the short term model was invalidated and the change is drastic enough, reset it.
if (!mShortTermModelValid && mShortTermModelAnchor != -1) {
- final float minAmbientLux =
- mShortTermModelAnchor - mShortTermModelAnchor * SHORT_TERM_MODEL_THRESHOLD_RATIO;
- final float maxAmbientLux =
- mShortTermModelAnchor + mShortTermModelAnchor * SHORT_TERM_MODEL_THRESHOLD_RATIO;
- if (minAmbientLux < mAmbientLux && mAmbientLux < maxAmbientLux) {
- if (mLoggingEnabled) {
- Slog.d(TAG, "ShortTermModel: re-validate user data, ambient lux is " +
- minAmbientLux + " < " + mAmbientLux + " < " + maxAmbientLux);
- }
- mShortTermModelValid = true;
- } else {
- Slog.d(TAG, "ShortTermModel: reset data, ambient lux is " + mAmbientLux +
- "(" + minAmbientLux + ", " + maxAmbientLux + ")");
+ if (mBrightnessMapper.shouldResetShortTermModel(mAmbientLux, mShortTermModelAnchor)) {
resetShortTermModel();
+ } else {
+ mShortTermModelValid = true;
}
}
}
diff --git a/services/core/java/com/android/server/display/BrightnessMappingStrategy.java b/services/core/java/com/android/server/display/BrightnessMappingStrategy.java
index 171cc5a..ff0b015 100644
--- a/services/core/java/com/android/server/display/BrightnessMappingStrategy.java
+++ b/services/core/java/com/android/server/display/BrightnessMappingStrategy.java
@@ -47,6 +47,7 @@
private static final float LUX_GRAD_SMOOTHING = 0.25f;
private static final float MAX_GRAD = 1.0f;
+ private static final float SHORT_TERM_MODEL_THRESHOLD_RATIO = 0.6f;
protected boolean mLoggingEnabled;
@@ -69,6 +70,9 @@
int[] backlightRange = resources.getIntArray(
com.android.internal.R.array.config_screenBrightnessBacklight);
+ long shortTermModelTimeout = resources.getInteger(
+ com.android.internal.R.integer.config_autoBrightnessShortTermModelTimeout);
+
if (isValidMapping(nitsRange, backlightRange)
&& isValidMapping(luxLevels, brightnessLevelsNits)) {
int minimumBacklight = resources.getInteger(
@@ -82,11 +86,14 @@
}
BrightnessConfiguration.Builder builder = new BrightnessConfiguration.Builder(
luxLevels, brightnessLevelsNits);
+ builder.setShortTermModelTimeout(shortTermModelTimeout);
+ builder.setShortTermModelLowerLuxMultiplier(SHORT_TERM_MODEL_THRESHOLD_RATIO);
+ builder.setShortTermModelUpperLuxMultiplier(SHORT_TERM_MODEL_THRESHOLD_RATIO);
return new PhysicalMappingStrategy(builder.build(), nitsRange, backlightRange,
autoBrightnessAdjustmentMaxGamma);
} else if (isValidMapping(luxLevels, brightnessLevelsBacklight)) {
return new SimpleMappingStrategy(luxLevels, brightnessLevelsBacklight,
- autoBrightnessAdjustmentMaxGamma);
+ autoBrightnessAdjustmentMaxGamma, shortTermModelTimeout);
} else {
return null;
}
@@ -189,6 +196,12 @@
public abstract boolean setBrightnessConfiguration(@Nullable BrightnessConfiguration config);
/**
+ * Gets the current {@link BrightnessConfiguration}.
+ */
+ @Nullable
+ public abstract BrightnessConfiguration getBrightnessConfiguration();
+
+ /**
* Returns the desired brightness of the display based on the current ambient lux, including
* any context-related corrections.
*
@@ -274,8 +287,53 @@
/** @return The default brightness configuration. */
public abstract BrightnessConfiguration getDefaultConfig();
+
+ /**
+ * Returns the timeout for the short term model
+ *
+ * Timeout after which we remove the effects any user interactions might've had on the
+ * brightness mapping. This timeout doesn't start until we transition to a non-interactive
+ * display policy so that we don't reset while users are using their devices, but also so that
+ * we don't erroneously keep the short-term model if the device is dozing but the
+ * display is fully on.
+ */
+ public abstract long getShortTermModelTimeout();
+
public abstract void dump(PrintWriter pw);
+ /**
+ * Check if the short term model should be reset given the anchor lux the last
+ * brightness change was made at and the current ambient lux.
+ */
+ public boolean shouldResetShortTermModel(float ambientLux, float shortTermModelAnchor) {
+ BrightnessConfiguration config = getBrightnessConfiguration();
+ float minThresholdRatio = SHORT_TERM_MODEL_THRESHOLD_RATIO;
+ float maxThresholdRatio = SHORT_TERM_MODEL_THRESHOLD_RATIO;
+ if (config != null) {
+ if (!Float.isNaN(config.getShortTermModelLowerLuxMultiplier())) {
+ minThresholdRatio = config.getShortTermModelLowerLuxMultiplier();
+ }
+ if (!Float.isNaN(config.getShortTermModelUpperLuxMultiplier())) {
+ maxThresholdRatio = config.getShortTermModelUpperLuxMultiplier();
+ }
+ }
+ final float minAmbientLux =
+ shortTermModelAnchor - shortTermModelAnchor * minThresholdRatio;
+ final float maxAmbientLux =
+ shortTermModelAnchor + shortTermModelAnchor * maxThresholdRatio;
+ if (minAmbientLux < ambientLux && ambientLux <= maxAmbientLux) {
+ if (mLoggingEnabled) {
+ Slog.d(TAG, "ShortTermModel: re-validate user data, ambient lux is "
+ + minAmbientLux + " < " + ambientLux + " < " + maxAmbientLux);
+ }
+ return false;
+ } else {
+ Slog.d(TAG, "ShortTermModel: reset data, ambient lux is " + ambientLux
+ + "(" + minAmbientLux + ", " + maxAmbientLux + ")");
+ return true;
+ }
+ }
+
protected float normalizeAbsoluteBrightness(int brightness) {
brightness = MathUtils.constrain(brightness,
PowerManager.BRIGHTNESS_OFF, PowerManager.BRIGHTNESS_ON);
@@ -455,8 +513,10 @@
private float mAutoBrightnessAdjustment;
private float mUserLux;
private float mUserBrightness;
+ private long mShortTermModelTimeout;
- public SimpleMappingStrategy(float[] lux, int[] brightness, float maxGamma) {
+ private SimpleMappingStrategy(float[] lux, int[] brightness, float maxGamma,
+ long timeout) {
Preconditions.checkArgument(lux.length != 0 && brightness.length != 0,
"Lux and brightness arrays must not be empty!");
Preconditions.checkArgument(lux.length == brightness.length,
@@ -481,6 +541,12 @@
PLOG.start("simple mapping strategy");
}
computeSpline();
+ mShortTermModelTimeout = timeout;
+ }
+
+ @Override
+ public long getShortTermModelTimeout() {
+ return mShortTermModelTimeout;
}
@Override
@@ -489,6 +555,11 @@
}
@Override
+ public BrightnessConfiguration getBrightnessConfiguration() {
+ return null;
+ }
+
+ @Override
public float getBrightness(float lux, String packageName,
@ApplicationInfo.Category int category) {
return mSpline.interpolate(lux);
@@ -660,6 +731,15 @@
}
@Override
+ public long getShortTermModelTimeout() {
+ if (mConfig.getShortTermModelTimeout() >= 0) {
+ return mConfig.getShortTermModelTimeout();
+ } else {
+ return mDefaultConfig.getShortTermModelTimeout();
+ }
+ }
+
+ @Override
public boolean setBrightnessConfiguration(@Nullable BrightnessConfiguration config) {
if (config == null) {
config = mDefaultConfig;
@@ -676,6 +756,11 @@
}
@Override
+ public BrightnessConfiguration getBrightnessConfiguration() {
+ return mConfig;
+ }
+
+ @Override
public float getBrightness(float lux, String packageName,
@ApplicationInfo.Category int category) {
float nits = mBrightnessSpline.interpolate(lux);
diff --git a/services/core/java/com/android/server/display/DisplayPowerController.java b/services/core/java/com/android/server/display/DisplayPowerController.java
index e42545e..f1655f0 100644
--- a/services/core/java/com/android/server/display/DisplayPowerController.java
+++ b/services/core/java/com/android/server/display/DisplayPowerController.java
@@ -483,8 +483,6 @@
+ initialLightSensorRate + ") to be less than or equal to "
+ "config_autoBrightnessLightSensorRate (" + lightSensorRate + ").");
}
- int shortTermModelTimeout = resources.getInteger(
- com.android.internal.R.integer.config_autoBrightnessShortTermModelTimeout);
String lightSensorType = resources.getString(
com.android.internal.R.string.config_displayLightSensorType);
@@ -498,8 +496,7 @@
mScreenBrightnessRangeMaximum, dozeScaleFactor, lightSensorRate,
initialLightSensorRate, brighteningLightDebounce, darkeningLightDebounce,
autoBrightnessResetAmbientLuxAfterWarmUp, ambientBrightnessThresholds,
- screenBrightnessThresholds, shortTermModelTimeout,
- context.getPackageManager());
+ screenBrightnessThresholds, context.getPackageManager());
} else {
mUseSoftwareAutoBrightnessConfig = false;
}
diff --git a/services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java b/services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java
index e5292a0..f3d60f5 100644
--- a/services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java
+++ b/services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java
@@ -225,11 +225,13 @@
builder.setIsPreInstalled(isSystemApp(packageName));
AppInstallMetadata appInstallMetadata = builder.build();
+ Map<String, String> allowedInstallers = getAllowedInstallers(packageInfo);
- Slog.i(TAG, "To be verified: " + appInstallMetadata);
+ Slog.i(
+ TAG,
+ "To be verified: " + appInstallMetadata + " installers " + allowedInstallers);
IntegrityCheckResult result =
- mEvaluationEngine.evaluate(
- appInstallMetadata, getAllowedInstallers(packageInfo));
+ mEvaluationEngine.evaluate(appInstallMetadata, allowedInstallers);
Slog.i(
TAG,
"Integrity check result: "
@@ -371,7 +373,7 @@
String[] packageAndCert =
packageCertPair.split(INSTALLER_PACKAGE_CERT_DELIMITER);
if (packageAndCert.length == 2) {
- String packageName = packageAndCert[0];
+ String packageName = getPackageNameNormalized(packageAndCert[0]);
String cert = packageAndCert[1];
packageCertMap.put(packageName, cert);
}
@@ -379,21 +381,9 @@
}
}
- Slog.i("DEBUG", "allowed installers map " + packageCertMap);
return packageCertMap;
}
- private boolean getPreInstalled(String packageName) {
- try {
- PackageInfo existingPackageInfo =
- mContext.getPackageManager().getPackageInfo(packageName, 0);
- return existingPackageInfo.applicationInfo != null
- && existingPackageInfo.applicationInfo.isSystemApp();
- } catch (PackageManager.NameNotFoundException e) {
- return false;
- }
- }
-
private static Signature getSignature(@NonNull PackageInfo packageInfo) {
if (packageInfo.signatures == null || packageInfo.signatures.length < 1) {
throw new IllegalArgumentException("Package signature not found in " + packageInfo);
@@ -463,7 +453,8 @@
PackageInfo basePackageInfo =
mContext.getPackageManager()
.getPackageArchiveInfo(
- baseFile.getAbsolutePath(), PackageManager.GET_SIGNATURES);
+ baseFile.getAbsolutePath(),
+ PackageManager.GET_SIGNATURES | PackageManager.GET_META_DATA);
if (basePackageInfo == null) {
for (File apkFile : multiApkDirectory.listFiles()) {
@@ -477,7 +468,8 @@
mContext.getPackageManager()
.getPackageArchiveInfo(
apkFile.getAbsolutePath(),
- PackageManager.GET_SIGNING_CERTIFICATES);
+ PackageManager.GET_SIGNING_CERTIFICATES
+ | PackageManager.GET_META_DATA);
if (basePackageInfo != null) {
Slog.i(TAG, "Found package info from " + apkFile);
break;
diff --git a/services/core/java/com/android/server/integrity/IntegrityFileManager.java b/services/core/java/com/android/server/integrity/IntegrityFileManager.java
index bdf0279..e224724 100644
--- a/services/core/java/com/android/server/integrity/IntegrityFileManager.java
+++ b/services/core/java/com/android/server/integrity/IntegrityFileManager.java
@@ -24,14 +24,14 @@
import com.android.internal.annotations.VisibleForTesting;
import com.android.server.integrity.model.RuleMetadata;
-import com.android.server.integrity.parser.RuleBinaryParser;
import com.android.server.integrity.parser.RuleMetadataParser;
import com.android.server.integrity.parser.RuleParseException;
import com.android.server.integrity.parser.RuleParser;
-import com.android.server.integrity.serializer.RuleBinarySerializer;
+import com.android.server.integrity.parser.RuleXmlParser;
import com.android.server.integrity.serializer.RuleMetadataSerializer;
import com.android.server.integrity.serializer.RuleSerializeException;
import com.android.server.integrity.serializer.RuleSerializer;
+import com.android.server.integrity.serializer.RuleXmlSerializer;
import java.io.File;
import java.io.FileInputStream;
@@ -75,8 +75,8 @@
private IntegrityFileManager() {
this(
- new RuleBinaryParser(),
- new RuleBinarySerializer(),
+ new RuleXmlParser(),
+ new RuleXmlSerializer(),
Environment.getDataSystemDirectory());
}
diff --git a/services/core/java/com/android/server/integrity/engine/RuleEvaluationEngine.java b/services/core/java/com/android/server/integrity/engine/RuleEvaluationEngine.java
index 0ea6efc..07eacbf 100644
--- a/services/core/java/com/android/server/integrity/engine/RuleEvaluationEngine.java
+++ b/services/core/java/com/android/server/integrity/engine/RuleEvaluationEngine.java
@@ -17,15 +17,21 @@
package com.android.server.integrity.engine;
import android.content.integrity.AppInstallMetadata;
+import android.content.integrity.AtomicFormula;
+import android.content.integrity.CompoundFormula;
+import android.content.integrity.Formula;
import android.content.integrity.Rule;
import android.util.Slog;
+import com.android.internal.annotations.VisibleForTesting;
import com.android.server.integrity.IntegrityFileManager;
import com.android.server.integrity.model.IntegrityCheckResult;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
/**
* The engine used to evaluate rules against app installs.
@@ -42,7 +48,8 @@
private final IntegrityFileManager mIntegrityFileManager;
- private RuleEvaluationEngine(IntegrityFileManager integrityFileManager) {
+ @VisibleForTesting
+ RuleEvaluationEngine(IntegrityFileManager integrityFileManager) {
mIntegrityFileManager = integrityFileManager;
}
@@ -64,6 +71,7 @@
public IntegrityCheckResult evaluate(
AppInstallMetadata appInstallMetadata, Map<String, String> allowedInstallers) {
List<Rule> rules = loadRules(appInstallMetadata);
+ allowedInstallersRule(allowedInstallers).ifPresent(rules::add);
return RuleEvaluator.evaluateRules(rules, appInstallMetadata);
}
@@ -75,4 +83,42 @@
return new ArrayList<>();
}
}
+
+ private static Optional<Rule> allowedInstallersRule(Map<String, String> allowedInstallers) {
+ if (allowedInstallers.isEmpty()) {
+ return Optional.empty();
+ }
+
+ List<Formula> formulas = new ArrayList<>(allowedInstallers.size());
+ allowedInstallers.forEach(
+ (installer, cert) -> {
+ formulas.add(allowedInstallerFormula(installer, cert));
+ });
+
+ // We need this special case since OR-formulas require at least two operands.
+ Formula allInstallersFormula =
+ formulas.size() == 1
+ ? formulas.get(0)
+ : new CompoundFormula(CompoundFormula.OR, formulas);
+
+ return Optional.of(
+ new Rule(
+ new CompoundFormula(
+ CompoundFormula.NOT, Arrays.asList(allInstallersFormula)),
+ Rule.DENY));
+ }
+
+ private static Formula allowedInstallerFormula(String installer, String cert) {
+ return new CompoundFormula(
+ CompoundFormula.AND,
+ Arrays.asList(
+ new AtomicFormula.StringAtomicFormula(
+ AtomicFormula.INSTALLER_NAME,
+ installer,
+ /* isHashedValue= */ false),
+ new AtomicFormula.StringAtomicFormula(
+ AtomicFormula.INSTALLER_CERTIFICATE,
+ cert,
+ /* isHashedValue= */ false)));
+ }
}
diff --git a/services/core/java/com/android/server/integrity/engine/RuleEvaluator.java b/services/core/java/com/android/server/integrity/engine/RuleEvaluator.java
index ee51d4f..b1c20d2 100644
--- a/services/core/java/com/android/server/integrity/engine/RuleEvaluator.java
+++ b/services/core/java/com/android/server/integrity/engine/RuleEvaluator.java
@@ -21,9 +21,6 @@
import android.annotation.NonNull;
import android.content.integrity.AppInstallMetadata;
-import android.content.integrity.AtomicFormula;
-import android.content.integrity.CompoundFormula;
-import android.content.integrity.Formula;
import android.content.integrity.Rule;
import android.util.Slog;
@@ -56,8 +53,7 @@
List<Rule> rules, AppInstallMetadata appInstallMetadata) {
List<Rule> matchedRules = new ArrayList<>();
for (Rule rule : rules) {
- if (isConjunctionOfFormulas(rule.getFormula())
- && rule.getFormula().isSatisfied(appInstallMetadata)) {
+ if (rule.getFormula().isSatisfied(appInstallMetadata)) {
matchedRules.add(rule);
}
}
@@ -81,25 +77,4 @@
}
return denied ? IntegrityCheckResult.deny(denyRule) : IntegrityCheckResult.allow();
}
-
- private static boolean isConjunctionOfFormulas(Formula formula) {
- if (formula == null) {
- return false;
- }
- if (isAtomicFormula(formula)) {
- return true;
- }
- CompoundFormula compoundFormula = (CompoundFormula) formula;
- return compoundFormula.getConnector() == CompoundFormula.AND
- && compoundFormula.getFormulas().stream().allMatch(RuleEvaluator::isAtomicFormula);
- }
-
- private static boolean isAtomicFormula(Formula formula) {
- if (formula instanceof AtomicFormula) {
- return true;
- }
- CompoundFormula compoundFormula = (CompoundFormula) formula;
- return compoundFormula.getConnector() == CompoundFormula.NOT
- && compoundFormula.getFormulas().get(0) instanceof AtomicFormula;
- }
}
diff --git a/services/core/java/com/android/server/media/MediaRoute2Provider.java b/services/core/java/com/android/server/media/MediaRoute2Provider.java
index 510dcd5..a30dd98 100644
--- a/services/core/java/com/android/server/media/MediaRoute2Provider.java
+++ b/services/core/java/com/android/server/media/MediaRoute2Provider.java
@@ -43,7 +43,7 @@
}
public abstract void requestCreateSession(String packageName, String routeId,
- String controlCategory, int requestId);
+ String controlCategory, long requestId);
public abstract void releaseSession(int sessionId);
public abstract void selectRoute(int sessionId, MediaRoute2Info route);
@@ -86,6 +86,6 @@
public interface Callback {
void onProviderStateChanged(@Nullable MediaRoute2Provider provider);
void onSessionCreated(@NonNull MediaRoute2Provider provider,
- @Nullable RouteSessionInfo sessionInfo, int requestId);
+ @Nullable RouteSessionInfo sessionInfo, long requestId);
}
}
diff --git a/services/core/java/com/android/server/media/MediaRoute2ProviderProxy.java b/services/core/java/com/android/server/media/MediaRoute2ProviderProxy.java
index b33b40b..0fc0606 100644
--- a/services/core/java/com/android/server/media/MediaRoute2ProviderProxy.java
+++ b/services/core/java/com/android/server/media/MediaRoute2ProviderProxy.java
@@ -76,7 +76,7 @@
@Override
public void requestCreateSession(String packageName, String routeId, String controlCategory,
- int requestId) {
+ long requestId) {
if (mConnectionReady) {
mActiveConnection.requestCreateSession(packageName, routeId, controlCategory,
requestId);
@@ -279,7 +279,7 @@
}
private void onSessionCreated(Connection connection, @Nullable RouteSessionInfo sessionInfo,
- int requestId) {
+ long requestId) {
if (mActiveConnection != connection) {
return;
}
@@ -327,7 +327,7 @@
}
public void requestCreateSession(String packageName, String routeId, String controlCategory,
- int requestId) {
+ long requestId) {
try {
mProvider.requestCreateSession(packageName, routeId,
controlCategory, requestId);
@@ -401,7 +401,7 @@
mHandler.post(() -> onProviderInfoUpdated(Connection.this, info));
}
- void postSessionCreated(@Nullable RouteSessionInfo sessionInfo, int requestId) {
+ void postSessionCreated(@Nullable RouteSessionInfo sessionInfo, long requestId) {
mHandler.post(() -> onSessionCreated(Connection.this, sessionInfo,
requestId));
}
@@ -427,7 +427,7 @@
}
@Override
- public void notifySessionCreated(@Nullable RouteSessionInfo sessionInfo, int requestId) {
+ public void notifySessionCreated(@Nullable RouteSessionInfo sessionInfo, long requestId) {
Connection connection = mConnectionRef.get();
if (connection != null) {
connection.postSessionCreated(sessionInfo, requestId);
diff --git a/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java b/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java
index a1ef850..fd41b6f 100644
--- a/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java
+++ b/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java
@@ -55,6 +55,7 @@
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicInteger;
/**
* TODO: Merge this to MediaRouterService once it's finished.
@@ -66,6 +67,7 @@
private final Context mContext;
private final Object mLock = new Object();
+ final AtomicInteger mNextClientId = new AtomicInteger(1);
@GuardedBy("mLock")
private final SparseArray<UserRecord> mUserRecords = new SparseArray<>();
@@ -76,6 +78,7 @@
@GuardedBy("mLock")
private int mCurrentUserId = -1;
+
MediaRouter2ServiceImpl(Context context) {
mContext = context;
}
@@ -173,6 +176,7 @@
}
final long token = Binder.clearCallingIdentity();
+
try {
synchronized (mLock) {
requestCreateSessionLocked(client, route, controlCategory, requestId);
@@ -358,10 +362,15 @@
}
private void requestCreateSessionLocked(@NonNull IMediaRouter2Client client,
- @NonNull MediaRoute2Info route, @NonNull String controlCategory, int requestId) {
+ @NonNull MediaRoute2Info route, @NonNull String controlCategory, long requestId) {
final IBinder binder = client.asBinder();
final Client2Record clientRecord = mAllClientRecords.get(binder);
+ // client id is not assigned yet
+ if (toClientId(requestId) == 0) {
+ requestId = toUniqueRequestId(clientRecord.mClientId, toClientRequestId(requestId));
+ }
+
if (clientRecord != null) {
clientRecord.mUserRecord.mHandler.sendMessage(
obtainMessage(UserHandler::requestCreateSessionOnHandler,
@@ -481,10 +490,11 @@
if (clientRecord == null) {
Slog.w(TAG, "Ignoring session creation for unknown client.");
}
+ long uniqueRequestId = toUniqueRequestId(managerRecord.mClientId, requestId);
if (clientRecord != null && managerRecord.mTrusted) {
//TODO: select category properly
requestCreateSessionLocked(clientRecord.mClient, route,
- route.getSupportedCategories().get(0), requestId);
+ route.getSupportedCategories().get(0), uniqueRequestId);
}
}
}
@@ -539,6 +549,18 @@
}
}
+ static long toUniqueRequestId(int clientId, int requestId) {
+ return ((long) clientId << 32) | requestId;
+ }
+
+ static int toClientId(long uniqueRequestId) {
+ return (int) (uniqueRequestId >> 32);
+ }
+
+ static int toClientRequestId(long uniqueRequestId) {
+ return (int) uniqueRequestId;
+ }
+
final class UserRecord {
public final int mUserId;
//TODO: make records private for thread-safety
@@ -570,6 +592,7 @@
public final int mUid;
public final int mPid;
public final boolean mTrusted;
+ public final int mClientId;
public List<String> mControlCategories;
public boolean mIsManagerSelecting;
@@ -586,6 +609,7 @@
mUid = uid;
mPid = pid;
mTrusted = trusted;
+ mClientId = mNextClientId.getAndIncrement();
}
public void dispose() {
@@ -605,6 +629,7 @@
public final int mPid;
public final String mPackageName;
public final boolean mTrusted;
+ public final int mClientId;
ManagerRecord(UserRecord userRecord, IMediaRouter2Manager manager,
int uid, int pid, String packageName, boolean trusted) {
@@ -614,6 +639,7 @@
mPid = pid;
mPackageName = packageName;
mTrusted = trusted;
+ mClientId = mNextClientId.getAndIncrement();
}
public void dispose() {
@@ -700,7 +726,7 @@
@Override
public void onSessionCreated(@NonNull MediaRoute2Provider provider,
- @Nullable RouteSessionInfo sessionInfo, int requestId) {
+ @Nullable RouteSessionInfo sessionInfo, long requestId) {
sendMessage(PooledLambda.obtainMessage(UserHandler::handleCreateSessionResultOnHandler,
this, provider, sessionInfo, requestId));
}
@@ -788,20 +814,20 @@
}
private void requestCreateSessionOnHandler(Client2Record clientRecord,
- MediaRoute2Info route, String controlCategory, int requestId) {
+ MediaRoute2Info route, String controlCategory, long requestId) {
final MediaRoute2Provider provider = findProvider(route.getProviderId());
if (provider == null) {
Slog.w(TAG, "Ignoring session creation request since no provider found for"
+ " given route=" + route);
- notifySessionCreationFailed(clientRecord, requestId);
+ notifySessionCreationFailed(clientRecord, (int) requestId);
return;
}
if (!route.getSupportedCategories().contains(controlCategory)) {
Slog.w(TAG, "Ignoring session creation request since the given route=" + route
+ " doesn't support the given category=" + controlCategory);
- notifySessionCreationFailed(clientRecord, requestId);
+ notifySessionCreationFailed(clientRecord, (int) requestId);
return;
}
@@ -816,7 +842,7 @@
private void handleCreateSessionResultOnHandler(
@NonNull MediaRoute2Provider provider, @Nullable RouteSessionInfo sessionInfo,
- int requestId) {
+ long requestId) {
SessionCreationRequest matchingRequest = null;
for (SessionCreationRequest request : mSessionCreationRequests) {
@@ -834,11 +860,17 @@
return;
}
+ //TODO: remove this when we are sure that request id is properly implemented.
+ if (matchingRequest.mClientRecord.mClientId != toClientId(requestId)) {
+ Slog.w(TAG, "Client id is changed. This shouldn't happen.");
+ return;
+ }
+
mSessionCreationRequests.remove(matchingRequest);
if (sessionInfo == null) {
// Failed
- notifySessionCreationFailed(matchingRequest.mClientRecord, requestId);
+ notifySessionCreationFailed(matchingRequest.mClientRecord, (int) requestId);
return;
}
@@ -855,13 +887,13 @@
+ " originalRouteId=" + originalRouteId
+ ", originalCategory=" + originalCategory + ", requestId=" + requestId
+ ", sessionInfo=" + sessionInfoWithProviderId);
- notifySessionCreationFailed(matchingRequest.mClientRecord, requestId);
+ notifySessionCreationFailed(matchingRequest.mClientRecord, (int) requestId);
return;
}
// Succeeded
notifySessionCreated(matchingRequest.mClientRecord,
- sessionInfoWithProviderId, requestId);
+ sessionInfoWithProviderId, (int) requestId);
// TODO: Tell managers for the session creation
}
@@ -1070,11 +1102,11 @@
public final Client2Record mClientRecord;
public final MediaRoute2Info mRoute;
public final String mControlCategory;
- public final int mRequestId;
+ public final long mRequestId;
SessionCreationRequest(@NonNull Client2Record clientRecord,
@NonNull MediaRoute2Info route,
- @NonNull String controlCategory, int requestId) {
+ @NonNull String controlCategory, long requestId) {
mClientRecord = clientRecord;
mRoute = route;
mControlCategory = controlCategory;
diff --git a/services/core/java/com/android/server/media/SystemMediaRoute2Provider.java b/services/core/java/com/android/server/media/SystemMediaRoute2Provider.java
index 59d7ca9..8451662 100644
--- a/services/core/java/com/android/server/media/SystemMediaRoute2Provider.java
+++ b/services/core/java/com/android/server/media/SystemMediaRoute2Provider.java
@@ -90,7 +90,7 @@
@Override
public void requestCreateSession(String packageName, String routeId, String controlCategory,
- int requestId) {
+ long requestId) {
// Do nothing
}
diff --git a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
index 2ebca88..99562eb 100644
--- a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
+++ b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
@@ -223,6 +223,7 @@
import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
import com.android.internal.notification.SystemNotificationChannels;
import com.android.internal.util.ArrayUtils;
+import com.android.internal.util.CollectionUtils;
import com.android.internal.util.ConcurrentUtils;
import com.android.internal.util.DumpUtils;
import com.android.internal.util.FastXmlSerializer;
@@ -1803,7 +1804,7 @@
/**
* Examine all currently active subscriptions from
- * {@link SubscriptionManager#getActiveSubscriptionIdList()} and update
+ * {@link SubscriptionManager#getActiveSubscriptionInfoList()} and update
* internal data structures.
* <p>
* Callers <em>must not</em> hold any locks when this method called.
@@ -1814,21 +1815,22 @@
final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
+ final List<SubscriptionInfo> subList = CollectionUtils.emptyIfNull(
+ sm.getActiveSubscriptionInfoList());
- final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
final List<String[]> mergedSubscriberIdsList = new ArrayList();
-
- final SparseArray<String> subIdToSubscriberId = new SparseArray<>(subIds.length);
- for (int subId : subIds) {
- final String subscriberId = tm.getSubscriberId(subId);
+ final SparseArray<String> subIdToSubscriberId = new SparseArray<>(subList.size());
+ for (SubscriptionInfo sub : subList) {
+ final TelephonyManager tmSub = tm.createForSubscriptionId(sub.getSubscriptionId());
+ final String subscriberId = tmSub.getSubscriberId();
if (!TextUtils.isEmpty(subscriberId)) {
- subIdToSubscriberId.put(subId, subscriberId);
+ subIdToSubscriberId.put(tmSub.getSubscriptionId(), subscriberId);
} else {
- Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
+ Slog.wtf(TAG, "Missing subscriberId for subId " + tmSub.getSubscriptionId());
}
- String[] mergedSubscriberId = ArrayUtils.defeatNullable(
- tm.createForSubscriptionId(subId).getMergedImsisFromGroup());
+ final String[] mergedSubscriberId = ArrayUtils.defeatNullable(
+ tmSub.getMergedImsisFromGroup());
mergedSubscriberIdsList.add(mergedSubscriberId);
}
diff --git a/services/tests/servicestests/src/com/android/server/backup/BackupManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/backup/BackupManagerServiceTest.java
index 68b413f..2326dfd 100644
--- a/services/tests/servicestests/src/com/android/server/backup/BackupManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/backup/BackupManagerServiceTest.java
@@ -34,9 +34,6 @@
import android.Manifest;
import android.annotation.UserIdInt;
import android.app.backup.BackupManager;
-import android.app.backup.IBackupManagerMonitor;
-import android.app.backup.IBackupObserver;
-import android.app.backup.IFullBackupRestoreObserver;
import android.app.backup.ISelectBackupTransportCallback;
import android.app.job.JobScheduler;
import android.content.ComponentName;
@@ -44,8 +41,6 @@
import android.content.pm.PackageManager;
import android.content.pm.UserInfo;
import android.os.ConditionVariable;
-import android.os.IBinder;
-import android.os.ParcelFileDescriptor;
import android.os.Process;
import android.os.RemoteException;
import android.os.UserHandle;
@@ -61,6 +56,7 @@
import org.junit.After;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
@@ -77,23 +73,8 @@
@Presubmit
@RunWith(AndroidJUnit4.class)
public class BackupManagerServiceTest {
- private static final String PACKAGE_NAME = "some.package.name";
- private static final String TRANSPORT_NAME = "some.transport.name";
- private static final String CURRENT_PASSWORD = "current_password";
- private static final String NEW_PASSWORD = "new_password";
- private static final String ENCRYPTION_PASSWORD = "encryption_password";
- private static final CharSequence DATA_MANAGEMENT_LABEL = "data_management_label";
- private static final String DESTINATION_STRING = "destination_string";
- private static final String[] PACKAGE_NAMES =
- new String[]{"some.package.name._1", "some.package.name._2"};
- private static final String[] TRANSPORTS =
- new String[]{"some.transport.name._1", "some.transport.name._2"};
private static final ComponentName TRANSPORT_COMPONENT_NAME = new ComponentName("package",
"class");
- private static final ComponentName[] TRANSPORT_COMPONENTS = new ComponentName[]{
- new ComponentName("package1", "class1"),
- new ComponentName("package2", "class2")
- };
private static final int NON_USER_SYSTEM = UserHandle.USER_SYSTEM + 1;
private static final int UNSTARTED_NON_USER_SYSTEM = UserHandle.USER_SYSTEM + 2;
@@ -104,16 +85,6 @@
@Mock
private Context mContextMock;
@Mock
- private IBinder mAgentMock;
- @Mock
- private ParcelFileDescriptor mParcelFileDescriptorMock;
- @Mock
- private IFullBackupRestoreObserver mFullBackupRestoreObserverMock;
- @Mock
- private IBackupObserver mBackupObserverMock;
- @Mock
- private IBackupManagerMonitor mBackupManagerMonitorMock;
- @Mock
private PrintWriter mPrintWriterMock;
@Mock
private UserManager mUserManagerMock;
@@ -543,6 +514,8 @@
verifyNoMoreInteractions(mUserBackupManagerService);
}
+ @Test
+ @Ignore("b/147012496")
public void testGetUserForAncestralSerialNumber() {
BackupManagerServiceTestable.sBackupDisabled = false;
BackupManagerService backupManagerService =
@@ -554,6 +527,7 @@
assertThat(user).isEqualTo(UserHandle.of(1));
}
+ @Test
public void testGetUserForAncestralSerialNumber_whenDisabled() {
BackupManagerServiceTestable.sBackupDisabled = true;
BackupManagerService backupManagerService =
diff --git a/services/tests/servicestests/src/com/android/server/backup/DataChangedJournalTest.java b/services/tests/servicestests/src/com/android/server/backup/DataChangedJournalTest.java
index 4e7fe44..0e918db 100644
--- a/services/tests/servicestests/src/com/android/server/backup/DataChangedJournalTest.java
+++ b/services/tests/servicestests/src/com/android/server/backup/DataChangedJournalTest.java
@@ -136,6 +136,7 @@
assertThat(mJournal.toString()).isEqualTo(mFile.toString());
}
+ @Test
public void listJournals_invalidJournalFile_returnsEmptyList() throws Exception {
when(invalidFile.listFiles()).thenReturn(null);
diff --git a/services/tests/servicestests/src/com/android/server/backup/utils/FileUtilsTest.java b/services/tests/servicestests/src/com/android/server/backup/utils/FileUtilsTest.java
index eaa9c45..d54aa3b 100644
--- a/services/tests/servicestests/src/com/android/server/backup/utils/FileUtilsTest.java
+++ b/services/tests/servicestests/src/com/android/server/backup/utils/FileUtilsTest.java
@@ -27,7 +27,6 @@
import org.junit.AfterClass;
import org.junit.Before;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -41,11 +40,6 @@
private static File sTemporaryDir;
private File mTemporaryFile;
- @BeforeClass
- public static void setUpClass() {
- sTemporaryDir = Files.createTempDir();
- }
-
@AfterClass
public static void tearDownClass() {
if (sTemporaryDir != null) {
@@ -55,17 +49,21 @@
@Before
public void setUp() throws Exception {
+ if (sTemporaryDir != null) {
+ sTemporaryDir.delete();
+ }
+ sTemporaryDir = Files.createTempDir();
mTemporaryFile = new File(sTemporaryDir, "fileutilstest.txt");
}
/** Test that if file does not exist, {@link FileUtils#createNewFile()} creates the file. */
@Test
public void testEnsureFileExists_fileDoesNotAlreadyExist_getsCreated() {
- assertThat(!mTemporaryFile.exists());
+ assertThat(mTemporaryFile.exists()).isFalse();
FileUtils.createNewFile(mTemporaryFile);
- assertThat(mTemporaryFile.exists());
+ assertThat(mTemporaryFile.exists()).isTrue();
}
/** Test that if file does exist, {@link FileUtils#createNewFile()} does not error out. */
@@ -75,6 +73,6 @@
FileUtils.createNewFile(mTemporaryFile);
- assertThat(mTemporaryFile.exists());
+ assertThat(mTemporaryFile.exists()).isTrue();
}
}
diff --git a/services/tests/servicestests/src/com/android/server/display/AutomaticBrightnessControllerTest.java b/services/tests/servicestests/src/com/android/server/display/AutomaticBrightnessControllerTest.java
index f6c4d3a..ca00116 100644
--- a/services/tests/servicestests/src/com/android/server/display/AutomaticBrightnessControllerTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/AutomaticBrightnessControllerTest.java
@@ -53,7 +53,6 @@
private static final int INITIAL_LIGHT_SENSOR_RATE = 20;
private static final int BRIGHTENING_LIGHT_DEBOUNCE_CONFIG = 0;
private static final int DARKENING_LIGHT_DEBOUNCE_CONFIG = 0;
- private static final int SHORT_TERM_MODEL_TIMEOUT = 0;
private static final float DOZE_SCALE_FACTOR = 0.0f;
private static final boolean RESET_AMBIENT_LUX_AFTER_WARMUP_CONFIG = false;
@@ -86,7 +85,7 @@
BRIGHTNESS_MAX, DOZE_SCALE_FACTOR, LIGHT_SENSOR_RATE, INITIAL_LIGHT_SENSOR_RATE,
BRIGHTENING_LIGHT_DEBOUNCE_CONFIG, DARKENING_LIGHT_DEBOUNCE_CONFIG,
RESET_AMBIENT_LUX_AFTER_WARMUP_CONFIG, mAmbientBrightnessThresholds,
- mScreenBrightnessThresholds, SHORT_TERM_MODEL_TIMEOUT, mPackageManager);
+ mScreenBrightnessThresholds, mPackageManager);
controller.setLoggingEnabled(true);
// Configure the brightness controller and grab an instance of the sensor listener,
@@ -189,4 +188,27 @@
listener.onSensorChanged(TestUtils.createSensorEvent(lightSensor, (int) lux2));
assertEquals(255, controller.getAutomaticScreenBrightness());
}
+
+ @Test
+ public void testUserAddUserDataPoint() throws Exception {
+ Sensor lightSensor = TestUtils.createSensor(Sensor.TYPE_LIGHT, "Light Sensor");
+ AutomaticBrightnessController controller = setupController(lightSensor);
+
+ ArgumentCaptor<SensorEventListener> listenerCaptor =
+ ArgumentCaptor.forClass(SensorEventListener.class);
+ verify(mSensorManager).registerListener(listenerCaptor.capture(), eq(lightSensor),
+ eq(INITIAL_LIGHT_SENSOR_RATE * 1000), any(Handler.class));
+ SensorEventListener listener = listenerCaptor.getValue();
+
+ // Sensor reads 1000 lux,
+ listener.onSensorChanged(TestUtils.createSensorEvent(lightSensor, 1000));
+
+ // User sets brightness to 100
+ controller.configure(true /* enable */, null /* configuration */,
+ 100 /* brightness */, true /* userChangedBrightness */, 0 /* adjustment */,
+ false /* userChanged */, DisplayPowerRequest.POLICY_BRIGHT);
+
+ // There should be a user data point added to the mapper.
+ verify(mBrightnessMappingStrategy).addUserDataPoint(1000f, 100);
+ }
}
diff --git a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystemTest.java b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystemTest.java
index 0a1899b..50ed975 100644
--- a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystemTest.java
+++ b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystemTest.java
@@ -534,6 +534,7 @@
assertThat(mNativeWrapper.getOnlyResultMessage()).isEqualTo(expectedMessage);
}
+ @Test
public void handleSystemAudioModeRequest_fromNonTV_tVNotSupport() {
HdmiCecMessage message =
HdmiCecMessageBuilder.buildSystemAudioModeRequest(
diff --git a/services/tests/servicestests/src/com/android/server/integrity/engine/RuleEvaluationEngineTest.java b/services/tests/servicestests/src/com/android/server/integrity/engine/RuleEvaluationEngineTest.java
new file mode 100644
index 0000000..d386487
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/integrity/engine/RuleEvaluationEngineTest.java
@@ -0,0 +1,197 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.integrity.engine;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.when;
+
+import android.content.integrity.AppInstallMetadata;
+import android.content.integrity.Rule;
+
+import com.android.server.integrity.IntegrityFileManager;
+import com.android.server.integrity.model.IntegrityCheckResult;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@RunWith(JUnit4.class)
+public class RuleEvaluationEngineTest {
+
+ private static final String INSTALLER_1 = "installer1";
+ private static final String INSTALLER_1_CERT = "installer1_cert";
+ private static final String INSTALLER_2 = "installer2";
+ private static final String INSTALLER_2_CERT = "installer2_cert";
+
+ private static final String RANDOM_INSTALLER = "random";
+ private static final String RANDOM_INSTALLER_CERT = "random_cert";
+
+ @Mock private IntegrityFileManager mIntegrityFileManager;
+
+ private RuleEvaluationEngine mEngine;
+
+ @Before
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+
+ mEngine = new RuleEvaluationEngine(mIntegrityFileManager);
+
+ when(mIntegrityFileManager.readRules(any())).thenReturn(new ArrayList<>());
+ }
+
+ @Test
+ public void testAllowedInstallers_empty() {
+ Map<String, String> allowedInstallers = Collections.emptyMap();
+
+ assertEquals(
+ IntegrityCheckResult.Effect.ALLOW,
+ mEngine.evaluate(
+ getAppInstallMetadataBuilder()
+ .setInstallerName(INSTALLER_1)
+ .setInstallerCertificate(INSTALLER_1_CERT)
+ .build(),
+ allowedInstallers)
+ .getEffect());
+ assertEquals(
+ IntegrityCheckResult.Effect.ALLOW,
+ mEngine.evaluate(
+ getAppInstallMetadataBuilder()
+ .setInstallerName(INSTALLER_2)
+ .setInstallerCertificate(INSTALLER_2_CERT)
+ .build(),
+ allowedInstallers)
+ .getEffect());
+ assertEquals(
+ IntegrityCheckResult.Effect.ALLOW,
+ mEngine.evaluate(
+ getAppInstallMetadataBuilder()
+ .setInstallerName(RANDOM_INSTALLER)
+ .setInstallerCertificate(RANDOM_INSTALLER_CERT)
+ .build(),
+ allowedInstallers)
+ .getEffect());
+ }
+
+ @Test
+ public void testAllowedInstallers_oneElement() {
+ Map<String, String> allowedInstallers =
+ Collections.singletonMap(INSTALLER_1, INSTALLER_1_CERT);
+
+ assertEquals(
+ IntegrityCheckResult.Effect.ALLOW,
+ mEngine.evaluate(
+ getAppInstallMetadataBuilder()
+ .setInstallerName(INSTALLER_1)
+ .setInstallerCertificate(INSTALLER_1_CERT)
+ .build(),
+ allowedInstallers)
+ .getEffect());
+ assertEquals(
+ IntegrityCheckResult.Effect.DENY,
+ mEngine.evaluate(
+ getAppInstallMetadataBuilder()
+ .setInstallerName(RANDOM_INSTALLER)
+ .setInstallerCertificate(INSTALLER_1_CERT)
+ .build(),
+ allowedInstallers)
+ .getEffect());
+ assertEquals(
+ IntegrityCheckResult.Effect.DENY,
+ mEngine.evaluate(
+ getAppInstallMetadataBuilder()
+ .setInstallerName(INSTALLER_1)
+ .setInstallerCertificate(RANDOM_INSTALLER_CERT)
+ .build(),
+ allowedInstallers)
+ .getEffect());
+ assertEquals(
+ IntegrityCheckResult.Effect.DENY,
+ mEngine.evaluate(
+ getAppInstallMetadataBuilder()
+ .setInstallerName(RANDOM_INSTALLER)
+ .setInstallerCertificate(RANDOM_INSTALLER_CERT)
+ .build(),
+ allowedInstallers)
+ .getEffect());
+ }
+
+ @Test
+ public void testAllowedInstallers_multipleElement() {
+ List<Rule> rules = new ArrayList<>();
+ Map<String, String> allowedInstallers = new HashMap<>(2);
+ allowedInstallers.put(INSTALLER_1, INSTALLER_1_CERT);
+ allowedInstallers.put(INSTALLER_2, INSTALLER_2_CERT);
+
+ assertEquals(
+ IntegrityCheckResult.Effect.ALLOW,
+ mEngine.evaluate(
+ getAppInstallMetadataBuilder()
+ .setInstallerName(INSTALLER_1)
+ .setInstallerCertificate(INSTALLER_1_CERT)
+ .build(),
+ allowedInstallers)
+ .getEffect());
+ assertEquals(
+ IntegrityCheckResult.Effect.ALLOW,
+ mEngine.evaluate(
+ getAppInstallMetadataBuilder()
+ .setInstallerName(INSTALLER_2)
+ .setInstallerCertificate(INSTALLER_2_CERT)
+ .build(),
+ allowedInstallers)
+ .getEffect());
+ assertEquals(
+ IntegrityCheckResult.Effect.DENY,
+ mEngine.evaluate(
+ getAppInstallMetadataBuilder()
+ .setInstallerName(INSTALLER_1)
+ .setInstallerCertificate(INSTALLER_2_CERT)
+ .build(),
+ allowedInstallers)
+ .getEffect());
+ assertEquals(
+ IntegrityCheckResult.Effect.DENY,
+ mEngine.evaluate(
+ getAppInstallMetadataBuilder()
+ .setInstallerName(INSTALLER_2)
+ .setInstallerCertificate(INSTALLER_1_CERT)
+ .build(),
+ allowedInstallers)
+ .getEffect());
+ }
+
+ /** Returns a builder with all fields filled with some dummy data. */
+ private AppInstallMetadata.Builder getAppInstallMetadataBuilder() {
+ return new AppInstallMetadata.Builder()
+ .setPackageName("abc")
+ .setAppCertificate("abc")
+ .setInstallerCertificate("abc")
+ .setInstallerName("abc")
+ .setVersionCode(-1)
+ .setIsPreInstalled(true);
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/net/NetworkPolicyManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/net/NetworkPolicyManagerServiceTest.java
index 545836e..7529bc5 100644
--- a/services/tests/servicestests/src/com/android/server/net/NetworkPolicyManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/net/NetworkPolicyManagerServiceTest.java
@@ -124,6 +124,7 @@
import android.os.UserHandle;
import android.platform.test.annotations.Presubmit;
import android.telephony.CarrierConfigManager;
+import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.SubscriptionPlan;
import android.telephony.TelephonyManager;
@@ -261,7 +262,7 @@
private static final int USER_ID = 0;
private static final int FAKE_SUB_ID = 3737373;
- private static final String FAKE_SUBSCRIBER_ID = "FAKE_SUB_ID";
+ private static final String FAKE_SUBSCRIBER_ID = "FAKE_SUBSCRIBER_ID";
private static final int DEFAULT_CYCLE_DAY = 1;
private static final int INVALID_CARRIER_CONFIG_VALUE = -9999;
private long mDefaultWarningBytes; // filled in with the actual default before tests are run
@@ -1461,10 +1462,9 @@
private PersistableBundle setupUpdateMobilePolicyCycleTests() throws RemoteException {
when(mConnManager.getAllNetworkState()).thenReturn(new NetworkState[0]);
- when(mSubscriptionManager.getActiveSubscriptionIdList()).thenReturn(new int[]{FAKE_SUB_ID});
- when(mTelephonyManager.getSubscriberId(FAKE_SUB_ID)).thenReturn(FAKE_SUBSCRIBER_ID);
- when(mTelephonyManager.createForSubscriptionId(FAKE_SUB_ID))
- .thenReturn(mock(TelephonyManager.class));
+
+ setupTelephonySubscriptionManagers(FAKE_SUB_ID, FAKE_SUBSCRIBER_ID);
+
PersistableBundle bundle = CarrierConfigManager.getDefaultConfig();
when(mCarrierConfigManager.getConfigForSubId(FAKE_SUB_ID)).thenReturn(bundle);
setNetworkPolicies(buildDefaultFakeMobilePolicy());
@@ -1474,10 +1474,9 @@
@Test
public void testUpdateMobilePolicyCycleWithNullConfig() throws RemoteException {
when(mConnManager.getAllNetworkState()).thenReturn(new NetworkState[0]);
- when(mSubscriptionManager.getActiveSubscriptionIdList()).thenReturn(new int[]{FAKE_SUB_ID});
- when(mTelephonyManager.getSubscriberId(FAKE_SUB_ID)).thenReturn(FAKE_SUBSCRIBER_ID);
- when(mTelephonyManager.createForSubscriptionId(FAKE_SUB_ID))
- .thenReturn(mock(TelephonyManager.class));
+
+ setupTelephonySubscriptionManagers(FAKE_SUB_ID, FAKE_SUBSCRIBER_ID);
+
when(mCarrierConfigManager.getConfigForSubId(FAKE_SUB_ID)).thenReturn(null);
setNetworkPolicies(buildDefaultFakeMobilePolicy());
// smoke test to make sure no errors are raised
@@ -1930,11 +1929,7 @@
}
private void expectMobileDefaults() throws Exception {
- when(mSubscriptionManager.getActiveSubscriptionIdList()).thenReturn(
- new int[] { TEST_SUB_ID });
- when(mTelephonyManager.getSubscriberId(TEST_SUB_ID)).thenReturn(TEST_IMSI);
- when(mTelephonyManager.createForSubscriptionId(TEST_SUB_ID))
- .thenReturn(mock(TelephonyManager.class));
+ setupTelephonySubscriptionManagers(TEST_SUB_ID, TEST_IMSI);
doNothing().when(mTelephonyManager).setPolicyDataEnabled(anyBoolean(), anyInt());
expectNetworkState(false /* roaming */);
}
@@ -2094,6 +2089,38 @@
}
/**
+ * Creates a mock {@link TelephonyManager} and {@link SubscriptionManager}.
+ */
+ private void setupTelephonySubscriptionManagers(int subscriptionId, String subscriberId) {
+ when(mSubscriptionManager.getActiveSubscriptionInfoList()).thenReturn(
+ createSubscriptionInfoList(subscriptionId));
+
+ TelephonyManager subTelephonyManager;
+ subTelephonyManager = mock(TelephonyManager.class);
+ when(subTelephonyManager.getSubscriptionId()).thenReturn(subscriptionId);
+ when(subTelephonyManager.getSubscriberId()).thenReturn(subscriberId);
+ when(mTelephonyManager.createForSubscriptionId(subscriptionId))
+ .thenReturn(subTelephonyManager);
+ }
+
+ /**
+ * Creates mock {@link SubscriptionInfo} from subscription id.
+ */
+ private List<SubscriptionInfo> createSubscriptionInfoList(int subId) {
+ final List<SubscriptionInfo> sub = new ArrayList<>();
+ sub.add(createSubscriptionInfo(subId));
+ return sub;
+ }
+
+ /**
+ * Creates mock {@link SubscriptionInfo} from subscription id.
+ */
+ private SubscriptionInfo createSubscriptionInfo(int subId) {
+ return new SubscriptionInfo(subId, null, -1, null, null, -1, -1,
+ null, -1, null, null, null, null, false, null, null);
+ }
+
+ /**
* Custom Mockito answer used to verify async {@link INetworkPolicyListener} calls.
*
* <p>Typical usage:
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationHistoryManagerTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationHistoryManagerTest.java
index 92c0546..3b6a4bd 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationHistoryManagerTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationHistoryManagerTest.java
@@ -41,6 +41,7 @@
import com.android.server.UiServiceTestCase;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
@@ -124,6 +125,8 @@
verify(mDb, times(1)).init();
}
+ @Test
+ @Ignore("b/147012298")
public void testOnUserUnlocked_historyDisabled() {
Settings.Secure.putIntForUser(getContext().getContentResolver(),
Settings.Secure.NOTIFICATION_HISTORY_ENABLED, 0, USER_SYSTEM);
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
index 876e77a..95617b1 100755
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
@@ -4502,6 +4502,7 @@
assertEquals(0, mService.countLogSmartSuggestionsVisible);
}
+ @Test
public void testReportSeen_delegated() {
Notification.Builder nb =
new Notification.Builder(mContext, mTestNotificationChannel.getId())
@@ -5767,6 +5768,7 @@
verify(mUsageStats, times(5)).registerImageRemoved(PKG);
}
+ @Test
public void testNotificationBubbles_flagAutoExpandForeground_fails_notForeground()
throws Exception {
// Bubbles are allowed!
diff --git a/services/voiceinteraction/java/com/android/server/soundtrigger/SoundTriggerService.java b/services/voiceinteraction/java/com/android/server/soundtrigger/SoundTriggerService.java
index 96d2df1..68b16f3 100644
--- a/services/voiceinteraction/java/com/android/server/soundtrigger/SoundTriggerService.java
+++ b/services/voiceinteraction/java/com/android/server/soundtrigger/SoundTriggerService.java
@@ -74,13 +74,13 @@
import com.android.internal.annotations.GuardedBy;
import com.android.internal.app.ISoundTriggerService;
-import com.android.internal.util.Preconditions;
import com.android.server.SystemService;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Map;
+import java.util.Objects;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@@ -429,9 +429,9 @@
@Override
public int startRecognitionForService(ParcelUuid soundModelId, Bundle params,
ComponentName detectionService, SoundTrigger.RecognitionConfig config) {
- Preconditions.checkNotNull(soundModelId);
- Preconditions.checkNotNull(detectionService);
- Preconditions.checkNotNull(config);
+ Objects.requireNonNull(soundModelId);
+ Objects.requireNonNull(detectionService);
+ Objects.requireNonNull(config);
enforceCallingPermission(Manifest.permission.MANAGE_SOUND_TRIGGER);
diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
index 404346f..e9db31b 100644
--- a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
+++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
@@ -76,7 +76,6 @@
import com.android.internal.content.PackageMonitor;
import com.android.internal.os.BackgroundThread;
import com.android.internal.util.DumpUtils;
-import com.android.internal.util.Preconditions;
import com.android.server.FgThread;
import com.android.server.LocalServices;
import com.android.server.SystemService;
@@ -89,6 +88,7 @@
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.List;
+import java.util.Objects;
import java.util.concurrent.Executor;
/**
@@ -117,11 +117,11 @@
mResolver = context.getContentResolver();
mDbHelper = new DatabaseHelper(context);
mServiceStub = new VoiceInteractionManagerServiceStub();
- mAmInternal = Preconditions.checkNotNull(
+ mAmInternal = Objects.requireNonNull(
LocalServices.getService(ActivityManagerInternal.class));
- mAtmInternal = Preconditions.checkNotNull(
+ mAtmInternal = Objects.requireNonNull(
LocalServices.getService(ActivityTaskManagerInternal.class));
- mUserManagerInternal = Preconditions.checkNotNull(
+ mUserManagerInternal = Objects.requireNonNull(
LocalServices.getService(UserManagerInternal.class));
PermissionManagerServiceInternal permissionManagerInternal = LocalServices.getService(
@@ -149,7 +149,7 @@
@Override
public void onBootPhase(int phase) {
if (PHASE_SYSTEM_SERVICES_READY == phase) {
- mShortcutServiceInternal = Preconditions.checkNotNull(
+ mShortcutServiceInternal = Objects.requireNonNull(
LocalServices.getService(ShortcutServiceInternal.class));
mSoundTriggerInternal = LocalServices.getService(SoundTriggerInternal.class);
} else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
diff --git a/telephony/java/android/telephony/SubscriptionManager.java b/telephony/java/android/telephony/SubscriptionManager.java
index 15398ca..ef6ae50 100644
--- a/telephony/java/android/telephony/SubscriptionManager.java
+++ b/telephony/java/android/telephony/SubscriptionManager.java
@@ -2655,8 +2655,7 @@
/**
* Checks whether the app with the given context is authorized to manage the given subscription
- * according to its metadata. Only supported for embedded subscriptions (if
- * {@code SubscriptionInfo#isEmbedded} returns true).
+ * according to its metadata.
*
* @param info The subscription to check.
* @return whether the app is authorized to manage this subscription per its metadata.
@@ -2669,16 +2668,16 @@
* Checks whether the given app is authorized to manage the given subscription. An app can only
* be authorized if it is included in the {@link android.telephony.UiccAccessRule} of the
* {@link android.telephony.SubscriptionInfo} with the access status.
- * Only supported for embedded subscriptions (if {@link SubscriptionInfo#isEmbedded}
- * returns true).
*
* @param info The subscription to check.
* @param packageName Package name of the app to check.
* @return whether the app is authorized to manage this subscription per its access rules.
* @hide
*/
- public boolean canManageSubscription(SubscriptionInfo info, String packageName) {
- if (info == null || info.getAllAccessRules() == null) {
+ @SystemApi
+ public boolean canManageSubscription(@Nullable SubscriptionInfo info,
+ @Nullable String packageName) {
+ if (info == null || info.getAllAccessRules() == null || packageName == null) {
return false;
}
PackageManager packageManager = mContext.getPackageManager();
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index 0f95325..365ab22 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -6425,7 +6425,19 @@
* Return an appropriate subscription ID for any situation.
*
* If this object has been created with {@link #createForSubscriptionId}, then the provided
- * subId is returned. Otherwise, the default subId will be returned.
+ * subscription ID is returned. Otherwise, the default subscription ID will be returned.
+ *
+ */
+ public int getSubscriptionId() {
+ return getSubId();
+ }
+
+ /**
+ * Return an appropriate subscription ID for any situation.
+ *
+ * If this object has been created with {@link #createForSubscriptionId}, then the provided
+ * subscription ID is returned. Otherwise, the default subscription ID will be returned.
+ *
*/
private int getSubId() {
if (SubscriptionManager.isUsableSubIdValue(mSubId)) {
diff --git a/telephony/java/com/android/internal/telephony/SmsMessageBase.java b/telephony/java/com/android/internal/telephony/SmsMessageBase.java
index a3efb75..d6632f3 100644
--- a/telephony/java/com/android/internal/telephony/SmsMessageBase.java
+++ b/telephony/java/com/android/internal/telephony/SmsMessageBase.java
@@ -18,19 +18,26 @@
import android.annotation.UnsupportedAppUsage;
import android.os.Build;
-import android.provider.Telephony;
import android.telephony.SmsMessage;
+import android.text.TextUtils;
+import android.util.Patterns;
import com.android.internal.telephony.GsmAlphabet.TextEncodingDetails;
import java.text.BreakIterator;
import java.util.Arrays;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
/**
* Base class declaring the specific methods and members for SmsMessage.
* {@hide}
*/
public abstract class SmsMessageBase {
+ // Copied from Telephony.Mms.NAME_ADDR_EMAIL_PATTERN
+ public static final Pattern NAME_ADDR_EMAIL_PATTERN =
+ Pattern.compile("\\s*(\"[^\"]*\"|[^<>\"]+)\\s*<([^<>]+)>\\s*");
+
/** {@hide} The address of the SMSC. May be null */
@UnsupportedAppUsage
protected String mScAddress;
@@ -355,6 +362,31 @@
}
}
+ private static String extractAddrSpec(String messageHeader) {
+ Matcher match = NAME_ADDR_EMAIL_PATTERN.matcher(messageHeader);
+
+ if (match.matches()) {
+ return match.group(2);
+ }
+ return messageHeader;
+ }
+
+ /**
+ * Returns true if the message header string indicates that the message is from a email address.
+ *
+ * @param messageHeader message header
+ * @return {@code true} if it's a message from an email address, {@code false} otherwise.
+ */
+ public static boolean isEmailAddress(String messageHeader) {
+ if (TextUtils.isEmpty(messageHeader)) {
+ return false;
+ }
+
+ String s = extractAddrSpec(messageHeader);
+ Matcher match = Patterns.EMAIL_ADDRESS.matcher(s);
+ return match.matches();
+ }
+
/**
* Try to parse this message as an email gateway message
* There are two ways specified in TS 23.040 Section 3.8 :
@@ -375,11 +407,11 @@
* -or-
* 2. [x@y][ ]/[body]
*/
- String[] parts = mMessageBody.split("( /)|( )", 2);
- if (parts.length < 2) return;
- mEmailFrom = parts[0];
- mEmailBody = parts[1];
- mIsEmail = Telephony.Mms.isEmailAddress(mEmailFrom);
+ String[] parts = mMessageBody.split("( /)|( )", 2);
+ if (parts.length < 2) return;
+ mEmailFrom = parts[0];
+ mEmailBody = parts[1];
+ mIsEmail = isEmailAddress(mEmailFrom);
}
/**
diff --git a/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/StagedRollbackTest.java b/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/StagedRollbackTest.java
index 879ac64..bb3906d 100644
--- a/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/StagedRollbackTest.java
+++ b/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/StagedRollbackTest.java
@@ -185,6 +185,12 @@
*/
@Test
public void testNativeWatchdogTriggersRollback_Phase1() throws Exception {
+ // When multiple staged sessions are installed on a device which doesn't support checkpoint,
+ // only the 1st one will prevail. We have to check no other rollbacks available to ensure
+ // TestApp.A is always the 1st and the only one to commit so rollback can work as intended.
+ // If there are leftover rollbacks from previous tests, this assertion will fail.
+ assertThat(RollbackUtils.getRollbackManager().getAvailableRollbacks()).isEmpty();
+
Uninstall.packages(TestApp.A);
Install.single(TestApp.A1).commit();
assertThat(InstallUtils.getInstalledVersion(TestApp.A)).isEqualTo(1);
@@ -373,6 +379,11 @@
assertThat(RollbackUtils.getAvailableRollback(getModuleMetadataPackageName())).isNotNull();
}
+ @Test
+ public void testRollbackWhitelistedApp_cleanUp() throws Exception {
+ RollbackUtils.getRollbackManager().expireRollbackForPackage(getModuleMetadataPackageName());
+ }
+
private static void runShellCommand(String cmd) {
ParcelFileDescriptor pfd = InstrumentationRegistry.getInstrumentation().getUiAutomation()
.executeShellCommand(cmd);
diff --git a/tests/RollbackTest/StagedRollbackTest/src/com/android/tests/rollback/host/StagedRollbackTest.java b/tests/RollbackTest/StagedRollbackTest/src/com/android/tests/rollback/host/StagedRollbackTest.java
index 07d829d..8ab4c4c 100644
--- a/tests/RollbackTest/StagedRollbackTest/src/com/android/tests/rollback/host/StagedRollbackTest.java
+++ b/tests/RollbackTest/StagedRollbackTest/src/com/android/tests/rollback/host/StagedRollbackTest.java
@@ -180,9 +180,16 @@
*/
@Test
public void testRollbackWhitelistedApp() throws Exception {
- runPhase("testRollbackWhitelistedApp_Phase1");
- getDevice().reboot();
- runPhase("testRollbackWhitelistedApp_Phase2");
+ try {
+ runPhase("testRollbackWhitelistedApp_Phase1");
+ getDevice().reboot();
+ runPhase("testRollbackWhitelistedApp_Phase2");
+ } finally {
+ // testNativeWatchdogTriggersRollback will fail if multiple staged sessions are
+ // committed on a device which doesn't support checkpoint. Let's clean up the rollback
+ // so there is only one rollback to commit when testing native crashes.
+ runPhase("testRollbackWhitelistedApp_cleanUp");
+ }
}
private void crashProcess(String processName, int numberOfCrashes) throws Exception {